@2112-lab/central-plant 0.1.4 → 0.1.5

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 (87) hide show
  1. package/dist/cjs/_virtual/_rollupPluginBabelHelpers.js +432 -1
  2. package/dist/cjs/node_modules/@2112-lab/pathfinder/dist/index.esm.js +1448 -1
  3. package/dist/cjs/node_modules/three/examples/jsm/controls/OrbitControls.js +1853 -1
  4. package/dist/cjs/node_modules/three/examples/jsm/exporters/GLTFExporter.js +3537 -1
  5. package/dist/cjs/node_modules/three/examples/jsm/exporters/OBJExporter.js +305 -1
  6. package/dist/cjs/node_modules/three/examples/jsm/exporters/PLYExporter.js +542 -1
  7. package/dist/cjs/node_modules/three/examples/jsm/exporters/STLExporter.js +218 -1
  8. package/dist/cjs/node_modules/three/examples/jsm/loaders/DRACOLoader.js +683 -1
  9. package/dist/cjs/node_modules/three/examples/jsm/loaders/GLTFLoader.js +4811 -1
  10. package/dist/cjs/node_modules/three/examples/jsm/loaders/RGBELoader.js +480 -1
  11. package/dist/cjs/node_modules/three/examples/jsm/renderers/CSS2DRenderer.js +309 -1
  12. package/dist/cjs/node_modules/three/examples/jsm/utils/BufferGeometryUtils.js +120 -1
  13. package/dist/cjs/src/analysis/analysis.js +560 -1
  14. package/dist/cjs/src/analysis/testing.js +958 -1
  15. package/dist/cjs/src/core/centralPlant.js +1149 -1
  16. package/dist/cjs/src/core/debugLogger.js +175 -1
  17. package/dist/cjs/src/core/mathUtils.js +574 -1
  18. package/dist/cjs/src/core/nameUtils.js +93 -1
  19. package/dist/cjs/src/data/export.js +716 -1
  20. package/dist/cjs/src/data/import.js +380 -1
  21. package/dist/cjs/src/data/numerics.js +522 -1
  22. package/dist/cjs/src/helpers/sceneHelper.js +572 -1
  23. package/dist/cjs/src/index.js +69 -1
  24. package/dist/cjs/src/managers/components/animationManager.js +123 -1
  25. package/dist/cjs/src/managers/components/componentManager.js +332 -1
  26. package/dist/cjs/src/managers/components/pathfindingManager.js +1441 -1
  27. package/dist/cjs/src/managers/controls/TransformControls.js +1063 -1
  28. package/dist/cjs/src/managers/controls/cameraControlsManager.js +79 -1
  29. package/dist/cjs/src/managers/controls/dragDropManager.js +1026 -1
  30. package/dist/cjs/src/managers/controls/keyboardControlsManager.js +395 -1
  31. package/dist/cjs/src/managers/controls/transformControlsManager.js +1807 -1
  32. package/dist/cjs/src/managers/environment/environmentManager.js +714 -1
  33. package/dist/cjs/src/managers/environment/textureConfig.js +229 -1
  34. package/dist/cjs/src/managers/scene/sceneExportManager.js +264 -1
  35. package/dist/cjs/src/managers/scene/sceneInitializationManager.js +346 -1
  36. package/dist/cjs/src/managers/scene/sceneOperationsManager.js +1509 -1
  37. package/dist/cjs/src/managers/scene/sceneTooltipsManager.js +661 -1
  38. package/dist/cjs/src/managers/system/disposalManager.js +444 -1
  39. package/dist/cjs/src/managers/system/hotReloadManager.js +291 -1
  40. package/dist/cjs/src/managers/system/performanceMonitor.js +863 -1
  41. package/dist/cjs/src/rendering/modelPreloader.js +369 -1
  42. package/dist/cjs/src/rendering/rendering2D.js +631 -1
  43. package/dist/cjs/src/rendering/rendering3D.js +685 -1
  44. package/dist/esm/_virtual/_rollupPluginBabelHelpers.js +396 -1
  45. package/dist/esm/node_modules/@2112-lab/pathfinder/dist/index.esm.js +1444 -1
  46. package/dist/esm/node_modules/three/examples/jsm/controls/OrbitControls.js +1849 -1
  47. package/dist/esm/node_modules/three/examples/jsm/exporters/GLTFExporter.js +3533 -1
  48. package/dist/esm/node_modules/three/examples/jsm/exporters/OBJExporter.js +301 -1
  49. package/dist/esm/node_modules/three/examples/jsm/exporters/PLYExporter.js +538 -1
  50. package/dist/esm/node_modules/three/examples/jsm/exporters/STLExporter.js +214 -1
  51. package/dist/esm/node_modules/three/examples/jsm/loaders/DRACOLoader.js +679 -1
  52. package/dist/esm/node_modules/three/examples/jsm/loaders/GLTFLoader.js +4807 -1
  53. package/dist/esm/node_modules/three/examples/jsm/loaders/RGBELoader.js +476 -1
  54. package/dist/esm/node_modules/three/examples/jsm/renderers/CSS2DRenderer.js +304 -1
  55. package/dist/esm/node_modules/three/examples/jsm/utils/BufferGeometryUtils.js +116 -1
  56. package/dist/esm/src/analysis/analysis.js +536 -1
  57. package/dist/esm/src/analysis/testing.js +954 -1
  58. package/dist/esm/src/core/centralPlant.js +1144 -1
  59. package/dist/esm/src/core/debugLogger.js +167 -1
  60. package/dist/esm/src/core/mathUtils.js +570 -1
  61. package/dist/esm/src/core/nameUtils.js +87 -1
  62. package/dist/esm/src/data/export.js +712 -1
  63. package/dist/esm/src/data/import.js +356 -1
  64. package/dist/esm/src/data/numerics.js +518 -1
  65. package/dist/esm/src/helpers/sceneHelper.js +547 -1
  66. package/dist/esm/src/index.js +35 -1
  67. package/dist/esm/src/managers/components/animationManager.js +119 -1
  68. package/dist/esm/src/managers/components/componentManager.js +328 -1
  69. package/dist/esm/src/managers/components/pathfindingManager.js +1417 -1
  70. package/dist/esm/src/managers/controls/TransformControls.js +1057 -1
  71. package/dist/esm/src/managers/controls/cameraControlsManager.js +75 -1
  72. package/dist/esm/src/managers/controls/dragDropManager.js +1002 -1
  73. package/dist/esm/src/managers/controls/keyboardControlsManager.js +371 -1
  74. package/dist/esm/src/managers/controls/transformControlsManager.js +1782 -1
  75. package/dist/esm/src/managers/environment/environmentManager.js +690 -1
  76. package/dist/esm/src/managers/environment/textureConfig.js +202 -1
  77. package/dist/esm/src/managers/scene/sceneExportManager.js +260 -1
  78. package/dist/esm/src/managers/scene/sceneInitializationManager.js +322 -1
  79. package/dist/esm/src/managers/scene/sceneOperationsManager.js +1485 -1
  80. package/dist/esm/src/managers/scene/sceneTooltipsManager.js +637 -1
  81. package/dist/esm/src/managers/system/disposalManager.js +440 -1
  82. package/dist/esm/src/managers/system/hotReloadManager.js +287 -1
  83. package/dist/esm/src/managers/system/performanceMonitor.js +858 -1
  84. package/dist/esm/src/rendering/modelPreloader.js +364 -1
  85. package/dist/esm/src/rendering/rendering2D.js +627 -1
  86. package/dist/esm/src/rendering/rendering3D.js +661 -1
  87. package/package.json +1 -1
@@ -1 +1,4811 @@
1
- "use strict";Object.defineProperty(exports,"t",{value:!0});var t=require("three"),e=require("../utils/BufferGeometryUtils.js");class s extends t.Loader{constructor(t){super(t),this.dracoLoader=null,this.ktx2Loader=null,this.meshoptDecoder=null,this.pluginCallbacks=[],this.register(function(t){return new a(t)}),this.register(function(t){return new u(t)}),this.register(function(t){return new _(t)}),this.register(function(t){return new E(t)}),this.register(function(t){return new p(t)}),this.register(function(t){return new f(t)}),this.register(function(t){return new l(t)}),this.register(function(t){return new d(t)}),this.register(function(t){return new m(t)}),this.register(function(t){return new c(t)}),this.register(function(t){return new v(t)}),this.register(function(t){return new h(t)}),this.register(function(t){return new T(t)}),this.register(function(t){return new w(t)}),this.register(function(t){return new r(t)}),this.register(function(t){return new R(t)}),this.register(function(t){return new A(t)})}load(e,s,i,n){const r=this;let o;if(""!==this.resourcePath)o=this.resourcePath;else if(""!==this.path){const s=t.LoaderUtils.extractUrlBase(e);o=t.LoaderUtils.resolveURL(s,this.path)}else o=t.LoaderUtils.extractUrlBase(e);this.manager.itemStart(e);const c=function(t){n&&n(t),r.manager.itemError(e),r.manager.itemEnd(e)},a=new t.FileLoader(this.manager);a.setPath(this.path),a.setResponseType("arraybuffer"),a.setRequestHeader(this.requestHeader),a.setWithCredentials(this.withCredentials),a.load(e,function(t){try{r.parse(t,o,function(t){s(t),r.manager.itemEnd(e)},c)}catch(t){c(t)}},i,c)}setDRACOLoader(t){return this.dracoLoader=t,this}setKTX2Loader(t){return this.ktx2Loader=t,this}setMeshoptDecoder(t){return this.meshoptDecoder=t,this}register(t){return-1===this.pluginCallbacks.indexOf(t)&&this.pluginCallbacks.push(t),this}unregister(t){return-1!==this.pluginCallbacks.indexOf(t)&&this.pluginCallbacks.splice(this.pluginCallbacks.indexOf(t),1),this}parse(t,e,s,i){let r;const c={},a={},u=new TextDecoder;if("string"==typeof t)r=JSON.parse(t);else if(t instanceof ArrayBuffer){if(u.decode(new Uint8Array(t,0,4))===P){try{c[n.KHR_BINARY_GLTF]=new g(t)}catch(t){return void(i&&i(t))}r=JSON.parse(c[n.KHR_BINARY_GLTF].content)}else r=JSON.parse(u.decode(t))}else r=t;if(void 0===r.asset||r.asset.version[0]<2)return void(i&&i(new Error("THREE.GLTFLoader: Unsupported asset. glTF versions >=2.0 are supported.")));const h=new Q(r,{path:e||this.resourcePath||"",crossOrigin:this.crossOrigin,requestHeader:this.requestHeader,manager:this.manager,ktx2Loader:this.ktx2Loader,meshoptDecoder:this.meshoptDecoder});h.fileLoader.setRequestHeader(this.requestHeader);for(let t=0;t<this.pluginCallbacks.length;t++){const e=this.pluginCallbacks[t](h);e.name,a[e.name]=e,c[e.name]=!0}if(r.extensionsUsed)for(let t=0;t<r.extensionsUsed.length;++t){const e=r.extensionsUsed[t],s=r.extensionsRequired||[];switch(e){case n.KHR_MATERIALS_UNLIT:c[e]=new o;break;case n.KHR_DRACO_MESH_COMPRESSION:c[e]=new I(r,this.dracoLoader);break;case n.KHR_TEXTURE_TRANSFORM:c[e]=new S;break;case n.KHR_MESH_QUANTIZATION:c[e]=new y;break;default:s.indexOf(e)>=0&&a[e]}}h.setExtensions(c),h.setPlugins(a),h.parse(s,i)}parseAsync(t,e){const s=this;return new Promise(function(i,n){s.parse(t,e,i,n)})}}function i(){let t={};return{get:function(e){return t[e]},add:function(e,s){t[e]=s},remove:function(e){delete t[e]},removeAll:function(){t={}}}}const n={KHR_BINARY_GLTF:"KHR_binary_glTF",KHR_DRACO_MESH_COMPRESSION:"KHR_draco_mesh_compression",KHR_LIGHTS_PUNCTUAL:"KHR_lights_punctual",KHR_MATERIALS_CLEARCOAT:"KHR_materials_clearcoat",KHR_MATERIALS_DISPERSION:"KHR_materials_dispersion",KHR_MATERIALS_IOR:"KHR_materials_ior",KHR_MATERIALS_SHEEN:"KHR_materials_sheen",KHR_MATERIALS_SPECULAR:"KHR_materials_specular",KHR_MATERIALS_TRANSMISSION:"KHR_materials_transmission",KHR_MATERIALS_IRIDESCENCE:"KHR_materials_iridescence",KHR_MATERIALS_ANISOTROPY:"KHR_materials_anisotropy",KHR_MATERIALS_UNLIT:"KHR_materials_unlit",KHR_MATERIALS_VOLUME:"KHR_materials_volume",KHR_TEXTURE_BASISU:"KHR_texture_basisu",KHR_TEXTURE_TRANSFORM:"KHR_texture_transform",KHR_MESH_QUANTIZATION:"KHR_mesh_quantization",KHR_MATERIALS_EMISSIVE_STRENGTH:"KHR_materials_emissive_strength",EXT_MATERIALS_BUMP:"EXT_materials_bump",EXT_TEXTURE_WEBP:"EXT_texture_webp",EXT_TEXTURE_AVIF:"EXT_texture_avif",EXT_MESHOPT_COMPRESSION:"EXT_meshopt_compression",EXT_MESH_GPU_INSTANCING:"EXT_mesh_gpu_instancing"};class r{constructor(t){this.parser=t,this.name=n.KHR_LIGHTS_PUNCTUAL,this.cache={refs:{},uses:{}}}i(){const t=this.parser,e=this.parser.json.nodes||[];for(let s=0,i=e.length;s<i;s++){const i=e[s];i.extensions&&i.extensions[this.name]&&void 0!==i.extensions[this.name].light&&t.o(this.cache,i.extensions[this.name].light)}}u(e){const s=this.parser,i="light:"+e;let n=s.cache.get(i);if(n)return n;const r=s.json,o=((r.extensions&&r.extensions[this.name]||{}).lights||[])[e];let c;const a=new t.Color(16777215);void 0!==o.color&&a.setRGB(o.color[0],o.color[1],o.color[2],t.LinearSRGBColorSpace);const u=void 0!==o.range?o.range:0;switch(o.type){case"directional":c=new t.DirectionalLight(a),c.target.position.set(0,0,-1),c.add(c.target);break;case"point":c=new t.PointLight(a),c.distance=u;break;case"spot":c=new t.SpotLight(a),c.distance=u,o.spot=o.spot||{},o.spot.innerConeAngle=void 0!==o.spot.innerConeAngle?o.spot.innerConeAngle:0,o.spot.outerConeAngle=void 0!==o.spot.outerConeAngle?o.spot.outerConeAngle:Math.PI/4,c.angle=o.spot.outerConeAngle,c.penumbra=1-o.spot.innerConeAngle/o.spot.outerConeAngle,c.target.position.set(0,0,-1),c.add(c.target);break;default:throw new Error("THREE.GLTFLoader: Unexpected light type: "+o.type)}return c.position.set(0,0,0),q(c,o),void 0!==o.intensity&&(c.intensity=o.intensity),c.name=s.createUniqueName(o.name||"light_"+e),n=Promise.resolve(c),s.cache.add(i,n),n}getDependency(t,e){if("light"===t)return this.u(e)}createNodeAttachment(t){const e=this,s=this.parser,i=s.json.nodes[t],n=(i.extensions&&i.extensions[this.name]||{}).light;return void 0===n?null:this.u(n).then(function(t){return s.h(e.cache,n,t)})}}class o{constructor(){this.name=n.KHR_MATERIALS_UNLIT}getMaterialType(){return t.MeshBasicMaterial}extendParams(e,s,i){const n=[];e.color=new t.Color(1,1,1),e.opacity=1;const r=s.pbrMetallicRoughness;if(r){if(Array.isArray(r.baseColorFactor)){const s=r.baseColorFactor;e.color.setRGB(s[0],s[1],s[2],t.LinearSRGBColorSpace),e.opacity=s[3]}void 0!==r.baseColorTexture&&n.push(i.assignTexture(e,"map",r.baseColorTexture,t.SRGBColorSpace))}return Promise.all(n)}}class c{constructor(t){this.parser=t,this.name=n.KHR_MATERIALS_EMISSIVE_STRENGTH}extendMaterialParams(t,e){const s=this.parser.json.materials[t];if(!s.extensions||!s.extensions[this.name])return Promise.resolve();const i=s.extensions[this.name].emissiveStrength;return void 0!==i&&(e.emissiveIntensity=i),Promise.resolve()}}class a{constructor(t){this.parser=t,this.name=n.KHR_MATERIALS_CLEARCOAT}getMaterialType(e){const s=this.parser.json.materials[e];return s.extensions&&s.extensions[this.name]?t.MeshPhysicalMaterial:null}extendMaterialParams(e,s){const i=this.parser,n=i.json.materials[e];if(!n.extensions||!n.extensions[this.name])return Promise.resolve();const r=[],o=n.extensions[this.name];if(void 0!==o.clearcoatFactor&&(s.clearcoat=o.clearcoatFactor),void 0!==o.clearcoatTexture&&r.push(i.assignTexture(s,"clearcoatMap",o.clearcoatTexture)),void 0!==o.clearcoatRoughnessFactor&&(s.clearcoatRoughness=o.clearcoatRoughnessFactor),void 0!==o.clearcoatRoughnessTexture&&r.push(i.assignTexture(s,"clearcoatRoughnessMap",o.clearcoatRoughnessTexture)),void 0!==o.clearcoatNormalTexture&&(r.push(i.assignTexture(s,"clearcoatNormalMap",o.clearcoatNormalTexture)),void 0!==o.clearcoatNormalTexture.scale)){const e=o.clearcoatNormalTexture.scale;s.clearcoatNormalScale=new t.Vector2(e,e)}return Promise.all(r)}}class u{constructor(t){this.parser=t,this.name=n.KHR_MATERIALS_DISPERSION}getMaterialType(e){const s=this.parser.json.materials[e];return s.extensions&&s.extensions[this.name]?t.MeshPhysicalMaterial:null}extendMaterialParams(t,e){const s=this.parser.json.materials[t];if(!s.extensions||!s.extensions[this.name])return Promise.resolve();const i=s.extensions[this.name];return e.dispersion=void 0!==i.dispersion?i.dispersion:0,Promise.resolve()}}class h{constructor(t){this.parser=t,this.name=n.KHR_MATERIALS_IRIDESCENCE}getMaterialType(e){const s=this.parser.json.materials[e];return s.extensions&&s.extensions[this.name]?t.MeshPhysicalMaterial:null}extendMaterialParams(t,e){const s=this.parser,i=s.json.materials[t];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();const n=[],r=i.extensions[this.name];return void 0!==r.iridescenceFactor&&(e.iridescence=r.iridescenceFactor),void 0!==r.iridescenceTexture&&n.push(s.assignTexture(e,"iridescenceMap",r.iridescenceTexture)),void 0!==r.iridescenceIor&&(e.iridescenceIOR=r.iridescenceIor),void 0===e.iridescenceThicknessRange&&(e.iridescenceThicknessRange=[100,400]),void 0!==r.iridescenceThicknessMinimum&&(e.iridescenceThicknessRange[0]=r.iridescenceThicknessMinimum),void 0!==r.iridescenceThicknessMaximum&&(e.iridescenceThicknessRange[1]=r.iridescenceThicknessMaximum),void 0!==r.iridescenceThicknessTexture&&n.push(s.assignTexture(e,"iridescenceThicknessMap",r.iridescenceThicknessTexture)),Promise.all(n)}}class f{constructor(t){this.parser=t,this.name=n.KHR_MATERIALS_SHEEN}getMaterialType(e){const s=this.parser.json.materials[e];return s.extensions&&s.extensions[this.name]?t.MeshPhysicalMaterial:null}extendMaterialParams(e,s){const i=this.parser,n=i.json.materials[e];if(!n.extensions||!n.extensions[this.name])return Promise.resolve();const r=[];s.sheenColor=new t.Color(0,0,0),s.sheenRoughness=0,s.sheen=1;const o=n.extensions[this.name];if(void 0!==o.sheenColorFactor){const e=o.sheenColorFactor;s.sheenColor.setRGB(e[0],e[1],e[2],t.LinearSRGBColorSpace)}return void 0!==o.sheenRoughnessFactor&&(s.sheenRoughness=o.sheenRoughnessFactor),void 0!==o.sheenColorTexture&&r.push(i.assignTexture(s,"sheenColorMap",o.sheenColorTexture,t.SRGBColorSpace)),void 0!==o.sheenRoughnessTexture&&r.push(i.assignTexture(s,"sheenRoughnessMap",o.sheenRoughnessTexture)),Promise.all(r)}}class l{constructor(t){this.parser=t,this.name=n.KHR_MATERIALS_TRANSMISSION}getMaterialType(e){const s=this.parser.json.materials[e];return s.extensions&&s.extensions[this.name]?t.MeshPhysicalMaterial:null}extendMaterialParams(t,e){const s=this.parser,i=s.json.materials[t];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();const n=[],r=i.extensions[this.name];return void 0!==r.transmissionFactor&&(e.transmission=r.transmissionFactor),void 0!==r.transmissionTexture&&n.push(s.assignTexture(e,"transmissionMap",r.transmissionTexture)),Promise.all(n)}}class d{constructor(t){this.parser=t,this.name=n.KHR_MATERIALS_VOLUME}getMaterialType(e){const s=this.parser.json.materials[e];return s.extensions&&s.extensions[this.name]?t.MeshPhysicalMaterial:null}extendMaterialParams(e,s){const i=this.parser,n=i.json.materials[e];if(!n.extensions||!n.extensions[this.name])return Promise.resolve();const r=[],o=n.extensions[this.name];s.thickness=void 0!==o.thicknessFactor?o.thicknessFactor:0,void 0!==o.thicknessTexture&&r.push(i.assignTexture(s,"thicknessMap",o.thicknessTexture)),s.attenuationDistance=o.attenuationDistance||1/0;const c=o.attenuationColor||[1,1,1];return s.attenuationColor=(new t.Color).setRGB(c[0],c[1],c[2],t.LinearSRGBColorSpace),Promise.all(r)}}class m{constructor(t){this.parser=t,this.name=n.KHR_MATERIALS_IOR}getMaterialType(e){const s=this.parser.json.materials[e];return s.extensions&&s.extensions[this.name]?t.MeshPhysicalMaterial:null}extendMaterialParams(t,e){const s=this.parser.json.materials[t];if(!s.extensions||!s.extensions[this.name])return Promise.resolve();const i=s.extensions[this.name];return e.ior=void 0!==i.ior?i.ior:1.5,Promise.resolve()}}class v{constructor(t){this.parser=t,this.name=n.KHR_MATERIALS_SPECULAR}getMaterialType(e){const s=this.parser.json.materials[e];return s.extensions&&s.extensions[this.name]?t.MeshPhysicalMaterial:null}extendMaterialParams(e,s){const i=this.parser,n=i.json.materials[e];if(!n.extensions||!n.extensions[this.name])return Promise.resolve();const r=[],o=n.extensions[this.name];s.specularIntensity=void 0!==o.specularFactor?o.specularFactor:1,void 0!==o.specularTexture&&r.push(i.assignTexture(s,"specularIntensityMap",o.specularTexture));const c=o.specularColorFactor||[1,1,1];return s.specularColor=(new t.Color).setRGB(c[0],c[1],c[2],t.LinearSRGBColorSpace),void 0!==o.specularColorTexture&&r.push(i.assignTexture(s,"specularColorMap",o.specularColorTexture,t.SRGBColorSpace)),Promise.all(r)}}class w{constructor(t){this.parser=t,this.name=n.EXT_MATERIALS_BUMP}getMaterialType(e){const s=this.parser.json.materials[e];return s.extensions&&s.extensions[this.name]?t.MeshPhysicalMaterial:null}extendMaterialParams(t,e){const s=this.parser,i=s.json.materials[t];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();const n=[],r=i.extensions[this.name];return e.bumpScale=void 0!==r.bumpFactor?r.bumpFactor:1,void 0!==r.bumpTexture&&n.push(s.assignTexture(e,"bumpMap",r.bumpTexture)),Promise.all(n)}}class T{constructor(t){this.parser=t,this.name=n.KHR_MATERIALS_ANISOTROPY}getMaterialType(e){const s=this.parser.json.materials[e];return s.extensions&&s.extensions[this.name]?t.MeshPhysicalMaterial:null}extendMaterialParams(t,e){const s=this.parser,i=s.json.materials[t];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();const n=[],r=i.extensions[this.name];return void 0!==r.anisotropyStrength&&(e.anisotropy=r.anisotropyStrength),void 0!==r.anisotropyRotation&&(e.anisotropyRotation=r.anisotropyRotation),void 0!==r.anisotropyTexture&&n.push(s.assignTexture(e,"anisotropyMap",r.anisotropyTexture)),Promise.all(n)}}class _{constructor(t){this.parser=t,this.name=n.KHR_TEXTURE_BASISU}loadTexture(t){const e=this.parser,s=e.json,i=s.textures[t];if(!i.extensions||!i.extensions[this.name])return null;const n=i.extensions[this.name],r=e.options.ktx2Loader;if(!r){if(s.extensionsRequired&&s.extensionsRequired.indexOf(this.name)>=0)throw new Error("THREE.GLTFLoader: setKTX2Loader must be called before loading KTX2 textures");return null}return e.loadTextureImage(t,n.source,r)}}class E{constructor(t){this.parser=t,this.name=n.EXT_TEXTURE_WEBP}loadTexture(t){const e=this.name,s=this.parser,i=s.json,n=i.textures[t];if(!n.extensions||!n.extensions[e])return null;const r=n.extensions[e],o=i.images[r.source];let c=s.textureLoader;if(o.uri){const t=s.options.manager.getHandler(o.uri);null!==t&&(c=t)}return s.loadTextureImage(t,r.source,c)}}class p{constructor(t){this.parser=t,this.name=n.EXT_TEXTURE_AVIF}loadTexture(t){const e=this.name,s=this.parser,i=s.json,n=i.textures[t];if(!n.extensions||!n.extensions[e])return null;const r=n.extensions[e],o=i.images[r.source];let c=s.textureLoader;if(o.uri){const t=s.options.manager.getHandler(o.uri);null!==t&&(c=t)}return s.loadTextureImage(t,r.source,c)}}class R{constructor(t){this.name=n.EXT_MESHOPT_COMPRESSION,this.parser=t}loadBufferView(t){const e=this.parser.json,s=e.bufferViews[t];if(s.extensions&&s.extensions[this.name]){const t=s.extensions[this.name],i=this.parser.getDependency("buffer",t.buffer),n=this.parser.options.meshoptDecoder;if(!n||!n.supported){if(e.extensionsRequired&&e.extensionsRequired.indexOf(this.name)>=0)throw new Error("THREE.GLTFLoader: setMeshoptDecoder must be called before loading compressed files");return null}return i.then(function(e){const s=t.byteOffset||0,i=t.byteLength||0,r=t.count,o=t.byteStride,c=new Uint8Array(e,s,i);return n.decodeGltfBufferAsync?n.decodeGltfBufferAsync(r,o,c,t.mode,t.filter).then(function(t){return t.buffer}):n.ready.then(function(){const e=new ArrayBuffer(r*o);return n.decodeGltfBuffer(new Uint8Array(e),r,o,c,t.mode,t.filter),e})})}return null}}class A{constructor(t){this.name=n.EXT_MESH_GPU_INSTANCING,this.parser=t}createNodeMesh(e){const s=this.parser.json,i=s.nodes[e];if(!i.extensions||!i.extensions[this.name]||void 0===i.mesh)return null;const n=s.meshes[i.mesh];for(const t of n.primitives)if(t.mode!==N.TRIANGLES&&t.mode!==N.TRIANGLE_STRIP&&t.mode!==N.TRIANGLE_FAN&&void 0!==t.mode)return null;const r=i.extensions[this.name].attributes,o=[],c={};for(const t in r)o.push(this.parser.getDependency("accessor",r[t]).then(e=>(c[t]=e,c[t])));return o.length<1?null:(o.push(this.parser.createNodeMesh(e)),Promise.all(o).then(e=>{const s=e.pop(),i=s.isGroup?s.children:[s],n=e[0].count,r=[];for(const e of i){const s=new t.Matrix4,i=new t.Vector3,o=new t.Quaternion,a=new t.Vector3(1,1,1),u=new t.InstancedMesh(e.geometry,e.material,n);for(let t=0;t<n;t++)c.TRANSLATION&&i.fromBufferAttribute(c.TRANSLATION,t),c.ROTATION&&o.fromBufferAttribute(c.ROTATION,t),c.SCALE&&a.fromBufferAttribute(c.SCALE,t),u.setMatrixAt(t,s.compose(i,o,a));for(const s in c)if("_COLOR_0"===s){const e=c[s];u.instanceColor=new t.InstancedBufferAttribute(e.array,e.itemSize,e.normalized)}else"TRANSLATION"!==s&&"ROTATION"!==s&&"SCALE"!==s&&e.geometry.setAttribute(s,c[s]);t.Object3D.prototype.copy.call(u,e),this.parser.assignFinalMaterial(u),r.push(u)}return s.isGroup?(s.clear(),s.add(...r),s):r[0]}))}}const P="glTF",M=1313821514,L=5130562;class g{constructor(t){this.name=n.KHR_BINARY_GLTF,this.content=null,this.body=null;const e=new DataView(t,0,12),s=new TextDecoder;if(this.header={magic:s.decode(new Uint8Array(t.slice(0,4))),version:e.getUint32(4,!0),length:e.getUint32(8,!0)},this.header.magic!==P)throw new Error("THREE.GLTFLoader: Unsupported glTF-Binary header.");if(this.header.version<2)throw new Error("THREE.GLTFLoader: Legacy binary file detected.");const i=this.header.length-12,r=new DataView(t,12);let o=0;for(;o<i;){const e=r.getUint32(o,!0);o+=4;const i=r.getUint32(o,!0);if(o+=4,i===M){const i=new Uint8Array(t,12+o,e);this.content=s.decode(i)}else if(i===L){const s=12+o;this.body=t.slice(s,s+e)}o+=e}if(null===this.content)throw new Error("THREE.GLTFLoader: JSON content not found.")}}class I{constructor(t,e){if(!e)throw new Error("THREE.GLTFLoader: No DRACOLoader instance provided.");this.name=n.KHR_DRACO_MESH_COMPRESSION,this.json=t,this.dracoLoader=e,this.dracoLoader.preload()}decodePrimitive(e,s){const i=this.json,n=this.dracoLoader,r=e.extensions[this.name].bufferView,o=e.extensions[this.name].attributes,c={},a={},u={};for(const t in o){const e=C[t]||t.toLowerCase();c[e]=o[t]}for(const t in e.attributes){const s=C[t]||t.toLowerCase();if(void 0!==o[t]){const n=i.accessors[e.attributes[t]],r=x[n.componentType];u[s]=r.name,a[s]=!0===n.normalized}}return s.getDependency("bufferView",r).then(function(e){return new Promise(function(s,i){n.decodeDracoFile(e,function(t){for(const e in t.attributes){const s=t.attributes[e],i=a[e];void 0!==i&&(s.normalized=i)}s(t)},c,u,t.LinearSRGBColorSpace,i)})})}}class S{constructor(){this.name=n.KHR_TEXTURE_TRANSFORM}extendTexture(t,e){return void 0!==e.texCoord&&e.texCoord!==t.channel||void 0!==e.offset||void 0!==e.rotation||void 0!==e.scale?(t=t.clone(),void 0!==e.texCoord&&(t.channel=e.texCoord),void 0!==e.offset&&t.offset.fromArray(e.offset),void 0!==e.rotation&&(t.rotation=e.rotation),void 0!==e.scale&&t.repeat.fromArray(e.scale),t.needsUpdate=!0,t):t}}class y{constructor(){this.name=n.KHR_MESH_QUANTIZATION}}class b extends t.Interpolant{constructor(t,e,s,i){super(t,e,s,i)}copySampleValue_(t){const e=this.resultBuffer,s=this.sampleValues,i=this.valueSize,n=t*i*3+i;for(let t=0;t!==i;t++)e[t]=s[n+t];return e}interpolate_(t,e,s,i){const n=this.resultBuffer,r=this.sampleValues,o=this.valueSize,c=2*o,a=3*o,u=i-e,h=(s-e)/u,f=h*h,l=f*h,d=t*a,m=d-a,v=-2*l+3*f,w=l-f,T=1-v,_=w-f+h;for(let t=0;t!==o;t++){const e=r[m+t+o],s=r[m+t+c]*u,i=r[d+t+o],a=r[d+t]*u;n[t]=T*e+_*s+v*i+w*a}return n}}const O=new t.Quaternion;class H extends b{interpolate_(t,e,s,i){const n=super.interpolate_(t,e,s,i);return O.fromArray(n).normalize().toArray(n),n}}const N={FLOAT:5126,FLOAT_MAT3:35675,FLOAT_MAT4:35676,FLOAT_VEC2:35664,FLOAT_VEC3:35665,FLOAT_VEC4:35666,LINEAR:9729,REPEAT:10497,SAMPLER_2D:35678,POINTS:0,LINES:1,LINE_LOOP:2,LINE_STRIP:3,TRIANGLES:4,TRIANGLE_STRIP:5,TRIANGLE_FAN:6,UNSIGNED_BYTE:5121,UNSIGNED_SHORT:5123},x={5120:Int8Array,5121:Uint8Array,5122:Int16Array,5123:Uint16Array,5125:Uint32Array,5126:Float32Array},k={9728:t.NearestFilter,9729:t.LinearFilter,9984:t.NearestMipmapNearestFilter,9985:t.LinearMipmapNearestFilter,9986:t.NearestMipmapLinearFilter,9987:t.LinearMipmapLinearFilter},K={33071:t.ClampToEdgeWrapping,33648:t.MirroredRepeatWrapping,10497:t.RepeatWrapping},U={SCALAR:1,VEC2:2,VEC3:3,VEC4:4,MAT2:4,MAT3:9,MAT4:16},C={POSITION:"position",NORMAL:"normal",TANGENT:"tangent",TEXCOORD_0:"uv",TEXCOORD_1:"uv1",TEXCOORD_2:"uv2",TEXCOORD_3:"uv3",COLOR_0:"color",WEIGHTS_0:"skinWeight",JOINTS_0:"skinIndex"},F={scale:"scale",translation:"position",rotation:"quaternion",weights:"morphTargetInfluences"},G={CUBICSPLINE:void 0,LINEAR:t.InterpolateLinear,STEP:t.InterpolateDiscrete},D="OPAQUE",V="MASK",X="BLEND";function B(e){return void 0===e.DefaultMaterial&&(e.DefaultMaterial=new t.MeshStandardMaterial({color:16777215,emissive:0,metalness:1,roughness:1,transparent:!1,depthTest:!0,side:t.FrontSide})),e.DefaultMaterial}function j(t,e,s){for(const i in s.extensions)void 0===t[i]&&(e.userData.gltfExtensions=e.userData.gltfExtensions||{},e.userData.gltfExtensions[i]=s.extensions[i])}function q(t,e){void 0!==e.extras&&"object"==typeof e.extras&&Object.assign(t.userData,e.extras)}function J(t,e){if(t.updateMorphTargets(),void 0!==e.weights)for(let s=0,i=e.weights.length;s<i;s++)t.morphTargetInfluences[s]=e.weights[s];if(e.extras&&Array.isArray(e.extras.targetNames)){const s=e.extras.targetNames;if(t.morphTargetInfluences.length===s.length){t.morphTargetDictionary={};for(let e=0,i=s.length;e<i;e++)t.morphTargetDictionary[s[e]]=e}}}function z(t){let e;const s=t.extensions&&t.extensions[n.KHR_DRACO_MESH_COMPRESSION];if(e=s?"draco:"+s.bufferView+":"+s.indices+":"+W(s.attributes):t.indices+":"+W(t.attributes)+":"+t.mode,void 0!==t.targets)for(let s=0,i=t.targets.length;s<i;s++)e+=":"+W(t.targets[s]);return e}function W(t){let e="";const s=Object.keys(t).sort();for(let i=0,n=s.length;i<n;i++)e+=s[i]+":"+t[s[i]]+";";return e}function Y(t){switch(t){case Int8Array:return 1/127;case Uint8Array:return 1/255;case Int16Array:return 1/32767;case Uint16Array:return 1/65535;default:throw new Error("THREE.GLTFLoader: Unsupported normalized accessor component type.")}}const $=new t.Matrix4;class Q{constructor(e={},s={}){this.json=e,this.extensions={},this.plugins={},this.options=s,this.cache=new i,this.associations=new Map,this.primitiveCache={},this.nodeCache={},this.meshCache={refs:{},uses:{}},this.cameraCache={refs:{},uses:{}},this.lightCache={refs:{},uses:{}},this.sourceCache={},this.textureCache={},this.nodeNamesUsed={};let n=!1,r=-1,o=!1,c=-1;if("undefined"!=typeof navigator){const t=navigator.userAgent;n=!0===/^((?!chrome|android).)*safari/i.test(t);const e=t.match(/Version\/(\d+)/);r=n&&e?parseInt(e[1],10):-1,o=t.indexOf("Firefox")>-1,c=o?t.match(/Firefox\/([0-9]+)\./)[1]:-1}"undefined"==typeof createImageBitmap||n&&r<17||o&&c<98?this.textureLoader=new t.TextureLoader(this.options.manager):this.textureLoader=new t.ImageBitmapLoader(this.options.manager),this.textureLoader.setCrossOrigin(this.options.crossOrigin),this.textureLoader.setRequestHeader(this.options.requestHeader),this.fileLoader=new t.FileLoader(this.options.manager),this.fileLoader.setResponseType("arraybuffer"),"use-credentials"===this.options.crossOrigin&&this.fileLoader.setWithCredentials(!0)}setExtensions(t){this.extensions=t}setPlugins(t){this.plugins=t}parse(t,e){const s=this,i=this.json,n=this.extensions;this.cache.removeAll(),this.nodeCache={},this.l(function(t){return t.i&&t.i()}),Promise.all(this.l(function(t){return t.beforeRoot&&t.beforeRoot()})).then(function(){return Promise.all([s.getDependencies("scene"),s.getDependencies("animation"),s.getDependencies("camera")])}).then(function(e){const r={scene:e[0][i.scene||0],scenes:e[0],animations:e[1],cameras:e[2],asset:i.asset,parser:s,userData:{}};return j(n,r,i),q(r,i),Promise.all(s.l(function(t){return t.afterRoot&&t.afterRoot(r)})).then(function(){for(const t of r.scenes)t.updateMatrixWorld();t(r)})}).catch(e)}i(){const t=this.json.nodes||[],e=this.json.skins||[],s=this.json.meshes||[];for(let s=0,i=e.length;s<i;s++){const i=e[s].joints;for(let e=0,s=i.length;e<s;e++)t[i[e]].isBone=!0}for(let e=0,i=t.length;e<i;e++){const i=t[e];void 0!==i.mesh&&(this.o(this.meshCache,i.mesh),void 0!==i.skin&&(s[i.mesh].isSkinnedMesh=!0)),void 0!==i.camera&&this.o(this.cameraCache,i.camera)}}o(t,e){void 0!==e&&(void 0===t.refs[e]&&(t.refs[e]=t.uses[e]=0),t.refs[e]++)}h(t,e,s){if(t.refs[e]<=1)return s;const i=s.clone(),n=(t,e)=>{const s=this.associations.get(t);null!=s&&this.associations.set(e,s);for(const[s,i]of t.children.entries())n(i,e.children[s])};return n(s,i),i.name+="_instance_"+t.uses[e]++,i}m(t){const e=Object.values(this.plugins);e.push(this);for(let s=0;s<e.length;s++){const i=t(e[s]);if(i)return i}return null}l(t){const e=Object.values(this.plugins);e.unshift(this);const s=[];for(let i=0;i<e.length;i++){const n=t(e[i]);n&&s.push(n)}return s}getDependency(t,e){const s=t+":"+e;let i=this.cache.get(s);if(!i){switch(t){case"scene":i=this.loadScene(e);break;case"node":i=this.m(function(t){return t.loadNode&&t.loadNode(e)});break;case"mesh":i=this.m(function(t){return t.loadMesh&&t.loadMesh(e)});break;case"accessor":i=this.loadAccessor(e);break;case"bufferView":i=this.m(function(t){return t.loadBufferView&&t.loadBufferView(e)});break;case"buffer":i=this.loadBuffer(e);break;case"material":i=this.m(function(t){return t.loadMaterial&&t.loadMaterial(e)});break;case"texture":i=this.m(function(t){return t.loadTexture&&t.loadTexture(e)});break;case"skin":i=this.loadSkin(e);break;case"animation":i=this.m(function(t){return t.loadAnimation&&t.loadAnimation(e)});break;case"camera":i=this.loadCamera(e);break;default:if(i=this.m(function(s){return s!=this&&s.getDependency&&s.getDependency(t,e)}),!i)throw new Error("Unknown type: "+t)}this.cache.add(s,i)}return i}getDependencies(t){let e=this.cache.get(t);if(!e){const s=this,i=this.json[t+("mesh"===t?"es":"s")]||[];e=Promise.all(i.map(function(e,i){return s.getDependency(t,i)})),this.cache.add(t,e)}return e}loadBuffer(e){const s=this.json.buffers[e],i=this.fileLoader;if(s.type&&"arraybuffer"!==s.type)throw new Error("THREE.GLTFLoader: "+s.type+" buffer type is not supported.");if(void 0===s.uri&&0===e)return Promise.resolve(this.extensions[n.KHR_BINARY_GLTF].body);const r=this.options;return new Promise(function(e,n){i.load(t.LoaderUtils.resolveURL(s.uri,r.path),e,void 0,function(){n(new Error('THREE.GLTFLoader: Failed to load buffer "'+s.uri+'".'))})})}loadBufferView(t){const e=this.json.bufferViews[t];return this.getDependency("buffer",e.buffer).then(function(t){const s=e.byteLength||0,i=e.byteOffset||0;return t.slice(i,i+s)})}loadAccessor(e){const s=this,i=this.json,n=this.json.accessors[e];if(void 0===n.bufferView&&void 0===n.sparse){const e=U[n.type],s=x[n.componentType],i=!0===n.normalized,r=new s(n.count*e);return Promise.resolve(new t.BufferAttribute(r,e,i))}const r=[];return void 0!==n.bufferView?r.push(this.getDependency("bufferView",n.bufferView)):r.push(null),void 0!==n.sparse&&(r.push(this.getDependency("bufferView",n.sparse.indices.bufferView)),r.push(this.getDependency("bufferView",n.sparse.values.bufferView))),Promise.all(r).then(function(e){const r=e[0],o=U[n.type],c=x[n.componentType],a=c.BYTES_PER_ELEMENT,u=a*o,h=n.byteOffset||0,f=void 0!==n.bufferView?i.bufferViews[n.bufferView].byteStride:void 0,l=!0===n.normalized;let d,m;if(f&&f!==u){const e=Math.floor(h/f),i="InterleavedBuffer:"+n.bufferView+":"+n.componentType+":"+e+":"+n.count;let u=s.cache.get(i);u||(d=new c(r,e*f,n.count*f/a),u=new t.InterleavedBuffer(d,f/a),s.cache.add(i,u)),m=new t.InterleavedBufferAttribute(u,o,h%f/a,l)}else d=null===r?new c(n.count*o):new c(r,h,n.count*o),m=new t.BufferAttribute(d,o,l);if(void 0!==n.sparse){const s=U.SCALAR,i=x[n.sparse.indices.componentType],a=n.sparse.indices.byteOffset||0,u=n.sparse.values.byteOffset||0,h=new i(e[1],a,n.sparse.count*s),f=new c(e[2],u,n.sparse.count*o);null!==r&&(m=new t.BufferAttribute(m.array.slice(),m.itemSize,m.normalized)),m.normalized=!1;for(let t=0,e=h.length;t<e;t++){const e=h[t];if(m.setX(e,f[t*o]),o>=2&&m.setY(e,f[t*o+1]),o>=3&&m.setZ(e,f[t*o+2]),o>=4&&m.setW(e,f[t*o+3]),o>=5)throw new Error("THREE.GLTFLoader: Unsupported itemSize in sparse BufferAttribute.")}m.normalized=l}return m})}loadTexture(t){const e=this.json,s=this.options,i=e.textures[t].source,n=e.images[i];let r=this.textureLoader;if(n.uri){const t=s.manager.getHandler(n.uri);null!==t&&(r=t)}return this.loadTextureImage(t,i,r)}loadTextureImage(e,s,i){const n=this,r=this.json,o=r.textures[e],c=r.images[s],a=(c.uri||c.bufferView)+":"+o.sampler;if(this.textureCache[a])return this.textureCache[a];const u=this.loadImageSource(s,i).then(function(s){s.flipY=!1,s.name=o.name||c.name||"",""===s.name&&"string"==typeof c.uri&&!1===c.uri.startsWith("data:image/")&&(s.name=c.uri);const i=(r.samplers||{})[o.sampler]||{};return s.magFilter=k[i.magFilter]||t.LinearFilter,s.minFilter=k[i.minFilter]||t.LinearMipmapLinearFilter,s.wrapS=K[i.wrapS]||t.RepeatWrapping,s.wrapT=K[i.wrapT]||t.RepeatWrapping,s.generateMipmaps=!s.isCompressedTexture&&s.minFilter!==t.NearestFilter&&s.minFilter!==t.LinearFilter,n.associations.set(s,{textures:e}),s}).catch(function(){return null});return this.textureCache[a]=u,u}loadImageSource(e,s){const i=this,n=this.json,r=this.options;if(void 0!==this.sourceCache[e])return this.sourceCache[e].then(t=>t.clone());const o=n.images[e],c=self.URL||self.webkitURL;let a=o.uri||"",u=!1;if(void 0!==o.bufferView)a=i.getDependency("bufferView",o.bufferView).then(function(t){u=!0;const e=new Blob([t],{type:o.mimeType});return a=c.createObjectURL(e),a});else if(void 0===o.uri)throw new Error("THREE.GLTFLoader: Image "+e+" is missing URI and bufferView");const h=Promise.resolve(a).then(function(e){return new Promise(function(i,n){let o=i;!0===s.isImageBitmapLoader&&(o=function(e){const s=new t.Texture(e);s.needsUpdate=!0,i(s)}),s.load(t.LoaderUtils.resolveURL(e,r.path),o,void 0,n)})}).then(function(t){var e;return!0===u&&c.revokeObjectURL(a),q(t,o),t.userData.mimeType=o.mimeType||((e=o.uri).search(/\.jpe?g($|\?)/i)>0||0===e.search(/^data\:image\/jpeg/)?"image/jpeg":e.search(/\.webp($|\?)/i)>0||0===e.search(/^data\:image\/webp/)?"image/webp":e.search(/\.ktx2($|\?)/i)>0||0===e.search(/^data\:image\/ktx2/)?"image/ktx2":"image/png"),t}).catch(function(t){throw t});return this.sourceCache[e]=h,h}assignTexture(t,e,s,i){const r=this;return this.getDependency("texture",s.index).then(function(o){if(!o)return null;if(void 0!==s.texCoord&&s.texCoord>0&&((o=o.clone()).channel=s.texCoord),r.extensions[n.KHR_TEXTURE_TRANSFORM]){const t=void 0!==s.extensions?s.extensions[n.KHR_TEXTURE_TRANSFORM]:void 0;if(t){const e=r.associations.get(o);o=r.extensions[n.KHR_TEXTURE_TRANSFORM].extendTexture(o,t),r.associations.set(o,e)}}return void 0!==i&&(o.colorSpace=i),t[e]=o,o})}assignFinalMaterial(e){const s=e.geometry;let i=e.material;const n=void 0===s.attributes.tangent,r=void 0!==s.attributes.color,o=void 0===s.attributes.normal;if(e.isPoints){const e="PointsMaterial:"+i.uuid;let s=this.cache.get(e);s||(s=new t.PointsMaterial,t.Material.prototype.copy.call(s,i),s.color.copy(i.color),s.map=i.map,s.sizeAttenuation=!1,this.cache.add(e,s)),i=s}else if(e.isLine){const e="LineBasicMaterial:"+i.uuid;let s=this.cache.get(e);s||(s=new t.LineBasicMaterial,t.Material.prototype.copy.call(s,i),s.color.copy(i.color),s.map=i.map,this.cache.add(e,s)),i=s}if(n||r||o){let t="ClonedMaterial:"+i.uuid+":";n&&(t+="derivative-tangents:"),r&&(t+="vertex-colors:"),o&&(t+="flat-shading:");let e=this.cache.get(t);e||(e=i.clone(),r&&(e.vertexColors=!0),o&&(e.flatShading=!0),n&&(e.normalScale&&(e.normalScale.y*=-1),e.clearcoatNormalScale&&(e.clearcoatNormalScale.y*=-1)),this.cache.add(t,e),this.associations.set(e,this.associations.get(i))),i=e}e.material=i}getMaterialType(){return t.MeshStandardMaterial}loadMaterial(e){const s=this,i=this.json,r=this.extensions,o=i.materials[e];let c;const a={},u=[];if((o.extensions||{})[n.KHR_MATERIALS_UNLIT]){const t=r[n.KHR_MATERIALS_UNLIT];c=t.getMaterialType(),u.push(t.extendParams(a,o,s))}else{const i=o.pbrMetallicRoughness||{};if(a.color=new t.Color(1,1,1),a.opacity=1,Array.isArray(i.baseColorFactor)){const e=i.baseColorFactor;a.color.setRGB(e[0],e[1],e[2],t.LinearSRGBColorSpace),a.opacity=e[3]}void 0!==i.baseColorTexture&&u.push(s.assignTexture(a,"map",i.baseColorTexture,t.SRGBColorSpace)),a.metalness=void 0!==i.metallicFactor?i.metallicFactor:1,a.roughness=void 0!==i.roughnessFactor?i.roughnessFactor:1,void 0!==i.metallicRoughnessTexture&&(u.push(s.assignTexture(a,"metalnessMap",i.metallicRoughnessTexture)),u.push(s.assignTexture(a,"roughnessMap",i.metallicRoughnessTexture))),c=this.m(function(t){return t.getMaterialType&&t.getMaterialType(e)}),u.push(Promise.all(this.l(function(t){return t.extendMaterialParams&&t.extendMaterialParams(e,a)})))}!0===o.doubleSided&&(a.side=t.DoubleSide);const h=o.alphaMode||D;if(h===X?(a.transparent=!0,a.depthWrite=!1):(a.transparent=!1,h===V&&(a.alphaTest=void 0!==o.alphaCutoff?o.alphaCutoff:.5)),void 0!==o.normalTexture&&c!==t.MeshBasicMaterial&&(u.push(s.assignTexture(a,"normalMap",o.normalTexture)),a.normalScale=new t.Vector2(1,1),void 0!==o.normalTexture.scale)){const t=o.normalTexture.scale;a.normalScale.set(t,t)}if(void 0!==o.occlusionTexture&&c!==t.MeshBasicMaterial&&(u.push(s.assignTexture(a,"aoMap",o.occlusionTexture)),void 0!==o.occlusionTexture.strength&&(a.aoMapIntensity=o.occlusionTexture.strength)),void 0!==o.emissiveFactor&&c!==t.MeshBasicMaterial){const e=o.emissiveFactor;a.emissive=(new t.Color).setRGB(e[0],e[1],e[2],t.LinearSRGBColorSpace)}return void 0!==o.emissiveTexture&&c!==t.MeshBasicMaterial&&u.push(s.assignTexture(a,"emissiveMap",o.emissiveTexture,t.SRGBColorSpace)),Promise.all(u).then(function(){const t=new c(a);return o.name&&(t.name=o.name),q(t,o),s.associations.set(t,{materials:e}),o.extensions&&j(r,t,o),t})}createUniqueName(e){const s=t.PropertyBinding.sanitizeNodeName(e||"");return s in this.nodeNamesUsed?s+"_"+ ++this.nodeNamesUsed[s]:(this.nodeNamesUsed[s]=0,s)}loadGeometries(e){const s=this,i=this.extensions,r=this.primitiveCache;function o(t){return i[n.KHR_DRACO_MESH_COMPRESSION].decodePrimitive(t,s).then(function(e){return Z(e,t,s)})}const c=[];for(let i=0,a=e.length;i<a;i++){const a=e[i],u=z(a),h=r[u];if(h)c.push(h.promise);else{let e;e=a.extensions&&a.extensions[n.KHR_DRACO_MESH_COMPRESSION]?o(a):Z(new t.BufferGeometry,a,s),r[u]={primitive:a,promise:e},c.push(e)}}return Promise.all(c)}loadMesh(s){const i=this,n=this.json,r=this.extensions,o=n.meshes[s],c=o.primitives,a=[];for(let t=0,e=c.length;t<e;t++){const e=void 0===c[t].material?B(this.cache):this.getDependency("material",c[t].material);a.push(e)}return a.push(i.loadGeometries(c)),Promise.all(a).then(function(n){const a=n.slice(0,n.length-1),u=n[n.length-1],h=[];for(let n=0,f=u.length;n<f;n++){const f=u[n],l=c[n];let d;const m=a[n];if(l.mode===N.TRIANGLES||l.mode===N.TRIANGLE_STRIP||l.mode===N.TRIANGLE_FAN||void 0===l.mode)d=!0===o.isSkinnedMesh?new t.SkinnedMesh(f,m):new t.Mesh(f,m),!0===d.isSkinnedMesh&&d.normalizeSkinWeights(),l.mode===N.TRIANGLE_STRIP?d.geometry=e.toTrianglesDrawMode(d.geometry,t.TriangleStripDrawMode):l.mode===N.TRIANGLE_FAN&&(d.geometry=e.toTrianglesDrawMode(d.geometry,t.TriangleFanDrawMode));else if(l.mode===N.LINES)d=new t.LineSegments(f,m);else if(l.mode===N.LINE_STRIP)d=new t.Line(f,m);else if(l.mode===N.LINE_LOOP)d=new t.LineLoop(f,m);else{if(l.mode!==N.POINTS)throw new Error("THREE.GLTFLoader: Primitive mode unsupported: "+l.mode);d=new t.Points(f,m)}Object.keys(d.geometry.morphAttributes).length>0&&J(d,o),d.name=i.createUniqueName(o.name||"mesh_"+s),q(d,o),l.extensions&&j(r,d,l),i.assignFinalMaterial(d),h.push(d)}for(let t=0,e=h.length;t<e;t++)i.associations.set(h[t],{meshes:s,primitives:t});if(1===h.length)return o.extensions&&j(r,h[0],o),h[0];const f=new t.Group;o.extensions&&j(r,f,o),i.associations.set(f,{meshes:s});for(let t=0,e=h.length;t<e;t++)f.add(h[t]);return f})}loadCamera(e){let s;const i=this.json.cameras[e],n=i[i.type];if(n)return"perspective"===i.type?s=new t.PerspectiveCamera(t.MathUtils.radToDeg(n.yfov),n.aspectRatio||1,n.znear||1,n.zfar||2e6):"orthographic"===i.type&&(s=new t.OrthographicCamera(-n.xmag,n.xmag,n.ymag,-n.ymag,n.znear,n.zfar)),i.name&&(s.name=this.createUniqueName(i.name)),q(s,i),Promise.resolve(s)}loadSkin(e){const s=this.json.skins[e],i=[];for(let t=0,e=s.joints.length;t<e;t++)i.push(this.v(s.joints[t]));return void 0!==s.inverseBindMatrices?i.push(this.getDependency("accessor",s.inverseBindMatrices)):i.push(null),Promise.all(i).then(function(e){const s=e.pop(),i=e,n=[],r=[];for(let e=0,o=i.length;e<o;e++){const o=i[e];if(o){n.push(o);const i=new t.Matrix4;null!==s&&i.fromArray(s.array,16*e),r.push(i)}}return new t.Skeleton(n,r)})}loadAnimation(e){const s=this.json,i=this,n=s.animations[e],r=n.name?n.name:"animation_"+e,o=[],c=[],a=[],u=[],h=[];for(let t=0,e=n.channels.length;t<e;t++){const e=n.channels[t],s=n.samplers[e.sampler],i=e.target,r=i.node,f=void 0!==n.parameters?n.parameters[s.input]:s.input,l=void 0!==n.parameters?n.parameters[s.output]:s.output;void 0!==i.node&&(o.push(this.getDependency("node",r)),c.push(this.getDependency("accessor",f)),a.push(this.getDependency("accessor",l)),u.push(s),h.push(i))}return Promise.all([Promise.all(o),Promise.all(c),Promise.all(a),Promise.all(u),Promise.all(h)]).then(function(e){const s=e[0],n=e[1],o=e[2],c=e[3],a=e[4],u=[];for(let t=0,e=s.length;t<e;t++){const e=s[t],r=n[t],h=o[t],f=c[t],l=a[t];if(void 0===e)continue;e.updateMatrix&&e.updateMatrix();const d=i.T(e,r,h,f,l);if(d)for(let t=0;t<d.length;t++)u.push(d[t])}return new t.AnimationClip(r,void 0,u)})}createNodeMesh(t){const e=this.json,s=this,i=e.nodes[t];return void 0===i.mesh?null:s.getDependency("mesh",i.mesh).then(function(t){const e=s.h(s.meshCache,i.mesh,t);return void 0!==i.weights&&e.traverse(function(t){if(t.isMesh)for(let e=0,s=i.weights.length;e<s;e++)t.morphTargetInfluences[e]=i.weights[e]}),e})}loadNode(t){const e=this,s=this.json.nodes[t],i=e.v(t),n=[],r=s.children||[];for(let t=0,s=r.length;t<s;t++)n.push(e.getDependency("node",r[t]));const o=void 0===s.skin?Promise.resolve(null):e.getDependency("skin",s.skin);return Promise.all([i,Promise.all(n),o]).then(function(t){const e=t[0],s=t[1],i=t[2];null!==i&&e.traverse(function(t){t.isSkinnedMesh&&t.bind(i,$)});for(let t=0,i=s.length;t<i;t++)e.add(s[t]);return e})}v(e){const s=this.json,i=this.extensions,n=this;if(void 0!==this.nodeCache[e])return this.nodeCache[e];const r=s.nodes[e],o=r.name?n.createUniqueName(r.name):"",c=[],a=n.m(function(t){return t.createNodeMesh&&t.createNodeMesh(e)});return a&&c.push(a),void 0!==r.camera&&c.push(n.getDependency("camera",r.camera).then(function(t){return n.h(n.cameraCache,r.camera,t)})),n.l(function(t){return t.createNodeAttachment&&t.createNodeAttachment(e)}).forEach(function(t){c.push(t)}),this.nodeCache[e]=Promise.all(c).then(function(s){let c;if(c=!0===r.isBone?new t.Bone:s.length>1?new t.Group:1===s.length?s[0]:new t.Object3D,c!==s[0])for(let t=0,e=s.length;t<e;t++)c.add(s[t]);if(r.name&&(c.userData.name=r.name,c.name=o),q(c,r),r.extensions&&j(i,c,r),void 0!==r.matrix){const e=new t.Matrix4;e.fromArray(r.matrix),c.applyMatrix4(e)}else void 0!==r.translation&&c.position.fromArray(r.translation),void 0!==r.rotation&&c.quaternion.fromArray(r.rotation),void 0!==r.scale&&c.scale.fromArray(r.scale);if(n.associations.has(c)){if(void 0!==r.mesh&&n.meshCache.refs[r.mesh]>1){const t=n.associations.get(c);n.associations.set(c,{...t})}}else n.associations.set(c,{});return n.associations.get(c).nodes=e,c}),this.nodeCache[e]}loadScene(e){const s=this.extensions,i=this.json.scenes[e],n=this,r=new t.Group;i.name&&(r.name=n.createUniqueName(i.name)),q(r,i),i.extensions&&j(s,r,i);const o=i.nodes||[],c=[];for(let t=0,e=o.length;t<e;t++)c.push(n.getDependency("node",o[t]));return Promise.all(c).then(function(e){for(let t=0,s=e.length;t<s;t++)r.add(e[t]);return n.associations=(e=>{const s=new Map;for(const[e,i]of n.associations)(e instanceof t.Material||e instanceof t.Texture)&&s.set(e,i);return e.traverse(t=>{const e=n.associations.get(t);null!=e&&s.set(t,e)}),s})(r),r})}T(e,s,i,n,r){const o=[],c=e.name?e.name:e.uuid,a=[];let u;switch(F[r.path]===F.weights?e.traverse(function(t){t.morphTargetInfluences&&a.push(t.name?t.name:t.uuid)}):a.push(c),F[r.path]){case F.weights:u=t.NumberKeyframeTrack;break;case F.rotation:u=t.QuaternionKeyframeTrack;break;case F.translation:case F.scale:u=t.VectorKeyframeTrack;break;default:if(1===i.itemSize)u=t.NumberKeyframeTrack;else u=t.VectorKeyframeTrack}const h=void 0!==n.interpolation?G[n.interpolation]:t.InterpolateLinear,f=this._(i);for(let t=0,e=a.length;t<e;t++){const e=new u(a[t]+"."+F[r.path],s.array,f,h);"CUBICSPLINE"===n.interpolation&&this.p(e),o.push(e)}return o}_(t){let e=t.array;if(t.normalized){const t=Y(e.constructor),s=new Float32Array(e.length);for(let i=0,n=e.length;i<n;i++)s[i]=e[i]*t;e=s}return e}p(e){e.createInterpolant=function(e){return new(this instanceof t.QuaternionKeyframeTrack?H:b)(this.times,this.values,this.getValueSize()/3,e)},e.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline=!0}}function Z(e,s,i){const n=s.attributes,r=[];function o(t,s){return i.getDependency("accessor",t).then(function(t){e.setAttribute(s,t)})}for(const t in n){const s=C[t]||t.toLowerCase();s in e.attributes||r.push(o(n[t],s))}if(void 0!==s.indices&&!e.index){const t=i.getDependency("accessor",s.indices).then(function(t){e.setIndex(t)});r.push(t)}return t.ColorManagement.workingColorSpace,t.LinearSRGBColorSpace,q(e,s),function(e,s,i){const n=s.attributes,r=new t.Box3;if(void 0===n.POSITION)return;{const e=i.json.accessors[n.POSITION],s=e.min,o=e.max;if(void 0===s||void 0===o)return;if(r.set(new t.Vector3(s[0],s[1],s[2]),new t.Vector3(o[0],o[1],o[2])),e.normalized){const t=Y(x[e.componentType]);r.min.multiplyScalar(t),r.max.multiplyScalar(t)}}const o=s.targets;if(void 0!==o){const e=new t.Vector3,s=new t.Vector3;for(let t=0,n=o.length;t<n;t++){const n=o[t];if(void 0!==n.POSITION){const t=i.json.accessors[n.POSITION],r=t.min,o=t.max;if(void 0!==r&&void 0!==o){if(s.setX(Math.max(Math.abs(r[0]),Math.abs(o[0]))),s.setY(Math.max(Math.abs(r[1]),Math.abs(o[1]))),s.setZ(Math.max(Math.abs(r[2]),Math.abs(o[2]))),t.normalized){const e=Y(x[t.componentType]);s.multiplyScalar(e)}e.max(s)}}}r.expandByVector(e)}e.boundingBox=r;const c=new t.Sphere;r.getCenter(c.center),c.radius=r.min.distanceTo(r.max)/2,e.boundingSphere=c}(e,s,i),Promise.all(r).then(function(){return void 0!==s.targets?function(t,e,s){let i=!1,n=!1,r=!1;for(let t=0,s=e.length;t<s;t++){const s=e[t];if(void 0!==s.POSITION&&(i=!0),void 0!==s.NORMAL&&(n=!0),void 0!==s.COLOR_0&&(r=!0),i&&n&&r)break}if(!i&&!n&&!r)return Promise.resolve(t);const o=[],c=[],a=[];for(let u=0,h=e.length;u<h;u++){const h=e[u];if(i){const e=void 0!==h.POSITION?s.getDependency("accessor",h.POSITION):t.attributes.position;o.push(e)}if(n){const e=void 0!==h.NORMAL?s.getDependency("accessor",h.NORMAL):t.attributes.normal;c.push(e)}if(r){const e=void 0!==h.COLOR_0?s.getDependency("accessor",h.COLOR_0):t.attributes.color;a.push(e)}}return Promise.all([Promise.all(o),Promise.all(c),Promise.all(a)]).then(function(e){const s=e[0],o=e[1],c=e[2];return i&&(t.morphAttributes.position=s),n&&(t.morphAttributes.normal=o),r&&(t.morphAttributes.color=c),t.morphTargetsRelative=!0,t})}(e,s.targets,i):e})}exports.GLTFLoader=s;
1
+ 'use strict';
2
+
3
+ Object.defineProperty(exports, '__esModule', { value: true });
4
+
5
+ var THREE = require('three');
6
+ var BufferGeometryUtils = require('../utils/BufferGeometryUtils.js');
7
+
8
+ /**
9
+ * A loader for the glTF 2.0 format.
10
+ *
11
+ * [glTF]{@link https://www.khronos.org/gltf/} (GL Transmission Format) is an [open format specification]{@link https://github.com/KhronosGroup/glTF/tree/main/specification/2.0}
12
+ * for efficient delivery and loading of 3D content. Assets may be provided either in JSON (.gltf) or binary (.glb)
13
+ * format. External files store textures (.jpg, .png) and additional binary data (.bin). A glTF asset may deliver
14
+ * one or more scenes, including meshes, materials, textures, skins, skeletons, morph targets, animations, lights,
15
+ * and/or cameras.
16
+ *
17
+ * `GLTFLoader` uses {@link ImageBitmapLoader} whenever possible. Be advised that image bitmaps are not
18
+ * automatically GC-collected when they are no longer referenced, and they require special handling during
19
+ * the disposal process.
20
+ *
21
+ * `GLTFLoader` supports the following glTF 2.0 extensions:
22
+ * - KHR_draco_mesh_compression
23
+ * - KHR_materials_clearcoat
24
+ * - KHR_materials_dispersion
25
+ * - KHR_materials_ior
26
+ * - KHR_materials_specular
27
+ * - KHR_materials_transmission
28
+ * - KHR_materials_iridescence
29
+ * - KHR_materials_unlit
30
+ * - KHR_materials_volume
31
+ * - KHR_mesh_quantization
32
+ * - KHR_lights_punctual
33
+ * - KHR_texture_basisu
34
+ * - KHR_texture_transform
35
+ * - EXT_texture_webp
36
+ * - EXT_meshopt_compression
37
+ * - EXT_mesh_gpu_instancing
38
+ *
39
+ * The following glTF 2.0 extension is supported by an external user plugin:
40
+ * - [KHR_materials_variants]{@link https://github.com/takahirox/three-gltf-extensions}
41
+ * - [MSFT_texture_dds]{@link https://github.com/takahirox/three-gltf-extensions}
42
+ *
43
+ * ```js
44
+ * const loader = new GLTFLoader();
45
+ *
46
+ * // Optional: Provide a DRACOLoader instance to decode compressed mesh data
47
+ * const dracoLoader = new DRACOLoader();
48
+ * dracoLoader.setDecoderPath( '/examples/jsm/libs/draco/' );
49
+ * loader.setDRACOLoader( dracoLoader );
50
+ *
51
+ * const gltf = await loader.loadAsync( 'models/gltf/duck/duck.gltf' );
52
+ * scene.add( gltf.scene );
53
+ * ```
54
+ *
55
+ * @augments Loader
56
+ * @three_import import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
57
+ */
58
+ class GLTFLoader extends THREE.Loader {
59
+
60
+ /**
61
+ * Constructs a new glTF loader.
62
+ *
63
+ * @param {LoadingManager} [manager] - The loading manager.
64
+ */
65
+ constructor( manager ) {
66
+
67
+ super( manager );
68
+
69
+ this.dracoLoader = null;
70
+ this.ktx2Loader = null;
71
+ this.meshoptDecoder = null;
72
+
73
+ this.pluginCallbacks = [];
74
+
75
+ this.register( function ( parser ) {
76
+
77
+ return new GLTFMaterialsClearcoatExtension( parser );
78
+
79
+ } );
80
+
81
+ this.register( function ( parser ) {
82
+
83
+ return new GLTFMaterialsDispersionExtension( parser );
84
+
85
+ } );
86
+
87
+ this.register( function ( parser ) {
88
+
89
+ return new GLTFTextureBasisUExtension( parser );
90
+
91
+ } );
92
+
93
+ this.register( function ( parser ) {
94
+
95
+ return new GLTFTextureWebPExtension( parser );
96
+
97
+ } );
98
+
99
+ this.register( function ( parser ) {
100
+
101
+ return new GLTFTextureAVIFExtension( parser );
102
+
103
+ } );
104
+
105
+ this.register( function ( parser ) {
106
+
107
+ return new GLTFMaterialsSheenExtension( parser );
108
+
109
+ } );
110
+
111
+ this.register( function ( parser ) {
112
+
113
+ return new GLTFMaterialsTransmissionExtension( parser );
114
+
115
+ } );
116
+
117
+ this.register( function ( parser ) {
118
+
119
+ return new GLTFMaterialsVolumeExtension( parser );
120
+
121
+ } );
122
+
123
+ this.register( function ( parser ) {
124
+
125
+ return new GLTFMaterialsIorExtension( parser );
126
+
127
+ } );
128
+
129
+ this.register( function ( parser ) {
130
+
131
+ return new GLTFMaterialsEmissiveStrengthExtension( parser );
132
+
133
+ } );
134
+
135
+ this.register( function ( parser ) {
136
+
137
+ return new GLTFMaterialsSpecularExtension( parser );
138
+
139
+ } );
140
+
141
+ this.register( function ( parser ) {
142
+
143
+ return new GLTFMaterialsIridescenceExtension( parser );
144
+
145
+ } );
146
+
147
+ this.register( function ( parser ) {
148
+
149
+ return new GLTFMaterialsAnisotropyExtension( parser );
150
+
151
+ } );
152
+
153
+ this.register( function ( parser ) {
154
+
155
+ return new GLTFMaterialsBumpExtension( parser );
156
+
157
+ } );
158
+
159
+ this.register( function ( parser ) {
160
+
161
+ return new GLTFLightsExtension( parser );
162
+
163
+ } );
164
+
165
+ this.register( function ( parser ) {
166
+
167
+ return new GLTFMeshoptCompression( parser );
168
+
169
+ } );
170
+
171
+ this.register( function ( parser ) {
172
+
173
+ return new GLTFMeshGpuInstancing( parser );
174
+
175
+ } );
176
+
177
+ }
178
+
179
+ /**
180
+ * Starts loading from the given URL and passes the loaded glTF asset
181
+ * to the `onLoad()` callback.
182
+ *
183
+ * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
184
+ * @param {function(GLTFLoader~LoadObject)} onLoad - Executed when the loading process has been finished.
185
+ * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
186
+ * @param {onErrorCallback} onError - Executed when errors occur.
187
+ */
188
+ load( url, onLoad, onProgress, onError ) {
189
+
190
+ const scope = this;
191
+
192
+ let resourcePath;
193
+
194
+ if ( this.resourcePath !== '' ) {
195
+
196
+ resourcePath = this.resourcePath;
197
+
198
+ } else if ( this.path !== '' ) {
199
+
200
+ // If a base path is set, resources will be relative paths from that plus the relative path of the gltf file
201
+ // Example path = 'https://my-cnd-server.com/', url = 'assets/models/model.gltf'
202
+ // resourcePath = 'https://my-cnd-server.com/assets/models/'
203
+ // referenced resource 'model.bin' will be loaded from 'https://my-cnd-server.com/assets/models/model.bin'
204
+ // referenced resource '../textures/texture.png' will be loaded from 'https://my-cnd-server.com/assets/textures/texture.png'
205
+ const relativeUrl = THREE.LoaderUtils.extractUrlBase( url );
206
+ resourcePath = THREE.LoaderUtils.resolveURL( relativeUrl, this.path );
207
+
208
+ } else {
209
+
210
+ resourcePath = THREE.LoaderUtils.extractUrlBase( url );
211
+
212
+ }
213
+
214
+ // Tells the LoadingManager to track an extra item, which resolves after
215
+ // the model is fully loaded. This means the count of items loaded will
216
+ // be incorrect, but ensures manager.onLoad() does not fire early.
217
+ this.manager.itemStart( url );
218
+
219
+ const _onError = function ( e ) {
220
+
221
+ if ( onError ) {
222
+
223
+ onError( e );
224
+
225
+ } else {
226
+
227
+ console.error( e );
228
+
229
+ }
230
+
231
+ scope.manager.itemError( url );
232
+ scope.manager.itemEnd( url );
233
+
234
+ };
235
+
236
+ const loader = new THREE.FileLoader( this.manager );
237
+
238
+ loader.setPath( this.path );
239
+ loader.setResponseType( 'arraybuffer' );
240
+ loader.setRequestHeader( this.requestHeader );
241
+ loader.setWithCredentials( this.withCredentials );
242
+
243
+ loader.load( url, function ( data ) {
244
+
245
+ try {
246
+
247
+ scope.parse( data, resourcePath, function ( gltf ) {
248
+
249
+ onLoad( gltf );
250
+
251
+ scope.manager.itemEnd( url );
252
+
253
+ }, _onError );
254
+
255
+ } catch ( e ) {
256
+
257
+ _onError( e );
258
+
259
+ }
260
+
261
+ }, onProgress, _onError );
262
+
263
+ }
264
+
265
+ /**
266
+ * Sets the given Draco loader to this loader. Required for decoding assets
267
+ * compressed with the `KHR_draco_mesh_compression` extension.
268
+ *
269
+ * @param {DRACOLoader} dracoLoader - The Draco loader to set.
270
+ * @return {GLTFLoader} A reference to this loader.
271
+ */
272
+ setDRACOLoader( dracoLoader ) {
273
+
274
+ this.dracoLoader = dracoLoader;
275
+ return this;
276
+
277
+ }
278
+
279
+ /**
280
+ * Sets the given KTX2 loader to this loader. Required for loading KTX2
281
+ * compressed textures.
282
+ *
283
+ * @param {KTX2Loader} ktx2Loader - The KTX2 loader to set.
284
+ * @return {GLTFLoader} A reference to this loader.
285
+ */
286
+ setKTX2Loader( ktx2Loader ) {
287
+
288
+ this.ktx2Loader = ktx2Loader;
289
+ return this;
290
+
291
+ }
292
+
293
+ /**
294
+ * Sets the given meshopt decoder. Required for decoding assets
295
+ * compressed with the `EXT_meshopt_compression` extension.
296
+ *
297
+ * @param {Object} meshoptDecoder - The meshopt decoder to set.
298
+ * @return {GLTFLoader} A reference to this loader.
299
+ */
300
+ setMeshoptDecoder( meshoptDecoder ) {
301
+
302
+ this.meshoptDecoder = meshoptDecoder;
303
+ return this;
304
+
305
+ }
306
+
307
+ /**
308
+ * Registers a plugin callback. This API is internally used to implement the various
309
+ * glTF extensions but can also used by third-party code to add additional logic
310
+ * to the loader.
311
+ *
312
+ * @param {function(parser:GLTFParser)} callback - The callback function to register.
313
+ * @return {GLTFLoader} A reference to this loader.
314
+ */
315
+ register( callback ) {
316
+
317
+ if ( this.pluginCallbacks.indexOf( callback ) === - 1 ) {
318
+
319
+ this.pluginCallbacks.push( callback );
320
+
321
+ }
322
+
323
+ return this;
324
+
325
+ }
326
+
327
+ /**
328
+ * Unregisters a plugin callback.
329
+ *
330
+ * @param {Function} callback - The callback function to unregister.
331
+ * @return {GLTFLoader} A reference to this loader.
332
+ */
333
+ unregister( callback ) {
334
+
335
+ if ( this.pluginCallbacks.indexOf( callback ) !== - 1 ) {
336
+
337
+ this.pluginCallbacks.splice( this.pluginCallbacks.indexOf( callback ), 1 );
338
+
339
+ }
340
+
341
+ return this;
342
+
343
+ }
344
+
345
+ /**
346
+ * Parses the given FBX data and returns the resulting group.
347
+ *
348
+ * @param {string|ArrayBuffer} data - The raw glTF data.
349
+ * @param {string} path - The URL base path.
350
+ * @param {function(GLTFLoader~LoadObject)} onLoad - Executed when the loading process has been finished.
351
+ * @param {onErrorCallback} onError - Executed when errors occur.
352
+ */
353
+ parse( data, path, onLoad, onError ) {
354
+
355
+ let json;
356
+ const extensions = {};
357
+ const plugins = {};
358
+ const textDecoder = new TextDecoder();
359
+
360
+ if ( typeof data === 'string' ) {
361
+
362
+ json = JSON.parse( data );
363
+
364
+ } else if ( data instanceof ArrayBuffer ) {
365
+
366
+ const magic = textDecoder.decode( new Uint8Array( data, 0, 4 ) );
367
+
368
+ if ( magic === BINARY_EXTENSION_HEADER_MAGIC ) {
369
+
370
+ try {
371
+
372
+ extensions[ EXTENSIONS.KHR_BINARY_GLTF ] = new GLTFBinaryExtension( data );
373
+
374
+ } catch ( error ) {
375
+
376
+ if ( onError ) onError( error );
377
+ return;
378
+
379
+ }
380
+
381
+ json = JSON.parse( extensions[ EXTENSIONS.KHR_BINARY_GLTF ].content );
382
+
383
+ } else {
384
+
385
+ json = JSON.parse( textDecoder.decode( data ) );
386
+
387
+ }
388
+
389
+ } else {
390
+
391
+ json = data;
392
+
393
+ }
394
+
395
+ if ( json.asset === undefined || json.asset.version[ 0 ] < 2 ) {
396
+
397
+ if ( onError ) onError( new Error( 'THREE.GLTFLoader: Unsupported asset. glTF versions >=2.0 are supported.' ) );
398
+ return;
399
+
400
+ }
401
+
402
+ const parser = new GLTFParser( json, {
403
+
404
+ path: path || this.resourcePath || '',
405
+ crossOrigin: this.crossOrigin,
406
+ requestHeader: this.requestHeader,
407
+ manager: this.manager,
408
+ ktx2Loader: this.ktx2Loader,
409
+ meshoptDecoder: this.meshoptDecoder
410
+
411
+ } );
412
+
413
+ parser.fileLoader.setRequestHeader( this.requestHeader );
414
+
415
+ for ( let i = 0; i < this.pluginCallbacks.length; i ++ ) {
416
+
417
+ const plugin = this.pluginCallbacks[ i ]( parser );
418
+
419
+ if ( ! plugin.name ) console.error( 'THREE.GLTFLoader: Invalid plugin found: missing name' );
420
+
421
+ plugins[ plugin.name ] = plugin;
422
+
423
+ // Workaround to avoid determining as unknown extension
424
+ // in addUnknownExtensionsToUserData().
425
+ // Remove this workaround if we move all the existing
426
+ // extension handlers to plugin system
427
+ extensions[ plugin.name ] = true;
428
+
429
+ }
430
+
431
+ if ( json.extensionsUsed ) {
432
+
433
+ for ( let i = 0; i < json.extensionsUsed.length; ++ i ) {
434
+
435
+ const extensionName = json.extensionsUsed[ i ];
436
+ const extensionsRequired = json.extensionsRequired || [];
437
+
438
+ switch ( extensionName ) {
439
+
440
+ case EXTENSIONS.KHR_MATERIALS_UNLIT:
441
+ extensions[ extensionName ] = new GLTFMaterialsUnlitExtension();
442
+ break;
443
+
444
+ case EXTENSIONS.KHR_DRACO_MESH_COMPRESSION:
445
+ extensions[ extensionName ] = new GLTFDracoMeshCompressionExtension( json, this.dracoLoader );
446
+ break;
447
+
448
+ case EXTENSIONS.KHR_TEXTURE_TRANSFORM:
449
+ extensions[ extensionName ] = new GLTFTextureTransformExtension();
450
+ break;
451
+
452
+ case EXTENSIONS.KHR_MESH_QUANTIZATION:
453
+ extensions[ extensionName ] = new GLTFMeshQuantizationExtension();
454
+ break;
455
+
456
+ default:
457
+
458
+ if ( extensionsRequired.indexOf( extensionName ) >= 0 && plugins[ extensionName ] === undefined ) {
459
+
460
+ console.warn( 'THREE.GLTFLoader: Unknown extension "' + extensionName + '".' );
461
+
462
+ }
463
+
464
+ }
465
+
466
+ }
467
+
468
+ }
469
+
470
+ parser.setExtensions( extensions );
471
+ parser.setPlugins( plugins );
472
+ parser.parse( onLoad, onError );
473
+
474
+ }
475
+
476
+ /**
477
+ * Async version of {@link GLTFLoader#parse}.
478
+ *
479
+ * @async
480
+ * @param {string|ArrayBuffer} data - The raw glTF data.
481
+ * @param {string} path - The URL base path.
482
+ * @return {Promise<GLTFLoader~LoadObject>} A Promise that resolves with the loaded glTF when the parsing has been finished.
483
+ */
484
+ parseAsync( data, path ) {
485
+
486
+ const scope = this;
487
+
488
+ return new Promise( function ( resolve, reject ) {
489
+
490
+ scope.parse( data, path, resolve, reject );
491
+
492
+ } );
493
+
494
+ }
495
+
496
+ }
497
+
498
+ /* GLTFREGISTRY */
499
+
500
+ function GLTFRegistry() {
501
+
502
+ let objects = {};
503
+
504
+ return {
505
+
506
+ get: function ( key ) {
507
+
508
+ return objects[ key ];
509
+
510
+ },
511
+
512
+ add: function ( key, object ) {
513
+
514
+ objects[ key ] = object;
515
+
516
+ },
517
+
518
+ remove: function ( key ) {
519
+
520
+ delete objects[ key ];
521
+
522
+ },
523
+
524
+ removeAll: function () {
525
+
526
+ objects = {};
527
+
528
+ }
529
+
530
+ };
531
+
532
+ }
533
+
534
+ /*********************************/
535
+ /********** EXTENSIONS ***********/
536
+ /*********************************/
537
+
538
+ const EXTENSIONS = {
539
+ KHR_BINARY_GLTF: 'KHR_binary_glTF',
540
+ KHR_DRACO_MESH_COMPRESSION: 'KHR_draco_mesh_compression',
541
+ KHR_LIGHTS_PUNCTUAL: 'KHR_lights_punctual',
542
+ KHR_MATERIALS_CLEARCOAT: 'KHR_materials_clearcoat',
543
+ KHR_MATERIALS_DISPERSION: 'KHR_materials_dispersion',
544
+ KHR_MATERIALS_IOR: 'KHR_materials_ior',
545
+ KHR_MATERIALS_SHEEN: 'KHR_materials_sheen',
546
+ KHR_MATERIALS_SPECULAR: 'KHR_materials_specular',
547
+ KHR_MATERIALS_TRANSMISSION: 'KHR_materials_transmission',
548
+ KHR_MATERIALS_IRIDESCENCE: 'KHR_materials_iridescence',
549
+ KHR_MATERIALS_ANISOTROPY: 'KHR_materials_anisotropy',
550
+ KHR_MATERIALS_UNLIT: 'KHR_materials_unlit',
551
+ KHR_MATERIALS_VOLUME: 'KHR_materials_volume',
552
+ KHR_TEXTURE_BASISU: 'KHR_texture_basisu',
553
+ KHR_TEXTURE_TRANSFORM: 'KHR_texture_transform',
554
+ KHR_MESH_QUANTIZATION: 'KHR_mesh_quantization',
555
+ KHR_MATERIALS_EMISSIVE_STRENGTH: 'KHR_materials_emissive_strength',
556
+ EXT_MATERIALS_BUMP: 'EXT_materials_bump',
557
+ EXT_TEXTURE_WEBP: 'EXT_texture_webp',
558
+ EXT_TEXTURE_AVIF: 'EXT_texture_avif',
559
+ EXT_MESHOPT_COMPRESSION: 'EXT_meshopt_compression',
560
+ EXT_MESH_GPU_INSTANCING: 'EXT_mesh_gpu_instancing'
561
+ };
562
+
563
+ /**
564
+ * Punctual Lights Extension
565
+ *
566
+ * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_lights_punctual
567
+ *
568
+ * @private
569
+ */
570
+ class GLTFLightsExtension {
571
+
572
+ constructor( parser ) {
573
+
574
+ this.parser = parser;
575
+ this.name = EXTENSIONS.KHR_LIGHTS_PUNCTUAL;
576
+
577
+ // Object3D instance caches
578
+ this.cache = { refs: {}, uses: {} };
579
+
580
+ }
581
+
582
+ _markDefs() {
583
+
584
+ const parser = this.parser;
585
+ const nodeDefs = this.parser.json.nodes || [];
586
+
587
+ for ( let nodeIndex = 0, nodeLength = nodeDefs.length; nodeIndex < nodeLength; nodeIndex ++ ) {
588
+
589
+ const nodeDef = nodeDefs[ nodeIndex ];
590
+
591
+ if ( nodeDef.extensions
592
+ && nodeDef.extensions[ this.name ]
593
+ && nodeDef.extensions[ this.name ].light !== undefined ) {
594
+
595
+ parser._addNodeRef( this.cache, nodeDef.extensions[ this.name ].light );
596
+
597
+ }
598
+
599
+ }
600
+
601
+ }
602
+
603
+ _loadLight( lightIndex ) {
604
+
605
+ const parser = this.parser;
606
+ const cacheKey = 'light:' + lightIndex;
607
+ let dependency = parser.cache.get( cacheKey );
608
+
609
+ if ( dependency ) return dependency;
610
+
611
+ const json = parser.json;
612
+ const extensions = ( json.extensions && json.extensions[ this.name ] ) || {};
613
+ const lightDefs = extensions.lights || [];
614
+ const lightDef = lightDefs[ lightIndex ];
615
+ let lightNode;
616
+
617
+ const color = new THREE.Color( 0xffffff );
618
+
619
+ if ( lightDef.color !== undefined ) color.setRGB( lightDef.color[ 0 ], lightDef.color[ 1 ], lightDef.color[ 2 ], THREE.LinearSRGBColorSpace );
620
+
621
+ const range = lightDef.range !== undefined ? lightDef.range : 0;
622
+
623
+ switch ( lightDef.type ) {
624
+
625
+ case 'directional':
626
+ lightNode = new THREE.DirectionalLight( color );
627
+ lightNode.target.position.set( 0, 0, - 1 );
628
+ lightNode.add( lightNode.target );
629
+ break;
630
+
631
+ case 'point':
632
+ lightNode = new THREE.PointLight( color );
633
+ lightNode.distance = range;
634
+ break;
635
+
636
+ case 'spot':
637
+ lightNode = new THREE.SpotLight( color );
638
+ lightNode.distance = range;
639
+ // Handle spotlight properties.
640
+ lightDef.spot = lightDef.spot || {};
641
+ lightDef.spot.innerConeAngle = lightDef.spot.innerConeAngle !== undefined ? lightDef.spot.innerConeAngle : 0;
642
+ lightDef.spot.outerConeAngle = lightDef.spot.outerConeAngle !== undefined ? lightDef.spot.outerConeAngle : Math.PI / 4.0;
643
+ lightNode.angle = lightDef.spot.outerConeAngle;
644
+ lightNode.penumbra = 1.0 - lightDef.spot.innerConeAngle / lightDef.spot.outerConeAngle;
645
+ lightNode.target.position.set( 0, 0, - 1 );
646
+ lightNode.add( lightNode.target );
647
+ break;
648
+
649
+ default:
650
+ throw new Error( 'THREE.GLTFLoader: Unexpected light type: ' + lightDef.type );
651
+
652
+ }
653
+
654
+ // Some lights (e.g. spot) default to a position other than the origin. Reset the position
655
+ // here, because node-level parsing will only override position if explicitly specified.
656
+ lightNode.position.set( 0, 0, 0 );
657
+
658
+ assignExtrasToUserData( lightNode, lightDef );
659
+
660
+ if ( lightDef.intensity !== undefined ) lightNode.intensity = lightDef.intensity;
661
+
662
+ lightNode.name = parser.createUniqueName( lightDef.name || ( 'light_' + lightIndex ) );
663
+
664
+ dependency = Promise.resolve( lightNode );
665
+
666
+ parser.cache.add( cacheKey, dependency );
667
+
668
+ return dependency;
669
+
670
+ }
671
+
672
+ getDependency( type, index ) {
673
+
674
+ if ( type !== 'light' ) return;
675
+
676
+ return this._loadLight( index );
677
+
678
+ }
679
+
680
+ createNodeAttachment( nodeIndex ) {
681
+
682
+ const self = this;
683
+ const parser = this.parser;
684
+ const json = parser.json;
685
+ const nodeDef = json.nodes[ nodeIndex ];
686
+ const lightDef = ( nodeDef.extensions && nodeDef.extensions[ this.name ] ) || {};
687
+ const lightIndex = lightDef.light;
688
+
689
+ if ( lightIndex === undefined ) return null;
690
+
691
+ return this._loadLight( lightIndex ).then( function ( light ) {
692
+
693
+ return parser._getNodeRef( self.cache, lightIndex, light );
694
+
695
+ } );
696
+
697
+ }
698
+
699
+ }
700
+
701
+ /**
702
+ * Unlit Materials Extension
703
+ *
704
+ * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_unlit
705
+ *
706
+ * @private
707
+ */
708
+ class GLTFMaterialsUnlitExtension {
709
+
710
+ constructor() {
711
+
712
+ this.name = EXTENSIONS.KHR_MATERIALS_UNLIT;
713
+
714
+ }
715
+
716
+ getMaterialType() {
717
+
718
+ return THREE.MeshBasicMaterial;
719
+
720
+ }
721
+
722
+ extendParams( materialParams, materialDef, parser ) {
723
+
724
+ const pending = [];
725
+
726
+ materialParams.color = new THREE.Color( 1.0, 1.0, 1.0 );
727
+ materialParams.opacity = 1.0;
728
+
729
+ const metallicRoughness = materialDef.pbrMetallicRoughness;
730
+
731
+ if ( metallicRoughness ) {
732
+
733
+ if ( Array.isArray( metallicRoughness.baseColorFactor ) ) {
734
+
735
+ const array = metallicRoughness.baseColorFactor;
736
+
737
+ materialParams.color.setRGB( array[ 0 ], array[ 1 ], array[ 2 ], THREE.LinearSRGBColorSpace );
738
+ materialParams.opacity = array[ 3 ];
739
+
740
+ }
741
+
742
+ if ( metallicRoughness.baseColorTexture !== undefined ) {
743
+
744
+ pending.push( parser.assignTexture( materialParams, 'map', metallicRoughness.baseColorTexture, THREE.SRGBColorSpace ) );
745
+
746
+ }
747
+
748
+ }
749
+
750
+ return Promise.all( pending );
751
+
752
+ }
753
+
754
+ }
755
+
756
+ /**
757
+ * Materials Emissive Strength Extension
758
+ *
759
+ * Specification: https://github.com/KhronosGroup/glTF/blob/5768b3ce0ef32bc39cdf1bef10b948586635ead3/extensions/2.0/Khronos/KHR_materials_emissive_strength/README.md
760
+ *
761
+ * @private
762
+ */
763
+ class GLTFMaterialsEmissiveStrengthExtension {
764
+
765
+ constructor( parser ) {
766
+
767
+ this.parser = parser;
768
+ this.name = EXTENSIONS.KHR_MATERIALS_EMISSIVE_STRENGTH;
769
+
770
+ }
771
+
772
+ extendMaterialParams( materialIndex, materialParams ) {
773
+
774
+ const parser = this.parser;
775
+ const materialDef = parser.json.materials[ materialIndex ];
776
+
777
+ if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) {
778
+
779
+ return Promise.resolve();
780
+
781
+ }
782
+
783
+ const emissiveStrength = materialDef.extensions[ this.name ].emissiveStrength;
784
+
785
+ if ( emissiveStrength !== undefined ) {
786
+
787
+ materialParams.emissiveIntensity = emissiveStrength;
788
+
789
+ }
790
+
791
+ return Promise.resolve();
792
+
793
+ }
794
+
795
+ }
796
+
797
+ /**
798
+ * Clearcoat Materials Extension
799
+ *
800
+ * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_clearcoat
801
+ *
802
+ * @private
803
+ */
804
+ class GLTFMaterialsClearcoatExtension {
805
+
806
+ constructor( parser ) {
807
+
808
+ this.parser = parser;
809
+ this.name = EXTENSIONS.KHR_MATERIALS_CLEARCOAT;
810
+
811
+ }
812
+
813
+ getMaterialType( materialIndex ) {
814
+
815
+ const parser = this.parser;
816
+ const materialDef = parser.json.materials[ materialIndex ];
817
+
818
+ if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) return null;
819
+
820
+ return THREE.MeshPhysicalMaterial;
821
+
822
+ }
823
+
824
+ extendMaterialParams( materialIndex, materialParams ) {
825
+
826
+ const parser = this.parser;
827
+ const materialDef = parser.json.materials[ materialIndex ];
828
+
829
+ if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) {
830
+
831
+ return Promise.resolve();
832
+
833
+ }
834
+
835
+ const pending = [];
836
+
837
+ const extension = materialDef.extensions[ this.name ];
838
+
839
+ if ( extension.clearcoatFactor !== undefined ) {
840
+
841
+ materialParams.clearcoat = extension.clearcoatFactor;
842
+
843
+ }
844
+
845
+ if ( extension.clearcoatTexture !== undefined ) {
846
+
847
+ pending.push( parser.assignTexture( materialParams, 'clearcoatMap', extension.clearcoatTexture ) );
848
+
849
+ }
850
+
851
+ if ( extension.clearcoatRoughnessFactor !== undefined ) {
852
+
853
+ materialParams.clearcoatRoughness = extension.clearcoatRoughnessFactor;
854
+
855
+ }
856
+
857
+ if ( extension.clearcoatRoughnessTexture !== undefined ) {
858
+
859
+ pending.push( parser.assignTexture( materialParams, 'clearcoatRoughnessMap', extension.clearcoatRoughnessTexture ) );
860
+
861
+ }
862
+
863
+ if ( extension.clearcoatNormalTexture !== undefined ) {
864
+
865
+ pending.push( parser.assignTexture( materialParams, 'clearcoatNormalMap', extension.clearcoatNormalTexture ) );
866
+
867
+ if ( extension.clearcoatNormalTexture.scale !== undefined ) {
868
+
869
+ const scale = extension.clearcoatNormalTexture.scale;
870
+
871
+ materialParams.clearcoatNormalScale = new THREE.Vector2( scale, scale );
872
+
873
+ }
874
+
875
+ }
876
+
877
+ return Promise.all( pending );
878
+
879
+ }
880
+
881
+ }
882
+
883
+ /**
884
+ * Materials dispersion Extension
885
+ *
886
+ * Specification: https://github.com/KhronosGroup/glTF/tree/main/extensions/2.0/Khronos/KHR_materials_dispersion
887
+ *
888
+ * @private
889
+ */
890
+ class GLTFMaterialsDispersionExtension {
891
+
892
+ constructor( parser ) {
893
+
894
+ this.parser = parser;
895
+ this.name = EXTENSIONS.KHR_MATERIALS_DISPERSION;
896
+
897
+ }
898
+
899
+ getMaterialType( materialIndex ) {
900
+
901
+ const parser = this.parser;
902
+ const materialDef = parser.json.materials[ materialIndex ];
903
+
904
+ if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) return null;
905
+
906
+ return THREE.MeshPhysicalMaterial;
907
+
908
+ }
909
+
910
+ extendMaterialParams( materialIndex, materialParams ) {
911
+
912
+ const parser = this.parser;
913
+ const materialDef = parser.json.materials[ materialIndex ];
914
+
915
+ if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) {
916
+
917
+ return Promise.resolve();
918
+
919
+ }
920
+
921
+ const extension = materialDef.extensions[ this.name ];
922
+
923
+ materialParams.dispersion = extension.dispersion !== undefined ? extension.dispersion : 0;
924
+
925
+ return Promise.resolve();
926
+
927
+ }
928
+
929
+ }
930
+
931
+ /**
932
+ * Iridescence Materials Extension
933
+ *
934
+ * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_iridescence
935
+ *
936
+ * @private
937
+ */
938
+ class GLTFMaterialsIridescenceExtension {
939
+
940
+ constructor( parser ) {
941
+
942
+ this.parser = parser;
943
+ this.name = EXTENSIONS.KHR_MATERIALS_IRIDESCENCE;
944
+
945
+ }
946
+
947
+ getMaterialType( materialIndex ) {
948
+
949
+ const parser = this.parser;
950
+ const materialDef = parser.json.materials[ materialIndex ];
951
+
952
+ if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) return null;
953
+
954
+ return THREE.MeshPhysicalMaterial;
955
+
956
+ }
957
+
958
+ extendMaterialParams( materialIndex, materialParams ) {
959
+
960
+ const parser = this.parser;
961
+ const materialDef = parser.json.materials[ materialIndex ];
962
+
963
+ if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) {
964
+
965
+ return Promise.resolve();
966
+
967
+ }
968
+
969
+ const pending = [];
970
+
971
+ const extension = materialDef.extensions[ this.name ];
972
+
973
+ if ( extension.iridescenceFactor !== undefined ) {
974
+
975
+ materialParams.iridescence = extension.iridescenceFactor;
976
+
977
+ }
978
+
979
+ if ( extension.iridescenceTexture !== undefined ) {
980
+
981
+ pending.push( parser.assignTexture( materialParams, 'iridescenceMap', extension.iridescenceTexture ) );
982
+
983
+ }
984
+
985
+ if ( extension.iridescenceIor !== undefined ) {
986
+
987
+ materialParams.iridescenceIOR = extension.iridescenceIor;
988
+
989
+ }
990
+
991
+ if ( materialParams.iridescenceThicknessRange === undefined ) {
992
+
993
+ materialParams.iridescenceThicknessRange = [ 100, 400 ];
994
+
995
+ }
996
+
997
+ if ( extension.iridescenceThicknessMinimum !== undefined ) {
998
+
999
+ materialParams.iridescenceThicknessRange[ 0 ] = extension.iridescenceThicknessMinimum;
1000
+
1001
+ }
1002
+
1003
+ if ( extension.iridescenceThicknessMaximum !== undefined ) {
1004
+
1005
+ materialParams.iridescenceThicknessRange[ 1 ] = extension.iridescenceThicknessMaximum;
1006
+
1007
+ }
1008
+
1009
+ if ( extension.iridescenceThicknessTexture !== undefined ) {
1010
+
1011
+ pending.push( parser.assignTexture( materialParams, 'iridescenceThicknessMap', extension.iridescenceThicknessTexture ) );
1012
+
1013
+ }
1014
+
1015
+ return Promise.all( pending );
1016
+
1017
+ }
1018
+
1019
+ }
1020
+
1021
+ /**
1022
+ * Sheen Materials Extension
1023
+ *
1024
+ * Specification: https://github.com/KhronosGroup/glTF/tree/main/extensions/2.0/Khronos/KHR_materials_sheen
1025
+ *
1026
+ * @private
1027
+ */
1028
+ class GLTFMaterialsSheenExtension {
1029
+
1030
+ constructor( parser ) {
1031
+
1032
+ this.parser = parser;
1033
+ this.name = EXTENSIONS.KHR_MATERIALS_SHEEN;
1034
+
1035
+ }
1036
+
1037
+ getMaterialType( materialIndex ) {
1038
+
1039
+ const parser = this.parser;
1040
+ const materialDef = parser.json.materials[ materialIndex ];
1041
+
1042
+ if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) return null;
1043
+
1044
+ return THREE.MeshPhysicalMaterial;
1045
+
1046
+ }
1047
+
1048
+ extendMaterialParams( materialIndex, materialParams ) {
1049
+
1050
+ const parser = this.parser;
1051
+ const materialDef = parser.json.materials[ materialIndex ];
1052
+
1053
+ if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) {
1054
+
1055
+ return Promise.resolve();
1056
+
1057
+ }
1058
+
1059
+ const pending = [];
1060
+
1061
+ materialParams.sheenColor = new THREE.Color( 0, 0, 0 );
1062
+ materialParams.sheenRoughness = 0;
1063
+ materialParams.sheen = 1;
1064
+
1065
+ const extension = materialDef.extensions[ this.name ];
1066
+
1067
+ if ( extension.sheenColorFactor !== undefined ) {
1068
+
1069
+ const colorFactor = extension.sheenColorFactor;
1070
+ materialParams.sheenColor.setRGB( colorFactor[ 0 ], colorFactor[ 1 ], colorFactor[ 2 ], THREE.LinearSRGBColorSpace );
1071
+
1072
+ }
1073
+
1074
+ if ( extension.sheenRoughnessFactor !== undefined ) {
1075
+
1076
+ materialParams.sheenRoughness = extension.sheenRoughnessFactor;
1077
+
1078
+ }
1079
+
1080
+ if ( extension.sheenColorTexture !== undefined ) {
1081
+
1082
+ pending.push( parser.assignTexture( materialParams, 'sheenColorMap', extension.sheenColorTexture, THREE.SRGBColorSpace ) );
1083
+
1084
+ }
1085
+
1086
+ if ( extension.sheenRoughnessTexture !== undefined ) {
1087
+
1088
+ pending.push( parser.assignTexture( materialParams, 'sheenRoughnessMap', extension.sheenRoughnessTexture ) );
1089
+
1090
+ }
1091
+
1092
+ return Promise.all( pending );
1093
+
1094
+ }
1095
+
1096
+ }
1097
+
1098
+ /**
1099
+ * Transmission Materials Extension
1100
+ *
1101
+ * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_transmission
1102
+ * Draft: https://github.com/KhronosGroup/glTF/pull/1698
1103
+ *
1104
+ * @private
1105
+ */
1106
+ class GLTFMaterialsTransmissionExtension {
1107
+
1108
+ constructor( parser ) {
1109
+
1110
+ this.parser = parser;
1111
+ this.name = EXTENSIONS.KHR_MATERIALS_TRANSMISSION;
1112
+
1113
+ }
1114
+
1115
+ getMaterialType( materialIndex ) {
1116
+
1117
+ const parser = this.parser;
1118
+ const materialDef = parser.json.materials[ materialIndex ];
1119
+
1120
+ if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) return null;
1121
+
1122
+ return THREE.MeshPhysicalMaterial;
1123
+
1124
+ }
1125
+
1126
+ extendMaterialParams( materialIndex, materialParams ) {
1127
+
1128
+ const parser = this.parser;
1129
+ const materialDef = parser.json.materials[ materialIndex ];
1130
+
1131
+ if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) {
1132
+
1133
+ return Promise.resolve();
1134
+
1135
+ }
1136
+
1137
+ const pending = [];
1138
+
1139
+ const extension = materialDef.extensions[ this.name ];
1140
+
1141
+ if ( extension.transmissionFactor !== undefined ) {
1142
+
1143
+ materialParams.transmission = extension.transmissionFactor;
1144
+
1145
+ }
1146
+
1147
+ if ( extension.transmissionTexture !== undefined ) {
1148
+
1149
+ pending.push( parser.assignTexture( materialParams, 'transmissionMap', extension.transmissionTexture ) );
1150
+
1151
+ }
1152
+
1153
+ return Promise.all( pending );
1154
+
1155
+ }
1156
+
1157
+ }
1158
+
1159
+ /**
1160
+ * Materials Volume Extension
1161
+ *
1162
+ * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_volume
1163
+ *
1164
+ * @private
1165
+ */
1166
+ class GLTFMaterialsVolumeExtension {
1167
+
1168
+ constructor( parser ) {
1169
+
1170
+ this.parser = parser;
1171
+ this.name = EXTENSIONS.KHR_MATERIALS_VOLUME;
1172
+
1173
+ }
1174
+
1175
+ getMaterialType( materialIndex ) {
1176
+
1177
+ const parser = this.parser;
1178
+ const materialDef = parser.json.materials[ materialIndex ];
1179
+
1180
+ if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) return null;
1181
+
1182
+ return THREE.MeshPhysicalMaterial;
1183
+
1184
+ }
1185
+
1186
+ extendMaterialParams( materialIndex, materialParams ) {
1187
+
1188
+ const parser = this.parser;
1189
+ const materialDef = parser.json.materials[ materialIndex ];
1190
+
1191
+ if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) {
1192
+
1193
+ return Promise.resolve();
1194
+
1195
+ }
1196
+
1197
+ const pending = [];
1198
+
1199
+ const extension = materialDef.extensions[ this.name ];
1200
+
1201
+ materialParams.thickness = extension.thicknessFactor !== undefined ? extension.thicknessFactor : 0;
1202
+
1203
+ if ( extension.thicknessTexture !== undefined ) {
1204
+
1205
+ pending.push( parser.assignTexture( materialParams, 'thicknessMap', extension.thicknessTexture ) );
1206
+
1207
+ }
1208
+
1209
+ materialParams.attenuationDistance = extension.attenuationDistance || Infinity;
1210
+
1211
+ const colorArray = extension.attenuationColor || [ 1, 1, 1 ];
1212
+ materialParams.attenuationColor = new THREE.Color().setRGB( colorArray[ 0 ], colorArray[ 1 ], colorArray[ 2 ], THREE.LinearSRGBColorSpace );
1213
+
1214
+ return Promise.all( pending );
1215
+
1216
+ }
1217
+
1218
+ }
1219
+
1220
+ /**
1221
+ * Materials ior Extension
1222
+ *
1223
+ * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_ior
1224
+ *
1225
+ * @private
1226
+ */
1227
+ class GLTFMaterialsIorExtension {
1228
+
1229
+ constructor( parser ) {
1230
+
1231
+ this.parser = parser;
1232
+ this.name = EXTENSIONS.KHR_MATERIALS_IOR;
1233
+
1234
+ }
1235
+
1236
+ getMaterialType( materialIndex ) {
1237
+
1238
+ const parser = this.parser;
1239
+ const materialDef = parser.json.materials[ materialIndex ];
1240
+
1241
+ if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) return null;
1242
+
1243
+ return THREE.MeshPhysicalMaterial;
1244
+
1245
+ }
1246
+
1247
+ extendMaterialParams( materialIndex, materialParams ) {
1248
+
1249
+ const parser = this.parser;
1250
+ const materialDef = parser.json.materials[ materialIndex ];
1251
+
1252
+ if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) {
1253
+
1254
+ return Promise.resolve();
1255
+
1256
+ }
1257
+
1258
+ const extension = materialDef.extensions[ this.name ];
1259
+
1260
+ materialParams.ior = extension.ior !== undefined ? extension.ior : 1.5;
1261
+
1262
+ return Promise.resolve();
1263
+
1264
+ }
1265
+
1266
+ }
1267
+
1268
+ /**
1269
+ * Materials specular Extension
1270
+ *
1271
+ * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_specular
1272
+ *
1273
+ * @private
1274
+ */
1275
+ class GLTFMaterialsSpecularExtension {
1276
+
1277
+ constructor( parser ) {
1278
+
1279
+ this.parser = parser;
1280
+ this.name = EXTENSIONS.KHR_MATERIALS_SPECULAR;
1281
+
1282
+ }
1283
+
1284
+ getMaterialType( materialIndex ) {
1285
+
1286
+ const parser = this.parser;
1287
+ const materialDef = parser.json.materials[ materialIndex ];
1288
+
1289
+ if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) return null;
1290
+
1291
+ return THREE.MeshPhysicalMaterial;
1292
+
1293
+ }
1294
+
1295
+ extendMaterialParams( materialIndex, materialParams ) {
1296
+
1297
+ const parser = this.parser;
1298
+ const materialDef = parser.json.materials[ materialIndex ];
1299
+
1300
+ if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) {
1301
+
1302
+ return Promise.resolve();
1303
+
1304
+ }
1305
+
1306
+ const pending = [];
1307
+
1308
+ const extension = materialDef.extensions[ this.name ];
1309
+
1310
+ materialParams.specularIntensity = extension.specularFactor !== undefined ? extension.specularFactor : 1.0;
1311
+
1312
+ if ( extension.specularTexture !== undefined ) {
1313
+
1314
+ pending.push( parser.assignTexture( materialParams, 'specularIntensityMap', extension.specularTexture ) );
1315
+
1316
+ }
1317
+
1318
+ const colorArray = extension.specularColorFactor || [ 1, 1, 1 ];
1319
+ materialParams.specularColor = new THREE.Color().setRGB( colorArray[ 0 ], colorArray[ 1 ], colorArray[ 2 ], THREE.LinearSRGBColorSpace );
1320
+
1321
+ if ( extension.specularColorTexture !== undefined ) {
1322
+
1323
+ pending.push( parser.assignTexture( materialParams, 'specularColorMap', extension.specularColorTexture, THREE.SRGBColorSpace ) );
1324
+
1325
+ }
1326
+
1327
+ return Promise.all( pending );
1328
+
1329
+ }
1330
+
1331
+ }
1332
+
1333
+
1334
+ /**
1335
+ * Materials bump Extension
1336
+ *
1337
+ * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/EXT_materials_bump
1338
+ *
1339
+ * @private
1340
+ */
1341
+ class GLTFMaterialsBumpExtension {
1342
+
1343
+ constructor( parser ) {
1344
+
1345
+ this.parser = parser;
1346
+ this.name = EXTENSIONS.EXT_MATERIALS_BUMP;
1347
+
1348
+ }
1349
+
1350
+ getMaterialType( materialIndex ) {
1351
+
1352
+ const parser = this.parser;
1353
+ const materialDef = parser.json.materials[ materialIndex ];
1354
+
1355
+ if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) return null;
1356
+
1357
+ return THREE.MeshPhysicalMaterial;
1358
+
1359
+ }
1360
+
1361
+ extendMaterialParams( materialIndex, materialParams ) {
1362
+
1363
+ const parser = this.parser;
1364
+ const materialDef = parser.json.materials[ materialIndex ];
1365
+
1366
+ if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) {
1367
+
1368
+ return Promise.resolve();
1369
+
1370
+ }
1371
+
1372
+ const pending = [];
1373
+
1374
+ const extension = materialDef.extensions[ this.name ];
1375
+
1376
+ materialParams.bumpScale = extension.bumpFactor !== undefined ? extension.bumpFactor : 1.0;
1377
+
1378
+ if ( extension.bumpTexture !== undefined ) {
1379
+
1380
+ pending.push( parser.assignTexture( materialParams, 'bumpMap', extension.bumpTexture ) );
1381
+
1382
+ }
1383
+
1384
+ return Promise.all( pending );
1385
+
1386
+ }
1387
+
1388
+ }
1389
+
1390
+ /**
1391
+ * Materials anisotropy Extension
1392
+ *
1393
+ * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_anisotropy
1394
+ *
1395
+ * @private
1396
+ */
1397
+ class GLTFMaterialsAnisotropyExtension {
1398
+
1399
+ constructor( parser ) {
1400
+
1401
+ this.parser = parser;
1402
+ this.name = EXTENSIONS.KHR_MATERIALS_ANISOTROPY;
1403
+
1404
+ }
1405
+
1406
+ getMaterialType( materialIndex ) {
1407
+
1408
+ const parser = this.parser;
1409
+ const materialDef = parser.json.materials[ materialIndex ];
1410
+
1411
+ if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) return null;
1412
+
1413
+ return THREE.MeshPhysicalMaterial;
1414
+
1415
+ }
1416
+
1417
+ extendMaterialParams( materialIndex, materialParams ) {
1418
+
1419
+ const parser = this.parser;
1420
+ const materialDef = parser.json.materials[ materialIndex ];
1421
+
1422
+ if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) {
1423
+
1424
+ return Promise.resolve();
1425
+
1426
+ }
1427
+
1428
+ const pending = [];
1429
+
1430
+ const extension = materialDef.extensions[ this.name ];
1431
+
1432
+ if ( extension.anisotropyStrength !== undefined ) {
1433
+
1434
+ materialParams.anisotropy = extension.anisotropyStrength;
1435
+
1436
+ }
1437
+
1438
+ if ( extension.anisotropyRotation !== undefined ) {
1439
+
1440
+ materialParams.anisotropyRotation = extension.anisotropyRotation;
1441
+
1442
+ }
1443
+
1444
+ if ( extension.anisotropyTexture !== undefined ) {
1445
+
1446
+ pending.push( parser.assignTexture( materialParams, 'anisotropyMap', extension.anisotropyTexture ) );
1447
+
1448
+ }
1449
+
1450
+ return Promise.all( pending );
1451
+
1452
+ }
1453
+
1454
+ }
1455
+
1456
+ /**
1457
+ * BasisU Texture Extension
1458
+ *
1459
+ * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_texture_basisu
1460
+ *
1461
+ * @private
1462
+ */
1463
+ class GLTFTextureBasisUExtension {
1464
+
1465
+ constructor( parser ) {
1466
+
1467
+ this.parser = parser;
1468
+ this.name = EXTENSIONS.KHR_TEXTURE_BASISU;
1469
+
1470
+ }
1471
+
1472
+ loadTexture( textureIndex ) {
1473
+
1474
+ const parser = this.parser;
1475
+ const json = parser.json;
1476
+
1477
+ const textureDef = json.textures[ textureIndex ];
1478
+
1479
+ if ( ! textureDef.extensions || ! textureDef.extensions[ this.name ] ) {
1480
+
1481
+ return null;
1482
+
1483
+ }
1484
+
1485
+ const extension = textureDef.extensions[ this.name ];
1486
+ const loader = parser.options.ktx2Loader;
1487
+
1488
+ if ( ! loader ) {
1489
+
1490
+ if ( json.extensionsRequired && json.extensionsRequired.indexOf( this.name ) >= 0 ) {
1491
+
1492
+ throw new Error( 'THREE.GLTFLoader: setKTX2Loader must be called before loading KTX2 textures' );
1493
+
1494
+ } else {
1495
+
1496
+ // Assumes that the extension is optional and that a fallback texture is present
1497
+ return null;
1498
+
1499
+ }
1500
+
1501
+ }
1502
+
1503
+ return parser.loadTextureImage( textureIndex, extension.source, loader );
1504
+
1505
+ }
1506
+
1507
+ }
1508
+
1509
+ /**
1510
+ * WebP Texture Extension
1511
+ *
1512
+ * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/EXT_texture_webp
1513
+ *
1514
+ * @private
1515
+ */
1516
+ class GLTFTextureWebPExtension {
1517
+
1518
+ constructor( parser ) {
1519
+
1520
+ this.parser = parser;
1521
+ this.name = EXTENSIONS.EXT_TEXTURE_WEBP;
1522
+
1523
+ }
1524
+
1525
+ loadTexture( textureIndex ) {
1526
+
1527
+ const name = this.name;
1528
+ const parser = this.parser;
1529
+ const json = parser.json;
1530
+
1531
+ const textureDef = json.textures[ textureIndex ];
1532
+
1533
+ if ( ! textureDef.extensions || ! textureDef.extensions[ name ] ) {
1534
+
1535
+ return null;
1536
+
1537
+ }
1538
+
1539
+ const extension = textureDef.extensions[ name ];
1540
+ const source = json.images[ extension.source ];
1541
+
1542
+ let loader = parser.textureLoader;
1543
+ if ( source.uri ) {
1544
+
1545
+ const handler = parser.options.manager.getHandler( source.uri );
1546
+ if ( handler !== null ) loader = handler;
1547
+
1548
+ }
1549
+
1550
+ return parser.loadTextureImage( textureIndex, extension.source, loader );
1551
+
1552
+ }
1553
+
1554
+ }
1555
+
1556
+ /**
1557
+ * AVIF Texture Extension
1558
+ *
1559
+ * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/EXT_texture_avif
1560
+ *
1561
+ * @private
1562
+ */
1563
+ class GLTFTextureAVIFExtension {
1564
+
1565
+ constructor( parser ) {
1566
+
1567
+ this.parser = parser;
1568
+ this.name = EXTENSIONS.EXT_TEXTURE_AVIF;
1569
+
1570
+ }
1571
+
1572
+ loadTexture( textureIndex ) {
1573
+
1574
+ const name = this.name;
1575
+ const parser = this.parser;
1576
+ const json = parser.json;
1577
+
1578
+ const textureDef = json.textures[ textureIndex ];
1579
+
1580
+ if ( ! textureDef.extensions || ! textureDef.extensions[ name ] ) {
1581
+
1582
+ return null;
1583
+
1584
+ }
1585
+
1586
+ const extension = textureDef.extensions[ name ];
1587
+ const source = json.images[ extension.source ];
1588
+
1589
+ let loader = parser.textureLoader;
1590
+ if ( source.uri ) {
1591
+
1592
+ const handler = parser.options.manager.getHandler( source.uri );
1593
+ if ( handler !== null ) loader = handler;
1594
+
1595
+ }
1596
+
1597
+ return parser.loadTextureImage( textureIndex, extension.source, loader );
1598
+
1599
+ }
1600
+
1601
+ }
1602
+
1603
+ /**
1604
+ * meshopt BufferView Compression Extension
1605
+ *
1606
+ * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/EXT_meshopt_compression
1607
+ *
1608
+ * @private
1609
+ */
1610
+ class GLTFMeshoptCompression {
1611
+
1612
+ constructor( parser ) {
1613
+
1614
+ this.name = EXTENSIONS.EXT_MESHOPT_COMPRESSION;
1615
+ this.parser = parser;
1616
+
1617
+ }
1618
+
1619
+ loadBufferView( index ) {
1620
+
1621
+ const json = this.parser.json;
1622
+ const bufferView = json.bufferViews[ index ];
1623
+
1624
+ if ( bufferView.extensions && bufferView.extensions[ this.name ] ) {
1625
+
1626
+ const extensionDef = bufferView.extensions[ this.name ];
1627
+
1628
+ const buffer = this.parser.getDependency( 'buffer', extensionDef.buffer );
1629
+ const decoder = this.parser.options.meshoptDecoder;
1630
+
1631
+ if ( ! decoder || ! decoder.supported ) {
1632
+
1633
+ if ( json.extensionsRequired && json.extensionsRequired.indexOf( this.name ) >= 0 ) {
1634
+
1635
+ throw new Error( 'THREE.GLTFLoader: setMeshoptDecoder must be called before loading compressed files' );
1636
+
1637
+ } else {
1638
+
1639
+ // Assumes that the extension is optional and that fallback buffer data is present
1640
+ return null;
1641
+
1642
+ }
1643
+
1644
+ }
1645
+
1646
+ return buffer.then( function ( res ) {
1647
+
1648
+ const byteOffset = extensionDef.byteOffset || 0;
1649
+ const byteLength = extensionDef.byteLength || 0;
1650
+
1651
+ const count = extensionDef.count;
1652
+ const stride = extensionDef.byteStride;
1653
+
1654
+ const source = new Uint8Array( res, byteOffset, byteLength );
1655
+
1656
+ if ( decoder.decodeGltfBufferAsync ) {
1657
+
1658
+ return decoder.decodeGltfBufferAsync( count, stride, source, extensionDef.mode, extensionDef.filter ).then( function ( res ) {
1659
+
1660
+ return res.buffer;
1661
+
1662
+ } );
1663
+
1664
+ } else {
1665
+
1666
+ // Support for MeshoptDecoder 0.18 or earlier, without decodeGltfBufferAsync
1667
+ return decoder.ready.then( function () {
1668
+
1669
+ const result = new ArrayBuffer( count * stride );
1670
+ decoder.decodeGltfBuffer( new Uint8Array( result ), count, stride, source, extensionDef.mode, extensionDef.filter );
1671
+ return result;
1672
+
1673
+ } );
1674
+
1675
+ }
1676
+
1677
+ } );
1678
+
1679
+ } else {
1680
+
1681
+ return null;
1682
+
1683
+ }
1684
+
1685
+ }
1686
+
1687
+ }
1688
+
1689
+ /**
1690
+ * GPU Instancing Extension
1691
+ *
1692
+ * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/EXT_mesh_gpu_instancing
1693
+ *
1694
+ * @private
1695
+ */
1696
+ class GLTFMeshGpuInstancing {
1697
+
1698
+ constructor( parser ) {
1699
+
1700
+ this.name = EXTENSIONS.EXT_MESH_GPU_INSTANCING;
1701
+ this.parser = parser;
1702
+
1703
+ }
1704
+
1705
+ createNodeMesh( nodeIndex ) {
1706
+
1707
+ const json = this.parser.json;
1708
+ const nodeDef = json.nodes[ nodeIndex ];
1709
+
1710
+ if ( ! nodeDef.extensions || ! nodeDef.extensions[ this.name ] ||
1711
+ nodeDef.mesh === undefined ) {
1712
+
1713
+ return null;
1714
+
1715
+ }
1716
+
1717
+ const meshDef = json.meshes[ nodeDef.mesh ];
1718
+
1719
+ // No Points or Lines + Instancing support yet
1720
+
1721
+ for ( const primitive of meshDef.primitives ) {
1722
+
1723
+ if ( primitive.mode !== WEBGL_CONSTANTS.TRIANGLES &&
1724
+ primitive.mode !== WEBGL_CONSTANTS.TRIANGLE_STRIP &&
1725
+ primitive.mode !== WEBGL_CONSTANTS.TRIANGLE_FAN &&
1726
+ primitive.mode !== undefined ) {
1727
+
1728
+ return null;
1729
+
1730
+ }
1731
+
1732
+ }
1733
+
1734
+ const extensionDef = nodeDef.extensions[ this.name ];
1735
+ const attributesDef = extensionDef.attributes;
1736
+
1737
+ // @TODO: Can we support InstancedMesh + SkinnedMesh?
1738
+
1739
+ const pending = [];
1740
+ const attributes = {};
1741
+
1742
+ for ( const key in attributesDef ) {
1743
+
1744
+ pending.push( this.parser.getDependency( 'accessor', attributesDef[ key ] ).then( accessor => {
1745
+
1746
+ attributes[ key ] = accessor;
1747
+ return attributes[ key ];
1748
+
1749
+ } ) );
1750
+
1751
+ }
1752
+
1753
+ if ( pending.length < 1 ) {
1754
+
1755
+ return null;
1756
+
1757
+ }
1758
+
1759
+ pending.push( this.parser.createNodeMesh( nodeIndex ) );
1760
+
1761
+ return Promise.all( pending ).then( results => {
1762
+
1763
+ const nodeObject = results.pop();
1764
+ const meshes = nodeObject.isGroup ? nodeObject.children : [ nodeObject ];
1765
+ const count = results[ 0 ].count; // All attribute counts should be same
1766
+ const instancedMeshes = [];
1767
+
1768
+ for ( const mesh of meshes ) {
1769
+
1770
+ // Temporal variables
1771
+ const m = new THREE.Matrix4();
1772
+ const p = new THREE.Vector3();
1773
+ const q = new THREE.Quaternion();
1774
+ const s = new THREE.Vector3( 1, 1, 1 );
1775
+
1776
+ const instancedMesh = new THREE.InstancedMesh( mesh.geometry, mesh.material, count );
1777
+
1778
+ for ( let i = 0; i < count; i ++ ) {
1779
+
1780
+ if ( attributes.TRANSLATION ) {
1781
+
1782
+ p.fromBufferAttribute( attributes.TRANSLATION, i );
1783
+
1784
+ }
1785
+
1786
+ if ( attributes.ROTATION ) {
1787
+
1788
+ q.fromBufferAttribute( attributes.ROTATION, i );
1789
+
1790
+ }
1791
+
1792
+ if ( attributes.SCALE ) {
1793
+
1794
+ s.fromBufferAttribute( attributes.SCALE, i );
1795
+
1796
+ }
1797
+
1798
+ instancedMesh.setMatrixAt( i, m.compose( p, q, s ) );
1799
+
1800
+ }
1801
+
1802
+ // Add instance attributes to the geometry, excluding TRS.
1803
+ for ( const attributeName in attributes ) {
1804
+
1805
+ if ( attributeName === '_COLOR_0' ) {
1806
+
1807
+ const attr = attributes[ attributeName ];
1808
+ instancedMesh.instanceColor = new THREE.InstancedBufferAttribute( attr.array, attr.itemSize, attr.normalized );
1809
+
1810
+ } else if ( attributeName !== 'TRANSLATION' &&
1811
+ attributeName !== 'ROTATION' &&
1812
+ attributeName !== 'SCALE' ) {
1813
+
1814
+ mesh.geometry.setAttribute( attributeName, attributes[ attributeName ] );
1815
+
1816
+ }
1817
+
1818
+ }
1819
+
1820
+ // Just in case
1821
+ THREE.Object3D.prototype.copy.call( instancedMesh, mesh );
1822
+
1823
+ this.parser.assignFinalMaterial( instancedMesh );
1824
+
1825
+ instancedMeshes.push( instancedMesh );
1826
+
1827
+ }
1828
+
1829
+ if ( nodeObject.isGroup ) {
1830
+
1831
+ nodeObject.clear();
1832
+
1833
+ nodeObject.add( ... instancedMeshes );
1834
+
1835
+ return nodeObject;
1836
+
1837
+ }
1838
+
1839
+ return instancedMeshes[ 0 ];
1840
+
1841
+ } );
1842
+
1843
+ }
1844
+
1845
+ }
1846
+
1847
+ /* BINARY EXTENSION */
1848
+ const BINARY_EXTENSION_HEADER_MAGIC = 'glTF';
1849
+ const BINARY_EXTENSION_HEADER_LENGTH = 12;
1850
+ const BINARY_EXTENSION_CHUNK_TYPES = { JSON: 0x4E4F534A, BIN: 0x004E4942 };
1851
+
1852
+ class GLTFBinaryExtension {
1853
+
1854
+ constructor( data ) {
1855
+
1856
+ this.name = EXTENSIONS.KHR_BINARY_GLTF;
1857
+ this.content = null;
1858
+ this.body = null;
1859
+
1860
+ const headerView = new DataView( data, 0, BINARY_EXTENSION_HEADER_LENGTH );
1861
+ const textDecoder = new TextDecoder();
1862
+
1863
+ this.header = {
1864
+ magic: textDecoder.decode( new Uint8Array( data.slice( 0, 4 ) ) ),
1865
+ version: headerView.getUint32( 4, true ),
1866
+ length: headerView.getUint32( 8, true )
1867
+ };
1868
+
1869
+ if ( this.header.magic !== BINARY_EXTENSION_HEADER_MAGIC ) {
1870
+
1871
+ throw new Error( 'THREE.GLTFLoader: Unsupported glTF-Binary header.' );
1872
+
1873
+ } else if ( this.header.version < 2.0 ) {
1874
+
1875
+ throw new Error( 'THREE.GLTFLoader: Legacy binary file detected.' );
1876
+
1877
+ }
1878
+
1879
+ const chunkContentsLength = this.header.length - BINARY_EXTENSION_HEADER_LENGTH;
1880
+ const chunkView = new DataView( data, BINARY_EXTENSION_HEADER_LENGTH );
1881
+ let chunkIndex = 0;
1882
+
1883
+ while ( chunkIndex < chunkContentsLength ) {
1884
+
1885
+ const chunkLength = chunkView.getUint32( chunkIndex, true );
1886
+ chunkIndex += 4;
1887
+
1888
+ const chunkType = chunkView.getUint32( chunkIndex, true );
1889
+ chunkIndex += 4;
1890
+
1891
+ if ( chunkType === BINARY_EXTENSION_CHUNK_TYPES.JSON ) {
1892
+
1893
+ const contentArray = new Uint8Array( data, BINARY_EXTENSION_HEADER_LENGTH + chunkIndex, chunkLength );
1894
+ this.content = textDecoder.decode( contentArray );
1895
+
1896
+ } else if ( chunkType === BINARY_EXTENSION_CHUNK_TYPES.BIN ) {
1897
+
1898
+ const byteOffset = BINARY_EXTENSION_HEADER_LENGTH + chunkIndex;
1899
+ this.body = data.slice( byteOffset, byteOffset + chunkLength );
1900
+
1901
+ }
1902
+
1903
+ // Clients must ignore chunks with unknown types.
1904
+
1905
+ chunkIndex += chunkLength;
1906
+
1907
+ }
1908
+
1909
+ if ( this.content === null ) {
1910
+
1911
+ throw new Error( 'THREE.GLTFLoader: JSON content not found.' );
1912
+
1913
+ }
1914
+
1915
+ }
1916
+
1917
+ }
1918
+
1919
+ /**
1920
+ * DRACO Mesh Compression Extension
1921
+ *
1922
+ * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_draco_mesh_compression
1923
+ *
1924
+ * @private
1925
+ */
1926
+ class GLTFDracoMeshCompressionExtension {
1927
+
1928
+ constructor( json, dracoLoader ) {
1929
+
1930
+ if ( ! dracoLoader ) {
1931
+
1932
+ throw new Error( 'THREE.GLTFLoader: No DRACOLoader instance provided.' );
1933
+
1934
+ }
1935
+
1936
+ this.name = EXTENSIONS.KHR_DRACO_MESH_COMPRESSION;
1937
+ this.json = json;
1938
+ this.dracoLoader = dracoLoader;
1939
+ this.dracoLoader.preload();
1940
+
1941
+ }
1942
+
1943
+ decodePrimitive( primitive, parser ) {
1944
+
1945
+ const json = this.json;
1946
+ const dracoLoader = this.dracoLoader;
1947
+ const bufferViewIndex = primitive.extensions[ this.name ].bufferView;
1948
+ const gltfAttributeMap = primitive.extensions[ this.name ].attributes;
1949
+ const threeAttributeMap = {};
1950
+ const attributeNormalizedMap = {};
1951
+ const attributeTypeMap = {};
1952
+
1953
+ for ( const attributeName in gltfAttributeMap ) {
1954
+
1955
+ const threeAttributeName = ATTRIBUTES[ attributeName ] || attributeName.toLowerCase();
1956
+
1957
+ threeAttributeMap[ threeAttributeName ] = gltfAttributeMap[ attributeName ];
1958
+
1959
+ }
1960
+
1961
+ for ( const attributeName in primitive.attributes ) {
1962
+
1963
+ const threeAttributeName = ATTRIBUTES[ attributeName ] || attributeName.toLowerCase();
1964
+
1965
+ if ( gltfAttributeMap[ attributeName ] !== undefined ) {
1966
+
1967
+ const accessorDef = json.accessors[ primitive.attributes[ attributeName ] ];
1968
+ const componentType = WEBGL_COMPONENT_TYPES[ accessorDef.componentType ];
1969
+
1970
+ attributeTypeMap[ threeAttributeName ] = componentType.name;
1971
+ attributeNormalizedMap[ threeAttributeName ] = accessorDef.normalized === true;
1972
+
1973
+ }
1974
+
1975
+ }
1976
+
1977
+ return parser.getDependency( 'bufferView', bufferViewIndex ).then( function ( bufferView ) {
1978
+
1979
+ return new Promise( function ( resolve, reject ) {
1980
+
1981
+ dracoLoader.decodeDracoFile( bufferView, function ( geometry ) {
1982
+
1983
+ for ( const attributeName in geometry.attributes ) {
1984
+
1985
+ const attribute = geometry.attributes[ attributeName ];
1986
+ const normalized = attributeNormalizedMap[ attributeName ];
1987
+
1988
+ if ( normalized !== undefined ) attribute.normalized = normalized;
1989
+
1990
+ }
1991
+
1992
+ resolve( geometry );
1993
+
1994
+ }, threeAttributeMap, attributeTypeMap, THREE.LinearSRGBColorSpace, reject );
1995
+
1996
+ } );
1997
+
1998
+ } );
1999
+
2000
+ }
2001
+
2002
+ }
2003
+
2004
+ /**
2005
+ * Texture Transform Extension
2006
+ *
2007
+ * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_texture_transform
2008
+ *
2009
+ * @private
2010
+ */
2011
+ class GLTFTextureTransformExtension {
2012
+
2013
+ constructor() {
2014
+
2015
+ this.name = EXTENSIONS.KHR_TEXTURE_TRANSFORM;
2016
+
2017
+ }
2018
+
2019
+ extendTexture( texture, transform ) {
2020
+
2021
+ if ( ( transform.texCoord === undefined || transform.texCoord === texture.channel )
2022
+ && transform.offset === undefined
2023
+ && transform.rotation === undefined
2024
+ && transform.scale === undefined ) {
2025
+
2026
+ // See https://github.com/mrdoob/three.js/issues/21819.
2027
+ return texture;
2028
+
2029
+ }
2030
+
2031
+ texture = texture.clone();
2032
+
2033
+ if ( transform.texCoord !== undefined ) {
2034
+
2035
+ texture.channel = transform.texCoord;
2036
+
2037
+ }
2038
+
2039
+ if ( transform.offset !== undefined ) {
2040
+
2041
+ texture.offset.fromArray( transform.offset );
2042
+
2043
+ }
2044
+
2045
+ if ( transform.rotation !== undefined ) {
2046
+
2047
+ texture.rotation = transform.rotation;
2048
+
2049
+ }
2050
+
2051
+ if ( transform.scale !== undefined ) {
2052
+
2053
+ texture.repeat.fromArray( transform.scale );
2054
+
2055
+ }
2056
+
2057
+ texture.needsUpdate = true;
2058
+
2059
+ return texture;
2060
+
2061
+ }
2062
+
2063
+ }
2064
+
2065
+ /**
2066
+ * Mesh Quantization Extension
2067
+ *
2068
+ * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_mesh_quantization
2069
+ *
2070
+ * @private
2071
+ */
2072
+ class GLTFMeshQuantizationExtension {
2073
+
2074
+ constructor() {
2075
+
2076
+ this.name = EXTENSIONS.KHR_MESH_QUANTIZATION;
2077
+
2078
+ }
2079
+
2080
+ }
2081
+
2082
+ /*********************************/
2083
+ /********** INTERPOLATION ********/
2084
+ /*********************************/
2085
+
2086
+ // Spline Interpolation
2087
+ // Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#appendix-c-spline-interpolation
2088
+ class GLTFCubicSplineInterpolant extends THREE.Interpolant {
2089
+
2090
+ constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
2091
+
2092
+ super( parameterPositions, sampleValues, sampleSize, resultBuffer );
2093
+
2094
+ }
2095
+
2096
+ copySampleValue_( index ) {
2097
+
2098
+ // Copies a sample value to the result buffer. See description of glTF
2099
+ // CUBICSPLINE values layout in interpolate_() function below.
2100
+
2101
+ const result = this.resultBuffer,
2102
+ values = this.sampleValues,
2103
+ valueSize = this.valueSize,
2104
+ offset = index * valueSize * 3 + valueSize;
2105
+
2106
+ for ( let i = 0; i !== valueSize; i ++ ) {
2107
+
2108
+ result[ i ] = values[ offset + i ];
2109
+
2110
+ }
2111
+
2112
+ return result;
2113
+
2114
+ }
2115
+
2116
+ interpolate_( i1, t0, t, t1 ) {
2117
+
2118
+ const result = this.resultBuffer;
2119
+ const values = this.sampleValues;
2120
+ const stride = this.valueSize;
2121
+
2122
+ const stride2 = stride * 2;
2123
+ const stride3 = stride * 3;
2124
+
2125
+ const td = t1 - t0;
2126
+
2127
+ const p = ( t - t0 ) / td;
2128
+ const pp = p * p;
2129
+ const ppp = pp * p;
2130
+
2131
+ const offset1 = i1 * stride3;
2132
+ const offset0 = offset1 - stride3;
2133
+
2134
+ const s2 = - 2 * ppp + 3 * pp;
2135
+ const s3 = ppp - pp;
2136
+ const s0 = 1 - s2;
2137
+ const s1 = s3 - pp + p;
2138
+
2139
+ // Layout of keyframe output values for CUBICSPLINE animations:
2140
+ // [ inTangent_1, splineVertex_1, outTangent_1, inTangent_2, splineVertex_2, ... ]
2141
+ for ( let i = 0; i !== stride; i ++ ) {
2142
+
2143
+ const p0 = values[ offset0 + i + stride ]; // splineVertex_k
2144
+ const m0 = values[ offset0 + i + stride2 ] * td; // outTangent_k * (t_k+1 - t_k)
2145
+ const p1 = values[ offset1 + i + stride ]; // splineVertex_k+1
2146
+ const m1 = values[ offset1 + i ] * td; // inTangent_k+1 * (t_k+1 - t_k)
2147
+
2148
+ result[ i ] = s0 * p0 + s1 * m0 + s2 * p1 + s3 * m1;
2149
+
2150
+ }
2151
+
2152
+ return result;
2153
+
2154
+ }
2155
+
2156
+ }
2157
+
2158
+ const _quaternion = new THREE.Quaternion();
2159
+
2160
+ class GLTFCubicSplineQuaternionInterpolant extends GLTFCubicSplineInterpolant {
2161
+
2162
+ interpolate_( i1, t0, t, t1 ) {
2163
+
2164
+ const result = super.interpolate_( i1, t0, t, t1 );
2165
+
2166
+ _quaternion.fromArray( result ).normalize().toArray( result );
2167
+
2168
+ return result;
2169
+
2170
+ }
2171
+
2172
+ }
2173
+
2174
+
2175
+ /*********************************/
2176
+ /********** INTERNALS ************/
2177
+ /*********************************/
2178
+
2179
+ /* CONSTANTS */
2180
+
2181
+ const WEBGL_CONSTANTS = {
2182
+ FLOAT: 5126,
2183
+ //FLOAT_MAT2: 35674,
2184
+ FLOAT_MAT3: 35675,
2185
+ FLOAT_MAT4: 35676,
2186
+ FLOAT_VEC2: 35664,
2187
+ FLOAT_VEC3: 35665,
2188
+ FLOAT_VEC4: 35666,
2189
+ LINEAR: 9729,
2190
+ REPEAT: 10497,
2191
+ SAMPLER_2D: 35678,
2192
+ POINTS: 0,
2193
+ LINES: 1,
2194
+ LINE_LOOP: 2,
2195
+ LINE_STRIP: 3,
2196
+ TRIANGLES: 4,
2197
+ TRIANGLE_STRIP: 5,
2198
+ TRIANGLE_FAN: 6,
2199
+ UNSIGNED_BYTE: 5121,
2200
+ UNSIGNED_SHORT: 5123
2201
+ };
2202
+
2203
+ const WEBGL_COMPONENT_TYPES = {
2204
+ 5120: Int8Array,
2205
+ 5121: Uint8Array,
2206
+ 5122: Int16Array,
2207
+ 5123: Uint16Array,
2208
+ 5125: Uint32Array,
2209
+ 5126: Float32Array
2210
+ };
2211
+
2212
+ const WEBGL_FILTERS = {
2213
+ 9728: THREE.NearestFilter,
2214
+ 9729: THREE.LinearFilter,
2215
+ 9984: THREE.NearestMipmapNearestFilter,
2216
+ 9985: THREE.LinearMipmapNearestFilter,
2217
+ 9986: THREE.NearestMipmapLinearFilter,
2218
+ 9987: THREE.LinearMipmapLinearFilter
2219
+ };
2220
+
2221
+ const WEBGL_WRAPPINGS = {
2222
+ 33071: THREE.ClampToEdgeWrapping,
2223
+ 33648: THREE.MirroredRepeatWrapping,
2224
+ 10497: THREE.RepeatWrapping
2225
+ };
2226
+
2227
+ const WEBGL_TYPE_SIZES = {
2228
+ 'SCALAR': 1,
2229
+ 'VEC2': 2,
2230
+ 'VEC3': 3,
2231
+ 'VEC4': 4,
2232
+ 'MAT2': 4,
2233
+ 'MAT3': 9,
2234
+ 'MAT4': 16
2235
+ };
2236
+
2237
+ const ATTRIBUTES = {
2238
+ POSITION: 'position',
2239
+ NORMAL: 'normal',
2240
+ TANGENT: 'tangent',
2241
+ TEXCOORD_0: 'uv',
2242
+ TEXCOORD_1: 'uv1',
2243
+ TEXCOORD_2: 'uv2',
2244
+ TEXCOORD_3: 'uv3',
2245
+ COLOR_0: 'color',
2246
+ WEIGHTS_0: 'skinWeight',
2247
+ JOINTS_0: 'skinIndex',
2248
+ };
2249
+
2250
+ const PATH_PROPERTIES = {
2251
+ scale: 'scale',
2252
+ translation: 'position',
2253
+ rotation: 'quaternion',
2254
+ weights: 'morphTargetInfluences'
2255
+ };
2256
+
2257
+ const INTERPOLATION = {
2258
+ CUBICSPLINE: undefined, // We use a custom interpolant (GLTFCubicSplineInterpolation) for CUBICSPLINE tracks. Each
2259
+ // keyframe track will be initialized with a default interpolation type, then modified.
2260
+ LINEAR: THREE.InterpolateLinear,
2261
+ STEP: THREE.InterpolateDiscrete
2262
+ };
2263
+
2264
+ const ALPHA_MODES = {
2265
+ OPAQUE: 'OPAQUE',
2266
+ MASK: 'MASK',
2267
+ BLEND: 'BLEND'
2268
+ };
2269
+
2270
+ /**
2271
+ * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#default-material
2272
+ *
2273
+ * @private
2274
+ * @param {Object<string, Material>} cache
2275
+ * @return {Material}
2276
+ */
2277
+ function createDefaultMaterial( cache ) {
2278
+
2279
+ if ( cache[ 'DefaultMaterial' ] === undefined ) {
2280
+
2281
+ cache[ 'DefaultMaterial' ] = new THREE.MeshStandardMaterial( {
2282
+ color: 0xFFFFFF,
2283
+ emissive: 0x000000,
2284
+ metalness: 1,
2285
+ roughness: 1,
2286
+ transparent: false,
2287
+ depthTest: true,
2288
+ side: THREE.FrontSide
2289
+ } );
2290
+
2291
+ }
2292
+
2293
+ return cache[ 'DefaultMaterial' ];
2294
+
2295
+ }
2296
+
2297
+ function addUnknownExtensionsToUserData( knownExtensions, object, objectDef ) {
2298
+
2299
+ // Add unknown glTF extensions to an object's userData.
2300
+
2301
+ for ( const name in objectDef.extensions ) {
2302
+
2303
+ if ( knownExtensions[ name ] === undefined ) {
2304
+
2305
+ object.userData.gltfExtensions = object.userData.gltfExtensions || {};
2306
+ object.userData.gltfExtensions[ name ] = objectDef.extensions[ name ];
2307
+
2308
+ }
2309
+
2310
+ }
2311
+
2312
+ }
2313
+
2314
+ /**
2315
+ *
2316
+ * @private
2317
+ * @param {Object3D|Material|BufferGeometry|Object} object
2318
+ * @param {GLTF.definition} gltfDef
2319
+ */
2320
+ function assignExtrasToUserData( object, gltfDef ) {
2321
+
2322
+ if ( gltfDef.extras !== undefined ) {
2323
+
2324
+ if ( typeof gltfDef.extras === 'object' ) {
2325
+
2326
+ Object.assign( object.userData, gltfDef.extras );
2327
+
2328
+ } else {
2329
+
2330
+ console.warn( 'THREE.GLTFLoader: Ignoring primitive type .extras, ' + gltfDef.extras );
2331
+
2332
+ }
2333
+
2334
+ }
2335
+
2336
+ }
2337
+
2338
+ /**
2339
+ * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#morph-targets
2340
+ *
2341
+ * @private
2342
+ * @param {BufferGeometry} geometry
2343
+ * @param {Array<GLTF.Target>} targets
2344
+ * @param {GLTFParser} parser
2345
+ * @return {Promise<BufferGeometry>}
2346
+ */
2347
+ function addMorphTargets( geometry, targets, parser ) {
2348
+
2349
+ let hasMorphPosition = false;
2350
+ let hasMorphNormal = false;
2351
+ let hasMorphColor = false;
2352
+
2353
+ for ( let i = 0, il = targets.length; i < il; i ++ ) {
2354
+
2355
+ const target = targets[ i ];
2356
+
2357
+ if ( target.POSITION !== undefined ) hasMorphPosition = true;
2358
+ if ( target.NORMAL !== undefined ) hasMorphNormal = true;
2359
+ if ( target.COLOR_0 !== undefined ) hasMorphColor = true;
2360
+
2361
+ if ( hasMorphPosition && hasMorphNormal && hasMorphColor ) break;
2362
+
2363
+ }
2364
+
2365
+ if ( ! hasMorphPosition && ! hasMorphNormal && ! hasMorphColor ) return Promise.resolve( geometry );
2366
+
2367
+ const pendingPositionAccessors = [];
2368
+ const pendingNormalAccessors = [];
2369
+ const pendingColorAccessors = [];
2370
+
2371
+ for ( let i = 0, il = targets.length; i < il; i ++ ) {
2372
+
2373
+ const target = targets[ i ];
2374
+
2375
+ if ( hasMorphPosition ) {
2376
+
2377
+ const pendingAccessor = target.POSITION !== undefined
2378
+ ? parser.getDependency( 'accessor', target.POSITION )
2379
+ : geometry.attributes.position;
2380
+
2381
+ pendingPositionAccessors.push( pendingAccessor );
2382
+
2383
+ }
2384
+
2385
+ if ( hasMorphNormal ) {
2386
+
2387
+ const pendingAccessor = target.NORMAL !== undefined
2388
+ ? parser.getDependency( 'accessor', target.NORMAL )
2389
+ : geometry.attributes.normal;
2390
+
2391
+ pendingNormalAccessors.push( pendingAccessor );
2392
+
2393
+ }
2394
+
2395
+ if ( hasMorphColor ) {
2396
+
2397
+ const pendingAccessor = target.COLOR_0 !== undefined
2398
+ ? parser.getDependency( 'accessor', target.COLOR_0 )
2399
+ : geometry.attributes.color;
2400
+
2401
+ pendingColorAccessors.push( pendingAccessor );
2402
+
2403
+ }
2404
+
2405
+ }
2406
+
2407
+ return Promise.all( [
2408
+ Promise.all( pendingPositionAccessors ),
2409
+ Promise.all( pendingNormalAccessors ),
2410
+ Promise.all( pendingColorAccessors )
2411
+ ] ).then( function ( accessors ) {
2412
+
2413
+ const morphPositions = accessors[ 0 ];
2414
+ const morphNormals = accessors[ 1 ];
2415
+ const morphColors = accessors[ 2 ];
2416
+
2417
+ if ( hasMorphPosition ) geometry.morphAttributes.position = morphPositions;
2418
+ if ( hasMorphNormal ) geometry.morphAttributes.normal = morphNormals;
2419
+ if ( hasMorphColor ) geometry.morphAttributes.color = morphColors;
2420
+ geometry.morphTargetsRelative = true;
2421
+
2422
+ return geometry;
2423
+
2424
+ } );
2425
+
2426
+ }
2427
+
2428
+ /**
2429
+ *
2430
+ * @private
2431
+ * @param {Mesh} mesh
2432
+ * @param {GLTF.Mesh} meshDef
2433
+ */
2434
+ function updateMorphTargets( mesh, meshDef ) {
2435
+
2436
+ mesh.updateMorphTargets();
2437
+
2438
+ if ( meshDef.weights !== undefined ) {
2439
+
2440
+ for ( let i = 0, il = meshDef.weights.length; i < il; i ++ ) {
2441
+
2442
+ mesh.morphTargetInfluences[ i ] = meshDef.weights[ i ];
2443
+
2444
+ }
2445
+
2446
+ }
2447
+
2448
+ // .extras has user-defined data, so check that .extras.targetNames is an array.
2449
+ if ( meshDef.extras && Array.isArray( meshDef.extras.targetNames ) ) {
2450
+
2451
+ const targetNames = meshDef.extras.targetNames;
2452
+
2453
+ if ( mesh.morphTargetInfluences.length === targetNames.length ) {
2454
+
2455
+ mesh.morphTargetDictionary = {};
2456
+
2457
+ for ( let i = 0, il = targetNames.length; i < il; i ++ ) {
2458
+
2459
+ mesh.morphTargetDictionary[ targetNames[ i ] ] = i;
2460
+
2461
+ }
2462
+
2463
+ } else {
2464
+
2465
+ console.warn( 'THREE.GLTFLoader: Invalid extras.targetNames length. Ignoring names.' );
2466
+
2467
+ }
2468
+
2469
+ }
2470
+
2471
+ }
2472
+
2473
+ function createPrimitiveKey( primitiveDef ) {
2474
+
2475
+ let geometryKey;
2476
+
2477
+ const dracoExtension = primitiveDef.extensions && primitiveDef.extensions[ EXTENSIONS.KHR_DRACO_MESH_COMPRESSION ];
2478
+
2479
+ if ( dracoExtension ) {
2480
+
2481
+ geometryKey = 'draco:' + dracoExtension.bufferView
2482
+ + ':' + dracoExtension.indices
2483
+ + ':' + createAttributesKey( dracoExtension.attributes );
2484
+
2485
+ } else {
2486
+
2487
+ geometryKey = primitiveDef.indices + ':' + createAttributesKey( primitiveDef.attributes ) + ':' + primitiveDef.mode;
2488
+
2489
+ }
2490
+
2491
+ if ( primitiveDef.targets !== undefined ) {
2492
+
2493
+ for ( let i = 0, il = primitiveDef.targets.length; i < il; i ++ ) {
2494
+
2495
+ geometryKey += ':' + createAttributesKey( primitiveDef.targets[ i ] );
2496
+
2497
+ }
2498
+
2499
+ }
2500
+
2501
+ return geometryKey;
2502
+
2503
+ }
2504
+
2505
+ function createAttributesKey( attributes ) {
2506
+
2507
+ let attributesKey = '';
2508
+
2509
+ const keys = Object.keys( attributes ).sort();
2510
+
2511
+ for ( let i = 0, il = keys.length; i < il; i ++ ) {
2512
+
2513
+ attributesKey += keys[ i ] + ':' + attributes[ keys[ i ] ] + ';';
2514
+
2515
+ }
2516
+
2517
+ return attributesKey;
2518
+
2519
+ }
2520
+
2521
+ function getNormalizedComponentScale( constructor ) {
2522
+
2523
+ // Reference:
2524
+ // https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_mesh_quantization#encoding-quantized-data
2525
+
2526
+ switch ( constructor ) {
2527
+
2528
+ case Int8Array:
2529
+ return 1 / 127;
2530
+
2531
+ case Uint8Array:
2532
+ return 1 / 255;
2533
+
2534
+ case Int16Array:
2535
+ return 1 / 32767;
2536
+
2537
+ case Uint16Array:
2538
+ return 1 / 65535;
2539
+
2540
+ default:
2541
+ throw new Error( 'THREE.GLTFLoader: Unsupported normalized accessor component type.' );
2542
+
2543
+ }
2544
+
2545
+ }
2546
+
2547
+ function getImageURIMimeType( uri ) {
2548
+
2549
+ if ( uri.search( /\.jpe?g($|\?)/i ) > 0 || uri.search( /^data\:image\/jpeg/ ) === 0 ) return 'image/jpeg';
2550
+ if ( uri.search( /\.webp($|\?)/i ) > 0 || uri.search( /^data\:image\/webp/ ) === 0 ) return 'image/webp';
2551
+ if ( uri.search( /\.ktx2($|\?)/i ) > 0 || uri.search( /^data\:image\/ktx2/ ) === 0 ) return 'image/ktx2';
2552
+
2553
+ return 'image/png';
2554
+
2555
+ }
2556
+
2557
+ const _identityMatrix = new THREE.Matrix4();
2558
+
2559
+ /* GLTF PARSER */
2560
+
2561
+ class GLTFParser {
2562
+
2563
+ constructor( json = {}, options = {} ) {
2564
+
2565
+ this.json = json;
2566
+ this.extensions = {};
2567
+ this.plugins = {};
2568
+ this.options = options;
2569
+
2570
+ // loader object cache
2571
+ this.cache = new GLTFRegistry();
2572
+
2573
+ // associations between Three.js objects and glTF elements
2574
+ this.associations = new Map();
2575
+
2576
+ // BufferGeometry caching
2577
+ this.primitiveCache = {};
2578
+
2579
+ // Node cache
2580
+ this.nodeCache = {};
2581
+
2582
+ // Object3D instance caches
2583
+ this.meshCache = { refs: {}, uses: {} };
2584
+ this.cameraCache = { refs: {}, uses: {} };
2585
+ this.lightCache = { refs: {}, uses: {} };
2586
+
2587
+ this.sourceCache = {};
2588
+ this.textureCache = {};
2589
+
2590
+ // Track node names, to ensure no duplicates
2591
+ this.nodeNamesUsed = {};
2592
+
2593
+ // Use an ImageBitmapLoader if imageBitmaps are supported. Moves much of the
2594
+ // expensive work of uploading a texture to the GPU off the main thread.
2595
+
2596
+ let isSafari = false;
2597
+ let safariVersion = - 1;
2598
+ let isFirefox = false;
2599
+ let firefoxVersion = - 1;
2600
+
2601
+ if ( typeof navigator !== 'undefined' ) {
2602
+
2603
+ const userAgent = navigator.userAgent;
2604
+
2605
+ isSafari = /^((?!chrome|android).)*safari/i.test( userAgent ) === true;
2606
+ const safariMatch = userAgent.match( /Version\/(\d+)/ );
2607
+ safariVersion = isSafari && safariMatch ? parseInt( safariMatch[ 1 ], 10 ) : - 1;
2608
+
2609
+ isFirefox = userAgent.indexOf( 'Firefox' ) > - 1;
2610
+ firefoxVersion = isFirefox ? userAgent.match( /Firefox\/([0-9]+)\./ )[ 1 ] : - 1;
2611
+
2612
+ }
2613
+
2614
+ if ( typeof createImageBitmap === 'undefined' || ( isSafari && safariVersion < 17 ) || ( isFirefox && firefoxVersion < 98 ) ) {
2615
+
2616
+ this.textureLoader = new THREE.TextureLoader( this.options.manager );
2617
+
2618
+ } else {
2619
+
2620
+ this.textureLoader = new THREE.ImageBitmapLoader( this.options.manager );
2621
+
2622
+ }
2623
+
2624
+ this.textureLoader.setCrossOrigin( this.options.crossOrigin );
2625
+ this.textureLoader.setRequestHeader( this.options.requestHeader );
2626
+
2627
+ this.fileLoader = new THREE.FileLoader( this.options.manager );
2628
+ this.fileLoader.setResponseType( 'arraybuffer' );
2629
+
2630
+ if ( this.options.crossOrigin === 'use-credentials' ) {
2631
+
2632
+ this.fileLoader.setWithCredentials( true );
2633
+
2634
+ }
2635
+
2636
+ }
2637
+
2638
+ setExtensions( extensions ) {
2639
+
2640
+ this.extensions = extensions;
2641
+
2642
+ }
2643
+
2644
+ setPlugins( plugins ) {
2645
+
2646
+ this.plugins = plugins;
2647
+
2648
+ }
2649
+
2650
+ parse( onLoad, onError ) {
2651
+
2652
+ const parser = this;
2653
+ const json = this.json;
2654
+ const extensions = this.extensions;
2655
+
2656
+ // Clear the loader cache
2657
+ this.cache.removeAll();
2658
+ this.nodeCache = {};
2659
+
2660
+ // Mark the special nodes/meshes in json for efficient parse
2661
+ this._invokeAll( function ( ext ) {
2662
+
2663
+ return ext._markDefs && ext._markDefs();
2664
+
2665
+ } );
2666
+
2667
+ Promise.all( this._invokeAll( function ( ext ) {
2668
+
2669
+ return ext.beforeRoot && ext.beforeRoot();
2670
+
2671
+ } ) ).then( function () {
2672
+
2673
+ return Promise.all( [
2674
+
2675
+ parser.getDependencies( 'scene' ),
2676
+ parser.getDependencies( 'animation' ),
2677
+ parser.getDependencies( 'camera' ),
2678
+
2679
+ ] );
2680
+
2681
+ } ).then( function ( dependencies ) {
2682
+
2683
+ const result = {
2684
+ scene: dependencies[ 0 ][ json.scene || 0 ],
2685
+ scenes: dependencies[ 0 ],
2686
+ animations: dependencies[ 1 ],
2687
+ cameras: dependencies[ 2 ],
2688
+ asset: json.asset,
2689
+ parser: parser,
2690
+ userData: {}
2691
+ };
2692
+
2693
+ addUnknownExtensionsToUserData( extensions, result, json );
2694
+
2695
+ assignExtrasToUserData( result, json );
2696
+
2697
+ return Promise.all( parser._invokeAll( function ( ext ) {
2698
+
2699
+ return ext.afterRoot && ext.afterRoot( result );
2700
+
2701
+ } ) ).then( function () {
2702
+
2703
+ for ( const scene of result.scenes ) {
2704
+
2705
+ scene.updateMatrixWorld();
2706
+
2707
+ }
2708
+
2709
+ onLoad( result );
2710
+
2711
+ } );
2712
+
2713
+ } ).catch( onError );
2714
+
2715
+ }
2716
+
2717
+ /**
2718
+ * Marks the special nodes/meshes in json for efficient parse.
2719
+ *
2720
+ * @private
2721
+ */
2722
+ _markDefs() {
2723
+
2724
+ const nodeDefs = this.json.nodes || [];
2725
+ const skinDefs = this.json.skins || [];
2726
+ const meshDefs = this.json.meshes || [];
2727
+
2728
+ // Nothing in the node definition indicates whether it is a Bone or an
2729
+ // Object3D. Use the skins' joint references to mark bones.
2730
+ for ( let skinIndex = 0, skinLength = skinDefs.length; skinIndex < skinLength; skinIndex ++ ) {
2731
+
2732
+ const joints = skinDefs[ skinIndex ].joints;
2733
+
2734
+ for ( let i = 0, il = joints.length; i < il; i ++ ) {
2735
+
2736
+ nodeDefs[ joints[ i ] ].isBone = true;
2737
+
2738
+ }
2739
+
2740
+ }
2741
+
2742
+ // Iterate over all nodes, marking references to shared resources,
2743
+ // as well as skeleton joints.
2744
+ for ( let nodeIndex = 0, nodeLength = nodeDefs.length; nodeIndex < nodeLength; nodeIndex ++ ) {
2745
+
2746
+ const nodeDef = nodeDefs[ nodeIndex ];
2747
+
2748
+ if ( nodeDef.mesh !== undefined ) {
2749
+
2750
+ this._addNodeRef( this.meshCache, nodeDef.mesh );
2751
+
2752
+ // Nothing in the mesh definition indicates whether it is
2753
+ // a SkinnedMesh or Mesh. Use the node's mesh reference
2754
+ // to mark SkinnedMesh if node has skin.
2755
+ if ( nodeDef.skin !== undefined ) {
2756
+
2757
+ meshDefs[ nodeDef.mesh ].isSkinnedMesh = true;
2758
+
2759
+ }
2760
+
2761
+ }
2762
+
2763
+ if ( nodeDef.camera !== undefined ) {
2764
+
2765
+ this._addNodeRef( this.cameraCache, nodeDef.camera );
2766
+
2767
+ }
2768
+
2769
+ }
2770
+
2771
+ }
2772
+
2773
+ /**
2774
+ * Counts references to shared node / Object3D resources. These resources
2775
+ * can be reused, or "instantiated", at multiple nodes in the scene
2776
+ * hierarchy. Mesh, Camera, and Light instances are instantiated and must
2777
+ * be marked. Non-scenegraph resources (like Materials, Geometries, and
2778
+ * Textures) can be reused directly and are not marked here.
2779
+ *
2780
+ * Example: CesiumMilkTruck sample model reuses "Wheel" meshes.
2781
+ *
2782
+ * @private
2783
+ * @param {Object} cache
2784
+ * @param {Object3D} index
2785
+ */
2786
+ _addNodeRef( cache, index ) {
2787
+
2788
+ if ( index === undefined ) return;
2789
+
2790
+ if ( cache.refs[ index ] === undefined ) {
2791
+
2792
+ cache.refs[ index ] = cache.uses[ index ] = 0;
2793
+
2794
+ }
2795
+
2796
+ cache.refs[ index ] ++;
2797
+
2798
+ }
2799
+
2800
+ /**
2801
+ * Returns a reference to a shared resource, cloning it if necessary.
2802
+ *
2803
+ * @private
2804
+ * @param {Object} cache
2805
+ * @param {number} index
2806
+ * @param {Object} object
2807
+ * @return {Object}
2808
+ */
2809
+ _getNodeRef( cache, index, object ) {
2810
+
2811
+ if ( cache.refs[ index ] <= 1 ) return object;
2812
+
2813
+ const ref = object.clone();
2814
+
2815
+ // Propagates mappings to the cloned object, prevents mappings on the
2816
+ // original object from being lost.
2817
+ const updateMappings = ( original, clone ) => {
2818
+
2819
+ const mappings = this.associations.get( original );
2820
+ if ( mappings != null ) {
2821
+
2822
+ this.associations.set( clone, mappings );
2823
+
2824
+ }
2825
+
2826
+ for ( const [ i, child ] of original.children.entries() ) {
2827
+
2828
+ updateMappings( child, clone.children[ i ] );
2829
+
2830
+ }
2831
+
2832
+ };
2833
+
2834
+ updateMappings( object, ref );
2835
+
2836
+ ref.name += '_instance_' + ( cache.uses[ index ] ++ );
2837
+
2838
+ return ref;
2839
+
2840
+ }
2841
+
2842
+ _invokeOne( func ) {
2843
+
2844
+ const extensions = Object.values( this.plugins );
2845
+ extensions.push( this );
2846
+
2847
+ for ( let i = 0; i < extensions.length; i ++ ) {
2848
+
2849
+ const result = func( extensions[ i ] );
2850
+
2851
+ if ( result ) return result;
2852
+
2853
+ }
2854
+
2855
+ return null;
2856
+
2857
+ }
2858
+
2859
+ _invokeAll( func ) {
2860
+
2861
+ const extensions = Object.values( this.plugins );
2862
+ extensions.unshift( this );
2863
+
2864
+ const pending = [];
2865
+
2866
+ for ( let i = 0; i < extensions.length; i ++ ) {
2867
+
2868
+ const result = func( extensions[ i ] );
2869
+
2870
+ if ( result ) pending.push( result );
2871
+
2872
+ }
2873
+
2874
+ return pending;
2875
+
2876
+ }
2877
+
2878
+ /**
2879
+ * Requests the specified dependency asynchronously, with caching.
2880
+ *
2881
+ * @private
2882
+ * @param {string} type
2883
+ * @param {number} index
2884
+ * @return {Promise<Object3D|Material|THREE.Texture|AnimationClip|ArrayBuffer|Object>}
2885
+ */
2886
+ getDependency( type, index ) {
2887
+
2888
+ const cacheKey = type + ':' + index;
2889
+ let dependency = this.cache.get( cacheKey );
2890
+
2891
+ if ( ! dependency ) {
2892
+
2893
+ switch ( type ) {
2894
+
2895
+ case 'scene':
2896
+ dependency = this.loadScene( index );
2897
+ break;
2898
+
2899
+ case 'node':
2900
+ dependency = this._invokeOne( function ( ext ) {
2901
+
2902
+ return ext.loadNode && ext.loadNode( index );
2903
+
2904
+ } );
2905
+ break;
2906
+
2907
+ case 'mesh':
2908
+ dependency = this._invokeOne( function ( ext ) {
2909
+
2910
+ return ext.loadMesh && ext.loadMesh( index );
2911
+
2912
+ } );
2913
+ break;
2914
+
2915
+ case 'accessor':
2916
+ dependency = this.loadAccessor( index );
2917
+ break;
2918
+
2919
+ case 'bufferView':
2920
+ dependency = this._invokeOne( function ( ext ) {
2921
+
2922
+ return ext.loadBufferView && ext.loadBufferView( index );
2923
+
2924
+ } );
2925
+ break;
2926
+
2927
+ case 'buffer':
2928
+ dependency = this.loadBuffer( index );
2929
+ break;
2930
+
2931
+ case 'material':
2932
+ dependency = this._invokeOne( function ( ext ) {
2933
+
2934
+ return ext.loadMaterial && ext.loadMaterial( index );
2935
+
2936
+ } );
2937
+ break;
2938
+
2939
+ case 'texture':
2940
+ dependency = this._invokeOne( function ( ext ) {
2941
+
2942
+ return ext.loadTexture && ext.loadTexture( index );
2943
+
2944
+ } );
2945
+ break;
2946
+
2947
+ case 'skin':
2948
+ dependency = this.loadSkin( index );
2949
+ break;
2950
+
2951
+ case 'animation':
2952
+ dependency = this._invokeOne( function ( ext ) {
2953
+
2954
+ return ext.loadAnimation && ext.loadAnimation( index );
2955
+
2956
+ } );
2957
+ break;
2958
+
2959
+ case 'camera':
2960
+ dependency = this.loadCamera( index );
2961
+ break;
2962
+
2963
+ default:
2964
+ dependency = this._invokeOne( function ( ext ) {
2965
+
2966
+ return ext != this && ext.getDependency && ext.getDependency( type, index );
2967
+
2968
+ } );
2969
+
2970
+ if ( ! dependency ) {
2971
+
2972
+ throw new Error( 'Unknown type: ' + type );
2973
+
2974
+ }
2975
+
2976
+ break;
2977
+
2978
+ }
2979
+
2980
+ this.cache.add( cacheKey, dependency );
2981
+
2982
+ }
2983
+
2984
+ return dependency;
2985
+
2986
+ }
2987
+
2988
+ /**
2989
+ * Requests all dependencies of the specified type asynchronously, with caching.
2990
+ *
2991
+ * @private
2992
+ * @param {string} type
2993
+ * @return {Promise<Array<Object>>}
2994
+ */
2995
+ getDependencies( type ) {
2996
+
2997
+ let dependencies = this.cache.get( type );
2998
+
2999
+ if ( ! dependencies ) {
3000
+
3001
+ const parser = this;
3002
+ const defs = this.json[ type + ( type === 'mesh' ? 'es' : 's' ) ] || [];
3003
+
3004
+ dependencies = Promise.all( defs.map( function ( def, index ) {
3005
+
3006
+ return parser.getDependency( type, index );
3007
+
3008
+ } ) );
3009
+
3010
+ this.cache.add( type, dependencies );
3011
+
3012
+ }
3013
+
3014
+ return dependencies;
3015
+
3016
+ }
3017
+
3018
+ /**
3019
+ * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#buffers-and-buffer-views
3020
+ *
3021
+ * @private
3022
+ * @param {number} bufferIndex
3023
+ * @return {Promise<ArrayBuffer>}
3024
+ */
3025
+ loadBuffer( bufferIndex ) {
3026
+
3027
+ const bufferDef = this.json.buffers[ bufferIndex ];
3028
+ const loader = this.fileLoader;
3029
+
3030
+ if ( bufferDef.type && bufferDef.type !== 'arraybuffer' ) {
3031
+
3032
+ throw new Error( 'THREE.GLTFLoader: ' + bufferDef.type + ' buffer type is not supported.' );
3033
+
3034
+ }
3035
+
3036
+ // If present, GLB container is required to be the first buffer.
3037
+ if ( bufferDef.uri === undefined && bufferIndex === 0 ) {
3038
+
3039
+ return Promise.resolve( this.extensions[ EXTENSIONS.KHR_BINARY_GLTF ].body );
3040
+
3041
+ }
3042
+
3043
+ const options = this.options;
3044
+
3045
+ return new Promise( function ( resolve, reject ) {
3046
+
3047
+ loader.load( THREE.LoaderUtils.resolveURL( bufferDef.uri, options.path ), resolve, undefined, function () {
3048
+
3049
+ reject( new Error( 'THREE.GLTFLoader: Failed to load buffer "' + bufferDef.uri + '".' ) );
3050
+
3051
+ } );
3052
+
3053
+ } );
3054
+
3055
+ }
3056
+
3057
+ /**
3058
+ * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#buffers-and-buffer-views
3059
+ *
3060
+ * @private
3061
+ * @param {number} bufferViewIndex
3062
+ * @return {Promise<ArrayBuffer>}
3063
+ */
3064
+ loadBufferView( bufferViewIndex ) {
3065
+
3066
+ const bufferViewDef = this.json.bufferViews[ bufferViewIndex ];
3067
+
3068
+ return this.getDependency( 'buffer', bufferViewDef.buffer ).then( function ( buffer ) {
3069
+
3070
+ const byteLength = bufferViewDef.byteLength || 0;
3071
+ const byteOffset = bufferViewDef.byteOffset || 0;
3072
+ return buffer.slice( byteOffset, byteOffset + byteLength );
3073
+
3074
+ } );
3075
+
3076
+ }
3077
+
3078
+ /**
3079
+ * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#accessors
3080
+ *
3081
+ * @private
3082
+ * @param {number} accessorIndex
3083
+ * @return {Promise<BufferAttribute|InterleavedBufferAttribute>}
3084
+ */
3085
+ loadAccessor( accessorIndex ) {
3086
+
3087
+ const parser = this;
3088
+ const json = this.json;
3089
+
3090
+ const accessorDef = this.json.accessors[ accessorIndex ];
3091
+
3092
+ if ( accessorDef.bufferView === undefined && accessorDef.sparse === undefined ) {
3093
+
3094
+ const itemSize = WEBGL_TYPE_SIZES[ accessorDef.type ];
3095
+ const TypedArray = WEBGL_COMPONENT_TYPES[ accessorDef.componentType ];
3096
+ const normalized = accessorDef.normalized === true;
3097
+
3098
+ const array = new TypedArray( accessorDef.count * itemSize );
3099
+ return Promise.resolve( new THREE.BufferAttribute( array, itemSize, normalized ) );
3100
+
3101
+ }
3102
+
3103
+ const pendingBufferViews = [];
3104
+
3105
+ if ( accessorDef.bufferView !== undefined ) {
3106
+
3107
+ pendingBufferViews.push( this.getDependency( 'bufferView', accessorDef.bufferView ) );
3108
+
3109
+ } else {
3110
+
3111
+ pendingBufferViews.push( null );
3112
+
3113
+ }
3114
+
3115
+ if ( accessorDef.sparse !== undefined ) {
3116
+
3117
+ pendingBufferViews.push( this.getDependency( 'bufferView', accessorDef.sparse.indices.bufferView ) );
3118
+ pendingBufferViews.push( this.getDependency( 'bufferView', accessorDef.sparse.values.bufferView ) );
3119
+
3120
+ }
3121
+
3122
+ return Promise.all( pendingBufferViews ).then( function ( bufferViews ) {
3123
+
3124
+ const bufferView = bufferViews[ 0 ];
3125
+
3126
+ const itemSize = WEBGL_TYPE_SIZES[ accessorDef.type ];
3127
+ const TypedArray = WEBGL_COMPONENT_TYPES[ accessorDef.componentType ];
3128
+
3129
+ // For VEC3: itemSize is 3, elementBytes is 4, itemBytes is 12.
3130
+ const elementBytes = TypedArray.BYTES_PER_ELEMENT;
3131
+ const itemBytes = elementBytes * itemSize;
3132
+ const byteOffset = accessorDef.byteOffset || 0;
3133
+ const byteStride = accessorDef.bufferView !== undefined ? json.bufferViews[ accessorDef.bufferView ].byteStride : undefined;
3134
+ const normalized = accessorDef.normalized === true;
3135
+ let array, bufferAttribute;
3136
+
3137
+ // The buffer is not interleaved if the stride is the item size in bytes.
3138
+ if ( byteStride && byteStride !== itemBytes ) {
3139
+
3140
+ // Each "slice" of the buffer, as defined by 'count' elements of 'byteStride' bytes, gets its own InterleavedBuffer
3141
+ // This makes sure that IBA.count reflects accessor.count properly
3142
+ const ibSlice = Math.floor( byteOffset / byteStride );
3143
+ const ibCacheKey = 'InterleavedBuffer:' + accessorDef.bufferView + ':' + accessorDef.componentType + ':' + ibSlice + ':' + accessorDef.count;
3144
+ let ib = parser.cache.get( ibCacheKey );
3145
+
3146
+ if ( ! ib ) {
3147
+
3148
+ array = new TypedArray( bufferView, ibSlice * byteStride, accessorDef.count * byteStride / elementBytes );
3149
+
3150
+ // Integer parameters to IB/IBA are in array elements, not bytes.
3151
+ ib = new THREE.InterleavedBuffer( array, byteStride / elementBytes );
3152
+
3153
+ parser.cache.add( ibCacheKey, ib );
3154
+
3155
+ }
3156
+
3157
+ bufferAttribute = new THREE.InterleavedBufferAttribute( ib, itemSize, ( byteOffset % byteStride ) / elementBytes, normalized );
3158
+
3159
+ } else {
3160
+
3161
+ if ( bufferView === null ) {
3162
+
3163
+ array = new TypedArray( accessorDef.count * itemSize );
3164
+
3165
+ } else {
3166
+
3167
+ array = new TypedArray( bufferView, byteOffset, accessorDef.count * itemSize );
3168
+
3169
+ }
3170
+
3171
+ bufferAttribute = new THREE.BufferAttribute( array, itemSize, normalized );
3172
+
3173
+ }
3174
+
3175
+ // https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#sparse-accessors
3176
+ if ( accessorDef.sparse !== undefined ) {
3177
+
3178
+ const itemSizeIndices = WEBGL_TYPE_SIZES.SCALAR;
3179
+ const TypedArrayIndices = WEBGL_COMPONENT_TYPES[ accessorDef.sparse.indices.componentType ];
3180
+
3181
+ const byteOffsetIndices = accessorDef.sparse.indices.byteOffset || 0;
3182
+ const byteOffsetValues = accessorDef.sparse.values.byteOffset || 0;
3183
+
3184
+ const sparseIndices = new TypedArrayIndices( bufferViews[ 1 ], byteOffsetIndices, accessorDef.sparse.count * itemSizeIndices );
3185
+ const sparseValues = new TypedArray( bufferViews[ 2 ], byteOffsetValues, accessorDef.sparse.count * itemSize );
3186
+
3187
+ if ( bufferView !== null ) {
3188
+
3189
+ // Avoid modifying the original ArrayBuffer, if the bufferView wasn't initialized with zeroes.
3190
+ bufferAttribute = new THREE.BufferAttribute( bufferAttribute.array.slice(), bufferAttribute.itemSize, bufferAttribute.normalized );
3191
+
3192
+ }
3193
+
3194
+ // Ignore normalized since we copy from sparse
3195
+ bufferAttribute.normalized = false;
3196
+
3197
+ for ( let i = 0, il = sparseIndices.length; i < il; i ++ ) {
3198
+
3199
+ const index = sparseIndices[ i ];
3200
+
3201
+ bufferAttribute.setX( index, sparseValues[ i * itemSize ] );
3202
+ if ( itemSize >= 2 ) bufferAttribute.setY( index, sparseValues[ i * itemSize + 1 ] );
3203
+ if ( itemSize >= 3 ) bufferAttribute.setZ( index, sparseValues[ i * itemSize + 2 ] );
3204
+ if ( itemSize >= 4 ) bufferAttribute.setW( index, sparseValues[ i * itemSize + 3 ] );
3205
+ if ( itemSize >= 5 ) throw new Error( 'THREE.GLTFLoader: Unsupported itemSize in sparse BufferAttribute.' );
3206
+
3207
+ }
3208
+
3209
+ bufferAttribute.normalized = normalized;
3210
+
3211
+ }
3212
+
3213
+ return bufferAttribute;
3214
+
3215
+ } );
3216
+
3217
+ }
3218
+
3219
+ /**
3220
+ * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#textures
3221
+ *
3222
+ * @private
3223
+ * @param {number} textureIndex
3224
+ * @return {Promise<THREE.Texture|null>}
3225
+ */
3226
+ loadTexture( textureIndex ) {
3227
+
3228
+ const json = this.json;
3229
+ const options = this.options;
3230
+ const textureDef = json.textures[ textureIndex ];
3231
+ const sourceIndex = textureDef.source;
3232
+ const sourceDef = json.images[ sourceIndex ];
3233
+
3234
+ let loader = this.textureLoader;
3235
+
3236
+ if ( sourceDef.uri ) {
3237
+
3238
+ const handler = options.manager.getHandler( sourceDef.uri );
3239
+ if ( handler !== null ) loader = handler;
3240
+
3241
+ }
3242
+
3243
+ return this.loadTextureImage( textureIndex, sourceIndex, loader );
3244
+
3245
+ }
3246
+
3247
+ loadTextureImage( textureIndex, sourceIndex, loader ) {
3248
+
3249
+ const parser = this;
3250
+ const json = this.json;
3251
+
3252
+ const textureDef = json.textures[ textureIndex ];
3253
+ const sourceDef = json.images[ sourceIndex ];
3254
+
3255
+ const cacheKey = ( sourceDef.uri || sourceDef.bufferView ) + ':' + textureDef.sampler;
3256
+
3257
+ if ( this.textureCache[ cacheKey ] ) {
3258
+
3259
+ // See https://github.com/mrdoob/three.js/issues/21559.
3260
+ return this.textureCache[ cacheKey ];
3261
+
3262
+ }
3263
+
3264
+ const promise = this.loadImageSource( sourceIndex, loader ).then( function ( texture ) {
3265
+
3266
+ texture.flipY = false;
3267
+
3268
+ texture.name = textureDef.name || sourceDef.name || '';
3269
+
3270
+ if ( texture.name === '' && typeof sourceDef.uri === 'string' && sourceDef.uri.startsWith( 'data:image/' ) === false ) {
3271
+
3272
+ texture.name = sourceDef.uri;
3273
+
3274
+ }
3275
+
3276
+ const samplers = json.samplers || {};
3277
+ const sampler = samplers[ textureDef.sampler ] || {};
3278
+
3279
+ texture.magFilter = WEBGL_FILTERS[ sampler.magFilter ] || THREE.LinearFilter;
3280
+ texture.minFilter = WEBGL_FILTERS[ sampler.minFilter ] || THREE.LinearMipmapLinearFilter;
3281
+ texture.wrapS = WEBGL_WRAPPINGS[ sampler.wrapS ] || THREE.RepeatWrapping;
3282
+ texture.wrapT = WEBGL_WRAPPINGS[ sampler.wrapT ] || THREE.RepeatWrapping;
3283
+ texture.generateMipmaps = ! texture.isCompressedTexture && texture.minFilter !== THREE.NearestFilter && texture.minFilter !== THREE.LinearFilter;
3284
+
3285
+ parser.associations.set( texture, { textures: textureIndex } );
3286
+
3287
+ return texture;
3288
+
3289
+ } ).catch( function () {
3290
+
3291
+ return null;
3292
+
3293
+ } );
3294
+
3295
+ this.textureCache[ cacheKey ] = promise;
3296
+
3297
+ return promise;
3298
+
3299
+ }
3300
+
3301
+ loadImageSource( sourceIndex, loader ) {
3302
+
3303
+ const parser = this;
3304
+ const json = this.json;
3305
+ const options = this.options;
3306
+
3307
+ if ( this.sourceCache[ sourceIndex ] !== undefined ) {
3308
+
3309
+ return this.sourceCache[ sourceIndex ].then( ( texture ) => texture.clone() );
3310
+
3311
+ }
3312
+
3313
+ const sourceDef = json.images[ sourceIndex ];
3314
+
3315
+ const URL = self.URL || self.webkitURL;
3316
+
3317
+ let sourceURI = sourceDef.uri || '';
3318
+ let isObjectURL = false;
3319
+
3320
+ if ( sourceDef.bufferView !== undefined ) {
3321
+
3322
+ // Load binary image data from bufferView, if provided.
3323
+
3324
+ sourceURI = parser.getDependency( 'bufferView', sourceDef.bufferView ).then( function ( bufferView ) {
3325
+
3326
+ isObjectURL = true;
3327
+ const blob = new Blob( [ bufferView ], { type: sourceDef.mimeType } );
3328
+ sourceURI = URL.createObjectURL( blob );
3329
+ return sourceURI;
3330
+
3331
+ } );
3332
+
3333
+ } else if ( sourceDef.uri === undefined ) {
3334
+
3335
+ throw new Error( 'THREE.GLTFLoader: Image ' + sourceIndex + ' is missing URI and bufferView' );
3336
+
3337
+ }
3338
+
3339
+ const promise = Promise.resolve( sourceURI ).then( function ( sourceURI ) {
3340
+
3341
+ return new Promise( function ( resolve, reject ) {
3342
+
3343
+ let onLoad = resolve;
3344
+
3345
+ if ( loader.isImageBitmapLoader === true ) {
3346
+
3347
+ onLoad = function ( imageBitmap ) {
3348
+
3349
+ const texture = new THREE.Texture( imageBitmap );
3350
+ texture.needsUpdate = true;
3351
+
3352
+ resolve( texture );
3353
+
3354
+ };
3355
+
3356
+ }
3357
+
3358
+ loader.load( THREE.LoaderUtils.resolveURL( sourceURI, options.path ), onLoad, undefined, reject );
3359
+
3360
+ } );
3361
+
3362
+ } ).then( function ( texture ) {
3363
+
3364
+ // Clean up resources and configure Texture.
3365
+
3366
+ if ( isObjectURL === true ) {
3367
+
3368
+ URL.revokeObjectURL( sourceURI );
3369
+
3370
+ }
3371
+
3372
+ assignExtrasToUserData( texture, sourceDef );
3373
+
3374
+ texture.userData.mimeType = sourceDef.mimeType || getImageURIMimeType( sourceDef.uri );
3375
+
3376
+ return texture;
3377
+
3378
+ } ).catch( function ( error ) {
3379
+
3380
+ console.error( 'THREE.GLTFLoader: Couldn\'t load texture', sourceURI );
3381
+ throw error;
3382
+
3383
+ } );
3384
+
3385
+ this.sourceCache[ sourceIndex ] = promise;
3386
+ return promise;
3387
+
3388
+ }
3389
+
3390
+ /**
3391
+ * Asynchronously assigns a texture to the given material parameters.
3392
+ *
3393
+ * @private
3394
+ * @param {Object} materialParams
3395
+ * @param {string} mapName
3396
+ * @param {Object} mapDef
3397
+ * @param {string} [colorSpace]
3398
+ * @return {Promise<Texture>}
3399
+ */
3400
+ assignTexture( materialParams, mapName, mapDef, colorSpace ) {
3401
+
3402
+ const parser = this;
3403
+
3404
+ return this.getDependency( 'texture', mapDef.index ).then( function ( texture ) {
3405
+
3406
+ if ( ! texture ) return null;
3407
+
3408
+ if ( mapDef.texCoord !== undefined && mapDef.texCoord > 0 ) {
3409
+
3410
+ texture = texture.clone();
3411
+ texture.channel = mapDef.texCoord;
3412
+
3413
+ }
3414
+
3415
+ if ( parser.extensions[ EXTENSIONS.KHR_TEXTURE_TRANSFORM ] ) {
3416
+
3417
+ const transform = mapDef.extensions !== undefined ? mapDef.extensions[ EXTENSIONS.KHR_TEXTURE_TRANSFORM ] : undefined;
3418
+
3419
+ if ( transform ) {
3420
+
3421
+ const gltfReference = parser.associations.get( texture );
3422
+ texture = parser.extensions[ EXTENSIONS.KHR_TEXTURE_TRANSFORM ].extendTexture( texture, transform );
3423
+ parser.associations.set( texture, gltfReference );
3424
+
3425
+ }
3426
+
3427
+ }
3428
+
3429
+ if ( colorSpace !== undefined ) {
3430
+
3431
+ texture.colorSpace = colorSpace;
3432
+
3433
+ }
3434
+
3435
+ materialParams[ mapName ] = texture;
3436
+
3437
+ return texture;
3438
+
3439
+ } );
3440
+
3441
+ }
3442
+
3443
+ /**
3444
+ * Assigns final material to a Mesh, Line, or Points instance. The instance
3445
+ * already has a material (generated from the glTF material options alone)
3446
+ * but reuse of the same glTF material may require multiple threejs materials
3447
+ * to accommodate different primitive types, defines, etc. New materials will
3448
+ * be created if necessary, and reused from a cache.
3449
+ *
3450
+ * @private
3451
+ * @param {Object3D} mesh Mesh, Line, or Points instance.
3452
+ */
3453
+ assignFinalMaterial( mesh ) {
3454
+
3455
+ const geometry = mesh.geometry;
3456
+ let material = mesh.material;
3457
+
3458
+ const useDerivativeTangents = geometry.attributes.tangent === undefined;
3459
+ const useVertexColors = geometry.attributes.color !== undefined;
3460
+ const useFlatShading = geometry.attributes.normal === undefined;
3461
+
3462
+ if ( mesh.isPoints ) {
3463
+
3464
+ const cacheKey = 'PointsMaterial:' + material.uuid;
3465
+
3466
+ let pointsMaterial = this.cache.get( cacheKey );
3467
+
3468
+ if ( ! pointsMaterial ) {
3469
+
3470
+ pointsMaterial = new THREE.PointsMaterial();
3471
+ THREE.Material.prototype.copy.call( pointsMaterial, material );
3472
+ pointsMaterial.color.copy( material.color );
3473
+ pointsMaterial.map = material.map;
3474
+ pointsMaterial.sizeAttenuation = false; // glTF spec says points should be 1px
3475
+
3476
+ this.cache.add( cacheKey, pointsMaterial );
3477
+
3478
+ }
3479
+
3480
+ material = pointsMaterial;
3481
+
3482
+ } else if ( mesh.isLine ) {
3483
+
3484
+ const cacheKey = 'LineBasicMaterial:' + material.uuid;
3485
+
3486
+ let lineMaterial = this.cache.get( cacheKey );
3487
+
3488
+ if ( ! lineMaterial ) {
3489
+
3490
+ lineMaterial = new THREE.LineBasicMaterial();
3491
+ THREE.Material.prototype.copy.call( lineMaterial, material );
3492
+ lineMaterial.color.copy( material.color );
3493
+ lineMaterial.map = material.map;
3494
+
3495
+ this.cache.add( cacheKey, lineMaterial );
3496
+
3497
+ }
3498
+
3499
+ material = lineMaterial;
3500
+
3501
+ }
3502
+
3503
+ // Clone the material if it will be modified
3504
+ if ( useDerivativeTangents || useVertexColors || useFlatShading ) {
3505
+
3506
+ let cacheKey = 'ClonedMaterial:' + material.uuid + ':';
3507
+
3508
+ if ( useDerivativeTangents ) cacheKey += 'derivative-tangents:';
3509
+ if ( useVertexColors ) cacheKey += 'vertex-colors:';
3510
+ if ( useFlatShading ) cacheKey += 'flat-shading:';
3511
+
3512
+ let cachedMaterial = this.cache.get( cacheKey );
3513
+
3514
+ if ( ! cachedMaterial ) {
3515
+
3516
+ cachedMaterial = material.clone();
3517
+
3518
+ if ( useVertexColors ) cachedMaterial.vertexColors = true;
3519
+ if ( useFlatShading ) cachedMaterial.flatShading = true;
3520
+
3521
+ if ( useDerivativeTangents ) {
3522
+
3523
+ // https://github.com/mrdoob/three.js/issues/11438#issuecomment-507003995
3524
+ if ( cachedMaterial.normalScale ) cachedMaterial.normalScale.y *= - 1;
3525
+ if ( cachedMaterial.clearcoatNormalScale ) cachedMaterial.clearcoatNormalScale.y *= - 1;
3526
+
3527
+ }
3528
+
3529
+ this.cache.add( cacheKey, cachedMaterial );
3530
+
3531
+ this.associations.set( cachedMaterial, this.associations.get( material ) );
3532
+
3533
+ }
3534
+
3535
+ material = cachedMaterial;
3536
+
3537
+ }
3538
+
3539
+ mesh.material = material;
3540
+
3541
+ }
3542
+
3543
+ getMaterialType( /* materialIndex */ ) {
3544
+
3545
+ return THREE.MeshStandardMaterial;
3546
+
3547
+ }
3548
+
3549
+ /**
3550
+ * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#materials
3551
+ *
3552
+ * @private
3553
+ * @param {number} materialIndex
3554
+ * @return {Promise<Material>}
3555
+ */
3556
+ loadMaterial( materialIndex ) {
3557
+
3558
+ const parser = this;
3559
+ const json = this.json;
3560
+ const extensions = this.extensions;
3561
+ const materialDef = json.materials[ materialIndex ];
3562
+
3563
+ let materialType;
3564
+ const materialParams = {};
3565
+ const materialExtensions = materialDef.extensions || {};
3566
+
3567
+ const pending = [];
3568
+
3569
+ if ( materialExtensions[ EXTENSIONS.KHR_MATERIALS_UNLIT ] ) {
3570
+
3571
+ const kmuExtension = extensions[ EXTENSIONS.KHR_MATERIALS_UNLIT ];
3572
+ materialType = kmuExtension.getMaterialType();
3573
+ pending.push( kmuExtension.extendParams( materialParams, materialDef, parser ) );
3574
+
3575
+ } else {
3576
+
3577
+ // Specification:
3578
+ // https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#metallic-roughness-material
3579
+
3580
+ const metallicRoughness = materialDef.pbrMetallicRoughness || {};
3581
+
3582
+ materialParams.color = new THREE.Color( 1.0, 1.0, 1.0 );
3583
+ materialParams.opacity = 1.0;
3584
+
3585
+ if ( Array.isArray( metallicRoughness.baseColorFactor ) ) {
3586
+
3587
+ const array = metallicRoughness.baseColorFactor;
3588
+
3589
+ materialParams.color.setRGB( array[ 0 ], array[ 1 ], array[ 2 ], THREE.LinearSRGBColorSpace );
3590
+ materialParams.opacity = array[ 3 ];
3591
+
3592
+ }
3593
+
3594
+ if ( metallicRoughness.baseColorTexture !== undefined ) {
3595
+
3596
+ pending.push( parser.assignTexture( materialParams, 'map', metallicRoughness.baseColorTexture, THREE.SRGBColorSpace ) );
3597
+
3598
+ }
3599
+
3600
+ materialParams.metalness = metallicRoughness.metallicFactor !== undefined ? metallicRoughness.metallicFactor : 1.0;
3601
+ materialParams.roughness = metallicRoughness.roughnessFactor !== undefined ? metallicRoughness.roughnessFactor : 1.0;
3602
+
3603
+ if ( metallicRoughness.metallicRoughnessTexture !== undefined ) {
3604
+
3605
+ pending.push( parser.assignTexture( materialParams, 'metalnessMap', metallicRoughness.metallicRoughnessTexture ) );
3606
+ pending.push( parser.assignTexture( materialParams, 'roughnessMap', metallicRoughness.metallicRoughnessTexture ) );
3607
+
3608
+ }
3609
+
3610
+ materialType = this._invokeOne( function ( ext ) {
3611
+
3612
+ return ext.getMaterialType && ext.getMaterialType( materialIndex );
3613
+
3614
+ } );
3615
+
3616
+ pending.push( Promise.all( this._invokeAll( function ( ext ) {
3617
+
3618
+ return ext.extendMaterialParams && ext.extendMaterialParams( materialIndex, materialParams );
3619
+
3620
+ } ) ) );
3621
+
3622
+ }
3623
+
3624
+ if ( materialDef.doubleSided === true ) {
3625
+
3626
+ materialParams.side = THREE.DoubleSide;
3627
+
3628
+ }
3629
+
3630
+ const alphaMode = materialDef.alphaMode || ALPHA_MODES.OPAQUE;
3631
+
3632
+ if ( alphaMode === ALPHA_MODES.BLEND ) {
3633
+
3634
+ materialParams.transparent = true;
3635
+
3636
+ // See: https://github.com/mrdoob/three.js/issues/17706
3637
+ materialParams.depthWrite = false;
3638
+
3639
+ } else {
3640
+
3641
+ materialParams.transparent = false;
3642
+
3643
+ if ( alphaMode === ALPHA_MODES.MASK ) {
3644
+
3645
+ materialParams.alphaTest = materialDef.alphaCutoff !== undefined ? materialDef.alphaCutoff : 0.5;
3646
+
3647
+ }
3648
+
3649
+ }
3650
+
3651
+ if ( materialDef.normalTexture !== undefined && materialType !== THREE.MeshBasicMaterial ) {
3652
+
3653
+ pending.push( parser.assignTexture( materialParams, 'normalMap', materialDef.normalTexture ) );
3654
+
3655
+ materialParams.normalScale = new THREE.Vector2( 1, 1 );
3656
+
3657
+ if ( materialDef.normalTexture.scale !== undefined ) {
3658
+
3659
+ const scale = materialDef.normalTexture.scale;
3660
+
3661
+ materialParams.normalScale.set( scale, scale );
3662
+
3663
+ }
3664
+
3665
+ }
3666
+
3667
+ if ( materialDef.occlusionTexture !== undefined && materialType !== THREE.MeshBasicMaterial ) {
3668
+
3669
+ pending.push( parser.assignTexture( materialParams, 'aoMap', materialDef.occlusionTexture ) );
3670
+
3671
+ if ( materialDef.occlusionTexture.strength !== undefined ) {
3672
+
3673
+ materialParams.aoMapIntensity = materialDef.occlusionTexture.strength;
3674
+
3675
+ }
3676
+
3677
+ }
3678
+
3679
+ if ( materialDef.emissiveFactor !== undefined && materialType !== THREE.MeshBasicMaterial ) {
3680
+
3681
+ const emissiveFactor = materialDef.emissiveFactor;
3682
+ materialParams.emissive = new THREE.Color().setRGB( emissiveFactor[ 0 ], emissiveFactor[ 1 ], emissiveFactor[ 2 ], THREE.LinearSRGBColorSpace );
3683
+
3684
+ }
3685
+
3686
+ if ( materialDef.emissiveTexture !== undefined && materialType !== THREE.MeshBasicMaterial ) {
3687
+
3688
+ pending.push( parser.assignTexture( materialParams, 'emissiveMap', materialDef.emissiveTexture, THREE.SRGBColorSpace ) );
3689
+
3690
+ }
3691
+
3692
+ return Promise.all( pending ).then( function () {
3693
+
3694
+ const material = new materialType( materialParams );
3695
+
3696
+ if ( materialDef.name ) material.name = materialDef.name;
3697
+
3698
+ assignExtrasToUserData( material, materialDef );
3699
+
3700
+ parser.associations.set( material, { materials: materialIndex } );
3701
+
3702
+ if ( materialDef.extensions ) addUnknownExtensionsToUserData( extensions, material, materialDef );
3703
+
3704
+ return material;
3705
+
3706
+ } );
3707
+
3708
+ }
3709
+
3710
+ /**
3711
+ * When Object3D instances are targeted by animation, they need unique names.
3712
+ *
3713
+ * @private
3714
+ * @param {string} originalName
3715
+ * @return {string}
3716
+ */
3717
+ createUniqueName( originalName ) {
3718
+
3719
+ const sanitizedName = THREE.PropertyBinding.sanitizeNodeName( originalName || '' );
3720
+
3721
+ if ( sanitizedName in this.nodeNamesUsed ) {
3722
+
3723
+ return sanitizedName + '_' + ( ++ this.nodeNamesUsed[ sanitizedName ] );
3724
+
3725
+ } else {
3726
+
3727
+ this.nodeNamesUsed[ sanitizedName ] = 0;
3728
+
3729
+ return sanitizedName;
3730
+
3731
+ }
3732
+
3733
+ }
3734
+
3735
+ /**
3736
+ * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#geometry
3737
+ *
3738
+ * Creates BufferGeometries from primitives.
3739
+ *
3740
+ * @private
3741
+ * @param {Array<GLTF.Primitive>} primitives
3742
+ * @return {Promise<Array<BufferGeometry>>}
3743
+ */
3744
+ loadGeometries( primitives ) {
3745
+
3746
+ const parser = this;
3747
+ const extensions = this.extensions;
3748
+ const cache = this.primitiveCache;
3749
+
3750
+ function createDracoPrimitive( primitive ) {
3751
+
3752
+ return extensions[ EXTENSIONS.KHR_DRACO_MESH_COMPRESSION ]
3753
+ .decodePrimitive( primitive, parser )
3754
+ .then( function ( geometry ) {
3755
+
3756
+ return addPrimitiveAttributes( geometry, primitive, parser );
3757
+
3758
+ } );
3759
+
3760
+ }
3761
+
3762
+ const pending = [];
3763
+
3764
+ for ( let i = 0, il = primitives.length; i < il; i ++ ) {
3765
+
3766
+ const primitive = primitives[ i ];
3767
+ const cacheKey = createPrimitiveKey( primitive );
3768
+
3769
+ // See if we've already created this geometry
3770
+ const cached = cache[ cacheKey ];
3771
+
3772
+ if ( cached ) {
3773
+
3774
+ // Use the cached geometry if it exists
3775
+ pending.push( cached.promise );
3776
+
3777
+ } else {
3778
+
3779
+ let geometryPromise;
3780
+
3781
+ if ( primitive.extensions && primitive.extensions[ EXTENSIONS.KHR_DRACO_MESH_COMPRESSION ] ) {
3782
+
3783
+ // Use DRACO geometry if available
3784
+ geometryPromise = createDracoPrimitive( primitive );
3785
+
3786
+ } else {
3787
+
3788
+ // Otherwise create a new geometry
3789
+ geometryPromise = addPrimitiveAttributes( new THREE.BufferGeometry(), primitive, parser );
3790
+
3791
+ }
3792
+
3793
+ // Cache this geometry
3794
+ cache[ cacheKey ] = { primitive: primitive, promise: geometryPromise };
3795
+
3796
+ pending.push( geometryPromise );
3797
+
3798
+ }
3799
+
3800
+ }
3801
+
3802
+ return Promise.all( pending );
3803
+
3804
+ }
3805
+
3806
+ /**
3807
+ * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#meshes
3808
+ *
3809
+ * @private
3810
+ * @param {number} meshIndex
3811
+ * @return {Promise<Group|Mesh|SkinnedMesh|Line|Points>}
3812
+ */
3813
+ loadMesh( meshIndex ) {
3814
+
3815
+ const parser = this;
3816
+ const json = this.json;
3817
+ const extensions = this.extensions;
3818
+
3819
+ const meshDef = json.meshes[ meshIndex ];
3820
+ const primitives = meshDef.primitives;
3821
+
3822
+ const pending = [];
3823
+
3824
+ for ( let i = 0, il = primitives.length; i < il; i ++ ) {
3825
+
3826
+ const material = primitives[ i ].material === undefined
3827
+ ? createDefaultMaterial( this.cache )
3828
+ : this.getDependency( 'material', primitives[ i ].material );
3829
+
3830
+ pending.push( material );
3831
+
3832
+ }
3833
+
3834
+ pending.push( parser.loadGeometries( primitives ) );
3835
+
3836
+ return Promise.all( pending ).then( function ( results ) {
3837
+
3838
+ const materials = results.slice( 0, results.length - 1 );
3839
+ const geometries = results[ results.length - 1 ];
3840
+
3841
+ const meshes = [];
3842
+
3843
+ for ( let i = 0, il = geometries.length; i < il; i ++ ) {
3844
+
3845
+ const geometry = geometries[ i ];
3846
+ const primitive = primitives[ i ];
3847
+
3848
+ // 1. create Mesh
3849
+
3850
+ let mesh;
3851
+
3852
+ const material = materials[ i ];
3853
+
3854
+ if ( primitive.mode === WEBGL_CONSTANTS.TRIANGLES ||
3855
+ primitive.mode === WEBGL_CONSTANTS.TRIANGLE_STRIP ||
3856
+ primitive.mode === WEBGL_CONSTANTS.TRIANGLE_FAN ||
3857
+ primitive.mode === undefined ) {
3858
+
3859
+ // .isSkinnedMesh isn't in glTF spec. See ._markDefs()
3860
+ mesh = meshDef.isSkinnedMesh === true
3861
+ ? new THREE.SkinnedMesh( geometry, material )
3862
+ : new THREE.Mesh( geometry, material );
3863
+
3864
+ if ( mesh.isSkinnedMesh === true ) {
3865
+
3866
+ // normalize skin weights to fix malformed assets (see #15319)
3867
+ mesh.normalizeSkinWeights();
3868
+
3869
+ }
3870
+
3871
+ if ( primitive.mode === WEBGL_CONSTANTS.TRIANGLE_STRIP ) {
3872
+
3873
+ mesh.geometry = BufferGeometryUtils.toTrianglesDrawMode( mesh.geometry, THREE.TriangleStripDrawMode );
3874
+
3875
+ } else if ( primitive.mode === WEBGL_CONSTANTS.TRIANGLE_FAN ) {
3876
+
3877
+ mesh.geometry = BufferGeometryUtils.toTrianglesDrawMode( mesh.geometry, THREE.TriangleFanDrawMode );
3878
+
3879
+ }
3880
+
3881
+ } else if ( primitive.mode === WEBGL_CONSTANTS.LINES ) {
3882
+
3883
+ mesh = new THREE.LineSegments( geometry, material );
3884
+
3885
+ } else if ( primitive.mode === WEBGL_CONSTANTS.LINE_STRIP ) {
3886
+
3887
+ mesh = new THREE.Line( geometry, material );
3888
+
3889
+ } else if ( primitive.mode === WEBGL_CONSTANTS.LINE_LOOP ) {
3890
+
3891
+ mesh = new THREE.LineLoop( geometry, material );
3892
+
3893
+ } else if ( primitive.mode === WEBGL_CONSTANTS.POINTS ) {
3894
+
3895
+ mesh = new THREE.Points( geometry, material );
3896
+
3897
+ } else {
3898
+
3899
+ throw new Error( 'THREE.GLTFLoader: Primitive mode unsupported: ' + primitive.mode );
3900
+
3901
+ }
3902
+
3903
+ if ( Object.keys( mesh.geometry.morphAttributes ).length > 0 ) {
3904
+
3905
+ updateMorphTargets( mesh, meshDef );
3906
+
3907
+ }
3908
+
3909
+ mesh.name = parser.createUniqueName( meshDef.name || ( 'mesh_' + meshIndex ) );
3910
+
3911
+ assignExtrasToUserData( mesh, meshDef );
3912
+
3913
+ if ( primitive.extensions ) addUnknownExtensionsToUserData( extensions, mesh, primitive );
3914
+
3915
+ parser.assignFinalMaterial( mesh );
3916
+
3917
+ meshes.push( mesh );
3918
+
3919
+ }
3920
+
3921
+ for ( let i = 0, il = meshes.length; i < il; i ++ ) {
3922
+
3923
+ parser.associations.set( meshes[ i ], {
3924
+ meshes: meshIndex,
3925
+ primitives: i
3926
+ } );
3927
+
3928
+ }
3929
+
3930
+ if ( meshes.length === 1 ) {
3931
+
3932
+ if ( meshDef.extensions ) addUnknownExtensionsToUserData( extensions, meshes[ 0 ], meshDef );
3933
+
3934
+ return meshes[ 0 ];
3935
+
3936
+ }
3937
+
3938
+ const group = new THREE.Group();
3939
+
3940
+ if ( meshDef.extensions ) addUnknownExtensionsToUserData( extensions, group, meshDef );
3941
+
3942
+ parser.associations.set( group, { meshes: meshIndex } );
3943
+
3944
+ for ( let i = 0, il = meshes.length; i < il; i ++ ) {
3945
+
3946
+ group.add( meshes[ i ] );
3947
+
3948
+ }
3949
+
3950
+ return group;
3951
+
3952
+ } );
3953
+
3954
+ }
3955
+
3956
+ /**
3957
+ * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#cameras
3958
+ *
3959
+ * @private
3960
+ * @param {number} cameraIndex
3961
+ * @return {Promise<THREE.Camera>}
3962
+ */
3963
+ loadCamera( cameraIndex ) {
3964
+
3965
+ let camera;
3966
+ const cameraDef = this.json.cameras[ cameraIndex ];
3967
+ const params = cameraDef[ cameraDef.type ];
3968
+
3969
+ if ( ! params ) {
3970
+
3971
+ console.warn( 'THREE.GLTFLoader: Missing camera parameters.' );
3972
+ return;
3973
+
3974
+ }
3975
+
3976
+ if ( cameraDef.type === 'perspective' ) {
3977
+
3978
+ camera = new THREE.PerspectiveCamera( THREE.MathUtils.radToDeg( params.yfov ), params.aspectRatio || 1, params.znear || 1, params.zfar || 2e6 );
3979
+
3980
+ } else if ( cameraDef.type === 'orthographic' ) {
3981
+
3982
+ camera = new THREE.OrthographicCamera( - params.xmag, params.xmag, params.ymag, - params.ymag, params.znear, params.zfar );
3983
+
3984
+ }
3985
+
3986
+ if ( cameraDef.name ) camera.name = this.createUniqueName( cameraDef.name );
3987
+
3988
+ assignExtrasToUserData( camera, cameraDef );
3989
+
3990
+ return Promise.resolve( camera );
3991
+
3992
+ }
3993
+
3994
+ /**
3995
+ * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins
3996
+ *
3997
+ * @private
3998
+ * @param {number} skinIndex
3999
+ * @return {Promise<Skeleton>}
4000
+ */
4001
+ loadSkin( skinIndex ) {
4002
+
4003
+ const skinDef = this.json.skins[ skinIndex ];
4004
+
4005
+ const pending = [];
4006
+
4007
+ for ( let i = 0, il = skinDef.joints.length; i < il; i ++ ) {
4008
+
4009
+ pending.push( this._loadNodeShallow( skinDef.joints[ i ] ) );
4010
+
4011
+ }
4012
+
4013
+ if ( skinDef.inverseBindMatrices !== undefined ) {
4014
+
4015
+ pending.push( this.getDependency( 'accessor', skinDef.inverseBindMatrices ) );
4016
+
4017
+ } else {
4018
+
4019
+ pending.push( null );
4020
+
4021
+ }
4022
+
4023
+ return Promise.all( pending ).then( function ( results ) {
4024
+
4025
+ const inverseBindMatrices = results.pop();
4026
+ const jointNodes = results;
4027
+
4028
+ // Note that bones (joint nodes) may or may not be in the
4029
+ // scene graph at this time.
4030
+
4031
+ const bones = [];
4032
+ const boneInverses = [];
4033
+
4034
+ for ( let i = 0, il = jointNodes.length; i < il; i ++ ) {
4035
+
4036
+ const jointNode = jointNodes[ i ];
4037
+
4038
+ if ( jointNode ) {
4039
+
4040
+ bones.push( jointNode );
4041
+
4042
+ const mat = new THREE.Matrix4();
4043
+
4044
+ if ( inverseBindMatrices !== null ) {
4045
+
4046
+ mat.fromArray( inverseBindMatrices.array, i * 16 );
4047
+
4048
+ }
4049
+
4050
+ boneInverses.push( mat );
4051
+
4052
+ } else {
4053
+
4054
+ console.warn( 'THREE.GLTFLoader: Joint "%s" could not be found.', skinDef.joints[ i ] );
4055
+
4056
+ }
4057
+
4058
+ }
4059
+
4060
+ return new THREE.Skeleton( bones, boneInverses );
4061
+
4062
+ } );
4063
+
4064
+ }
4065
+
4066
+ /**
4067
+ * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#animations
4068
+ *
4069
+ * @private
4070
+ * @param {number} animationIndex
4071
+ * @return {Promise<AnimationClip>}
4072
+ */
4073
+ loadAnimation( animationIndex ) {
4074
+
4075
+ const json = this.json;
4076
+ const parser = this;
4077
+
4078
+ const animationDef = json.animations[ animationIndex ];
4079
+ const animationName = animationDef.name ? animationDef.name : 'animation_' + animationIndex;
4080
+
4081
+ const pendingNodes = [];
4082
+ const pendingInputAccessors = [];
4083
+ const pendingOutputAccessors = [];
4084
+ const pendingSamplers = [];
4085
+ const pendingTargets = [];
4086
+
4087
+ for ( let i = 0, il = animationDef.channels.length; i < il; i ++ ) {
4088
+
4089
+ const channel = animationDef.channels[ i ];
4090
+ const sampler = animationDef.samplers[ channel.sampler ];
4091
+ const target = channel.target;
4092
+ const name = target.node;
4093
+ const input = animationDef.parameters !== undefined ? animationDef.parameters[ sampler.input ] : sampler.input;
4094
+ const output = animationDef.parameters !== undefined ? animationDef.parameters[ sampler.output ] : sampler.output;
4095
+
4096
+ if ( target.node === undefined ) continue;
4097
+
4098
+ pendingNodes.push( this.getDependency( 'node', name ) );
4099
+ pendingInputAccessors.push( this.getDependency( 'accessor', input ) );
4100
+ pendingOutputAccessors.push( this.getDependency( 'accessor', output ) );
4101
+ pendingSamplers.push( sampler );
4102
+ pendingTargets.push( target );
4103
+
4104
+ }
4105
+
4106
+ return Promise.all( [
4107
+
4108
+ Promise.all( pendingNodes ),
4109
+ Promise.all( pendingInputAccessors ),
4110
+ Promise.all( pendingOutputAccessors ),
4111
+ Promise.all( pendingSamplers ),
4112
+ Promise.all( pendingTargets )
4113
+
4114
+ ] ).then( function ( dependencies ) {
4115
+
4116
+ const nodes = dependencies[ 0 ];
4117
+ const inputAccessors = dependencies[ 1 ];
4118
+ const outputAccessors = dependencies[ 2 ];
4119
+ const samplers = dependencies[ 3 ];
4120
+ const targets = dependencies[ 4 ];
4121
+
4122
+ const tracks = [];
4123
+
4124
+ for ( let i = 0, il = nodes.length; i < il; i ++ ) {
4125
+
4126
+ const node = nodes[ i ];
4127
+ const inputAccessor = inputAccessors[ i ];
4128
+ const outputAccessor = outputAccessors[ i ];
4129
+ const sampler = samplers[ i ];
4130
+ const target = targets[ i ];
4131
+
4132
+ if ( node === undefined ) continue;
4133
+
4134
+ if ( node.updateMatrix ) {
4135
+
4136
+ node.updateMatrix();
4137
+
4138
+ }
4139
+
4140
+ const createdTracks = parser._createAnimationTracks( node, inputAccessor, outputAccessor, sampler, target );
4141
+
4142
+ if ( createdTracks ) {
4143
+
4144
+ for ( let k = 0; k < createdTracks.length; k ++ ) {
4145
+
4146
+ tracks.push( createdTracks[ k ] );
4147
+
4148
+ }
4149
+
4150
+ }
4151
+
4152
+ }
4153
+
4154
+ return new THREE.AnimationClip( animationName, undefined, tracks );
4155
+
4156
+ } );
4157
+
4158
+ }
4159
+
4160
+ createNodeMesh( nodeIndex ) {
4161
+
4162
+ const json = this.json;
4163
+ const parser = this;
4164
+ const nodeDef = json.nodes[ nodeIndex ];
4165
+
4166
+ if ( nodeDef.mesh === undefined ) return null;
4167
+
4168
+ return parser.getDependency( 'mesh', nodeDef.mesh ).then( function ( mesh ) {
4169
+
4170
+ const node = parser._getNodeRef( parser.meshCache, nodeDef.mesh, mesh );
4171
+
4172
+ // if weights are provided on the node, override weights on the mesh.
4173
+ if ( nodeDef.weights !== undefined ) {
4174
+
4175
+ node.traverse( function ( o ) {
4176
+
4177
+ if ( ! o.isMesh ) return;
4178
+
4179
+ for ( let i = 0, il = nodeDef.weights.length; i < il; i ++ ) {
4180
+
4181
+ o.morphTargetInfluences[ i ] = nodeDef.weights[ i ];
4182
+
4183
+ }
4184
+
4185
+ } );
4186
+
4187
+ }
4188
+
4189
+ return node;
4190
+
4191
+ } );
4192
+
4193
+ }
4194
+
4195
+ /**
4196
+ * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#nodes-and-hierarchy
4197
+ *
4198
+ * @private
4199
+ * @param {number} nodeIndex
4200
+ * @return {Promise<Object3D>}
4201
+ */
4202
+ loadNode( nodeIndex ) {
4203
+
4204
+ const json = this.json;
4205
+ const parser = this;
4206
+
4207
+ const nodeDef = json.nodes[ nodeIndex ];
4208
+
4209
+ const nodePending = parser._loadNodeShallow( nodeIndex );
4210
+
4211
+ const childPending = [];
4212
+ const childrenDef = nodeDef.children || [];
4213
+
4214
+ for ( let i = 0, il = childrenDef.length; i < il; i ++ ) {
4215
+
4216
+ childPending.push( parser.getDependency( 'node', childrenDef[ i ] ) );
4217
+
4218
+ }
4219
+
4220
+ const skeletonPending = nodeDef.skin === undefined
4221
+ ? Promise.resolve( null )
4222
+ : parser.getDependency( 'skin', nodeDef.skin );
4223
+
4224
+ return Promise.all( [
4225
+ nodePending,
4226
+ Promise.all( childPending ),
4227
+ skeletonPending
4228
+ ] ).then( function ( results ) {
4229
+
4230
+ const node = results[ 0 ];
4231
+ const children = results[ 1 ];
4232
+ const skeleton = results[ 2 ];
4233
+
4234
+ if ( skeleton !== null ) {
4235
+
4236
+ // This full traverse should be fine because
4237
+ // child glTF nodes have not been added to this node yet.
4238
+ node.traverse( function ( mesh ) {
4239
+
4240
+ if ( ! mesh.isSkinnedMesh ) return;
4241
+
4242
+ mesh.bind( skeleton, _identityMatrix );
4243
+
4244
+ } );
4245
+
4246
+ }
4247
+
4248
+ for ( let i = 0, il = children.length; i < il; i ++ ) {
4249
+
4250
+ node.add( children[ i ] );
4251
+
4252
+ }
4253
+
4254
+ return node;
4255
+
4256
+ } );
4257
+
4258
+ }
4259
+
4260
+ // ._loadNodeShallow() parses a single node.
4261
+ // skin and child nodes are created and added in .loadNode() (no '_' prefix).
4262
+ _loadNodeShallow( nodeIndex ) {
4263
+
4264
+ const json = this.json;
4265
+ const extensions = this.extensions;
4266
+ const parser = this;
4267
+
4268
+ // This method is called from .loadNode() and .loadSkin().
4269
+ // Cache a node to avoid duplication.
4270
+
4271
+ if ( this.nodeCache[ nodeIndex ] !== undefined ) {
4272
+
4273
+ return this.nodeCache[ nodeIndex ];
4274
+
4275
+ }
4276
+
4277
+ const nodeDef = json.nodes[ nodeIndex ];
4278
+
4279
+ // reserve node's name before its dependencies, so the root has the intended name.
4280
+ const nodeName = nodeDef.name ? parser.createUniqueName( nodeDef.name ) : '';
4281
+
4282
+ const pending = [];
4283
+
4284
+ const meshPromise = parser._invokeOne( function ( ext ) {
4285
+
4286
+ return ext.createNodeMesh && ext.createNodeMesh( nodeIndex );
4287
+
4288
+ } );
4289
+
4290
+ if ( meshPromise ) {
4291
+
4292
+ pending.push( meshPromise );
4293
+
4294
+ }
4295
+
4296
+ if ( nodeDef.camera !== undefined ) {
4297
+
4298
+ pending.push( parser.getDependency( 'camera', nodeDef.camera ).then( function ( camera ) {
4299
+
4300
+ return parser._getNodeRef( parser.cameraCache, nodeDef.camera, camera );
4301
+
4302
+ } ) );
4303
+
4304
+ }
4305
+
4306
+ parser._invokeAll( function ( ext ) {
4307
+
4308
+ return ext.createNodeAttachment && ext.createNodeAttachment( nodeIndex );
4309
+
4310
+ } ).forEach( function ( promise ) {
4311
+
4312
+ pending.push( promise );
4313
+
4314
+ } );
4315
+
4316
+ this.nodeCache[ nodeIndex ] = Promise.all( pending ).then( function ( objects ) {
4317
+
4318
+ let node;
4319
+
4320
+ // .isBone isn't in glTF spec. See ._markDefs
4321
+ if ( nodeDef.isBone === true ) {
4322
+
4323
+ node = new THREE.Bone();
4324
+
4325
+ } else if ( objects.length > 1 ) {
4326
+
4327
+ node = new THREE.Group();
4328
+
4329
+ } else if ( objects.length === 1 ) {
4330
+
4331
+ node = objects[ 0 ];
4332
+
4333
+ } else {
4334
+
4335
+ node = new THREE.Object3D();
4336
+
4337
+ }
4338
+
4339
+ if ( node !== objects[ 0 ] ) {
4340
+
4341
+ for ( let i = 0, il = objects.length; i < il; i ++ ) {
4342
+
4343
+ node.add( objects[ i ] );
4344
+
4345
+ }
4346
+
4347
+ }
4348
+
4349
+ if ( nodeDef.name ) {
4350
+
4351
+ node.userData.name = nodeDef.name;
4352
+ node.name = nodeName;
4353
+
4354
+ }
4355
+
4356
+ assignExtrasToUserData( node, nodeDef );
4357
+
4358
+ if ( nodeDef.extensions ) addUnknownExtensionsToUserData( extensions, node, nodeDef );
4359
+
4360
+ if ( nodeDef.matrix !== undefined ) {
4361
+
4362
+ const matrix = new THREE.Matrix4();
4363
+ matrix.fromArray( nodeDef.matrix );
4364
+ node.applyMatrix4( matrix );
4365
+
4366
+ } else {
4367
+
4368
+ if ( nodeDef.translation !== undefined ) {
4369
+
4370
+ node.position.fromArray( nodeDef.translation );
4371
+
4372
+ }
4373
+
4374
+ if ( nodeDef.rotation !== undefined ) {
4375
+
4376
+ node.quaternion.fromArray( nodeDef.rotation );
4377
+
4378
+ }
4379
+
4380
+ if ( nodeDef.scale !== undefined ) {
4381
+
4382
+ node.scale.fromArray( nodeDef.scale );
4383
+
4384
+ }
4385
+
4386
+ }
4387
+
4388
+ if ( ! parser.associations.has( node ) ) {
4389
+
4390
+ parser.associations.set( node, {} );
4391
+
4392
+ } else if ( nodeDef.mesh !== undefined && parser.meshCache.refs[ nodeDef.mesh ] > 1 ) {
4393
+
4394
+ const mapping = parser.associations.get( node );
4395
+ parser.associations.set( node, { ...mapping } );
4396
+
4397
+ }
4398
+
4399
+ parser.associations.get( node ).nodes = nodeIndex;
4400
+
4401
+ return node;
4402
+
4403
+ } );
4404
+
4405
+ return this.nodeCache[ nodeIndex ];
4406
+
4407
+ }
4408
+
4409
+ /**
4410
+ * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#scenes
4411
+ *
4412
+ * @private
4413
+ * @param {number} sceneIndex
4414
+ * @return {Promise<Group>}
4415
+ */
4416
+ loadScene( sceneIndex ) {
4417
+
4418
+ const extensions = this.extensions;
4419
+ const sceneDef = this.json.scenes[ sceneIndex ];
4420
+ const parser = this;
4421
+
4422
+ // Loader returns Group, not Scene.
4423
+ // See: https://github.com/mrdoob/three.js/issues/18342#issuecomment-578981172
4424
+ const scene = new THREE.Group();
4425
+ if ( sceneDef.name ) scene.name = parser.createUniqueName( sceneDef.name );
4426
+
4427
+ assignExtrasToUserData( scene, sceneDef );
4428
+
4429
+ if ( sceneDef.extensions ) addUnknownExtensionsToUserData( extensions, scene, sceneDef );
4430
+
4431
+ const nodeIds = sceneDef.nodes || [];
4432
+
4433
+ const pending = [];
4434
+
4435
+ for ( let i = 0, il = nodeIds.length; i < il; i ++ ) {
4436
+
4437
+ pending.push( parser.getDependency( 'node', nodeIds[ i ] ) );
4438
+
4439
+ }
4440
+
4441
+ return Promise.all( pending ).then( function ( nodes ) {
4442
+
4443
+ for ( let i = 0, il = nodes.length; i < il; i ++ ) {
4444
+
4445
+ scene.add( nodes[ i ] );
4446
+
4447
+ }
4448
+
4449
+ // Removes dangling associations, associations that reference a node that
4450
+ // didn't make it into the scene.
4451
+ const reduceAssociations = ( node ) => {
4452
+
4453
+ const reducedAssociations = new Map();
4454
+
4455
+ for ( const [ key, value ] of parser.associations ) {
4456
+
4457
+ if ( key instanceof THREE.Material || key instanceof THREE.Texture ) {
4458
+
4459
+ reducedAssociations.set( key, value );
4460
+
4461
+ }
4462
+
4463
+ }
4464
+
4465
+ node.traverse( ( node ) => {
4466
+
4467
+ const mappings = parser.associations.get( node );
4468
+
4469
+ if ( mappings != null ) {
4470
+
4471
+ reducedAssociations.set( node, mappings );
4472
+
4473
+ }
4474
+
4475
+ } );
4476
+
4477
+ return reducedAssociations;
4478
+
4479
+ };
4480
+
4481
+ parser.associations = reduceAssociations( scene );
4482
+
4483
+ return scene;
4484
+
4485
+ } );
4486
+
4487
+ }
4488
+
4489
+ _createAnimationTracks( node, inputAccessor, outputAccessor, sampler, target ) {
4490
+
4491
+ const tracks = [];
4492
+
4493
+ const targetName = node.name ? node.name : node.uuid;
4494
+ const targetNames = [];
4495
+
4496
+ if ( PATH_PROPERTIES[ target.path ] === PATH_PROPERTIES.weights ) {
4497
+
4498
+ node.traverse( function ( object ) {
4499
+
4500
+ if ( object.morphTargetInfluences ) {
4501
+
4502
+ targetNames.push( object.name ? object.name : object.uuid );
4503
+
4504
+ }
4505
+
4506
+ } );
4507
+
4508
+ } else {
4509
+
4510
+ targetNames.push( targetName );
4511
+
4512
+ }
4513
+
4514
+ let TypedKeyframeTrack;
4515
+
4516
+ switch ( PATH_PROPERTIES[ target.path ] ) {
4517
+
4518
+ case PATH_PROPERTIES.weights:
4519
+
4520
+ TypedKeyframeTrack = THREE.NumberKeyframeTrack;
4521
+ break;
4522
+
4523
+ case PATH_PROPERTIES.rotation:
4524
+
4525
+ TypedKeyframeTrack = THREE.QuaternionKeyframeTrack;
4526
+ break;
4527
+
4528
+ case PATH_PROPERTIES.translation:
4529
+ case PATH_PROPERTIES.scale:
4530
+
4531
+ TypedKeyframeTrack = THREE.VectorKeyframeTrack;
4532
+ break;
4533
+
4534
+ default:
4535
+
4536
+ switch ( outputAccessor.itemSize ) {
4537
+
4538
+ case 1:
4539
+ TypedKeyframeTrack = THREE.NumberKeyframeTrack;
4540
+ break;
4541
+ case 2:
4542
+ case 3:
4543
+ default:
4544
+ TypedKeyframeTrack = THREE.VectorKeyframeTrack;
4545
+ break;
4546
+
4547
+ }
4548
+
4549
+ break;
4550
+
4551
+ }
4552
+
4553
+ const interpolation = sampler.interpolation !== undefined ? INTERPOLATION[ sampler.interpolation ] : THREE.InterpolateLinear;
4554
+
4555
+
4556
+ const outputArray = this._getArrayFromAccessor( outputAccessor );
4557
+
4558
+ for ( let j = 0, jl = targetNames.length; j < jl; j ++ ) {
4559
+
4560
+ const track = new TypedKeyframeTrack(
4561
+ targetNames[ j ] + '.' + PATH_PROPERTIES[ target.path ],
4562
+ inputAccessor.array,
4563
+ outputArray,
4564
+ interpolation
4565
+ );
4566
+
4567
+ // Override interpolation with custom factory method.
4568
+ if ( sampler.interpolation === 'CUBICSPLINE' ) {
4569
+
4570
+ this._createCubicSplineTrackInterpolant( track );
4571
+
4572
+ }
4573
+
4574
+ tracks.push( track );
4575
+
4576
+ }
4577
+
4578
+ return tracks;
4579
+
4580
+ }
4581
+
4582
+ _getArrayFromAccessor( accessor ) {
4583
+
4584
+ let outputArray = accessor.array;
4585
+
4586
+ if ( accessor.normalized ) {
4587
+
4588
+ const scale = getNormalizedComponentScale( outputArray.constructor );
4589
+ const scaled = new Float32Array( outputArray.length );
4590
+
4591
+ for ( let j = 0, jl = outputArray.length; j < jl; j ++ ) {
4592
+
4593
+ scaled[ j ] = outputArray[ j ] * scale;
4594
+
4595
+ }
4596
+
4597
+ outputArray = scaled;
4598
+
4599
+ }
4600
+
4601
+ return outputArray;
4602
+
4603
+ }
4604
+
4605
+ _createCubicSplineTrackInterpolant( track ) {
4606
+
4607
+ track.createInterpolant = function InterpolantFactoryMethodGLTFCubicSpline( result ) {
4608
+
4609
+ // A CUBICSPLINE keyframe in glTF has three output values for each input value,
4610
+ // representing inTangent, splineVertex, and outTangent. As a result, track.getValueSize()
4611
+ // must be divided by three to get the interpolant's sampleSize argument.
4612
+
4613
+ const interpolantType = ( this instanceof THREE.QuaternionKeyframeTrack ) ? GLTFCubicSplineQuaternionInterpolant : GLTFCubicSplineInterpolant;
4614
+
4615
+ return new interpolantType( this.times, this.values, this.getValueSize() / 3, result );
4616
+
4617
+ };
4618
+
4619
+ // Mark as CUBICSPLINE. `track.getInterpolation()` doesn't support custom interpolants.
4620
+ track.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline = true;
4621
+
4622
+ }
4623
+
4624
+ }
4625
+
4626
+ /**
4627
+ *
4628
+ * @private
4629
+ * @param {BufferGeometry} geometry
4630
+ * @param {GLTF.Primitive} primitiveDef
4631
+ * @param {GLTFParser} parser
4632
+ */
4633
+ function computeBounds( geometry, primitiveDef, parser ) {
4634
+
4635
+ const attributes = primitiveDef.attributes;
4636
+
4637
+ const box = new THREE.Box3();
4638
+
4639
+ if ( attributes.POSITION !== undefined ) {
4640
+
4641
+ const accessor = parser.json.accessors[ attributes.POSITION ];
4642
+
4643
+ const min = accessor.min;
4644
+ const max = accessor.max;
4645
+
4646
+ // glTF requires 'min' and 'max', but VRM (which extends glTF) currently ignores that requirement.
4647
+
4648
+ if ( min !== undefined && max !== undefined ) {
4649
+
4650
+ box.set(
4651
+ new THREE.Vector3( min[ 0 ], min[ 1 ], min[ 2 ] ),
4652
+ new THREE.Vector3( max[ 0 ], max[ 1 ], max[ 2 ] )
4653
+ );
4654
+
4655
+ if ( accessor.normalized ) {
4656
+
4657
+ const boxScale = getNormalizedComponentScale( WEBGL_COMPONENT_TYPES[ accessor.componentType ] );
4658
+ box.min.multiplyScalar( boxScale );
4659
+ box.max.multiplyScalar( boxScale );
4660
+
4661
+ }
4662
+
4663
+ } else {
4664
+
4665
+ console.warn( 'THREE.GLTFLoader: Missing min/max properties for accessor POSITION.' );
4666
+
4667
+ return;
4668
+
4669
+ }
4670
+
4671
+ } else {
4672
+
4673
+ return;
4674
+
4675
+ }
4676
+
4677
+ const targets = primitiveDef.targets;
4678
+
4679
+ if ( targets !== undefined ) {
4680
+
4681
+ const maxDisplacement = new THREE.Vector3();
4682
+ const vector = new THREE.Vector3();
4683
+
4684
+ for ( let i = 0, il = targets.length; i < il; i ++ ) {
4685
+
4686
+ const target = targets[ i ];
4687
+
4688
+ if ( target.POSITION !== undefined ) {
4689
+
4690
+ const accessor = parser.json.accessors[ target.POSITION ];
4691
+ const min = accessor.min;
4692
+ const max = accessor.max;
4693
+
4694
+ // glTF requires 'min' and 'max', but VRM (which extends glTF) currently ignores that requirement.
4695
+
4696
+ if ( min !== undefined && max !== undefined ) {
4697
+
4698
+ // we need to get max of absolute components because target weight is [-1,1]
4699
+ vector.setX( Math.max( Math.abs( min[ 0 ] ), Math.abs( max[ 0 ] ) ) );
4700
+ vector.setY( Math.max( Math.abs( min[ 1 ] ), Math.abs( max[ 1 ] ) ) );
4701
+ vector.setZ( Math.max( Math.abs( min[ 2 ] ), Math.abs( max[ 2 ] ) ) );
4702
+
4703
+
4704
+ if ( accessor.normalized ) {
4705
+
4706
+ const boxScale = getNormalizedComponentScale( WEBGL_COMPONENT_TYPES[ accessor.componentType ] );
4707
+ vector.multiplyScalar( boxScale );
4708
+
4709
+ }
4710
+
4711
+ // Note: this assumes that the sum of all weights is at most 1. This isn't quite correct - it's more conservative
4712
+ // to assume that each target can have a max weight of 1. However, for some use cases - notably, when morph targets
4713
+ // are used to implement key-frame animations and as such only two are active at a time - this results in very large
4714
+ // boxes. So for now we make a box that's sometimes a touch too small but is hopefully mostly of reasonable size.
4715
+ maxDisplacement.max( vector );
4716
+
4717
+ } else {
4718
+
4719
+ console.warn( 'THREE.GLTFLoader: Missing min/max properties for accessor POSITION.' );
4720
+
4721
+ }
4722
+
4723
+ }
4724
+
4725
+ }
4726
+
4727
+ // As per comment above this box isn't conservative, but has a reasonable size for a very large number of morph targets.
4728
+ box.expandByVector( maxDisplacement );
4729
+
4730
+ }
4731
+
4732
+ geometry.boundingBox = box;
4733
+
4734
+ const sphere = new THREE.Sphere();
4735
+
4736
+ box.getCenter( sphere.center );
4737
+ sphere.radius = box.min.distanceTo( box.max ) / 2;
4738
+
4739
+ geometry.boundingSphere = sphere;
4740
+
4741
+ }
4742
+
4743
+ /**
4744
+ *
4745
+ * @private
4746
+ * @param {BufferGeometry} geometry
4747
+ * @param {GLTF.Primitive} primitiveDef
4748
+ * @param {GLTFParser} parser
4749
+ * @return {Promise<BufferGeometry>}
4750
+ */
4751
+ function addPrimitiveAttributes( geometry, primitiveDef, parser ) {
4752
+
4753
+ const attributes = primitiveDef.attributes;
4754
+
4755
+ const pending = [];
4756
+
4757
+ function assignAttributeAccessor( accessorIndex, attributeName ) {
4758
+
4759
+ return parser.getDependency( 'accessor', accessorIndex )
4760
+ .then( function ( accessor ) {
4761
+
4762
+ geometry.setAttribute( attributeName, accessor );
4763
+
4764
+ } );
4765
+
4766
+ }
4767
+
4768
+ for ( const gltfAttributeName in attributes ) {
4769
+
4770
+ const threeAttributeName = ATTRIBUTES[ gltfAttributeName ] || gltfAttributeName.toLowerCase();
4771
+
4772
+ // Skip attributes already provided by e.g. Draco extension.
4773
+ if ( threeAttributeName in geometry.attributes ) continue;
4774
+
4775
+ pending.push( assignAttributeAccessor( attributes[ gltfAttributeName ], threeAttributeName ) );
4776
+
4777
+ }
4778
+
4779
+ if ( primitiveDef.indices !== undefined && ! geometry.index ) {
4780
+
4781
+ const accessor = parser.getDependency( 'accessor', primitiveDef.indices ).then( function ( accessor ) {
4782
+
4783
+ geometry.setIndex( accessor );
4784
+
4785
+ } );
4786
+
4787
+ pending.push( accessor );
4788
+
4789
+ }
4790
+
4791
+ if ( THREE.ColorManagement.workingColorSpace !== THREE.LinearSRGBColorSpace && 'COLOR_0' in attributes ) {
4792
+
4793
+ console.warn( `THREE.GLTFLoader: Converting vertex colors from "srgb-linear" to "${THREE.ColorManagement.workingColorSpace}" not supported.` );
4794
+
4795
+ }
4796
+
4797
+ assignExtrasToUserData( geometry, primitiveDef );
4798
+
4799
+ computeBounds( geometry, primitiveDef, parser );
4800
+
4801
+ return Promise.all( pending ).then( function () {
4802
+
4803
+ return primitiveDef.targets !== undefined
4804
+ ? addMorphTargets( geometry, primitiveDef.targets, parser )
4805
+ : geometry;
4806
+
4807
+ } );
4808
+
4809
+ }
4810
+
4811
+ exports.GLTFLoader = GLTFLoader;