GLTFLoader.js 83 KB

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