@inweb/viewer-three 26.10.6 → 26.11.0

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 (143) hide show
  1. package/README.md +7 -4
  2. package/dist/{plugins → extensions}/components/AxesHelperComponent.js +23 -1
  3. package/dist/extensions/components/AxesHelperComponent.js.map +1 -0
  4. package/dist/extensions/components/AxesHelperComponent.min.js +24 -0
  5. package/dist/{plugins → extensions}/components/AxesHelperComponent.module.js +24 -2
  6. package/dist/extensions/components/AxesHelperComponent.module.js.map +1 -0
  7. package/dist/{plugins → extensions}/components/ExtentsHelperComponent.js +18 -0
  8. package/dist/extensions/components/ExtentsHelperComponent.js.map +1 -0
  9. package/dist/{plugins/components/AxesHelperComponent.min.js → extensions/components/ExtentsHelperComponent.min.js} +1 -1
  10. package/dist/{plugins → extensions}/components/ExtentsHelperComponent.module.js +19 -1
  11. package/dist/extensions/components/ExtentsHelperComponent.module.js.map +1 -0
  12. package/dist/extensions/components/GridHelperComponent.js.map +1 -0
  13. package/dist/extensions/components/GridHelperComponent.module.js.map +1 -0
  14. package/dist/extensions/components/LightHelperComponent.js.map +1 -0
  15. package/dist/extensions/components/LightHelperComponent.module.js.map +1 -0
  16. package/dist/extensions/components/RoomEnvironmentComponent.js.map +1 -0
  17. package/dist/extensions/components/RoomEnvironmentComponent.module.js.map +1 -0
  18. package/dist/extensions/components/StatsPanelComponent.js.map +1 -0
  19. package/dist/extensions/components/StatsPanelComponent.module.js.map +1 -0
  20. package/dist/{plugins → extensions}/loaders/GLTFCloudLoader.js +2 -3
  21. package/dist/extensions/loaders/GLTFCloudLoader.js.map +1 -0
  22. package/dist/{plugins → extensions}/loaders/GLTFCloudLoader.min.js +1 -1
  23. package/dist/{plugins → extensions}/loaders/GLTFCloudLoader.module.js +2 -3
  24. package/dist/extensions/loaders/GLTFCloudLoader.module.js.map +1 -0
  25. package/dist/extensions/loaders/GLTFFileLoader.js +2499 -0
  26. package/dist/extensions/loaders/GLTFFileLoader.js.map +1 -0
  27. package/dist/extensions/loaders/GLTFFileLoader.min.js +24 -0
  28. package/dist/extensions/loaders/GLTFFileLoader.module.js +74 -0
  29. package/dist/extensions/loaders/GLTFFileLoader.module.js.map +1 -0
  30. package/dist/{plugins → extensions}/loaders/IFCXLoader.js +5 -7
  31. package/dist/extensions/loaders/IFCXLoader.js.map +1 -0
  32. package/dist/{plugins → extensions}/loaders/IFCXLoader.min.js +1 -1
  33. package/dist/{plugins → extensions}/loaders/IFCXLoader.module.js +5 -7
  34. package/dist/extensions/loaders/IFCXLoader.module.js.map +1 -0
  35. package/dist/{plugins → extensions}/loaders/PotreeLoader.js +1 -2
  36. package/dist/extensions/loaders/PotreeLoader.js.map +1 -0
  37. package/dist/{plugins → extensions}/loaders/PotreeLoader.min.js +1 -1
  38. package/dist/{plugins → extensions}/loaders/PotreeLoader.module.js +1 -2
  39. package/dist/extensions/loaders/PotreeLoader.module.js.map +1 -0
  40. package/dist/viewer-three.js +1015 -2926
  41. package/dist/viewer-three.js.map +1 -1
  42. package/dist/viewer-three.min.js +3 -3
  43. package/dist/viewer-three.module.js +847 -356
  44. package/dist/viewer-three.module.js.map +1 -1
  45. package/{plugins → extensions}/components/AxesHelperComponent.ts +31 -2
  46. package/{plugins → extensions}/components/ExtentsHelperComponent.ts +25 -0
  47. package/{plugins → extensions}/loaders/GLTFCloudLoader.ts +2 -3
  48. package/{src/Viewer → extensions}/loaders/GLTFFileLoader.ts +21 -12
  49. package/{plugins → extensions}/loaders/IFCX/IFCXCloudLoader.ts +5 -5
  50. package/{plugins → extensions}/loaders/IFCX/IFCXFileLoader.ts +3 -4
  51. package/{plugins → extensions}/loaders/Potree/PotreeFileLoader.ts +3 -4
  52. package/lib/Viewer/Viewer.d.ts +27 -20
  53. package/lib/Viewer/commands/GetSelected2.d.ts +2 -0
  54. package/lib/Viewer/commands/SelectModel.d.ts +1 -1
  55. package/lib/Viewer/commands/SetSelected2.d.ts +2 -0
  56. package/lib/Viewer/components/SelectionComponent.d.ts +1 -3
  57. package/lib/Viewer/components/index.d.ts +6 -6
  58. package/lib/Viewer/draggers/MeasureLineDragger.d.ts +7 -1
  59. package/lib/Viewer/loaders/DynamicGltfLoader/DynamicModelImpl.d.ts +0 -1
  60. package/lib/Viewer/loaders/GLTFBinaryExtension.d.ts +5 -0
  61. package/lib/Viewer/loaders/GLTFCloudDynamicLoader.d.ts +2 -2
  62. package/lib/Viewer/loaders/{GLTFFileLoader.d.ts → GLTFFileDynamicLoader.d.ts} +7 -1
  63. package/lib/Viewer/loaders/GLTFLoadingManager.d.ts +4 -3
  64. package/lib/Viewer/loaders/RangesLoader.d.ts +15 -0
  65. package/lib/Viewer/loaders/index.d.ts +22 -14
  66. package/lib/Viewer/measurement/Snapper.d.ts +15 -0
  67. package/lib/Viewer/measurement/UnitConverter.d.ts +63 -0
  68. package/lib/Viewer/measurement/UnitFormatter.d.ts +4 -0
  69. package/lib/Viewer/models/IModelImpl.d.ts +10 -8
  70. package/lib/Viewer/models/ModelImpl.d.ts +7 -5
  71. package/package.json +11 -11
  72. package/src/Viewer/Viewer.ts +120 -88
  73. package/src/Viewer/commands/ClearSelected.ts +3 -1
  74. package/src/Viewer/commands/GetModels.ts +1 -1
  75. package/src/Viewer/commands/GetSelected.ts +2 -2
  76. package/src/Viewer/commands/GetSelected2.ts +34 -0
  77. package/src/Viewer/commands/HideSelected.ts +3 -1
  78. package/src/Viewer/commands/SelectModel.ts +5 -5
  79. package/src/Viewer/commands/SetSelected.ts +9 -10
  80. package/src/Viewer/commands/SetSelected2.ts +42 -0
  81. package/src/Viewer/commands/ZoomToObjects.ts +5 -6
  82. package/src/Viewer/commands/ZoomToSelected.ts +3 -1
  83. package/src/Viewer/commands/index.ts +4 -0
  84. package/src/Viewer/components/CameraComponent.ts +6 -1
  85. package/src/Viewer/components/ExtentsComponent.ts +4 -1
  86. package/src/Viewer/components/SelectionComponent.ts +7 -30
  87. package/src/Viewer/components/index.ts +6 -6
  88. package/src/Viewer/draggers/MeasureLineDragger.ts +84 -226
  89. package/src/Viewer/loaders/DynamicGltfLoader/DynamicGltfLoader.js +263 -34
  90. package/src/Viewer/loaders/DynamicGltfLoader/DynamicModelImpl.ts +20 -10
  91. package/src/Viewer/loaders/DynamicGltfLoader/GltfStructure.js +4 -1
  92. package/src/Viewer/loaders/GLTFBinaryExtension.ts +91 -0
  93. package/src/Viewer/loaders/GLTFCloudDynamicLoader.ts +13 -19
  94. package/src/Viewer/loaders/GLTFFileDynamicLoader.ts +145 -0
  95. package/src/Viewer/loaders/GLTFLoadingManager.ts +5 -4
  96. package/src/Viewer/loaders/RangesLoader.ts +95 -0
  97. package/src/Viewer/loaders/index.ts +24 -16
  98. package/src/Viewer/measurement/Snapper.ts +208 -0
  99. package/src/Viewer/measurement/UnitConverter.ts +47 -0
  100. package/src/Viewer/measurement/UnitFormatter.ts +95 -0
  101. package/src/Viewer/models/IModelImpl.ts +15 -8
  102. package/src/Viewer/models/ModelImpl.ts +48 -17
  103. package/src/index-umd.ts +1 -1
  104. package/dist/plugins/components/AxesHelperComponent.js.map +0 -1
  105. package/dist/plugins/components/AxesHelperComponent.module.js.map +0 -1
  106. package/dist/plugins/components/ExtentsHelperComponent.js.map +0 -1
  107. package/dist/plugins/components/ExtentsHelperComponent.min.js +0 -24
  108. package/dist/plugins/components/ExtentsHelperComponent.module.js.map +0 -1
  109. package/dist/plugins/components/GridHelperComponent.js.map +0 -1
  110. package/dist/plugins/components/GridHelperComponent.module.js.map +0 -1
  111. package/dist/plugins/components/LightHelperComponent.js.map +0 -1
  112. package/dist/plugins/components/LightHelperComponent.module.js.map +0 -1
  113. package/dist/plugins/components/RoomEnvironmentComponent.js.map +0 -1
  114. package/dist/plugins/components/RoomEnvironmentComponent.module.js.map +0 -1
  115. package/dist/plugins/components/StatsPanelComponent.js.map +0 -1
  116. package/dist/plugins/components/StatsPanelComponent.module.js.map +0 -1
  117. package/dist/plugins/loaders/GLTFCloudLoader.js.map +0 -1
  118. package/dist/plugins/loaders/GLTFCloudLoader.module.js.map +0 -1
  119. package/dist/plugins/loaders/IFCXLoader.js.map +0 -1
  120. package/dist/plugins/loaders/IFCXLoader.module.js.map +0 -1
  121. package/dist/plugins/loaders/PotreeLoader.js.map +0 -1
  122. package/dist/plugins/loaders/PotreeLoader.module.js.map +0 -1
  123. /package/dist/{plugins → extensions}/components/GridHelperComponent.js +0 -0
  124. /package/dist/{plugins → extensions}/components/GridHelperComponent.min.js +0 -0
  125. /package/dist/{plugins → extensions}/components/GridHelperComponent.module.js +0 -0
  126. /package/dist/{plugins → extensions}/components/LightHelperComponent.js +0 -0
  127. /package/dist/{plugins → extensions}/components/LightHelperComponent.min.js +0 -0
  128. /package/dist/{plugins → extensions}/components/LightHelperComponent.module.js +0 -0
  129. /package/dist/{plugins → extensions}/components/RoomEnvironmentComponent.js +0 -0
  130. /package/dist/{plugins → extensions}/components/RoomEnvironmentComponent.min.js +0 -0
  131. /package/dist/{plugins → extensions}/components/RoomEnvironmentComponent.module.js +0 -0
  132. /package/dist/{plugins → extensions}/components/StatsPanelComponent.js +0 -0
  133. /package/dist/{plugins → extensions}/components/StatsPanelComponent.min.js +0 -0
  134. /package/dist/{plugins → extensions}/components/StatsPanelComponent.module.js +0 -0
  135. /package/{plugins → extensions}/components/GridHelperComponent.ts +0 -0
  136. /package/{plugins → extensions}/components/LightHelperComponent.ts +0 -0
  137. /package/{plugins → extensions}/components/RoomEnvironmentComponent.ts +0 -0
  138. /package/{plugins → extensions}/components/StatsPanelComponent.ts +0 -0
  139. /package/{plugins → extensions}/loaders/IFCX/IFCXLoader.ts +0 -0
  140. /package/{plugins → extensions}/loaders/IFCX/index.ts +0 -0
  141. /package/{plugins → extensions}/loaders/IFCX/render.js +0 -0
  142. /package/{plugins → extensions}/loaders/Potree/PotreeModelImpl.ts +0 -0
  143. /package/{plugins → extensions}/loaders/Potree/index.ts +0 -0
@@ -0,0 +1,2499 @@
1
+ ///////////////////////////////////////////////////////////////////////////////
2
+ // Copyright (C) 2002-2025, Open Design Alliance (the "Alliance").
3
+ // All rights reserved.
4
+ //
5
+ // This software and its documentation and related materials are owned by
6
+ // the Alliance. The software may only be incorporated into application
7
+ // programs owned by members of the Alliance, subject to a signed
8
+ // Membership Agreement and Supplemental Software License Agreement with the
9
+ // Alliance. The structure and organization of this software are the valuable
10
+ // trade secrets of the Alliance and its suppliers. The software is also
11
+ // protected by copyright law and international treaty provisions. Application
12
+ // programs incorporating this software must include the following statement
13
+ // with their copyright notices:
14
+ //
15
+ // This application incorporates Open Design Alliance software pursuant to a
16
+ // license agreement with Open Design Alliance.
17
+ // Open Design Alliance Copyright (C) 2002-2025 by Open Design Alliance.
18
+ // All rights reserved.
19
+ //
20
+ // By use of this software, its documentation or related materials, you
21
+ // acknowledge and accept the above terms.
22
+ ///////////////////////////////////////////////////////////////////////////////
23
+
24
+ (function (global, factory) {
25
+ typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('three'), require('@inweb/viewer-three')) :
26
+ typeof define === 'function' && define.amd ? define(['exports', 'three', '@inweb/viewer-three'], factory) :
27
+ (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory((global.ODA = global.ODA || {}, global.ODA.Three = global.ODA.Three || {}, global.ODA.Three.Extensions = global.ODA.Three.Extensions || {}), global.THREE, global.ODA.Three));
28
+ })(this, (function (exports, three, viewerThree) { 'use strict';
29
+
30
+ function toTrianglesDrawMode( geometry, drawMode ) {
31
+ if ( drawMode === three.TrianglesDrawMode ) {
32
+ console.warn( 'THREE.BufferGeometryUtils.toTrianglesDrawMode(): Geometry already defined as triangles.' );
33
+ return geometry;
34
+ }
35
+ if ( drawMode === three.TriangleFanDrawMode || drawMode === three.TriangleStripDrawMode ) {
36
+ let index = geometry.getIndex();
37
+ if ( index === null ) {
38
+ const indices = [];
39
+ const position = geometry.getAttribute( 'position' );
40
+ if ( position !== undefined ) {
41
+ for ( let i = 0; i < position.count; i ++ ) {
42
+ indices.push( i );
43
+ }
44
+ geometry.setIndex( indices );
45
+ index = geometry.getIndex();
46
+ } else {
47
+ console.error( 'THREE.BufferGeometryUtils.toTrianglesDrawMode(): Undefined position attribute. Processing not possible.' );
48
+ return geometry;
49
+ }
50
+ }
51
+ const numberOfTriangles = index.count - 2;
52
+ const newIndices = [];
53
+ if ( drawMode === three.TriangleFanDrawMode ) {
54
+ for ( let i = 1; i <= numberOfTriangles; i ++ ) {
55
+ newIndices.push( index.getX( 0 ) );
56
+ newIndices.push( index.getX( i ) );
57
+ newIndices.push( index.getX( i + 1 ) );
58
+ }
59
+ } else {
60
+ for ( let i = 0; i < numberOfTriangles; i ++ ) {
61
+ if ( i % 2 === 0 ) {
62
+ newIndices.push( index.getX( i ) );
63
+ newIndices.push( index.getX( i + 1 ) );
64
+ newIndices.push( index.getX( i + 2 ) );
65
+ } else {
66
+ newIndices.push( index.getX( i + 2 ) );
67
+ newIndices.push( index.getX( i + 1 ) );
68
+ newIndices.push( index.getX( i ) );
69
+ }
70
+ }
71
+ }
72
+ if ( ( newIndices.length / 3 ) !== numberOfTriangles ) {
73
+ console.error( 'THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unable to generate correct amount of triangles.' );
74
+ }
75
+ const newGeometry = geometry.clone();
76
+ newGeometry.setIndex( newIndices );
77
+ newGeometry.clearGroups();
78
+ return newGeometry;
79
+ } else {
80
+ console.error( 'THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unknown draw mode:', drawMode );
81
+ return geometry;
82
+ }
83
+ }
84
+
85
+ class GLTFLoader extends three.Loader {
86
+ constructor( manager ) {
87
+ super( manager );
88
+ this.dracoLoader = null;
89
+ this.ktx2Loader = null;
90
+ this.meshoptDecoder = null;
91
+ this.pluginCallbacks = [];
92
+ this.register( function ( parser ) {
93
+ return new GLTFMaterialsClearcoatExtension( parser );
94
+ } );
95
+ this.register( function ( parser ) {
96
+ return new GLTFMaterialsDispersionExtension( parser );
97
+ } );
98
+ this.register( function ( parser ) {
99
+ return new GLTFTextureBasisUExtension( parser );
100
+ } );
101
+ this.register( function ( parser ) {
102
+ return new GLTFTextureWebPExtension( parser );
103
+ } );
104
+ this.register( function ( parser ) {
105
+ return new GLTFTextureAVIFExtension( parser );
106
+ } );
107
+ this.register( function ( parser ) {
108
+ return new GLTFMaterialsSheenExtension( parser );
109
+ } );
110
+ this.register( function ( parser ) {
111
+ return new GLTFMaterialsTransmissionExtension( parser );
112
+ } );
113
+ this.register( function ( parser ) {
114
+ return new GLTFMaterialsVolumeExtension( parser );
115
+ } );
116
+ this.register( function ( parser ) {
117
+ return new GLTFMaterialsIorExtension( parser );
118
+ } );
119
+ this.register( function ( parser ) {
120
+ return new GLTFMaterialsEmissiveStrengthExtension( parser );
121
+ } );
122
+ this.register( function ( parser ) {
123
+ return new GLTFMaterialsSpecularExtension( parser );
124
+ } );
125
+ this.register( function ( parser ) {
126
+ return new GLTFMaterialsIridescenceExtension( parser );
127
+ } );
128
+ this.register( function ( parser ) {
129
+ return new GLTFMaterialsAnisotropyExtension( parser );
130
+ } );
131
+ this.register( function ( parser ) {
132
+ return new GLTFMaterialsBumpExtension( parser );
133
+ } );
134
+ this.register( function ( parser ) {
135
+ return new GLTFLightsExtension( parser );
136
+ } );
137
+ this.register( function ( parser ) {
138
+ return new GLTFMeshoptCompression( parser );
139
+ } );
140
+ this.register( function ( parser ) {
141
+ return new GLTFMeshGpuInstancing( parser );
142
+ } );
143
+ }
144
+ load( url, onLoad, onProgress, onError ) {
145
+ const scope = this;
146
+ let resourcePath;
147
+ if ( this.resourcePath !== '' ) {
148
+ resourcePath = this.resourcePath;
149
+ } else if ( this.path !== '' ) {
150
+ const relativeUrl = three.LoaderUtils.extractUrlBase( url );
151
+ resourcePath = three.LoaderUtils.resolveURL( relativeUrl, this.path );
152
+ } else {
153
+ resourcePath = three.LoaderUtils.extractUrlBase( url );
154
+ }
155
+ this.manager.itemStart( url );
156
+ const _onError = function ( e ) {
157
+ if ( onError ) {
158
+ onError( e );
159
+ } else {
160
+ console.error( e );
161
+ }
162
+ scope.manager.itemError( url );
163
+ scope.manager.itemEnd( url );
164
+ };
165
+ const loader = new three.FileLoader( this.manager );
166
+ loader.setPath( this.path );
167
+ loader.setResponseType( 'arraybuffer' );
168
+ loader.setRequestHeader( this.requestHeader );
169
+ loader.setWithCredentials( this.withCredentials );
170
+ loader.load( url, function ( data ) {
171
+ try {
172
+ scope.parse( data, resourcePath, function ( gltf ) {
173
+ onLoad( gltf );
174
+ scope.manager.itemEnd( url );
175
+ }, _onError );
176
+ } catch ( e ) {
177
+ _onError( e );
178
+ }
179
+ }, onProgress, _onError );
180
+ }
181
+ setDRACOLoader( dracoLoader ) {
182
+ this.dracoLoader = dracoLoader;
183
+ return this;
184
+ }
185
+ setKTX2Loader( ktx2Loader ) {
186
+ this.ktx2Loader = ktx2Loader;
187
+ return this;
188
+ }
189
+ setMeshoptDecoder( meshoptDecoder ) {
190
+ this.meshoptDecoder = meshoptDecoder;
191
+ return this;
192
+ }
193
+ register( callback ) {
194
+ if ( this.pluginCallbacks.indexOf( callback ) === -1 ) {
195
+ this.pluginCallbacks.push( callback );
196
+ }
197
+ return this;
198
+ }
199
+ unregister( callback ) {
200
+ if ( this.pluginCallbacks.indexOf( callback ) !== -1 ) {
201
+ this.pluginCallbacks.splice( this.pluginCallbacks.indexOf( callback ), 1 );
202
+ }
203
+ return this;
204
+ }
205
+ parse( data, path, onLoad, onError ) {
206
+ let json;
207
+ const extensions = {};
208
+ const plugins = {};
209
+ const textDecoder = new TextDecoder();
210
+ if ( typeof data === 'string' ) {
211
+ json = JSON.parse( data );
212
+ } else if ( data instanceof ArrayBuffer ) {
213
+ const magic = textDecoder.decode( new Uint8Array( data, 0, 4 ) );
214
+ if ( magic === BINARY_EXTENSION_HEADER_MAGIC ) {
215
+ try {
216
+ extensions[ EXTENSIONS.KHR_BINARY_GLTF ] = new GLTFBinaryExtension( data );
217
+ } catch ( error ) {
218
+ if ( onError ) onError( error );
219
+ return;
220
+ }
221
+ json = JSON.parse( extensions[ EXTENSIONS.KHR_BINARY_GLTF ].content );
222
+ } else {
223
+ json = JSON.parse( textDecoder.decode( data ) );
224
+ }
225
+ } else {
226
+ json = data;
227
+ }
228
+ if ( json.asset === undefined || json.asset.version[ 0 ] < 2 ) {
229
+ if ( onError ) onError( new Error( 'THREE.GLTFLoader: Unsupported asset. glTF versions >=2.0 are supported.' ) );
230
+ return;
231
+ }
232
+ const parser = new GLTFParser( json, {
233
+ path: path || this.resourcePath || '',
234
+ crossOrigin: this.crossOrigin,
235
+ requestHeader: this.requestHeader,
236
+ manager: this.manager,
237
+ ktx2Loader: this.ktx2Loader,
238
+ meshoptDecoder: this.meshoptDecoder
239
+ } );
240
+ parser.fileLoader.setRequestHeader( this.requestHeader );
241
+ for ( let i = 0; i < this.pluginCallbacks.length; i ++ ) {
242
+ const plugin = this.pluginCallbacks[ i ]( parser );
243
+ if ( ! plugin.name ) console.error( 'THREE.GLTFLoader: Invalid plugin found: missing name' );
244
+ plugins[ plugin.name ] = plugin;
245
+ extensions[ plugin.name ] = true;
246
+ }
247
+ if ( json.extensionsUsed ) {
248
+ for ( let i = 0; i < json.extensionsUsed.length; ++ i ) {
249
+ const extensionName = json.extensionsUsed[ i ];
250
+ const extensionsRequired = json.extensionsRequired || [];
251
+ switch ( extensionName ) {
252
+ case EXTENSIONS.KHR_MATERIALS_UNLIT:
253
+ extensions[ extensionName ] = new GLTFMaterialsUnlitExtension();
254
+ break;
255
+ case EXTENSIONS.KHR_DRACO_MESH_COMPRESSION:
256
+ extensions[ extensionName ] = new GLTFDracoMeshCompressionExtension( json, this.dracoLoader );
257
+ break;
258
+ case EXTENSIONS.KHR_TEXTURE_TRANSFORM:
259
+ extensions[ extensionName ] = new GLTFTextureTransformExtension();
260
+ break;
261
+ case EXTENSIONS.KHR_MESH_QUANTIZATION:
262
+ extensions[ extensionName ] = new GLTFMeshQuantizationExtension();
263
+ break;
264
+ default:
265
+ if ( extensionsRequired.indexOf( extensionName ) >= 0 && plugins[ extensionName ] === undefined ) {
266
+ console.warn( 'THREE.GLTFLoader: Unknown extension "' + extensionName + '".' );
267
+ }
268
+ }
269
+ }
270
+ }
271
+ parser.setExtensions( extensions );
272
+ parser.setPlugins( plugins );
273
+ parser.parse( onLoad, onError );
274
+ }
275
+ parseAsync( data, path ) {
276
+ const scope = this;
277
+ return new Promise( function ( resolve, reject ) {
278
+ scope.parse( data, path, resolve, reject );
279
+ } );
280
+ }
281
+ }
282
+ function GLTFRegistry() {
283
+ let objects = {};
284
+ return {
285
+ get: function ( key ) {
286
+ return objects[ key ];
287
+ },
288
+ add: function ( key, object ) {
289
+ objects[ key ] = object;
290
+ },
291
+ remove: function ( key ) {
292
+ delete objects[ key ];
293
+ },
294
+ removeAll: function () {
295
+ objects = {};
296
+ }
297
+ };
298
+ }
299
+ const EXTENSIONS = {
300
+ KHR_BINARY_GLTF: 'KHR_binary_glTF',
301
+ KHR_DRACO_MESH_COMPRESSION: 'KHR_draco_mesh_compression',
302
+ KHR_LIGHTS_PUNCTUAL: 'KHR_lights_punctual',
303
+ KHR_MATERIALS_CLEARCOAT: 'KHR_materials_clearcoat',
304
+ KHR_MATERIALS_DISPERSION: 'KHR_materials_dispersion',
305
+ KHR_MATERIALS_IOR: 'KHR_materials_ior',
306
+ KHR_MATERIALS_SHEEN: 'KHR_materials_sheen',
307
+ KHR_MATERIALS_SPECULAR: 'KHR_materials_specular',
308
+ KHR_MATERIALS_TRANSMISSION: 'KHR_materials_transmission',
309
+ KHR_MATERIALS_IRIDESCENCE: 'KHR_materials_iridescence',
310
+ KHR_MATERIALS_ANISOTROPY: 'KHR_materials_anisotropy',
311
+ KHR_MATERIALS_UNLIT: 'KHR_materials_unlit',
312
+ KHR_MATERIALS_VOLUME: 'KHR_materials_volume',
313
+ KHR_TEXTURE_BASISU: 'KHR_texture_basisu',
314
+ KHR_TEXTURE_TRANSFORM: 'KHR_texture_transform',
315
+ KHR_MESH_QUANTIZATION: 'KHR_mesh_quantization',
316
+ KHR_MATERIALS_EMISSIVE_STRENGTH: 'KHR_materials_emissive_strength',
317
+ EXT_MATERIALS_BUMP: 'EXT_materials_bump',
318
+ EXT_TEXTURE_WEBP: 'EXT_texture_webp',
319
+ EXT_TEXTURE_AVIF: 'EXT_texture_avif',
320
+ EXT_MESHOPT_COMPRESSION: 'EXT_meshopt_compression',
321
+ EXT_MESH_GPU_INSTANCING: 'EXT_mesh_gpu_instancing'
322
+ };
323
+ class GLTFLightsExtension {
324
+ constructor( parser ) {
325
+ this.parser = parser;
326
+ this.name = EXTENSIONS.KHR_LIGHTS_PUNCTUAL;
327
+ this.cache = { refs: {}, uses: {} };
328
+ }
329
+ _markDefs() {
330
+ const parser = this.parser;
331
+ const nodeDefs = this.parser.json.nodes || [];
332
+ for ( let nodeIndex = 0, nodeLength = nodeDefs.length; nodeIndex < nodeLength; nodeIndex ++ ) {
333
+ const nodeDef = nodeDefs[ nodeIndex ];
334
+ if ( nodeDef.extensions
335
+ && nodeDef.extensions[ this.name ]
336
+ && nodeDef.extensions[ this.name ].light !== undefined ) {
337
+ parser._addNodeRef( this.cache, nodeDef.extensions[ this.name ].light );
338
+ }
339
+ }
340
+ }
341
+ _loadLight( lightIndex ) {
342
+ const parser = this.parser;
343
+ const cacheKey = 'light:' + lightIndex;
344
+ let dependency = parser.cache.get( cacheKey );
345
+ if ( dependency ) return dependency;
346
+ const json = parser.json;
347
+ const extensions = ( json.extensions && json.extensions[ this.name ] ) || {};
348
+ const lightDefs = extensions.lights || [];
349
+ const lightDef = lightDefs[ lightIndex ];
350
+ let lightNode;
351
+ const color = new three.Color( 0xffffff );
352
+ if ( lightDef.color !== undefined ) color.setRGB( lightDef.color[ 0 ], lightDef.color[ 1 ], lightDef.color[ 2 ], three.LinearSRGBColorSpace );
353
+ const range = lightDef.range !== undefined ? lightDef.range : 0;
354
+ switch ( lightDef.type ) {
355
+ case 'directional':
356
+ lightNode = new three.DirectionalLight( color );
357
+ lightNode.target.position.set( 0, 0, -1 );
358
+ lightNode.add( lightNode.target );
359
+ break;
360
+ case 'point':
361
+ lightNode = new three.PointLight( color );
362
+ lightNode.distance = range;
363
+ break;
364
+ case 'spot':
365
+ lightNode = new three.SpotLight( color );
366
+ lightNode.distance = range;
367
+ lightDef.spot = lightDef.spot || {};
368
+ lightDef.spot.innerConeAngle = lightDef.spot.innerConeAngle !== undefined ? lightDef.spot.innerConeAngle : 0;
369
+ lightDef.spot.outerConeAngle = lightDef.spot.outerConeAngle !== undefined ? lightDef.spot.outerConeAngle : Math.PI / 4.0;
370
+ lightNode.angle = lightDef.spot.outerConeAngle;
371
+ lightNode.penumbra = 1.0 - lightDef.spot.innerConeAngle / lightDef.spot.outerConeAngle;
372
+ lightNode.target.position.set( 0, 0, -1 );
373
+ lightNode.add( lightNode.target );
374
+ break;
375
+ default:
376
+ throw new Error( 'THREE.GLTFLoader: Unexpected light type: ' + lightDef.type );
377
+ }
378
+ lightNode.position.set( 0, 0, 0 );
379
+ assignExtrasToUserData( lightNode, lightDef );
380
+ if ( lightDef.intensity !== undefined ) lightNode.intensity = lightDef.intensity;
381
+ lightNode.name = parser.createUniqueName( lightDef.name || ( 'light_' + lightIndex ) );
382
+ dependency = Promise.resolve( lightNode );
383
+ parser.cache.add( cacheKey, dependency );
384
+ return dependency;
385
+ }
386
+ getDependency( type, index ) {
387
+ if ( type !== 'light' ) return;
388
+ return this._loadLight( index );
389
+ }
390
+ createNodeAttachment( nodeIndex ) {
391
+ const self = this;
392
+ const parser = this.parser;
393
+ const json = parser.json;
394
+ const nodeDef = json.nodes[ nodeIndex ];
395
+ const lightDef = ( nodeDef.extensions && nodeDef.extensions[ this.name ] ) || {};
396
+ const lightIndex = lightDef.light;
397
+ if ( lightIndex === undefined ) return null;
398
+ return this._loadLight( lightIndex ).then( function ( light ) {
399
+ return parser._getNodeRef( self.cache, lightIndex, light );
400
+ } );
401
+ }
402
+ }
403
+ class GLTFMaterialsUnlitExtension {
404
+ constructor() {
405
+ this.name = EXTENSIONS.KHR_MATERIALS_UNLIT;
406
+ }
407
+ getMaterialType() {
408
+ return three.MeshBasicMaterial;
409
+ }
410
+ extendParams( materialParams, materialDef, parser ) {
411
+ const pending = [];
412
+ materialParams.color = new three.Color( 1.0, 1.0, 1.0 );
413
+ materialParams.opacity = 1.0;
414
+ const metallicRoughness = materialDef.pbrMetallicRoughness;
415
+ if ( metallicRoughness ) {
416
+ if ( Array.isArray( metallicRoughness.baseColorFactor ) ) {
417
+ const array = metallicRoughness.baseColorFactor;
418
+ materialParams.color.setRGB( array[ 0 ], array[ 1 ], array[ 2 ], three.LinearSRGBColorSpace );
419
+ materialParams.opacity = array[ 3 ];
420
+ }
421
+ if ( metallicRoughness.baseColorTexture !== undefined ) {
422
+ pending.push( parser.assignTexture( materialParams, 'map', metallicRoughness.baseColorTexture, three.SRGBColorSpace ) );
423
+ }
424
+ }
425
+ return Promise.all( pending );
426
+ }
427
+ }
428
+ class GLTFMaterialsEmissiveStrengthExtension {
429
+ constructor( parser ) {
430
+ this.parser = parser;
431
+ this.name = EXTENSIONS.KHR_MATERIALS_EMISSIVE_STRENGTH;
432
+ }
433
+ extendMaterialParams( materialIndex, materialParams ) {
434
+ const parser = this.parser;
435
+ const materialDef = parser.json.materials[ materialIndex ];
436
+ if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) {
437
+ return Promise.resolve();
438
+ }
439
+ const emissiveStrength = materialDef.extensions[ this.name ].emissiveStrength;
440
+ if ( emissiveStrength !== undefined ) {
441
+ materialParams.emissiveIntensity = emissiveStrength;
442
+ }
443
+ return Promise.resolve();
444
+ }
445
+ }
446
+ class GLTFMaterialsClearcoatExtension {
447
+ constructor( parser ) {
448
+ this.parser = parser;
449
+ this.name = EXTENSIONS.KHR_MATERIALS_CLEARCOAT;
450
+ }
451
+ getMaterialType( materialIndex ) {
452
+ const parser = this.parser;
453
+ const materialDef = parser.json.materials[ materialIndex ];
454
+ if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) return null;
455
+ return three.MeshPhysicalMaterial;
456
+ }
457
+ extendMaterialParams( materialIndex, materialParams ) {
458
+ const parser = this.parser;
459
+ const materialDef = parser.json.materials[ materialIndex ];
460
+ if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) {
461
+ return Promise.resolve();
462
+ }
463
+ const pending = [];
464
+ const extension = materialDef.extensions[ this.name ];
465
+ if ( extension.clearcoatFactor !== undefined ) {
466
+ materialParams.clearcoat = extension.clearcoatFactor;
467
+ }
468
+ if ( extension.clearcoatTexture !== undefined ) {
469
+ pending.push( parser.assignTexture( materialParams, 'clearcoatMap', extension.clearcoatTexture ) );
470
+ }
471
+ if ( extension.clearcoatRoughnessFactor !== undefined ) {
472
+ materialParams.clearcoatRoughness = extension.clearcoatRoughnessFactor;
473
+ }
474
+ if ( extension.clearcoatRoughnessTexture !== undefined ) {
475
+ pending.push( parser.assignTexture( materialParams, 'clearcoatRoughnessMap', extension.clearcoatRoughnessTexture ) );
476
+ }
477
+ if ( extension.clearcoatNormalTexture !== undefined ) {
478
+ pending.push( parser.assignTexture( materialParams, 'clearcoatNormalMap', extension.clearcoatNormalTexture ) );
479
+ if ( extension.clearcoatNormalTexture.scale !== undefined ) {
480
+ const scale = extension.clearcoatNormalTexture.scale;
481
+ materialParams.clearcoatNormalScale = new three.Vector2( scale, scale );
482
+ }
483
+ }
484
+ return Promise.all( pending );
485
+ }
486
+ }
487
+ class GLTFMaterialsDispersionExtension {
488
+ constructor( parser ) {
489
+ this.parser = parser;
490
+ this.name = EXTENSIONS.KHR_MATERIALS_DISPERSION;
491
+ }
492
+ getMaterialType( materialIndex ) {
493
+ const parser = this.parser;
494
+ const materialDef = parser.json.materials[ materialIndex ];
495
+ if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) return null;
496
+ return three.MeshPhysicalMaterial;
497
+ }
498
+ extendMaterialParams( materialIndex, materialParams ) {
499
+ const parser = this.parser;
500
+ const materialDef = parser.json.materials[ materialIndex ];
501
+ if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) {
502
+ return Promise.resolve();
503
+ }
504
+ const extension = materialDef.extensions[ this.name ];
505
+ materialParams.dispersion = extension.dispersion !== undefined ? extension.dispersion : 0;
506
+ return Promise.resolve();
507
+ }
508
+ }
509
+ class GLTFMaterialsIridescenceExtension {
510
+ constructor( parser ) {
511
+ this.parser = parser;
512
+ this.name = EXTENSIONS.KHR_MATERIALS_IRIDESCENCE;
513
+ }
514
+ getMaterialType( materialIndex ) {
515
+ const parser = this.parser;
516
+ const materialDef = parser.json.materials[ materialIndex ];
517
+ if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) return null;
518
+ return three.MeshPhysicalMaterial;
519
+ }
520
+ extendMaterialParams( materialIndex, materialParams ) {
521
+ const parser = this.parser;
522
+ const materialDef = parser.json.materials[ materialIndex ];
523
+ if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) {
524
+ return Promise.resolve();
525
+ }
526
+ const pending = [];
527
+ const extension = materialDef.extensions[ this.name ];
528
+ if ( extension.iridescenceFactor !== undefined ) {
529
+ materialParams.iridescence = extension.iridescenceFactor;
530
+ }
531
+ if ( extension.iridescenceTexture !== undefined ) {
532
+ pending.push( parser.assignTexture( materialParams, 'iridescenceMap', extension.iridescenceTexture ) );
533
+ }
534
+ if ( extension.iridescenceIor !== undefined ) {
535
+ materialParams.iridescenceIOR = extension.iridescenceIor;
536
+ }
537
+ if ( materialParams.iridescenceThicknessRange === undefined ) {
538
+ materialParams.iridescenceThicknessRange = [ 100, 400 ];
539
+ }
540
+ if ( extension.iridescenceThicknessMinimum !== undefined ) {
541
+ materialParams.iridescenceThicknessRange[ 0 ] = extension.iridescenceThicknessMinimum;
542
+ }
543
+ if ( extension.iridescenceThicknessMaximum !== undefined ) {
544
+ materialParams.iridescenceThicknessRange[ 1 ] = extension.iridescenceThicknessMaximum;
545
+ }
546
+ if ( extension.iridescenceThicknessTexture !== undefined ) {
547
+ pending.push( parser.assignTexture( materialParams, 'iridescenceThicknessMap', extension.iridescenceThicknessTexture ) );
548
+ }
549
+ return Promise.all( pending );
550
+ }
551
+ }
552
+ class GLTFMaterialsSheenExtension {
553
+ constructor( parser ) {
554
+ this.parser = parser;
555
+ this.name = EXTENSIONS.KHR_MATERIALS_SHEEN;
556
+ }
557
+ getMaterialType( materialIndex ) {
558
+ const parser = this.parser;
559
+ const materialDef = parser.json.materials[ materialIndex ];
560
+ if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) return null;
561
+ return three.MeshPhysicalMaterial;
562
+ }
563
+ extendMaterialParams( materialIndex, materialParams ) {
564
+ const parser = this.parser;
565
+ const materialDef = parser.json.materials[ materialIndex ];
566
+ if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) {
567
+ return Promise.resolve();
568
+ }
569
+ const pending = [];
570
+ materialParams.sheenColor = new three.Color( 0, 0, 0 );
571
+ materialParams.sheenRoughness = 0;
572
+ materialParams.sheen = 1;
573
+ const extension = materialDef.extensions[ this.name ];
574
+ if ( extension.sheenColorFactor !== undefined ) {
575
+ const colorFactor = extension.sheenColorFactor;
576
+ materialParams.sheenColor.setRGB( colorFactor[ 0 ], colorFactor[ 1 ], colorFactor[ 2 ], three.LinearSRGBColorSpace );
577
+ }
578
+ if ( extension.sheenRoughnessFactor !== undefined ) {
579
+ materialParams.sheenRoughness = extension.sheenRoughnessFactor;
580
+ }
581
+ if ( extension.sheenColorTexture !== undefined ) {
582
+ pending.push( parser.assignTexture( materialParams, 'sheenColorMap', extension.sheenColorTexture, three.SRGBColorSpace ) );
583
+ }
584
+ if ( extension.sheenRoughnessTexture !== undefined ) {
585
+ pending.push( parser.assignTexture( materialParams, 'sheenRoughnessMap', extension.sheenRoughnessTexture ) );
586
+ }
587
+ return Promise.all( pending );
588
+ }
589
+ }
590
+ class GLTFMaterialsTransmissionExtension {
591
+ constructor( parser ) {
592
+ this.parser = parser;
593
+ this.name = EXTENSIONS.KHR_MATERIALS_TRANSMISSION;
594
+ }
595
+ getMaterialType( materialIndex ) {
596
+ const parser = this.parser;
597
+ const materialDef = parser.json.materials[ materialIndex ];
598
+ if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) return null;
599
+ return three.MeshPhysicalMaterial;
600
+ }
601
+ extendMaterialParams( materialIndex, materialParams ) {
602
+ const parser = this.parser;
603
+ const materialDef = parser.json.materials[ materialIndex ];
604
+ if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) {
605
+ return Promise.resolve();
606
+ }
607
+ const pending = [];
608
+ const extension = materialDef.extensions[ this.name ];
609
+ if ( extension.transmissionFactor !== undefined ) {
610
+ materialParams.transmission = extension.transmissionFactor;
611
+ }
612
+ if ( extension.transmissionTexture !== undefined ) {
613
+ pending.push( parser.assignTexture( materialParams, 'transmissionMap', extension.transmissionTexture ) );
614
+ }
615
+ return Promise.all( pending );
616
+ }
617
+ }
618
+ class GLTFMaterialsVolumeExtension {
619
+ constructor( parser ) {
620
+ this.parser = parser;
621
+ this.name = EXTENSIONS.KHR_MATERIALS_VOLUME;
622
+ }
623
+ getMaterialType( materialIndex ) {
624
+ const parser = this.parser;
625
+ const materialDef = parser.json.materials[ materialIndex ];
626
+ if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) return null;
627
+ return three.MeshPhysicalMaterial;
628
+ }
629
+ extendMaterialParams( materialIndex, materialParams ) {
630
+ const parser = this.parser;
631
+ const materialDef = parser.json.materials[ materialIndex ];
632
+ if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) {
633
+ return Promise.resolve();
634
+ }
635
+ const pending = [];
636
+ const extension = materialDef.extensions[ this.name ];
637
+ materialParams.thickness = extension.thicknessFactor !== undefined ? extension.thicknessFactor : 0;
638
+ if ( extension.thicknessTexture !== undefined ) {
639
+ pending.push( parser.assignTexture( materialParams, 'thicknessMap', extension.thicknessTexture ) );
640
+ }
641
+ materialParams.attenuationDistance = extension.attenuationDistance || Infinity;
642
+ const colorArray = extension.attenuationColor || [ 1, 1, 1 ];
643
+ materialParams.attenuationColor = new three.Color().setRGB( colorArray[ 0 ], colorArray[ 1 ], colorArray[ 2 ], three.LinearSRGBColorSpace );
644
+ return Promise.all( pending );
645
+ }
646
+ }
647
+ class GLTFMaterialsIorExtension {
648
+ constructor( parser ) {
649
+ this.parser = parser;
650
+ this.name = EXTENSIONS.KHR_MATERIALS_IOR;
651
+ }
652
+ getMaterialType( materialIndex ) {
653
+ const parser = this.parser;
654
+ const materialDef = parser.json.materials[ materialIndex ];
655
+ if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) return null;
656
+ return three.MeshPhysicalMaterial;
657
+ }
658
+ extendMaterialParams( materialIndex, materialParams ) {
659
+ const parser = this.parser;
660
+ const materialDef = parser.json.materials[ materialIndex ];
661
+ if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) {
662
+ return Promise.resolve();
663
+ }
664
+ const extension = materialDef.extensions[ this.name ];
665
+ materialParams.ior = extension.ior !== undefined ? extension.ior : 1.5;
666
+ return Promise.resolve();
667
+ }
668
+ }
669
+ class GLTFMaterialsSpecularExtension {
670
+ constructor( parser ) {
671
+ this.parser = parser;
672
+ this.name = EXTENSIONS.KHR_MATERIALS_SPECULAR;
673
+ }
674
+ getMaterialType( materialIndex ) {
675
+ const parser = this.parser;
676
+ const materialDef = parser.json.materials[ materialIndex ];
677
+ if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) return null;
678
+ return three.MeshPhysicalMaterial;
679
+ }
680
+ extendMaterialParams( materialIndex, materialParams ) {
681
+ const parser = this.parser;
682
+ const materialDef = parser.json.materials[ materialIndex ];
683
+ if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) {
684
+ return Promise.resolve();
685
+ }
686
+ const pending = [];
687
+ const extension = materialDef.extensions[ this.name ];
688
+ materialParams.specularIntensity = extension.specularFactor !== undefined ? extension.specularFactor : 1.0;
689
+ if ( extension.specularTexture !== undefined ) {
690
+ pending.push( parser.assignTexture( materialParams, 'specularIntensityMap', extension.specularTexture ) );
691
+ }
692
+ const colorArray = extension.specularColorFactor || [ 1, 1, 1 ];
693
+ materialParams.specularColor = new three.Color().setRGB( colorArray[ 0 ], colorArray[ 1 ], colorArray[ 2 ], three.LinearSRGBColorSpace );
694
+ if ( extension.specularColorTexture !== undefined ) {
695
+ pending.push( parser.assignTexture( materialParams, 'specularColorMap', extension.specularColorTexture, three.SRGBColorSpace ) );
696
+ }
697
+ return Promise.all( pending );
698
+ }
699
+ }
700
+ class GLTFMaterialsBumpExtension {
701
+ constructor( parser ) {
702
+ this.parser = parser;
703
+ this.name = EXTENSIONS.EXT_MATERIALS_BUMP;
704
+ }
705
+ getMaterialType( materialIndex ) {
706
+ const parser = this.parser;
707
+ const materialDef = parser.json.materials[ materialIndex ];
708
+ if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) return null;
709
+ return three.MeshPhysicalMaterial;
710
+ }
711
+ extendMaterialParams( materialIndex, materialParams ) {
712
+ const parser = this.parser;
713
+ const materialDef = parser.json.materials[ materialIndex ];
714
+ if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) {
715
+ return Promise.resolve();
716
+ }
717
+ const pending = [];
718
+ const extension = materialDef.extensions[ this.name ];
719
+ materialParams.bumpScale = extension.bumpFactor !== undefined ? extension.bumpFactor : 1.0;
720
+ if ( extension.bumpTexture !== undefined ) {
721
+ pending.push( parser.assignTexture( materialParams, 'bumpMap', extension.bumpTexture ) );
722
+ }
723
+ return Promise.all( pending );
724
+ }
725
+ }
726
+ class GLTFMaterialsAnisotropyExtension {
727
+ constructor( parser ) {
728
+ this.parser = parser;
729
+ this.name = EXTENSIONS.KHR_MATERIALS_ANISOTROPY;
730
+ }
731
+ getMaterialType( materialIndex ) {
732
+ const parser = this.parser;
733
+ const materialDef = parser.json.materials[ materialIndex ];
734
+ if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) return null;
735
+ return three.MeshPhysicalMaterial;
736
+ }
737
+ extendMaterialParams( materialIndex, materialParams ) {
738
+ const parser = this.parser;
739
+ const materialDef = parser.json.materials[ materialIndex ];
740
+ if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) {
741
+ return Promise.resolve();
742
+ }
743
+ const pending = [];
744
+ const extension = materialDef.extensions[ this.name ];
745
+ if ( extension.anisotropyStrength !== undefined ) {
746
+ materialParams.anisotropy = extension.anisotropyStrength;
747
+ }
748
+ if ( extension.anisotropyRotation !== undefined ) {
749
+ materialParams.anisotropyRotation = extension.anisotropyRotation;
750
+ }
751
+ if ( extension.anisotropyTexture !== undefined ) {
752
+ pending.push( parser.assignTexture( materialParams, 'anisotropyMap', extension.anisotropyTexture ) );
753
+ }
754
+ return Promise.all( pending );
755
+ }
756
+ }
757
+ class GLTFTextureBasisUExtension {
758
+ constructor( parser ) {
759
+ this.parser = parser;
760
+ this.name = EXTENSIONS.KHR_TEXTURE_BASISU;
761
+ }
762
+ loadTexture( textureIndex ) {
763
+ const parser = this.parser;
764
+ const json = parser.json;
765
+ const textureDef = json.textures[ textureIndex ];
766
+ if ( ! textureDef.extensions || ! textureDef.extensions[ this.name ] ) {
767
+ return null;
768
+ }
769
+ const extension = textureDef.extensions[ this.name ];
770
+ const loader = parser.options.ktx2Loader;
771
+ if ( ! loader ) {
772
+ if ( json.extensionsRequired && json.extensionsRequired.indexOf( this.name ) >= 0 ) {
773
+ throw new Error( 'THREE.GLTFLoader: setKTX2Loader must be called before loading KTX2 textures' );
774
+ } else {
775
+ return null;
776
+ }
777
+ }
778
+ return parser.loadTextureImage( textureIndex, extension.source, loader );
779
+ }
780
+ }
781
+ class GLTFTextureWebPExtension {
782
+ constructor( parser ) {
783
+ this.parser = parser;
784
+ this.name = EXTENSIONS.EXT_TEXTURE_WEBP;
785
+ }
786
+ loadTexture( textureIndex ) {
787
+ const name = this.name;
788
+ const parser = this.parser;
789
+ const json = parser.json;
790
+ const textureDef = json.textures[ textureIndex ];
791
+ if ( ! textureDef.extensions || ! textureDef.extensions[ name ] ) {
792
+ return null;
793
+ }
794
+ const extension = textureDef.extensions[ name ];
795
+ const source = json.images[ extension.source ];
796
+ let loader = parser.textureLoader;
797
+ if ( source.uri ) {
798
+ const handler = parser.options.manager.getHandler( source.uri );
799
+ if ( handler !== null ) loader = handler;
800
+ }
801
+ return parser.loadTextureImage( textureIndex, extension.source, loader );
802
+ }
803
+ }
804
+ class GLTFTextureAVIFExtension {
805
+ constructor( parser ) {
806
+ this.parser = parser;
807
+ this.name = EXTENSIONS.EXT_TEXTURE_AVIF;
808
+ }
809
+ loadTexture( textureIndex ) {
810
+ const name = this.name;
811
+ const parser = this.parser;
812
+ const json = parser.json;
813
+ const textureDef = json.textures[ textureIndex ];
814
+ if ( ! textureDef.extensions || ! textureDef.extensions[ name ] ) {
815
+ return null;
816
+ }
817
+ const extension = textureDef.extensions[ name ];
818
+ const source = json.images[ extension.source ];
819
+ let loader = parser.textureLoader;
820
+ if ( source.uri ) {
821
+ const handler = parser.options.manager.getHandler( source.uri );
822
+ if ( handler !== null ) loader = handler;
823
+ }
824
+ return parser.loadTextureImage( textureIndex, extension.source, loader );
825
+ }
826
+ }
827
+ class GLTFMeshoptCompression {
828
+ constructor( parser ) {
829
+ this.name = EXTENSIONS.EXT_MESHOPT_COMPRESSION;
830
+ this.parser = parser;
831
+ }
832
+ loadBufferView( index ) {
833
+ const json = this.parser.json;
834
+ const bufferView = json.bufferViews[ index ];
835
+ if ( bufferView.extensions && bufferView.extensions[ this.name ] ) {
836
+ const extensionDef = bufferView.extensions[ this.name ];
837
+ const buffer = this.parser.getDependency( 'buffer', extensionDef.buffer );
838
+ const decoder = this.parser.options.meshoptDecoder;
839
+ if ( ! decoder || ! decoder.supported ) {
840
+ if ( json.extensionsRequired && json.extensionsRequired.indexOf( this.name ) >= 0 ) {
841
+ throw new Error( 'THREE.GLTFLoader: setMeshoptDecoder must be called before loading compressed files' );
842
+ } else {
843
+ return null;
844
+ }
845
+ }
846
+ return buffer.then( function ( res ) {
847
+ const byteOffset = extensionDef.byteOffset || 0;
848
+ const byteLength = extensionDef.byteLength || 0;
849
+ const count = extensionDef.count;
850
+ const stride = extensionDef.byteStride;
851
+ const source = new Uint8Array( res, byteOffset, byteLength );
852
+ if ( decoder.decodeGltfBufferAsync ) {
853
+ return decoder.decodeGltfBufferAsync( count, stride, source, extensionDef.mode, extensionDef.filter ).then( function ( res ) {
854
+ return res.buffer;
855
+ } );
856
+ } else {
857
+ return decoder.ready.then( function () {
858
+ const result = new ArrayBuffer( count * stride );
859
+ decoder.decodeGltfBuffer( new Uint8Array( result ), count, stride, source, extensionDef.mode, extensionDef.filter );
860
+ return result;
861
+ } );
862
+ }
863
+ } );
864
+ } else {
865
+ return null;
866
+ }
867
+ }
868
+ }
869
+ class GLTFMeshGpuInstancing {
870
+ constructor( parser ) {
871
+ this.name = EXTENSIONS.EXT_MESH_GPU_INSTANCING;
872
+ this.parser = parser;
873
+ }
874
+ createNodeMesh( nodeIndex ) {
875
+ const json = this.parser.json;
876
+ const nodeDef = json.nodes[ nodeIndex ];
877
+ if ( ! nodeDef.extensions || ! nodeDef.extensions[ this.name ] ||
878
+ nodeDef.mesh === undefined ) {
879
+ return null;
880
+ }
881
+ const meshDef = json.meshes[ nodeDef.mesh ];
882
+ for ( const primitive of meshDef.primitives ) {
883
+ if ( primitive.mode !== WEBGL_CONSTANTS.TRIANGLES &&
884
+ primitive.mode !== WEBGL_CONSTANTS.TRIANGLE_STRIP &&
885
+ primitive.mode !== WEBGL_CONSTANTS.TRIANGLE_FAN &&
886
+ primitive.mode !== undefined ) {
887
+ return null;
888
+ }
889
+ }
890
+ const extensionDef = nodeDef.extensions[ this.name ];
891
+ const attributesDef = extensionDef.attributes;
892
+ const pending = [];
893
+ const attributes = {};
894
+ for ( const key in attributesDef ) {
895
+ pending.push( this.parser.getDependency( 'accessor', attributesDef[ key ] ).then( accessor => {
896
+ attributes[ key ] = accessor;
897
+ return attributes[ key ];
898
+ } ) );
899
+ }
900
+ if ( pending.length < 1 ) {
901
+ return null;
902
+ }
903
+ pending.push( this.parser.createNodeMesh( nodeIndex ) );
904
+ return Promise.all( pending ).then( results => {
905
+ const nodeObject = results.pop();
906
+ const meshes = nodeObject.isGroup ? nodeObject.children : [ nodeObject ];
907
+ const count = results[ 0 ].count;
908
+ const instancedMeshes = [];
909
+ for ( const mesh of meshes ) {
910
+ const m = new three.Matrix4();
911
+ const p = new three.Vector3();
912
+ const q = new three.Quaternion();
913
+ const s = new three.Vector3( 1, 1, 1 );
914
+ const instancedMesh = new three.InstancedMesh( mesh.geometry, mesh.material, count );
915
+ for ( let i = 0; i < count; i ++ ) {
916
+ if ( attributes.TRANSLATION ) {
917
+ p.fromBufferAttribute( attributes.TRANSLATION, i );
918
+ }
919
+ if ( attributes.ROTATION ) {
920
+ q.fromBufferAttribute( attributes.ROTATION, i );
921
+ }
922
+ if ( attributes.SCALE ) {
923
+ s.fromBufferAttribute( attributes.SCALE, i );
924
+ }
925
+ instancedMesh.setMatrixAt( i, m.compose( p, q, s ) );
926
+ }
927
+ for ( const attributeName in attributes ) {
928
+ if ( attributeName === '_COLOR_0' ) {
929
+ const attr = attributes[ attributeName ];
930
+ instancedMesh.instanceColor = new three.InstancedBufferAttribute( attr.array, attr.itemSize, attr.normalized );
931
+ } else if ( attributeName !== 'TRANSLATION' &&
932
+ attributeName !== 'ROTATION' &&
933
+ attributeName !== 'SCALE' ) {
934
+ mesh.geometry.setAttribute( attributeName, attributes[ attributeName ] );
935
+ }
936
+ }
937
+ three.Object3D.prototype.copy.call( instancedMesh, mesh );
938
+ this.parser.assignFinalMaterial( instancedMesh );
939
+ instancedMeshes.push( instancedMesh );
940
+ }
941
+ if ( nodeObject.isGroup ) {
942
+ nodeObject.clear();
943
+ nodeObject.add( ... instancedMeshes );
944
+ return nodeObject;
945
+ }
946
+ return instancedMeshes[ 0 ];
947
+ } );
948
+ }
949
+ }
950
+ const BINARY_EXTENSION_HEADER_MAGIC = 'glTF';
951
+ const BINARY_EXTENSION_HEADER_LENGTH = 12;
952
+ const BINARY_EXTENSION_CHUNK_TYPES = { JSON: 0x4E4F534A, BIN: 0x004E4942 };
953
+ class GLTFBinaryExtension {
954
+ constructor( data ) {
955
+ this.name = EXTENSIONS.KHR_BINARY_GLTF;
956
+ this.content = null;
957
+ this.body = null;
958
+ const headerView = new DataView( data, 0, BINARY_EXTENSION_HEADER_LENGTH );
959
+ const textDecoder = new TextDecoder();
960
+ this.header = {
961
+ magic: textDecoder.decode( new Uint8Array( data.slice( 0, 4 ) ) ),
962
+ version: headerView.getUint32( 4, true ),
963
+ length: headerView.getUint32( 8, true )
964
+ };
965
+ if ( this.header.magic !== BINARY_EXTENSION_HEADER_MAGIC ) {
966
+ throw new Error( 'THREE.GLTFLoader: Unsupported glTF-Binary header.' );
967
+ } else if ( this.header.version < 2.0 ) {
968
+ throw new Error( 'THREE.GLTFLoader: Legacy binary file detected.' );
969
+ }
970
+ const chunkContentsLength = this.header.length - BINARY_EXTENSION_HEADER_LENGTH;
971
+ const chunkView = new DataView( data, BINARY_EXTENSION_HEADER_LENGTH );
972
+ let chunkIndex = 0;
973
+ while ( chunkIndex < chunkContentsLength ) {
974
+ const chunkLength = chunkView.getUint32( chunkIndex, true );
975
+ chunkIndex += 4;
976
+ const chunkType = chunkView.getUint32( chunkIndex, true );
977
+ chunkIndex += 4;
978
+ if ( chunkType === BINARY_EXTENSION_CHUNK_TYPES.JSON ) {
979
+ const contentArray = new Uint8Array( data, BINARY_EXTENSION_HEADER_LENGTH + chunkIndex, chunkLength );
980
+ this.content = textDecoder.decode( contentArray );
981
+ } else if ( chunkType === BINARY_EXTENSION_CHUNK_TYPES.BIN ) {
982
+ const byteOffset = BINARY_EXTENSION_HEADER_LENGTH + chunkIndex;
983
+ this.body = data.slice( byteOffset, byteOffset + chunkLength );
984
+ }
985
+ chunkIndex += chunkLength;
986
+ }
987
+ if ( this.content === null ) {
988
+ throw new Error( 'THREE.GLTFLoader: JSON content not found.' );
989
+ }
990
+ }
991
+ }
992
+ class GLTFDracoMeshCompressionExtension {
993
+ constructor( json, dracoLoader ) {
994
+ if ( ! dracoLoader ) {
995
+ throw new Error( 'THREE.GLTFLoader: No DRACOLoader instance provided.' );
996
+ }
997
+ this.name = EXTENSIONS.KHR_DRACO_MESH_COMPRESSION;
998
+ this.json = json;
999
+ this.dracoLoader = dracoLoader;
1000
+ this.dracoLoader.preload();
1001
+ }
1002
+ decodePrimitive( primitive, parser ) {
1003
+ const json = this.json;
1004
+ const dracoLoader = this.dracoLoader;
1005
+ const bufferViewIndex = primitive.extensions[ this.name ].bufferView;
1006
+ const gltfAttributeMap = primitive.extensions[ this.name ].attributes;
1007
+ const threeAttributeMap = {};
1008
+ const attributeNormalizedMap = {};
1009
+ const attributeTypeMap = {};
1010
+ for ( const attributeName in gltfAttributeMap ) {
1011
+ const threeAttributeName = ATTRIBUTES[ attributeName ] || attributeName.toLowerCase();
1012
+ threeAttributeMap[ threeAttributeName ] = gltfAttributeMap[ attributeName ];
1013
+ }
1014
+ for ( const attributeName in primitive.attributes ) {
1015
+ const threeAttributeName = ATTRIBUTES[ attributeName ] || attributeName.toLowerCase();
1016
+ if ( gltfAttributeMap[ attributeName ] !== undefined ) {
1017
+ const accessorDef = json.accessors[ primitive.attributes[ attributeName ] ];
1018
+ const componentType = WEBGL_COMPONENT_TYPES[ accessorDef.componentType ];
1019
+ attributeTypeMap[ threeAttributeName ] = componentType.name;
1020
+ attributeNormalizedMap[ threeAttributeName ] = accessorDef.normalized === true;
1021
+ }
1022
+ }
1023
+ return parser.getDependency( 'bufferView', bufferViewIndex ).then( function ( bufferView ) {
1024
+ return new Promise( function ( resolve, reject ) {
1025
+ dracoLoader.decodeDracoFile( bufferView, function ( geometry ) {
1026
+ for ( const attributeName in geometry.attributes ) {
1027
+ const attribute = geometry.attributes[ attributeName ];
1028
+ const normalized = attributeNormalizedMap[ attributeName ];
1029
+ if ( normalized !== undefined ) attribute.normalized = normalized;
1030
+ }
1031
+ resolve( geometry );
1032
+ }, threeAttributeMap, attributeTypeMap, three.LinearSRGBColorSpace, reject );
1033
+ } );
1034
+ } );
1035
+ }
1036
+ }
1037
+ class GLTFTextureTransformExtension {
1038
+ constructor() {
1039
+ this.name = EXTENSIONS.KHR_TEXTURE_TRANSFORM;
1040
+ }
1041
+ extendTexture( texture, transform ) {
1042
+ if ( ( transform.texCoord === undefined || transform.texCoord === texture.channel )
1043
+ && transform.offset === undefined
1044
+ && transform.rotation === undefined
1045
+ && transform.scale === undefined ) {
1046
+ return texture;
1047
+ }
1048
+ texture = texture.clone();
1049
+ if ( transform.texCoord !== undefined ) {
1050
+ texture.channel = transform.texCoord;
1051
+ }
1052
+ if ( transform.offset !== undefined ) {
1053
+ texture.offset.fromArray( transform.offset );
1054
+ }
1055
+ if ( transform.rotation !== undefined ) {
1056
+ texture.rotation = transform.rotation;
1057
+ }
1058
+ if ( transform.scale !== undefined ) {
1059
+ texture.repeat.fromArray( transform.scale );
1060
+ }
1061
+ texture.needsUpdate = true;
1062
+ return texture;
1063
+ }
1064
+ }
1065
+ class GLTFMeshQuantizationExtension {
1066
+ constructor() {
1067
+ this.name = EXTENSIONS.KHR_MESH_QUANTIZATION;
1068
+ }
1069
+ }
1070
+ class GLTFCubicSplineInterpolant extends three.Interpolant {
1071
+ constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
1072
+ super( parameterPositions, sampleValues, sampleSize, resultBuffer );
1073
+ }
1074
+ copySampleValue_( index ) {
1075
+ const result = this.resultBuffer,
1076
+ values = this.sampleValues,
1077
+ valueSize = this.valueSize,
1078
+ offset = index * valueSize * 3 + valueSize;
1079
+ for ( let i = 0; i !== valueSize; i ++ ) {
1080
+ result[ i ] = values[ offset + i ];
1081
+ }
1082
+ return result;
1083
+ }
1084
+ interpolate_( i1, t0, t, t1 ) {
1085
+ const result = this.resultBuffer;
1086
+ const values = this.sampleValues;
1087
+ const stride = this.valueSize;
1088
+ const stride2 = stride * 2;
1089
+ const stride3 = stride * 3;
1090
+ const td = t1 - t0;
1091
+ const p = ( t - t0 ) / td;
1092
+ const pp = p * p;
1093
+ const ppp = pp * p;
1094
+ const offset1 = i1 * stride3;
1095
+ const offset0 = offset1 - stride3;
1096
+ const s2 = -2 * ppp + 3 * pp;
1097
+ const s3 = ppp - pp;
1098
+ const s0 = 1 - s2;
1099
+ const s1 = s3 - pp + p;
1100
+ for ( let i = 0; i !== stride; i ++ ) {
1101
+ const p0 = values[ offset0 + i + stride ];
1102
+ const m0 = values[ offset0 + i + stride2 ] * td;
1103
+ const p1 = values[ offset1 + i + stride ];
1104
+ const m1 = values[ offset1 + i ] * td;
1105
+ result[ i ] = s0 * p0 + s1 * m0 + s2 * p1 + s3 * m1;
1106
+ }
1107
+ return result;
1108
+ }
1109
+ }
1110
+ const _quaternion = new three.Quaternion();
1111
+ class GLTFCubicSplineQuaternionInterpolant extends GLTFCubicSplineInterpolant {
1112
+ interpolate_( i1, t0, t, t1 ) {
1113
+ const result = super.interpolate_( i1, t0, t, t1 );
1114
+ _quaternion.fromArray( result ).normalize().toArray( result );
1115
+ return result;
1116
+ }
1117
+ }
1118
+ const WEBGL_CONSTANTS = {
1119
+ POINTS: 0,
1120
+ LINES: 1,
1121
+ LINE_LOOP: 2,
1122
+ LINE_STRIP: 3,
1123
+ TRIANGLES: 4,
1124
+ TRIANGLE_STRIP: 5,
1125
+ TRIANGLE_FAN: 6};
1126
+ const WEBGL_COMPONENT_TYPES = {
1127
+ 5120: Int8Array,
1128
+ 5121: Uint8Array,
1129
+ 5122: Int16Array,
1130
+ 5123: Uint16Array,
1131
+ 5125: Uint32Array,
1132
+ 5126: Float32Array
1133
+ };
1134
+ const WEBGL_FILTERS = {
1135
+ 9728: three.NearestFilter,
1136
+ 9729: three.LinearFilter,
1137
+ 9984: three.NearestMipmapNearestFilter,
1138
+ 9985: three.LinearMipmapNearestFilter,
1139
+ 9986: three.NearestMipmapLinearFilter,
1140
+ 9987: three.LinearMipmapLinearFilter
1141
+ };
1142
+ const WEBGL_WRAPPINGS = {
1143
+ 33071: three.ClampToEdgeWrapping,
1144
+ 33648: three.MirroredRepeatWrapping,
1145
+ 10497: three.RepeatWrapping
1146
+ };
1147
+ const WEBGL_TYPE_SIZES = {
1148
+ 'SCALAR': 1,
1149
+ 'VEC2': 2,
1150
+ 'VEC3': 3,
1151
+ 'VEC4': 4,
1152
+ 'MAT2': 4,
1153
+ 'MAT3': 9,
1154
+ 'MAT4': 16
1155
+ };
1156
+ const ATTRIBUTES = {
1157
+ POSITION: 'position',
1158
+ NORMAL: 'normal',
1159
+ TANGENT: 'tangent',
1160
+ TEXCOORD_0: 'uv',
1161
+ TEXCOORD_1: 'uv1',
1162
+ TEXCOORD_2: 'uv2',
1163
+ TEXCOORD_3: 'uv3',
1164
+ COLOR_0: 'color',
1165
+ WEIGHTS_0: 'skinWeight',
1166
+ JOINTS_0: 'skinIndex',
1167
+ };
1168
+ const PATH_PROPERTIES = {
1169
+ scale: 'scale',
1170
+ translation: 'position',
1171
+ rotation: 'quaternion',
1172
+ weights: 'morphTargetInfluences'
1173
+ };
1174
+ const INTERPOLATION = {
1175
+ CUBICSPLINE: undefined,
1176
+ LINEAR: three.InterpolateLinear,
1177
+ STEP: three.InterpolateDiscrete
1178
+ };
1179
+ const ALPHA_MODES = {
1180
+ OPAQUE: 'OPAQUE',
1181
+ MASK: 'MASK',
1182
+ BLEND: 'BLEND'
1183
+ };
1184
+ function createDefaultMaterial( cache ) {
1185
+ if ( cache[ 'DefaultMaterial' ] === undefined ) {
1186
+ cache[ 'DefaultMaterial' ] = new three.MeshStandardMaterial( {
1187
+ color: 0xFFFFFF,
1188
+ emissive: 0x000000,
1189
+ metalness: 1,
1190
+ roughness: 1,
1191
+ transparent: false,
1192
+ depthTest: true,
1193
+ side: three.FrontSide
1194
+ } );
1195
+ }
1196
+ return cache[ 'DefaultMaterial' ];
1197
+ }
1198
+ function addUnknownExtensionsToUserData( knownExtensions, object, objectDef ) {
1199
+ for ( const name in objectDef.extensions ) {
1200
+ if ( knownExtensions[ name ] === undefined ) {
1201
+ object.userData.gltfExtensions = object.userData.gltfExtensions || {};
1202
+ object.userData.gltfExtensions[ name ] = objectDef.extensions[ name ];
1203
+ }
1204
+ }
1205
+ }
1206
+ function assignExtrasToUserData( object, gltfDef ) {
1207
+ if ( gltfDef.extras !== undefined ) {
1208
+ if ( typeof gltfDef.extras === 'object' ) {
1209
+ Object.assign( object.userData, gltfDef.extras );
1210
+ } else {
1211
+ console.warn( 'THREE.GLTFLoader: Ignoring primitive type .extras, ' + gltfDef.extras );
1212
+ }
1213
+ }
1214
+ }
1215
+ function addMorphTargets( geometry, targets, parser ) {
1216
+ let hasMorphPosition = false;
1217
+ let hasMorphNormal = false;
1218
+ let hasMorphColor = false;
1219
+ for ( let i = 0, il = targets.length; i < il; i ++ ) {
1220
+ const target = targets[ i ];
1221
+ if ( target.POSITION !== undefined ) hasMorphPosition = true;
1222
+ if ( target.NORMAL !== undefined ) hasMorphNormal = true;
1223
+ if ( target.COLOR_0 !== undefined ) hasMorphColor = true;
1224
+ if ( hasMorphPosition && hasMorphNormal && hasMorphColor ) break;
1225
+ }
1226
+ if ( ! hasMorphPosition && ! hasMorphNormal && ! hasMorphColor ) return Promise.resolve( geometry );
1227
+ const pendingPositionAccessors = [];
1228
+ const pendingNormalAccessors = [];
1229
+ const pendingColorAccessors = [];
1230
+ for ( let i = 0, il = targets.length; i < il; i ++ ) {
1231
+ const target = targets[ i ];
1232
+ if ( hasMorphPosition ) {
1233
+ const pendingAccessor = target.POSITION !== undefined
1234
+ ? parser.getDependency( 'accessor', target.POSITION )
1235
+ : geometry.attributes.position;
1236
+ pendingPositionAccessors.push( pendingAccessor );
1237
+ }
1238
+ if ( hasMorphNormal ) {
1239
+ const pendingAccessor = target.NORMAL !== undefined
1240
+ ? parser.getDependency( 'accessor', target.NORMAL )
1241
+ : geometry.attributes.normal;
1242
+ pendingNormalAccessors.push( pendingAccessor );
1243
+ }
1244
+ if ( hasMorphColor ) {
1245
+ const pendingAccessor = target.COLOR_0 !== undefined
1246
+ ? parser.getDependency( 'accessor', target.COLOR_0 )
1247
+ : geometry.attributes.color;
1248
+ pendingColorAccessors.push( pendingAccessor );
1249
+ }
1250
+ }
1251
+ return Promise.all( [
1252
+ Promise.all( pendingPositionAccessors ),
1253
+ Promise.all( pendingNormalAccessors ),
1254
+ Promise.all( pendingColorAccessors )
1255
+ ] ).then( function ( accessors ) {
1256
+ const morphPositions = accessors[ 0 ];
1257
+ const morphNormals = accessors[ 1 ];
1258
+ const morphColors = accessors[ 2 ];
1259
+ if ( hasMorphPosition ) geometry.morphAttributes.position = morphPositions;
1260
+ if ( hasMorphNormal ) geometry.morphAttributes.normal = morphNormals;
1261
+ if ( hasMorphColor ) geometry.morphAttributes.color = morphColors;
1262
+ geometry.morphTargetsRelative = true;
1263
+ return geometry;
1264
+ } );
1265
+ }
1266
+ function updateMorphTargets( mesh, meshDef ) {
1267
+ mesh.updateMorphTargets();
1268
+ if ( meshDef.weights !== undefined ) {
1269
+ for ( let i = 0, il = meshDef.weights.length; i < il; i ++ ) {
1270
+ mesh.morphTargetInfluences[ i ] = meshDef.weights[ i ];
1271
+ }
1272
+ }
1273
+ if ( meshDef.extras && Array.isArray( meshDef.extras.targetNames ) ) {
1274
+ const targetNames = meshDef.extras.targetNames;
1275
+ if ( mesh.morphTargetInfluences.length === targetNames.length ) {
1276
+ mesh.morphTargetDictionary = {};
1277
+ for ( let i = 0, il = targetNames.length; i < il; i ++ ) {
1278
+ mesh.morphTargetDictionary[ targetNames[ i ] ] = i;
1279
+ }
1280
+ } else {
1281
+ console.warn( 'THREE.GLTFLoader: Invalid extras.targetNames length. Ignoring names.' );
1282
+ }
1283
+ }
1284
+ }
1285
+ function createPrimitiveKey( primitiveDef ) {
1286
+ let geometryKey;
1287
+ const dracoExtension = primitiveDef.extensions && primitiveDef.extensions[ EXTENSIONS.KHR_DRACO_MESH_COMPRESSION ];
1288
+ if ( dracoExtension ) {
1289
+ geometryKey = 'draco:' + dracoExtension.bufferView
1290
+ + ':' + dracoExtension.indices
1291
+ + ':' + createAttributesKey( dracoExtension.attributes );
1292
+ } else {
1293
+ geometryKey = primitiveDef.indices + ':' + createAttributesKey( primitiveDef.attributes ) + ':' + primitiveDef.mode;
1294
+ }
1295
+ if ( primitiveDef.targets !== undefined ) {
1296
+ for ( let i = 0, il = primitiveDef.targets.length; i < il; i ++ ) {
1297
+ geometryKey += ':' + createAttributesKey( primitiveDef.targets[ i ] );
1298
+ }
1299
+ }
1300
+ return geometryKey;
1301
+ }
1302
+ function createAttributesKey( attributes ) {
1303
+ let attributesKey = '';
1304
+ const keys = Object.keys( attributes ).sort();
1305
+ for ( let i = 0, il = keys.length; i < il; i ++ ) {
1306
+ attributesKey += keys[ i ] + ':' + attributes[ keys[ i ] ] + ';';
1307
+ }
1308
+ return attributesKey;
1309
+ }
1310
+ function getNormalizedComponentScale( constructor ) {
1311
+ switch ( constructor ) {
1312
+ case Int8Array:
1313
+ return 1 / 127;
1314
+ case Uint8Array:
1315
+ return 1 / 255;
1316
+ case Int16Array:
1317
+ return 1 / 32767;
1318
+ case Uint16Array:
1319
+ return 1 / 65535;
1320
+ default:
1321
+ throw new Error( 'THREE.GLTFLoader: Unsupported normalized accessor component type.' );
1322
+ }
1323
+ }
1324
+ function getImageURIMimeType( uri ) {
1325
+ if ( uri.search( /\.jpe?g($|\?)/i ) > 0 || uri.search( /^data\:image\/jpeg/ ) === 0 ) return 'image/jpeg';
1326
+ if ( uri.search( /\.webp($|\?)/i ) > 0 || uri.search( /^data\:image\/webp/ ) === 0 ) return 'image/webp';
1327
+ if ( uri.search( /\.ktx2($|\?)/i ) > 0 || uri.search( /^data\:image\/ktx2/ ) === 0 ) return 'image/ktx2';
1328
+ return 'image/png';
1329
+ }
1330
+ const _identityMatrix = new three.Matrix4();
1331
+ class GLTFParser {
1332
+ constructor( json = {}, options = {} ) {
1333
+ this.json = json;
1334
+ this.extensions = {};
1335
+ this.plugins = {};
1336
+ this.options = options;
1337
+ this.cache = new GLTFRegistry();
1338
+ this.associations = new Map();
1339
+ this.primitiveCache = {};
1340
+ this.nodeCache = {};
1341
+ this.meshCache = { refs: {}, uses: {} };
1342
+ this.cameraCache = { refs: {}, uses: {} };
1343
+ this.lightCache = { refs: {}, uses: {} };
1344
+ this.sourceCache = {};
1345
+ this.textureCache = {};
1346
+ this.nodeNamesUsed = {};
1347
+ let isSafari = false;
1348
+ let safariVersion = -1;
1349
+ let isFirefox = false;
1350
+ let firefoxVersion = -1;
1351
+ if ( typeof navigator !== 'undefined' ) {
1352
+ const userAgent = navigator.userAgent;
1353
+ isSafari = /^((?!chrome|android).)*safari/i.test( userAgent ) === true;
1354
+ const safariMatch = userAgent.match( /Version\/(\d+)/ );
1355
+ safariVersion = isSafari && safariMatch ? parseInt( safariMatch[ 1 ], 10 ) : -1;
1356
+ isFirefox = userAgent.indexOf( 'Firefox' ) > -1;
1357
+ firefoxVersion = isFirefox ? userAgent.match( /Firefox\/([0-9]+)\./ )[ 1 ] : -1;
1358
+ }
1359
+ if ( typeof createImageBitmap === 'undefined' || ( isSafari && safariVersion < 17 ) || ( isFirefox && firefoxVersion < 98 ) ) {
1360
+ this.textureLoader = new three.TextureLoader( this.options.manager );
1361
+ } else {
1362
+ this.textureLoader = new three.ImageBitmapLoader( this.options.manager );
1363
+ }
1364
+ this.textureLoader.setCrossOrigin( this.options.crossOrigin );
1365
+ this.textureLoader.setRequestHeader( this.options.requestHeader );
1366
+ this.fileLoader = new three.FileLoader( this.options.manager );
1367
+ this.fileLoader.setResponseType( 'arraybuffer' );
1368
+ if ( this.options.crossOrigin === 'use-credentials' ) {
1369
+ this.fileLoader.setWithCredentials( true );
1370
+ }
1371
+ }
1372
+ setExtensions( extensions ) {
1373
+ this.extensions = extensions;
1374
+ }
1375
+ setPlugins( plugins ) {
1376
+ this.plugins = plugins;
1377
+ }
1378
+ parse( onLoad, onError ) {
1379
+ const parser = this;
1380
+ const json = this.json;
1381
+ const extensions = this.extensions;
1382
+ this.cache.removeAll();
1383
+ this.nodeCache = {};
1384
+ this._invokeAll( function ( ext ) {
1385
+ return ext._markDefs && ext._markDefs();
1386
+ } );
1387
+ Promise.all( this._invokeAll( function ( ext ) {
1388
+ return ext.beforeRoot && ext.beforeRoot();
1389
+ } ) ).then( function () {
1390
+ return Promise.all( [
1391
+ parser.getDependencies( 'scene' ),
1392
+ parser.getDependencies( 'animation' ),
1393
+ parser.getDependencies( 'camera' ),
1394
+ ] );
1395
+ } ).then( function ( dependencies ) {
1396
+ const result = {
1397
+ scene: dependencies[ 0 ][ json.scene || 0 ],
1398
+ scenes: dependencies[ 0 ],
1399
+ animations: dependencies[ 1 ],
1400
+ cameras: dependencies[ 2 ],
1401
+ asset: json.asset,
1402
+ parser: parser,
1403
+ userData: {}
1404
+ };
1405
+ addUnknownExtensionsToUserData( extensions, result, json );
1406
+ assignExtrasToUserData( result, json );
1407
+ return Promise.all( parser._invokeAll( function ( ext ) {
1408
+ return ext.afterRoot && ext.afterRoot( result );
1409
+ } ) ).then( function () {
1410
+ for ( const scene of result.scenes ) {
1411
+ scene.updateMatrixWorld();
1412
+ }
1413
+ onLoad( result );
1414
+ } );
1415
+ } ).catch( onError );
1416
+ }
1417
+ _markDefs() {
1418
+ const nodeDefs = this.json.nodes || [];
1419
+ const skinDefs = this.json.skins || [];
1420
+ const meshDefs = this.json.meshes || [];
1421
+ for ( let skinIndex = 0, skinLength = skinDefs.length; skinIndex < skinLength; skinIndex ++ ) {
1422
+ const joints = skinDefs[ skinIndex ].joints;
1423
+ for ( let i = 0, il = joints.length; i < il; i ++ ) {
1424
+ nodeDefs[ joints[ i ] ].isBone = true;
1425
+ }
1426
+ }
1427
+ for ( let nodeIndex = 0, nodeLength = nodeDefs.length; nodeIndex < nodeLength; nodeIndex ++ ) {
1428
+ const nodeDef = nodeDefs[ nodeIndex ];
1429
+ if ( nodeDef.mesh !== undefined ) {
1430
+ this._addNodeRef( this.meshCache, nodeDef.mesh );
1431
+ if ( nodeDef.skin !== undefined ) {
1432
+ meshDefs[ nodeDef.mesh ].isSkinnedMesh = true;
1433
+ }
1434
+ }
1435
+ if ( nodeDef.camera !== undefined ) {
1436
+ this._addNodeRef( this.cameraCache, nodeDef.camera );
1437
+ }
1438
+ }
1439
+ }
1440
+ _addNodeRef( cache, index ) {
1441
+ if ( index === undefined ) return;
1442
+ if ( cache.refs[ index ] === undefined ) {
1443
+ cache.refs[ index ] = cache.uses[ index ] = 0;
1444
+ }
1445
+ cache.refs[ index ] ++;
1446
+ }
1447
+ _getNodeRef( cache, index, object ) {
1448
+ if ( cache.refs[ index ] <= 1 ) return object;
1449
+ const ref = object.clone();
1450
+ const updateMappings = ( original, clone ) => {
1451
+ const mappings = this.associations.get( original );
1452
+ if ( mappings != null ) {
1453
+ this.associations.set( clone, mappings );
1454
+ }
1455
+ for ( const [ i, child ] of original.children.entries() ) {
1456
+ updateMappings( child, clone.children[ i ] );
1457
+ }
1458
+ };
1459
+ updateMappings( object, ref );
1460
+ ref.name += '_instance_' + ( cache.uses[ index ] ++ );
1461
+ return ref;
1462
+ }
1463
+ _invokeOne( func ) {
1464
+ const extensions = Object.values( this.plugins );
1465
+ extensions.push( this );
1466
+ for ( let i = 0; i < extensions.length; i ++ ) {
1467
+ const result = func( extensions[ i ] );
1468
+ if ( result ) return result;
1469
+ }
1470
+ return null;
1471
+ }
1472
+ _invokeAll( func ) {
1473
+ const extensions = Object.values( this.plugins );
1474
+ extensions.unshift( this );
1475
+ const pending = [];
1476
+ for ( let i = 0; i < extensions.length; i ++ ) {
1477
+ const result = func( extensions[ i ] );
1478
+ if ( result ) pending.push( result );
1479
+ }
1480
+ return pending;
1481
+ }
1482
+ getDependency( type, index ) {
1483
+ const cacheKey = type + ':' + index;
1484
+ let dependency = this.cache.get( cacheKey );
1485
+ if ( ! dependency ) {
1486
+ switch ( type ) {
1487
+ case 'scene':
1488
+ dependency = this.loadScene( index );
1489
+ break;
1490
+ case 'node':
1491
+ dependency = this._invokeOne( function ( ext ) {
1492
+ return ext.loadNode && ext.loadNode( index );
1493
+ } );
1494
+ break;
1495
+ case 'mesh':
1496
+ dependency = this._invokeOne( function ( ext ) {
1497
+ return ext.loadMesh && ext.loadMesh( index );
1498
+ } );
1499
+ break;
1500
+ case 'accessor':
1501
+ dependency = this.loadAccessor( index );
1502
+ break;
1503
+ case 'bufferView':
1504
+ dependency = this._invokeOne( function ( ext ) {
1505
+ return ext.loadBufferView && ext.loadBufferView( index );
1506
+ } );
1507
+ break;
1508
+ case 'buffer':
1509
+ dependency = this.loadBuffer( index );
1510
+ break;
1511
+ case 'material':
1512
+ dependency = this._invokeOne( function ( ext ) {
1513
+ return ext.loadMaterial && ext.loadMaterial( index );
1514
+ } );
1515
+ break;
1516
+ case 'texture':
1517
+ dependency = this._invokeOne( function ( ext ) {
1518
+ return ext.loadTexture && ext.loadTexture( index );
1519
+ } );
1520
+ break;
1521
+ case 'skin':
1522
+ dependency = this.loadSkin( index );
1523
+ break;
1524
+ case 'animation':
1525
+ dependency = this._invokeOne( function ( ext ) {
1526
+ return ext.loadAnimation && ext.loadAnimation( index );
1527
+ } );
1528
+ break;
1529
+ case 'camera':
1530
+ dependency = this.loadCamera( index );
1531
+ break;
1532
+ default:
1533
+ dependency = this._invokeOne( function ( ext ) {
1534
+ return ext != this && ext.getDependency && ext.getDependency( type, index );
1535
+ } );
1536
+ if ( ! dependency ) {
1537
+ throw new Error( 'Unknown type: ' + type );
1538
+ }
1539
+ break;
1540
+ }
1541
+ this.cache.add( cacheKey, dependency );
1542
+ }
1543
+ return dependency;
1544
+ }
1545
+ getDependencies( type ) {
1546
+ let dependencies = this.cache.get( type );
1547
+ if ( ! dependencies ) {
1548
+ const parser = this;
1549
+ const defs = this.json[ type + ( type === 'mesh' ? 'es' : 's' ) ] || [];
1550
+ dependencies = Promise.all( defs.map( function ( def, index ) {
1551
+ return parser.getDependency( type, index );
1552
+ } ) );
1553
+ this.cache.add( type, dependencies );
1554
+ }
1555
+ return dependencies;
1556
+ }
1557
+ loadBuffer( bufferIndex ) {
1558
+ const bufferDef = this.json.buffers[ bufferIndex ];
1559
+ const loader = this.fileLoader;
1560
+ if ( bufferDef.type && bufferDef.type !== 'arraybuffer' ) {
1561
+ throw new Error( 'THREE.GLTFLoader: ' + bufferDef.type + ' buffer type is not supported.' );
1562
+ }
1563
+ if ( bufferDef.uri === undefined && bufferIndex === 0 ) {
1564
+ return Promise.resolve( this.extensions[ EXTENSIONS.KHR_BINARY_GLTF ].body );
1565
+ }
1566
+ const options = this.options;
1567
+ return new Promise( function ( resolve, reject ) {
1568
+ loader.load( three.LoaderUtils.resolveURL( bufferDef.uri, options.path ), resolve, undefined, function () {
1569
+ reject( new Error( 'THREE.GLTFLoader: Failed to load buffer "' + bufferDef.uri + '".' ) );
1570
+ } );
1571
+ } );
1572
+ }
1573
+ loadBufferView( bufferViewIndex ) {
1574
+ const bufferViewDef = this.json.bufferViews[ bufferViewIndex ];
1575
+ return this.getDependency( 'buffer', bufferViewDef.buffer ).then( function ( buffer ) {
1576
+ const byteLength = bufferViewDef.byteLength || 0;
1577
+ const byteOffset = bufferViewDef.byteOffset || 0;
1578
+ return buffer.slice( byteOffset, byteOffset + byteLength );
1579
+ } );
1580
+ }
1581
+ loadAccessor( accessorIndex ) {
1582
+ const parser = this;
1583
+ const json = this.json;
1584
+ const accessorDef = this.json.accessors[ accessorIndex ];
1585
+ if ( accessorDef.bufferView === undefined && accessorDef.sparse === undefined ) {
1586
+ const itemSize = WEBGL_TYPE_SIZES[ accessorDef.type ];
1587
+ const TypedArray = WEBGL_COMPONENT_TYPES[ accessorDef.componentType ];
1588
+ const normalized = accessorDef.normalized === true;
1589
+ const array = new TypedArray( accessorDef.count * itemSize );
1590
+ return Promise.resolve( new three.BufferAttribute( array, itemSize, normalized ) );
1591
+ }
1592
+ const pendingBufferViews = [];
1593
+ if ( accessorDef.bufferView !== undefined ) {
1594
+ pendingBufferViews.push( this.getDependency( 'bufferView', accessorDef.bufferView ) );
1595
+ } else {
1596
+ pendingBufferViews.push( null );
1597
+ }
1598
+ if ( accessorDef.sparse !== undefined ) {
1599
+ pendingBufferViews.push( this.getDependency( 'bufferView', accessorDef.sparse.indices.bufferView ) );
1600
+ pendingBufferViews.push( this.getDependency( 'bufferView', accessorDef.sparse.values.bufferView ) );
1601
+ }
1602
+ return Promise.all( pendingBufferViews ).then( function ( bufferViews ) {
1603
+ const bufferView = bufferViews[ 0 ];
1604
+ const itemSize = WEBGL_TYPE_SIZES[ accessorDef.type ];
1605
+ const TypedArray = WEBGL_COMPONENT_TYPES[ accessorDef.componentType ];
1606
+ const elementBytes = TypedArray.BYTES_PER_ELEMENT;
1607
+ const itemBytes = elementBytes * itemSize;
1608
+ const byteOffset = accessorDef.byteOffset || 0;
1609
+ const byteStride = accessorDef.bufferView !== undefined ? json.bufferViews[ accessorDef.bufferView ].byteStride : undefined;
1610
+ const normalized = accessorDef.normalized === true;
1611
+ let array, bufferAttribute;
1612
+ if ( byteStride && byteStride !== itemBytes ) {
1613
+ const ibSlice = Math.floor( byteOffset / byteStride );
1614
+ const ibCacheKey = 'InterleavedBuffer:' + accessorDef.bufferView + ':' + accessorDef.componentType + ':' + ibSlice + ':' + accessorDef.count;
1615
+ let ib = parser.cache.get( ibCacheKey );
1616
+ if ( ! ib ) {
1617
+ array = new TypedArray( bufferView, ibSlice * byteStride, accessorDef.count * byteStride / elementBytes );
1618
+ ib = new three.InterleavedBuffer( array, byteStride / elementBytes );
1619
+ parser.cache.add( ibCacheKey, ib );
1620
+ }
1621
+ bufferAttribute = new three.InterleavedBufferAttribute( ib, itemSize, ( byteOffset % byteStride ) / elementBytes, normalized );
1622
+ } else {
1623
+ if ( bufferView === null ) {
1624
+ array = new TypedArray( accessorDef.count * itemSize );
1625
+ } else {
1626
+ array = new TypedArray( bufferView, byteOffset, accessorDef.count * itemSize );
1627
+ }
1628
+ bufferAttribute = new three.BufferAttribute( array, itemSize, normalized );
1629
+ }
1630
+ if ( accessorDef.sparse !== undefined ) {
1631
+ const itemSizeIndices = WEBGL_TYPE_SIZES.SCALAR;
1632
+ const TypedArrayIndices = WEBGL_COMPONENT_TYPES[ accessorDef.sparse.indices.componentType ];
1633
+ const byteOffsetIndices = accessorDef.sparse.indices.byteOffset || 0;
1634
+ const byteOffsetValues = accessorDef.sparse.values.byteOffset || 0;
1635
+ const sparseIndices = new TypedArrayIndices( bufferViews[ 1 ], byteOffsetIndices, accessorDef.sparse.count * itemSizeIndices );
1636
+ const sparseValues = new TypedArray( bufferViews[ 2 ], byteOffsetValues, accessorDef.sparse.count * itemSize );
1637
+ if ( bufferView !== null ) {
1638
+ bufferAttribute = new three.BufferAttribute( bufferAttribute.array.slice(), bufferAttribute.itemSize, bufferAttribute.normalized );
1639
+ }
1640
+ bufferAttribute.normalized = false;
1641
+ for ( let i = 0, il = sparseIndices.length; i < il; i ++ ) {
1642
+ const index = sparseIndices[ i ];
1643
+ bufferAttribute.setX( index, sparseValues[ i * itemSize ] );
1644
+ if ( itemSize >= 2 ) bufferAttribute.setY( index, sparseValues[ i * itemSize + 1 ] );
1645
+ if ( itemSize >= 3 ) bufferAttribute.setZ( index, sparseValues[ i * itemSize + 2 ] );
1646
+ if ( itemSize >= 4 ) bufferAttribute.setW( index, sparseValues[ i * itemSize + 3 ] );
1647
+ if ( itemSize >= 5 ) throw new Error( 'THREE.GLTFLoader: Unsupported itemSize in sparse BufferAttribute.' );
1648
+ }
1649
+ bufferAttribute.normalized = normalized;
1650
+ }
1651
+ return bufferAttribute;
1652
+ } );
1653
+ }
1654
+ loadTexture( textureIndex ) {
1655
+ const json = this.json;
1656
+ const options = this.options;
1657
+ const textureDef = json.textures[ textureIndex ];
1658
+ const sourceIndex = textureDef.source;
1659
+ const sourceDef = json.images[ sourceIndex ];
1660
+ let loader = this.textureLoader;
1661
+ if ( sourceDef.uri ) {
1662
+ const handler = options.manager.getHandler( sourceDef.uri );
1663
+ if ( handler !== null ) loader = handler;
1664
+ }
1665
+ return this.loadTextureImage( textureIndex, sourceIndex, loader );
1666
+ }
1667
+ loadTextureImage( textureIndex, sourceIndex, loader ) {
1668
+ const parser = this;
1669
+ const json = this.json;
1670
+ const textureDef = json.textures[ textureIndex ];
1671
+ const sourceDef = json.images[ sourceIndex ];
1672
+ const cacheKey = ( sourceDef.uri || sourceDef.bufferView ) + ':' + textureDef.sampler;
1673
+ if ( this.textureCache[ cacheKey ] ) {
1674
+ return this.textureCache[ cacheKey ];
1675
+ }
1676
+ const promise = this.loadImageSource( sourceIndex, loader ).then( function ( texture ) {
1677
+ texture.flipY = false;
1678
+ texture.name = textureDef.name || sourceDef.name || '';
1679
+ if ( texture.name === '' && typeof sourceDef.uri === 'string' && sourceDef.uri.startsWith( 'data:image/' ) === false ) {
1680
+ texture.name = sourceDef.uri;
1681
+ }
1682
+ const samplers = json.samplers || {};
1683
+ const sampler = samplers[ textureDef.sampler ] || {};
1684
+ texture.magFilter = WEBGL_FILTERS[ sampler.magFilter ] || three.LinearFilter;
1685
+ texture.minFilter = WEBGL_FILTERS[ sampler.minFilter ] || three.LinearMipmapLinearFilter;
1686
+ texture.wrapS = WEBGL_WRAPPINGS[ sampler.wrapS ] || three.RepeatWrapping;
1687
+ texture.wrapT = WEBGL_WRAPPINGS[ sampler.wrapT ] || three.RepeatWrapping;
1688
+ texture.generateMipmaps = ! texture.isCompressedTexture && texture.minFilter !== three.NearestFilter && texture.minFilter !== three.LinearFilter;
1689
+ parser.associations.set( texture, { textures: textureIndex } );
1690
+ return texture;
1691
+ } ).catch( function () {
1692
+ return null;
1693
+ } );
1694
+ this.textureCache[ cacheKey ] = promise;
1695
+ return promise;
1696
+ }
1697
+ loadImageSource( sourceIndex, loader ) {
1698
+ const parser = this;
1699
+ const json = this.json;
1700
+ const options = this.options;
1701
+ if ( this.sourceCache[ sourceIndex ] !== undefined ) {
1702
+ return this.sourceCache[ sourceIndex ].then( ( texture ) => texture.clone() );
1703
+ }
1704
+ const sourceDef = json.images[ sourceIndex ];
1705
+ const URL = self.URL || self.webkitURL;
1706
+ let sourceURI = sourceDef.uri || '';
1707
+ let isObjectURL = false;
1708
+ if ( sourceDef.bufferView !== undefined ) {
1709
+ sourceURI = parser.getDependency( 'bufferView', sourceDef.bufferView ).then( function ( bufferView ) {
1710
+ isObjectURL = true;
1711
+ const blob = new Blob( [ bufferView ], { type: sourceDef.mimeType } );
1712
+ sourceURI = URL.createObjectURL( blob );
1713
+ return sourceURI;
1714
+ } );
1715
+ } else if ( sourceDef.uri === undefined ) {
1716
+ throw new Error( 'THREE.GLTFLoader: Image ' + sourceIndex + ' is missing URI and bufferView' );
1717
+ }
1718
+ const promise = Promise.resolve( sourceURI ).then( function ( sourceURI ) {
1719
+ return new Promise( function ( resolve, reject ) {
1720
+ let onLoad = resolve;
1721
+ if ( loader.isImageBitmapLoader === true ) {
1722
+ onLoad = function ( imageBitmap ) {
1723
+ const texture = new three.Texture( imageBitmap );
1724
+ texture.needsUpdate = true;
1725
+ resolve( texture );
1726
+ };
1727
+ }
1728
+ loader.load( three.LoaderUtils.resolveURL( sourceURI, options.path ), onLoad, undefined, reject );
1729
+ } );
1730
+ } ).then( function ( texture ) {
1731
+ if ( isObjectURL === true ) {
1732
+ URL.revokeObjectURL( sourceURI );
1733
+ }
1734
+ assignExtrasToUserData( texture, sourceDef );
1735
+ texture.userData.mimeType = sourceDef.mimeType || getImageURIMimeType( sourceDef.uri );
1736
+ return texture;
1737
+ } ).catch( function ( error ) {
1738
+ console.error( 'THREE.GLTFLoader: Couldn\'t load texture', sourceURI );
1739
+ throw error;
1740
+ } );
1741
+ this.sourceCache[ sourceIndex ] = promise;
1742
+ return promise;
1743
+ }
1744
+ assignTexture( materialParams, mapName, mapDef, colorSpace ) {
1745
+ const parser = this;
1746
+ return this.getDependency( 'texture', mapDef.index ).then( function ( texture ) {
1747
+ if ( ! texture ) return null;
1748
+ if ( mapDef.texCoord !== undefined && mapDef.texCoord > 0 ) {
1749
+ texture = texture.clone();
1750
+ texture.channel = mapDef.texCoord;
1751
+ }
1752
+ if ( parser.extensions[ EXTENSIONS.KHR_TEXTURE_TRANSFORM ] ) {
1753
+ const transform = mapDef.extensions !== undefined ? mapDef.extensions[ EXTENSIONS.KHR_TEXTURE_TRANSFORM ] : undefined;
1754
+ if ( transform ) {
1755
+ const gltfReference = parser.associations.get( texture );
1756
+ texture = parser.extensions[ EXTENSIONS.KHR_TEXTURE_TRANSFORM ].extendTexture( texture, transform );
1757
+ parser.associations.set( texture, gltfReference );
1758
+ }
1759
+ }
1760
+ if ( colorSpace !== undefined ) {
1761
+ texture.colorSpace = colorSpace;
1762
+ }
1763
+ materialParams[ mapName ] = texture;
1764
+ return texture;
1765
+ } );
1766
+ }
1767
+ assignFinalMaterial( mesh ) {
1768
+ const geometry = mesh.geometry;
1769
+ let material = mesh.material;
1770
+ const useDerivativeTangents = geometry.attributes.tangent === undefined;
1771
+ const useVertexColors = geometry.attributes.color !== undefined;
1772
+ const useFlatShading = geometry.attributes.normal === undefined;
1773
+ if ( mesh.isPoints ) {
1774
+ const cacheKey = 'PointsMaterial:' + material.uuid;
1775
+ let pointsMaterial = this.cache.get( cacheKey );
1776
+ if ( ! pointsMaterial ) {
1777
+ pointsMaterial = new three.PointsMaterial();
1778
+ three.Material.prototype.copy.call( pointsMaterial, material );
1779
+ pointsMaterial.color.copy( material.color );
1780
+ pointsMaterial.map = material.map;
1781
+ pointsMaterial.sizeAttenuation = false;
1782
+ this.cache.add( cacheKey, pointsMaterial );
1783
+ }
1784
+ material = pointsMaterial;
1785
+ } else if ( mesh.isLine ) {
1786
+ const cacheKey = 'LineBasicMaterial:' + material.uuid;
1787
+ let lineMaterial = this.cache.get( cacheKey );
1788
+ if ( ! lineMaterial ) {
1789
+ lineMaterial = new three.LineBasicMaterial();
1790
+ three.Material.prototype.copy.call( lineMaterial, material );
1791
+ lineMaterial.color.copy( material.color );
1792
+ lineMaterial.map = material.map;
1793
+ this.cache.add( cacheKey, lineMaterial );
1794
+ }
1795
+ material = lineMaterial;
1796
+ }
1797
+ if ( useDerivativeTangents || useVertexColors || useFlatShading ) {
1798
+ let cacheKey = 'ClonedMaterial:' + material.uuid + ':';
1799
+ if ( useDerivativeTangents ) cacheKey += 'derivative-tangents:';
1800
+ if ( useVertexColors ) cacheKey += 'vertex-colors:';
1801
+ if ( useFlatShading ) cacheKey += 'flat-shading:';
1802
+ let cachedMaterial = this.cache.get( cacheKey );
1803
+ if ( ! cachedMaterial ) {
1804
+ cachedMaterial = material.clone();
1805
+ if ( useVertexColors ) cachedMaterial.vertexColors = true;
1806
+ if ( useFlatShading ) cachedMaterial.flatShading = true;
1807
+ if ( useDerivativeTangents ) {
1808
+ if ( cachedMaterial.normalScale ) cachedMaterial.normalScale.y *= -1;
1809
+ if ( cachedMaterial.clearcoatNormalScale ) cachedMaterial.clearcoatNormalScale.y *= -1;
1810
+ }
1811
+ this.cache.add( cacheKey, cachedMaterial );
1812
+ this.associations.set( cachedMaterial, this.associations.get( material ) );
1813
+ }
1814
+ material = cachedMaterial;
1815
+ }
1816
+ mesh.material = material;
1817
+ }
1818
+ getMaterialType( ) {
1819
+ return three.MeshStandardMaterial;
1820
+ }
1821
+ loadMaterial( materialIndex ) {
1822
+ const parser = this;
1823
+ const json = this.json;
1824
+ const extensions = this.extensions;
1825
+ const materialDef = json.materials[ materialIndex ];
1826
+ let materialType;
1827
+ const materialParams = {};
1828
+ const materialExtensions = materialDef.extensions || {};
1829
+ const pending = [];
1830
+ if ( materialExtensions[ EXTENSIONS.KHR_MATERIALS_UNLIT ] ) {
1831
+ const kmuExtension = extensions[ EXTENSIONS.KHR_MATERIALS_UNLIT ];
1832
+ materialType = kmuExtension.getMaterialType();
1833
+ pending.push( kmuExtension.extendParams( materialParams, materialDef, parser ) );
1834
+ } else {
1835
+ const metallicRoughness = materialDef.pbrMetallicRoughness || {};
1836
+ materialParams.color = new three.Color( 1.0, 1.0, 1.0 );
1837
+ materialParams.opacity = 1.0;
1838
+ if ( Array.isArray( metallicRoughness.baseColorFactor ) ) {
1839
+ const array = metallicRoughness.baseColorFactor;
1840
+ materialParams.color.setRGB( array[ 0 ], array[ 1 ], array[ 2 ], three.LinearSRGBColorSpace );
1841
+ materialParams.opacity = array[ 3 ];
1842
+ }
1843
+ if ( metallicRoughness.baseColorTexture !== undefined ) {
1844
+ pending.push( parser.assignTexture( materialParams, 'map', metallicRoughness.baseColorTexture, three.SRGBColorSpace ) );
1845
+ }
1846
+ materialParams.metalness = metallicRoughness.metallicFactor !== undefined ? metallicRoughness.metallicFactor : 1.0;
1847
+ materialParams.roughness = metallicRoughness.roughnessFactor !== undefined ? metallicRoughness.roughnessFactor : 1.0;
1848
+ if ( metallicRoughness.metallicRoughnessTexture !== undefined ) {
1849
+ pending.push( parser.assignTexture( materialParams, 'metalnessMap', metallicRoughness.metallicRoughnessTexture ) );
1850
+ pending.push( parser.assignTexture( materialParams, 'roughnessMap', metallicRoughness.metallicRoughnessTexture ) );
1851
+ }
1852
+ materialType = this._invokeOne( function ( ext ) {
1853
+ return ext.getMaterialType && ext.getMaterialType( materialIndex );
1854
+ } );
1855
+ pending.push( Promise.all( this._invokeAll( function ( ext ) {
1856
+ return ext.extendMaterialParams && ext.extendMaterialParams( materialIndex, materialParams );
1857
+ } ) ) );
1858
+ }
1859
+ if ( materialDef.doubleSided === true ) {
1860
+ materialParams.side = three.DoubleSide;
1861
+ }
1862
+ const alphaMode = materialDef.alphaMode || ALPHA_MODES.OPAQUE;
1863
+ if ( alphaMode === ALPHA_MODES.BLEND ) {
1864
+ materialParams.transparent = true;
1865
+ materialParams.depthWrite = false;
1866
+ } else {
1867
+ materialParams.transparent = false;
1868
+ if ( alphaMode === ALPHA_MODES.MASK ) {
1869
+ materialParams.alphaTest = materialDef.alphaCutoff !== undefined ? materialDef.alphaCutoff : 0.5;
1870
+ }
1871
+ }
1872
+ if ( materialDef.normalTexture !== undefined && materialType !== three.MeshBasicMaterial ) {
1873
+ pending.push( parser.assignTexture( materialParams, 'normalMap', materialDef.normalTexture ) );
1874
+ materialParams.normalScale = new three.Vector2( 1, 1 );
1875
+ if ( materialDef.normalTexture.scale !== undefined ) {
1876
+ const scale = materialDef.normalTexture.scale;
1877
+ materialParams.normalScale.set( scale, scale );
1878
+ }
1879
+ }
1880
+ if ( materialDef.occlusionTexture !== undefined && materialType !== three.MeshBasicMaterial ) {
1881
+ pending.push( parser.assignTexture( materialParams, 'aoMap', materialDef.occlusionTexture ) );
1882
+ if ( materialDef.occlusionTexture.strength !== undefined ) {
1883
+ materialParams.aoMapIntensity = materialDef.occlusionTexture.strength;
1884
+ }
1885
+ }
1886
+ if ( materialDef.emissiveFactor !== undefined && materialType !== three.MeshBasicMaterial ) {
1887
+ const emissiveFactor = materialDef.emissiveFactor;
1888
+ materialParams.emissive = new three.Color().setRGB( emissiveFactor[ 0 ], emissiveFactor[ 1 ], emissiveFactor[ 2 ], three.LinearSRGBColorSpace );
1889
+ }
1890
+ if ( materialDef.emissiveTexture !== undefined && materialType !== three.MeshBasicMaterial ) {
1891
+ pending.push( parser.assignTexture( materialParams, 'emissiveMap', materialDef.emissiveTexture, three.SRGBColorSpace ) );
1892
+ }
1893
+ return Promise.all( pending ).then( function () {
1894
+ const material = new materialType( materialParams );
1895
+ if ( materialDef.name ) material.name = materialDef.name;
1896
+ assignExtrasToUserData( material, materialDef );
1897
+ parser.associations.set( material, { materials: materialIndex } );
1898
+ if ( materialDef.extensions ) addUnknownExtensionsToUserData( extensions, material, materialDef );
1899
+ return material;
1900
+ } );
1901
+ }
1902
+ createUniqueName( originalName ) {
1903
+ const sanitizedName = three.PropertyBinding.sanitizeNodeName( originalName || '' );
1904
+ if ( sanitizedName in this.nodeNamesUsed ) {
1905
+ return sanitizedName + '_' + ( ++ this.nodeNamesUsed[ sanitizedName ] );
1906
+ } else {
1907
+ this.nodeNamesUsed[ sanitizedName ] = 0;
1908
+ return sanitizedName;
1909
+ }
1910
+ }
1911
+ loadGeometries( primitives ) {
1912
+ const parser = this;
1913
+ const extensions = this.extensions;
1914
+ const cache = this.primitiveCache;
1915
+ function createDracoPrimitive( primitive ) {
1916
+ return extensions[ EXTENSIONS.KHR_DRACO_MESH_COMPRESSION ]
1917
+ .decodePrimitive( primitive, parser )
1918
+ .then( function ( geometry ) {
1919
+ return addPrimitiveAttributes( geometry, primitive, parser );
1920
+ } );
1921
+ }
1922
+ const pending = [];
1923
+ for ( let i = 0, il = primitives.length; i < il; i ++ ) {
1924
+ const primitive = primitives[ i ];
1925
+ const cacheKey = createPrimitiveKey( primitive );
1926
+ const cached = cache[ cacheKey ];
1927
+ if ( cached ) {
1928
+ pending.push( cached.promise );
1929
+ } else {
1930
+ let geometryPromise;
1931
+ if ( primitive.extensions && primitive.extensions[ EXTENSIONS.KHR_DRACO_MESH_COMPRESSION ] ) {
1932
+ geometryPromise = createDracoPrimitive( primitive );
1933
+ } else {
1934
+ geometryPromise = addPrimitiveAttributes( new three.BufferGeometry(), primitive, parser );
1935
+ }
1936
+ cache[ cacheKey ] = { primitive: primitive, promise: geometryPromise };
1937
+ pending.push( geometryPromise );
1938
+ }
1939
+ }
1940
+ return Promise.all( pending );
1941
+ }
1942
+ loadMesh( meshIndex ) {
1943
+ const parser = this;
1944
+ const json = this.json;
1945
+ const extensions = this.extensions;
1946
+ const meshDef = json.meshes[ meshIndex ];
1947
+ const primitives = meshDef.primitives;
1948
+ const pending = [];
1949
+ for ( let i = 0, il = primitives.length; i < il; i ++ ) {
1950
+ const material = primitives[ i ].material === undefined
1951
+ ? createDefaultMaterial( this.cache )
1952
+ : this.getDependency( 'material', primitives[ i ].material );
1953
+ pending.push( material );
1954
+ }
1955
+ pending.push( parser.loadGeometries( primitives ) );
1956
+ return Promise.all( pending ).then( function ( results ) {
1957
+ const materials = results.slice( 0, results.length - 1 );
1958
+ const geometries = results[ results.length - 1 ];
1959
+ const meshes = [];
1960
+ for ( let i = 0, il = geometries.length; i < il; i ++ ) {
1961
+ const geometry = geometries[ i ];
1962
+ const primitive = primitives[ i ];
1963
+ let mesh;
1964
+ const material = materials[ i ];
1965
+ if ( primitive.mode === WEBGL_CONSTANTS.TRIANGLES ||
1966
+ primitive.mode === WEBGL_CONSTANTS.TRIANGLE_STRIP ||
1967
+ primitive.mode === WEBGL_CONSTANTS.TRIANGLE_FAN ||
1968
+ primitive.mode === undefined ) {
1969
+ mesh = meshDef.isSkinnedMesh === true
1970
+ ? new three.SkinnedMesh( geometry, material )
1971
+ : new three.Mesh( geometry, material );
1972
+ if ( mesh.isSkinnedMesh === true ) {
1973
+ mesh.normalizeSkinWeights();
1974
+ }
1975
+ if ( primitive.mode === WEBGL_CONSTANTS.TRIANGLE_STRIP ) {
1976
+ mesh.geometry = toTrianglesDrawMode( mesh.geometry, three.TriangleStripDrawMode );
1977
+ } else if ( primitive.mode === WEBGL_CONSTANTS.TRIANGLE_FAN ) {
1978
+ mesh.geometry = toTrianglesDrawMode( mesh.geometry, three.TriangleFanDrawMode );
1979
+ }
1980
+ } else if ( primitive.mode === WEBGL_CONSTANTS.LINES ) {
1981
+ mesh = new three.LineSegments( geometry, material );
1982
+ } else if ( primitive.mode === WEBGL_CONSTANTS.LINE_STRIP ) {
1983
+ mesh = new three.Line( geometry, material );
1984
+ } else if ( primitive.mode === WEBGL_CONSTANTS.LINE_LOOP ) {
1985
+ mesh = new three.LineLoop( geometry, material );
1986
+ } else if ( primitive.mode === WEBGL_CONSTANTS.POINTS ) {
1987
+ mesh = new three.Points( geometry, material );
1988
+ } else {
1989
+ throw new Error( 'THREE.GLTFLoader: Primitive mode unsupported: ' + primitive.mode );
1990
+ }
1991
+ if ( Object.keys( mesh.geometry.morphAttributes ).length > 0 ) {
1992
+ updateMorphTargets( mesh, meshDef );
1993
+ }
1994
+ mesh.name = parser.createUniqueName( meshDef.name || ( 'mesh_' + meshIndex ) );
1995
+ assignExtrasToUserData( mesh, meshDef );
1996
+ if ( primitive.extensions ) addUnknownExtensionsToUserData( extensions, mesh, primitive );
1997
+ parser.assignFinalMaterial( mesh );
1998
+ meshes.push( mesh );
1999
+ }
2000
+ for ( let i = 0, il = meshes.length; i < il; i ++ ) {
2001
+ parser.associations.set( meshes[ i ], {
2002
+ meshes: meshIndex,
2003
+ primitives: i
2004
+ } );
2005
+ }
2006
+ if ( meshes.length === 1 ) {
2007
+ if ( meshDef.extensions ) addUnknownExtensionsToUserData( extensions, meshes[ 0 ], meshDef );
2008
+ return meshes[ 0 ];
2009
+ }
2010
+ const group = new three.Group();
2011
+ if ( meshDef.extensions ) addUnknownExtensionsToUserData( extensions, group, meshDef );
2012
+ parser.associations.set( group, { meshes: meshIndex } );
2013
+ for ( let i = 0, il = meshes.length; i < il; i ++ ) {
2014
+ group.add( meshes[ i ] );
2015
+ }
2016
+ return group;
2017
+ } );
2018
+ }
2019
+ loadCamera( cameraIndex ) {
2020
+ let camera;
2021
+ const cameraDef = this.json.cameras[ cameraIndex ];
2022
+ const params = cameraDef[ cameraDef.type ];
2023
+ if ( ! params ) {
2024
+ console.warn( 'THREE.GLTFLoader: Missing camera parameters.' );
2025
+ return;
2026
+ }
2027
+ if ( cameraDef.type === 'perspective' ) {
2028
+ camera = new three.PerspectiveCamera( three.MathUtils.radToDeg( params.yfov ), params.aspectRatio || 1, params.znear || 1, params.zfar || 2e6 );
2029
+ } else if ( cameraDef.type === 'orthographic' ) {
2030
+ camera = new three.OrthographicCamera( - params.xmag, params.xmag, params.ymag, - params.ymag, params.znear, params.zfar );
2031
+ }
2032
+ if ( cameraDef.name ) camera.name = this.createUniqueName( cameraDef.name );
2033
+ assignExtrasToUserData( camera, cameraDef );
2034
+ return Promise.resolve( camera );
2035
+ }
2036
+ loadSkin( skinIndex ) {
2037
+ const skinDef = this.json.skins[ skinIndex ];
2038
+ const pending = [];
2039
+ for ( let i = 0, il = skinDef.joints.length; i < il; i ++ ) {
2040
+ pending.push( this._loadNodeShallow( skinDef.joints[ i ] ) );
2041
+ }
2042
+ if ( skinDef.inverseBindMatrices !== undefined ) {
2043
+ pending.push( this.getDependency( 'accessor', skinDef.inverseBindMatrices ) );
2044
+ } else {
2045
+ pending.push( null );
2046
+ }
2047
+ return Promise.all( pending ).then( function ( results ) {
2048
+ const inverseBindMatrices = results.pop();
2049
+ const jointNodes = results;
2050
+ const bones = [];
2051
+ const boneInverses = [];
2052
+ for ( let i = 0, il = jointNodes.length; i < il; i ++ ) {
2053
+ const jointNode = jointNodes[ i ];
2054
+ if ( jointNode ) {
2055
+ bones.push( jointNode );
2056
+ const mat = new three.Matrix4();
2057
+ if ( inverseBindMatrices !== null ) {
2058
+ mat.fromArray( inverseBindMatrices.array, i * 16 );
2059
+ }
2060
+ boneInverses.push( mat );
2061
+ } else {
2062
+ console.warn( 'THREE.GLTFLoader: Joint "%s" could not be found.', skinDef.joints[ i ] );
2063
+ }
2064
+ }
2065
+ return new three.Skeleton( bones, boneInverses );
2066
+ } );
2067
+ }
2068
+ loadAnimation( animationIndex ) {
2069
+ const json = this.json;
2070
+ const parser = this;
2071
+ const animationDef = json.animations[ animationIndex ];
2072
+ const animationName = animationDef.name ? animationDef.name : 'animation_' + animationIndex;
2073
+ const pendingNodes = [];
2074
+ const pendingInputAccessors = [];
2075
+ const pendingOutputAccessors = [];
2076
+ const pendingSamplers = [];
2077
+ const pendingTargets = [];
2078
+ for ( let i = 0, il = animationDef.channels.length; i < il; i ++ ) {
2079
+ const channel = animationDef.channels[ i ];
2080
+ const sampler = animationDef.samplers[ channel.sampler ];
2081
+ const target = channel.target;
2082
+ const name = target.node;
2083
+ const input = animationDef.parameters !== undefined ? animationDef.parameters[ sampler.input ] : sampler.input;
2084
+ const output = animationDef.parameters !== undefined ? animationDef.parameters[ sampler.output ] : sampler.output;
2085
+ if ( target.node === undefined ) continue;
2086
+ pendingNodes.push( this.getDependency( 'node', name ) );
2087
+ pendingInputAccessors.push( this.getDependency( 'accessor', input ) );
2088
+ pendingOutputAccessors.push( this.getDependency( 'accessor', output ) );
2089
+ pendingSamplers.push( sampler );
2090
+ pendingTargets.push( target );
2091
+ }
2092
+ return Promise.all( [
2093
+ Promise.all( pendingNodes ),
2094
+ Promise.all( pendingInputAccessors ),
2095
+ Promise.all( pendingOutputAccessors ),
2096
+ Promise.all( pendingSamplers ),
2097
+ Promise.all( pendingTargets )
2098
+ ] ).then( function ( dependencies ) {
2099
+ const nodes = dependencies[ 0 ];
2100
+ const inputAccessors = dependencies[ 1 ];
2101
+ const outputAccessors = dependencies[ 2 ];
2102
+ const samplers = dependencies[ 3 ];
2103
+ const targets = dependencies[ 4 ];
2104
+ const tracks = [];
2105
+ for ( let i = 0, il = nodes.length; i < il; i ++ ) {
2106
+ const node = nodes[ i ];
2107
+ const inputAccessor = inputAccessors[ i ];
2108
+ const outputAccessor = outputAccessors[ i ];
2109
+ const sampler = samplers[ i ];
2110
+ const target = targets[ i ];
2111
+ if ( node === undefined ) continue;
2112
+ if ( node.updateMatrix ) {
2113
+ node.updateMatrix();
2114
+ }
2115
+ const createdTracks = parser._createAnimationTracks( node, inputAccessor, outputAccessor, sampler, target );
2116
+ if ( createdTracks ) {
2117
+ for ( let k = 0; k < createdTracks.length; k ++ ) {
2118
+ tracks.push( createdTracks[ k ] );
2119
+ }
2120
+ }
2121
+ }
2122
+ const animation = new three.AnimationClip( animationName, undefined, tracks );
2123
+ assignExtrasToUserData( animation, animationDef );
2124
+ return animation;
2125
+ } );
2126
+ }
2127
+ createNodeMesh( nodeIndex ) {
2128
+ const json = this.json;
2129
+ const parser = this;
2130
+ const nodeDef = json.nodes[ nodeIndex ];
2131
+ if ( nodeDef.mesh === undefined ) return null;
2132
+ return parser.getDependency( 'mesh', nodeDef.mesh ).then( function ( mesh ) {
2133
+ const node = parser._getNodeRef( parser.meshCache, nodeDef.mesh, mesh );
2134
+ if ( nodeDef.weights !== undefined ) {
2135
+ node.traverse( function ( o ) {
2136
+ if ( ! o.isMesh ) return;
2137
+ for ( let i = 0, il = nodeDef.weights.length; i < il; i ++ ) {
2138
+ o.morphTargetInfluences[ i ] = nodeDef.weights[ i ];
2139
+ }
2140
+ } );
2141
+ }
2142
+ return node;
2143
+ } );
2144
+ }
2145
+ loadNode( nodeIndex ) {
2146
+ const json = this.json;
2147
+ const parser = this;
2148
+ const nodeDef = json.nodes[ nodeIndex ];
2149
+ const nodePending = parser._loadNodeShallow( nodeIndex );
2150
+ const childPending = [];
2151
+ const childrenDef = nodeDef.children || [];
2152
+ for ( let i = 0, il = childrenDef.length; i < il; i ++ ) {
2153
+ childPending.push( parser.getDependency( 'node', childrenDef[ i ] ) );
2154
+ }
2155
+ const skeletonPending = nodeDef.skin === undefined
2156
+ ? Promise.resolve( null )
2157
+ : parser.getDependency( 'skin', nodeDef.skin );
2158
+ return Promise.all( [
2159
+ nodePending,
2160
+ Promise.all( childPending ),
2161
+ skeletonPending
2162
+ ] ).then( function ( results ) {
2163
+ const node = results[ 0 ];
2164
+ const children = results[ 1 ];
2165
+ const skeleton = results[ 2 ];
2166
+ if ( skeleton !== null ) {
2167
+ node.traverse( function ( mesh ) {
2168
+ if ( ! mesh.isSkinnedMesh ) return;
2169
+ mesh.bind( skeleton, _identityMatrix );
2170
+ } );
2171
+ }
2172
+ for ( let i = 0, il = children.length; i < il; i ++ ) {
2173
+ node.add( children[ i ] );
2174
+ }
2175
+ return node;
2176
+ } );
2177
+ }
2178
+ _loadNodeShallow( nodeIndex ) {
2179
+ const json = this.json;
2180
+ const extensions = this.extensions;
2181
+ const parser = this;
2182
+ if ( this.nodeCache[ nodeIndex ] !== undefined ) {
2183
+ return this.nodeCache[ nodeIndex ];
2184
+ }
2185
+ const nodeDef = json.nodes[ nodeIndex ];
2186
+ const nodeName = nodeDef.name ? parser.createUniqueName( nodeDef.name ) : '';
2187
+ const pending = [];
2188
+ const meshPromise = parser._invokeOne( function ( ext ) {
2189
+ return ext.createNodeMesh && ext.createNodeMesh( nodeIndex );
2190
+ } );
2191
+ if ( meshPromise ) {
2192
+ pending.push( meshPromise );
2193
+ }
2194
+ if ( nodeDef.camera !== undefined ) {
2195
+ pending.push( parser.getDependency( 'camera', nodeDef.camera ).then( function ( camera ) {
2196
+ return parser._getNodeRef( parser.cameraCache, nodeDef.camera, camera );
2197
+ } ) );
2198
+ }
2199
+ parser._invokeAll( function ( ext ) {
2200
+ return ext.createNodeAttachment && ext.createNodeAttachment( nodeIndex );
2201
+ } ).forEach( function ( promise ) {
2202
+ pending.push( promise );
2203
+ } );
2204
+ this.nodeCache[ nodeIndex ] = Promise.all( pending ).then( function ( objects ) {
2205
+ let node;
2206
+ if ( nodeDef.isBone === true ) {
2207
+ node = new three.Bone();
2208
+ } else if ( objects.length > 1 ) {
2209
+ node = new three.Group();
2210
+ } else if ( objects.length === 1 ) {
2211
+ node = objects[ 0 ];
2212
+ } else {
2213
+ node = new three.Object3D();
2214
+ }
2215
+ if ( node !== objects[ 0 ] ) {
2216
+ for ( let i = 0, il = objects.length; i < il; i ++ ) {
2217
+ node.add( objects[ i ] );
2218
+ }
2219
+ }
2220
+ if ( nodeDef.name ) {
2221
+ node.userData.name = nodeDef.name;
2222
+ node.name = nodeName;
2223
+ }
2224
+ assignExtrasToUserData( node, nodeDef );
2225
+ if ( nodeDef.extensions ) addUnknownExtensionsToUserData( extensions, node, nodeDef );
2226
+ if ( nodeDef.matrix !== undefined ) {
2227
+ const matrix = new three.Matrix4();
2228
+ matrix.fromArray( nodeDef.matrix );
2229
+ node.applyMatrix4( matrix );
2230
+ } else {
2231
+ if ( nodeDef.translation !== undefined ) {
2232
+ node.position.fromArray( nodeDef.translation );
2233
+ }
2234
+ if ( nodeDef.rotation !== undefined ) {
2235
+ node.quaternion.fromArray( nodeDef.rotation );
2236
+ }
2237
+ if ( nodeDef.scale !== undefined ) {
2238
+ node.scale.fromArray( nodeDef.scale );
2239
+ }
2240
+ }
2241
+ if ( ! parser.associations.has( node ) ) {
2242
+ parser.associations.set( node, {} );
2243
+ } else if ( nodeDef.mesh !== undefined && parser.meshCache.refs[ nodeDef.mesh ] > 1 ) {
2244
+ const mapping = parser.associations.get( node );
2245
+ parser.associations.set( node, { ...mapping } );
2246
+ }
2247
+ parser.associations.get( node ).nodes = nodeIndex;
2248
+ return node;
2249
+ } );
2250
+ return this.nodeCache[ nodeIndex ];
2251
+ }
2252
+ loadScene( sceneIndex ) {
2253
+ const extensions = this.extensions;
2254
+ const sceneDef = this.json.scenes[ sceneIndex ];
2255
+ const parser = this;
2256
+ const scene = new three.Group();
2257
+ if ( sceneDef.name ) scene.name = parser.createUniqueName( sceneDef.name );
2258
+ assignExtrasToUserData( scene, sceneDef );
2259
+ if ( sceneDef.extensions ) addUnknownExtensionsToUserData( extensions, scene, sceneDef );
2260
+ const nodeIds = sceneDef.nodes || [];
2261
+ const pending = [];
2262
+ for ( let i = 0, il = nodeIds.length; i < il; i ++ ) {
2263
+ pending.push( parser.getDependency( 'node', nodeIds[ i ] ) );
2264
+ }
2265
+ return Promise.all( pending ).then( function ( nodes ) {
2266
+ for ( let i = 0, il = nodes.length; i < il; i ++ ) {
2267
+ scene.add( nodes[ i ] );
2268
+ }
2269
+ const reduceAssociations = ( node ) => {
2270
+ const reducedAssociations = new Map();
2271
+ for ( const [ key, value ] of parser.associations ) {
2272
+ if ( key instanceof three.Material || key instanceof three.Texture ) {
2273
+ reducedAssociations.set( key, value );
2274
+ }
2275
+ }
2276
+ node.traverse( ( node ) => {
2277
+ const mappings = parser.associations.get( node );
2278
+ if ( mappings != null ) {
2279
+ reducedAssociations.set( node, mappings );
2280
+ }
2281
+ } );
2282
+ return reducedAssociations;
2283
+ };
2284
+ parser.associations = reduceAssociations( scene );
2285
+ return scene;
2286
+ } );
2287
+ }
2288
+ _createAnimationTracks( node, inputAccessor, outputAccessor, sampler, target ) {
2289
+ const tracks = [];
2290
+ const targetName = node.name ? node.name : node.uuid;
2291
+ const targetNames = [];
2292
+ if ( PATH_PROPERTIES[ target.path ] === PATH_PROPERTIES.weights ) {
2293
+ node.traverse( function ( object ) {
2294
+ if ( object.morphTargetInfluences ) {
2295
+ targetNames.push( object.name ? object.name : object.uuid );
2296
+ }
2297
+ } );
2298
+ } else {
2299
+ targetNames.push( targetName );
2300
+ }
2301
+ let TypedKeyframeTrack;
2302
+ switch ( PATH_PROPERTIES[ target.path ] ) {
2303
+ case PATH_PROPERTIES.weights:
2304
+ TypedKeyframeTrack = three.NumberKeyframeTrack;
2305
+ break;
2306
+ case PATH_PROPERTIES.rotation:
2307
+ TypedKeyframeTrack = three.QuaternionKeyframeTrack;
2308
+ break;
2309
+ case PATH_PROPERTIES.translation:
2310
+ case PATH_PROPERTIES.scale:
2311
+ TypedKeyframeTrack = three.VectorKeyframeTrack;
2312
+ break;
2313
+ default:
2314
+ switch ( outputAccessor.itemSize ) {
2315
+ case 1:
2316
+ TypedKeyframeTrack = three.NumberKeyframeTrack;
2317
+ break;
2318
+ case 2:
2319
+ case 3:
2320
+ default:
2321
+ TypedKeyframeTrack = three.VectorKeyframeTrack;
2322
+ break;
2323
+ }
2324
+ break;
2325
+ }
2326
+ const interpolation = sampler.interpolation !== undefined ? INTERPOLATION[ sampler.interpolation ] : three.InterpolateLinear;
2327
+ const outputArray = this._getArrayFromAccessor( outputAccessor );
2328
+ for ( let j = 0, jl = targetNames.length; j < jl; j ++ ) {
2329
+ const track = new TypedKeyframeTrack(
2330
+ targetNames[ j ] + '.' + PATH_PROPERTIES[ target.path ],
2331
+ inputAccessor.array,
2332
+ outputArray,
2333
+ interpolation
2334
+ );
2335
+ if ( sampler.interpolation === 'CUBICSPLINE' ) {
2336
+ this._createCubicSplineTrackInterpolant( track );
2337
+ }
2338
+ tracks.push( track );
2339
+ }
2340
+ return tracks;
2341
+ }
2342
+ _getArrayFromAccessor( accessor ) {
2343
+ let outputArray = accessor.array;
2344
+ if ( accessor.normalized ) {
2345
+ const scale = getNormalizedComponentScale( outputArray.constructor );
2346
+ const scaled = new Float32Array( outputArray.length );
2347
+ for ( let j = 0, jl = outputArray.length; j < jl; j ++ ) {
2348
+ scaled[ j ] = outputArray[ j ] * scale;
2349
+ }
2350
+ outputArray = scaled;
2351
+ }
2352
+ return outputArray;
2353
+ }
2354
+ _createCubicSplineTrackInterpolant( track ) {
2355
+ track.createInterpolant = function InterpolantFactoryMethodGLTFCubicSpline( result ) {
2356
+ const interpolantType = ( this instanceof three.QuaternionKeyframeTrack ) ? GLTFCubicSplineQuaternionInterpolant : GLTFCubicSplineInterpolant;
2357
+ return new interpolantType( this.times, this.values, this.getValueSize() / 3, result );
2358
+ };
2359
+ track.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline = true;
2360
+ }
2361
+ }
2362
+ function computeBounds( geometry, primitiveDef, parser ) {
2363
+ const attributes = primitiveDef.attributes;
2364
+ const box = new three.Box3();
2365
+ if ( attributes.POSITION !== undefined ) {
2366
+ const accessor = parser.json.accessors[ attributes.POSITION ];
2367
+ const min = accessor.min;
2368
+ const max = accessor.max;
2369
+ if ( min !== undefined && max !== undefined ) {
2370
+ box.set(
2371
+ new three.Vector3( min[ 0 ], min[ 1 ], min[ 2 ] ),
2372
+ new three.Vector3( max[ 0 ], max[ 1 ], max[ 2 ] )
2373
+ );
2374
+ if ( accessor.normalized ) {
2375
+ const boxScale = getNormalizedComponentScale( WEBGL_COMPONENT_TYPES[ accessor.componentType ] );
2376
+ box.min.multiplyScalar( boxScale );
2377
+ box.max.multiplyScalar( boxScale );
2378
+ }
2379
+ } else {
2380
+ console.warn( 'THREE.GLTFLoader: Missing min/max properties for accessor POSITION.' );
2381
+ return;
2382
+ }
2383
+ } else {
2384
+ return;
2385
+ }
2386
+ const targets = primitiveDef.targets;
2387
+ if ( targets !== undefined ) {
2388
+ const maxDisplacement = new three.Vector3();
2389
+ const vector = new three.Vector3();
2390
+ for ( let i = 0, il = targets.length; i < il; i ++ ) {
2391
+ const target = targets[ i ];
2392
+ if ( target.POSITION !== undefined ) {
2393
+ const accessor = parser.json.accessors[ target.POSITION ];
2394
+ const min = accessor.min;
2395
+ const max = accessor.max;
2396
+ if ( min !== undefined && max !== undefined ) {
2397
+ vector.setX( Math.max( Math.abs( min[ 0 ] ), Math.abs( max[ 0 ] ) ) );
2398
+ vector.setY( Math.max( Math.abs( min[ 1 ] ), Math.abs( max[ 1 ] ) ) );
2399
+ vector.setZ( Math.max( Math.abs( min[ 2 ] ), Math.abs( max[ 2 ] ) ) );
2400
+ if ( accessor.normalized ) {
2401
+ const boxScale = getNormalizedComponentScale( WEBGL_COMPONENT_TYPES[ accessor.componentType ] );
2402
+ vector.multiplyScalar( boxScale );
2403
+ }
2404
+ maxDisplacement.max( vector );
2405
+ } else {
2406
+ console.warn( 'THREE.GLTFLoader: Missing min/max properties for accessor POSITION.' );
2407
+ }
2408
+ }
2409
+ }
2410
+ box.expandByVector( maxDisplacement );
2411
+ }
2412
+ geometry.boundingBox = box;
2413
+ const sphere = new three.Sphere();
2414
+ box.getCenter( sphere.center );
2415
+ sphere.radius = box.min.distanceTo( box.max ) / 2;
2416
+ geometry.boundingSphere = sphere;
2417
+ }
2418
+ function addPrimitiveAttributes( geometry, primitiveDef, parser ) {
2419
+ const attributes = primitiveDef.attributes;
2420
+ const pending = [];
2421
+ function assignAttributeAccessor( accessorIndex, attributeName ) {
2422
+ return parser.getDependency( 'accessor', accessorIndex )
2423
+ .then( function ( accessor ) {
2424
+ geometry.setAttribute( attributeName, accessor );
2425
+ } );
2426
+ }
2427
+ for ( const gltfAttributeName in attributes ) {
2428
+ const threeAttributeName = ATTRIBUTES[ gltfAttributeName ] || gltfAttributeName.toLowerCase();
2429
+ if ( threeAttributeName in geometry.attributes ) continue;
2430
+ pending.push( assignAttributeAccessor( attributes[ gltfAttributeName ], threeAttributeName ) );
2431
+ }
2432
+ if ( primitiveDef.indices !== undefined && ! geometry.index ) {
2433
+ const accessor = parser.getDependency( 'accessor', primitiveDef.indices ).then( function ( accessor ) {
2434
+ geometry.setIndex( accessor );
2435
+ } );
2436
+ pending.push( accessor );
2437
+ }
2438
+ if ( three.ColorManagement.workingColorSpace !== three.LinearSRGBColorSpace && 'COLOR_0' in attributes ) {
2439
+ console.warn( `THREE.GLTFLoader: Converting vertex colors from "srgb-linear" to "${three.ColorManagement.workingColorSpace}" not supported.` );
2440
+ }
2441
+ assignExtrasToUserData( geometry, primitiveDef );
2442
+ computeBounds( geometry, primitiveDef, parser );
2443
+ return Promise.all( pending ).then( function () {
2444
+ return primitiveDef.targets !== undefined
2445
+ ? addMorphTargets( geometry, primitiveDef.targets, parser )
2446
+ : geometry;
2447
+ } );
2448
+ }
2449
+
2450
+ class GLTFFileLoader extends viewerThree.Loader {
2451
+ constructor(viewer) {
2452
+ super();
2453
+ this.viewer = viewer;
2454
+ }
2455
+ dispose() {
2456
+ if (this.manager)
2457
+ this.manager.dispose();
2458
+ }
2459
+ isSupport(file, format) {
2460
+ return ((typeof file === "string" || file instanceof globalThis.File || file instanceof ArrayBuffer) &&
2461
+ /(gltf|glb)$/i.test(format));
2462
+ }
2463
+ async load(file, format, params = {}) {
2464
+ this.manager = new viewerThree.GLTFLoadingManager(file, params);
2465
+ const loader = new GLTFLoader(this.manager);
2466
+ loader.setPath(this.manager.path);
2467
+ loader.setCrossOrigin(params.crossOrigin || loader.crossOrigin);
2468
+ loader.setRequestHeader(params.requestHeader || {});
2469
+ loader.setWithCredentials(params.withCredentials || loader.withCredentials);
2470
+ const progress = (event) => {
2471
+ const { lengthComputable, loaded, total } = event;
2472
+ const progress = lengthComputable ? loaded / total : 1;
2473
+ this.viewer.emitEvent({ type: "geometryprogress", data: progress, file });
2474
+ };
2475
+ const gltf = await loader.loadAsync(this.manager.fileURL, progress);
2476
+ if (!this.viewer.scene)
2477
+ return this;
2478
+ let handle = 0;
2479
+ gltf.scene.traverse((object) => {
2480
+ object.userData = { handle: handle + "", ...object.userData };
2481
+ handle++;
2482
+ });
2483
+ const modelImpl = new viewerThree.ModelImpl(gltf.scene);
2484
+ modelImpl.id = params.modelId || this.extractFileName(file);
2485
+ this.viewer.scene.add(gltf.scene);
2486
+ this.viewer.models.push(modelImpl);
2487
+ this.viewer.syncOptions();
2488
+ this.viewer.syncOverlay();
2489
+ this.viewer.update();
2490
+ this.viewer.emitEvent({ type: "databasechunk", data: gltf.scene, file });
2491
+ return this;
2492
+ }
2493
+ }
2494
+ viewerThree.loaders.registerLoader("gltf-file", (viewer) => new GLTFFileLoader(viewer));
2495
+
2496
+ exports.GLTFFileLoader = GLTFFileLoader;
2497
+
2498
+ }));
2499
+ //# sourceMappingURL=GLTFFileLoader.js.map