GLTFLoader.js 80 KB

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