UNPKG

itowns

Version:

A JS/WebGL framework for 3D geospatial data visualization

1,385 lines (1,163 loc) 113 kB
"use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.GLTFLoader = void 0; var _typeof2 = _interopRequireDefault(require("@babel/runtime/helpers/typeof")); var _assertThisInitialized2 = _interopRequireDefault(require("@babel/runtime/helpers/assertThisInitialized")); var _get2 = _interopRequireDefault(require("@babel/runtime/helpers/get")); var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck")); var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass")); var _inherits2 = _interopRequireDefault(require("@babel/runtime/helpers/inherits")); var _possibleConstructorReturn2 = _interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn")); var _getPrototypeOf2 = _interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf")); var _three = require("three"); function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function () { var Super = (0, _getPrototypeOf2["default"])(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = (0, _getPrototypeOf2["default"])(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return (0, _possibleConstructorReturn2["default"])(this, result); }; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } var GLTFLoader = /*#__PURE__*/function (_Loader) { (0, _inherits2["default"])(GLTFLoader, _Loader); var _super = _createSuper(GLTFLoader); function GLTFLoader(manager) { var _this; (0, _classCallCheck2["default"])(this, GLTFLoader); _this = _super.call(this, manager); _this.dracoLoader = null; _this.ktx2Loader = null; _this.meshoptDecoder = null; _this.pluginCallbacks = []; _this.register(function (parser) { return new GLTFMaterialsClearcoatExtension(parser); }); _this.register(function (parser) { return new GLTFTextureBasisUExtension(parser); }); _this.register(function (parser) { return new GLTFTextureWebPExtension(parser); }); _this.register(function (parser) { return new GLTFMaterialsTransmissionExtension(parser); }); _this.register(function (parser) { return new GLTFMaterialsVolumeExtension(parser); }); _this.register(function (parser) { return new GLTFMaterialsIorExtension(parser); }); _this.register(function (parser) { return new GLTFMaterialsSpecularExtension(parser); }); _this.register(function (parser) { return new GLTFLightsExtension(parser); }); _this.register(function (parser) { return new GLTFMeshoptCompression(parser); }); return _this; } (0, _createClass2["default"])(GLTFLoader, [{ key: "load", value: function load(url, onLoad, onProgress, onError) { var scope = this; var resourcePath; if (this.resourcePath !== '') { resourcePath = this.resourcePath; } else if (this.path !== '') { resourcePath = this.path; } else { resourcePath = _three.LoaderUtils.extractUrlBase(url); } // Tells the LoadingManager to track an extra item, which resolves after // the model is fully loaded. This means the count of items loaded will // be incorrect, but ensures manager.onLoad() does not fire early. this.manager.itemStart(url); var _onError = function (e) { if (onError) { onError(e); } else { console.error(e); } scope.manager.itemError(url); scope.manager.itemEnd(url); }; var loader = new _three.FileLoader(this.manager); loader.setPath(this.path); loader.setResponseType('arraybuffer'); loader.setRequestHeader(this.requestHeader); loader.setWithCredentials(this.withCredentials); loader.load(url, function (data) { try { scope.parse(data, resourcePath, function (gltf) { onLoad(gltf); scope.manager.itemEnd(url); }, _onError); } catch (e) { _onError(e); } }, onProgress, _onError); } }, { key: "setDRACOLoader", value: function setDRACOLoader(dracoLoader) { this.dracoLoader = dracoLoader; return this; } }, { key: "setDDSLoader", value: function setDDSLoader() { throw new Error('THREE.GLTFLoader: "MSFT_texture_dds" no longer supported. Please update to "KHR_texture_basisu".'); } }, { key: "setKTX2Loader", value: function setKTX2Loader(ktx2Loader) { this.ktx2Loader = ktx2Loader; return this; } }, { key: "setMeshoptDecoder", value: function setMeshoptDecoder(meshoptDecoder) { this.meshoptDecoder = meshoptDecoder; return this; } }, { key: "register", value: function register(callback) { if (this.pluginCallbacks.indexOf(callback) === -1) { this.pluginCallbacks.push(callback); } return this; } }, { key: "unregister", value: function unregister(callback) { if (this.pluginCallbacks.indexOf(callback) !== -1) { this.pluginCallbacks.splice(this.pluginCallbacks.indexOf(callback), 1); } return this; } }, { key: "parse", value: function parse(data, path, onLoad, onError) { var content; var extensions = {}; var plugins = {}; if (typeof data === 'string') { content = data; } else { var magic = _three.LoaderUtils.decodeText(new Uint8Array(data, 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 = _three.LoaderUtils.decodeText(new Uint8Array(data)); } } var 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; } var 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 (var i = 0; i < this.pluginCallbacks.length; i++) { var plugin = this.pluginCallbacks[i](parser); plugins[plugin.name] = plugin; // Workaround to avoid determining as unknown extension // in addUnknownExtensionsToUserData(). // Remove this workaround if we move all the existing // extension handlers to plugin system extensions[plugin.name] = true; } if (json.extensionsUsed) { for (var _i = 0; _i < json.extensionsUsed.length; ++_i) { var extensionName = json.extensionsUsed[_i]; var extensionsRequired = json.extensionsRequired || []; switch (extensionName) { case EXTENSIONS.KHR_MATERIALS_UNLIT: extensions[extensionName] = new GLTFMaterialsUnlitExtension(); break; case EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS: extensions[extensionName] = new GLTFMaterialsPbrSpecularGlossinessExtension(); 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); } }]); return GLTFLoader; }(_three.Loader); /* GLTFREGISTRY */ exports.GLTFLoader = GLTFLoader; function GLTFRegistry() { var objects = {}; return { get: function get(key) { return objects[key]; }, add: function add(key, object) { objects[key] = object; }, remove: function remove(key) { delete objects[key]; }, removeAll: function removeAll() { objects = {}; } }; } /*********************************/ /********** EXTENSIONS ***********/ /*********************************/ var 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_PBR_SPECULAR_GLOSSINESS: 'KHR_materials_pbrSpecularGlossiness', KHR_MATERIALS_SPECULAR: 'KHR_materials_specular', KHR_MATERIALS_TRANSMISSION: 'KHR_materials_transmission', 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', EXT_TEXTURE_WEBP: 'EXT_texture_webp', EXT_MESHOPT_COMPRESSION: 'EXT_meshopt_compression' }; /** * Punctual Lights Extension * * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_lights_punctual */ var GLTFLightsExtension = /*#__PURE__*/function () { function GLTFLightsExtension(parser) { (0, _classCallCheck2["default"])(this, GLTFLightsExtension); this.parser = parser; this.name = EXTENSIONS.KHR_LIGHTS_PUNCTUAL; // Object3D instance caches this.cache = { refs: {}, uses: {} }; } (0, _createClass2["default"])(GLTFLightsExtension, [{ key: "_markDefs", value: function _markDefs() { var parser = this.parser; var nodeDefs = this.parser.json.nodes || []; for (var nodeIndex = 0, nodeLength = nodeDefs.length; nodeIndex < nodeLength; nodeIndex++) { var 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); } } } }, { key: "_loadLight", value: function _loadLight(lightIndex) { var parser = this.parser; var cacheKey = 'light:' + lightIndex; var dependency = parser.cache.get(cacheKey); if (dependency) return dependency; var json = parser.json; var extensions = json.extensions && json.extensions[this.name] || {}; var lightDefs = extensions.lights || []; var lightDef = lightDefs[lightIndex]; var lightNode; var color = new _three.Color(0xffffff); if (lightDef.color !== undefined) color.fromArray(lightDef.color); var 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; // Handle spotlight properties. 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); } // Some lights (e.g. spot) default to a position other than the origin. Reset the position // here, because node-level parsing will only override position if explicitly specified. 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; } }, { key: "createNodeAttachment", value: function createNodeAttachment(nodeIndex) { var self = this; var parser = this.parser; var json = parser.json; var nodeDef = json.nodes[nodeIndex]; var lightDef = nodeDef.extensions && nodeDef.extensions[this.name] || {}; var lightIndex = lightDef.light; if (lightIndex === undefined) return null; return this._loadLight(lightIndex).then(function (light) { return parser._getNodeRef(self.cache, lightIndex, light); }); } }]); return GLTFLightsExtension; }(); /** * Unlit Materials Extension * * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_unlit */ var GLTFMaterialsUnlitExtension = /*#__PURE__*/function () { function GLTFMaterialsUnlitExtension() { (0, _classCallCheck2["default"])(this, GLTFMaterialsUnlitExtension); this.name = EXTENSIONS.KHR_MATERIALS_UNLIT; } (0, _createClass2["default"])(GLTFMaterialsUnlitExtension, [{ key: "getMaterialType", value: function getMaterialType() { return _three.MeshBasicMaterial; } }, { key: "extendParams", value: function extendParams(materialParams, materialDef, parser) { var pending = []; materialParams.color = new _three.Color(1.0, 1.0, 1.0); materialParams.opacity = 1.0; var metallicRoughness = materialDef.pbrMetallicRoughness; if (metallicRoughness) { if (Array.isArray(metallicRoughness.baseColorFactor)) { var array = metallicRoughness.baseColorFactor; materialParams.color.fromArray(array); materialParams.opacity = array[3]; } if (metallicRoughness.baseColorTexture !== undefined) { pending.push(parser.assignTexture(materialParams, 'map', metallicRoughness.baseColorTexture)); } } return Promise.all(pending); } }]); return GLTFMaterialsUnlitExtension; }(); /** * Clearcoat Materials Extension * * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_clearcoat */ var GLTFMaterialsClearcoatExtension = /*#__PURE__*/function () { function GLTFMaterialsClearcoatExtension(parser) { (0, _classCallCheck2["default"])(this, GLTFMaterialsClearcoatExtension); this.parser = parser; this.name = EXTENSIONS.KHR_MATERIALS_CLEARCOAT; } (0, _createClass2["default"])(GLTFMaterialsClearcoatExtension, [{ key: "getMaterialType", value: function getMaterialType(materialIndex) { var parser = this.parser; var materialDef = parser.json.materials[materialIndex]; if (!materialDef.extensions || !materialDef.extensions[this.name]) return null; return _three.MeshPhysicalMaterial; } }, { key: "extendMaterialParams", value: function extendMaterialParams(materialIndex, materialParams) { var parser = this.parser; var materialDef = parser.json.materials[materialIndex]; if (!materialDef.extensions || !materialDef.extensions[this.name]) { return Promise.resolve(); } var pending = []; var 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) { var scale = extension.clearcoatNormalTexture.scale; // https://github.com/mrdoob/three.js/issues/11438#issuecomment-507003995 materialParams.clearcoatNormalScale = new _three.Vector2(scale, -scale); } } return Promise.all(pending); } }]); return GLTFMaterialsClearcoatExtension; }(); /** * Transmission Materials Extension * * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_transmission * Draft: https://github.com/KhronosGroup/glTF/pull/1698 */ var GLTFMaterialsTransmissionExtension = /*#__PURE__*/function () { function GLTFMaterialsTransmissionExtension(parser) { (0, _classCallCheck2["default"])(this, GLTFMaterialsTransmissionExtension); this.parser = parser; this.name = EXTENSIONS.KHR_MATERIALS_TRANSMISSION; } (0, _createClass2["default"])(GLTFMaterialsTransmissionExtension, [{ key: "getMaterialType", value: function getMaterialType(materialIndex) { var parser = this.parser; var materialDef = parser.json.materials[materialIndex]; if (!materialDef.extensions || !materialDef.extensions[this.name]) return null; return _three.MeshPhysicalMaterial; } }, { key: "extendMaterialParams", value: function extendMaterialParams(materialIndex, materialParams) { var parser = this.parser; var materialDef = parser.json.materials[materialIndex]; if (!materialDef.extensions || !materialDef.extensions[this.name]) { return Promise.resolve(); } var pending = []; var 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); } }]); return GLTFMaterialsTransmissionExtension; }(); /** * Materials Volume Extension * * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_volume */ var GLTFMaterialsVolumeExtension = /*#__PURE__*/function () { function GLTFMaterialsVolumeExtension(parser) { (0, _classCallCheck2["default"])(this, GLTFMaterialsVolumeExtension); this.parser = parser; this.name = EXTENSIONS.KHR_MATERIALS_VOLUME; } (0, _createClass2["default"])(GLTFMaterialsVolumeExtension, [{ key: "getMaterialType", value: function getMaterialType(materialIndex) { var parser = this.parser; var materialDef = parser.json.materials[materialIndex]; if (!materialDef.extensions || !materialDef.extensions[this.name]) return null; return _three.MeshPhysicalMaterial; } }, { key: "extendMaterialParams", value: function extendMaterialParams(materialIndex, materialParams) { var parser = this.parser; var materialDef = parser.json.materials[materialIndex]; if (!materialDef.extensions || !materialDef.extensions[this.name]) { return Promise.resolve(); } var pending = []; var 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; var colorArray = extension.attenuationColor || [1, 1, 1]; materialParams.attenuationTint = new _three.Color(colorArray[0], colorArray[1], colorArray[2]); return Promise.all(pending); } }]); return GLTFMaterialsVolumeExtension; }(); /** * Materials ior Extension * * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_ior */ var GLTFMaterialsIorExtension = /*#__PURE__*/function () { function GLTFMaterialsIorExtension(parser) { (0, _classCallCheck2["default"])(this, GLTFMaterialsIorExtension); this.parser = parser; this.name = EXTENSIONS.KHR_MATERIALS_IOR; } (0, _createClass2["default"])(GLTFMaterialsIorExtension, [{ key: "getMaterialType", value: function getMaterialType(materialIndex) { var parser = this.parser; var materialDef = parser.json.materials[materialIndex]; if (!materialDef.extensions || !materialDef.extensions[this.name]) return null; return _three.MeshPhysicalMaterial; } }, { key: "extendMaterialParams", value: function extendMaterialParams(materialIndex, materialParams) { var parser = this.parser; var materialDef = parser.json.materials[materialIndex]; if (!materialDef.extensions || !materialDef.extensions[this.name]) { return Promise.resolve(); } var extension = materialDef.extensions[this.name]; materialParams.ior = extension.ior !== undefined ? extension.ior : 1.5; return Promise.resolve(); } }]); return GLTFMaterialsIorExtension; }(); /** * Materials specular Extension * * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_specular */ var GLTFMaterialsSpecularExtension = /*#__PURE__*/function () { function GLTFMaterialsSpecularExtension(parser) { (0, _classCallCheck2["default"])(this, GLTFMaterialsSpecularExtension); this.parser = parser; this.name = EXTENSIONS.KHR_MATERIALS_SPECULAR; } (0, _createClass2["default"])(GLTFMaterialsSpecularExtension, [{ key: "getMaterialType", value: function getMaterialType(materialIndex) { var parser = this.parser; var materialDef = parser.json.materials[materialIndex]; if (!materialDef.extensions || !materialDef.extensions[this.name]) return null; return _three.MeshPhysicalMaterial; } }, { key: "extendMaterialParams", value: function extendMaterialParams(materialIndex, materialParams) { var parser = this.parser; var materialDef = parser.json.materials[materialIndex]; if (!materialDef.extensions || !materialDef.extensions[this.name]) { return Promise.resolve(); } var pending = []; var 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)); } var colorArray = extension.specularColorFactor || [1, 1, 1]; materialParams.specularTint = new _three.Color(colorArray[0], colorArray[1], colorArray[2]); if (extension.specularColorTexture !== undefined) { pending.push(parser.assignTexture(materialParams, 'specularTintMap', extension.specularColorTexture).then(function (texture) { texture.encoding = _three.sRGBEncoding; })); } return Promise.all(pending); } }]); return GLTFMaterialsSpecularExtension; }(); /** * BasisU Texture Extension * * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_texture_basisu */ var GLTFTextureBasisUExtension = /*#__PURE__*/function () { function GLTFTextureBasisUExtension(parser) { (0, _classCallCheck2["default"])(this, GLTFTextureBasisUExtension); this.parser = parser; this.name = EXTENSIONS.KHR_TEXTURE_BASISU; } (0, _createClass2["default"])(GLTFTextureBasisUExtension, [{ key: "loadTexture", value: function loadTexture(textureIndex) { var parser = this.parser; var json = parser.json; var textureDef = json.textures[textureIndex]; if (!textureDef.extensions || !textureDef.extensions[this.name]) { return null; } var extension = textureDef.extensions[this.name]; var source = json.images[extension.source]; var 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 { // Assumes that the extension is optional and that a fallback texture is present return null; } } return parser.loadTextureImage(textureIndex, source, loader); } }]); return GLTFTextureBasisUExtension; }(); /** * WebP Texture Extension * * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/EXT_texture_webp */ var GLTFTextureWebPExtension = /*#__PURE__*/function () { function GLTFTextureWebPExtension(parser) { (0, _classCallCheck2["default"])(this, GLTFTextureWebPExtension); this.parser = parser; this.name = EXTENSIONS.EXT_TEXTURE_WEBP; this.isSupported = null; } (0, _createClass2["default"])(GLTFTextureWebPExtension, [{ key: "loadTexture", value: function loadTexture(textureIndex) { var name = this.name; var parser = this.parser; var json = parser.json; var textureDef = json.textures[textureIndex]; if (!textureDef.extensions || !textureDef.extensions[name]) { return null; } var extension = textureDef.extensions[name]; var source = json.images[extension.source]; var loader = parser.textureLoader; if (source.uri) { var handler = parser.options.manager.getHandler(source.uri); if (handler !== null) loader = handler; } return this.detectSupport().then(function (isSupported) { if (isSupported) return parser.loadTextureImage(textureIndex, source, loader); if (json.extensionsRequired && json.extensionsRequired.indexOf(name) >= 0) { throw new Error('THREE.GLTFLoader: WebP required by asset but unsupported.'); } // Fall back to PNG or JPEG. return parser.loadTexture(textureIndex); }); } }, { key: "detectSupport", value: function detectSupport() { if (!this.isSupported) { this.isSupported = new Promise(function (resolve) { var image = new Image(); // Lossy test image. Support for lossy images doesn't guarantee support for all // WebP images, unfortunately. image.src = 'data:image/webp;base64,UklGRiIAAABXRUJQVlA4IBYAAAAwAQCdASoBAAEADsD+JaQAA3AAAAAA'; image.onload = image.onerror = function () { resolve(image.height === 1); }; }); } return this.isSupported; } }]); return GLTFTextureWebPExtension; }(); /** * meshopt BufferView Compression Extension * * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/EXT_meshopt_compression */ var GLTFMeshoptCompression = /*#__PURE__*/function () { function GLTFMeshoptCompression(parser) { (0, _classCallCheck2["default"])(this, GLTFMeshoptCompression); this.name = EXTENSIONS.EXT_MESHOPT_COMPRESSION; this.parser = parser; } (0, _createClass2["default"])(GLTFMeshoptCompression, [{ key: "loadBufferView", value: function loadBufferView(index) { var json = this.parser.json; var bufferView = json.bufferViews[index]; if (bufferView.extensions && bufferView.extensions[this.name]) { var extensionDef = bufferView.extensions[this.name]; var buffer = this.parser.getDependency('buffer', extensionDef.buffer); var 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 { // Assumes that the extension is optional and that fallback buffer data is present return null; } } return Promise.all([buffer, decoder.ready]).then(function (res) { var byteOffset = extensionDef.byteOffset || 0; var byteLength = extensionDef.byteLength || 0; var count = extensionDef.count; var stride = extensionDef.byteStride; var result = new ArrayBuffer(count * stride); var source = new Uint8Array(res[0], byteOffset, byteLength); decoder.decodeGltfBuffer(new Uint8Array(result), count, stride, source, extensionDef.mode, extensionDef.filter); return result; }); } else { return null; } } }]); return GLTFMeshoptCompression; }(); /* BINARY EXTENSION */ var BINARY_EXTENSION_HEADER_MAGIC = 'glTF'; var BINARY_EXTENSION_HEADER_LENGTH = 12; var BINARY_EXTENSION_CHUNK_TYPES = { JSON: 0x4E4F534A, BIN: 0x004E4942 }; var GLTFBinaryExtension = function GLTFBinaryExtension(data) { (0, _classCallCheck2["default"])(this, GLTFBinaryExtension); this.name = EXTENSIONS.KHR_BINARY_GLTF; this.content = null; this.body = null; var headerView = new DataView(data, 0, BINARY_EXTENSION_HEADER_LENGTH); this.header = { magic: _three.LoaderUtils.decodeText(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.'); } var chunkContentsLength = this.header.length - BINARY_EXTENSION_HEADER_LENGTH; var chunkView = new DataView(data, BINARY_EXTENSION_HEADER_LENGTH); var chunkIndex = 0; while (chunkIndex < chunkContentsLength) { var chunkLength = chunkView.getUint32(chunkIndex, true); chunkIndex += 4; var chunkType = chunkView.getUint32(chunkIndex, true); chunkIndex += 4; if (chunkType === BINARY_EXTENSION_CHUNK_TYPES.JSON) { var contentArray = new Uint8Array(data, BINARY_EXTENSION_HEADER_LENGTH + chunkIndex, chunkLength); this.content = _three.LoaderUtils.decodeText(contentArray); } else if (chunkType === BINARY_EXTENSION_CHUNK_TYPES.BIN) { var byteOffset = BINARY_EXTENSION_HEADER_LENGTH + chunkIndex; this.body = data.slice(byteOffset, byteOffset + chunkLength); } // Clients must ignore chunks with unknown types. chunkIndex += chunkLength; } if (this.content === null) { throw new Error('THREE.GLTFLoader: JSON content not found.'); } }; /** * DRACO Mesh Compression Extension * * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_draco_mesh_compression */ var GLTFDracoMeshCompressionExtension = /*#__PURE__*/function () { function GLTFDracoMeshCompressionExtension(json, dracoLoader) { (0, _classCallCheck2["default"])(this, GLTFDracoMeshCompressionExtension); if (!dracoLoader) { throw new Error('THREE.GLTFLoader: No DRACOLoader instance provided.'); } this.name = EXTENSIONS.KHR_DRACO_MESH_COMPRESSION; this.json = json; this.dracoLoader = dracoLoader; this.dracoLoader.preload(); } (0, _createClass2["default"])(GLTFDracoMeshCompressionExtension, [{ key: "decodePrimitive", value: function decodePrimitive(primitive, parser) { var json = this.json; var dracoLoader = this.dracoLoader; var bufferViewIndex = primitive.extensions[this.name].bufferView; var gltfAttributeMap = primitive.extensions[this.name].attributes; var threeAttributeMap = {}; var attributeNormalizedMap = {}; var attributeTypeMap = {}; for (var attributeName in gltfAttributeMap) { var threeAttributeName = ATTRIBUTES[attributeName] || attributeName.toLowerCase(); threeAttributeMap[threeAttributeName] = gltfAttributeMap[attributeName]; } for (var _attributeName in primitive.attributes) { var _threeAttributeName = ATTRIBUTES[_attributeName] || _attributeName.toLowerCase(); if (gltfAttributeMap[_attributeName] !== undefined) { var accessorDef = json.accessors[primitive.attributes[_attributeName]]; var componentType = WEBGL_COMPONENT_TYPES[accessorDef.componentType]; attributeTypeMap[_threeAttributeName] = componentType; attributeNormalizedMap[_threeAttributeName] = accessorDef.normalized === true; } } return parser.getDependency('bufferView', bufferViewIndex).then(function (bufferView) { return new Promise(function (resolve) { dracoLoader.decodeDracoFile(bufferView, function (geometry) { for (var _attributeName2 in geometry.attributes) { var attribute = geometry.attributes[_attributeName2]; var normalized = attributeNormalizedMap[_attributeName2]; if (normalized !== undefined) attribute.normalized = normalized; } resolve(geometry); }, threeAttributeMap, attributeTypeMap); }); }); } }]); return GLTFDracoMeshCompressionExtension; }(); /** * Texture Transform Extension * * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_texture_transform */ var GLTFTextureTransformExtension = /*#__PURE__*/function () { function GLTFTextureTransformExtension() { (0, _classCallCheck2["default"])(this, GLTFTextureTransformExtension); this.name = EXTENSIONS.KHR_TEXTURE_TRANSFORM; } (0, _createClass2["default"])(GLTFTextureTransformExtension, [{ key: "extendTexture", value: function 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) { // See https://github.com/mrdoob/three.js/issues/21819. 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; } }]); return GLTFTextureTransformExtension; }(); /** * Specular-Glossiness Extension * * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_pbrSpecularGlossiness */ /** * A sub class of StandardMaterial with some of the functionality * changed via the `onBeforeCompile` callback * @pailhead */ var GLTFMeshStandardSGMaterial = /*#__PURE__*/function (_MeshStandardMaterial) { (0, _inherits2["default"])(GLTFMeshStandardSGMaterial, _MeshStandardMaterial); var _super2 = _createSuper(GLTFMeshStandardSGMaterial); function GLTFMeshStandardSGMaterial(params) { var _this2; (0, _classCallCheck2["default"])(this, GLTFMeshStandardSGMaterial); _this2 = _super2.call(this); _this2.isGLTFSpecularGlossinessMaterial = true; //various chunks that need replacing var specularMapParsFragmentChunk = ['#ifdef USE_SPECULARMAP', ' uniform sampler2D specularMap;', '#endif'].join('\n'); var glossinessMapParsFragmentChunk = ['#ifdef USE_GLOSSINESSMAP', ' uniform sampler2D glossinessMap;', '#endif'].join('\n'); var specularMapFragmentChunk = ['vec3 specularFactor = specular;', '#ifdef USE_SPECULARMAP', ' vec4 texelSpecular = texture2D( specularMap, vUv );', ' texelSpecular = sRGBToLinear( texelSpecular );', ' // reads channel RGB, compatible with a glTF Specular-Glossiness (RGBA) texture', ' specularFactor *= texelSpecular.rgb;', '#endif'].join('\n'); var glossinessMapFragmentChunk = ['float glossinessFactor = glossiness;', '#ifdef USE_GLOSSINESSMAP', ' vec4 texelGlossiness = texture2D( glossinessMap, vUv );', ' // reads channel A, compatible with a glTF Specular-Glossiness (RGBA) texture', ' glossinessFactor *= texelGlossiness.a;', '#endif'].join('\n'); var lightPhysicalFragmentChunk = ['PhysicalMaterial material;', 'material.diffuseColor = diffuseColor.rgb * ( 1. - max( specularFactor.r, max( specularFactor.g, specularFactor.b ) ) );', 'vec3 dxy = max( abs( dFdx( geometryNormal ) ), abs( dFdy( geometryNormal ) ) );', 'float geometryRoughness = max( max( dxy.x, dxy.y ), dxy.z );', 'material.specularRoughness = max( 1.0 - glossinessFactor, 0.0525 ); // 0.0525 corresponds to the base mip of a 256 cubemap.', 'material.specularRoughness += geometryRoughness;', 'material.specularRoughness = min( material.specularRoughness, 1.0 );', 'material.specularColor = specularFactor;'].join('\n'); var uniforms = { specular: { value: new _three.Color().setHex(0xffffff) }, glossiness: { value: 1 }, specularMap: { value: null }, glossinessMap: { value: null } }; _this2._extraUniforms = uniforms; _this2.onBeforeCompile = function (shader) { for (var uniformName in uniforms) { shader.uniforms[uniformName] = uniforms[uniformName]; } shader.fragmentShader = shader.fragmentShader.replace('uniform float roughness;', 'uniform vec3 specular;').replace('uniform float metalness;', 'uniform float glossiness;').replace('#include <roughnessmap_pars_fragment>', specularMapParsFragmentChunk).replace('#include <metalnessmap_pars_fragment>', glossinessMapParsFragmentChunk).replace('#include <roughnessmap_fragment>', specularMapFragmentChunk).replace('#include <metalnessmap_fragment>', glossinessMapFragmentChunk).replace('#include <lights_physical_fragment>', lightPhysicalFragmentChunk); }; Object.defineProperties((0, _assertThisInitialized2["default"])(_this2), { specular: { get: function get() { return uniforms.specular.value; }, set: function set(v) { uniforms.specular.value = v; } }, specularMap: { get: function get() { return uniforms.specularMap.value; }, set: function set(v) { uniforms.specularMap.value = v; if (v) { this.defines.USE_SPECULARMAP = ''; // USE_UV is set by the renderer for specular maps } else { delete this.defines.USE_SPECULARMAP; } } }, glossiness: { get: function get() { return uniforms.glossiness.value; }, set: function set(v) { uniforms.glossiness.value = v; } }, glossinessMap: { get: function get() { return uniforms.glossinessMap.value; }, set: function set(v) { uniforms.glossinessMap.value = v; if (v) { this.defines.USE_GLOSSINESSMAP = ''; this.defines.USE_UV = ''; } else { delete this.defines.USE_GLOSSINESSMAP; delete this.defines.USE_UV; } } } }); delete _this2.metalness; delete _this2.roughness; delete _this2.metalnessMap; delete _this2.roughnessMap; _this2.setValues(params); return _this2; } (0, _createClass2["default"])(GLTFMeshStandardSGMaterial, [{ key: "copy", value: function copy(source) { (0, _get2["default"])((0, _getPrototypeOf2["default"])(GLTFMeshStandardSGMaterial.prototype), "copy", this).call(this, source); this.specularMap = source.specularMap; this.specular.copy(source.specular); this.glossinessMap = source.glossinessMap; this.glossiness = source.glossiness; delete this.metalness; delete this.roughness; delete this.metalnessMap; delete this.roughnessMap; return this; } }]); return GLTFMeshStandardSGMaterial; }(_three.MeshStandardMaterial); var GLTFMaterialsPbrSpecularGlossinessExtension = /*#__PURE__*/function () { function GLTFMaterialsPbrSpecularGlossinessExtension() { (0, _classCallCheck2["default"])(this, GLTFMaterialsPbrSpecularGlossinessExtension); this.name = EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS; this.specularGlossinessParams = ['color', 'map', 'lightMap', 'lightMapIntensity', 'aoMap', 'aoMapIntensity', 'emissive', 'emissiveIntensity', 'emissiveMap', 'bumpMap', 'bumpScale', 'normalMap', 'normalMapType', 'displacementMap', 'displacementScale', 'displacementBias', 'specularMap', 'specular', 'glossinessMap', 'glossiness', 'alphaMap', 'envMap', 'envMapIntensity', 'refractionRatio']; } (0, _createClass2["default"])(GLTFMaterialsPbrSpecularGlossinessExtension, [{ key: "getMaterialType", value: function getMaterialType() { return GLTFMeshStandardSGMaterial; } }, { key: "extendParams", value: function extendParams(materialParams, materialDef, parser) { var pbrSpecularGlossiness = materialDef.extensions[this.name]; materialParams.color = new _three.Color(1.0, 1.0, 1.0); materialParams.opacity = 1.0; var pending = []; if (Array.isArray(pbrSpecularGlossiness.diffuseFactor)) { var array = pbrSpecularGlossiness.diffuseFactor; materialParams.color.fromArray(array); materialParams.opacity = array[3]; } if (pbrSpecularGlossiness.diffuseTexture !== undefined) { pending.push(parser.assignTexture(materialParams, 'map', pbrSpecularGlossiness.diffuseTexture)); } materialParams.emissive = new _three.Color(0.0, 0.0, 0.0); materialParams.glossiness = pbrSpecularGlossiness.glossinessFactor !== undefined ? pbrSpecularGlossiness.glossinessFactor : 1.0; materialParams.specular = new _three.Color(1.0, 1.0, 1.0); if (Array.isArray(pbrSpecularGlossiness.specularFactor)) { materialParams.specular.fromArray(pbrSpecularGlossiness.specularFactor); } if (pbrSpecularGlossiness.specularGlossinessTexture !== undefined) { var specGlossMapDef = pbrSpecularGlossiness.specularGlossinessTexture; pending.push(parser.assignTexture(materialParams, 'glossinessMap', specGlossMapDef)); pending.push(parser.assignTexture(materialParams, 'specularMap', specGlossMapDef)); } return Promise.all(pending); } }, { key: "createMaterial", value: function createMaterial(materialParams) { var material = new GLTFMeshStandardSGMaterial(materialParams); material.fog = true; material.color = materialParams.color; material.map = materialParams.map === undefined ? null : materialParams.map; material.lightMap = null; material.lightMapIntensity = 1.0; material.aoMap = materialParams.aoMap === undefined ? null : materialParams.aoMap; material.aoMapIntensity = 1.0; material.emissive = materialParams.emissive; material.emissiveIntensity = 1.0; material.emissiveMap = materialParams.emissiveMap === undefined ? null : materialParams.emissiveMap; material.bumpMap = materialParams.bumpMap === undefined ? null : materialParams.bumpMap; material.bumpScale = 1; material.normalMap = materialParams.normalMap === undefined ? null : materialParams.normalMap; material.normalMapType = _three.TangentSpaceNormalMap; if (materialParams.normalScale) material.normalScale = materialParams.normalScale; material.displacementMap = null; material.displacementScale = 1; material.displacementBias = 0; material.specularMap = materialParams.specularMap === undefined ? null : materialParams.specularMap; material.specular = materialParams.specular; material.glossinessMap = materialParams.glossinessMap === undefined ? null : materialParams.glossinessMap; material.glossiness = materialParams.glossiness; material.alphaMap = null; material.envMap = materialParams.envMap === undefined ? null : materialParams.envMap; material.envMapIntensity = 1.0; material.refractionRatio = 0.98; return material; } }]); return GLTFMaterialsPbrSpecularGlossinessExtension; }(); /** * Mesh Quantization Extension * * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_mesh_quantization */ var GLTFMeshQuantizationExtension = function GLTFMeshQuantizationExtension() { (0, _classCallCheck2["default"])(this, GLTFMeshQuantizationExtension); this.name = EXTENSIONS.KHR_MESH_QUANTIZATION; }; /*********************************/ /********** INTERPOLATION ********/ /*********************************/ // Spline Interpolation // Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#appendix-c-spline-interpolation var GLTFCubicSplineInterpolant = /*#__PURE__*/function (_Interpolant) { (0, _inherits2["default"])(GLTFCubicSplineInterpolant, _Interpolant); var _super3 = _createSuper(GLTFCubicSplineInterpolant); function GLTFCubicSplineInterpolant(parameterPositions, sampleValues, sampleSize, resultBuffer) { (0, _classCallCheck2["default"])(this, GLTFCubicSplineInterpolant); return _super3.call(this, parameterPositions, sampleValues, sampleSize, resultBuffer); } (0, _createClass2["default"])(GLTFCubicSplineInterpolant, [{ key: "copySampleValue_", value: function copySampleValue_(index) { // Copies a sample value to the result buffer. See description of glTF // CUBICSPLINE values layout in interpolate_() function below. var result = this.resultBuffer, values = this.sampleValues, valueSize = this.valueSize; for (var i = 0; i !== valueSize; i++) { result[i] = values[index * valueSize * 3 + valueSize + i]; } return result; } }]); return GLTFCubicSplineInterpolant; }(_three.Interpolant); GLTFCubicSplineInterpolant.prototype.beforeStart_ = GLTFCubicSplineInterpolant.prototype.copySampleValue_; GLTFCubicSplineInterpolant.prototype.afterEnd_ = GLTFCubicSplineInterpolant.prototype.copySampleValue_; GLTFCubicSplineInterpolant.prototype.interpolate_ = function (i1, t0, t, t1) { var result = this.resultBuffer; var values = this.sampleValues; var stride = this.valueSize; var stride3 = stride * 3; var td = t1 - t0; var p = (t - t0) / td; var pp = p * p; var ppp = pp * p; var offset1 = i1 * stride3; var offset0 = offset1 - stride3; var s2 = -2 * ppp + 3 * pp; var s3 = ppp - pp; // Layout of keyframe output values for CUBICSPLINE animations: // [ inTangent_1, splineVertex_1, outTangent_1, inTangent_2, splineVertex_2, ... ] for (var i = 0; i !== stride; i++) { var p0 = values[offset0 + i + stride]; // splineVertex_k var m0 = values[offset0 + i + stride * 2] * td; // outTangent_k * (t_k+1 - t_k) var p1 = values[offset1 + i + stride]; // splineVertex_k+1 var m1 = values[offset1 + i] * td; // inTangent_k+1 * (t_k+1 - t_k) result[i] = (1 - s2) * p0 + (s3 - pp + p) * m0 + s2 * p1 + s3 * m1; } return result; }; /*********************************/ /********** INTERNALS ************/ /*********************************/ /* CONSTANTS */ var WEBGL_CONSTANTS = { FLOAT: 5126, //FLOAT_MAT2: 35674, 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 }; var WEBGL_COMPONENT_TYPES = { 5120: Int8Array, 5121: Uint8Array, 5122: Int16Array, 5123: Uint16Array, 5125: Uint32Array, 5126: Float32Array }; var WEBGL_FILTERS = { 9728: _three.NearestFilter, 9729: _three.LinearFilter, 9984: _three.NearestMipmapNearestFilter, 9985: _three.LinearMipmapNearestFilter, 9986: _three.NearestMipmapLinearFilter, 9987: _three.LinearMipmapLinearFilter }; var WEBGL_WRAPPINGS = { 33071: _three.ClampToEdgeWrapping, 33648: _three.MirroredRepeatWrapping, 10497: _three.RepeatWrapp