GLTFLoader.js 108 KB

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