GLTFLoader.js 91 KB

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