GLTFLoader.js 73 KB

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