GLTFLoader.js 108 KB

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