GLTFLoader.js 88 KB

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