GLTF2Loader.js 56 KB

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