GLTFLoader.js 86 KB

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