GLTF2Loader.js 56 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454
  1. /**
  2. * @author Rich Tibbett / https://github.com/richtr
  3. * @author mrdoob / http://mrdoob.com/
  4. * @author Tony Parisi / http://www.tonyparisi.com/
  5. * @author Takahiro / https://github.com/takahirox
  6. * @author Don McCurdy / https://www.donmccurdy.com
  7. */
  8. THREE.GLTF2Loader = ( function () {
  9. function GLTF2Loader( manager ) {
  10. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  11. }
  12. GLTF2Loader.prototype = {
  13. constructor: GLTF2Loader,
  14. crossOrigin: 'Anonymous',
  15. load: function ( url, onLoad, onProgress, onError ) {
  16. var scope = this;
  17. var path = this.path && ( typeof this.path === 'string' ) ? this.path : THREE.Loader.prototype.extractUrlBase( url );
  18. var loader = new THREE.FileLoader( scope.manager );
  19. loader.setResponseType( 'arraybuffer' );
  20. loader.load( url, function ( data ) {
  21. try {
  22. scope.parse( data, path, onLoad, onError );
  23. } catch ( e ) {
  24. // For SyntaxError or TypeError, return a generic failure message.
  25. onError( e.constructor === Error ? e : new Error( 'THREE.GLTF2Loader: Unable to parse model.' ) );
  26. }
  27. }, onProgress, onError );
  28. },
  29. setCrossOrigin: function ( value ) {
  30. this.crossOrigin = value;
  31. },
  32. setPath: function ( value ) {
  33. this.path = value;
  34. },
  35. parse: function ( data, path, onLoad, onError ) {
  36. var content;
  37. var extensions = {};
  38. var magic = convertUint8ArrayToString( new Uint8Array( data, 0, 4 ) );
  39. if ( magic === BINARY_EXTENSION_HEADER_MAGIC ) {
  40. extensions[ EXTENSIONS.KHR_BINARY_GLTF ] = new GLTFBinaryExtension( data );
  41. content = extensions[ EXTENSIONS.KHR_BINARY_GLTF ].content;
  42. } else {
  43. content = convertUint8ArrayToString( new Uint8Array( data ) );
  44. }
  45. var json = JSON.parse( content );
  46. if ( json.asset.version[0] < 2 ) {
  47. onError( new Error( 'THREE.GLTF2Loader: Legacy glTF detected. Use THREE.GLTFLoader instead.' ) );
  48. return;
  49. }
  50. if ( json.extensionsUsed ) {
  51. if( json.extensionsUsed.indexOf( EXTENSIONS.KHR_LIGHTS ) >= 0 ) {
  52. extensions[ EXTENSIONS.KHR_LIGHTS ] = new GLTFLightsExtension( json );
  53. }
  54. if( json.extensionsUsed.indexOf( EXTENSIONS.KHR_MATERIALS_COMMON ) >= 0 ) {
  55. extensions[ EXTENSIONS.KHR_MATERIALS_COMMON ] = new GLTFMaterialsCommonExtension( json );
  56. }
  57. if( json.extensionsUsed.indexOf( EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ) >= 0 ) {
  58. extensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ] = new GLTFMaterialsPbrSpecularGlossinessExtension();
  59. }
  60. }
  61. console.time( 'GLTF2Loader' );
  62. var parser = new GLTFParser( json, extensions, {
  63. path: path || this.path,
  64. crossOrigin: this.crossOrigin
  65. } );
  66. parser.parse( function ( scene, scenes, cameras, animations ) {
  67. console.timeEnd( 'GLTF2Loader' );
  68. var glTF = {
  69. scene: scene,
  70. scenes: scenes,
  71. cameras: cameras,
  72. animations: animations
  73. };
  74. onLoad( glTF );
  75. }, onError );
  76. }
  77. };
  78. /* GLTFREGISTRY */
  79. function GLTFRegistry() {
  80. var objects = {};
  81. return {
  82. get: function ( key ) {
  83. return objects[ key ];
  84. },
  85. add: function ( key, object ) {
  86. objects[ key ] = object;
  87. },
  88. remove: function ( key ) {
  89. delete objects[ key ];
  90. },
  91. removeAll: function () {
  92. objects = {};
  93. },
  94. update: function ( scene, camera ) {
  95. for ( var name in objects ) {
  96. var object = objects[ name ];
  97. if ( object.update ) {
  98. object.update( scene, camera );
  99. }
  100. }
  101. }
  102. };
  103. }
  104. /*********************************/
  105. /********** EXTENSIONS ***********/
  106. /*********************************/
  107. var EXTENSIONS = {
  108. KHR_BINARY_GLTF: 'KHR_binary_glTF',
  109. KHR_LIGHTS: 'KHR_lights',
  110. KHR_MATERIALS_COMMON: 'KHR_materials_common',
  111. KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS: 'KHR_materials_pbrSpecularGlossiness',
  112. KHR_TECHNIQUE_WEBGL: 'KHR_technique_webgl',
  113. };
  114. /**
  115. * Lights Extension
  116. *
  117. * Specification: PENDING
  118. */
  119. function GLTFLightsExtension( json ) {
  120. this.name = EXTENSIONS.KHR_LIGHTS;
  121. this.lights = {};
  122. var extension = ( json.extensions && json.extensions[ EXTENSIONS.KHR_LIGHTS ] ) || {};
  123. var lights = extension.lights || {};
  124. for ( var lightId in lights ) {
  125. var light = lights[ lightId ];
  126. var lightNode;
  127. var color = new THREE.Color().fromArray( light.color );
  128. switch ( light.type ) {
  129. case 'directional':
  130. lightNode = new THREE.DirectionalLight( color );
  131. lightNode.position.set( 0, 0, 1 );
  132. break;
  133. case 'point':
  134. lightNode = new THREE.PointLight( color );
  135. break;
  136. case 'spot':
  137. lightNode = new THREE.SpotLight( color );
  138. lightNode.position.set( 0, 0, 1 );
  139. break;
  140. case 'ambient':
  141. lightNode = new THREE.AmbientLight( color );
  142. break;
  143. }
  144. if ( lightNode ) {
  145. if ( light.constantAttenuation !== undefined ) {
  146. lightNode.intensity = light.constantAttenuation;
  147. }
  148. if ( light.linearAttenuation !== undefined ) {
  149. lightNode.distance = 1 / light.linearAttenuation;
  150. }
  151. if ( light.quadraticAttenuation !== undefined ) {
  152. lightNode.decay = light.quadraticAttenuation;
  153. }
  154. if ( light.fallOffAngle !== undefined ) {
  155. lightNode.angle = light.fallOffAngle;
  156. }
  157. if ( light.fallOffExponent !== undefined ) {
  158. console.warn( 'THREE.GLTF2Loader:: light.fallOffExponent not currently supported.' );
  159. }
  160. lightNode.name = light.name || ( 'light_' + lightId );
  161. this.lights[ lightId ] = lightNode;
  162. }
  163. }
  164. }
  165. /**
  166. * Common Materials Extension
  167. *
  168. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/Khronos/KHR_materials_common
  169. */
  170. function GLTFMaterialsCommonExtension( json ) {
  171. this.name = EXTENSIONS.KHR_MATERIALS_COMMON;
  172. }
  173. GLTFMaterialsCommonExtension.prototype.getMaterialType = function ( material ) {
  174. var khrMaterial = material.extensions[ this.name ];
  175. switch ( khrMaterial.type ) {
  176. case 'commonBlinn' :
  177. case 'commonPhong' :
  178. return THREE.MeshPhongMaterial;
  179. case 'commonLambert' :
  180. return THREE.MeshLambertMaterial;
  181. case 'commonConstant' :
  182. default :
  183. return THREE.MeshBasicMaterial;
  184. }
  185. };
  186. GLTFMaterialsCommonExtension.prototype.extendParams = function ( materialParams, material, parser ) {
  187. var khrMaterial = material.extensions[ this.name ];
  188. var pending = [];
  189. var keys = [];
  190. // TODO: Currently ignored: 'ambientFactor', 'ambientTexture'
  191. switch ( khrMaterial.type ) {
  192. case 'commonBlinn' :
  193. case 'commonPhong' :
  194. keys.push( 'diffuseFactor', 'diffuseTexture', 'specularFactor', 'specularTexture', 'shininessFactor' );
  195. break;
  196. case 'commonLambert' :
  197. keys.push( 'diffuseFactor', 'diffuseTexture' );
  198. break;
  199. case 'commonConstant' :
  200. default :
  201. break;
  202. }
  203. var materialValues = {};
  204. keys.forEach( function( v ) {
  205. if ( khrMaterial[ v ] !== undefined ) materialValues[ v ] = khrMaterial[ v ];
  206. } );
  207. if ( materialValues.diffuseFactor !== undefined ) {
  208. materialParams.color = new THREE.Color().fromArray( materialValues.diffuseFactor );
  209. materialParams.opacity = materialValues.diffuseFactor[ 3 ];
  210. }
  211. if ( materialValues.diffuseTexture !== undefined ) {
  212. pending.push( parser.assignTexture( materialParams, 'map', materialValues.diffuseTexture.index ) );
  213. }
  214. if ( materialValues.specularFactor !== undefined ) {
  215. materialParams.specular = new THREE.Color().fromArray( materialValues.specularFactor );
  216. }
  217. if ( materialValues.specularTexture !== undefined ) {
  218. pending.push( parser.assignTexture( materialParams, 'specularMap', materialValues.specularTexture.index ) );
  219. }
  220. if ( materialValues.shininessFactor !== undefined ) {
  221. materialParams.shininess = materialValues.shininessFactor;
  222. }
  223. return Promise.all( pending );
  224. };
  225. /* BINARY EXTENSION */
  226. var BINARY_EXTENSION_BUFFER_NAME = 'binary_glTF';
  227. var BINARY_EXTENSION_HEADER_MAGIC = 'glTF';
  228. var BINARY_EXTENSION_HEADER_LENGTH = 12;
  229. var BINARY_EXTENSION_CHUNK_TYPES = { JSON: 0x4E4F534A, BIN: 0x004E4942 };
  230. function GLTFBinaryExtension( data ) {
  231. this.name = EXTENSIONS.KHR_BINARY_GLTF;
  232. this.content = null;
  233. this.body = null;
  234. var headerView = new DataView( data, 0, BINARY_EXTENSION_HEADER_LENGTH );
  235. this.header = {
  236. magic: convertUint8ArrayToString( new Uint8Array( data.slice( 0, 4 ) ) ),
  237. version: headerView.getUint32( 4, true ),
  238. length: headerView.getUint32( 8, true )
  239. };
  240. if ( this.header.magic !== BINARY_EXTENSION_HEADER_MAGIC ) {
  241. throw new Error( 'THREE.GLTF2Loader: Unsupported glTF-Binary header.' );
  242. } else if ( this.header.version < 2.0 ) {
  243. throw new Error( 'THREE.GLTF2Loader: Legacy binary file detected. Use GLTFLoader instead.' );
  244. }
  245. var chunkView = new DataView( data, BINARY_EXTENSION_HEADER_LENGTH );
  246. var chunkIndex = 0;
  247. while ( chunkIndex < chunkView.byteLength ) {
  248. var chunkLength = chunkView.getUint32( chunkIndex, true );
  249. chunkIndex += 4;
  250. var chunkType = chunkView.getUint32( chunkIndex, true );
  251. chunkIndex += 4;
  252. if ( chunkType === BINARY_EXTENSION_CHUNK_TYPES.JSON ) {
  253. var contentArray = new Uint8Array( data, BINARY_EXTENSION_HEADER_LENGTH + chunkIndex, chunkLength );
  254. this.content = convertUint8ArrayToString( contentArray );
  255. } else if ( chunkType === BINARY_EXTENSION_CHUNK_TYPES.BIN ) {
  256. var byteOffset = BINARY_EXTENSION_HEADER_LENGTH + chunkIndex;
  257. this.body = data.slice( byteOffset, byteOffset + chunkLength );
  258. }
  259. // Clients must ignore chunks with unknown types.
  260. chunkIndex += chunkLength;
  261. }
  262. if ( this.content === null ) {
  263. throw new Error( 'THREE.GLTF2Loader: JSON content not found.' );
  264. }
  265. }
  266. /**
  267. * Specular-Glossiness Extension
  268. *
  269. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  270. */
  271. function GLTFMaterialsPbrSpecularGlossinessExtension() {
  272. return {
  273. name: EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS,
  274. getMaterialType: function () {
  275. return THREE.ShaderMaterial;
  276. },
  277. extendParams: function ( params, material, parser ) {
  278. var pbrSpecularGlossiness = material.extensions[ this.name ];
  279. var shader = THREE.ShaderLib[ 'standard' ];
  280. var uniforms = THREE.UniformsUtils.clone( shader.uniforms );
  281. var specularMapParsFragmentChunk = [
  282. '#ifdef USE_SPECULARMAP',
  283. ' uniform sampler2D specularMap;',
  284. '#endif'
  285. ].join( '\n' );
  286. var glossinessMapParsFragmentChunk = [
  287. '#ifdef USE_GLOSSINESSMAP',
  288. ' uniform sampler2D glossinessMap;',
  289. '#endif'
  290. ].join( '\n' );
  291. var specularMapFragmentChunk = [
  292. 'vec3 specularFactor = specular;',
  293. '#ifdef USE_SPECULARMAP',
  294. ' vec4 texelSpecular = texture2D( specularMap, vUv );',
  295. ' // reads channel RGB, compatible with a glTF Specular-Glossiness (RGBA) texture',
  296. ' specularFactor *= texelSpecular.rgb;',
  297. '#endif'
  298. ].join( '\n' );
  299. var glossinessMapFragmentChunk = [
  300. 'float glossinessFactor = glossiness;',
  301. '#ifdef USE_GLOSSINESSMAP',
  302. ' vec4 texelGlossiness = texture2D( glossinessMap, vUv );',
  303. ' // reads channel A, compatible with a glTF Specular-Glossiness (RGBA) texture',
  304. ' glossinessFactor *= texelGlossiness.a;',
  305. '#endif'
  306. ].join( '\n' );
  307. var lightPhysicalFragmentChunk = [
  308. 'PhysicalMaterial material;',
  309. 'material.diffuseColor = diffuseColor.rgb;',
  310. 'material.specularRoughness = clamp( 1.0 - glossinessFactor, 0.04, 1.0 );',
  311. 'material.specularColor = specularFactor.rgb;',
  312. ].join( '\n' );
  313. var fragmentShader = shader.fragmentShader
  314. .replace( '#include <specularmap_fragment>', '' )
  315. .replace( 'uniform float roughness;', 'uniform vec3 specular;' )
  316. .replace( 'uniform float metalness;', 'uniform float glossiness;' )
  317. .replace( '#include <roughnessmap_pars_fragment>', specularMapParsFragmentChunk )
  318. .replace( '#include <metalnessmap_pars_fragment>', glossinessMapParsFragmentChunk )
  319. .replace( '#include <roughnessmap_fragment>', specularMapFragmentChunk )
  320. .replace( '#include <metalnessmap_fragment>', glossinessMapFragmentChunk )
  321. .replace( '#include <lights_physical_fragment>', lightPhysicalFragmentChunk );
  322. delete uniforms.roughness;
  323. delete uniforms.metalness;
  324. delete uniforms.roughnessMap;
  325. delete uniforms.metalnessMap;
  326. uniforms.specular = { value: new THREE.Color().setHex( 0x111111 ) };
  327. uniforms.glossiness = { value: 0.5 };
  328. uniforms.specularMap = { value: null };
  329. uniforms.glossinessMap = { value: null };
  330. params.vertexShader = shader.vertexShader;
  331. params.fragmentShader = fragmentShader;
  332. params.uniforms = uniforms;
  333. params.defines = { 'STANDARD': '' };
  334. params.color = new THREE.Color( 1.0, 1.0, 1.0 );
  335. params.opacity = 1.0;
  336. var pending = [];
  337. if ( Array.isArray( pbrSpecularGlossiness.diffuseFactor ) ) {
  338. var array = pbrSpecularGlossiness.diffuseFactor;
  339. params.color.fromArray( array );
  340. params.opacity = array[ 3 ];
  341. }
  342. if ( pbrSpecularGlossiness.diffuseTexture !== undefined ) {
  343. pending.push( parser.assignTexture( params, 'map', pbrSpecularGlossiness.diffuseTexture.index ) );
  344. }
  345. params.emissive = new THREE.Color( 0.0, 0.0, 0.0 );
  346. params.glossiness = pbrSpecularGlossiness.glossinessFactor !== undefined ? pbrSpecularGlossiness.glossinessFactor : 1.0;
  347. params.specular = new THREE.Color( 1.0, 1.0, 1.0 );
  348. if ( Array.isArray( pbrSpecularGlossiness.specularFactor ) ) {
  349. params.specular.fromArray( pbrSpecularGlossiness.specularFactor );
  350. }
  351. if ( pbrSpecularGlossiness.specularGlossinessTexture !== undefined ) {
  352. var specGlossIndex = pbrSpecularGlossiness.specularGlossinessTexture.index;
  353. pending.push( parser.assignTexture( params, 'glossinessMap', specGlossIndex ) );
  354. pending.push( parser.assignTexture( params, 'specularMap', specGlossIndex ) );
  355. }
  356. return Promise.all( pending );
  357. },
  358. createMaterial: function ( params ) {
  359. // setup material properties based on MeshStandardMaterial for Specular-Glossiness
  360. var material = new THREE.ShaderMaterial( {
  361. defines: params.defines,
  362. vertexShader: params.vertexShader,
  363. fragmentShader: params.fragmentShader,
  364. uniforms: params.uniforms,
  365. fog: true,
  366. lights: true,
  367. opacity: params.opacity,
  368. transparent: params.transparent
  369. } );
  370. material.isGLTFSpecularGlossinessMaterial = true;
  371. material.color = params.color;
  372. material.map = params.map === undefined ? null : params.map;
  373. material.lightMap = null;
  374. material.lightMapIntensity = 1.0;
  375. material.aoMap = params.aoMap === undefined ? null : params.aoMap;
  376. material.aoMapIntensity = 1.0;
  377. material.emissive = params.emissive;
  378. material.emissiveIntensity = 1.0;
  379. material.emissiveMap = params.emissiveMap === undefined ? null : params.emissiveMap;
  380. material.bumpMap = params.bumpMap === undefined ? null : params.bumpMap;
  381. material.bumpScale = 1;
  382. material.normalMap = params.normalMap === undefined ? null : params.normalMap;
  383. material.normalScale = new THREE.Vector2( 1, 1 );
  384. material.displacementMap = null;
  385. material.displacementScale = 1;
  386. material.displacementBias = 0;
  387. material.specularMap = params.specularMap === undefined ? null : params.specularMap;
  388. material.specular = params.specular;
  389. material.glossinessMap = params.glossinessMap === undefined ? null : params.glossinessMap;
  390. material.glossiness = params.glossiness;
  391. material.alphaMap = null;
  392. material.envMap = params.envMap === undefined ? null : params.envMap;
  393. material.envMapIntensity = 1.0;
  394. material.refractionRatio = 0.98;
  395. material.extensions.derivatives = true;
  396. return material;
  397. },
  398. // Here's based on refreshUniformsCommon() and refreshUniformsStandard() in WebGLRenderer.
  399. refreshUniforms: function ( renderer, scene, camera, geometry, material, group ) {
  400. var uniforms = material.uniforms;
  401. var defines = material.defines;
  402. uniforms.opacity.value = material.opacity;
  403. uniforms.diffuse.value.copy( material.color );
  404. uniforms.emissive.value.copy( material.emissive ).multiplyScalar( material.emissiveIntensity );
  405. uniforms.map.value = material.map;
  406. uniforms.specularMap.value = material.specularMap;
  407. uniforms.alphaMap.value = material.alphaMap;
  408. uniforms.lightMap.value = material.lightMap;
  409. uniforms.lightMapIntensity.value = material.lightMapIntensity;
  410. uniforms.aoMap.value = material.aoMap;
  411. uniforms.aoMapIntensity.value = material.aoMapIntensity;
  412. // uv repeat and offset setting priorities
  413. // 1. color map
  414. // 2. specular map
  415. // 3. normal map
  416. // 4. bump map
  417. // 5. alpha map
  418. // 6. emissive map
  419. var uvScaleMap;
  420. if ( material.map ) {
  421. uvScaleMap = material.map;
  422. } else if ( material.specularMap ) {
  423. uvScaleMap = material.specularMap;
  424. } else if ( material.displacementMap ) {
  425. uvScaleMap = material.displacementMap;
  426. } else if ( material.normalMap ) {
  427. uvScaleMap = material.normalMap;
  428. } else if ( material.bumpMap ) {
  429. uvScaleMap = material.bumpMap;
  430. } else if ( material.glossinessMap ) {
  431. uvScaleMap = material.glossinessMap;
  432. } else if ( material.alphaMap ) {
  433. uvScaleMap = material.alphaMap;
  434. } else if ( material.emissiveMap ) {
  435. uvScaleMap = material.emissiveMap;
  436. }
  437. if ( uvScaleMap !== undefined ) {
  438. // backwards compatibility
  439. if ( uvScaleMap.isWebGLRenderTarget ) {
  440. uvScaleMap = uvScaleMap.texture;
  441. }
  442. var offset = uvScaleMap.offset;
  443. var repeat = uvScaleMap.repeat;
  444. uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y );
  445. }
  446. uniforms.envMap.value = material.envMap;
  447. uniforms.envMapIntensity.value = material.envMapIntensity;
  448. uniforms.flipEnvMap.value = ( material.envMap && material.envMap.isCubeTexture ) ? -1 : 1;
  449. uniforms.refractionRatio.value = material.refractionRatio;
  450. uniforms.specular.value.copy( material.specular );
  451. uniforms.glossiness.value = material.glossiness;
  452. uniforms.glossinessMap.value = material.glossinessMap;
  453. uniforms.emissiveMap.value = material.emissiveMap;
  454. uniforms.bumpMap.value = material.bumpMap;
  455. uniforms.normalMap.value = material.normalMap;
  456. uniforms.displacementMap.value = material.displacementMap;
  457. uniforms.displacementScale.value = material.displacementScale;
  458. uniforms.displacementBias.value = material.displacementBias;
  459. if ( uniforms.glossinessMap.value !== null && defines.USE_GLOSSINESSMAP === undefined ) {
  460. defines.USE_GLOSSINESSMAP = '';
  461. // set USE_ROUGHNESSMAP to enable vUv
  462. defines.USE_ROUGHNESSMAP = ''
  463. }
  464. if ( uniforms.glossinessMap.value === null && defines.USE_GLOSSINESSMAP !== undefined ) {
  465. delete defines.USE_GLOSSINESSMAP;
  466. delete defines.USE_ROUGHNESSMAP;
  467. }
  468. }
  469. };
  470. }
  471. /*********************************/
  472. /********** INTERNALS ************/
  473. /*********************************/
  474. /* CONSTANTS */
  475. var WEBGL_CONSTANTS = {
  476. FLOAT: 5126,
  477. //FLOAT_MAT2: 35674,
  478. FLOAT_MAT3: 35675,
  479. FLOAT_MAT4: 35676,
  480. FLOAT_VEC2: 35664,
  481. FLOAT_VEC3: 35665,
  482. FLOAT_VEC4: 35666,
  483. LINEAR: 9729,
  484. REPEAT: 10497,
  485. SAMPLER_2D: 35678,
  486. POINTS: 0,
  487. LINES: 1,
  488. LINE_LOOP: 2,
  489. LINE_STRIP: 3,
  490. TRIANGLES: 4,
  491. TRIANGLE_STRIP: 5,
  492. TRIANGLE_FAN: 6,
  493. UNSIGNED_BYTE: 5121,
  494. UNSIGNED_SHORT: 5123
  495. };
  496. var WEBGL_TYPE = {
  497. 5126: Number,
  498. //35674: THREE.Matrix2,
  499. 35675: THREE.Matrix3,
  500. 35676: THREE.Matrix4,
  501. 35664: THREE.Vector2,
  502. 35665: THREE.Vector3,
  503. 35666: THREE.Vector4,
  504. 35678: THREE.Texture
  505. };
  506. var WEBGL_COMPONENT_TYPES = {
  507. 5120: Int8Array,
  508. 5121: Uint8Array,
  509. 5122: Int16Array,
  510. 5123: Uint16Array,
  511. 5125: Uint32Array,
  512. 5126: Float32Array
  513. };
  514. var WEBGL_FILTERS = {
  515. 9728: THREE.NearestFilter,
  516. 9729: THREE.LinearFilter,
  517. 9984: THREE.NearestMipMapNearestFilter,
  518. 9985: THREE.LinearMipMapNearestFilter,
  519. 9986: THREE.NearestMipMapLinearFilter,
  520. 9987: THREE.LinearMipMapLinearFilter
  521. };
  522. var WEBGL_WRAPPINGS = {
  523. 33071: THREE.ClampToEdgeWrapping,
  524. 33648: THREE.MirroredRepeatWrapping,
  525. 10497: THREE.RepeatWrapping
  526. };
  527. var WEBGL_TEXTURE_FORMATS = {
  528. 6406: THREE.AlphaFormat,
  529. 6407: THREE.RGBFormat,
  530. 6408: THREE.RGBAFormat,
  531. 6409: THREE.LuminanceFormat,
  532. 6410: THREE.LuminanceAlphaFormat
  533. };
  534. var WEBGL_TEXTURE_DATATYPES = {
  535. 5121: THREE.UnsignedByteType,
  536. 32819: THREE.UnsignedShort4444Type,
  537. 32820: THREE.UnsignedShort5551Type,
  538. 33635: THREE.UnsignedShort565Type
  539. };
  540. var WEBGL_SIDES = {
  541. 1028: THREE.BackSide, // Culling front
  542. 1029: THREE.FrontSide // Culling back
  543. //1032: THREE.NoSide // Culling front and back, what to do?
  544. };
  545. var WEBGL_DEPTH_FUNCS = {
  546. 512: THREE.NeverDepth,
  547. 513: THREE.LessDepth,
  548. 514: THREE.EqualDepth,
  549. 515: THREE.LessEqualDepth,
  550. 516: THREE.GreaterEqualDepth,
  551. 517: THREE.NotEqualDepth,
  552. 518: THREE.GreaterEqualDepth,
  553. 519: THREE.AlwaysDepth
  554. };
  555. var WEBGL_BLEND_EQUATIONS = {
  556. 32774: THREE.AddEquation,
  557. 32778: THREE.SubtractEquation,
  558. 32779: THREE.ReverseSubtractEquation
  559. };
  560. var WEBGL_BLEND_FUNCS = {
  561. 0: THREE.ZeroFactor,
  562. 1: THREE.OneFactor,
  563. 768: THREE.SrcColorFactor,
  564. 769: THREE.OneMinusSrcColorFactor,
  565. 770: THREE.SrcAlphaFactor,
  566. 771: THREE.OneMinusSrcAlphaFactor,
  567. 772: THREE.DstAlphaFactor,
  568. 773: THREE.OneMinusDstAlphaFactor,
  569. 774: THREE.DstColorFactor,
  570. 775: THREE.OneMinusDstColorFactor,
  571. 776: THREE.SrcAlphaSaturateFactor
  572. // The followings are not supported by Three.js yet
  573. //32769: CONSTANT_COLOR,
  574. //32770: ONE_MINUS_CONSTANT_COLOR,
  575. //32771: CONSTANT_ALPHA,
  576. //32772: ONE_MINUS_CONSTANT_COLOR
  577. };
  578. var WEBGL_TYPE_SIZES = {
  579. 'SCALAR': 1,
  580. 'VEC2': 2,
  581. 'VEC3': 3,
  582. 'VEC4': 4,
  583. 'MAT2': 4,
  584. 'MAT3': 9,
  585. 'MAT4': 16
  586. };
  587. var PATH_PROPERTIES = {
  588. scale: 'scale',
  589. translation: 'position',
  590. rotation: 'quaternion',
  591. weights: 'morphTargetInfluences'
  592. };
  593. var INTERPOLATION = {
  594. CATMULLROMSPLINE: THREE.InterpolateSmooth,
  595. CUBICSPLINE: THREE.InterpolateSmooth,
  596. LINEAR: THREE.InterpolateLinear,
  597. STEP: THREE.InterpolateDiscrete
  598. };
  599. var STATES_ENABLES = {
  600. 2884: 'CULL_FACE',
  601. 2929: 'DEPTH_TEST',
  602. 3042: 'BLEND',
  603. 3089: 'SCISSOR_TEST',
  604. 32823: 'POLYGON_OFFSET_FILL',
  605. 32926: 'SAMPLE_ALPHA_TO_COVERAGE'
  606. };
  607. var ALPHA_MODES = {
  608. OPAQUE: 'OPAQUE',
  609. MASK: 'MASK',
  610. BLEND: 'BLEND'
  611. };
  612. /* UTILITY FUNCTIONS */
  613. function _each( object, callback, thisObj ) {
  614. if ( !object ) {
  615. return Promise.resolve();
  616. }
  617. var results;
  618. var fns = [];
  619. if ( Object.prototype.toString.call( object ) === '[object Array]' ) {
  620. results = [];
  621. var length = object.length;
  622. for ( var idx = 0; idx < length; idx ++ ) {
  623. var value = callback.call( thisObj || this, object[ idx ], idx );
  624. if ( value ) {
  625. fns.push( value );
  626. if ( value instanceof Promise ) {
  627. value.then( function( key, value ) {
  628. results[ key ] = value;
  629. }.bind( this, idx ));
  630. } else {
  631. results[ idx ] = value;
  632. }
  633. }
  634. }
  635. } else {
  636. results = {};
  637. for ( var key in object ) {
  638. if ( object.hasOwnProperty( key ) ) {
  639. var value = callback.call( thisObj || this, object[ key ], key );
  640. if ( value ) {
  641. fns.push( value );
  642. if ( value instanceof Promise ) {
  643. value.then( function( key, value ) {
  644. results[ key ] = value;
  645. }.bind( this, key ));
  646. } else {
  647. results[ key ] = value;
  648. }
  649. }
  650. }
  651. }
  652. }
  653. return Promise.all( fns ).then( function() {
  654. return results;
  655. });
  656. }
  657. function resolveURL( url, path ) {
  658. // Invalid URL
  659. if ( typeof url !== 'string' || url === '' )
  660. return '';
  661. // Absolute URL http://,https://,//
  662. if ( /^(https?:)?\/\//i.test( url ) ) {
  663. return url;
  664. }
  665. // Data URI
  666. if ( /^data:.*,.*$/i.test( url ) ) {
  667. return url;
  668. }
  669. // Blob URL
  670. if ( /^blob:.*$/i.test( url ) ) {
  671. return url;
  672. }
  673. // Relative URL
  674. return ( path || '' ) + url;
  675. }
  676. function convertUint8ArrayToString( array ) {
  677. if ( window.TextDecoder !== undefined ) {
  678. return new TextDecoder().decode( array );
  679. }
  680. // Avoid the String.fromCharCode.apply(null, array) shortcut, which
  681. // throws a "maximum call stack size exceeded" error for large arrays.
  682. var s = '';
  683. for ( var i = 0, il = array.length; i < il; i ++ ) {
  684. s += String.fromCharCode( array[ i ] );
  685. }
  686. return s;
  687. }
  688. /**
  689. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#default-material
  690. */
  691. function createDefaultMaterial() {
  692. return new THREE.MeshStandardMaterial( {
  693. color: 0xFFFFFF,
  694. emissive: 0x000000,
  695. metalness: 1,
  696. roughness: 1,
  697. transparent: false,
  698. depthTest: true,
  699. side: THREE.FrontSide
  700. } );
  701. }
  702. /**
  703. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#morph-targets
  704. * @param {THREE.Mesh} mesh
  705. * @param {GLTF.Mesh} meshDef
  706. * @param {GLTF.Primitive} primitiveDef
  707. * @param {Object} dependencies
  708. */
  709. function addMorphTargets ( mesh, meshDef, primitiveDef, dependencies ) {
  710. var geometry = mesh.geometry;
  711. var material = mesh.material;
  712. var targets = primitiveDef.targets;
  713. var morphAttributes = geometry.morphAttributes;
  714. morphAttributes.position = [];
  715. morphAttributes.normal = [];
  716. material.morphTargets = true;
  717. for ( var i = 0, il = targets.length; i < il; i ++ ) {
  718. var target = targets[ i ];
  719. var attributeName = 'morphTarget' + i;
  720. var positionAttribute, normalAttribute;
  721. if ( target.POSITION !== undefined ) {
  722. // Three.js morph formula is
  723. // position
  724. // + weight0 * ( morphTarget0 - position )
  725. // + weight1 * ( morphTarget1 - position )
  726. // ...
  727. // while the glTF one is
  728. // position
  729. // + weight0 * morphTarget0
  730. // + weight1 * morphTarget1
  731. // ...
  732. // then adding position to morphTarget.
  733. // So morphTarget value will depend on mesh's position, then cloning attribute
  734. // for the case if attribute is shared among two or more meshes.
  735. positionAttribute = dependencies.accessors[ target.POSITION ].clone();
  736. var position = geometry.attributes.position;
  737. for ( var j = 0, jl = positionAttribute.count; j < jl; j ++ ) {
  738. positionAttribute.setXYZ(
  739. j,
  740. positionAttribute.getX( j ) + position.getX( j ),
  741. positionAttribute.getY( j ) + position.getY( j ),
  742. positionAttribute.getZ( j ) + position.getZ( j )
  743. );
  744. }
  745. } else {
  746. // Copying the original position not to affect the final position.
  747. // See the formula above.
  748. positionAttribute = geometry.attributes.position.clone();
  749. }
  750. if ( target.NORMAL !== undefined ) {
  751. material.morphNormals = true;
  752. // see target.POSITION's comment
  753. normalAttribute = dependencies.accessors[ target.NORMAL ].clone();
  754. var normal = geometry.attributes.normal;
  755. for ( var j = 0, jl = normalAttribute.count; j < jl; j ++ ) {
  756. normalAttribute.setXYZ(
  757. j,
  758. normalAttribute.getX( j ) + normal.getX( j ),
  759. normalAttribute.getY( j ) + normal.getY( j ),
  760. normalAttribute.getZ( j ) + normal.getZ( j )
  761. );
  762. }
  763. } else {
  764. normalAttribute = geometry.attributes.normal.clone();
  765. }
  766. if ( target.TANGENT !== undefined ) {
  767. // TODO: implement
  768. }
  769. positionAttribute.name = attributeName;
  770. normalAttribute.name = attributeName;
  771. morphAttributes.position.push( positionAttribute );
  772. morphAttributes.normal.push( normalAttribute );
  773. }
  774. mesh.updateMorphTargets();
  775. if ( meshDef.weights !== undefined ) {
  776. for ( var i = 0, il = meshDef.weights.length; i < il; i ++ ) {
  777. mesh.morphTargetInfluences[ i ] = meshDef.weights[ i ];
  778. }
  779. }
  780. }
  781. /* GLTF PARSER */
  782. function GLTFParser( json, extensions, options ) {
  783. this.json = json || {};
  784. this.extensions = extensions || {};
  785. this.options = options || {};
  786. // loader object cache
  787. this.cache = new GLTFRegistry();
  788. }
  789. GLTFParser.prototype._withDependencies = function ( dependencies ) {
  790. var _dependencies = {};
  791. for ( var i = 0; i < dependencies.length; i ++ ) {
  792. var dependency = dependencies[ i ];
  793. var fnName = 'load' + dependency.charAt( 0 ).toUpperCase() + dependency.slice( 1 );
  794. var cached = this.cache.get( dependency );
  795. if ( cached !== undefined ) {
  796. _dependencies[ dependency ] = cached;
  797. } else if ( this[ fnName ] ) {
  798. var fn = this[ fnName ]();
  799. this.cache.add( dependency, fn );
  800. _dependencies[ dependency ] = fn;
  801. }
  802. }
  803. return _each( _dependencies, function ( dependency ) {
  804. return dependency;
  805. } );
  806. };
  807. GLTFParser.prototype.parse = function ( onLoad, onError ) {
  808. var json = this.json;
  809. // Clear the loader cache
  810. this.cache.removeAll();
  811. // Fire the callback on complete
  812. this._withDependencies( [
  813. 'scenes',
  814. 'cameras',
  815. 'animations'
  816. ] ).then( function ( dependencies ) {
  817. var scenes = [];
  818. for ( var name in dependencies.scenes ) {
  819. scenes.push( dependencies.scenes[ name ] );
  820. }
  821. var scene = json.scene !== undefined ? dependencies.scenes[ json.scene ] : scenes[ 0 ];
  822. var cameras = [];
  823. for ( var name in dependencies.cameras ) {
  824. var camera = dependencies.cameras[ name ];
  825. cameras.push( camera );
  826. }
  827. var animations = [];
  828. for ( var name in dependencies.animations ) {
  829. animations.push( dependencies.animations[ name ] );
  830. }
  831. onLoad( scene, scenes, cameras, animations );
  832. } ).catch( onError );
  833. };
  834. /**
  835. * Requests the specified dependency asynchronously, with caching.
  836. * @param {string} type
  837. * @param {number} index
  838. * @return {Promise<Object>}
  839. */
  840. GLTFParser.prototype.getDependency = function ( type, index ) {
  841. var cacheKey = type + ':' + index;
  842. var dependency = this.cache.get( cacheKey );
  843. if ( !dependency ) {
  844. var fnName = 'load' + type.charAt( 0 ).toUpperCase() + type.slice( 1 );
  845. dependency = this[ fnName ]( index );
  846. this.cache.add( cacheKey, dependency );
  847. }
  848. return dependency;
  849. };
  850. GLTFParser.prototype.loadBuffers = function () {
  851. var json = this.json;
  852. var extensions = this.extensions;
  853. var options = this.options;
  854. return _each( json.buffers, function ( buffer, name ) {
  855. if ( buffer.type === 'arraybuffer' || buffer.type === undefined ) {
  856. // If present, GLB container is required to be the first buffer.
  857. if ( buffer.uri === undefined && name === 0 ) {
  858. return extensions[ EXTENSIONS.KHR_BINARY_GLTF ].body;
  859. }
  860. return new Promise( function ( resolve ) {
  861. var loader = new THREE.FileLoader();
  862. loader.setResponseType( 'arraybuffer' );
  863. loader.load( resolveURL( buffer.uri, options.path ), function ( buffer ) {
  864. resolve( buffer );
  865. } );
  866. } );
  867. } else {
  868. console.warn( 'THREE.GLTF2Loader: %s buffer type is not supported.', buffer.type );
  869. }
  870. } );
  871. };
  872. /**
  873. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#buffers-and-buffer-views
  874. * @param {number} bufferViewIndex
  875. * @return {Promise<ArrayBuffer>}
  876. */
  877. GLTFParser.prototype.loadBufferView = function ( bufferViewIndex ) {
  878. return this._withDependencies( [
  879. 'bufferViews'
  880. ] ).then( function ( dependencies ) {
  881. return dependencies.bufferViews[ bufferViewIndex ];
  882. } );
  883. };
  884. /** @deprecated */
  885. GLTFParser.prototype.loadBufferViews = function () {
  886. var json = this.json;
  887. return this._withDependencies( [
  888. 'buffers'
  889. ] ).then( function ( dependencies ) {
  890. return _each( json.bufferViews, function ( bufferView ) {
  891. var arraybuffer = dependencies.buffers[ bufferView.buffer ];
  892. var byteLength = bufferView.byteLength || 0;
  893. var byteOffset = bufferView.byteOffset || 0;
  894. return arraybuffer.slice( byteOffset, byteOffset + byteLength );
  895. } );
  896. } );
  897. };
  898. GLTFParser.prototype.loadAccessors = function () {
  899. var json = this.json;
  900. return this._withDependencies( [
  901. 'bufferViews'
  902. ] ).then( function ( dependencies ) {
  903. return _each( json.accessors, function ( accessor ) {
  904. var arraybuffer = dependencies.bufferViews[ accessor.bufferView ];
  905. var itemSize = WEBGL_TYPE_SIZES[ accessor.type ];
  906. var TypedArray = WEBGL_COMPONENT_TYPES[ accessor.componentType ];
  907. // For VEC3: itemSize is 3, elementBytes is 4, itemBytes is 12.
  908. var elementBytes = TypedArray.BYTES_PER_ELEMENT;
  909. var itemBytes = elementBytes * itemSize;
  910. var byteStride = json.bufferViews[ accessor.bufferView ].byteStride;
  911. var array;
  912. // The buffer is not interleaved if the stride is the item size in bytes.
  913. if ( byteStride && byteStride !== itemBytes ) {
  914. // Use the full buffer if it's interleaved.
  915. array = new TypedArray( arraybuffer );
  916. // Integer parameters to IB/IBA are in array elements, not bytes.
  917. var ib = new THREE.InterleavedBuffer( array, byteStride / elementBytes );
  918. return new THREE.InterleavedBufferAttribute( ib, itemSize, accessor.byteOffset / elementBytes );
  919. } else {
  920. array = new TypedArray( arraybuffer, accessor.byteOffset, accessor.count * itemSize );
  921. return new THREE.BufferAttribute( array, itemSize );
  922. }
  923. } );
  924. } );
  925. };
  926. var URL = window.URL || window.webkitURL;
  927. /**
  928. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#textures
  929. * @param {number} textureIndex
  930. * @return {Promise<THREE.Texture>}
  931. */
  932. GLTFParser.prototype.loadTexture = function ( textureIndex ) {
  933. var parser = this;
  934. var json = this.json;
  935. var options = this.options;
  936. var textureDef = this.json.textures[ textureIndex ];
  937. if ( textureDef.source === undefined ) {
  938. throw new Error( 'THREE.GLTF2Loader: Unknown texture for index ' + textureIndex );
  939. }
  940. var source = json.images[ textureDef.source ];
  941. var sourceURI = source.uri;
  942. var isObjectURL = false;
  943. if ( source.bufferView !== undefined ) {
  944. // Load binary image data from bufferView, if provided.
  945. sourceURI = parser.loadBufferView( source.bufferView )
  946. .then( function ( bufferView ) {
  947. isObjectURL = true;
  948. var blob = new Blob( [ bufferView ], { type: source.mimeType } );
  949. sourceURI = URL.createObjectURL( blob );
  950. return sourceURI;
  951. } );
  952. }
  953. return Promise.resolve( sourceURI ).then( function ( sourceURI ) {
  954. // Load Texture resource.
  955. var textureLoader = THREE.Loader.Handlers.get( sourceURI ) || new THREE.TextureLoader();
  956. textureLoader.setCrossOrigin( options.crossOrigin );
  957. return new Promise( function ( resolve, reject ) {
  958. textureLoader.load( resolveURL( sourceURI, options.path ), resolve, undefined, reject );
  959. } );
  960. } ).then( function ( texture ) {
  961. // Clean up resources and configure Texture.
  962. if ( isObjectURL !== undefined ) {
  963. URL.revokeObjectURL( sourceURI );
  964. }
  965. texture.flipY = false;
  966. if ( textureDef.name !== undefined ) texture.name = textureDef.name;
  967. texture.format = textureDef.format !== undefined ? WEBGL_TEXTURE_FORMATS[ textureDef.format ] : THREE.RGBAFormat;
  968. if ( textureDef.internalFormat !== undefined && texture.format !== WEBGL_TEXTURE_FORMATS[ textureDef.internalFormat ] ) {
  969. console.warn( 'THREE.GLTF2Loader: Three.js does not support texture internalFormat which is different from texture format. ' +
  970. 'internalFormat will be forced to be the same value as format.' );
  971. }
  972. texture.type = textureDef.type !== undefined ? WEBGL_TEXTURE_DATATYPES[ textureDef.type ] : THREE.UnsignedByteType;
  973. var samplers = json.samplers || {};
  974. var sampler = samplers[ textureDef.sampler ] || {};
  975. texture.magFilter = WEBGL_FILTERS[ sampler.magFilter ] || THREE.LinearFilter;
  976. texture.minFilter = WEBGL_FILTERS[ sampler.minFilter ] || THREE.LinearMipMapLinearFilter;
  977. texture.wrapS = WEBGL_WRAPPINGS[ sampler.wrapS ] || THREE.RepeatWrapping;
  978. texture.wrapT = WEBGL_WRAPPINGS[ sampler.wrapT ] || THREE.RepeatWrapping;
  979. return texture;
  980. } );
  981. };
  982. /**
  983. * Asynchronously assigns a texture to the given material parameters.
  984. * @param {Object} materialParams
  985. * @param {string} textureName
  986. * @param {number} textureIndex
  987. * @return {Promise}
  988. */
  989. GLTFParser.prototype.assignTexture = function ( materialParams, textureName, textureIndex ) {
  990. return this.getDependency( 'texture', textureIndex ).then( function ( texture ) {
  991. materialParams[ textureName ] = texture;
  992. } );
  993. };
  994. /**
  995. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#materials
  996. * @return {Promise<Array<THREE.Material>>}
  997. */
  998. GLTFParser.prototype.loadMaterials = function () {
  999. var parser = this;
  1000. var json = this.json;
  1001. var extensions = this.extensions;
  1002. return _each( json.materials, function ( material ) {
  1003. var materialType;
  1004. var materialParams = {};
  1005. var materialExtensions = material.extensions || {};
  1006. var pending = [];
  1007. if ( materialExtensions[ EXTENSIONS.KHR_MATERIALS_COMMON ] ) {
  1008. var khcExtension = extensions[ EXTENSIONS.KHR_MATERIALS_COMMON ];
  1009. materialType = khcExtension.getMaterialType( material );
  1010. pending.push( khcExtension.extendParams( materialParams, material, parser ) );
  1011. } else if ( materialExtensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ] ) {
  1012. var sgExtension = extensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ];
  1013. materialType = sgExtension.getMaterialType( material );
  1014. pending.push( sgExtension.extendParams( materialParams, material, parser ) );
  1015. } else if ( materialExtensions[ EXTENSIONS.KHR_TECHNIQUE_WEBGL ] ) {
  1016. materialType = extensions[ EXTENSIONS.KHR_TECHNIQUE_WEBGL ].getMaterialType( material );
  1017. extensions[ EXTENSIONS.KHR_TECHNIQUE_WEBGL ].extendParams( materialParams, material, dependencies );
  1018. } else if ( material.pbrMetallicRoughness !== undefined ) {
  1019. // Specification:
  1020. // https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#metallic-roughness-material
  1021. materialType = THREE.MeshStandardMaterial;
  1022. var metallicRoughness = material.pbrMetallicRoughness;
  1023. materialParams.color = new THREE.Color( 1.0, 1.0, 1.0 );
  1024. materialParams.opacity = 1.0;
  1025. if ( Array.isArray( metallicRoughness.baseColorFactor ) ) {
  1026. var array = metallicRoughness.baseColorFactor;
  1027. materialParams.color.fromArray( array );
  1028. materialParams.opacity = array[ 3 ];
  1029. }
  1030. if ( metallicRoughness.baseColorTexture !== undefined ) {
  1031. pending.push( parser.assignTexture( materialParams, 'map', metallicRoughness.baseColorTexture.index ) );
  1032. }
  1033. materialParams.metalness = metallicRoughness.metallicFactor !== undefined ? metallicRoughness.metallicFactor : 1.0;
  1034. materialParams.roughness = metallicRoughness.roughnessFactor !== undefined ? metallicRoughness.roughnessFactor : 1.0;
  1035. if ( metallicRoughness.metallicRoughnessTexture !== undefined ) {
  1036. var textureIndex = metallicRoughness.metallicRoughnessTexture.index;
  1037. pending.push( parser.assignTexture( materialParams, 'metalnessMap', textureIndex ) );
  1038. pending.push( parser.assignTexture( materialParams, 'roughnessMap', textureIndex ) );
  1039. }
  1040. } else {
  1041. materialType = THREE.MeshPhongMaterial;
  1042. }
  1043. if ( material.doubleSided === true ) {
  1044. materialParams.side = THREE.DoubleSide;
  1045. }
  1046. var alphaMode = material.alphaMode || ALPHA_MODES.OPAQUE;
  1047. if ( alphaMode !== ALPHA_MODES.OPAQUE ) {
  1048. materialParams.transparent = true;
  1049. } else {
  1050. materialParams.transparent = false;
  1051. }
  1052. if ( material.normalTexture !== undefined ) {
  1053. pending.push( parser.assignTexture( materialParams, 'normalMap', material.normalTexture.index ) );
  1054. }
  1055. if ( material.occlusionTexture !== undefined ) {
  1056. pending.push( parser.assignTexture( materialParams, 'aoMap', material.occlusionTexture.index ) );
  1057. }
  1058. if ( material.emissiveFactor !== undefined ) {
  1059. if ( materialType === THREE.MeshBasicMaterial ) {
  1060. materialParams.color = new THREE.Color().fromArray( material.emissiveFactor );
  1061. } else {
  1062. materialParams.emissive = new THREE.Color().fromArray( material.emissiveFactor );
  1063. }
  1064. }
  1065. if ( material.emissiveTexture !== undefined ) {
  1066. if ( materialType === THREE.MeshBasicMaterial ) {
  1067. pending.push( parser.assignTexture( materialParams, 'map', material.emissiveTexture.index ) );
  1068. } else {
  1069. pending.push( parser.assignTexture( materialParams, 'emissiveMap', material.emissiveTexture.index ) );
  1070. }
  1071. }
  1072. return Promise.all( pending ).then( function () {
  1073. var _material;
  1074. if ( materialType === THREE.ShaderMaterial ) {
  1075. _material = extensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ].createMaterial( materialParams );
  1076. } else {
  1077. _material = new materialType( materialParams );
  1078. }
  1079. if ( material.name !== undefined ) _material.name = material.name;
  1080. // Normal map textures use OpenGL conventions:
  1081. // https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#materialnormaltexture
  1082. _material.normalScale.x = -1;
  1083. _material.userData = material.extras;
  1084. return _material;
  1085. } );
  1086. } );
  1087. };
  1088. GLTFParser.prototype.loadGeometries = function ( primitives ) {
  1089. return this._withDependencies( [
  1090. 'accessors',
  1091. 'bufferViews',
  1092. ] ).then( function ( dependencies ) {
  1093. return _each( primitives, function ( primitive ) {
  1094. var geometry = new THREE.BufferGeometry();
  1095. var attributes = primitive.attributes;
  1096. for ( var attributeId in attributes ) {
  1097. var attributeEntry = attributes[ attributeId ];
  1098. if ( attributeEntry === undefined ) return;
  1099. var bufferAttribute = dependencies.accessors[ attributeEntry ];
  1100. switch ( attributeId ) {
  1101. case 'POSITION':
  1102. geometry.addAttribute( 'position', bufferAttribute );
  1103. break;
  1104. case 'NORMAL':
  1105. geometry.addAttribute( 'normal', bufferAttribute );
  1106. break;
  1107. case 'TEXCOORD_0':
  1108. case 'TEXCOORD0':
  1109. case 'TEXCOORD':
  1110. geometry.addAttribute( 'uv', bufferAttribute );
  1111. break;
  1112. case 'TEXCOORD_1':
  1113. geometry.addAttribute( 'uv2', bufferAttribute );
  1114. break;
  1115. case 'COLOR_0':
  1116. case 'COLOR0':
  1117. case 'COLOR':
  1118. geometry.addAttribute( 'color', bufferAttribute );
  1119. break;
  1120. case 'WEIGHTS_0':
  1121. case 'WEIGHT': // WEIGHT semantic deprecated.
  1122. geometry.addAttribute( 'skinWeight', bufferAttribute );
  1123. break;
  1124. case 'JOINTS_0':
  1125. case 'JOINT': // JOINT semantic deprecated.
  1126. geometry.addAttribute( 'skinIndex', bufferAttribute );
  1127. break;
  1128. }
  1129. }
  1130. if ( primitive.indices !== undefined ) {
  1131. geometry.setIndex( dependencies.accessors[ primitive.indices ] );
  1132. }
  1133. return geometry;
  1134. } );
  1135. } );
  1136. };
  1137. /**
  1138. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#meshes
  1139. */
  1140. GLTFParser.prototype.loadMeshes = function () {
  1141. var scope = this;
  1142. var json = this.json;
  1143. return this._withDependencies( [
  1144. 'accessors',
  1145. 'materials'
  1146. ] ).then( function ( dependencies ) {
  1147. return _each( json.meshes, function ( meshDef ) {
  1148. var group = new THREE.Group();
  1149. if ( meshDef.name !== undefined ) group.name = meshDef.name;
  1150. if ( meshDef.extras ) group.userData = meshDef.extras;
  1151. var primitives = meshDef.primitives || [];
  1152. return scope.loadGeometries( primitives ).then( function ( geometries ) {
  1153. for ( var name in primitives ) {
  1154. var primitive = primitives[ name ];
  1155. var geometry = geometries[ name ];
  1156. var material = primitive.material === undefined
  1157. ? createDefaultMaterial()
  1158. : dependencies.materials[ primitive.material ];
  1159. if ( material.aoMap
  1160. && geometry.attributes.uv2 === undefined
  1161. && geometry.attributes.uv !== undefined ) {
  1162. console.log( 'THREE.GLTF2Loader: Duplicating UVs to support aoMap.' );
  1163. geometry.addAttribute( 'uv2', new THREE.BufferAttribute( geometry.attributes.uv.array, 2 ) );
  1164. }
  1165. if ( geometry.attributes.color !== undefined ) {
  1166. material.vertexColors = THREE.VertexColors;
  1167. material.needsUpdate = true;
  1168. }
  1169. if ( geometry.attributes.normal === undefined ) {
  1170. if ( material.flatShading !== undefined ) {
  1171. material.flatShading = true;
  1172. } else {
  1173. // TODO: Remove this backwards-compatibility fix after r87 release.
  1174. material.shading = THREE.FlatShading;
  1175. }
  1176. }
  1177. var mesh;
  1178. if ( primitive.mode === WEBGL_CONSTANTS.TRIANGLES || primitive.mode === undefined ) {
  1179. mesh = new THREE.Mesh( geometry, material );
  1180. } else if ( primitive.mode === WEBGL_CONSTANTS.TRIANGLE_STRIP ) {
  1181. mesh = new THREE.Mesh( geometry, material );
  1182. mesh.drawMode = THREE.TriangleStripDrawMode;
  1183. } else if ( primitive.mode === WEBGL_CONSTANTS.TRIANGLE_FAN ) {
  1184. mesh = new THREE.Mesh( geometry, material );
  1185. mesh.drawMode = THREE.TriangleFanDrawMode;
  1186. } else if ( primitive.mode === WEBGL_CONSTANTS.LINES ) {
  1187. mesh = new THREE.LineSegments( geometry, material );
  1188. } else if ( primitive.mode === WEBGL_CONSTANTS.LINE_STRIP ) {
  1189. mesh = new THREE.Line( geometry, material );
  1190. } else if ( primitive.mode === WEBGL_CONSTANTS.LINE_LOOP ) {
  1191. mesh = new THREE.LineLoop( geometry, material );
  1192. } else if ( primitive.mode === WEBGL_CONSTANTS.POINTS ) {
  1193. mesh = new THREE.Points( geometry, material );
  1194. } else {
  1195. throw new Error( 'THREE.GLTF2Loader: Primitive mode unsupported: ', primitive.mode );
  1196. }
  1197. mesh.name = group.name + '_' + name;
  1198. if ( primitive.targets !== undefined ) {
  1199. addMorphTargets( mesh, meshDef, primitive, dependencies );
  1200. }
  1201. if ( primitive.extras ) mesh.userData = primitive.extras;
  1202. group.add( mesh );
  1203. }
  1204. return group;
  1205. } );
  1206. } );
  1207. } );
  1208. };
  1209. /**
  1210. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#cameras
  1211. */
  1212. GLTFParser.prototype.loadCameras = function () {
  1213. var json = this.json;
  1214. return _each( json.cameras, function ( camera ) {
  1215. var _camera;
  1216. var params = camera[ camera.type ];
  1217. if ( !params ) {
  1218. console.warn( 'THREE.GLTF2Loader: Missing camera parameters.' );
  1219. return;
  1220. }
  1221. if ( camera.type === 'perspective' ) {
  1222. var aspectRatio = params.aspectRatio || 1;
  1223. var xfov = params.yfov * aspectRatio;
  1224. _camera = new THREE.PerspectiveCamera( THREE.Math.radToDeg( xfov ), aspectRatio, params.znear || 1, params.zfar || 2e6 );
  1225. } else if ( camera.type === 'orthographic' ) {
  1226. _camera = new THREE.OrthographicCamera( params.xmag / -2, params.xmag / 2, params.ymag / 2, params.ymag / -2, params.znear, params.zfar );
  1227. }
  1228. if ( camera.name !== undefined ) _camera.name = camera.name;
  1229. if ( camera.extras ) _camera.userData = camera.extras;
  1230. return _camera;
  1231. } );
  1232. };
  1233. GLTFParser.prototype.loadSkins = function () {
  1234. var json = this.json;
  1235. return this._withDependencies( [
  1236. 'accessors'
  1237. ] ).then( function ( dependencies ) {
  1238. return _each( json.skins, function ( skin ) {
  1239. var _skin = {
  1240. joints: skin.joints,
  1241. inverseBindMatrices: dependencies.accessors[ skin.inverseBindMatrices ]
  1242. };
  1243. return _skin;
  1244. } );
  1245. } );
  1246. };
  1247. GLTFParser.prototype.loadAnimations = function () {
  1248. var json = this.json;
  1249. return this._withDependencies( [
  1250. 'accessors',
  1251. 'nodes'
  1252. ] ).then( function ( dependencies ) {
  1253. return _each( json.animations, function ( animation, animationId ) {
  1254. var tracks = [];
  1255. for ( var channelId in animation.channels ) {
  1256. var channel = animation.channels[ channelId ];
  1257. var sampler = animation.samplers[ channel.sampler ];
  1258. if ( sampler ) {
  1259. var target = channel.target;
  1260. var name = target.node !== undefined ? target.node : target.id; // NOTE: target.id is deprecated.
  1261. var input = animation.parameters !== undefined ? animation.parameters[ sampler.input ] : sampler.input;
  1262. var output = animation.parameters !== undefined ? animation.parameters[ sampler.output ] : sampler.output;
  1263. var inputAccessor = dependencies.accessors[ input ];
  1264. var outputAccessor = dependencies.accessors[ output ];
  1265. var node = dependencies.nodes[ name ];
  1266. if ( node ) {
  1267. node.updateMatrix();
  1268. node.matrixAutoUpdate = true;
  1269. var TypedKeyframeTrack;
  1270. switch ( PATH_PROPERTIES[ target.path ] ) {
  1271. case PATH_PROPERTIES.weights:
  1272. TypedKeyframeTrack = THREE.NumberKeyframeTrack;
  1273. break;
  1274. case PATH_PROPERTIES.rotation:
  1275. TypedKeyframeTrack = THREE.QuaternionKeyframeTrack;
  1276. break;
  1277. case PATH_PROPERTIES.position:
  1278. case PATH_PROPERTIES.scale:
  1279. default:
  1280. TypedKeyframeTrack = THREE.VectorKeyframeTrack;
  1281. break;
  1282. }
  1283. var targetName = node.name ? node.name : node.uuid;
  1284. if ( sampler.interpolation === 'CATMULLROMSPLINE' ) {
  1285. console.warn( 'THREE.GLTF2Loader: CATMULLROMSPLINE interpolation is not supported. Using CUBICSPLINE instead.' );
  1286. }
  1287. var interpolation = sampler.interpolation !== undefined ? INTERPOLATION[ sampler.interpolation ] : THREE.InterpolateLinear;
  1288. var targetNames = [];
  1289. if ( PATH_PROPERTIES[ target.path ] === PATH_PROPERTIES.weights ) {
  1290. // node should be THREE.Group here but
  1291. // PATH_PROPERTIES.weights(morphTargetInfluences) should be
  1292. // the property of a mesh object under node.
  1293. // So finding targets here.
  1294. node.traverse( function ( object ) {
  1295. if ( object.isMesh === true && object.material.morphTargets === true ) {
  1296. targetNames.push( object.name ? object.name : object.uuid );
  1297. }
  1298. } );
  1299. } else {
  1300. targetNames.push( targetName );
  1301. }
  1302. // KeyframeTrack.optimize() will modify given 'times' and 'values'
  1303. // buffers before creating a truncated copy to keep. Because buffers may
  1304. // be reused by other tracks, make copies here.
  1305. for ( var i = 0, il = targetNames.length; i < il; i ++ ) {
  1306. tracks.push( new TypedKeyframeTrack(
  1307. targetNames[ i ] + '.' + PATH_PROPERTIES[ target.path ],
  1308. THREE.AnimationUtils.arraySlice( inputAccessor.array, 0 ),
  1309. THREE.AnimationUtils.arraySlice( outputAccessor.array, 0 ),
  1310. interpolation
  1311. ) );
  1312. }
  1313. }
  1314. }
  1315. }
  1316. var name = animation.name !== undefined ? animation.name : 'animation_' + animationId;
  1317. return new THREE.AnimationClip( name, undefined, tracks );
  1318. } );
  1319. } );
  1320. };
  1321. GLTFParser.prototype.loadNodes = function () {
  1322. var json = this.json;
  1323. var extensions = this.extensions;
  1324. var scope = this;
  1325. var nodes = json.nodes || [];
  1326. var skins = json.skins || [];
  1327. // Nothing in the node definition indicates whether it is a Bone or an
  1328. // Object3D. Use the skins' joint references to mark bones.
  1329. skins.forEach( function ( skin ) {
  1330. skin.joints.forEach( function ( id ) {
  1331. nodes[ id ].isBone = true;
  1332. } );
  1333. } );
  1334. return _each( json.nodes, function ( node ) {
  1335. var matrix = new THREE.Matrix4();
  1336. var _node = node.isBone === true ? new THREE.Bone() : new THREE.Object3D();
  1337. if ( node.name !== undefined ) {
  1338. _node.name = THREE.PropertyBinding.sanitizeNodeName( node.name );
  1339. }
  1340. if ( node.extras ) _node.userData = node.extras;
  1341. if ( node.matrix !== undefined ) {
  1342. matrix.fromArray( node.matrix );
  1343. _node.applyMatrix( matrix );
  1344. } else {
  1345. if ( node.translation !== undefined ) {
  1346. _node.position.fromArray( node.translation );
  1347. }
  1348. if ( node.rotation !== undefined ) {
  1349. _node.quaternion.fromArray( node.rotation );
  1350. }
  1351. if ( node.scale !== undefined ) {
  1352. _node.scale.fromArray( node.scale );
  1353. }
  1354. }
  1355. return _node;
  1356. } ).then( function ( __nodes ) {
  1357. return scope._withDependencies( [
  1358. 'meshes',
  1359. 'skins',
  1360. 'cameras'
  1361. ] ).then( function ( dependencies ) {
  1362. return _each( __nodes, function ( _node, nodeId ) {
  1363. var node = json.nodes[ nodeId ];
  1364. var meshes;
  1365. if ( node.mesh !== undefined) {
  1366. meshes = [ node.mesh ];
  1367. } else if ( node.meshes !== undefined ) {
  1368. console.warn( 'THREE.GLTF2Loader: Legacy glTF file detected. Nodes may have no more than one mesh.' );
  1369. meshes = node.meshes;
  1370. }
  1371. if ( meshes !== undefined ) {
  1372. for ( var meshId in meshes ) {
  1373. var mesh = meshes[ meshId ];
  1374. var group = dependencies.meshes[ mesh ];
  1375. if ( group === undefined ) {
  1376. console.warn( 'THREE.GLTF2Loader: Could not find node "' + mesh + '".' );
  1377. continue;
  1378. }
  1379. // do not clone children as they will be replaced anyway
  1380. var clonedgroup = group.clone( false );
  1381. for ( var childrenId in group.children ) {
  1382. var child = group.children[ childrenId ];
  1383. var originalChild = child;
  1384. // clone Mesh to add to _node
  1385. var originalMaterial = child.material;
  1386. var originalGeometry = child.geometry;
  1387. var originalInfluences = child.morphTargetInfluences;
  1388. var originalUserData = child.userData;
  1389. var originalName = child.name;
  1390. var material = originalMaterial;
  1391. switch ( child.type ) {
  1392. case 'LineSegments':
  1393. child = new THREE.LineSegments( originalGeometry, material );
  1394. break;
  1395. case 'LineLoop':
  1396. child = new THREE.LineLoop( originalGeometry, material );
  1397. break;
  1398. case 'Line':
  1399. child = new THREE.Line( originalGeometry, material );
  1400. break;
  1401. case 'Points':
  1402. child = new THREE.Points( originalGeometry, material );
  1403. break;
  1404. default:
  1405. child = new THREE.Mesh( originalGeometry, material );
  1406. child.drawMode = originalChild.drawMode;
  1407. }
  1408. child.castShadow = true;
  1409. child.morphTargetInfluences = originalInfluences;
  1410. child.userData = originalUserData;
  1411. child.name = originalName;
  1412. var skinEntry;
  1413. if ( node.skin !== undefined ) {
  1414. skinEntry = dependencies.skins[ node.skin ];
  1415. }
  1416. // Replace Mesh with SkinnedMesh in library
  1417. if ( skinEntry ) {
  1418. var geometry = originalGeometry;
  1419. material = originalMaterial;
  1420. material.skinning = true;
  1421. child = new THREE.SkinnedMesh( geometry, material );
  1422. child.castShadow = true;
  1423. child.userData = originalUserData;
  1424. child.name = originalName;
  1425. var bones = [];
  1426. var boneInverses = [];
  1427. for ( var i = 0, l = skinEntry.joints.length; i < l; i ++ ) {
  1428. var jointId = skinEntry.joints[ i ];
  1429. var jointNode = __nodes[ jointId ];
  1430. if ( jointNode ) {
  1431. bones.push( jointNode );
  1432. var m = skinEntry.inverseBindMatrices.array;
  1433. var mat = new THREE.Matrix4().fromArray( m, i * 16 );
  1434. boneInverses.push( mat );
  1435. } else {
  1436. console.warn( 'THREE.GLTF2Loader: Joint "%s" could not be found.', jointId );
  1437. }
  1438. }
  1439. child.bind( new THREE.Skeleton( bones, boneInverses ), child.matrixWorld );
  1440. }
  1441. clonedgroup.add( child );
  1442. }
  1443. _node.add( clonedgroup );
  1444. }
  1445. }
  1446. if ( node.camera !== undefined ) {
  1447. var camera = dependencies.cameras[ node.camera ];
  1448. _node.add( camera );
  1449. }
  1450. if ( node.extensions
  1451. && node.extensions[ EXTENSIONS.KHR_LIGHTS ]
  1452. && node.extensions[ EXTENSIONS.KHR_LIGHTS ].light !== undefined ) {
  1453. var lights = extensions[ EXTENSIONS.KHR_LIGHTS ].lights;
  1454. _node.add( lights[ node.extensions[ EXTENSIONS.KHR_LIGHTS ].light ] );
  1455. }
  1456. return _node;
  1457. } );
  1458. } );
  1459. } );
  1460. };
  1461. GLTFParser.prototype.loadScenes = function () {
  1462. var json = this.json;
  1463. var extensions = this.extensions;
  1464. // scene node hierachy builder
  1465. function buildNodeHierachy( nodeId, parentObject, allNodes ) {
  1466. var _node = allNodes[ nodeId ];
  1467. parentObject.add( _node );
  1468. var node = json.nodes[ nodeId ];
  1469. if ( node.children ) {
  1470. var children = node.children;
  1471. for ( var i = 0, l = children.length; i < l; i ++ ) {
  1472. var child = children[ i ];
  1473. buildNodeHierachy( child, _node, allNodes );
  1474. }
  1475. }
  1476. }
  1477. return this._withDependencies( [
  1478. 'nodes'
  1479. ] ).then( function ( dependencies ) {
  1480. return _each( json.scenes, function ( scene ) {
  1481. var _scene = new THREE.Scene();
  1482. if ( scene.name !== undefined ) _scene.name = scene.name;
  1483. if ( scene.extras ) _scene.userData = scene.extras;
  1484. var nodes = scene.nodes || [];
  1485. for ( var i = 0, l = nodes.length; i < l; i ++ ) {
  1486. var nodeId = nodes[ i ];
  1487. buildNodeHierachy( nodeId, _scene, dependencies.nodes );
  1488. }
  1489. _scene.traverse( function ( child ) {
  1490. // for Specular-Glossiness.
  1491. if ( child.material && child.material.isGLTFSpecularGlossinessMaterial ) {
  1492. child.onBeforeRender = extensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ].refreshUniforms;
  1493. }
  1494. } );
  1495. // Ambient lighting, if present, is always attached to the scene root.
  1496. if ( scene.extensions
  1497. && scene.extensions[ EXTENSIONS.KHR_LIGHTS ]
  1498. && scene.extensions[ EXTENSIONS.KHR_LIGHTS ].light !== undefined ) {
  1499. var lights = extensions[ EXTENSIONS.KHR_LIGHTS ].lights;
  1500. _scene.add( lights[ scene.extensions[ EXTENSIONS.KHR_LIGHTS ].light ] );
  1501. }
  1502. return _scene;
  1503. } );
  1504. } );
  1505. };
  1506. return GLTF2Loader;
  1507. } )();