GLTFLoader.js 89 KB

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