GLTFLoader.js 68 KB

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