GLTFLoader.js 79 KB

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