GLTFLoader.js 79 KB

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