GLTFLoader.js 107 KB

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