GLTFLoader.js 96 KB

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