GLTFLoader.js 103 KB

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