GLTFLoader.js 71 KB

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