GLTFLoader.js 69 KB

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