GLTFLoader.js 63 KB

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