GLTFLoader.js 69 KB

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