GLTFLoader.js 68 KB

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