GLTFLoader.js 68 KB

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