GLTFLoader.js 79 KB

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