GLTFLoader.js 59 KB

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