GLTFLoader.js 65 KB

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