UNPKG

bytev-charts

Version:

基于echarts和JavaScript及ES6封装的一个可以直接调用的图表组件库,内置主题设计,简单快捷,且支持用户自定义配置; npm 安装方式: npm install bytev-charts 若启动提示还需额外install插件,则运行 npm install @babel/runtime-corejs2 即可;

1,397 lines (1,162 loc) 97 kB
import _typeof from "@babel/runtime-corejs2/helpers/typeof"; import "core-js/modules/es.array.index-of.js"; import "core-js/modules/es.array.splice.js"; import "core-js/modules/es.array.iterator.js"; import "core-js/modules/es.array-buffer.slice.js"; import "core-js/modules/es.object.to-string.js"; import "core-js/modules/es.typed-array.uint8-array.js"; import "core-js/modules/es.typed-array.copy-within.js"; import "core-js/modules/es.typed-array.every.js"; import "core-js/modules/es.typed-array.fill.js"; import "core-js/modules/es.typed-array.filter.js"; import "core-js/modules/es.typed-array.find.js"; import "core-js/modules/es.typed-array.find-index.js"; import "core-js/modules/es.typed-array.for-each.js"; import "core-js/modules/es.typed-array.includes.js"; import "core-js/modules/es.typed-array.index-of.js"; import "core-js/modules/es.typed-array.iterator.js"; import "core-js/modules/es.typed-array.join.js"; import "core-js/modules/es.typed-array.last-index-of.js"; import "core-js/modules/es.typed-array.map.js"; import "core-js/modules/es.typed-array.reduce.js"; import "core-js/modules/es.typed-array.reduce-right.js"; import "core-js/modules/es.typed-array.reverse.js"; import "core-js/modules/es.typed-array.set.js"; import "core-js/modules/es.typed-array.slice.js"; import "core-js/modules/es.typed-array.some.js"; import "core-js/modules/es.typed-array.sort.js"; import "core-js/modules/es.typed-array.subarray.js"; import "core-js/modules/es.typed-array.to-locale-string.js"; import "core-js/modules/es.typed-array.to-string.js"; import "core-js/modules/es.function.name.js"; import "core-js/modules/es.promise.js"; import "core-js/modules/es.string.iterator.js"; import "core-js/modules/web.dom-collections.iterator.js"; import "core-js/modules/es.data-view.js"; import "core-js/modules/es.array.slice.js"; import "core-js/modules/es.string.repeat.js"; import "core-js/modules/es.array.join.js"; import "core-js/modules/es.regexp.exec.js"; import "core-js/modules/es.string.replace.js"; import "core-js/modules/es.array.map.js"; import "core-js/modules/es.typed-array.int8-array.js"; import "core-js/modules/es.typed-array.int16-array.js"; import "core-js/modules/es.typed-array.uint16-array.js"; import "core-js/modules/es.typed-array.uint32-array.js"; import "core-js/modules/es.typed-array.float32-array.js"; import "core-js/modules/es.array.sort.js"; import "core-js/modules/web.url.js"; import "core-js/modules/web.url-search-params.js"; import "core-js/modules/es.function.bind.js"; import _Object$assign from "@babel/runtime-corejs2/core-js/object/assign"; import _Object$create from "@babel/runtime-corejs2/core-js/object/create"; import _Promise from "@babel/runtime-corejs2/core-js/promise"; import _Array$isArray from "@babel/runtime-corejs2/core-js/array/is-array"; import _Object$defineProperties from "@babel/runtime-corejs2/core-js/object/define-properties"; import _Object$keys from "@babel/runtime-corejs2/core-js/object/keys"; import _Map from "@babel/runtime-corejs2/core-js/map"; import _Object$values from "@babel/runtime-corejs2/core-js/object/values"; console.warn("THREE.GLTFLoader: As part of the transition to ES6 Modules, the files in 'examples/js' were deprecated in May 2020 (r117) and will be deleted in December 2020 (r124). You can find more information about developing using ES6 Modules in https://threejs.org/docs/#manual/en/introduction/Installation."); THREE.GLTFLoader = function () { function GLTFLoader(manager) { THREE.Loader.call(this, manager); this.dracoLoader = null; this.ddsLoader = null; this.ktx2Loader = 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 GLTFMaterialsTransmissionExtension(parser); }); } GLTFLoader.prototype = _Object$assign(_Object$create(THREE.Loader.prototype), { constructor: GLTFLoader, load: 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. scope.manager.itemStart(url); var _onError = function _onError(e) { if (onError) { onError(e); } else { console.error(e); } scope.manager.itemError(url); scope.manager.itemEnd(url); }; var loader = new THREE.FileLoader(scope.manager); loader.setPath(this.path); loader.setResponseType('arraybuffer'); loader.setRequestHeader(this.requestHeader); if (scope.crossOrigin === 'use-credentials') { loader.setWithCredentials(true); } 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); }, setDRACOLoader: function setDRACOLoader(dracoLoader) { this.dracoLoader = dracoLoader; return this; }, setDDSLoader: function setDDSLoader(ddsLoader) { this.ddsLoader = ddsLoader; return this; }, setKTX2Loader: function setKTX2Loader(ktx2Loader) { this.ktx2Loader = ktx2Loader; return this; }, register: function register(callback) { if (this.pluginCallbacks.indexOf(callback) === -1) { this.pluginCallbacks.push(callback); } return this; }, unregister: function unregister(callback) { if (this.pluginCallbacks.indexOf(callback) !== -1) { this.pluginCallbacks.splice(this.pluginCallbacks.indexOf(callback), 1); } return this; }, parse: 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, manager: this.manager, ktx2Loader: this.ktx2Loader }); 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_LIGHTS_PUNCTUAL: extensions[extensionName] = new GLTFLightsExtension(json); break; 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.MSFT_TEXTURE_DDS: extensions[extensionName] = new GLTFTextureDDSExtension(this.ddsLoader); 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); } }); /* GLTFREGISTRY */ 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_PBR_SPECULAR_GLOSSINESS: 'KHR_materials_pbrSpecularGlossiness', KHR_MATERIALS_TRANSMISSION: 'KHR_materials_transmission', KHR_MATERIALS_UNLIT: 'KHR_materials_unlit', KHR_TEXTURE_BASISU: 'KHR_texture_basisu', KHR_TEXTURE_TRANSFORM: 'KHR_texture_transform', KHR_MESH_QUANTIZATION: 'KHR_mesh_quantization', MSFT_TEXTURE_DDS: 'MSFT_texture_dds' }; /** * DDS Texture Extension * * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/MSFT_texture_dds * */ function GLTFTextureDDSExtension(ddsLoader) { if (!ddsLoader) { throw new Error('THREE.GLTFLoader: Attempting to load .dds texture without importing THREE.DDSLoader'); } this.name = EXTENSIONS.MSFT_TEXTURE_DDS; this.ddsLoader = ddsLoader; } /** * Punctual Lights Extension * * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_lights_punctual */ function GLTFLightsExtension(json) { this.name = EXTENSIONS.KHR_LIGHTS_PUNCTUAL; var extension = json.extensions && json.extensions[EXTENSIONS.KHR_LIGHTS_PUNCTUAL] || {}; this.lightDefs = extension.lights || []; } GLTFLightsExtension.prototype.loadLight = function (lightIndex) { var lightDef = this.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 = lightDef.name || 'light_' + lightIndex; return _Promise.resolve(lightNode); }; /** * Unlit Materials Extension * * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_unlit */ function GLTFMaterialsUnlitExtension() { this.name = EXTENSIONS.KHR_MATERIALS_UNLIT; } GLTFMaterialsUnlitExtension.prototype.getMaterialType = function () { return THREE.MeshBasicMaterial; }; GLTFMaterialsUnlitExtension.prototype.extendParams = function (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); }; /** * Clearcoat Materials Extension * * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_clearcoat */ function GLTFMaterialsClearcoatExtension(parser) { this.parser = parser; this.name = EXTENSIONS.KHR_MATERIALS_CLEARCOAT; } GLTFMaterialsClearcoatExtension.prototype.getMaterialType = function (materialIndex) { var parser = this.parser; var materialDef = parser.json.materials[materialIndex]; if (!materialDef.extensions || !materialDef.extensions[this.name]) return null; return THREE.MeshPhysicalMaterial; }; GLTFMaterialsClearcoatExtension.prototype.extendMaterialParams = function (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; materialParams.clearcoatNormalScale = new THREE.Vector2(scale, scale); } } return _Promise.all(pending); }; /** * 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 */ function GLTFMaterialsTransmissionExtension(parser) { this.parser = parser; this.name = EXTENSIONS.KHR_MATERIALS_TRANSMISSION; } GLTFMaterialsTransmissionExtension.prototype.getMaterialType = function (materialIndex) { var parser = this.parser; var materialDef = parser.json.materials[materialIndex]; if (!materialDef.extensions || !materialDef.extensions[this.name]) return null; return THREE.MeshPhysicalMaterial; }; GLTFMaterialsTransmissionExtension.prototype.extendMaterialParams = function (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); }; /** * BasisU Texture Extension * * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_texture_basisu * (draft PR https://github.com/KhronosGroup/glTF/pull/1751) */ function GLTFTextureBasisUExtension(parser) { this.parser = parser; this.name = EXTENSIONS.KHR_TEXTURE_BASISU; } GLTFTextureBasisUExtension.prototype.loadTexture = function (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) { throw new Error('THREE.GLTFLoader: setKTX2Loader must be called before loading KTX2 textures'); } return parser.loadTextureImage(textureIndex, source, loader); }; /* BINARY EXTENSION */ var BINARY_EXTENSION_HEADER_MAGIC = 'glTF'; var BINARY_EXTENSION_HEADER_LENGTH = 12; var BINARY_EXTENSION_CHUNK_TYPES = { JSON: 0x4E4F534A, BIN: 0x004E4942 }; function GLTFBinaryExtension(data) { 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 chunkView = new DataView(data, BINARY_EXTENSION_HEADER_LENGTH); var chunkIndex = 0; while (chunkIndex < chunkView.byteLength) { 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 */ function GLTFDracoMeshCompressionExtension(json, dracoLoader) { 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(); } GLTFDracoMeshCompressionExtension.prototype.decodePrimitive = function (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 (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 attributeName in geometry.attributes) { var attribute = geometry.attributes[attributeName]; var normalized = attributeNormalizedMap[attributeName]; if (normalized !== undefined) attribute.normalized = normalized; } resolve(geometry); }, threeAttributeMap, attributeTypeMap); }); }); }; /** * Texture Transform Extension * * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_texture_transform */ function GLTFTextureTransformExtension() { this.name = EXTENSIONS.KHR_TEXTURE_TRANSFORM; } GLTFTextureTransformExtension.prototype.extendTexture = function (texture, transform) { 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); } if (transform.texCoord !== undefined) { console.warn('THREE.GLTFLoader: Custom UV sets in "' + this.name + '" extension not yet supported.'); } texture.needsUpdate = true; return texture; }; /** * Specular-Glossiness Extension * * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_pbrSpecularGlossiness */ /** * A sub class of THREE.StandardMaterial with some of the functionality * changed via the `onBeforeCompile` callback * @pailhead */ function GLTFMeshStandardSGMaterial(params) { THREE.MeshStandardMaterial.call(this); this.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;', '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.rgb;'].join('\n'); var uniforms = { specular: { value: new THREE.Color().setHex(0xffffff) }, glossiness: { value: 1 }, specularMap: { value: null }, glossinessMap: { value: null } }; this._extraUniforms = uniforms; // please see #14031 or #13198 for an alternate approach this.onBeforeCompile = function (shader) { for (var uniformName in uniforms) { shader.uniforms[uniformName] = uniforms[uniformName]; } shader.fragmentShader = shader.fragmentShader.replace('uniform float roughness;', 'uniform vec3 specular;'); shader.fragmentShader = shader.fragmentShader.replace('uniform float metalness;', 'uniform float glossiness;'); shader.fragmentShader = shader.fragmentShader.replace('#include <roughnessmap_pars_fragment>', specularMapParsFragmentChunk); shader.fragmentShader = shader.fragmentShader.replace('#include <metalnessmap_pars_fragment>', glossinessMapParsFragmentChunk); shader.fragmentShader = shader.fragmentShader.replace('#include <roughnessmap_fragment>', specularMapFragmentChunk); shader.fragmentShader = shader.fragmentShader.replace('#include <metalnessmap_fragment>', glossinessMapFragmentChunk); shader.fragmentShader = shader.fragmentShader.replace('#include <lights_physical_fragment>', lightPhysicalFragmentChunk); }; /*eslint-disable*/ _Object$defineProperties(this, { 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; } }, 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; //how about something like this - @pailhead if (v) { this.defines.USE_GLOSSINESSMAP = ''; // set USE_ROUGHNESSMAP to enable vUv this.defines.USE_ROUGHNESSMAP = ''; } else { delete this.defines.USE_ROUGHNESSMAP; delete this.defines.USE_GLOSSINESSMAP; } } } }); /*eslint-enable*/ delete this.metalness; delete this.roughness; delete this.metalnessMap; delete this.roughnessMap; this.setValues(params); } GLTFMeshStandardSGMaterial.prototype = _Object$create(THREE.MeshStandardMaterial.prototype); GLTFMeshStandardSGMaterial.prototype.constructor = GLTFMeshStandardSGMaterial; GLTFMeshStandardSGMaterial.prototype.copy = function (source) { THREE.MeshStandardMaterial.prototype.copy.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; }; function GLTFMaterialsPbrSpecularGlossinessExtension() { return { name: EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS, 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'], getMaterialType: function getMaterialType() { return GLTFMeshStandardSGMaterial; }, extendParams: 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); }, createMaterial: 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; } }; } /** * Mesh Quantization Extension * * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_mesh_quantization */ function 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 function GLTFCubicSplineInterpolant(parameterPositions, sampleValues, sampleSize, resultBuffer) { THREE.Interpolant.call(this, parameterPositions, sampleValues, sampleSize, resultBuffer); } GLTFCubicSplineInterpolant.prototype = _Object$create(THREE.Interpolant.prototype); GLTFCubicSplineInterpolant.prototype.constructor = GLTFCubicSplineInterpolant; GLTFCubicSplineInterpolant.prototype.copySampleValue_ = function (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, offset = index * valueSize * 3 + valueSize; for (var i = 0; i !== valueSize; i++) { result[i] = values[offset + i]; } return result; }; 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 stride2 = stride * 2; 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; var s0 = 1 - s2; var s1 = s3 - pp + p; // 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 + stride2] * 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] = s0 * p0 + s1 * 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.RepeatWrapping }; var WEBGL_TYPE_SIZES = { 'SCALAR': 1, 'VEC2': 2, 'VEC3': 3, 'VEC4': 4, 'MAT2': 4, 'MAT3': 9, 'MAT4': 16 }; var ATTRIBUTES = { POSITION: 'position', NORMAL: 'normal', TANGENT: 'tangent', TEXCOORD_0: 'uv', TEXCOORD_1: 'uv2', COLOR_0: 'color', WEIGHTS_0: 'skinWeight', JOINTS_0: 'skinIndex' }; var PATH_PROPERTIES = { scale: 'scale', translation: 'position', rotation: 'quaternion', weights: 'morphTargetInfluences' }; var INTERPOLATION = { CUBICSPLINE: undefined, // We use a custom interpolant (GLTFCubicSplineInterpolation) for CUBICSPLINE tracks. Each // keyframe track will be initialized with a default interpolation type, then modified. LINEAR: THREE.InterpolateLinear, STEP: THREE.InterpolateDiscrete }; var ALPHA_MODES = { OPAQUE: 'OPAQUE', MASK: 'MASK', BLEND: 'BLEND' }; /* UTILITY FUNCTIONS */ function resolveURL(url, path) { // Invalid URL if (typeof url !== 'string' || url === '') return ''; // Host Relative URL if (/^https?:\/\//i.test(path) && /^\//.test(url)) { path = path.replace(/(^https?:\/\/[^\/]+).*/i, '$1'); } // Absolute URL http://,https://,// if (/^(https?:)?\/\//i.test(url)) return url; // Data URI if (/^data:.*,.*$/i.test(url)) return url; // Blob URL if (/^blob:.*$/i.test(url)) return url; // Relative URL return path + url; } /** * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#default-material */ 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) { // Add unknown glTF extensions to an object's userData. for (var name in objectDef.extensions) { if (knownExtensions[name] === undefined) { object.userData.gltfExtensions = object.userData.gltfExtensions || {}; object.userData.gltfExtensions[name] = objectDef.extensions[name]; } } } /** * @param {THREE.Object3D|THREE.Material|THREE.BufferGeometry} object * @param {GLTF.definition} gltfDef */ 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); } } } /** * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#morph-targets * * @param {THREE.BufferGeometry} geometry * @param {Array<GLTF.Target>} targets * @param {GLTFParser} parser * @return {Promise<THREE.BufferGeometry>} */ function addMorphTargets(geometry, targets, parser) { var hasMorphPosition = false; var hasMorphNormal = false; for (var i = 0, il = targets.length; i < il; i++) { var 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); var pendingPositionAccessors = []; var pendingNormalAccessors = []; for (var i = 0, il = targets.length; i < il; i++) { var target = targets[i]; if (hasMorphPosition) { var pendingAccessor = target.POSITION !== undefined ? parser.getDependency('accessor', target.POSITION) : geometry.attributes.position; pendingPositionAccessors.push(pendingAccessor); } if (hasMorphNormal) { var 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(function (accessors) { var morphPositions = accessors[0]; var morphNormals = accessors[1]; if (hasMorphPosition) geometry.morphAttributes.position = morphPositions; if (hasMorphNormal) geometry.morphAttributes.normal = morphNormals; geometry.morphTargetsRelative = true; return geometry; }); } /** * @param {THREE.Mesh} mesh * @param {GLTF.Mesh} meshDef */ function updateMorphTargets(mesh, meshDef) { mesh.updateMorphTargets(); if (meshDef.weights !== undefined) { for (var i = 0, il = meshDef.weights.length; i < il; i++) { mesh.morphTargetInfluences[i] = meshDef.weights[i]; } } // .extras has user-defined data, so check that .extras.targetNames is an array. if (meshDef.extras && _Array$isArray(meshDef.extras.targetNames)) { var targetNames = meshDef.extras.targetNames; if (mesh.morphTargetInfluences.length === targetNames.length) { mesh.morphTargetDictionary = {}; for (var i = 0, il = targetNames.length; i < il; i++) { mesh.morphTargetDictionary[targetNames[i]] = i; } } else { console.warn('THREE.GLTFLoader: Invalid extras.targetNames length. Ignoring names.'); } } } function createPrimitiveKey(primitiveDef) { var dracoExtension = primitiveDef.extensions && primitiveDef.extensions[EXTENSIONS.KHR_DRACO_MESH_COMPRESSION]; var geometryKey; if (dracoExtension) { geometryKey = 'draco:' + dracoExtension.bufferView + ':' + dracoExtension.indices + ':' + createAttributesKey(dracoExtension.attributes); } else { geometryKey = primitiveDef.indices + ':' + createAttributesKey(primitiveDef.attributes) + ':' + primitiveDef.mode; } return geometryKey; } function createAttributesKey(attributes) { var attributesKey = ''; var keys = _Object$keys(attributes).sort(); for (var i = 0, il = keys.length; i < il; i++) { attributesKey += keys[i] + ':' + attributes[keys[i]] + ';'; } return attributesKey; } /* GLTF PARSER */ function GLTFParser(json, options) { this.json = json || {}; this.extensions = {}; this.plugins = {}; this.options = options || {}; // loader object cache this.cache = new GLTFRegistry(); // associations between Three.js objects and glTF elements this.associations = new _Map(); // BufferGeometry caching this.primitiveCache = {}; // Object3D instance caches this.meshCache = { refs: {}, uses: {} }; this.cameraCache = { refs: {}, uses: {} }; this.lightCache = { refs: {}, uses: {} }; // Use an ImageBitmapLoader if imageBitmaps are supported. Moves much of the // expensive work of uploading a texture to the GPU off the main thread. if (typeof createImageBitmap !== 'undefined' && /Firefox/.test(navigator.userAgent) === false) { this.textureLoader = new THREE.ImageBitmapLoader(this.options.manager); } else { this.textureLoader = new THREE.TextureLoader(this.options.manager); } this.textureLoader.setCrossOrigin(this.options.crossOrigin); this.fileLoader = new THREE.FileLoader(this.options.manager); this.fileLoader.setResponseType('arraybuffer'); if (this.options.crossOrigin === 'use-credentials') { this.fileLoader.setWithCredentials(true); } } GLTFParser.prototype.setExtensions = function (extensions) { this.extensions = extensions; }; GLTFParser.prototype.setPlugins = function (plugins) { this.plugins = plugins; }; GLTFParser.prototype.parse = function (onLoad, onError) { var parser = this; var json = this.json; var extensions = this.extensions; // Clear the loader cache this.cache.removeAll(); // Mark the special nodes/meshes in json for efficient parse this._markDefs(); _Promise.all([this.getDependencies('scene'), this.getDependencies('animation'), this.getDependencies('camera')]).then(function (dependencies) { var result = { scene: dependencies[0][json.scene || 0], scenes: dependencies[0], animations: dependencies[1], cameras: dependencies[2], asset: json.asset, parser: parser, userData: {} }; addUnknownExtensionsToUserData(extensions, result, json); assignExtrasToUserData(result, json); onLoad(result); })["catch"](onError); }; /** * Marks the special nodes/meshes in json for efficient parse. */ GLTFParser.prototype._markDefs = function () { var nodeDefs = this.json.nodes || []; var skinDefs = this.json.skins || []; var meshDefs = this.json.meshes || []; // Nothing in the node definition indicates whether it is a Bone or an // Object3D. Use the skins' joint references to mark bones. for (var skinIndex = 0, skinLength = skinDefs.length; skinIndex < skinLength; skinIndex++) { var joints = skinDefs[skinIndex].joints; for (var i = 0, il = joints.length; i < il; i++) { nodeDefs[joints[i]].isBone = true; } } // Iterate over all nodes, marking references to shared resources, // as well as skeleton joints. for (var nodeIndex = 0, nodeLength = nodeDefs.length; nodeIndex < nodeLength; nodeIndex++) { var nodeDef = nodeDefs[nodeIndex]; if (nodeDef.mesh !== undefined) { this._addNodeRef(this.meshCache, nodeDef.mesh); // Nothing in the mesh definition indicates whether it is // a SkinnedMesh or Mesh. Use the node's mesh reference // to mark SkinnedMesh if node has skin. if (nodeDef.skin !== undefined) { meshDefs[nodeDef.mesh].isSkinnedMesh = true; } } if (nodeDef.camera !== undefined) { this._addNodeRef(this.cameraCache, nodeDef.camera); } if (nodeDef.extensions && nodeDef.extensions[EXTENSIONS.KHR_LIGHTS_PUNCTUAL] && nodeDef.extensions[EXTENSIONS.KHR_LIGHTS_PUNCTUAL].light !== undefined) { this._addNodeRef(this.lightCache, nodeDef.extensions[EXTENSIONS.KHR_LIGHTS_PUNCTUAL].light); } } }; /** * Counts references to shared node / Object3D resources. These resources * can be reused, or "instantiated", at multiple nodes in the scene * hierarchy. Mesh, Camera, and Light instances are instantiated and must * be marked. Non-scenegraph resources (like Materials, Geometries, and * Textures) can be reused directly and are not marked here. * * Example: CesiumMilkTruck sample model reuses "Wheel" meshes. */ GLTFParser.prototype._addNodeRef = function (cache, index) { if (index === undefined) return; if (cache.refs[index] === undefined) { cache.refs[index] = cache.uses[index] = 0; } cache.refs[index]++; }; /** Returns a reference to a shared resource, cloning it if necessary. */ GLTFParser.prototype._getNodeRef = function (cache, index, object) { if (cache.refs[index] <= 1) return object; var ref = object.clone(); ref.name += '_instance_' + cache.uses[index]++; return ref; }; GLTFParser.prototype._invokeOne = function (func) { var extensions = _Object$values(this.plugins); extensions.push(this); for (var i = 0; i < extensions.length; i++) { var result = func(extensions[i]); if (result) return result; } }; GLTFParser.prototype._invokeAll = function (func) { var extensions = _Object$values(this.plugins); extensions.unshift(this); var pending = []; for (var i = 0; i < extensions.length; i++) { pending.push(func(extensions[i])); } return _Promise.all(pending); }; /** * Requests the specified dependency asynchronously, with caching. * @param {string} type * @param {number} index * @return {Promise<THREE.Object3D|THREE.Material|THREE.Texture|THREE.AnimationClip|ArrayBuffer|Object>} */ GLTFParser.prototype.getDependency = function (type, index) { var cacheKey = type + ':' + index; var dependency = this.cache.get(cacheKey); if (!dependency) { switch (type) { case 'scene': dependency = this.loadScene(index); break; case 'node': dependency = this.loadNode(index); break; case 'mesh': dependency = this._invokeOne(function (ext) { return ext.loadMesh && ext.loadMesh(index); }); break; case 'accessor': dependency = this.loadA