GLTFLoader.js 72 KB

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