GLTFLoader.js 83 KB

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