2
0

GLTFLoader.js 69 KB

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