GLTFLoader.js 92 KB

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