GLTFLoader.js 79 KB

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