UNPKG

node-three-gltf

Version:

Use three.js GLTFLoader in a Node.js environment

1,277 lines (1,271 loc) 188 kB
'use strict'; var jsdom = require('jsdom'); var node_util = require('node:util'); var node_buffer = require('node:buffer'); var node_url = require('node:url'); var node_path = require('node:path'); var three = require('three'); var promises = require('node:fs/promises'); var fetch = require('node-fetch'); var base64Js = require('base64-js'); var sharp = require('sharp'); var node_worker_threads = require('node:worker_threads'); var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null; const dom = new jsdom.JSDOM().window; if (!global.DOMParser) { global.DOMParser = dom.DOMParser; } if (!global.Blob) { global.Blob = node_buffer.Blob; } if (!global.URL) { global.URL = node_url.URL; } if (!global.TextDecoder) { global.TextDecoder = node_util.TextDecoder; } const loading = {}; class FileLoader extends three.Loader { constructor(manager) { super(manager); } load(url, onLoad, onProgress, onError) { if (url === undefined) url = ''; if (this.path !== undefined) url = this.path + url; url = this.manager.resolveURL(url); if (loading[url] !== undefined) { loading[url].push({ onLoad, onProgress, onError }); return; } loading[url] = []; loading[url].push({ onLoad, onProgress, onError, }); const mimeType = this.mimeType; const responseType = this.responseType; let promise; if (!/^https?:\/\//.test(url) && !/^data:/.test(url)) { promise = promises.readFile(url) .then(buffer => { switch (responseType) { case 'arraybuffer': const ab = new ArrayBuffer(buffer.length); const view = new Uint8Array(ab); for (let i = 0; i < buffer.length; i++) { view[i] = buffer[i]; } return ab; case 'document': const text = buffer.toString(); const parser = new DOMParser(); return parser.parseFromString(text, mimeType); case 'json': return JSON.parse(buffer.toString()); default: return buffer.toString(); } }); } else if (/^data:application\/octet-stream;base64,/.test(url)) { const base64 = url.split(';base64,').pop(); const buffer = base64Js.toByteArray(base64); promise = Promise.resolve(buffer.buffer); } else { const req = new fetch.Request(url, { headers: new fetch.Headers(this.requestHeader), credentials: this.withCredentials ? 'include' : 'same-origin', }); promise = fetch(req) .then(response => { if (response.status === 200 || response.status === 0) { if (response.status === 0) { console.warn('THREE.FileLoader: HTTP Status 0 received.'); } return response; } else { throw Error(`fetch for "${response.url}" responded with ${response.status}: ${response.statusText}`); } }) .then(response => { switch (responseType) { case 'arraybuffer': return response.arrayBuffer(); case 'blob': return response.blob(); case 'document': return response.text() .then(text => { const parser = new DOMParser(); return parser.parseFromString(text, mimeType); }); case 'json': return response.json(); default: if (mimeType === undefined) { return response.text(); } else { const re = /charset="?([^;"\s]*)"?/i; const exec = re.exec(mimeType); const label = exec && exec[1] ? exec[1].toLowerCase() : undefined; const decoder = new TextDecoder(label); return response.arrayBuffer().then(ab => decoder.decode(ab)); } } }); } promise .then(data => { const callbacks = loading[url]; delete loading[url]; for (let i = 0, il = callbacks.length; i < il; i++) { const callback = callbacks[i]; if (callback.onLoad) callback.onLoad(data); } }) .catch(err => { const callbacks = loading[url]; if (callbacks === undefined) { this.manager.itemError(url); throw err; } delete loading[url]; for (let i = 0, il = callbacks.length; i < il; i++) { const callback = callbacks[i]; if (callback.onError) callback.onError(err); } this.manager.itemError(url); }) .finally(() => { this.manager.itemEnd(url); }); this.manager.itemStart(url); } setResponseType(value) { this.responseType = value; return this; } setMimeType(value) { this.mimeType = value; return this; } } class ImageLoader extends three.Loader { constructor(manager) { super(manager); } load(url, onLoad, onProgress, onError) { if (this.path !== undefined) url = this.path + url; url = this.manager.resolveURL(url); const scope = this; const cached = three.Cache.get(url); if (cached !== undefined) { scope.manager.itemStart(url); setTimeout(function () { if (onLoad) onLoad(cached); scope.manager.itemEnd(url); }, 0); } scope.manager.itemStart(url); Promise.resolve() .then(async () => { if (/^blob:.*$/i.test(url)) { const blob = node_buffer.resolveObjectURL(url); const imageBuffer = node_buffer.Buffer.from(await blob.arrayBuffer()); return sharp(imageBuffer); } else if (/^data:/.test(url)) { const base64 = url.split(';base64,').pop(); const imageBuffer = base64Js.toByteArray(base64); return sharp(imageBuffer); } else if (/^https?:\/\//.test(url)) { const req = new fetch.Request(url, { headers: new fetch.Headers(this.requestHeader), credentials: this.withCredentials ? 'include' : 'same-origin', }); const response = await fetch(req); const buffer = node_buffer.Buffer.from(await response.arrayBuffer()); return sharp(buffer); } else { return sharp(url); } }) .then(image => image .ensureAlpha() .raw() .toBuffer({ resolveWithObject: true })) .then(({ data, info }) => ({ data, width: info.width, height: info.height, channels: info.channels, })) .then(data => { three.Cache.add(url, data); if (onLoad) onLoad(data); scope.manager.itemEnd(url); }) .catch(err => { if (onError) onError(err); scope.manager.itemError(url); scope.manager.itemEnd(url); }); } } class TextureLoader extends three.Loader { constructor(manager) { super(manager); } load(url, onLoad, onProgress, onError) { const texture = new three.Texture(); const loader = new ImageLoader(this.manager); loader.setCrossOrigin(this.crossOrigin); loader.setPath(this.path); loader.load(url, function (image) { texture.image = image; texture.needsUpdate = true; if (onLoad !== undefined) { onLoad(texture); } }, onProgress, onError); return texture; } } class GLTFLoader extends three.Loader { constructor(manager) { super(manager); this.dracoLoader = null; this.ktx2Loader = null; this.meshoptDecoder = null; this.pluginCallbacks = []; this.register((parser) => { return new GLTFMaterialsClearcoatExtension$1(parser); }); this.register((parser) => { return new GLTFTextureBasisUExtension(parser); }); this.register((parser) => { return new GLTFTextureWebPExtension(parser); }); this.register((parser) => { return new GLTFMaterialsSheenExtension$1(parser); }); this.register((parser) => { return new GLTFMaterialsTransmissionExtension$1(parser); }); this.register((parser) => { return new GLTFMaterialsVolumeExtension$1(parser); }); this.register((parser) => { return new GLTFMaterialsIorExtension$1(parser); }); this.register(function (parser) { return new GLTFMaterialsEmissiveStrengthExtension$1(parser); }); this.register((parser) => { return new GLTFMaterialsSpecularExtension$1(parser); }); this.register(function (parser) { return new GLTFMaterialsAnisotropyExtension$1(parser); }); this.register((parser) => { return new GLTFLightsExtension(parser); }); this.register((parser) => { return new GLTFMeshoptCompression(parser); }); } load(url, onLoad, onProgress, onError) { const scope = this; let resourcePath; if (this.resourcePath !== '') { resourcePath = this.resourcePath; } else if (this.path !== '') { resourcePath = this.path; } else { if (!/^https?:\/\//.test(url) && !/^data:/.test(url)) { resourcePath = node_path.dirname(url) + node_path.sep; } else { resourcePath = three.LoaderUtils.extractUrlBase(url); } } this.manager.itemStart(url); const _onError = (e) => { if (onError) { onError(e); } else { console.error(e); } scope.manager.itemError(url); scope.manager.itemEnd(url); }; const loader = new FileLoader(this.manager); loader.setPath(this.path); loader.setResponseType('arraybuffer'); loader.setRequestHeader(this.requestHeader); loader.setWithCredentials(this.withCredentials); loader.load(url, (data) => { try { scope.parse(data, resourcePath, (gltf) => { onLoad(gltf); scope.manager.itemEnd(url); }, _onError); } catch (e) { _onError(e); } }, onProgress, _onError); } setDRACOLoader(dracoLoader) { this.dracoLoader = dracoLoader; return this; } setDDSLoader() { throw new Error('THREE.GLTFLoader: "MSFT_texture_dds" no longer supported. Please update to "KHR_texture_basisu".'); } setKTX2Loader(ktx2Loader) { this.ktx2Loader = ktx2Loader; return this; } setMeshoptDecoder(meshoptDecoder) { this.meshoptDecoder = meshoptDecoder; return this; } register(callback) { if (this.pluginCallbacks.indexOf(callback) === -1) { this.pluginCallbacks.push(callback); } return this; } unregister(callback) { if (this.pluginCallbacks.indexOf(callback) !== -1) { this.pluginCallbacks.splice(this.pluginCallbacks.indexOf(callback), 1); } return this; } parse(data, path, onLoad, onError) { let content; const extensions = {}; const plugins = {}; const textDecoder = new TextDecoder(); if (typeof data === 'string') { content = data; } else { if (data instanceof node_buffer.Buffer) { data = data.buffer; } const magic = textDecoder.decode(new Uint8Array(data.slice(0, 4))); if (magic === BINARY_EXTENSION_HEADER_MAGIC) { try { extensions[EXTENSIONS.KHR_BINARY_GLTF] = new GLTFBinaryExtension(data); } catch (error) { if (onError) onError(error); return; } content = extensions[EXTENSIONS.KHR_BINARY_GLTF].content; } else { content = textDecoder.decode(new Uint8Array(data)); } } const json = JSON.parse(content); if (json.asset === undefined || json.asset.version[0] < 2) { if (onError) { onError(new Error('THREE.GLTFLoader: Unsupported asset. glTF versions >=2.0 are supported.')); } return; } const parser = new GLTFParser(json, { path: path || this.resourcePath || '', crossOrigin: this.crossOrigin, requestHeader: this.requestHeader, manager: this.manager, ktx2Loader: this.ktx2Loader, meshoptDecoder: this.meshoptDecoder }); parser.fileLoader.setRequestHeader(this.requestHeader); for (let i = 0; i < this.pluginCallbacks.length; i++) { const plugin = this.pluginCallbacks[i](parser); plugins[plugin.name] = plugin; extensions[plugin.name] = true; } if (json.extensionsUsed) { for (let i = 0; i < json.extensionsUsed.length; ++i) { const extensionName = json.extensionsUsed[i]; const extensionsRequired = json.extensionsRequired || []; switch (extensionName) { case EXTENSIONS.KHR_MATERIALS_UNLIT: extensions[extensionName] = new GLTFMaterialsUnlitExtension$1(); break; case EXTENSIONS.KHR_DRACO_MESH_COMPRESSION: extensions[extensionName] = new GLTFDracoMeshCompressionExtension(json, this.dracoLoader); break; case EXTENSIONS.KHR_TEXTURE_TRANSFORM: extensions[extensionName] = new GLTFTextureTransformExtension(); break; case EXTENSIONS.KHR_MESH_QUANTIZATION: extensions[extensionName] = new GLTFMeshQuantizationExtension(); break; default: if (extensionsRequired.indexOf(extensionName) >= 0 && plugins[extensionName] === undefined) { console.warn('THREE.GLTFLoader: Unknown extension "' + extensionName + '".'); } } } } parser.setExtensions(extensions); parser.setPlugins(plugins); parser.parse(onLoad, onError); } parseAsync(data, path) { const scope = this; return new Promise(function (resolve, reject) { scope.parse(data, path, resolve, reject); }); } } GLTFLoader.LOG_TEXTURE_LOAD_ERROR = true; function GLTFRegistry() { let objects = {}; return { get: (key) => { return objects[key]; }, add: (key, object) => { objects[key] = object; }, remove: (key) => { delete objects[key]; }, removeAll: () => { objects = {}; } }; } const EXTENSIONS = { 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_IOR: 'KHR_materials_ior', KHR_MATERIALS_SHEEN: 'KHR_materials_sheen', KHR_MATERIALS_SPECULAR: 'KHR_materials_specular', KHR_MATERIALS_TRANSMISSION: 'KHR_materials_transmission', 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_TEXTURE_WEBP: 'EXT_texture_webp', EXT_MESHOPT_COMPRESSION: 'EXT_meshopt_compression' }; class GLTFLightsExtension { constructor(parser) { this.name = EXTENSIONS.KHR_LIGHTS_PUNCTUAL; this.cache = { refs: {}, uses: {} }; this.parser = parser; } _markDefs() { const parser = this.parser; const nodeDefs = this.parser.json.nodes || []; for (let nodeIndex = 0, nodeLength = nodeDefs.length; nodeIndex < nodeLength; nodeIndex++) { const nodeDef = nodeDefs[nodeIndex]; if (nodeDef.extensions && nodeDef.extensions[this.name] && nodeDef.extensions[this.name].light !== undefined) { parser._addNodeRef(this.cache, nodeDef.extensions[this.name].light); } } } _loadLight(lightIndex) { const parser = this.parser; const cacheKey = 'light:' + lightIndex; let dependency = parser.cache.get(cacheKey); if (dependency) return dependency; const json = parser.json; const extensions = (json.extensions && json.extensions[this.name]) || {}; const lightDefs = extensions.lights || []; const lightDef = lightDefs[lightIndex]; let lightNode; const color = new three.Color(0xffffff); if (lightDef.color !== undefined) color.setRGB(lightDef.color[0], lightDef.color[1], lightDef.color[2], three.LinearSRGBColorSpace); const range = lightDef.range !== undefined ? lightDef.range : 0; switch (lightDef.type) { case 'directional': lightNode = new three.DirectionalLight(color); lightNode.target.position.set(0, 0, -1); lightNode.add(lightNode.target); break; case 'point': lightNode = new three.PointLight(color); lightNode.distance = range; break; case 'spot': lightNode = new three.SpotLight(color); lightNode.distance = range; lightDef.spot = lightDef.spot || {}; lightDef.spot.innerConeAngle = lightDef.spot.innerConeAngle !== undefined ? lightDef.spot.innerConeAngle : 0; lightDef.spot.outerConeAngle = lightDef.spot.outerConeAngle !== undefined ? lightDef.spot.outerConeAngle : Math.PI / 4.0; lightNode.angle = lightDef.spot.outerConeAngle; lightNode.penumbra = 1.0 - lightDef.spot.innerConeAngle / lightDef.spot.outerConeAngle; lightNode.target.position.set(0, 0, -1); lightNode.add(lightNode.target); break; default: throw new Error('THREE.GLTFLoader: Unexpected light type: ' + lightDef.type); } lightNode.position.set(0, 0, 0); lightNode.decay = 2; if (lightDef.intensity !== undefined) lightNode.intensity = lightDef.intensity; lightNode.name = parser.createUniqueName(lightDef.name || ('light_' + lightIndex)); dependency = Promise.resolve(lightNode); parser.cache.add(cacheKey, dependency); return dependency; } createNodeAttachment(nodeIndex) { const self = this; const parser = this.parser; const json = parser.json; const nodeDef = json.nodes[nodeIndex]; const lightDef = (nodeDef.extensions && nodeDef.extensions[this.name]) || {}; const lightIndex = lightDef.light; if (lightIndex === undefined) return null; return this._loadLight(lightIndex).then(function (light) { return parser._getNodeRef(self.cache, lightIndex, light); }); } } let GLTFMaterialsUnlitExtension$1 = class GLTFMaterialsUnlitExtension { constructor() { this.name = EXTENSIONS.KHR_MATERIALS_UNLIT; } getMaterialType() { return three.MeshBasicMaterial; } extendParams(materialParams, materialDef, parser) { const pending = []; materialParams.color = new three.Color(1.0, 1.0, 1.0); materialParams.opacity = 1.0; const metallicRoughness = materialDef.pbrMetallicRoughness; if (metallicRoughness) { if (Array.isArray(metallicRoughness.baseColorFactor)) { const array = metallicRoughness.baseColorFactor; materialParams.color.setRGB(array[0], array[1], array[2], three.LinearSRGBColorSpace); materialParams.opacity = array[3]; } if (metallicRoughness.baseColorTexture !== undefined) { pending.push(parser.assignTexture(materialParams, 'map', metallicRoughness.baseColorTexture, three.SRGBColorSpace)); } } return Promise.all(pending); } }; let GLTFMaterialsEmissiveStrengthExtension$1 = class GLTFMaterialsEmissiveStrengthExtension { constructor(parser) { this.name = EXTENSIONS.KHR_MATERIALS_EMISSIVE_STRENGTH; this.parser = parser; } extendMaterialParams(materialIndex, materialParams) { const parser = this.parser; const materialDef = parser.json.materials[materialIndex]; if (!materialDef.extensions || !materialDef.extensions[this.name]) { return Promise.resolve(); } const emissiveStrength = materialDef.extensions[this.name].emissiveStrength; if (emissiveStrength !== undefined) { materialParams.emissiveIntensity = emissiveStrength; } return Promise.resolve(); } }; let GLTFMaterialsClearcoatExtension$1 = class GLTFMaterialsClearcoatExtension { constructor(parser) { this.name = EXTENSIONS.KHR_MATERIALS_CLEARCOAT; this.parser = parser; } getMaterialType(materialIndex) { const parser = this.parser; const materialDef = parser.json.materials[materialIndex]; if (!materialDef.extensions || !materialDef.extensions[this.name]) return null; return three.MeshPhysicalMaterial; } extendMaterialParams(materialIndex, materialParams) { const parser = this.parser; const materialDef = parser.json.materials[materialIndex]; if (!materialDef.extensions || !materialDef.extensions[this.name]) { return Promise.resolve(); } const pending = []; const extension = materialDef.extensions[this.name]; if (extension.clearcoatFactor !== undefined) { materialParams.clearcoat = extension.clearcoatFactor; } if (extension.clearcoatTexture !== undefined) { pending.push(parser.assignTexture(materialParams, 'clearcoatMap', extension.clearcoatTexture)); } if (extension.clearcoatRoughnessFactor !== undefined) { materialParams.clearcoatRoughness = extension.clearcoatRoughnessFactor; } if (extension.clearcoatRoughnessTexture !== undefined) { pending.push(parser.assignTexture(materialParams, 'clearcoatRoughnessMap', extension.clearcoatRoughnessTexture)); } if (extension.clearcoatNormalTexture !== undefined) { pending.push(parser.assignTexture(materialParams, 'clearcoatNormalMap', extension.clearcoatNormalTexture)); if (extension.clearcoatNormalTexture.scale !== undefined) { const scale = extension.clearcoatNormalTexture.scale; materialParams.clearcoatNormalScale = new three.Vector2(scale, scale); } } return Promise.all(pending); } }; let GLTFMaterialsSheenExtension$1 = class GLTFMaterialsSheenExtension { constructor(parser) { this.name = EXTENSIONS.KHR_MATERIALS_SHEEN; this.parser = parser; } getMaterialType(materialIndex) { const parser = this.parser; const materialDef = parser.json.materials[materialIndex]; if (!materialDef.extensions || !materialDef.extensions[this.name]) return null; return three.MeshPhysicalMaterial; } extendMaterialParams(materialIndex, materialParams) { const parser = this.parser; const materialDef = parser.json.materials[materialIndex]; if (!materialDef.extensions || !materialDef.extensions[this.name]) { return Promise.resolve(); } const pending = []; materialParams.sheenColor = new three.Color(0, 0, 0); materialParams.sheenRoughness = 0; materialParams.sheen = 1; const extension = materialDef.extensions[this.name]; if (extension.sheenColorFactor !== undefined) { const colorFactor = extension.sheenColorFactor; materialParams.sheenColor.setRGB(colorFactor[0], colorFactor[1], colorFactor[2], three.LinearSRGBColorSpace); } if (extension.sheenRoughnessFactor !== undefined) { materialParams.sheenRoughness = extension.sheenRoughnessFactor; } if (extension.sheenColorTexture !== undefined) { pending.push(parser.assignTexture(materialParams, 'sheenColorMap', extension.sheenColorTexture, three.SRGBColorSpace)); } if (extension.sheenRoughnessTexture !== undefined) { pending.push(parser.assignTexture(materialParams, 'sheenRoughnessMap', extension.sheenRoughnessTexture)); } return Promise.all(pending); } }; let GLTFMaterialsTransmissionExtension$1 = class GLTFMaterialsTransmissionExtension { constructor(parser) { this.name = EXTENSIONS.KHR_MATERIALS_TRANSMISSION; this.parser = parser; } getMaterialType(materialIndex) { const parser = this.parser; const materialDef = parser.json.materials[materialIndex]; if (!materialDef.extensions || !materialDef.extensions[this.name]) return null; return three.MeshPhysicalMaterial; } extendMaterialParams(materialIndex, materialParams) { const parser = this.parser; const materialDef = parser.json.materials[materialIndex]; if (!materialDef.extensions || !materialDef.extensions[this.name]) { return Promise.resolve(); } const pending = []; const extension = materialDef.extensions[this.name]; if (extension.transmissionFactor !== undefined) { materialParams.transmission = extension.transmissionFactor; } if (extension.transmissionTexture !== undefined) { pending.push(parser.assignTexture(materialParams, 'transmissionMap', extension.transmissionTexture)); } return Promise.all(pending); } }; let GLTFMaterialsVolumeExtension$1 = class GLTFMaterialsVolumeExtension { constructor(parser) { this.name = EXTENSIONS.KHR_MATERIALS_VOLUME; this.parser = parser; } getMaterialType(materialIndex) { const parser = this.parser; const materialDef = parser.json.materials[materialIndex]; if (!materialDef.extensions || !materialDef.extensions[this.name]) return null; return three.MeshPhysicalMaterial; } extendMaterialParams(materialIndex, materialParams) { const parser = this.parser; const materialDef = parser.json.materials[materialIndex]; if (!materialDef.extensions || !materialDef.extensions[this.name]) { return Promise.resolve(); } const pending = []; const extension = materialDef.extensions[this.name]; materialParams.thickness = extension.thicknessFactor !== undefined ? extension.thicknessFactor : 0; if (extension.thicknessTexture !== undefined) { pending.push(parser.assignTexture(materialParams, 'thicknessMap', extension.thicknessTexture)); } materialParams.attenuationDistance = extension.attenuationDistance || 0; const colorArray = extension.attenuationColor || [1, 1, 1]; materialParams.attenuationColor = new three.Color().setRGB(colorArray[0], colorArray[1], colorArray[2], three.LinearSRGBColorSpace); return Promise.all(pending); } }; let GLTFMaterialsIorExtension$1 = class GLTFMaterialsIorExtension { constructor(parser) { this.name = EXTENSIONS.KHR_MATERIALS_IOR; this.parser = parser; } getMaterialType(materialIndex) { const parser = this.parser; const materialDef = parser.json.materials[materialIndex]; if (!materialDef.extensions || !materialDef.extensions[this.name]) return null; return three.MeshPhysicalMaterial; } extendMaterialParams(materialIndex, materialParams) { const parser = this.parser; const materialDef = parser.json.materials[materialIndex]; if (!materialDef.extensions || !materialDef.extensions[this.name]) { return Promise.resolve(); } const extension = materialDef.extensions[this.name]; materialParams.ior = extension.ior !== undefined ? extension.ior : 1.5; return Promise.resolve(); } }; let GLTFMaterialsSpecularExtension$1 = class GLTFMaterialsSpecularExtension { constructor(parser) { this.name = EXTENSIONS.KHR_MATERIALS_SPECULAR; this.parser = parser; } getMaterialType(materialIndex) { const parser = this.parser; const materialDef = parser.json.materials[materialIndex]; if (!materialDef.extensions || !materialDef.extensions[this.name]) return null; return three.MeshPhysicalMaterial; } extendMaterialParams(materialIndex, materialParams) { const parser = this.parser; const materialDef = parser.json.materials[materialIndex]; if (!materialDef.extensions || !materialDef.extensions[this.name]) { return Promise.resolve(); } const pending = []; const extension = materialDef.extensions[this.name]; materialParams.specularIntensity = extension.specularFactor !== undefined ? extension.specularFactor : 1.0; if (extension.specularTexture !== undefined) { pending.push(parser.assignTexture(materialParams, 'specularIntensityMap', extension.specularTexture)); } const colorArray = extension.specularColorFactor || [1, 1, 1]; materialParams.specularColor = new three.Color().setRGB(colorArray[0], colorArray[1], colorArray[2], three.LinearSRGBColorSpace); if (extension.specularColorTexture !== undefined) { pending.push(parser.assignTexture(materialParams, 'specularColorMap', extension.specularColorTexture, three.SRGBColorSpace)); } return Promise.all(pending); } }; let GLTFMaterialsAnisotropyExtension$1 = class GLTFMaterialsAnisotropyExtension { constructor(parser) { this.name = EXTENSIONS.KHR_MATERIALS_ANISOTROPY; this.parser = parser; } getMaterialType(materialIndex) { const parser = this.parser; const materialDef = parser.json.materials[materialIndex]; if (!materialDef.extensions || !materialDef.extensions[this.name]) return null; return three.MeshPhysicalMaterial; } extendMaterialParams(materialIndex, materialParams) { const parser = this.parser; const materialDef = parser.json.materials[materialIndex]; if (!materialDef.extensions || !materialDef.extensions[this.name]) { return Promise.resolve(); } const pending = []; const extension = materialDef.extensions[this.name]; if (extension.anisotropyStrength !== undefined) { materialParams.anisotropy = extension.anisotropyStrength; } if (extension.anisotropyRotation !== undefined) { materialParams.anisotropyRotation = extension.anisotropyRotation; } if (extension.anisotropyTexture !== undefined) { pending.push(parser.assignTexture(materialParams, 'anisotropyMap', extension.anisotropyTexture)); } return Promise.all(pending); } }; class GLTFTextureBasisUExtension { constructor(parser) { this.name = EXTENSIONS.KHR_TEXTURE_BASISU; this.parser = parser; } loadTexture(textureIndex) { const parser = this.parser; const json = parser.json; const textureDef = json.textures[textureIndex]; if (!textureDef.extensions || !textureDef.extensions[this.name]) { return null; } const extension = textureDef.extensions[this.name]; const loader = parser.options.ktx2Loader; if (!loader) { if (json.extensionsRequired && json.extensionsRequired.indexOf(this.name) >= 0) { throw new Error('THREE.GLTFLoader: setKTX2Loader must be called before loading KTX2 textures'); } else { return null; } } return parser.loadTextureImage(textureIndex, extension.source, loader); } } class GLTFTextureWebPExtension { constructor(parser) { this.name = EXTENSIONS.EXT_TEXTURE_WEBP; this.isSupported = null; this.parser = parser; } loadTexture(textureIndex) { const name = this.name; const parser = this.parser; const json = parser.json; const textureDef = json.textures[textureIndex]; if (!textureDef.extensions || !textureDef.extensions[name]) { return null; } const extension = textureDef.extensions[name]; const source = json.images[extension.source]; let loader = parser.textureLoader; if (source.uri) { const handler = parser.options.manager.getHandler(source.uri); if (handler !== null) loader = handler; } return this.detectSupport().then(function (isSupported) { if (isSupported) return parser.loadTextureImage(textureIndex, extension.source, loader); if (json.extensionsRequired && json.extensionsRequired.indexOf(name) >= 0) { throw new Error('THREE.GLTFLoader: WebP required by asset but unsupported.'); } return parser.loadTexture(textureIndex); }); } detectSupport() { if (!this.isSupported) { this.isSupported = Promise.resolve(true); } return this.isSupported; } } class GLTFMeshoptCompression { constructor(parser) { this.name = EXTENSIONS.EXT_MESHOPT_COMPRESSION; this.parser = parser; } loadBufferView(index) { const json = this.parser.json; const bufferView = json.bufferViews[index]; if (bufferView.extensions && bufferView.extensions[this.name]) { const extensionDef = bufferView.extensions[this.name]; const buffer = this.parser.getDependency('buffer', extensionDef.buffer); const decoder = this.parser.options.meshoptDecoder; if (!decoder || !decoder.supported) { if (json.extensionsRequired && json.extensionsRequired.indexOf(this.name) >= 0) { throw new Error('THREE.GLTFLoader: setMeshoptDecoder must be called before loading compressed files'); } else { return null; } } return Promise.all([buffer, decoder.ready]).then(function (res) { const byteOffset = extensionDef.byteOffset || 0; const byteLength = extensionDef.byteLength || 0; const count = extensionDef.count; const stride = extensionDef.byteStride; const result = new ArrayBuffer(count * stride); const source = new Uint8Array(res[0], byteOffset, byteLength); decoder.decodeGltfBuffer(new Uint8Array(result), count, stride, source, extensionDef.mode, extensionDef.filter); return result; }); } else { return null; } } } const BINARY_EXTENSION_HEADER_MAGIC = 'glTF'; const BINARY_EXTENSION_HEADER_LENGTH = 12; const BINARY_EXTENSION_CHUNK_TYPES = { JSON: 0x4E4F534A, BIN: 0x004E4942 }; class GLTFBinaryExtension { constructor(data) { this.name = EXTENSIONS.KHR_BINARY_GLTF; this.content = null; this.body = null; const headerView = new DataView(data, 0, BINARY_EXTENSION_HEADER_LENGTH); const textDecoder = new TextDecoder(); this.header = { magic: textDecoder.decode(new Uint8Array(data.slice(0, 4))), version: headerView.getUint32(4, true), length: headerView.getUint32(8, true) }; if (this.header.magic !== BINARY_EXTENSION_HEADER_MAGIC) { throw new Error('THREE.GLTFLoader: Unsupported glTF-Binary header.'); } else if (this.header.version < 2.0) { throw new Error('THREE.GLTFLoader: Legacy binary file detected.'); } const chunkContentsLength = this.header.length - BINARY_EXTENSION_HEADER_LENGTH; const chunkView = new DataView(data, BINARY_EXTENSION_HEADER_LENGTH); let chunkIndex = 0; while (chunkIndex < chunkContentsLength) { const chunkLength = chunkView.getUint32(chunkIndex, true); chunkIndex += 4; const chunkType = chunkView.getUint32(chunkIndex, true); chunkIndex += 4; if (chunkType === BINARY_EXTENSION_CHUNK_TYPES.JSON) { const contentArray = new Uint8Array(data, BINARY_EXTENSION_HEADER_LENGTH + chunkIndex, chunkLength); this.content = textDecoder.decode(contentArray); } else if (chunkType === BINARY_EXTENSION_CHUNK_TYPES.BIN) { const byteOffset = BINARY_EXTENSION_HEADER_LENGTH + chunkIndex; this.body = data.slice(byteOffset, byteOffset + chunkLength); } chunkIndex += chunkLength; } if (this.content === null) { throw new Error('THREE.GLTFLoader: JSON content not found.'); } } } class GLTFDracoMeshCompressionExtension { constructor(json, dracoLoader) { this.name = EXTENSIONS.KHR_DRACO_MESH_COMPRESSION; if (!dracoLoader) { throw new Error('THREE.GLTFLoader: No DRACOLoader instance provided.'); } this.json = json; this.dracoLoader = dracoLoader; this.dracoLoader.preload(); } decodePrimitive(primitive, parser) { const json = this.json; const dracoLoader = this.dracoLoader; const bufferViewIndex = primitive.extensions[this.name].bufferView; const gltfAttributeMap = primitive.extensions[this.name].attributes; const threeAttributeMap = {}; const attributeNormalizedMap = {}; const attributeTypeMap = {}; for (const attributeName in gltfAttributeMap) { const threeAttributeName = ATTRIBUTES[attributeName] || attributeName.toLowerCase(); threeAttributeMap[threeAttributeName] = gltfAttributeMap[attributeName]; } for (const attributeName in primitive.attributes) { const threeAttributeName = ATTRIBUTES[attributeName] || attributeName.toLowerCase(); if (gltfAttributeMap[attributeName] !== undefined) { const accessorDef = json.accessors[primitive.attributes[attributeName]]; const componentType = WEBGL_COMPONENT_TYPES[accessorDef.componentType]; attributeTypeMap[threeAttributeName] = componentType.name; attributeNormalizedMap[threeAttributeName] = accessorDef.normalized === true; } } return parser.getDependency('bufferView', bufferViewIndex).then(function (bufferView) { return new Promise(function (resolve) { dracoLoader.decodeDracoFile(bufferView, function (geometry) { for (const attributeName in geometry.attributes) { const attribute = geometry.attributes[attributeName]; const normalized = attributeNormalizedMap[attributeName]; if (normalized !== undefined) attribute.normalized = normalized; } resolve(geometry); }, threeAttributeMap, attributeTypeMap); }); }); } } class GLTFTextureTransformExtension { constructor() { this.name = EXTENSIONS.KHR_TEXTURE_TRANSFORM; } extendTexture(texture, transform) { if (transform.texCoord !== undefined) { console.warn('THREE.GLTFLoader: Custom UV sets in "' + this.name + '" extension not yet supported.'); } if (transform.offset === undefined && transform.rotation === undefined && transform.scale === undefined) { return texture; } texture = texture.clone(); if (transform.offset !== undefined) { texture.offset.fromArray(transform.offset); } if (transform.rotation !== undefined) { texture.rotation = transform.rotation; } if (transform.scale !== undefined) { texture.repeat.fromArray(transform.scale); } texture.needsUpdate = true; return texture; } } class GLTFMeshQuantizationExtension { constructor() { this.name = EXTENSIONS.KHR_MESH_QUANTIZATION; } } class GLTFCubicSplineInterpolant extends three.Interpolant { constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) { super(parameterPositions, sampleValues, sampleSize, resultBuffer); this.beforeStart_ = this.copySampleValue_; this.afterEnd_ = this.copySampleValue_; } copySampleValue_(index) { const result = this.resultBuffer, values = this.sampleValues, valueSize = this.valueSize, offset = index * valueSize * 3 + valueSize; for (let i = 0; i !== valueSize; i++) { result[i] = values[offset + i]; } return result; } interpolate_(i1, t0, t, t1) { const result = this.resultBuffer; const values = this.sampleValues; const stride = this.valueSize; const stride2 = stride * 2; const stride3 = stride * 3; const td = t1 - t0; const p = (t - t0) / td; const pp = p * p; const ppp = pp * p; const offset1 = i1 * stride3; const offset0 = offset1 - stride3; const s2 = -2 * ppp + 3 * pp; const s3 = ppp - pp; const s0 = 1 - s2; const s1 = s3 - pp + p; for (let i = 0; i !== stride; i++) { const p0 = values[offset0 + i + stride]; const m0 = values[offset0 + i + stride2] * td; const p1 = values[offset1 + i + stride]; const m1 = values[offset1 + i] * td; result[i] = s0 * p0 + s1 * m0 + s2 * p1 + s3 * m1; } return result; } ; } const _q = new three.Quaternion(); class GLTFCubicSplineQuaternionInterpolant extends GLTFCubicSplineInterpolant { interpolate_(i1, t0, t, t1) { const result = super.interpolate_(i1, t0, t, t1); _q.fromArray(result).normalize().toArray(result); return result; } } const WEBGL_CONSTANTS$1 = { 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 }; const WEBGL_COMPONENT_TYPES = { 5120: Int8Array, 5121: Uint8Array, 5122: Int16Array, 5123: Uint16Array, 5125: Uint32Array, 5126: Float32Array }; const WEBGL_FILTERS = { 9728: three.NearestFilter, 9729: three.LinearFilter, 9984: three.NearestMipmapNearestFilter, 9985: three.LinearMipmapNearestFilter, 9986: three.NearestMipmapLinearFilter, 9987: three.LinearMipmapLinearFilter }; const WEBGL_WRAPPINGS = { 33071: three.ClampToEdgeWrapping, 33648: three.MirroredRepeatWrapping, 10497: three.RepeatWrapping }; const WEBGL_TYPE_SIZES = { 'SCALAR': 1, 'VEC2': 2, 'VEC3': 3, 'VEC4': 4, 'MAT2': 4, 'MAT3': 9, 'MAT4': 16 }; const ATTRIBUTES = { POSITION: 'position', NORMAL: 'normal', TANGENT: 'tangent', TEXCOORD_0: 'uv', TEXCOORD_1: 'uv2', COLOR_0: 'color', WEIGHTS_0: 'skinWeight', JOINTS_0: 'skinIndex', }; const PATH_PROPERTIES$1 = { scale: 'scale', translation: 'position', rotation: 'quaternion', weights: 'morphTargetInfluences' }; const INTERPOLATION = { CUBICSPLINE: undefined, LINEAR: three.InterpolateLinear, STEP: three.InterpolateDiscrete }; const ALPHA_MODES = { OPAQUE: 'OPAQUE', MASK: 'MASK', BLEND: 'BLEND' }; function createDefaultMaterial(cache) { if (cache['DefaultMaterial'] === undefined) { cache['DefaultMaterial'] = new three.MeshStandardMaterial({ color: 0xFFFFFF, emissive: 0x000000, metalness: 1, roughness: 1, transparent: false, depthTest: true, side: three.FrontSide }); } return cache['DefaultMaterial']; } function addUnknownExtensionsToUserData(knownExtensions, object, objectDef) { for (const name in objectDef.extensions) { if (knownExtensions[name] === undefined) { object.userData.gltfExtensions = object.userData.gltfExtensions || {}; object.userData.gltfExtensions[name] = objectDef.extensions[name]; } } } function assignExtrasToUserData(object, gltfDef) { if (gltfDef.extras !== undefined) { if (typeof gltfDef.extras === 'object') { Object.assign(object.userData, gltfDef.extras); } else { console.warn('THREE.GLTFLoader: Ignoring primitive type .extras, ' + gltfDef.extras); } } } function addMorphTargets(geometry, targets, parser) { let hasMorphPosition = false; let hasMorphNormal = false; for (let i = 0, il = targets.length; i < il; i++) { const target = targets[i]; if (target.POSITION !== undefined) hasMorphPosition = true; if (target.NORMAL !== undefined) hasMorphNormal = true; if (hasMorphPosition && hasMorphNormal) break; } if (!hasMorphPosition && !hasMorphNormal) return Promise.resolve(geometry); const pendingPositionAccessors = []; const pendingNormalAccessors = []; for (let i = 0, il = targets.length; i < il; i++) { const target = targets[i]; if (hasMorphPosition) { const pendingAccessor = target.POSITION !== undefined ? parser.getDependency('accessor', target.POSITION) : geometry.attributes.position; pendingPositionAccessors.push(pendingAccessor); } if (hasMorphNormal) { const pendingAccessor = target.NORMAL !== undefined ? parser.getDependency('accessor', target.NORMAL) : geometry.attributes.normal; pendingNormalAccessors.push(pendingAccessor); } } return Promise.all([ Promise.all(pendingPositionAccessors), Promise.all(pendingNormalAccessors) ]).then(accessors => { const morphPositions = accessors[0]; const morphNormals = accessors[1]; if (hasMorphPosition) geometry.morphAttributes.position = morphPositions; if (hasMorphNormal) geometry.morphAttributes.normal = morphNormals; geometry.morphTargetsRelative = true; return geometry; }); } function updateMorphTargets(mesh, meshDef) { mesh.updateMorphTargets(); if (meshDef.weights !== undefined) { for (let i = 0, il = meshDef.weights.length; i < il; i++) { mesh.morphTargetInfluences[i] = meshDef.weights[i]; } } if (meshDef.extras && Array.isArray(meshDef.extras.targetNames)) { const targetNames = meshDef.extras.targetNames; if (mesh.morphTargetInfluences.length === targetNames.length) { mesh.morphTargetDictionary = {}; for (let i = 0, il = targetNames.length; i < il; i++) { mesh.morphTargetDictionary[targetNames[i]