GLTFLoader.js 77 KB

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