three
Version:
JavaScript 3D library
1,968 lines (1,257 loc) • 105 kB
JavaScript
( function () {
class GLTFLoader extends THREE.Loader {
constructor( manager ) {
super( 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 GLTFMaterialsSheenExtension( 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 );
} );
}
load( url, onLoad, onProgress, onError ) {
const scope = this;
let 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 );
const _onError = function ( e ) {
if ( onError ) {
onError( e );
} else {
console.error( e );
}
scope.manager.itemError( url );
scope.manager.itemEnd( url );
};
const 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 );
}
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 = {};
if ( typeof data === 'string' ) {
content = data;
} else {
const 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 ) );
}
}
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; // 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 ( 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();
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 );
}
parseAsync( data, path ) {
const scope = this;
return new Promise( function ( resolve, reject ) {
scope.parse( data, path, resolve, reject );
} );
}
}
/* GLTFREGISTRY */
function GLTFRegistry() {
let objects = {};
return {
get: function ( key ) {
return objects[ key ];
},
add: function ( key, object ) {
objects[ key ] = object;
},
remove: function ( key ) {
delete objects[ key ];
},
removeAll: function () {
objects = {};
}
};
}
/*********************************/
/********** EXTENSIONS ***********/
/*********************************/
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_PBR_SPECULAR_GLOSSINESS: 'KHR_materials_pbrSpecularGlossiness',
KHR_MATERIALS_SHEEN: 'KHR_materials_sheen',
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
*/
class GLTFLightsExtension {
constructor( parser ) {
this.parser = parser;
this.name = EXTENSIONS.KHR_LIGHTS_PUNCTUAL; // THREE.Object3D instance caches
this.cache = {
refs: {},
uses: {}
};
}
_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.fromArray( lightDef.color );
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; // 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;
}
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 );
} );
}
}
/**
* Unlit Materials Extension
*
* Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_unlit
*/
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.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
*/
class GLTFMaterialsClearcoatExtension {
constructor( parser ) {
this.parser = parser;
this.name = EXTENSIONS.KHR_MATERIALS_CLEARCOAT;
}
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 );
}
}
/**
* Sheen Materials Extension
*
* Specification: https://github.com/KhronosGroup/glTF/tree/main/extensions/2.0/Khronos/KHR_materials_sheen
*/
class GLTFMaterialsSheenExtension {
constructor( parser ) {
this.parser = parser;
this.name = EXTENSIONS.KHR_MATERIALS_SHEEN;
}
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 ) {
materialParams.sheenColor.fromArray( extension.sheenColorFactor );
}
if ( extension.sheenRoughnessFactor !== undefined ) {
materialParams.sheenRoughness = extension.sheenRoughnessFactor;
}
if ( extension.sheenColorTexture !== undefined ) {
pending.push( parser.assignTexture( materialParams, 'sheenColorMap', extension.sheenColorTexture ) );
}
if ( extension.sheenRoughnessTexture !== undefined ) {
pending.push( parser.assignTexture( materialParams, 'sheenRoughnessMap', extension.sheenRoughnessTexture ) );
}
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
*/
class GLTFMaterialsTransmissionExtension {
constructor( parser ) {
this.parser = parser;
this.name = EXTENSIONS.KHR_MATERIALS_TRANSMISSION;
}
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 );
}
}
/**
* Materials Volume Extension
*
* Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_volume
*/
class GLTFMaterialsVolumeExtension {
constructor( parser ) {
this.parser = parser;
this.name = EXTENSIONS.KHR_MATERIALS_VOLUME;
}
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( colorArray[ 0 ], colorArray[ 1 ], colorArray[ 2 ] );
return Promise.all( pending );
}
}
/**
* Materials ior Extension
*
* Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_ior
*/
class GLTFMaterialsIorExtension {
constructor( parser ) {
this.parser = parser;
this.name = EXTENSIONS.KHR_MATERIALS_IOR;
}
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();
}
}
/**
* Materials specular Extension
*
* Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_specular
*/
class GLTFMaterialsSpecularExtension {
constructor( parser ) {
this.parser = parser;
this.name = EXTENSIONS.KHR_MATERIALS_SPECULAR;
}
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( colorArray[ 0 ], colorArray[ 1 ], colorArray[ 2 ] );
if ( extension.specularColorTexture !== undefined ) {
pending.push( parser.assignTexture( materialParams, 'specularColorMap', extension.specularColorTexture ).then( function ( texture ) {
texture.encoding = THREE.sRGBEncoding;
} ) );
}
return Promise.all( pending );
}
}
/**
* BasisU THREE.Texture Extension
*
* Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_texture_basisu
*/
class GLTFTextureBasisUExtension {
constructor( parser ) {
this.parser = parser;
this.name = EXTENSIONS.KHR_TEXTURE_BASISU;
}
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 {
// Assumes that the extension is optional and that a fallback texture is present
return null;
}
}
return parser.loadTextureImage( textureIndex, extension.source, loader );
}
}
/**
* WebP THREE.Texture Extension
*
* Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/EXT_texture_webp
*/
class GLTFTextureWebPExtension {
constructor( parser ) {
this.parser = parser;
this.name = EXTENSIONS.EXT_TEXTURE_WEBP;
this.isSupported = null;
}
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, 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 );
} );
}
detectSupport() {
if ( ! this.isSupported ) {
this.isSupported = new Promise( function ( resolve ) {
const 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;
}
}
/**
* meshopt BufferView Compression Extension
*
* Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/EXT_meshopt_compression
*/
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 {
// Assumes that the extension is optional and that fallback buffer data is present
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;
}
}
}
/* BINARY EXTENSION */
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 );
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.' );
}
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 = THREE.LoaderUtils.decodeText( contentArray );
} else if ( chunkType === BINARY_EXTENSION_CHUNK_TYPES.BIN ) {
const 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 THREE.Mesh Compression Extension
*
* Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_draco_mesh_compression
*/
class GLTFDracoMeshCompressionExtension {
constructor( 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();
}
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;
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 );
} );
} );
}
}
/**
* THREE.Texture Transform Extension
*
* Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_texture_transform
*/
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 ) {
// 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;
}
}
/**
* Specular-Glossiness Extension
*
* Specification: https://github.com/KhronosGroup/glTF/tree/main/extensions/2.0/Archived/KHR_materials_pbrSpecularGlossiness
*/
/**
* A sub class of StandardMaterial with some of the functionality
* changed via the `onBeforeCompile` callback
* @pailhead
*/
class GLTFMeshStandardSGMaterial extends THREE.MeshStandardMaterial {
constructor( params ) {
super();
this.isGLTFSpecularGlossinessMaterial = true; //various chunks that need replacing
const specularMapParsFragmentChunk = [ '#ifdef USE_SPECULARMAP', ' uniform sampler2D specularMap;', '#endif' ].join( '\n' );
const glossinessMapParsFragmentChunk = [ '#ifdef USE_GLOSSINESSMAP', ' uniform sampler2D glossinessMap;', '#endif' ].join( '\n' );
const specularMapFragmentChunk = [ 'vec3 specularFactor = specular;', '#ifdef USE_SPECULARMAP', ' vec4 texelSpecular = texture2D( specularMap, vUv );', ' // reads channel RGB, compatible with a glTF Specular-Glossiness (RGBA) texture', ' specularFactor *= texelSpecular.rgb;', '#endif' ].join( '\n' );
const 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' );
const 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.roughness = max( 1.0 - glossinessFactor, 0.0525 ); // 0.0525 corresponds to the base mip of a 256 cubemap.', 'material.roughness += geometryRoughness;', 'material.roughness = min( material.roughness, 1.0 );', 'material.specularColor = specularFactor;' ].join( '\n' );
const uniforms = {
specular: {
value: new THREE.Color().setHex( 0xffffff )
},
glossiness: {
value: 1
},
specularMap: {
value: null
},
glossinessMap: {
value: null
}
};
this._extraUniforms = uniforms;
this.onBeforeCompile = function ( shader ) {
for ( const 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( this, {
specular: {
get: function () {
return uniforms.specular.value;
},
set: function ( v ) {
uniforms.specular.value = v;
}
},
specularMap: {
get: function () {
return uniforms.specularMap.value;
},
set: function ( 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 () {
return uniforms.glossiness.value;
},
set: function ( v ) {
uniforms.glossiness.value = v;
}
},
glossinessMap: {
get: function () {
return uniforms.glossinessMap.value;
},
set: function ( 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 this.metalness;
delete this.roughness;
delete this.metalnessMap;
delete this.roughnessMap;
this.setValues( params );
}
copy( source ) {
super.copy( 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;
}
}
class GLTFMaterialsPbrSpecularGlossinessExtension {
constructor() {
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' ];
}
getMaterialType() {
return GLTFMeshStandardSGMaterial;
}
extendParams( materialParams, materialDef, parser ) {
const pbrSpecularGlossiness = materialDef.extensions[ this.name ];
materialParams.color = new THREE.Color( 1.0, 1.0, 1.0 );
materialParams.opacity = 1.0;
const pending = [];
if ( Array.isArray( pbrSpecularGlossiness.diffuseFactor ) ) {
const 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 ) {
const specGlossMapDef = pbrSpecularGlossiness.specularGlossinessTexture;
pending.push( parser.assignTexture( materialParams, 'glossinessMap', specGlossMapDef ) );
pending.push( parser.assignTexture( materialParams, 'specularMap', specGlossMapDef ) );
}
return Promise.all( pending );
}
createMaterial( materialParams ) {
const 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;
}
}
/**
* THREE.Mesh Quantization Extension
*
* Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_mesh_quantization
*/
class GLTFMeshQuantizationExtension {
constructor() {
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
class GLTFCubicSplineInterpolant extends THREE.Interpolant {
constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
super( parameterPositions, sampleValues, sampleSize, resultBuffer );
}
copySampleValue_( index ) {
// Copies a sample value to the result buffer. See description of glTF
// CUBICSPLINE values layout in interpolate_() function below.
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;
}
}
GLTFCubicSplineInterpolant.prototype.beforeStart_ = GLTFCubicSplineInterpolant.prototype.copySampleValue_;
GLTFCubicSplineInterpolant.prototype.afterEnd_ = GLTFCubicSplineInterpolant.prototype.copySampleValue_;
GLTFCubicSplineInterpolant.prototype.interpolate_ = function ( 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; // Layout of keyframe output values for CUBICSPLINE animations:
// [ inTangent_1, splineVertex_1, outTangent_1, inTangent_2, splineVertex_2, ... ]
for ( let i = 0; i !== stride; i ++ ) {
const p0 = values[ offset0 + i + stride ]; // splineVertex_k
const m0 = values[ offset0 + i + stride2 ] * td; // outTangent_k * (t_k+1 - t_k)
const p1 = values[ offset1 + i + stride ]; // splineVertex_k+1
const 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;
};
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;
}
}
/*********************************/
/********** INTERNALS ************/
/*********************************/
/* CONSTANTS */
const 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
};
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 = {
scale: 'scale',
translation: 'position',
rotation: 'quaternion',
weights: 'morphTargetInfluences'
};
const 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
};
const ALPHA_MODES = {
OPAQUE: 'OPAQUE',
MASK: 'MASK',
BLEND: 'BLEND'
};
/**
* 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 ( const name in objectDef.extensions ) {
if ( knownExtensions[ name ] === undefined ) {
object.userData.gltfExtensions = object.userData.gltfExtensions || {};
object.userData.gltfExtensions[ name ] = objectDef.extensions[ name ];
}
}
}
/**
* @param {Object3D|Material|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 {BufferGeometry} geometry
* @param {Array<GLTF.Target>} targets
* @param {GLTFParser} parser
* @return {Promise<BufferGeometry>}
*/
function addMorphTargets( geometry, targets, parser ) {
let hasMorphPosition = false;
let hasMorphNormal = false;
let hasMorphColor = 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 ( target.COLOR_0 !== undefined ) hasMorphColor = true;
if ( hasMorphPosition && hasMorphNormal && hasMorphColor ) break;
}
if ( ! hasMorphPosition && ! hasMorphNormal && ! hasMorphColor ) return Promise.resolve( geometry );
const pendingPositionAccessors = [];
const pendingNormalAccessors = [];
const pendingColorAccessors = [];
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 );
}
if ( hasMorphColor ) {
const pendingAccessor = target.COLOR_0 !== undefined ? parser.getDependency( 'accessor', target.COLOR_0 ) : geometry.attributes.color;
pendingColorAccessors.push( pendingAccessor );
}
}
return Promise.all( [ Promise.all( pendingPositionAccessors ), Promise.all( pendingNormalAccessors ), Promise.all( pendingColorAccessors ) ] ).then( function ( accessors ) {
const morphPositions = accessors[ 0 ];
const morphNormals = accessors[ 1 ];
const morphColors = accessors[ 2 ];
if ( hasMorphPosition ) geometry.morphAttributes.position = morphPositions;
if ( hasMorphNormal ) geometry.morphAttributes.normal = morphNormals;
if ( hasMorphColor ) geometry.morphAttributes.color = morphColors;
geometry.morphTargetsRelative = true;
return geometry;
} );
}
/**
* @param {Mesh} mesh
* @param {GLTF.Mesh} meshDef
*/
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 ];
}
} // .extras has user-defined data, so check that .extras.targetNames is an array.
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 ] ] = i;
}
} else {
console.warn( 'THREE.GLTFLoader: Invalid extras.targetNames length. Ignoring names.' );
}
}
}
function createPrimitiveKey( primitiveDef ) {
const dracoExtension = primitiveDef.extensions && primitiveDef.extensions[ EXTENSIONS.KHR_DRACO_MESH_COMPRESSION ];
let 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 ) {
let attributesKey = '';
const keys = Object.keys( attributes ).sort();
for ( let i = 0, il = keys.length; i < il; i ++ ) {
attributesKey += keys[ i ] + ':' + attributes[ keys[ i ] ] + ';';
}
return attributesKey;
}
function getNormalizedComponentScale( constructor ) {
// Reference:
// https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_mesh_quantization#encoding-quantized-data
switch ( constructor ) {
case Int8Array:
return 1 /