GLTFLoader.js 79 KB

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