GLTFLoader.js 58 KB

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