GLTFLoader.js 95 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875
  1. THREE.GLTFLoader = ( function () {
  2. function GLTFLoader( manager ) {
  3. THREE.Loader.call( this, manager );
  4. this.dracoLoader = null;
  5. this.ddsLoader = null;
  6. this.ktx2Loader = null;
  7. this.meshoptDecoder = null;
  8. this.pluginCallbacks = [];
  9. this.register( function ( parser ) {
  10. return new GLTFMaterialsClearcoatExtension( parser );
  11. } );
  12. this.register( function ( parser ) {
  13. return new GLTFTextureBasisUExtension( parser );
  14. } );
  15. this.register( function ( parser ) {
  16. return new GLTFTextureWebPExtension( parser );
  17. } );
  18. this.register( function ( parser ) {
  19. return new GLTFMaterialsTransmissionExtension( parser );
  20. } );
  21. this.register( function ( parser ) {
  22. return new GLTFLightsExtension( parser );
  23. } );
  24. this.register( function ( parser ) {
  25. return new GLTFMeshoptCompression( parser );
  26. } );
  27. }
  28. GLTFLoader.prototype = Object.assign( Object.create( THREE.Loader.prototype ), {
  29. constructor: GLTFLoader,
  30. load: function ( url, onLoad, onProgress, onError ) {
  31. var scope = this;
  32. var resourcePath;
  33. if ( this.resourcePath !== '' ) {
  34. resourcePath = this.resourcePath;
  35. } else if ( this.path !== '' ) {
  36. resourcePath = this.path;
  37. } else {
  38. resourcePath = THREE.LoaderUtils.extractUrlBase( url );
  39. }
  40. // Tells the LoadingManager to track an extra item, which resolves after
  41. // the model is fully loaded. This means the count of items loaded will
  42. // be incorrect, but ensures manager.onLoad() does not fire early.
  43. this.manager.itemStart( url );
  44. var _onError = function ( e ) {
  45. if ( onError ) {
  46. onError( e );
  47. } else {
  48. console.error( e );
  49. }
  50. scope.manager.itemError( url );
  51. scope.manager.itemEnd( url );
  52. };
  53. var loader = new THREE.FileLoader( this.manager );
  54. loader.setPath( this.path );
  55. loader.setResponseType( 'arraybuffer' );
  56. loader.setRequestHeader( this.requestHeader );
  57. loader.setWithCredentials( this.withCredentials );
  58. loader.load( url, function ( data ) {
  59. try {
  60. scope.parse( data, resourcePath, function ( gltf ) {
  61. onLoad( gltf );
  62. scope.manager.itemEnd( url );
  63. }, _onError );
  64. } catch ( e ) {
  65. _onError( e );
  66. }
  67. }, onProgress, _onError );
  68. },
  69. setDRACOLoader: function ( dracoLoader ) {
  70. this.dracoLoader = dracoLoader;
  71. return this;
  72. },
  73. setDDSLoader: function ( ddsLoader ) {
  74. this.ddsLoader = ddsLoader;
  75. return this;
  76. },
  77. setKTX2Loader: function ( ktx2Loader ) {
  78. this.ktx2Loader = ktx2Loader;
  79. return this;
  80. },
  81. setMeshoptDecoder: function ( meshoptDecoder ) {
  82. this.meshoptDecoder = meshoptDecoder;
  83. return this;
  84. },
  85. register: function ( callback ) {
  86. if ( this.pluginCallbacks.indexOf( callback ) === - 1 ) {
  87. this.pluginCallbacks.push( callback );
  88. }
  89. return this;
  90. },
  91. unregister: function ( callback ) {
  92. if ( this.pluginCallbacks.indexOf( callback ) !== - 1 ) {
  93. this.pluginCallbacks.splice( this.pluginCallbacks.indexOf( callback ), 1 );
  94. }
  95. return this;
  96. },
  97. parse: function ( data, path, onLoad, onError ) {
  98. var content;
  99. var extensions = {};
  100. var plugins = {};
  101. if ( typeof data === 'string' ) {
  102. content = data;
  103. } else {
  104. var magic = THREE.LoaderUtils.decodeText( new Uint8Array( data, 0, 4 ) );
  105. if ( magic === BINARY_EXTENSION_HEADER_MAGIC ) {
  106. try {
  107. extensions[ EXTENSIONS.KHR_BINARY_GLTF ] = new GLTFBinaryExtension( data );
  108. } catch ( error ) {
  109. if ( onError ) onError( error );
  110. return;
  111. }
  112. content = extensions[ EXTENSIONS.KHR_BINARY_GLTF ].content;
  113. } else {
  114. content = THREE.LoaderUtils.decodeText( new Uint8Array( data ) );
  115. }
  116. }
  117. var json = JSON.parse( content );
  118. if ( json.asset === undefined || json.asset.version[ 0 ] < 2 ) {
  119. if ( onError ) onError( new Error( 'THREE.GLTFLoader: Unsupported asset. glTF versions >=2.0 are supported.' ) );
  120. return;
  121. }
  122. var parser = new GLTFParser( json, {
  123. path: path || this.resourcePath || '',
  124. crossOrigin: this.crossOrigin,
  125. manager: this.manager,
  126. ktx2Loader: this.ktx2Loader,
  127. meshoptDecoder: this.meshoptDecoder
  128. } );
  129. parser.fileLoader.setRequestHeader( this.requestHeader );
  130. for ( var i = 0; i < this.pluginCallbacks.length; i ++ ) {
  131. var plugin = this.pluginCallbacks[ i ]( parser );
  132. plugins[ plugin.name ] = plugin;
  133. // Workaround to avoid determining as unknown extension
  134. // in addUnknownExtensionsToUserData().
  135. // Remove this workaround if we move all the existing
  136. // extension handlers to plugin system
  137. extensions[ plugin.name ] = true;
  138. }
  139. if ( json.extensionsUsed ) {
  140. for ( var i = 0; i < json.extensionsUsed.length; ++ i ) {
  141. var extensionName = json.extensionsUsed[ i ];
  142. var extensionsRequired = json.extensionsRequired || [];
  143. switch ( extensionName ) {
  144. case EXTENSIONS.KHR_MATERIALS_UNLIT:
  145. extensions[ extensionName ] = new GLTFMaterialsUnlitExtension();
  146. break;
  147. case EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS:
  148. extensions[ extensionName ] = new GLTFMaterialsPbrSpecularGlossinessExtension();
  149. break;
  150. case EXTENSIONS.KHR_DRACO_MESH_COMPRESSION:
  151. extensions[ extensionName ] = new GLTFDracoMeshCompressionExtension( json, this.dracoLoader );
  152. break;
  153. case EXTENSIONS.MSFT_TEXTURE_DDS:
  154. extensions[ extensionName ] = new GLTFTextureDDSExtension( this.ddsLoader );
  155. break;
  156. case EXTENSIONS.KHR_TEXTURE_TRANSFORM:
  157. extensions[ extensionName ] = new GLTFTextureTransformExtension();
  158. break;
  159. case EXTENSIONS.KHR_MESH_QUANTIZATION:
  160. extensions[ extensionName ] = new GLTFMeshQuantizationExtension();
  161. break;
  162. default:
  163. if ( extensionsRequired.indexOf( extensionName ) >= 0 && plugins[ extensionName ] === undefined ) {
  164. console.warn( 'THREE.GLTFLoader: Unknown extension "' + extensionName + '".' );
  165. }
  166. }
  167. }
  168. }
  169. parser.setExtensions( extensions );
  170. parser.setPlugins( plugins );
  171. parser.parse( onLoad, onError );
  172. }
  173. } );
  174. /* GLTFREGISTRY */
  175. function GLTFRegistry() {
  176. var objects = {};
  177. return {
  178. get: function ( key ) {
  179. return objects[ key ];
  180. },
  181. add: function ( key, object ) {
  182. objects[ key ] = object;
  183. },
  184. remove: function ( key ) {
  185. delete objects[ key ];
  186. },
  187. removeAll: function () {
  188. objects = {};
  189. }
  190. };
  191. }
  192. /*********************************/
  193. /********** EXTENSIONS ***********/
  194. /*********************************/
  195. var EXTENSIONS = {
  196. KHR_BINARY_GLTF: 'KHR_binary_glTF',
  197. KHR_DRACO_MESH_COMPRESSION: 'KHR_draco_mesh_compression',
  198. KHR_LIGHTS_PUNCTUAL: 'KHR_lights_punctual',
  199. KHR_MATERIALS_CLEARCOAT: 'KHR_materials_clearcoat',
  200. KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS: 'KHR_materials_pbrSpecularGlossiness',
  201. KHR_MATERIALS_TRANSMISSION: 'KHR_materials_transmission',
  202. KHR_MATERIALS_UNLIT: 'KHR_materials_unlit',
  203. KHR_TEXTURE_BASISU: 'KHR_texture_basisu',
  204. KHR_TEXTURE_TRANSFORM: 'KHR_texture_transform',
  205. KHR_MESH_QUANTIZATION: 'KHR_mesh_quantization',
  206. EXT_TEXTURE_WEBP: 'EXT_texture_webp',
  207. EXT_MESHOPT_COMPRESSION: 'EXT_meshopt_compression',
  208. MSFT_TEXTURE_DDS: 'MSFT_texture_dds'
  209. };
  210. /**
  211. * DDS Texture Extension
  212. *
  213. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/MSFT_texture_dds
  214. *
  215. */
  216. function GLTFTextureDDSExtension( ddsLoader ) {
  217. if ( ! ddsLoader ) {
  218. throw new Error( 'THREE.GLTFLoader: Attempting to load .dds texture without importing THREE.DDSLoader' );
  219. }
  220. this.name = EXTENSIONS.MSFT_TEXTURE_DDS;
  221. this.ddsLoader = ddsLoader;
  222. }
  223. /**
  224. * Punctual Lights Extension
  225. *
  226. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_lights_punctual
  227. */
  228. function GLTFLightsExtension( parser ) {
  229. this.parser = parser;
  230. this.name = EXTENSIONS.KHR_LIGHTS_PUNCTUAL;
  231. // Object3D instance caches
  232. this.cache = { refs: {}, uses: {} };
  233. }
  234. GLTFLightsExtension.prototype._markDefs = function () {
  235. var parser = this.parser;
  236. var nodeDefs = this.parser.json.nodes || [];
  237. for ( var nodeIndex = 0, nodeLength = nodeDefs.length; nodeIndex < nodeLength; nodeIndex ++ ) {
  238. var nodeDef = nodeDefs[ nodeIndex ];
  239. if ( nodeDef.extensions
  240. && nodeDef.extensions[ this.name ]
  241. && nodeDef.extensions[ this.name ].light !== undefined ) {
  242. parser._addNodeRef( this.cache, nodeDef.extensions[ this.name ].light );
  243. }
  244. }
  245. };
  246. GLTFLightsExtension.prototype._loadLight = function ( lightIndex ) {
  247. var parser = this.parser;
  248. var cacheKey = 'light:' + lightIndex;
  249. var dependency = parser.cache.get( cacheKey );
  250. if ( dependency ) return dependency;
  251. var json = parser.json;
  252. var extensions = ( json.extensions && json.extensions[ this.name ] ) || {};
  253. var lightDefs = extensions.lights || [];
  254. var lightDef = lightDefs[ lightIndex ];
  255. var lightNode;
  256. var color = new THREE.Color( 0xffffff );
  257. if ( lightDef.color !== undefined ) color.fromArray( lightDef.color );
  258. var range = lightDef.range !== undefined ? lightDef.range : 0;
  259. switch ( lightDef.type ) {
  260. case 'directional':
  261. lightNode = new THREE.DirectionalLight( color );
  262. lightNode.target.position.set( 0, 0, - 1 );
  263. lightNode.add( lightNode.target );
  264. break;
  265. case 'point':
  266. lightNode = new THREE.PointLight( color );
  267. lightNode.distance = range;
  268. break;
  269. case 'spot':
  270. lightNode = new THREE.SpotLight( color );
  271. lightNode.distance = range;
  272. // Handle spotlight properties.
  273. lightDef.spot = lightDef.spot || {};
  274. lightDef.spot.innerConeAngle = lightDef.spot.innerConeAngle !== undefined ? lightDef.spot.innerConeAngle : 0;
  275. lightDef.spot.outerConeAngle = lightDef.spot.outerConeAngle !== undefined ? lightDef.spot.outerConeAngle : Math.PI / 4.0;
  276. lightNode.angle = lightDef.spot.outerConeAngle;
  277. lightNode.penumbra = 1.0 - lightDef.spot.innerConeAngle / lightDef.spot.outerConeAngle;
  278. lightNode.target.position.set( 0, 0, - 1 );
  279. lightNode.add( lightNode.target );
  280. break;
  281. default:
  282. throw new Error( 'THREE.GLTFLoader: Unexpected light type: ' + lightDef.type );
  283. }
  284. // Some lights (e.g. spot) default to a position other than the origin. Reset the position
  285. // here, because node-level parsing will only override position if explicitly specified.
  286. lightNode.position.set( 0, 0, 0 );
  287. lightNode.decay = 2;
  288. if ( lightDef.intensity !== undefined ) lightNode.intensity = lightDef.intensity;
  289. lightNode.name = parser.createUniqueName( lightDef.name || ( 'light_' + lightIndex ) );
  290. dependency = Promise.resolve( lightNode );
  291. parser.cache.add( cacheKey, dependency );
  292. return dependency;
  293. };
  294. GLTFLightsExtension.prototype.createNodeAttachment = function ( nodeIndex ) {
  295. var self = this;
  296. var parser = this.parser;
  297. var json = parser.json;
  298. var nodeDef = json.nodes[ nodeIndex ];
  299. var lightDef = ( nodeDef.extensions && nodeDef.extensions[ this.name ] ) || {};
  300. var lightIndex = lightDef.light;
  301. if ( lightIndex === undefined ) return null;
  302. return this._loadLight( lightIndex ).then( function ( light ) {
  303. return parser._getNodeRef( self.cache, lightIndex, light );
  304. } );
  305. };
  306. /**
  307. * Unlit Materials Extension
  308. *
  309. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_unlit
  310. */
  311. function GLTFMaterialsUnlitExtension() {
  312. this.name = EXTENSIONS.KHR_MATERIALS_UNLIT;
  313. }
  314. GLTFMaterialsUnlitExtension.prototype.getMaterialType = function () {
  315. return THREE.MeshBasicMaterial;
  316. };
  317. GLTFMaterialsUnlitExtension.prototype.extendParams = function ( materialParams, materialDef, parser ) {
  318. var pending = [];
  319. materialParams.color = new THREE.Color( 1.0, 1.0, 1.0 );
  320. materialParams.opacity = 1.0;
  321. var metallicRoughness = materialDef.pbrMetallicRoughness;
  322. if ( metallicRoughness ) {
  323. if ( Array.isArray( metallicRoughness.baseColorFactor ) ) {
  324. var array = metallicRoughness.baseColorFactor;
  325. materialParams.color.fromArray( array );
  326. materialParams.opacity = array[ 3 ];
  327. }
  328. if ( metallicRoughness.baseColorTexture !== undefined ) {
  329. pending.push( parser.assignTexture( materialParams, 'map', metallicRoughness.baseColorTexture ) );
  330. }
  331. }
  332. return Promise.all( pending );
  333. };
  334. /**
  335. * Clearcoat Materials Extension
  336. *
  337. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_clearcoat
  338. */
  339. function GLTFMaterialsClearcoatExtension( parser ) {
  340. this.parser = parser;
  341. this.name = EXTENSIONS.KHR_MATERIALS_CLEARCOAT;
  342. }
  343. GLTFMaterialsClearcoatExtension.prototype.getMaterialType = function ( materialIndex ) {
  344. var parser = this.parser;
  345. var materialDef = parser.json.materials[ materialIndex ];
  346. if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) return null;
  347. return THREE.MeshPhysicalMaterial;
  348. };
  349. GLTFMaterialsClearcoatExtension.prototype.extendMaterialParams = function ( materialIndex, materialParams ) {
  350. var parser = this.parser;
  351. var materialDef = parser.json.materials[ materialIndex ];
  352. if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) {
  353. return Promise.resolve();
  354. }
  355. var pending = [];
  356. var extension = materialDef.extensions[ this.name ];
  357. if ( extension.clearcoatFactor !== undefined ) {
  358. materialParams.clearcoat = extension.clearcoatFactor;
  359. }
  360. if ( extension.clearcoatTexture !== undefined ) {
  361. pending.push( parser.assignTexture( materialParams, 'clearcoatMap', extension.clearcoatTexture ) );
  362. }
  363. if ( extension.clearcoatRoughnessFactor !== undefined ) {
  364. materialParams.clearcoatRoughness = extension.clearcoatRoughnessFactor;
  365. }
  366. if ( extension.clearcoatRoughnessTexture !== undefined ) {
  367. pending.push( parser.assignTexture( materialParams, 'clearcoatRoughnessMap', extension.clearcoatRoughnessTexture ) );
  368. }
  369. if ( extension.clearcoatNormalTexture !== undefined ) {
  370. pending.push( parser.assignTexture( materialParams, 'clearcoatNormalMap', extension.clearcoatNormalTexture ) );
  371. if ( extension.clearcoatNormalTexture.scale !== undefined ) {
  372. var scale = extension.clearcoatNormalTexture.scale;
  373. // https://github.com/mrdoob/three.js/issues/11438#issuecomment-507003995
  374. materialParams.clearcoatNormalScale = new THREE.Vector2( scale, -scale );
  375. }
  376. }
  377. return Promise.all( pending );
  378. };
  379. /**
  380. * Transmission Materials Extension
  381. *
  382. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_transmission
  383. * Draft: https://github.com/KhronosGroup/glTF/pull/1698
  384. */
  385. function GLTFMaterialsTransmissionExtension( parser ) {
  386. this.parser = parser;
  387. this.name = EXTENSIONS.KHR_MATERIALS_TRANSMISSION;
  388. }
  389. GLTFMaterialsTransmissionExtension.prototype.getMaterialType = function ( materialIndex ) {
  390. var parser = this.parser;
  391. var materialDef = parser.json.materials[ materialIndex ];
  392. if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) return null;
  393. return THREE.MeshPhysicalMaterial;
  394. };
  395. GLTFMaterialsTransmissionExtension.prototype.extendMaterialParams = function ( materialIndex, materialParams ) {
  396. var parser = this.parser;
  397. var materialDef = parser.json.materials[ materialIndex ];
  398. if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) {
  399. return Promise.resolve();
  400. }
  401. var pending = [];
  402. var extension = materialDef.extensions[ this.name ];
  403. if ( extension.transmissionFactor !== undefined ) {
  404. materialParams.transmission = extension.transmissionFactor;
  405. }
  406. if ( extension.transmissionTexture !== undefined ) {
  407. pending.push( parser.assignTexture( materialParams, 'transmissionMap', extension.transmissionTexture ) );
  408. }
  409. return Promise.all( pending );
  410. };
  411. /**
  412. * BasisU Texture Extension
  413. *
  414. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_texture_basisu
  415. */
  416. function GLTFTextureBasisUExtension( parser ) {
  417. this.parser = parser;
  418. this.name = EXTENSIONS.KHR_TEXTURE_BASISU;
  419. }
  420. GLTFTextureBasisUExtension.prototype.loadTexture = function ( textureIndex ) {
  421. var parser = this.parser;
  422. var json = parser.json;
  423. var textureDef = json.textures[ textureIndex ];
  424. if ( ! textureDef.extensions || ! textureDef.extensions[ this.name ] ) {
  425. return null;
  426. }
  427. var extension = textureDef.extensions[ this.name ];
  428. var source = json.images[ extension.source ];
  429. var loader = parser.options.ktx2Loader;
  430. if ( ! loader ) {
  431. if ( json.extensionsRequired && json.extensionsRequired.indexOf( this.name ) >= 0 ) {
  432. throw new Error( 'THREE.GLTFLoader: setKTX2Loader must be called before loading KTX2 textures' );
  433. } else {
  434. // Assumes that the extension is optional and that a fallback texture is present
  435. return null;
  436. }
  437. }
  438. return parser.loadTextureImage( textureIndex, source, loader );
  439. };
  440. /**
  441. * WebP Texture Extension
  442. *
  443. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/EXT_texture_webp
  444. */
  445. function GLTFTextureWebPExtension( parser ) {
  446. this.parser = parser;
  447. this.name = EXTENSIONS.EXT_TEXTURE_WEBP;
  448. this.isSupported = null;
  449. }
  450. GLTFTextureWebPExtension.prototype.loadTexture = function ( textureIndex ) {
  451. var name = this.name;
  452. var parser = this.parser;
  453. var json = parser.json;
  454. var textureDef = json.textures[ textureIndex ];
  455. if ( ! textureDef.extensions || ! textureDef.extensions[ name ] ) {
  456. return null;
  457. }
  458. var extension = textureDef.extensions[ name ];
  459. var source = json.images[ extension.source ];
  460. var loader = source.uri ? parser.options.manager.getHandler( source.uri ) : parser.textureLoader;
  461. return this.detectSupport().then( function ( isSupported ) {
  462. if ( isSupported ) return parser.loadTextureImage( textureIndex, source, loader );
  463. if ( json.extensionsRequired && json.extensionsRequired.indexOf( name ) >= 0 ) {
  464. throw new Error( 'THREE.GLTFLoader: WebP required by asset but unsupported.' );
  465. }
  466. // Fall back to PNG or JPEG.
  467. return parser.loadTexture( textureIndex );
  468. } );
  469. };
  470. GLTFTextureWebPExtension.prototype.detectSupport = function () {
  471. if ( ! this.isSupported ) {
  472. this.isSupported = new Promise( function ( resolve ) {
  473. var image = new Image();
  474. // Lossy test image. Support for lossy images doesn't guarantee support for all
  475. // WebP images, unfortunately.
  476. image.src = 'data:image/webp;base64,UklGRiIAAABXRUJQVlA4IBYAAAAwAQCdASoBAAEADsD+JaQAA3AAAAAA';
  477. image.onload = image.onerror = function () {
  478. resolve( image.height === 1 );
  479. };
  480. } );
  481. }
  482. return this.isSupported;
  483. };
  484. /**
  485. * meshopt BufferView Compression Extension
  486. *
  487. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/EXT_meshopt_compression
  488. */
  489. function GLTFMeshoptCompression( parser ) {
  490. this.name = EXTENSIONS.EXT_MESHOPT_COMPRESSION;
  491. this.parser = parser;
  492. }
  493. GLTFMeshoptCompression.prototype.loadBufferView = function ( index ) {
  494. var json = this.parser.json;
  495. var bufferView = json.bufferViews[ index ];
  496. if ( bufferView.extensions && bufferView.extensions[ this.name ] ) {
  497. var extensionDef = bufferView.extensions[ this.name ];
  498. var buffer = this.parser.getDependency( 'buffer', extensionDef.buffer );
  499. var decoder = this.parser.options.meshoptDecoder;
  500. if ( ! decoder || ! decoder.supported ) {
  501. if ( json.extensionsRequired && json.extensionsRequired.indexOf( this.name ) >= 0 ) {
  502. throw new Error( 'THREE.GLTFLoader: setMeshoptDecoder must be called before loading compressed files' );
  503. } else {
  504. // Assumes that the extension is optional and that fallback buffer data is present
  505. return null;
  506. }
  507. }
  508. return Promise.all( [ buffer, decoder.ready ] ).then( function ( res ) {
  509. var byteOffset = extensionDef.byteOffset || 0;
  510. var byteLength = extensionDef.byteLength || 0;
  511. var count = extensionDef.count;
  512. var stride = extensionDef.byteStride;
  513. var result = new ArrayBuffer( count * stride );
  514. var source = new Uint8Array( res[ 0 ], byteOffset, byteLength );
  515. decoder.decodeGltfBuffer( new Uint8Array( result ), count, stride, source, extensionDef.mode, extensionDef.filter );
  516. return result;
  517. } );
  518. } else {
  519. return null;
  520. }
  521. };
  522. /* BINARY EXTENSION */
  523. var BINARY_EXTENSION_HEADER_MAGIC = 'glTF';
  524. var BINARY_EXTENSION_HEADER_LENGTH = 12;
  525. var BINARY_EXTENSION_CHUNK_TYPES = { JSON: 0x4E4F534A, BIN: 0x004E4942 };
  526. function GLTFBinaryExtension( data ) {
  527. this.name = EXTENSIONS.KHR_BINARY_GLTF;
  528. this.content = null;
  529. this.body = null;
  530. var headerView = new DataView( data, 0, BINARY_EXTENSION_HEADER_LENGTH );
  531. this.header = {
  532. magic: THREE.LoaderUtils.decodeText( new Uint8Array( data.slice( 0, 4 ) ) ),
  533. version: headerView.getUint32( 4, true ),
  534. length: headerView.getUint32( 8, true )
  535. };
  536. if ( this.header.magic !== BINARY_EXTENSION_HEADER_MAGIC ) {
  537. throw new Error( 'THREE.GLTFLoader: Unsupported glTF-Binary header.' );
  538. } else if ( this.header.version < 2.0 ) {
  539. throw new Error( 'THREE.GLTFLoader: Legacy binary file detected.' );
  540. }
  541. var chunkContentsLength = this.header.length - BINARY_EXTENSION_HEADER_LENGTH;
  542. var chunkView = new DataView( data, BINARY_EXTENSION_HEADER_LENGTH );
  543. var chunkIndex = 0;
  544. while ( chunkIndex < chunkContentsLength ) {
  545. var chunkLength = chunkView.getUint32( chunkIndex, true );
  546. chunkIndex += 4;
  547. var chunkType = chunkView.getUint32( chunkIndex, true );
  548. chunkIndex += 4;
  549. if ( chunkType === BINARY_EXTENSION_CHUNK_TYPES.JSON ) {
  550. var contentArray = new Uint8Array( data, BINARY_EXTENSION_HEADER_LENGTH + chunkIndex, chunkLength );
  551. this.content = THREE.LoaderUtils.decodeText( contentArray );
  552. } else if ( chunkType === BINARY_EXTENSION_CHUNK_TYPES.BIN ) {
  553. var byteOffset = BINARY_EXTENSION_HEADER_LENGTH + chunkIndex;
  554. this.body = data.slice( byteOffset, byteOffset + chunkLength );
  555. }
  556. // Clients must ignore chunks with unknown types.
  557. chunkIndex += chunkLength;
  558. }
  559. if ( this.content === null ) {
  560. throw new Error( 'THREE.GLTFLoader: JSON content not found.' );
  561. }
  562. }
  563. /**
  564. * DRACO Mesh Compression Extension
  565. *
  566. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_draco_mesh_compression
  567. */
  568. function GLTFDracoMeshCompressionExtension( json, dracoLoader ) {
  569. if ( ! dracoLoader ) {
  570. throw new Error( 'THREE.GLTFLoader: No DRACOLoader instance provided.' );
  571. }
  572. this.name = EXTENSIONS.KHR_DRACO_MESH_COMPRESSION;
  573. this.json = json;
  574. this.dracoLoader = dracoLoader;
  575. this.dracoLoader.preload();
  576. }
  577. GLTFDracoMeshCompressionExtension.prototype.decodePrimitive = function ( primitive, parser ) {
  578. var json = this.json;
  579. var dracoLoader = this.dracoLoader;
  580. var bufferViewIndex = primitive.extensions[ this.name ].bufferView;
  581. var gltfAttributeMap = primitive.extensions[ this.name ].attributes;
  582. var threeAttributeMap = {};
  583. var attributeNormalizedMap = {};
  584. var attributeTypeMap = {};
  585. for ( var attributeName in gltfAttributeMap ) {
  586. var threeAttributeName = ATTRIBUTES[ attributeName ] || attributeName.toLowerCase();
  587. threeAttributeMap[ threeAttributeName ] = gltfAttributeMap[ attributeName ];
  588. }
  589. for ( attributeName in primitive.attributes ) {
  590. var threeAttributeName = ATTRIBUTES[ attributeName ] || attributeName.toLowerCase();
  591. if ( gltfAttributeMap[ attributeName ] !== undefined ) {
  592. var accessorDef = json.accessors[ primitive.attributes[ attributeName ] ];
  593. var componentType = WEBGL_COMPONENT_TYPES[ accessorDef.componentType ];
  594. attributeTypeMap[ threeAttributeName ] = componentType;
  595. attributeNormalizedMap[ threeAttributeName ] = accessorDef.normalized === true;
  596. }
  597. }
  598. return parser.getDependency( 'bufferView', bufferViewIndex ).then( function ( bufferView ) {
  599. return new Promise( function ( resolve ) {
  600. dracoLoader.decodeDracoFile( bufferView, function ( geometry ) {
  601. for ( var attributeName in geometry.attributes ) {
  602. var attribute = geometry.attributes[ attributeName ];
  603. var normalized = attributeNormalizedMap[ attributeName ];
  604. if ( normalized !== undefined ) attribute.normalized = normalized;
  605. }
  606. resolve( geometry );
  607. }, threeAttributeMap, attributeTypeMap );
  608. } );
  609. } );
  610. };
  611. /**
  612. * Texture Transform Extension
  613. *
  614. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_texture_transform
  615. */
  616. function GLTFTextureTransformExtension() {
  617. this.name = EXTENSIONS.KHR_TEXTURE_TRANSFORM;
  618. }
  619. GLTFTextureTransformExtension.prototype.extendTexture = function ( texture, transform ) {
  620. texture = texture.clone();
  621. if ( transform.offset !== undefined ) {
  622. texture.offset.fromArray( transform.offset );
  623. }
  624. if ( transform.rotation !== undefined ) {
  625. texture.rotation = transform.rotation;
  626. }
  627. if ( transform.scale !== undefined ) {
  628. texture.repeat.fromArray( transform.scale );
  629. }
  630. if ( transform.texCoord !== undefined ) {
  631. console.warn( 'THREE.GLTFLoader: Custom UV sets in "' + this.name + '" extension not yet supported.' );
  632. }
  633. texture.needsUpdate = true;
  634. return texture;
  635. };
  636. /**
  637. * Specular-Glossiness Extension
  638. *
  639. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_pbrSpecularGlossiness
  640. */
  641. /**
  642. * A sub class of THREE.StandardMaterial with some of the functionality
  643. * changed via the `onBeforeCompile` callback
  644. * @pailhead
  645. */
  646. function GLTFMeshStandardSGMaterial( params ) {
  647. THREE.MeshStandardMaterial.call( this );
  648. this.isGLTFSpecularGlossinessMaterial = true;
  649. //various chunks that need replacing
  650. var specularMapParsFragmentChunk = [
  651. '#ifdef USE_SPECULARMAP',
  652. ' uniform sampler2D specularMap;',
  653. '#endif'
  654. ].join( '\n' );
  655. var glossinessMapParsFragmentChunk = [
  656. '#ifdef USE_GLOSSINESSMAP',
  657. ' uniform sampler2D glossinessMap;',
  658. '#endif'
  659. ].join( '\n' );
  660. var specularMapFragmentChunk = [
  661. 'vec3 specularFactor = specular;',
  662. '#ifdef USE_SPECULARMAP',
  663. ' vec4 texelSpecular = texture2D( specularMap, vUv );',
  664. ' texelSpecular = sRGBToLinear( texelSpecular );',
  665. ' // reads channel RGB, compatible with a glTF Specular-Glossiness (RGBA) texture',
  666. ' specularFactor *= texelSpecular.rgb;',
  667. '#endif'
  668. ].join( '\n' );
  669. var glossinessMapFragmentChunk = [
  670. 'float glossinessFactor = glossiness;',
  671. '#ifdef USE_GLOSSINESSMAP',
  672. ' vec4 texelGlossiness = texture2D( glossinessMap, vUv );',
  673. ' // reads channel A, compatible with a glTF Specular-Glossiness (RGBA) texture',
  674. ' glossinessFactor *= texelGlossiness.a;',
  675. '#endif'
  676. ].join( '\n' );
  677. var lightPhysicalFragmentChunk = [
  678. 'PhysicalMaterial material;',
  679. 'material.diffuseColor = diffuseColor.rgb * ( 1. - max( specularFactor.r, max( specularFactor.g, specularFactor.b ) ) );',
  680. 'vec3 dxy = max( abs( dFdx( geometryNormal ) ), abs( dFdy( geometryNormal ) ) );',
  681. 'float geometryRoughness = max( max( dxy.x, dxy.y ), dxy.z );',
  682. 'material.specularRoughness = max( 1.0 - glossinessFactor, 0.0525 ); // 0.0525 corresponds to the base mip of a 256 cubemap.',
  683. 'material.specularRoughness += geometryRoughness;',
  684. 'material.specularRoughness = min( material.specularRoughness, 1.0 );',
  685. 'material.specularColor = specularFactor;',
  686. ].join( '\n' );
  687. var uniforms = {
  688. specular: { value: new THREE.Color().setHex( 0xffffff ) },
  689. glossiness: { value: 1 },
  690. specularMap: { value: null },
  691. glossinessMap: { value: null }
  692. };
  693. this._extraUniforms = uniforms;
  694. this.onBeforeCompile = function ( shader ) {
  695. for ( var uniformName in uniforms ) {
  696. shader.uniforms[ uniformName ] = uniforms[ uniformName ];
  697. }
  698. shader.fragmentShader = shader.fragmentShader
  699. .replace( 'uniform float roughness;', 'uniform vec3 specular;' )
  700. .replace( 'uniform float metalness;', 'uniform float glossiness;' )
  701. .replace( '#include <roughnessmap_pars_fragment>', specularMapParsFragmentChunk )
  702. .replace( '#include <metalnessmap_pars_fragment>', glossinessMapParsFragmentChunk )
  703. .replace( '#include <roughnessmap_fragment>', specularMapFragmentChunk )
  704. .replace( '#include <metalnessmap_fragment>', glossinessMapFragmentChunk )
  705. .replace( '#include <lights_physical_fragment>', lightPhysicalFragmentChunk );
  706. };
  707. Object.defineProperties( this, {
  708. specular: {
  709. get: function () {
  710. return uniforms.specular.value;
  711. },
  712. set: function ( v ) {
  713. uniforms.specular.value = v;
  714. }
  715. },
  716. specularMap: {
  717. get: function () {
  718. return uniforms.specularMap.value;
  719. },
  720. set: function ( v ) {
  721. uniforms.specularMap.value = v;
  722. if ( v ) {
  723. this.defines.USE_SPECULARMAP = ''; // USE_UV is set by the renderer for specular maps
  724. } else {
  725. delete this.defines.USE_SPECULARMAP;
  726. }
  727. }
  728. },
  729. glossiness: {
  730. get: function () {
  731. return uniforms.glossiness.value;
  732. },
  733. set: function ( v ) {
  734. uniforms.glossiness.value = v;
  735. }
  736. },
  737. glossinessMap: {
  738. get: function () {
  739. return uniforms.glossinessMap.value;
  740. },
  741. set: function ( v ) {
  742. uniforms.glossinessMap.value = v;
  743. if ( v ) {
  744. this.defines.USE_GLOSSINESSMAP = '';
  745. this.defines.USE_UV = '';
  746. } else {
  747. delete this.defines.USE_GLOSSINESSMAP;
  748. delete this.defines.USE_UV;
  749. }
  750. }
  751. }
  752. } );
  753. delete this.metalness;
  754. delete this.roughness;
  755. delete this.metalnessMap;
  756. delete this.roughnessMap;
  757. this.setValues( params );
  758. }
  759. GLTFMeshStandardSGMaterial.prototype = Object.create( THREE.MeshStandardMaterial.prototype );
  760. GLTFMeshStandardSGMaterial.prototype.constructor = GLTFMeshStandardSGMaterial;
  761. GLTFMeshStandardSGMaterial.prototype.copy = function ( source ) {
  762. THREE.MeshStandardMaterial.prototype.copy.call( this, source );
  763. this.specularMap = source.specularMap;
  764. this.specular.copy( source.specular );
  765. this.glossinessMap = source.glossinessMap;
  766. this.glossiness = source.glossiness;
  767. delete this.metalness;
  768. delete this.roughness;
  769. delete this.metalnessMap;
  770. delete this.roughnessMap;
  771. return this;
  772. };
  773. function GLTFMaterialsPbrSpecularGlossinessExtension() {
  774. return {
  775. name: EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS,
  776. specularGlossinessParams: [
  777. 'color',
  778. 'map',
  779. 'lightMap',
  780. 'lightMapIntensity',
  781. 'aoMap',
  782. 'aoMapIntensity',
  783. 'emissive',
  784. 'emissiveIntensity',
  785. 'emissiveMap',
  786. 'bumpMap',
  787. 'bumpScale',
  788. 'normalMap',
  789. 'normalMapType',
  790. 'displacementMap',
  791. 'displacementScale',
  792. 'displacementBias',
  793. 'specularMap',
  794. 'specular',
  795. 'glossinessMap',
  796. 'glossiness',
  797. 'alphaMap',
  798. 'envMap',
  799. 'envMapIntensity',
  800. 'refractionRatio',
  801. ],
  802. getMaterialType: function () {
  803. return GLTFMeshStandardSGMaterial;
  804. },
  805. extendParams: function ( materialParams, materialDef, parser ) {
  806. var pbrSpecularGlossiness = materialDef.extensions[ this.name ];
  807. materialParams.color = new THREE.Color( 1.0, 1.0, 1.0 );
  808. materialParams.opacity = 1.0;
  809. var pending = [];
  810. if ( Array.isArray( pbrSpecularGlossiness.diffuseFactor ) ) {
  811. var array = pbrSpecularGlossiness.diffuseFactor;
  812. materialParams.color.fromArray( array );
  813. materialParams.opacity = array[ 3 ];
  814. }
  815. if ( pbrSpecularGlossiness.diffuseTexture !== undefined ) {
  816. pending.push( parser.assignTexture( materialParams, 'map', pbrSpecularGlossiness.diffuseTexture ) );
  817. }
  818. materialParams.emissive = new THREE.Color( 0.0, 0.0, 0.0 );
  819. materialParams.glossiness = pbrSpecularGlossiness.glossinessFactor !== undefined ? pbrSpecularGlossiness.glossinessFactor : 1.0;
  820. materialParams.specular = new THREE.Color( 1.0, 1.0, 1.0 );
  821. if ( Array.isArray( pbrSpecularGlossiness.specularFactor ) ) {
  822. materialParams.specular.fromArray( pbrSpecularGlossiness.specularFactor );
  823. }
  824. if ( pbrSpecularGlossiness.specularGlossinessTexture !== undefined ) {
  825. var specGlossMapDef = pbrSpecularGlossiness.specularGlossinessTexture;
  826. pending.push( parser.assignTexture( materialParams, 'glossinessMap', specGlossMapDef ) );
  827. pending.push( parser.assignTexture( materialParams, 'specularMap', specGlossMapDef ) );
  828. }
  829. return Promise.all( pending );
  830. },
  831. createMaterial: function ( materialParams ) {
  832. var material = new GLTFMeshStandardSGMaterial( materialParams );
  833. material.fog = true;
  834. material.color = materialParams.color;
  835. material.map = materialParams.map === undefined ? null : materialParams.map;
  836. material.lightMap = null;
  837. material.lightMapIntensity = 1.0;
  838. material.aoMap = materialParams.aoMap === undefined ? null : materialParams.aoMap;
  839. material.aoMapIntensity = 1.0;
  840. material.emissive = materialParams.emissive;
  841. material.emissiveIntensity = 1.0;
  842. material.emissiveMap = materialParams.emissiveMap === undefined ? null : materialParams.emissiveMap;
  843. material.bumpMap = materialParams.bumpMap === undefined ? null : materialParams.bumpMap;
  844. material.bumpScale = 1;
  845. material.normalMap = materialParams.normalMap === undefined ? null : materialParams.normalMap;
  846. material.normalMapType = THREE.TangentSpaceNormalMap;
  847. if ( materialParams.normalScale ) material.normalScale = materialParams.normalScale;
  848. material.displacementMap = null;
  849. material.displacementScale = 1;
  850. material.displacementBias = 0;
  851. material.specularMap = materialParams.specularMap === undefined ? null : materialParams.specularMap;
  852. material.specular = materialParams.specular;
  853. material.glossinessMap = materialParams.glossinessMap === undefined ? null : materialParams.glossinessMap;
  854. material.glossiness = materialParams.glossiness;
  855. material.alphaMap = null;
  856. material.envMap = materialParams.envMap === undefined ? null : materialParams.envMap;
  857. material.envMapIntensity = 1.0;
  858. material.refractionRatio = 0.98;
  859. return material;
  860. },
  861. };
  862. }
  863. /**
  864. * Mesh Quantization Extension
  865. *
  866. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_mesh_quantization
  867. */
  868. function GLTFMeshQuantizationExtension() {
  869. this.name = EXTENSIONS.KHR_MESH_QUANTIZATION;
  870. }
  871. /*********************************/
  872. /********** INTERPOLATION ********/
  873. /*********************************/
  874. // Spline Interpolation
  875. // Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#appendix-c-spline-interpolation
  876. function GLTFCubicSplineInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  877. THREE.Interpolant.call( this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  878. }
  879. GLTFCubicSplineInterpolant.prototype = Object.create( THREE.Interpolant.prototype );
  880. GLTFCubicSplineInterpolant.prototype.constructor = GLTFCubicSplineInterpolant;
  881. GLTFCubicSplineInterpolant.prototype.copySampleValue_ = function ( index ) {
  882. // Copies a sample value to the result buffer. See description of glTF
  883. // CUBICSPLINE values layout in interpolate_() function below.
  884. var result = this.resultBuffer,
  885. values = this.sampleValues,
  886. valueSize = this.valueSize,
  887. offset = index * valueSize * 3 + valueSize;
  888. for ( var i = 0; i !== valueSize; i ++ ) {
  889. result[ i ] = values[ offset + i ];
  890. }
  891. return result;
  892. };
  893. GLTFCubicSplineInterpolant.prototype.beforeStart_ = GLTFCubicSplineInterpolant.prototype.copySampleValue_;
  894. GLTFCubicSplineInterpolant.prototype.afterEnd_ = GLTFCubicSplineInterpolant.prototype.copySampleValue_;
  895. GLTFCubicSplineInterpolant.prototype.interpolate_ = function ( i1, t0, t, t1 ) {
  896. var result = this.resultBuffer;
  897. var values = this.sampleValues;
  898. var stride = this.valueSize;
  899. var stride2 = stride * 2;
  900. var stride3 = stride * 3;
  901. var td = t1 - t0;
  902. var p = ( t - t0 ) / td;
  903. var pp = p * p;
  904. var ppp = pp * p;
  905. var offset1 = i1 * stride3;
  906. var offset0 = offset1 - stride3;
  907. var s2 = - 2 * ppp + 3 * pp;
  908. var s3 = ppp - pp;
  909. var s0 = 1 - s2;
  910. var s1 = s3 - pp + p;
  911. // Layout of keyframe output values for CUBICSPLINE animations:
  912. // [ inTangent_1, splineVertex_1, outTangent_1, inTangent_2, splineVertex_2, ... ]
  913. for ( var i = 0; i !== stride; i ++ ) {
  914. var p0 = values[ offset0 + i + stride ]; // splineVertex_k
  915. var m0 = values[ offset0 + i + stride2 ] * td; // outTangent_k * (t_k+1 - t_k)
  916. var p1 = values[ offset1 + i + stride ]; // splineVertex_k+1
  917. var m1 = values[ offset1 + i ] * td; // inTangent_k+1 * (t_k+1 - t_k)
  918. result[ i ] = s0 * p0 + s1 * m0 + s2 * p1 + s3 * m1;
  919. }
  920. return result;
  921. };
  922. /*********************************/
  923. /********** INTERNALS ************/
  924. /*********************************/
  925. /* CONSTANTS */
  926. var WEBGL_CONSTANTS = {
  927. FLOAT: 5126,
  928. //FLOAT_MAT2: 35674,
  929. FLOAT_MAT3: 35675,
  930. FLOAT_MAT4: 35676,
  931. FLOAT_VEC2: 35664,
  932. FLOAT_VEC3: 35665,
  933. FLOAT_VEC4: 35666,
  934. LINEAR: 9729,
  935. REPEAT: 10497,
  936. SAMPLER_2D: 35678,
  937. POINTS: 0,
  938. LINES: 1,
  939. LINE_LOOP: 2,
  940. LINE_STRIP: 3,
  941. TRIANGLES: 4,
  942. TRIANGLE_STRIP: 5,
  943. TRIANGLE_FAN: 6,
  944. UNSIGNED_BYTE: 5121,
  945. UNSIGNED_SHORT: 5123
  946. };
  947. var WEBGL_COMPONENT_TYPES = {
  948. 5120: Int8Array,
  949. 5121: Uint8Array,
  950. 5122: Int16Array,
  951. 5123: Uint16Array,
  952. 5125: Uint32Array,
  953. 5126: Float32Array
  954. };
  955. var WEBGL_FILTERS = {
  956. 9728: THREE.NearestFilter,
  957. 9729: THREE.LinearFilter,
  958. 9984: THREE.NearestMipmapNearestFilter,
  959. 9985: THREE.LinearMipmapNearestFilter,
  960. 9986: THREE.NearestMipmapLinearFilter,
  961. 9987: THREE.LinearMipmapLinearFilter
  962. };
  963. var WEBGL_WRAPPINGS = {
  964. 33071: THREE.ClampToEdgeWrapping,
  965. 33648: THREE.MirroredRepeatWrapping,
  966. 10497: THREE.RepeatWrapping
  967. };
  968. var WEBGL_TYPE_SIZES = {
  969. 'SCALAR': 1,
  970. 'VEC2': 2,
  971. 'VEC3': 3,
  972. 'VEC4': 4,
  973. 'MAT2': 4,
  974. 'MAT3': 9,
  975. 'MAT4': 16
  976. };
  977. var ATTRIBUTES = {
  978. POSITION: 'position',
  979. NORMAL: 'normal',
  980. TANGENT: 'tangent',
  981. TEXCOORD_0: 'uv',
  982. TEXCOORD_1: 'uv2',
  983. COLOR_0: 'color',
  984. WEIGHTS_0: 'skinWeight',
  985. JOINTS_0: 'skinIndex',
  986. };
  987. var PATH_PROPERTIES = {
  988. scale: 'scale',
  989. translation: 'position',
  990. rotation: 'quaternion',
  991. weights: 'morphTargetInfluences'
  992. };
  993. var INTERPOLATION = {
  994. CUBICSPLINE: undefined, // We use a custom interpolant (GLTFCubicSplineInterpolation) for CUBICSPLINE tracks. Each
  995. // keyframe track will be initialized with a default interpolation type, then modified.
  996. LINEAR: THREE.InterpolateLinear,
  997. STEP: THREE.InterpolateDiscrete
  998. };
  999. var ALPHA_MODES = {
  1000. OPAQUE: 'OPAQUE',
  1001. MASK: 'MASK',
  1002. BLEND: 'BLEND'
  1003. };
  1004. /* UTILITY FUNCTIONS */
  1005. function resolveURL( url, path ) {
  1006. // Invalid URL
  1007. if ( typeof url !== 'string' || url === '' ) return '';
  1008. // Host Relative URL
  1009. if ( /^https?:\/\//i.test( path ) && /^\//.test( url ) ) {
  1010. path = path.replace( /(^https?:\/\/[^\/]+).*/i, '$1' );
  1011. }
  1012. // Absolute URL http://,https://,//
  1013. if ( /^(https?:)?\/\//i.test( url ) ) return url;
  1014. // Data URI
  1015. if ( /^data:.*,.*$/i.test( url ) ) return url;
  1016. // Blob URL
  1017. if ( /^blob:.*$/i.test( url ) ) return url;
  1018. // Relative URL
  1019. return path + url;
  1020. }
  1021. /**
  1022. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#default-material
  1023. */
  1024. function createDefaultMaterial( cache ) {
  1025. if ( cache[ 'DefaultMaterial' ] === undefined ) {
  1026. cache[ 'DefaultMaterial' ] = new THREE.MeshStandardMaterial( {
  1027. color: 0xFFFFFF,
  1028. emissive: 0x000000,
  1029. metalness: 1,
  1030. roughness: 1,
  1031. transparent: false,
  1032. depthTest: true,
  1033. side: THREE.FrontSide
  1034. } );
  1035. }
  1036. return cache[ 'DefaultMaterial' ];
  1037. }
  1038. function addUnknownExtensionsToUserData( knownExtensions, object, objectDef ) {
  1039. // Add unknown glTF extensions to an object's userData.
  1040. for ( var name in objectDef.extensions ) {
  1041. if ( knownExtensions[ name ] === undefined ) {
  1042. object.userData.gltfExtensions = object.userData.gltfExtensions || {};
  1043. object.userData.gltfExtensions[ name ] = objectDef.extensions[ name ];
  1044. }
  1045. }
  1046. }
  1047. /**
  1048. * @param {THREE.Object3D|THREE.Material|THREE.BufferGeometry} object
  1049. * @param {GLTF.definition} gltfDef
  1050. */
  1051. function assignExtrasToUserData( object, gltfDef ) {
  1052. if ( gltfDef.extras !== undefined ) {
  1053. if ( typeof gltfDef.extras === 'object' ) {
  1054. Object.assign( object.userData, gltfDef.extras );
  1055. } else {
  1056. console.warn( 'THREE.GLTFLoader: Ignoring primitive type .extras, ' + gltfDef.extras );
  1057. }
  1058. }
  1059. }
  1060. /**
  1061. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#morph-targets
  1062. *
  1063. * @param {THREE.BufferGeometry} geometry
  1064. * @param {Array<GLTF.Target>} targets
  1065. * @param {GLTFParser} parser
  1066. * @return {Promise<THREE.BufferGeometry>}
  1067. */
  1068. function addMorphTargets( geometry, targets, parser ) {
  1069. var hasMorphPosition = false;
  1070. var hasMorphNormal = false;
  1071. for ( var i = 0, il = targets.length; i < il; i ++ ) {
  1072. var target = targets[ i ];
  1073. if ( target.POSITION !== undefined ) hasMorphPosition = true;
  1074. if ( target.NORMAL !== undefined ) hasMorphNormal = true;
  1075. if ( hasMorphPosition && hasMorphNormal ) break;
  1076. }
  1077. if ( ! hasMorphPosition && ! hasMorphNormal ) return Promise.resolve( geometry );
  1078. var pendingPositionAccessors = [];
  1079. var pendingNormalAccessors = [];
  1080. for ( var i = 0, il = targets.length; i < il; i ++ ) {
  1081. var target = targets[ i ];
  1082. if ( hasMorphPosition ) {
  1083. var pendingAccessor = target.POSITION !== undefined
  1084. ? parser.getDependency( 'accessor', target.POSITION )
  1085. : geometry.attributes.position;
  1086. pendingPositionAccessors.push( pendingAccessor );
  1087. }
  1088. if ( hasMorphNormal ) {
  1089. var pendingAccessor = target.NORMAL !== undefined
  1090. ? parser.getDependency( 'accessor', target.NORMAL )
  1091. : geometry.attributes.normal;
  1092. pendingNormalAccessors.push( pendingAccessor );
  1093. }
  1094. }
  1095. return Promise.all( [
  1096. Promise.all( pendingPositionAccessors ),
  1097. Promise.all( pendingNormalAccessors )
  1098. ] ).then( function ( accessors ) {
  1099. var morphPositions = accessors[ 0 ];
  1100. var morphNormals = accessors[ 1 ];
  1101. if ( hasMorphPosition ) geometry.morphAttributes.position = morphPositions;
  1102. if ( hasMorphNormal ) geometry.morphAttributes.normal = morphNormals;
  1103. geometry.morphTargetsRelative = true;
  1104. return geometry;
  1105. } );
  1106. }
  1107. /**
  1108. * @param {THREE.Mesh} mesh
  1109. * @param {GLTF.Mesh} meshDef
  1110. */
  1111. function updateMorphTargets( mesh, meshDef ) {
  1112. mesh.updateMorphTargets();
  1113. if ( meshDef.weights !== undefined ) {
  1114. for ( var i = 0, il = meshDef.weights.length; i < il; i ++ ) {
  1115. mesh.morphTargetInfluences[ i ] = meshDef.weights[ i ];
  1116. }
  1117. }
  1118. // .extras has user-defined data, so check that .extras.targetNames is an array.
  1119. if ( meshDef.extras && Array.isArray( meshDef.extras.targetNames ) ) {
  1120. var targetNames = meshDef.extras.targetNames;
  1121. if ( mesh.morphTargetInfluences.length === targetNames.length ) {
  1122. mesh.morphTargetDictionary = {};
  1123. for ( var i = 0, il = targetNames.length; i < il; i ++ ) {
  1124. mesh.morphTargetDictionary[ targetNames[ i ] ] = i;
  1125. }
  1126. } else {
  1127. console.warn( 'THREE.GLTFLoader: Invalid extras.targetNames length. Ignoring names.' );
  1128. }
  1129. }
  1130. }
  1131. function createPrimitiveKey( primitiveDef ) {
  1132. var dracoExtension = primitiveDef.extensions && primitiveDef.extensions[ EXTENSIONS.KHR_DRACO_MESH_COMPRESSION ];
  1133. var geometryKey;
  1134. if ( dracoExtension ) {
  1135. geometryKey = 'draco:' + dracoExtension.bufferView
  1136. + ':' + dracoExtension.indices
  1137. + ':' + createAttributesKey( dracoExtension.attributes );
  1138. } else {
  1139. geometryKey = primitiveDef.indices + ':' + createAttributesKey( primitiveDef.attributes ) + ':' + primitiveDef.mode;
  1140. }
  1141. return geometryKey;
  1142. }
  1143. function createAttributesKey( attributes ) {
  1144. var attributesKey = '';
  1145. var keys = Object.keys( attributes ).sort();
  1146. for ( var i = 0, il = keys.length; i < il; i ++ ) {
  1147. attributesKey += keys[ i ] + ':' + attributes[ keys[ i ] ] + ';';
  1148. }
  1149. return attributesKey;
  1150. }
  1151. /* GLTF PARSER */
  1152. function GLTFParser( json, options ) {
  1153. this.json = json || {};
  1154. this.extensions = {};
  1155. this.plugins = {};
  1156. this.options = options || {};
  1157. // loader object cache
  1158. this.cache = new GLTFRegistry();
  1159. // associations between Three.js objects and glTF elements
  1160. this.associations = new Map();
  1161. // BufferGeometry caching
  1162. this.primitiveCache = {};
  1163. // Object3D instance caches
  1164. this.meshCache = { refs: {}, uses: {} };
  1165. this.cameraCache = { refs: {}, uses: {} };
  1166. this.lightCache = { refs: {}, uses: {} };
  1167. // Track node names, to ensure no duplicates
  1168. this.nodeNamesUsed = {};
  1169. // Use an ImageBitmapLoader if imageBitmaps are supported. Moves much of the
  1170. // expensive work of uploading a texture to the GPU off the main thread.
  1171. if ( typeof createImageBitmap !== 'undefined' && /Firefox/.test( navigator.userAgent ) === false ) {
  1172. this.textureLoader = new THREE.ImageBitmapLoader( this.options.manager );
  1173. } else {
  1174. this.textureLoader = new THREE.TextureLoader( this.options.manager );
  1175. }
  1176. this.textureLoader.setCrossOrigin( this.options.crossOrigin );
  1177. this.fileLoader = new THREE.FileLoader( this.options.manager );
  1178. this.fileLoader.setResponseType( 'arraybuffer' );
  1179. if ( this.options.crossOrigin === 'use-credentials' ) {
  1180. this.fileLoader.setWithCredentials( true );
  1181. }
  1182. }
  1183. GLTFParser.prototype.setExtensions = function ( extensions ) {
  1184. this.extensions = extensions;
  1185. };
  1186. GLTFParser.prototype.setPlugins = function ( plugins ) {
  1187. this.plugins = plugins;
  1188. };
  1189. GLTFParser.prototype.parse = function ( onLoad, onError ) {
  1190. var parser = this;
  1191. var json = this.json;
  1192. var extensions = this.extensions;
  1193. // Clear the loader cache
  1194. this.cache.removeAll();
  1195. // Mark the special nodes/meshes in json for efficient parse
  1196. this._invokeAll( function ( ext ) {
  1197. return ext._markDefs && ext._markDefs();
  1198. } );
  1199. Promise.all( [
  1200. this.getDependencies( 'scene' ),
  1201. this.getDependencies( 'animation' ),
  1202. this.getDependencies( 'camera' ),
  1203. ] ).then( function ( dependencies ) {
  1204. var result = {
  1205. scene: dependencies[ 0 ][ json.scene || 0 ],
  1206. scenes: dependencies[ 0 ],
  1207. animations: dependencies[ 1 ],
  1208. cameras: dependencies[ 2 ],
  1209. asset: json.asset,
  1210. parser: parser,
  1211. userData: {}
  1212. };
  1213. addUnknownExtensionsToUserData( extensions, result, json );
  1214. assignExtrasToUserData( result, json );
  1215. onLoad( result );
  1216. } ).catch( onError );
  1217. };
  1218. /**
  1219. * Marks the special nodes/meshes in json for efficient parse.
  1220. */
  1221. GLTFParser.prototype._markDefs = function () {
  1222. var nodeDefs = this.json.nodes || [];
  1223. var skinDefs = this.json.skins || [];
  1224. var meshDefs = this.json.meshes || [];
  1225. // Nothing in the node definition indicates whether it is a Bone or an
  1226. // Object3D. Use the skins' joint references to mark bones.
  1227. for ( var skinIndex = 0, skinLength = skinDefs.length; skinIndex < skinLength; skinIndex ++ ) {
  1228. var joints = skinDefs[ skinIndex ].joints;
  1229. for ( var i = 0, il = joints.length; i < il; i ++ ) {
  1230. nodeDefs[ joints[ i ] ].isBone = true;
  1231. }
  1232. }
  1233. // Iterate over all nodes, marking references to shared resources,
  1234. // as well as skeleton joints.
  1235. for ( var nodeIndex = 0, nodeLength = nodeDefs.length; nodeIndex < nodeLength; nodeIndex ++ ) {
  1236. var nodeDef = nodeDefs[ nodeIndex ];
  1237. if ( nodeDef.mesh !== undefined ) {
  1238. this._addNodeRef( this.meshCache, nodeDef.mesh );
  1239. // Nothing in the mesh definition indicates whether it is
  1240. // a SkinnedMesh or Mesh. Use the node's mesh reference
  1241. // to mark SkinnedMesh if node has skin.
  1242. if ( nodeDef.skin !== undefined ) {
  1243. meshDefs[ nodeDef.mesh ].isSkinnedMesh = true;
  1244. }
  1245. }
  1246. if ( nodeDef.camera !== undefined ) {
  1247. this._addNodeRef( this.cameraCache, nodeDef.camera );
  1248. }
  1249. }
  1250. };
  1251. /**
  1252. * Counts references to shared node / Object3D resources. These resources
  1253. * can be reused, or "instantiated", at multiple nodes in the scene
  1254. * hierarchy. Mesh, Camera, and Light instances are instantiated and must
  1255. * be marked. Non-scenegraph resources (like Materials, Geometries, and
  1256. * Textures) can be reused directly and are not marked here.
  1257. *
  1258. * Example: CesiumMilkTruck sample model reuses "Wheel" meshes.
  1259. */
  1260. GLTFParser.prototype._addNodeRef = function ( cache, index ) {
  1261. if ( index === undefined ) return;
  1262. if ( cache.refs[ index ] === undefined ) {
  1263. cache.refs[ index ] = cache.uses[ index ] = 0;
  1264. }
  1265. cache.refs[ index ] ++;
  1266. };
  1267. /** Returns a reference to a shared resource, cloning it if necessary. */
  1268. GLTFParser.prototype._getNodeRef = function ( cache, index, object ) {
  1269. if ( cache.refs[ index ] <= 1 ) return object;
  1270. var ref = object.clone();
  1271. ref.name += '_instance_' + ( cache.uses[ index ] ++ );
  1272. return ref;
  1273. };
  1274. GLTFParser.prototype._invokeOne = function ( func ) {
  1275. var extensions = Object.values( this.plugins );
  1276. extensions.push( this );
  1277. for ( var i = 0; i < extensions.length; i ++ ) {
  1278. var result = func( extensions[ i ] );
  1279. if ( result ) return result;
  1280. }
  1281. };
  1282. GLTFParser.prototype._invokeAll = function ( func ) {
  1283. var extensions = Object.values( this.plugins );
  1284. extensions.unshift( this );
  1285. var pending = [];
  1286. for ( var i = 0; i < extensions.length; i ++ ) {
  1287. var result = func( extensions[ i ] );
  1288. if ( result ) pending.push( result );
  1289. }
  1290. return pending;
  1291. };
  1292. /**
  1293. * Requests the specified dependency asynchronously, with caching.
  1294. * @param {string} type
  1295. * @param {number} index
  1296. * @return {Promise<THREE.Object3D|THREE.Material|THREE.Texture|THREE.AnimationClip|ArrayBuffer|Object>}
  1297. */
  1298. GLTFParser.prototype.getDependency = function ( type, index ) {
  1299. var cacheKey = type + ':' + index;
  1300. var dependency = this.cache.get( cacheKey );
  1301. if ( ! dependency ) {
  1302. switch ( type ) {
  1303. case 'scene':
  1304. dependency = this.loadScene( index );
  1305. break;
  1306. case 'node':
  1307. dependency = this.loadNode( index );
  1308. break;
  1309. case 'mesh':
  1310. dependency = this._invokeOne( function ( ext ) {
  1311. return ext.loadMesh && ext.loadMesh( index );
  1312. } );
  1313. break;
  1314. case 'accessor':
  1315. dependency = this.loadAccessor( index );
  1316. break;
  1317. case 'bufferView':
  1318. dependency = this._invokeOne( function ( ext ) {
  1319. return ext.loadBufferView && ext.loadBufferView( index );
  1320. } );
  1321. break;
  1322. case 'buffer':
  1323. dependency = this.loadBuffer( index );
  1324. break;
  1325. case 'material':
  1326. dependency = this._invokeOne( function ( ext ) {
  1327. return ext.loadMaterial && ext.loadMaterial( index );
  1328. } );
  1329. break;
  1330. case 'texture':
  1331. dependency = this._invokeOne( function ( ext ) {
  1332. return ext.loadTexture && ext.loadTexture( index );
  1333. } );
  1334. break;
  1335. case 'skin':
  1336. dependency = this.loadSkin( index );
  1337. break;
  1338. case 'animation':
  1339. dependency = this.loadAnimation( index );
  1340. break;
  1341. case 'camera':
  1342. dependency = this.loadCamera( index );
  1343. break;
  1344. default:
  1345. throw new Error( 'Unknown type: ' + type );
  1346. }
  1347. this.cache.add( cacheKey, dependency );
  1348. }
  1349. return dependency;
  1350. };
  1351. /**
  1352. * Requests all dependencies of the specified type asynchronously, with caching.
  1353. * @param {string} type
  1354. * @return {Promise<Array<Object>>}
  1355. */
  1356. GLTFParser.prototype.getDependencies = function ( type ) {
  1357. var dependencies = this.cache.get( type );
  1358. if ( ! dependencies ) {
  1359. var parser = this;
  1360. var defs = this.json[ type + ( type === 'mesh' ? 'es' : 's' ) ] || [];
  1361. dependencies = Promise.all( defs.map( function ( def, index ) {
  1362. return parser.getDependency( type, index );
  1363. } ) );
  1364. this.cache.add( type, dependencies );
  1365. }
  1366. return dependencies;
  1367. };
  1368. /**
  1369. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#buffers-and-buffer-views
  1370. * @param {number} bufferIndex
  1371. * @return {Promise<ArrayBuffer>}
  1372. */
  1373. GLTFParser.prototype.loadBuffer = function ( bufferIndex ) {
  1374. var bufferDef = this.json.buffers[ bufferIndex ];
  1375. var loader = this.fileLoader;
  1376. if ( bufferDef.type && bufferDef.type !== 'arraybuffer' ) {
  1377. throw new Error( 'THREE.GLTFLoader: ' + bufferDef.type + ' buffer type is not supported.' );
  1378. }
  1379. // If present, GLB container is required to be the first buffer.
  1380. if ( bufferDef.uri === undefined && bufferIndex === 0 ) {
  1381. return Promise.resolve( this.extensions[ EXTENSIONS.KHR_BINARY_GLTF ].body );
  1382. }
  1383. var options = this.options;
  1384. return new Promise( function ( resolve, reject ) {
  1385. loader.load( resolveURL( bufferDef.uri, options.path ), resolve, undefined, function () {
  1386. reject( new Error( 'THREE.GLTFLoader: Failed to load buffer "' + bufferDef.uri + '".' ) );
  1387. } );
  1388. } );
  1389. };
  1390. /**
  1391. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#buffers-and-buffer-views
  1392. * @param {number} bufferViewIndex
  1393. * @return {Promise<ArrayBuffer>}
  1394. */
  1395. GLTFParser.prototype.loadBufferView = function ( bufferViewIndex ) {
  1396. var bufferViewDef = this.json.bufferViews[ bufferViewIndex ];
  1397. return this.getDependency( 'buffer', bufferViewDef.buffer ).then( function ( buffer ) {
  1398. var byteLength = bufferViewDef.byteLength || 0;
  1399. var byteOffset = bufferViewDef.byteOffset || 0;
  1400. return buffer.slice( byteOffset, byteOffset + byteLength );
  1401. } );
  1402. };
  1403. /**
  1404. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#accessors
  1405. * @param {number} accessorIndex
  1406. * @return {Promise<THREE.BufferAttribute|THREE.InterleavedBufferAttribute>}
  1407. */
  1408. GLTFParser.prototype.loadAccessor = function ( accessorIndex ) {
  1409. var parser = this;
  1410. var json = this.json;
  1411. var accessorDef = this.json.accessors[ accessorIndex ];
  1412. if ( accessorDef.bufferView === undefined && accessorDef.sparse === undefined ) {
  1413. // Ignore empty accessors, which may be used to declare runtime
  1414. // information about attributes coming from another source (e.g. Draco
  1415. // compression extension).
  1416. return Promise.resolve( null );
  1417. }
  1418. var pendingBufferViews = [];
  1419. if ( accessorDef.bufferView !== undefined ) {
  1420. pendingBufferViews.push( this.getDependency( 'bufferView', accessorDef.bufferView ) );
  1421. } else {
  1422. pendingBufferViews.push( null );
  1423. }
  1424. if ( accessorDef.sparse !== undefined ) {
  1425. pendingBufferViews.push( this.getDependency( 'bufferView', accessorDef.sparse.indices.bufferView ) );
  1426. pendingBufferViews.push( this.getDependency( 'bufferView', accessorDef.sparse.values.bufferView ) );
  1427. }
  1428. return Promise.all( pendingBufferViews ).then( function ( bufferViews ) {
  1429. var bufferView = bufferViews[ 0 ];
  1430. var itemSize = WEBGL_TYPE_SIZES[ accessorDef.type ];
  1431. var TypedArray = WEBGL_COMPONENT_TYPES[ accessorDef.componentType ];
  1432. // For VEC3: itemSize is 3, elementBytes is 4, itemBytes is 12.
  1433. var elementBytes = TypedArray.BYTES_PER_ELEMENT;
  1434. var itemBytes = elementBytes * itemSize;
  1435. var byteOffset = accessorDef.byteOffset || 0;
  1436. var byteStride = accessorDef.bufferView !== undefined ? json.bufferViews[ accessorDef.bufferView ].byteStride : undefined;
  1437. var normalized = accessorDef.normalized === true;
  1438. var array, bufferAttribute;
  1439. // The buffer is not interleaved if the stride is the item size in bytes.
  1440. if ( byteStride && byteStride !== itemBytes ) {
  1441. // Each "slice" of the buffer, as defined by 'count' elements of 'byteStride' bytes, gets its own InterleavedBuffer
  1442. // This makes sure that IBA.count reflects accessor.count properly
  1443. var ibSlice = Math.floor( byteOffset / byteStride );
  1444. var ibCacheKey = 'InterleavedBuffer:' + accessorDef.bufferView + ':' + accessorDef.componentType + ':' + ibSlice + ':' + accessorDef.count;
  1445. var ib = parser.cache.get( ibCacheKey );
  1446. if ( ! ib ) {
  1447. array = new TypedArray( bufferView, ibSlice * byteStride, accessorDef.count * byteStride / elementBytes );
  1448. // Integer parameters to IB/IBA are in array elements, not bytes.
  1449. ib = new THREE.InterleavedBuffer( array, byteStride / elementBytes );
  1450. parser.cache.add( ibCacheKey, ib );
  1451. }
  1452. bufferAttribute = new THREE.InterleavedBufferAttribute( ib, itemSize, ( byteOffset % byteStride ) / elementBytes, normalized );
  1453. } else {
  1454. if ( bufferView === null ) {
  1455. array = new TypedArray( accessorDef.count * itemSize );
  1456. } else {
  1457. array = new TypedArray( bufferView, byteOffset, accessorDef.count * itemSize );
  1458. }
  1459. bufferAttribute = new THREE.BufferAttribute( array, itemSize, normalized );
  1460. }
  1461. // https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#sparse-accessors
  1462. if ( accessorDef.sparse !== undefined ) {
  1463. var itemSizeIndices = WEBGL_TYPE_SIZES.SCALAR;
  1464. var TypedArrayIndices = WEBGL_COMPONENT_TYPES[ accessorDef.sparse.indices.componentType ];
  1465. var byteOffsetIndices = accessorDef.sparse.indices.byteOffset || 0;
  1466. var byteOffsetValues = accessorDef.sparse.values.byteOffset || 0;
  1467. var sparseIndices = new TypedArrayIndices( bufferViews[ 1 ], byteOffsetIndices, accessorDef.sparse.count * itemSizeIndices );
  1468. var sparseValues = new TypedArray( bufferViews[ 2 ], byteOffsetValues, accessorDef.sparse.count * itemSize );
  1469. if ( bufferView !== null ) {
  1470. // Avoid modifying the original ArrayBuffer, if the bufferView wasn't initialized with zeroes.
  1471. bufferAttribute = new THREE.BufferAttribute( bufferAttribute.array.slice(), bufferAttribute.itemSize, bufferAttribute.normalized );
  1472. }
  1473. for ( var i = 0, il = sparseIndices.length; i < il; i ++ ) {
  1474. var index = sparseIndices[ i ];
  1475. bufferAttribute.setX( index, sparseValues[ i * itemSize ] );
  1476. if ( itemSize >= 2 ) bufferAttribute.setY( index, sparseValues[ i * itemSize + 1 ] );
  1477. if ( itemSize >= 3 ) bufferAttribute.setZ( index, sparseValues[ i * itemSize + 2 ] );
  1478. if ( itemSize >= 4 ) bufferAttribute.setW( index, sparseValues[ i * itemSize + 3 ] );
  1479. if ( itemSize >= 5 ) throw new Error( 'THREE.GLTFLoader: Unsupported itemSize in sparse BufferAttribute.' );
  1480. }
  1481. }
  1482. return bufferAttribute;
  1483. } );
  1484. };
  1485. /**
  1486. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#textures
  1487. * @param {number} textureIndex
  1488. * @return {Promise<THREE.Texture>}
  1489. */
  1490. GLTFParser.prototype.loadTexture = function ( textureIndex ) {
  1491. var parser = this;
  1492. var json = this.json;
  1493. var options = this.options;
  1494. var textureDef = json.textures[ textureIndex ];
  1495. var textureExtensions = textureDef.extensions || {};
  1496. var source;
  1497. if ( textureExtensions[ EXTENSIONS.MSFT_TEXTURE_DDS ] ) {
  1498. source = json.images[ textureExtensions[ EXTENSIONS.MSFT_TEXTURE_DDS ].source ];
  1499. } else {
  1500. source = json.images[ textureDef.source ];
  1501. }
  1502. var loader;
  1503. if ( source.uri ) {
  1504. loader = options.manager.getHandler( source.uri );
  1505. }
  1506. if ( ! loader ) {
  1507. loader = textureExtensions[ EXTENSIONS.MSFT_TEXTURE_DDS ]
  1508. ? parser.extensions[ EXTENSIONS.MSFT_TEXTURE_DDS ].ddsLoader
  1509. : this.textureLoader;
  1510. }
  1511. return this.loadTextureImage( textureIndex, source, loader );
  1512. };
  1513. GLTFParser.prototype.loadTextureImage = function ( textureIndex, source, loader ) {
  1514. var parser = this;
  1515. var json = this.json;
  1516. var options = this.options;
  1517. var textureDef = json.textures[ textureIndex ];
  1518. var URL = self.URL || self.webkitURL;
  1519. var sourceURI = source.uri;
  1520. var isObjectURL = false;
  1521. var hasAlpha = true;
  1522. if ( source.mimeType === 'image/jpeg' ) hasAlpha = false;
  1523. if ( source.bufferView !== undefined ) {
  1524. // Load binary image data from bufferView, if provided.
  1525. sourceURI = parser.getDependency( 'bufferView', source.bufferView ).then( function ( bufferView ) {
  1526. if ( source.mimeType === 'image/png' ) {
  1527. // Inspect the PNG 'IHDR' chunk to determine whether the image could have an
  1528. // alpha channel. This check is conservative — the image could have an alpha
  1529. // channel with all values == 1, and the indexed type (colorType == 3) only
  1530. // sometimes contains alpha.
  1531. //
  1532. // https://en.wikipedia.org/wiki/Portable_Network_Graphics#File_header
  1533. var colorType = new DataView( bufferView, 25, 1 ).getUint8( 0, false );
  1534. hasAlpha = colorType === 6 || colorType === 4 || colorType === 3;
  1535. }
  1536. isObjectURL = true;
  1537. var blob = new Blob( [ bufferView ], { type: source.mimeType } );
  1538. sourceURI = URL.createObjectURL( blob );
  1539. return sourceURI;
  1540. } );
  1541. } else if ( source.uri === undefined ) {
  1542. throw new Error( 'THREE.GLTFLoader: Image ' + textureIndex + ' is missing URI and bufferView' );
  1543. }
  1544. return Promise.resolve( sourceURI ).then( function ( sourceURI ) {
  1545. return new Promise( function ( resolve, reject ) {
  1546. var onLoad = resolve;
  1547. if ( loader.isImageBitmapLoader === true ) {
  1548. onLoad = function ( imageBitmap ) {
  1549. resolve( new THREE.CanvasTexture( imageBitmap ) );
  1550. };
  1551. }
  1552. loader.load( resolveURL( sourceURI, options.path ), onLoad, undefined, reject );
  1553. } );
  1554. } ).then( function ( texture ) {
  1555. // Clean up resources and configure Texture.
  1556. if ( isObjectURL === true ) {
  1557. URL.revokeObjectURL( sourceURI );
  1558. }
  1559. texture.flipY = false;
  1560. if ( textureDef.name ) texture.name = textureDef.name;
  1561. // When there is definitely no alpha channel in the texture, set RGBFormat to save space.
  1562. if ( ! hasAlpha ) texture.format = THREE.RGBFormat;
  1563. var samplers = json.samplers || {};
  1564. var sampler = samplers[ textureDef.sampler ] || {};
  1565. texture.magFilter = WEBGL_FILTERS[ sampler.magFilter ] || THREE.LinearFilter;
  1566. texture.minFilter = WEBGL_FILTERS[ sampler.minFilter ] || THREE.LinearMipmapLinearFilter;
  1567. texture.wrapS = WEBGL_WRAPPINGS[ sampler.wrapS ] || THREE.RepeatWrapping;
  1568. texture.wrapT = WEBGL_WRAPPINGS[ sampler.wrapT ] || THREE.RepeatWrapping;
  1569. parser.associations.set( texture, {
  1570. type: 'textures',
  1571. index: textureIndex
  1572. } );
  1573. return texture;
  1574. } );
  1575. };
  1576. /**
  1577. * Asynchronously assigns a texture to the given material parameters.
  1578. * @param {Object} materialParams
  1579. * @param {string} mapName
  1580. * @param {Object} mapDef
  1581. * @return {Promise}
  1582. */
  1583. GLTFParser.prototype.assignTexture = function ( materialParams, mapName, mapDef ) {
  1584. var parser = this;
  1585. return this.getDependency( 'texture', mapDef.index ).then( function ( texture ) {
  1586. // Materials sample aoMap from UV set 1 and other maps from UV set 0 - this can't be configured
  1587. // However, we will copy UV set 0 to UV set 1 on demand for aoMap
  1588. if ( mapDef.texCoord !== undefined && mapDef.texCoord != 0 && ! ( mapName === 'aoMap' && mapDef.texCoord == 1 ) ) {
  1589. console.warn( 'THREE.GLTFLoader: Custom UV set ' + mapDef.texCoord + ' for texture ' + mapName + ' not yet supported.' );
  1590. }
  1591. if ( parser.extensions[ EXTENSIONS.KHR_TEXTURE_TRANSFORM ] ) {
  1592. var transform = mapDef.extensions !== undefined ? mapDef.extensions[ EXTENSIONS.KHR_TEXTURE_TRANSFORM ] : undefined;
  1593. if ( transform ) {
  1594. var gltfReference = parser.associations.get( texture );
  1595. texture = parser.extensions[ EXTENSIONS.KHR_TEXTURE_TRANSFORM ].extendTexture( texture, transform );
  1596. parser.associations.set( texture, gltfReference );
  1597. }
  1598. }
  1599. materialParams[ mapName ] = texture;
  1600. } );
  1601. };
  1602. /**
  1603. * Assigns final material to a Mesh, Line, or Points instance. The instance
  1604. * already has a material (generated from the glTF material options alone)
  1605. * but reuse of the same glTF material may require multiple threejs materials
  1606. * to accomodate different primitive types, defines, etc. New materials will
  1607. * be created if necessary, and reused from a cache.
  1608. * @param {THREE.Object3D} mesh Mesh, Line, or Points instance.
  1609. */
  1610. GLTFParser.prototype.assignFinalMaterial = function ( mesh ) {
  1611. var geometry = mesh.geometry;
  1612. var material = mesh.material;
  1613. var useVertexTangents = geometry.attributes.tangent !== undefined;
  1614. var useVertexColors = geometry.attributes.color !== undefined;
  1615. var useFlatShading = geometry.attributes.normal === undefined;
  1616. var useSkinning = mesh.isSkinnedMesh === true;
  1617. var useMorphTargets = Object.keys( geometry.morphAttributes ).length > 0;
  1618. var useMorphNormals = useMorphTargets && geometry.morphAttributes.normal !== undefined;
  1619. if ( mesh.isPoints ) {
  1620. var cacheKey = 'PointsMaterial:' + material.uuid;
  1621. var pointsMaterial = this.cache.get( cacheKey );
  1622. if ( ! pointsMaterial ) {
  1623. pointsMaterial = new THREE.PointsMaterial();
  1624. THREE.Material.prototype.copy.call( pointsMaterial, material );
  1625. pointsMaterial.color.copy( material.color );
  1626. pointsMaterial.map = material.map;
  1627. pointsMaterial.sizeAttenuation = false; // glTF spec says points should be 1px
  1628. this.cache.add( cacheKey, pointsMaterial );
  1629. }
  1630. material = pointsMaterial;
  1631. } else if ( mesh.isLine ) {
  1632. var cacheKey = 'LineBasicMaterial:' + material.uuid;
  1633. var lineMaterial = this.cache.get( cacheKey );
  1634. if ( ! lineMaterial ) {
  1635. lineMaterial = new THREE.LineBasicMaterial();
  1636. THREE.Material.prototype.copy.call( lineMaterial, material );
  1637. lineMaterial.color.copy( material.color );
  1638. this.cache.add( cacheKey, lineMaterial );
  1639. }
  1640. material = lineMaterial;
  1641. }
  1642. // Clone the material if it will be modified
  1643. if ( useVertexTangents || useVertexColors || useFlatShading || useSkinning || useMorphTargets ) {
  1644. var cacheKey = 'ClonedMaterial:' + material.uuid + ':';
  1645. if ( material.isGLTFSpecularGlossinessMaterial ) cacheKey += 'specular-glossiness:';
  1646. if ( useSkinning ) cacheKey += 'skinning:';
  1647. if ( useVertexTangents ) cacheKey += 'vertex-tangents:';
  1648. if ( useVertexColors ) cacheKey += 'vertex-colors:';
  1649. if ( useFlatShading ) cacheKey += 'flat-shading:';
  1650. if ( useMorphTargets ) cacheKey += 'morph-targets:';
  1651. if ( useMorphNormals ) cacheKey += 'morph-normals:';
  1652. var cachedMaterial = this.cache.get( cacheKey );
  1653. if ( ! cachedMaterial ) {
  1654. cachedMaterial = material.clone();
  1655. if ( useSkinning ) cachedMaterial.skinning = true;
  1656. if ( useVertexColors ) cachedMaterial.vertexColors = true;
  1657. if ( useFlatShading ) cachedMaterial.flatShading = true;
  1658. if ( useMorphTargets ) cachedMaterial.morphTargets = true;
  1659. if ( useMorphNormals ) cachedMaterial.morphNormals = true;
  1660. if ( useVertexTangents ) {
  1661. cachedMaterial.vertexTangents = true;
  1662. // https://github.com/mrdoob/three.js/issues/11438#issuecomment-507003995
  1663. if ( cachedMaterial.normalScale ) cachedMaterial.normalScale.y *= -1;
  1664. if ( cachedMaterial.clearcoatNormalScale ) cachedMaterial.clearcoatNormalScale.y *= -1;
  1665. }
  1666. this.cache.add( cacheKey, cachedMaterial );
  1667. this.associations.set( cachedMaterial, this.associations.get( material ) );
  1668. }
  1669. material = cachedMaterial;
  1670. }
  1671. // workarounds for mesh and geometry
  1672. if ( material.aoMap && geometry.attributes.uv2 === undefined && geometry.attributes.uv !== undefined ) {
  1673. geometry.setAttribute( 'uv2', geometry.attributes.uv );
  1674. }
  1675. mesh.material = material;
  1676. };
  1677. GLTFParser.prototype.getMaterialType = function ( /* materialIndex */ ) {
  1678. return THREE.MeshStandardMaterial;
  1679. };
  1680. /**
  1681. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#materials
  1682. * @param {number} materialIndex
  1683. * @return {Promise<THREE.Material>}
  1684. */
  1685. GLTFParser.prototype.loadMaterial = function ( materialIndex ) {
  1686. var parser = this;
  1687. var json = this.json;
  1688. var extensions = this.extensions;
  1689. var materialDef = json.materials[ materialIndex ];
  1690. var materialType;
  1691. var materialParams = {};
  1692. var materialExtensions = materialDef.extensions || {};
  1693. var pending = [];
  1694. if ( materialExtensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ] ) {
  1695. var sgExtension = extensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ];
  1696. materialType = sgExtension.getMaterialType();
  1697. pending.push( sgExtension.extendParams( materialParams, materialDef, parser ) );
  1698. } else if ( materialExtensions[ EXTENSIONS.KHR_MATERIALS_UNLIT ] ) {
  1699. var kmuExtension = extensions[ EXTENSIONS.KHR_MATERIALS_UNLIT ];
  1700. materialType = kmuExtension.getMaterialType();
  1701. pending.push( kmuExtension.extendParams( materialParams, materialDef, parser ) );
  1702. } else {
  1703. // Specification:
  1704. // https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#metallic-roughness-material
  1705. var metallicRoughness = materialDef.pbrMetallicRoughness || {};
  1706. materialParams.color = new THREE.Color( 1.0, 1.0, 1.0 );
  1707. materialParams.opacity = 1.0;
  1708. if ( Array.isArray( metallicRoughness.baseColorFactor ) ) {
  1709. var array = metallicRoughness.baseColorFactor;
  1710. materialParams.color.fromArray( array );
  1711. materialParams.opacity = array[ 3 ];
  1712. }
  1713. if ( metallicRoughness.baseColorTexture !== undefined ) {
  1714. pending.push( parser.assignTexture( materialParams, 'map', metallicRoughness.baseColorTexture ) );
  1715. }
  1716. materialParams.metalness = metallicRoughness.metallicFactor !== undefined ? metallicRoughness.metallicFactor : 1.0;
  1717. materialParams.roughness = metallicRoughness.roughnessFactor !== undefined ? metallicRoughness.roughnessFactor : 1.0;
  1718. if ( metallicRoughness.metallicRoughnessTexture !== undefined ) {
  1719. pending.push( parser.assignTexture( materialParams, 'metalnessMap', metallicRoughness.metallicRoughnessTexture ) );
  1720. pending.push( parser.assignTexture( materialParams, 'roughnessMap', metallicRoughness.metallicRoughnessTexture ) );
  1721. }
  1722. materialType = this._invokeOne( function ( ext ) {
  1723. return ext.getMaterialType && ext.getMaterialType( materialIndex );
  1724. } );
  1725. pending.push( Promise.all( this._invokeAll( function ( ext ) {
  1726. return ext.extendMaterialParams && ext.extendMaterialParams( materialIndex, materialParams );
  1727. } ) ) );
  1728. }
  1729. if ( materialDef.doubleSided === true ) {
  1730. materialParams.side = THREE.DoubleSide;
  1731. }
  1732. var alphaMode = materialDef.alphaMode || ALPHA_MODES.OPAQUE;
  1733. if ( alphaMode === ALPHA_MODES.BLEND ) {
  1734. materialParams.transparent = true;
  1735. // See: https://github.com/mrdoob/three.js/issues/17706
  1736. materialParams.depthWrite = false;
  1737. } else {
  1738. materialParams.transparent = false;
  1739. if ( alphaMode === ALPHA_MODES.MASK ) {
  1740. materialParams.alphaTest = materialDef.alphaCutoff !== undefined ? materialDef.alphaCutoff : 0.5;
  1741. }
  1742. }
  1743. if ( materialDef.normalTexture !== undefined && materialType !== THREE.MeshBasicMaterial ) {
  1744. pending.push( parser.assignTexture( materialParams, 'normalMap', materialDef.normalTexture ) );
  1745. // https://github.com/mrdoob/three.js/issues/11438#issuecomment-507003995
  1746. materialParams.normalScale = new THREE.Vector2( 1, -1 );
  1747. if ( materialDef.normalTexture.scale !== undefined ) {
  1748. materialParams.normalScale.set( materialDef.normalTexture.scale, -materialDef.normalTexture.scale );
  1749. }
  1750. }
  1751. if ( materialDef.occlusionTexture !== undefined && materialType !== THREE.MeshBasicMaterial ) {
  1752. pending.push( parser.assignTexture( materialParams, 'aoMap', materialDef.occlusionTexture ) );
  1753. if ( materialDef.occlusionTexture.strength !== undefined ) {
  1754. materialParams.aoMapIntensity = materialDef.occlusionTexture.strength;
  1755. }
  1756. }
  1757. if ( materialDef.emissiveFactor !== undefined && materialType !== THREE.MeshBasicMaterial ) {
  1758. materialParams.emissive = new THREE.Color().fromArray( materialDef.emissiveFactor );
  1759. }
  1760. if ( materialDef.emissiveTexture !== undefined && materialType !== THREE.MeshBasicMaterial ) {
  1761. pending.push( parser.assignTexture( materialParams, 'emissiveMap', materialDef.emissiveTexture ) );
  1762. }
  1763. return Promise.all( pending ).then( function () {
  1764. var material;
  1765. if ( materialType === GLTFMeshStandardSGMaterial ) {
  1766. material = extensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ].createMaterial( materialParams );
  1767. } else {
  1768. material = new materialType( materialParams );
  1769. }
  1770. if ( materialDef.name ) material.name = materialDef.name;
  1771. // baseColorTexture, emissiveTexture, and specularGlossinessTexture use sRGB encoding.
  1772. if ( material.map ) material.map.encoding = THREE.sRGBEncoding;
  1773. if ( material.emissiveMap ) material.emissiveMap.encoding = THREE.sRGBEncoding;
  1774. assignExtrasToUserData( material, materialDef );
  1775. parser.associations.set( material, { type: 'materials', index: materialIndex } );
  1776. if ( materialDef.extensions ) addUnknownExtensionsToUserData( extensions, material, materialDef );
  1777. return material;
  1778. } );
  1779. };
  1780. /** When Object3D instances are targeted by animation, they need unique names. */
  1781. GLTFParser.prototype.createUniqueName = function ( originalName ) {
  1782. var sanitizedName = THREE.PropertyBinding.sanitizeNodeName( originalName || '' );
  1783. var name = sanitizedName;
  1784. for ( var i = 1; this.nodeNamesUsed[ name ]; ++ i ) {
  1785. name = sanitizedName + '_' + i;
  1786. }
  1787. this.nodeNamesUsed[ name ] = true;
  1788. return name;
  1789. };
  1790. /**
  1791. * @param {THREE.BufferGeometry} geometry
  1792. * @param {GLTF.Primitive} primitiveDef
  1793. * @param {GLTFParser} parser
  1794. */
  1795. function computeBounds( geometry, primitiveDef, parser ) {
  1796. var attributes = primitiveDef.attributes;
  1797. var box = new THREE.Box3();
  1798. if ( attributes.POSITION !== undefined ) {
  1799. var accessor = parser.json.accessors[ attributes.POSITION ];
  1800. var min = accessor.min;
  1801. var max = accessor.max;
  1802. // glTF requires 'min' and 'max', but VRM (which extends glTF) currently ignores that requirement.
  1803. if ( min !== undefined && max !== undefined ) {
  1804. box.set(
  1805. new THREE.Vector3( min[ 0 ], min[ 1 ], min[ 2 ] ),
  1806. new THREE.Vector3( max[ 0 ], max[ 1 ], max[ 2 ] ) );
  1807. } else {
  1808. console.warn( 'THREE.GLTFLoader: Missing min/max properties for accessor POSITION.' );
  1809. return;
  1810. }
  1811. } else {
  1812. return;
  1813. }
  1814. var targets = primitiveDef.targets;
  1815. if ( targets !== undefined ) {
  1816. var maxDisplacement = new THREE.Vector3();
  1817. var vector = new THREE.Vector3();
  1818. for ( var i = 0, il = targets.length; i < il; i ++ ) {
  1819. var target = targets[ i ];
  1820. if ( target.POSITION !== undefined ) {
  1821. var accessor = parser.json.accessors[ target.POSITION ];
  1822. var min = accessor.min;
  1823. var max = accessor.max;
  1824. // glTF requires 'min' and 'max', but VRM (which extends glTF) currently ignores that requirement.
  1825. if ( min !== undefined && max !== undefined ) {
  1826. // we need to get max of absolute components because target weight is [-1,1]
  1827. vector.setX( Math.max( Math.abs( min[ 0 ] ), Math.abs( max[ 0 ] ) ) );
  1828. vector.setY( Math.max( Math.abs( min[ 1 ] ), Math.abs( max[ 1 ] ) ) );
  1829. vector.setZ( Math.max( Math.abs( min[ 2 ] ), Math.abs( max[ 2 ] ) ) );
  1830. // Note: this assumes that the sum of all weights is at most 1. This isn't quite correct - it's more conservative
  1831. // to assume that each target can have a max weight of 1. However, for some use cases - notably, when morph targets
  1832. // are used to implement key-frame animations and as such only two are active at a time - this results in very large
  1833. // boxes. So for now we make a box that's sometimes a touch too small but is hopefully mostly of reasonable size.
  1834. maxDisplacement.max( vector );
  1835. } else {
  1836. console.warn( 'THREE.GLTFLoader: Missing min/max properties for accessor POSITION.' );
  1837. }
  1838. }
  1839. }
  1840. // As per comment above this box isn't conservative, but has a reasonable size for a very large number of morph targets.
  1841. box.expandByVector( maxDisplacement );
  1842. }
  1843. geometry.boundingBox = box;
  1844. var sphere = new THREE.Sphere();
  1845. box.getCenter( sphere.center );
  1846. sphere.radius = box.min.distanceTo( box.max ) / 2;
  1847. geometry.boundingSphere = sphere;
  1848. }
  1849. /**
  1850. * @param {THREE.BufferGeometry} geometry
  1851. * @param {GLTF.Primitive} primitiveDef
  1852. * @param {GLTFParser} parser
  1853. * @return {Promise<THREE.BufferGeometry>}
  1854. */
  1855. function addPrimitiveAttributes( geometry, primitiveDef, parser ) {
  1856. var attributes = primitiveDef.attributes;
  1857. var pending = [];
  1858. function assignAttributeAccessor( accessorIndex, attributeName ) {
  1859. return parser.getDependency( 'accessor', accessorIndex )
  1860. .then( function ( accessor ) {
  1861. geometry.setAttribute( attributeName, accessor );
  1862. } );
  1863. }
  1864. for ( var gltfAttributeName in attributes ) {
  1865. var threeAttributeName = ATTRIBUTES[ gltfAttributeName ] || gltfAttributeName.toLowerCase();
  1866. // Skip attributes already provided by e.g. Draco extension.
  1867. if ( threeAttributeName in geometry.attributes ) continue;
  1868. pending.push( assignAttributeAccessor( attributes[ gltfAttributeName ], threeAttributeName ) );
  1869. }
  1870. if ( primitiveDef.indices !== undefined && ! geometry.index ) {
  1871. var accessor = parser.getDependency( 'accessor', primitiveDef.indices ).then( function ( accessor ) {
  1872. geometry.setIndex( accessor );
  1873. } );
  1874. pending.push( accessor );
  1875. }
  1876. assignExtrasToUserData( geometry, primitiveDef );
  1877. computeBounds( geometry, primitiveDef, parser );
  1878. return Promise.all( pending ).then( function () {
  1879. return primitiveDef.targets !== undefined
  1880. ? addMorphTargets( geometry, primitiveDef.targets, parser )
  1881. : geometry;
  1882. } );
  1883. }
  1884. /**
  1885. * @param {THREE.BufferGeometry} geometry
  1886. * @param {Number} drawMode
  1887. * @return {THREE.BufferGeometry}
  1888. */
  1889. function toTrianglesDrawMode( geometry, drawMode ) {
  1890. var index = geometry.getIndex();
  1891. // generate index if not present
  1892. if ( index === null ) {
  1893. var indices = [];
  1894. var position = geometry.getAttribute( 'position' );
  1895. if ( position !== undefined ) {
  1896. for ( var i = 0; i < position.count; i ++ ) {
  1897. indices.push( i );
  1898. }
  1899. geometry.setIndex( indices );
  1900. index = geometry.getIndex();
  1901. } else {
  1902. console.error( 'THREE.GLTFLoader.toTrianglesDrawMode(): Undefined position attribute. Processing not possible.' );
  1903. return geometry;
  1904. }
  1905. }
  1906. //
  1907. var numberOfTriangles = index.count - 2;
  1908. var newIndices = [];
  1909. if ( drawMode === THREE.TriangleFanDrawMode ) {
  1910. // gl.TRIANGLE_FAN
  1911. for ( var i = 1; i <= numberOfTriangles; i ++ ) {
  1912. newIndices.push( index.getX( 0 ) );
  1913. newIndices.push( index.getX( i ) );
  1914. newIndices.push( index.getX( i + 1 ) );
  1915. }
  1916. } else {
  1917. // gl.TRIANGLE_STRIP
  1918. for ( var i = 0; i < numberOfTriangles; i ++ ) {
  1919. if ( i % 2 === 0 ) {
  1920. newIndices.push( index.getX( i ) );
  1921. newIndices.push( index.getX( i + 1 ) );
  1922. newIndices.push( index.getX( i + 2 ) );
  1923. } else {
  1924. newIndices.push( index.getX( i + 2 ) );
  1925. newIndices.push( index.getX( i + 1 ) );
  1926. newIndices.push( index.getX( i ) );
  1927. }
  1928. }
  1929. }
  1930. if ( ( newIndices.length / 3 ) !== numberOfTriangles ) {
  1931. console.error( 'THREE.GLTFLoader.toTrianglesDrawMode(): Unable to generate correct amount of triangles.' );
  1932. }
  1933. // build final geometry
  1934. var newGeometry = geometry.clone();
  1935. newGeometry.setIndex( newIndices );
  1936. return newGeometry;
  1937. }
  1938. /**
  1939. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#geometry
  1940. *
  1941. * Creates BufferGeometries from primitives.
  1942. *
  1943. * @param {Array<GLTF.Primitive>} primitives
  1944. * @return {Promise<Array<THREE.BufferGeometry>>}
  1945. */
  1946. GLTFParser.prototype.loadGeometries = function ( primitives ) {
  1947. var parser = this;
  1948. var extensions = this.extensions;
  1949. var cache = this.primitiveCache;
  1950. function createDracoPrimitive( primitive ) {
  1951. return extensions[ EXTENSIONS.KHR_DRACO_MESH_COMPRESSION ]
  1952. .decodePrimitive( primitive, parser )
  1953. .then( function ( geometry ) {
  1954. return addPrimitiveAttributes( geometry, primitive, parser );
  1955. } );
  1956. }
  1957. var pending = [];
  1958. for ( var i = 0, il = primitives.length; i < il; i ++ ) {
  1959. var primitive = primitives[ i ];
  1960. var cacheKey = createPrimitiveKey( primitive );
  1961. // See if we've already created this geometry
  1962. var cached = cache[ cacheKey ];
  1963. if ( cached ) {
  1964. // Use the cached geometry if it exists
  1965. pending.push( cached.promise );
  1966. } else {
  1967. var geometryPromise;
  1968. if ( primitive.extensions && primitive.extensions[ EXTENSIONS.KHR_DRACO_MESH_COMPRESSION ] ) {
  1969. // Use DRACO geometry if available
  1970. geometryPromise = createDracoPrimitive( primitive );
  1971. } else {
  1972. // Otherwise create a new geometry
  1973. geometryPromise = addPrimitiveAttributes( new THREE.BufferGeometry(), primitive, parser );
  1974. }
  1975. // Cache this geometry
  1976. cache[ cacheKey ] = { primitive: primitive, promise: geometryPromise };
  1977. pending.push( geometryPromise );
  1978. }
  1979. }
  1980. return Promise.all( pending );
  1981. };
  1982. /**
  1983. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#meshes
  1984. * @param {number} meshIndex
  1985. * @return {Promise<THREE.Group|THREE.Mesh|THREE.SkinnedMesh>}
  1986. */
  1987. GLTFParser.prototype.loadMesh = function ( meshIndex ) {
  1988. var parser = this;
  1989. var json = this.json;
  1990. var extensions = this.extensions;
  1991. var meshDef = json.meshes[ meshIndex ];
  1992. var primitives = meshDef.primitives;
  1993. var pending = [];
  1994. for ( var i = 0, il = primitives.length; i < il; i ++ ) {
  1995. var material = primitives[ i ].material === undefined
  1996. ? createDefaultMaterial( this.cache )
  1997. : this.getDependency( 'material', primitives[ i ].material );
  1998. pending.push( material );
  1999. }
  2000. pending.push( parser.loadGeometries( primitives ) );
  2001. return Promise.all( pending ).then( function ( results ) {
  2002. var materials = results.slice( 0, results.length - 1 );
  2003. var geometries = results[ results.length - 1 ];
  2004. var meshes = [];
  2005. for ( var i = 0, il = geometries.length; i < il; i ++ ) {
  2006. var geometry = geometries[ i ];
  2007. var primitive = primitives[ i ];
  2008. // 1. create Mesh
  2009. var mesh;
  2010. var material = materials[ i ];
  2011. if ( primitive.mode === WEBGL_CONSTANTS.TRIANGLES ||
  2012. primitive.mode === WEBGL_CONSTANTS.TRIANGLE_STRIP ||
  2013. primitive.mode === WEBGL_CONSTANTS.TRIANGLE_FAN ||
  2014. primitive.mode === undefined ) {
  2015. // .isSkinnedMesh isn't in glTF spec. See ._markDefs()
  2016. mesh = meshDef.isSkinnedMesh === true
  2017. ? new THREE.SkinnedMesh( geometry, material )
  2018. : new THREE.Mesh( geometry, material );
  2019. if ( mesh.isSkinnedMesh === true && ! mesh.geometry.attributes.skinWeight.normalized ) {
  2020. // we normalize floating point skin weight array to fix malformed assets (see #15319)
  2021. // it's important to skip this for non-float32 data since normalizeSkinWeights assumes non-normalized inputs
  2022. mesh.normalizeSkinWeights();
  2023. }
  2024. if ( primitive.mode === WEBGL_CONSTANTS.TRIANGLE_STRIP ) {
  2025. mesh.geometry = toTrianglesDrawMode( mesh.geometry, THREE.TriangleStripDrawMode );
  2026. } else if ( primitive.mode === WEBGL_CONSTANTS.TRIANGLE_FAN ) {
  2027. mesh.geometry = toTrianglesDrawMode( mesh.geometry, THREE.TriangleFanDrawMode );
  2028. }
  2029. } else if ( primitive.mode === WEBGL_CONSTANTS.LINES ) {
  2030. mesh = new THREE.LineSegments( geometry, material );
  2031. } else if ( primitive.mode === WEBGL_CONSTANTS.LINE_STRIP ) {
  2032. mesh = new THREE.Line( geometry, material );
  2033. } else if ( primitive.mode === WEBGL_CONSTANTS.LINE_LOOP ) {
  2034. mesh = new THREE.LineLoop( geometry, material );
  2035. } else if ( primitive.mode === WEBGL_CONSTANTS.POINTS ) {
  2036. mesh = new THREE.Points( geometry, material );
  2037. } else {
  2038. throw new Error( 'THREE.GLTFLoader: Primitive mode unsupported: ' + primitive.mode );
  2039. }
  2040. if ( Object.keys( mesh.geometry.morphAttributes ).length > 0 ) {
  2041. updateMorphTargets( mesh, meshDef );
  2042. }
  2043. mesh.name = parser.createUniqueName( meshDef.name || ( 'mesh_' + meshIndex ) );
  2044. assignExtrasToUserData( mesh, meshDef );
  2045. if ( primitive.extensions ) addUnknownExtensionsToUserData( extensions, mesh, primitive );
  2046. parser.assignFinalMaterial( mesh );
  2047. meshes.push( mesh );
  2048. }
  2049. if ( meshes.length === 1 ) {
  2050. return meshes[ 0 ];
  2051. }
  2052. var group = new THREE.Group();
  2053. for ( var i = 0, il = meshes.length; i < il; i ++ ) {
  2054. group.add( meshes[ i ] );
  2055. }
  2056. return group;
  2057. } );
  2058. };
  2059. /**
  2060. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#cameras
  2061. * @param {number} cameraIndex
  2062. * @return {Promise<THREE.Camera>}
  2063. */
  2064. GLTFParser.prototype.loadCamera = function ( cameraIndex ) {
  2065. var camera;
  2066. var cameraDef = this.json.cameras[ cameraIndex ];
  2067. var params = cameraDef[ cameraDef.type ];
  2068. if ( ! params ) {
  2069. console.warn( 'THREE.GLTFLoader: Missing camera parameters.' );
  2070. return;
  2071. }
  2072. if ( cameraDef.type === 'perspective' ) {
  2073. camera = new THREE.PerspectiveCamera( THREE.MathUtils.radToDeg( params.yfov ), params.aspectRatio || 1, params.znear || 1, params.zfar || 2e6 );
  2074. } else if ( cameraDef.type === 'orthographic' ) {
  2075. camera = new THREE.OrthographicCamera( - params.xmag, params.xmag, params.ymag, - params.ymag, params.znear, params.zfar );
  2076. }
  2077. if ( cameraDef.name ) camera.name = this.createUniqueName( cameraDef.name );
  2078. assignExtrasToUserData( camera, cameraDef );
  2079. return Promise.resolve( camera );
  2080. };
  2081. /**
  2082. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins
  2083. * @param {number} skinIndex
  2084. * @return {Promise<Object>}
  2085. */
  2086. GLTFParser.prototype.loadSkin = function ( skinIndex ) {
  2087. var skinDef = this.json.skins[ skinIndex ];
  2088. var skinEntry = { joints: skinDef.joints };
  2089. if ( skinDef.inverseBindMatrices === undefined ) {
  2090. return Promise.resolve( skinEntry );
  2091. }
  2092. return this.getDependency( 'accessor', skinDef.inverseBindMatrices ).then( function ( accessor ) {
  2093. skinEntry.inverseBindMatrices = accessor;
  2094. return skinEntry;
  2095. } );
  2096. };
  2097. /**
  2098. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#animations
  2099. * @param {number} animationIndex
  2100. * @return {Promise<THREE.AnimationClip>}
  2101. */
  2102. GLTFParser.prototype.loadAnimation = function ( animationIndex ) {
  2103. var json = this.json;
  2104. var animationDef = json.animations[ animationIndex ];
  2105. var pendingNodes = [];
  2106. var pendingInputAccessors = [];
  2107. var pendingOutputAccessors = [];
  2108. var pendingSamplers = [];
  2109. var pendingTargets = [];
  2110. for ( var i = 0, il = animationDef.channels.length; i < il; i ++ ) {
  2111. var channel = animationDef.channels[ i ];
  2112. var sampler = animationDef.samplers[ channel.sampler ];
  2113. var target = channel.target;
  2114. var name = target.node !== undefined ? target.node : target.id; // NOTE: target.id is deprecated.
  2115. var input = animationDef.parameters !== undefined ? animationDef.parameters[ sampler.input ] : sampler.input;
  2116. var output = animationDef.parameters !== undefined ? animationDef.parameters[ sampler.output ] : sampler.output;
  2117. pendingNodes.push( this.getDependency( 'node', name ) );
  2118. pendingInputAccessors.push( this.getDependency( 'accessor', input ) );
  2119. pendingOutputAccessors.push( this.getDependency( 'accessor', output ) );
  2120. pendingSamplers.push( sampler );
  2121. pendingTargets.push( target );
  2122. }
  2123. return Promise.all( [
  2124. Promise.all( pendingNodes ),
  2125. Promise.all( pendingInputAccessors ),
  2126. Promise.all( pendingOutputAccessors ),
  2127. Promise.all( pendingSamplers ),
  2128. Promise.all( pendingTargets )
  2129. ] ).then( function ( dependencies ) {
  2130. var nodes = dependencies[ 0 ];
  2131. var inputAccessors = dependencies[ 1 ];
  2132. var outputAccessors = dependencies[ 2 ];
  2133. var samplers = dependencies[ 3 ];
  2134. var targets = dependencies[ 4 ];
  2135. var tracks = [];
  2136. for ( var i = 0, il = nodes.length; i < il; i ++ ) {
  2137. var node = nodes[ i ];
  2138. var inputAccessor = inputAccessors[ i ];
  2139. var outputAccessor = outputAccessors[ i ];
  2140. var sampler = samplers[ i ];
  2141. var target = targets[ i ];
  2142. if ( node === undefined ) continue;
  2143. node.updateMatrix();
  2144. node.matrixAutoUpdate = true;
  2145. var TypedKeyframeTrack;
  2146. switch ( PATH_PROPERTIES[ target.path ] ) {
  2147. case PATH_PROPERTIES.weights:
  2148. TypedKeyframeTrack = THREE.NumberKeyframeTrack;
  2149. break;
  2150. case PATH_PROPERTIES.rotation:
  2151. TypedKeyframeTrack = THREE.QuaternionKeyframeTrack;
  2152. break;
  2153. case PATH_PROPERTIES.position:
  2154. case PATH_PROPERTIES.scale:
  2155. default:
  2156. TypedKeyframeTrack = THREE.VectorKeyframeTrack;
  2157. break;
  2158. }
  2159. var targetName = node.name ? node.name : node.uuid;
  2160. var interpolation = sampler.interpolation !== undefined ? INTERPOLATION[ sampler.interpolation ] : THREE.InterpolateLinear;
  2161. var targetNames = [];
  2162. if ( PATH_PROPERTIES[ target.path ] === PATH_PROPERTIES.weights ) {
  2163. // Node may be a THREE.Group (glTF mesh with several primitives) or a THREE.Mesh.
  2164. node.traverse( function ( object ) {
  2165. if ( object.isMesh === true && object.morphTargetInfluences ) {
  2166. targetNames.push( object.name ? object.name : object.uuid );
  2167. }
  2168. } );
  2169. } else {
  2170. targetNames.push( targetName );
  2171. }
  2172. var outputArray = outputAccessor.array;
  2173. if ( outputAccessor.normalized ) {
  2174. var scale;
  2175. if ( outputArray.constructor === Int8Array ) {
  2176. scale = 1 / 127;
  2177. } else if ( outputArray.constructor === Uint8Array ) {
  2178. scale = 1 / 255;
  2179. } else if ( outputArray.constructor == Int16Array ) {
  2180. scale = 1 / 32767;
  2181. } else if ( outputArray.constructor === Uint16Array ) {
  2182. scale = 1 / 65535;
  2183. } else {
  2184. throw new Error( 'THREE.GLTFLoader: Unsupported output accessor component type.' );
  2185. }
  2186. var scaled = new Float32Array( outputArray.length );
  2187. for ( var j = 0, jl = outputArray.length; j < jl; j ++ ) {
  2188. scaled[ j ] = outputArray[ j ] * scale;
  2189. }
  2190. outputArray = scaled;
  2191. }
  2192. for ( var j = 0, jl = targetNames.length; j < jl; j ++ ) {
  2193. var track = new TypedKeyframeTrack(
  2194. targetNames[ j ] + '.' + PATH_PROPERTIES[ target.path ],
  2195. inputAccessor.array,
  2196. outputArray,
  2197. interpolation
  2198. );
  2199. // Override interpolation with custom factory method.
  2200. if ( sampler.interpolation === 'CUBICSPLINE' ) {
  2201. track.createInterpolant = function InterpolantFactoryMethodGLTFCubicSpline( result ) {
  2202. // A CUBICSPLINE keyframe in glTF has three output values for each input value,
  2203. // representing inTangent, splineVertex, and outTangent. As a result, track.getValueSize()
  2204. // must be divided by three to get the interpolant's sampleSize argument.
  2205. return new GLTFCubicSplineInterpolant( this.times, this.values, this.getValueSize() / 3, result );
  2206. };
  2207. // Mark as CUBICSPLINE. `track.getInterpolation()` doesn't support custom interpolants.
  2208. track.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline = true;
  2209. }
  2210. tracks.push( track );
  2211. }
  2212. }
  2213. var name = animationDef.name ? animationDef.name : 'animation_' + animationIndex;
  2214. return new THREE.AnimationClip( name, undefined, tracks );
  2215. } );
  2216. };
  2217. /**
  2218. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#nodes-and-hierarchy
  2219. * @param {number} nodeIndex
  2220. * @return {Promise<THREE.Object3D>}
  2221. */
  2222. GLTFParser.prototype.loadNode = function ( nodeIndex ) {
  2223. var json = this.json;
  2224. var extensions = this.extensions;
  2225. var parser = this;
  2226. var nodeDef = json.nodes[ nodeIndex ];
  2227. // reserve node's name before its dependencies, so the root has the intended name.
  2228. var nodeName = nodeDef.name ? parser.createUniqueName( nodeDef.name ) : '';
  2229. return ( function () {
  2230. var pending = [];
  2231. if ( nodeDef.mesh !== undefined ) {
  2232. pending.push( parser.getDependency( 'mesh', nodeDef.mesh ).then( function ( mesh ) {
  2233. var node = parser._getNodeRef( parser.meshCache, nodeDef.mesh, mesh );
  2234. // if weights are provided on the node, override weights on the mesh.
  2235. if ( nodeDef.weights !== undefined ) {
  2236. node.traverse( function ( o ) {
  2237. if ( ! o.isMesh ) return;
  2238. for ( var i = 0, il = nodeDef.weights.length; i < il; i ++ ) {
  2239. o.morphTargetInfluences[ i ] = nodeDef.weights[ i ];
  2240. }
  2241. } );
  2242. }
  2243. return node;
  2244. } ) );
  2245. }
  2246. if ( nodeDef.camera !== undefined ) {
  2247. pending.push( parser.getDependency( 'camera', nodeDef.camera ).then( function ( camera ) {
  2248. return parser._getNodeRef( parser.cameraCache, nodeDef.camera, camera );
  2249. } ) );
  2250. }
  2251. parser._invokeAll( function ( ext ) {
  2252. return ext.createNodeAttachment && ext.createNodeAttachment( nodeIndex );
  2253. } ).forEach( function ( promise ) {
  2254. pending.push( promise );
  2255. } );
  2256. return Promise.all( pending );
  2257. }() ).then( function ( objects ) {
  2258. var node;
  2259. // .isBone isn't in glTF spec. See ._markDefs
  2260. if ( nodeDef.isBone === true ) {
  2261. node = new THREE.Bone();
  2262. } else if ( objects.length > 1 ) {
  2263. node = new THREE.Group();
  2264. } else if ( objects.length === 1 ) {
  2265. node = objects[ 0 ];
  2266. } else {
  2267. node = new THREE.Object3D();
  2268. }
  2269. if ( node !== objects[ 0 ] ) {
  2270. for ( var i = 0, il = objects.length; i < il; i ++ ) {
  2271. node.add( objects[ i ] );
  2272. }
  2273. }
  2274. if ( nodeDef.name ) {
  2275. node.userData.name = nodeDef.name;
  2276. node.name = nodeName;
  2277. }
  2278. assignExtrasToUserData( node, nodeDef );
  2279. if ( nodeDef.extensions ) addUnknownExtensionsToUserData( extensions, node, nodeDef );
  2280. if ( nodeDef.matrix !== undefined ) {
  2281. var matrix = new THREE.Matrix4();
  2282. matrix.fromArray( nodeDef.matrix );
  2283. node.applyMatrix4( matrix );
  2284. } else {
  2285. if ( nodeDef.translation !== undefined ) {
  2286. node.position.fromArray( nodeDef.translation );
  2287. }
  2288. if ( nodeDef.rotation !== undefined ) {
  2289. node.quaternion.fromArray( nodeDef.rotation );
  2290. }
  2291. if ( nodeDef.scale !== undefined ) {
  2292. node.scale.fromArray( nodeDef.scale );
  2293. }
  2294. }
  2295. parser.associations.set( node, { type: 'nodes', index: nodeIndex } );
  2296. return node;
  2297. } );
  2298. };
  2299. /**
  2300. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#scenes
  2301. * @param {number} sceneIndex
  2302. * @return {Promise<THREE.Group>}
  2303. */
  2304. GLTFParser.prototype.loadScene = function () {
  2305. // scene node hierachy builder
  2306. function buildNodeHierachy( nodeId, parentObject, json, parser ) {
  2307. var nodeDef = json.nodes[ nodeId ];
  2308. return parser.getDependency( 'node', nodeId ).then( function ( node ) {
  2309. if ( nodeDef.skin === undefined ) return node;
  2310. // build skeleton here as well
  2311. var skinEntry;
  2312. return parser.getDependency( 'skin', nodeDef.skin ).then( function ( skin ) {
  2313. skinEntry = skin;
  2314. var pendingJoints = [];
  2315. for ( var i = 0, il = skinEntry.joints.length; i < il; i ++ ) {
  2316. pendingJoints.push( parser.getDependency( 'node', skinEntry.joints[ i ] ) );
  2317. }
  2318. return Promise.all( pendingJoints );
  2319. } ).then( function ( jointNodes ) {
  2320. node.traverse( function ( mesh ) {
  2321. if ( ! mesh.isMesh ) return;
  2322. var bones = [];
  2323. var boneInverses = [];
  2324. for ( var j = 0, jl = jointNodes.length; j < jl; j ++ ) {
  2325. var jointNode = jointNodes[ j ];
  2326. if ( jointNode ) {
  2327. bones.push( jointNode );
  2328. var mat = new THREE.Matrix4();
  2329. if ( skinEntry.inverseBindMatrices !== undefined ) {
  2330. mat.fromArray( skinEntry.inverseBindMatrices.array, j * 16 );
  2331. }
  2332. boneInverses.push( mat );
  2333. } else {
  2334. console.warn( 'THREE.GLTFLoader: Joint "%s" could not be found.', skinEntry.joints[ j ] );
  2335. }
  2336. }
  2337. mesh.bind( new THREE.Skeleton( bones, boneInverses ), mesh.matrixWorld );
  2338. } );
  2339. return node;
  2340. } );
  2341. } ).then( function ( node ) {
  2342. // build node hierachy
  2343. parentObject.add( node );
  2344. var pending = [];
  2345. if ( nodeDef.children ) {
  2346. var children = nodeDef.children;
  2347. for ( var i = 0, il = children.length; i < il; i ++ ) {
  2348. var child = children[ i ];
  2349. pending.push( buildNodeHierachy( child, node, json, parser ) );
  2350. }
  2351. }
  2352. return Promise.all( pending );
  2353. } );
  2354. }
  2355. return function loadScene( sceneIndex ) {
  2356. var json = this.json;
  2357. var extensions = this.extensions;
  2358. var sceneDef = this.json.scenes[ sceneIndex ];
  2359. var parser = this;
  2360. // Loader returns Group, not Scene.
  2361. // See: https://github.com/mrdoob/three.js/issues/18342#issuecomment-578981172
  2362. var scene = new THREE.Group();
  2363. if ( sceneDef.name ) scene.name = parser.createUniqueName( sceneDef.name );
  2364. assignExtrasToUserData( scene, sceneDef );
  2365. if ( sceneDef.extensions ) addUnknownExtensionsToUserData( extensions, scene, sceneDef );
  2366. var nodeIds = sceneDef.nodes || [];
  2367. var pending = [];
  2368. for ( var i = 0, il = nodeIds.length; i < il; i ++ ) {
  2369. pending.push( buildNodeHierachy( nodeIds[ i ], scene, json, parser ) );
  2370. }
  2371. return Promise.all( pending ).then( function () {
  2372. return scene;
  2373. } );
  2374. };
  2375. }();
  2376. return GLTFLoader;
  2377. } )();