GLTFLoader.js 69 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800
  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 targets = primitiveDef.targets;
  780. var hasMorphPosition = false;
  781. var hasMorphNormal = false;
  782. for ( var i = 0, il = targets.length; i < il; i ++ ) {
  783. var target = targets[ i ];
  784. if ( target.POSITION !== undefined ) hasMorphPosition = true;
  785. if ( target.NORMAL !== undefined ) hasMorphNormal = true;
  786. if ( hasMorphPosition && hasMorphNormal ) break;
  787. }
  788. // unnecessary to set morph if base attributes don't exist
  789. if ( geometry.attributes.position === undefined ) hasMorphPosition = false;
  790. if ( geometry.attributes.normal === undefined ) hasMorphNormal = false;
  791. if ( ! hasMorphPosition && ! hasMorphNormal ) return;
  792. var morphPositions = [];
  793. var morphNormals = [];
  794. for ( var i = 0, il = targets.length; i < il; i ++ ) {
  795. var target = targets[ i ];
  796. var attributeName = 'morphTarget' + i;
  797. if ( hasMorphPosition ) {
  798. // Three.js morph position is absolute value. The formula is
  799. // basePosition
  800. // + weight0 * ( morphPosition0 - basePosition )
  801. // + weight1 * ( morphPosition1 - basePosition )
  802. // ...
  803. // while the glTF one is relative
  804. // basePosition
  805. // + weight0 * glTFmorphPosition0
  806. // + weight1 * glTFmorphPosition1
  807. // ...
  808. // then we need to convert from relative to absolute here.
  809. if ( target.POSITION !== undefined ) {
  810. // Cloning not to pollute original accessor
  811. var positionAttribute = cloneBufferAttribute( accessors[ target.POSITION ] );
  812. positionAttribute.name = attributeName;
  813. var position = geometry.attributes.position;
  814. for ( var j = 0, jl = positionAttribute.count; j < jl; j ++ ) {
  815. positionAttribute.setXYZ(
  816. j,
  817. positionAttribute.getX( j ) + position.getX( j ),
  818. positionAttribute.getY( j ) + position.getY( j ),
  819. positionAttribute.getZ( j ) + position.getZ( j )
  820. );
  821. }
  822. } else {
  823. positionAttribute = geometry.attributes.position;
  824. }
  825. morphPositions.push( positionAttribute );
  826. }
  827. if ( hasMorphNormal ) {
  828. // see target.POSITION's comment
  829. var normalAttribute;
  830. if ( target.NORMAL !== undefined ) {
  831. var normalAttribute = cloneBufferAttribute( accessors[ target.NORMAL ] );
  832. normalAttribute.name = attributeName;
  833. var normal = geometry.attributes.normal;
  834. for ( var j = 0, jl = normalAttribute.count; j < jl; j ++ ) {
  835. normalAttribute.setXYZ(
  836. j,
  837. normalAttribute.getX( j ) + normal.getX( j ),
  838. normalAttribute.getY( j ) + normal.getY( j ),
  839. normalAttribute.getZ( j ) + normal.getZ( j )
  840. );
  841. }
  842. } else {
  843. normalAttribute = geometry.attributes.normal;
  844. }
  845. morphNormals.push( normalAttribute );
  846. }
  847. }
  848. if ( hasMorphPosition ) geometry.morphAttributes.position = morphPositions;
  849. if ( hasMorphNormal ) geometry.morphAttributes.normal = morphNormals;
  850. mesh.updateMorphTargets();
  851. if ( meshDef.weights !== undefined ) {
  852. for ( var i = 0, il = meshDef.weights.length; i < il; i ++ ) {
  853. mesh.morphTargetInfluences[ i ] = meshDef.weights[ i ];
  854. }
  855. }
  856. // .extras has user-defined data, so check that .extras.targetNames is an array.
  857. if ( meshDef.extras && Array.isArray( meshDef.extras.targetNames ) ) {
  858. for ( var i = 0, il = meshDef.extras.targetNames.length; i < il; i ++ ) {
  859. mesh.morphTargetDictionary[ meshDef.extras.targetNames[ i ] ] = i;
  860. }
  861. }
  862. }
  863. function isPrimitiveEqual( a, b ) {
  864. if ( a.indices !== b.indices ) {
  865. return false;
  866. }
  867. var attribA = a.attributes || {};
  868. var attribB = b.attributes || {};
  869. var keysA = Object.keys( attribA );
  870. var keysB = Object.keys( attribB );
  871. if ( keysA.length !== keysB.length ) {
  872. return false;
  873. }
  874. for ( var i = 0, il = keysA.length; i < il; i ++ ) {
  875. var key = keysA[ i ];
  876. if ( attribA[ key ] !== attribB[ key ] ) {
  877. return false;
  878. }
  879. }
  880. return true;
  881. }
  882. function getCachedGeometry( cache, newPrimitive ) {
  883. for ( var i = 0, il = cache.length; i < il; i ++ ) {
  884. var cached = cache[ i ];
  885. if ( isPrimitiveEqual( cached.primitive, newPrimitive ) ) {
  886. return cached.promise;
  887. }
  888. }
  889. return null;
  890. }
  891. function cloneBufferAttribute( attribute ) {
  892. if ( attribute.isInterleavedBufferAttribute ) {
  893. var count = attribute.count;
  894. var itemSize = attribute.itemSize;
  895. var array = attribute.array.slice( 0, count * itemSize );
  896. for ( var i = 0; i < count; ++ i ) {
  897. array[ i ] = attribute.getX( i );
  898. if ( itemSize >= 2 ) array[ i + 1 ] = attribute.getY( i );
  899. if ( itemSize >= 3 ) array[ i + 2 ] = attribute.getZ( i );
  900. if ( itemSize >= 4 ) array[ i + 3 ] = attribute.getW( i );
  901. }
  902. return new THREE.BufferAttribute( array, itemSize, attribute.normalized );
  903. }
  904. return attribute.clone();
  905. }
  906. /* GLTF PARSER */
  907. function GLTFParser( json, extensions, options ) {
  908. this.json = json || {};
  909. this.extensions = extensions || {};
  910. this.options = options || {};
  911. // loader object cache
  912. this.cache = new GLTFRegistry();
  913. // BufferGeometry caching
  914. this.primitiveCache = [];
  915. this.textureLoader = new THREE.TextureLoader( this.options.manager );
  916. this.textureLoader.setCrossOrigin( this.options.crossOrigin );
  917. this.fileLoader = new THREE.FileLoader( this.options.manager );
  918. this.fileLoader.setResponseType( 'arraybuffer' );
  919. }
  920. GLTFParser.prototype.parse = function ( onLoad, onError ) {
  921. var json = this.json;
  922. // Clear the loader cache
  923. this.cache.removeAll();
  924. // Mark the special nodes/meshes in json for efficient parse
  925. this.markDefs();
  926. // Fire the callback on complete
  927. this.getMultiDependencies( [
  928. 'scene',
  929. 'animation',
  930. 'camera'
  931. ] ).then( function ( dependencies ) {
  932. var scenes = dependencies.scenes || [];
  933. var scene = scenes[ json.scene || 0 ];
  934. var animations = dependencies.animations || [];
  935. var asset = json.asset;
  936. var cameras = dependencies.cameras || [];
  937. onLoad( scene, scenes, cameras, animations, asset );
  938. } ).catch( onError );
  939. };
  940. /**
  941. * Marks the special nodes/meshes in json for efficient parse.
  942. */
  943. GLTFParser.prototype.markDefs = function () {
  944. var nodeDefs = this.json.nodes || [];
  945. var skinDefs = this.json.skins || [];
  946. var meshDefs = this.json.meshes || [];
  947. var meshReferences = {};
  948. var meshUses = {};
  949. // Nothing in the node definition indicates whether it is a Bone or an
  950. // Object3D. Use the skins' joint references to mark bones.
  951. for ( var skinIndex = 0, skinLength = skinDefs.length; skinIndex < skinLength; skinIndex ++ ) {
  952. var joints = skinDefs[ skinIndex ].joints;
  953. for ( var i = 0, il = joints.length; i < il; i ++ ) {
  954. nodeDefs[ joints[ i ] ].isBone = true;
  955. }
  956. }
  957. // Meshes can (and should) be reused by multiple nodes in a glTF asset. To
  958. // avoid having more than one THREE.Mesh with the same name, count
  959. // references and rename instances below.
  960. //
  961. // Example: CesiumMilkTruck sample model reuses "Wheel" meshes.
  962. for ( var nodeIndex = 0, nodeLength = nodeDefs.length; nodeIndex < nodeLength; nodeIndex ++ ) {
  963. var nodeDef = nodeDefs[ nodeIndex ];
  964. if ( nodeDef.mesh !== undefined ) {
  965. if ( meshReferences[ nodeDef.mesh ] === undefined ) {
  966. meshReferences[ nodeDef.mesh ] = meshUses[ nodeDef.mesh ] = 0;
  967. }
  968. meshReferences[ nodeDef.mesh ] ++;
  969. // Nothing in the mesh definition indicates whether it is
  970. // a SkinnedMesh or Mesh. Use the node's mesh reference
  971. // to mark SkinnedMesh if node has skin.
  972. if ( nodeDef.skin !== undefined ) {
  973. meshDefs[ nodeDef.mesh ].isSkinnedMesh = true;
  974. }
  975. }
  976. }
  977. this.json.meshReferences = meshReferences;
  978. this.json.meshUses = meshUses;
  979. };
  980. /**
  981. * Requests the specified dependency asynchronously, with caching.
  982. * @param {string} type
  983. * @param {number} index
  984. * @return {Promise<Object>}
  985. */
  986. GLTFParser.prototype.getDependency = function ( type, index ) {
  987. var cacheKey = type + ':' + index;
  988. var dependency = this.cache.get( cacheKey );
  989. if ( ! dependency ) {
  990. var fnName = 'load' + type.charAt( 0 ).toUpperCase() + type.slice( 1 );
  991. dependency = this[ fnName ]( index );
  992. this.cache.add( cacheKey, dependency );
  993. }
  994. return dependency;
  995. };
  996. /**
  997. * Requests all dependencies of the specified type asynchronously, with caching.
  998. * @param {string} type
  999. * @return {Promise<Array<Object>>}
  1000. */
  1001. GLTFParser.prototype.getDependencies = function ( type ) {
  1002. var dependencies = this.cache.get( type );
  1003. if ( ! dependencies ) {
  1004. var parser = this;
  1005. var defs = this.json[ type + ( type === 'mesh' ? 'es' : 's' ) ] || [];
  1006. dependencies = Promise.all( defs.map( function ( def, index ) {
  1007. return parser.getDependency( type, index );
  1008. } ) );
  1009. this.cache.add( type, dependencies );
  1010. }
  1011. return dependencies;
  1012. };
  1013. /**
  1014. * Requests all multiple dependencies of the specified types asynchronously, with caching.
  1015. * @param {Array<string>} types
  1016. * @return {Promise<Object<Array<Object>>>}
  1017. */
  1018. GLTFParser.prototype.getMultiDependencies = function ( types ) {
  1019. var results = {};
  1020. var pendings = [];
  1021. for ( var i = 0, il = types.length; i < il; i ++ ) {
  1022. var type = types[ i ];
  1023. var value = this.getDependencies( type );
  1024. value = value.then( function ( key, value ) {
  1025. results[ key ] = value;
  1026. }.bind( this, type + ( type === 'mesh' ? 'es' : 's' ) ) );
  1027. pendings.push( value );
  1028. }
  1029. return Promise.all( pendings ).then( function () {
  1030. return results;
  1031. } );
  1032. };
  1033. /**
  1034. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#buffers-and-buffer-views
  1035. * @param {number} bufferIndex
  1036. * @return {Promise<ArrayBuffer>}
  1037. */
  1038. GLTFParser.prototype.loadBuffer = function ( bufferIndex ) {
  1039. var bufferDef = this.json.buffers[ bufferIndex ];
  1040. var loader = this.fileLoader;
  1041. if ( bufferDef.type && bufferDef.type !== 'arraybuffer' ) {
  1042. throw new Error( 'THREE.GLTFLoader: ' + bufferDef.type + ' buffer type is not supported.' );
  1043. }
  1044. // If present, GLB container is required to be the first buffer.
  1045. if ( bufferDef.uri === undefined && bufferIndex === 0 ) {
  1046. return Promise.resolve( this.extensions[ EXTENSIONS.KHR_BINARY_GLTF ].body );
  1047. }
  1048. var options = this.options;
  1049. return new Promise( function ( resolve, reject ) {
  1050. loader.load( resolveURL( bufferDef.uri, options.path ), resolve, undefined, function () {
  1051. reject( new Error( 'THREE.GLTFLoader: Failed to load buffer "' + bufferDef.uri + '".' ) );
  1052. } );
  1053. } );
  1054. };
  1055. /**
  1056. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#buffers-and-buffer-views
  1057. * @param {number} bufferViewIndex
  1058. * @return {Promise<ArrayBuffer>}
  1059. */
  1060. GLTFParser.prototype.loadBufferView = function ( bufferViewIndex ) {
  1061. var bufferViewDef = this.json.bufferViews[ bufferViewIndex ];
  1062. return this.getDependency( 'buffer', bufferViewDef.buffer ).then( function ( buffer ) {
  1063. var byteLength = bufferViewDef.byteLength || 0;
  1064. var byteOffset = bufferViewDef.byteOffset || 0;
  1065. return buffer.slice( byteOffset, byteOffset + byteLength );
  1066. } );
  1067. };
  1068. /**
  1069. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#accessors
  1070. * @param {number} accessorIndex
  1071. * @return {Promise<THREE.BufferAttribute|THREE.InterleavedBufferAttribute>}
  1072. */
  1073. GLTFParser.prototype.loadAccessor = function ( accessorIndex ) {
  1074. var parser = this;
  1075. var json = this.json;
  1076. var accessorDef = this.json.accessors[ accessorIndex ];
  1077. if ( accessorDef.bufferView === undefined && accessorDef.sparse === undefined ) {
  1078. // Ignore empty accessors, which may be used to declare runtime
  1079. // information about attributes coming from another source (e.g. Draco
  1080. // compression extension).
  1081. return null;
  1082. }
  1083. var pendingBufferViews = [];
  1084. if ( accessorDef.bufferView !== undefined ) {
  1085. pendingBufferViews.push( this.getDependency( 'bufferView', accessorDef.bufferView ) );
  1086. } else {
  1087. pendingBufferViews.push( null );
  1088. }
  1089. if ( accessorDef.sparse !== undefined ) {
  1090. pendingBufferViews.push( this.getDependency( 'bufferView', accessorDef.sparse.indices.bufferView ) );
  1091. pendingBufferViews.push( this.getDependency( 'bufferView', accessorDef.sparse.values.bufferView ) );
  1092. }
  1093. return Promise.all( pendingBufferViews ).then( function ( bufferViews ) {
  1094. var bufferView = bufferViews[ 0 ];
  1095. var itemSize = WEBGL_TYPE_SIZES[ accessorDef.type ];
  1096. var TypedArray = WEBGL_COMPONENT_TYPES[ accessorDef.componentType ];
  1097. // For VEC3: itemSize is 3, elementBytes is 4, itemBytes is 12.
  1098. var elementBytes = TypedArray.BYTES_PER_ELEMENT;
  1099. var itemBytes = elementBytes * itemSize;
  1100. var byteOffset = accessorDef.byteOffset || 0;
  1101. var byteStride = json.bufferViews[ accessorDef.bufferView ].byteStride;
  1102. var normalized = accessorDef.normalized === true;
  1103. var array, bufferAttribute;
  1104. // The buffer is not interleaved if the stride is the item size in bytes.
  1105. if ( byteStride && byteStride !== itemBytes ) {
  1106. var ibCacheKey = 'InterleavedBuffer:' + accessorDef.bufferView + ':' + accessorDef.componentType;
  1107. var ib = parser.cache.get( ibCacheKey );
  1108. if ( ! ib ) {
  1109. // Use the full buffer if it's interleaved.
  1110. array = new TypedArray( bufferView );
  1111. // Integer parameters to IB/IBA are in array elements, not bytes.
  1112. ib = new THREE.InterleavedBuffer( array, byteStride / elementBytes );
  1113. parser.cache.add( ibCacheKey, ib );
  1114. }
  1115. bufferAttribute = new THREE.InterleavedBufferAttribute( ib, itemSize, byteOffset / elementBytes, normalized );
  1116. } else {
  1117. if ( bufferView === null ) {
  1118. array = new TypedArray( accessorDef.count * itemSize );
  1119. } else {
  1120. array = new TypedArray( bufferView, byteOffset, accessorDef.count * itemSize );
  1121. }
  1122. bufferAttribute = new THREE.BufferAttribute( array, itemSize, normalized );
  1123. }
  1124. // https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#sparse-accessors
  1125. if ( accessorDef.sparse !== undefined ) {
  1126. var itemSizeIndices = WEBGL_TYPE_SIZES.SCALAR;
  1127. var TypedArrayIndices = WEBGL_COMPONENT_TYPES[ accessorDef.sparse.indices.componentType ];
  1128. var byteOffsetIndices = accessorDef.sparse.indices.byteOffset || 0;
  1129. var byteOffsetValues = accessorDef.sparse.values.byteOffset || 0;
  1130. var sparseIndices = new TypedArrayIndices( bufferViews[ 1 ], byteOffsetIndices, accessorDef.sparse.count * itemSizeIndices );
  1131. var sparseValues = new TypedArray( bufferViews[ 2 ], byteOffsetValues, accessorDef.sparse.count * itemSize );
  1132. if ( bufferView !== null ) {
  1133. // Avoid modifying the original ArrayBuffer, if the bufferView wasn't initialized with zeroes.
  1134. bufferAttribute.setArray( bufferAttribute.array.slice() );
  1135. }
  1136. for ( var i = 0, il = sparseIndices.length; i < il; i ++ ) {
  1137. var index = sparseIndices[ i ];
  1138. bufferAttribute.setX( index, sparseValues[ i * itemSize ] );
  1139. if ( itemSize >= 2 ) bufferAttribute.setY( index, sparseValues[ i * itemSize + 1 ] );
  1140. if ( itemSize >= 3 ) bufferAttribute.setZ( index, sparseValues[ i * itemSize + 2 ] );
  1141. if ( itemSize >= 4 ) bufferAttribute.setW( index, sparseValues[ i * itemSize + 3 ] );
  1142. if ( itemSize >= 5 ) throw new Error( 'THREE.GLTFLoader: Unsupported itemSize in sparse BufferAttribute.' );
  1143. }
  1144. }
  1145. return bufferAttribute;
  1146. } );
  1147. };
  1148. /**
  1149. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#textures
  1150. * @param {number} textureIndex
  1151. * @return {Promise<THREE.Texture>}
  1152. */
  1153. GLTFParser.prototype.loadTexture = function ( textureIndex ) {
  1154. var parser = this;
  1155. var json = this.json;
  1156. var options = this.options;
  1157. var textureLoader = this.textureLoader;
  1158. var URL = window.URL || window.webkitURL;
  1159. var textureDef = json.textures[ textureIndex ];
  1160. var source = json.images[ textureDef.source ];
  1161. var sourceURI = source.uri;
  1162. var isObjectURL = false;
  1163. if ( source.bufferView !== undefined ) {
  1164. // Load binary image data from bufferView, if provided.
  1165. sourceURI = parser.getDependency( 'bufferView', source.bufferView ).then( function ( bufferView ) {
  1166. isObjectURL = true;
  1167. var blob = new Blob( [ bufferView ], { type: source.mimeType } );
  1168. sourceURI = URL.createObjectURL( blob );
  1169. return sourceURI;
  1170. } );
  1171. }
  1172. return Promise.resolve( sourceURI ).then( function ( sourceURI ) {
  1173. // Load Texture resource.
  1174. var loader = THREE.Loader.Handlers.get( sourceURI ) || textureLoader;
  1175. return new Promise( function ( resolve, reject ) {
  1176. loader.load( resolveURL( sourceURI, options.path ), resolve, undefined, reject );
  1177. } );
  1178. } ).then( function ( texture ) {
  1179. // Clean up resources and configure Texture.
  1180. if ( isObjectURL === true ) {
  1181. URL.revokeObjectURL( sourceURI );
  1182. }
  1183. texture.flipY = false;
  1184. if ( textureDef.name !== undefined ) texture.name = textureDef.name;
  1185. texture.format = textureDef.format !== undefined ? WEBGL_TEXTURE_FORMATS[ textureDef.format ] : THREE.RGBAFormat;
  1186. if ( textureDef.internalFormat !== undefined && texture.format !== WEBGL_TEXTURE_FORMATS[ textureDef.internalFormat ] ) {
  1187. console.warn( 'THREE.GLTFLoader: Three.js does not support texture internalFormat which is different from texture format. ' +
  1188. 'internalFormat will be forced to be the same value as format.' );
  1189. }
  1190. texture.type = textureDef.type !== undefined ? WEBGL_TEXTURE_DATATYPES[ textureDef.type ] : THREE.UnsignedByteType;
  1191. var samplers = json.samplers || {};
  1192. var sampler = samplers[ textureDef.sampler ] || {};
  1193. texture.magFilter = WEBGL_FILTERS[ sampler.magFilter ] || THREE.LinearFilter;
  1194. texture.minFilter = WEBGL_FILTERS[ sampler.minFilter ] || THREE.LinearMipMapLinearFilter;
  1195. texture.wrapS = WEBGL_WRAPPINGS[ sampler.wrapS ] || THREE.RepeatWrapping;
  1196. texture.wrapT = WEBGL_WRAPPINGS[ sampler.wrapT ] || THREE.RepeatWrapping;
  1197. return texture;
  1198. } );
  1199. };
  1200. /**
  1201. * Asynchronously assigns a texture to the given material parameters.
  1202. * @param {Object} materialParams
  1203. * @param {string} textureName
  1204. * @param {number} textureIndex
  1205. * @return {Promise}
  1206. */
  1207. GLTFParser.prototype.assignTexture = function ( materialParams, textureName, textureIndex ) {
  1208. return this.getDependency( 'texture', textureIndex ).then( function ( texture ) {
  1209. materialParams[ textureName ] = texture;
  1210. } );
  1211. };
  1212. /**
  1213. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#materials
  1214. * @param {number} materialIndex
  1215. * @return {Promise<THREE.Material>}
  1216. */
  1217. GLTFParser.prototype.loadMaterial = function ( materialIndex ) {
  1218. var parser = this;
  1219. var json = this.json;
  1220. var extensions = this.extensions;
  1221. var materialDef = this.json.materials[ materialIndex ];
  1222. var materialType;
  1223. var materialParams = {};
  1224. var materialExtensions = materialDef.extensions || {};
  1225. var pending = [];
  1226. if ( materialExtensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ] ) {
  1227. var sgExtension = extensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ];
  1228. materialType = sgExtension.getMaterialType( materialDef );
  1229. pending.push( sgExtension.extendParams( materialParams, materialDef, parser ) );
  1230. } else if ( materialExtensions[ EXTENSIONS.KHR_MATERIALS_UNLIT ] ) {
  1231. var kmuExtension = extensions[ EXTENSIONS.KHR_MATERIALS_UNLIT ];
  1232. materialType = kmuExtension.getMaterialType( materialDef );
  1233. pending.push( kmuExtension.extendParams( materialParams, materialDef, parser ) );
  1234. } else {
  1235. // Specification:
  1236. // https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#metallic-roughness-material
  1237. materialType = THREE.MeshStandardMaterial;
  1238. var metallicRoughness = materialDef.pbrMetallicRoughness || {};
  1239. materialParams.color = new THREE.Color( 1.0, 1.0, 1.0 );
  1240. materialParams.opacity = 1.0;
  1241. if ( Array.isArray( metallicRoughness.baseColorFactor ) ) {
  1242. var array = metallicRoughness.baseColorFactor;
  1243. materialParams.color.fromArray( array );
  1244. materialParams.opacity = array[ 3 ];
  1245. }
  1246. if ( metallicRoughness.baseColorTexture !== undefined ) {
  1247. pending.push( parser.assignTexture( materialParams, 'map', metallicRoughness.baseColorTexture.index ) );
  1248. }
  1249. materialParams.metalness = metallicRoughness.metallicFactor !== undefined ? metallicRoughness.metallicFactor : 1.0;
  1250. materialParams.roughness = metallicRoughness.roughnessFactor !== undefined ? metallicRoughness.roughnessFactor : 1.0;
  1251. if ( metallicRoughness.metallicRoughnessTexture !== undefined ) {
  1252. var textureIndex = metallicRoughness.metallicRoughnessTexture.index;
  1253. pending.push( parser.assignTexture( materialParams, 'metalnessMap', textureIndex ) );
  1254. pending.push( parser.assignTexture( materialParams, 'roughnessMap', textureIndex ) );
  1255. }
  1256. }
  1257. if ( materialDef.doubleSided === true ) {
  1258. materialParams.side = THREE.DoubleSide;
  1259. }
  1260. var alphaMode = materialDef.alphaMode || ALPHA_MODES.OPAQUE;
  1261. if ( alphaMode === ALPHA_MODES.BLEND ) {
  1262. materialParams.transparent = true;
  1263. } else {
  1264. materialParams.transparent = false;
  1265. if ( alphaMode === ALPHA_MODES.MASK ) {
  1266. materialParams.alphaTest = materialDef.alphaCutoff !== undefined ? materialDef.alphaCutoff : 0.5;
  1267. }
  1268. }
  1269. if ( materialDef.normalTexture !== undefined && materialType !== THREE.MeshBasicMaterial) {
  1270. pending.push( parser.assignTexture( materialParams, 'normalMap', materialDef.normalTexture.index ) );
  1271. materialParams.normalScale = new THREE.Vector2( 1, 1 );
  1272. if ( materialDef.normalTexture.scale !== undefined ) {
  1273. materialParams.normalScale.set( materialDef.normalTexture.scale, materialDef.normalTexture.scale );
  1274. }
  1275. }
  1276. if ( materialDef.occlusionTexture !== undefined && materialType !== THREE.MeshBasicMaterial) {
  1277. pending.push( parser.assignTexture( materialParams, 'aoMap', materialDef.occlusionTexture.index ) );
  1278. if ( materialDef.occlusionTexture.strength !== undefined ) {
  1279. materialParams.aoMapIntensity = materialDef.occlusionTexture.strength;
  1280. }
  1281. }
  1282. if ( materialDef.emissiveFactor !== undefined && materialType !== THREE.MeshBasicMaterial) {
  1283. materialParams.emissive = new THREE.Color().fromArray( materialDef.emissiveFactor );
  1284. }
  1285. if ( materialDef.emissiveTexture !== undefined && materialType !== THREE.MeshBasicMaterial) {
  1286. pending.push( parser.assignTexture( materialParams, 'emissiveMap', materialDef.emissiveTexture.index ) );
  1287. }
  1288. return Promise.all( pending ).then( function () {
  1289. var material;
  1290. if ( materialType === THREE.ShaderMaterial ) {
  1291. material = extensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ].createMaterial( materialParams );
  1292. } else {
  1293. material = new materialType( materialParams );
  1294. }
  1295. if ( materialDef.name !== undefined ) material.name = materialDef.name;
  1296. // Normal map textures use OpenGL conventions:
  1297. // https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#materialnormaltexture
  1298. if ( material.normalScale ) {
  1299. material.normalScale.x = - material.normalScale.x;
  1300. }
  1301. // emissiveTexture and baseColorTexture use sRGB encoding.
  1302. if ( material.map ) material.map.encoding = THREE.sRGBEncoding;
  1303. if ( material.emissiveMap ) material.emissiveMap.encoding = THREE.sRGBEncoding;
  1304. if ( materialDef.extras ) material.userData = materialDef.extras;
  1305. return material;
  1306. } );
  1307. };
  1308. /**
  1309. * @param {THREE.BufferGeometry} geometry
  1310. * @param {GLTF.Primitive} primitiveDef
  1311. * @param {Array<THREE.BufferAttribute>} accessors
  1312. */
  1313. function addPrimitiveAttributes ( geometry, primitiveDef, accessors ) {
  1314. var attributes = primitiveDef.attributes;
  1315. for ( var gltfAttributeName in attributes ) {
  1316. var threeAttributeName = ATTRIBUTES[ gltfAttributeName ];
  1317. var bufferAttribute = accessors[ attributes[ gltfAttributeName ] ];
  1318. // Skip attributes already provided by e.g. Draco extension.
  1319. if ( !threeAttributeName ) continue;
  1320. if ( threeAttributeName in geometry.attributes ) continue;
  1321. geometry.addAttribute( threeAttributeName, bufferAttribute );
  1322. }
  1323. if ( primitiveDef.indices !== undefined && !geometry.index ) {
  1324. geometry.setIndex( accessors[ primitiveDef.indices ] );
  1325. }
  1326. }
  1327. /**
  1328. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#geometry
  1329. * @param {Array<Object>} primitives
  1330. * @return {Promise<Array<THREE.BufferGeometry>>}
  1331. */
  1332. GLTFParser.prototype.loadGeometries = function ( primitives ) {
  1333. var parser = this;
  1334. var extensions = this.extensions;
  1335. var cache = this.primitiveCache;
  1336. return this.getDependencies( 'accessor' ).then( function ( accessors ) {
  1337. var pending = [];
  1338. for ( var i = 0, il = primitives.length; i < il; i ++ ) {
  1339. var primitive = primitives[ i ];
  1340. // See if we've already created this geometry
  1341. var cached = getCachedGeometry( cache, primitive );
  1342. if ( cached ) {
  1343. // Use the cached geometry if it exists
  1344. pending.push( cached );
  1345. } else if ( primitive.extensions && primitive.extensions[ EXTENSIONS.KHR_DRACO_MESH_COMPRESSION ] ) {
  1346. // Use DRACO geometry if available
  1347. var geometryPromise = extensions[ EXTENSIONS.KHR_DRACO_MESH_COMPRESSION ]
  1348. .decodePrimitive( primitive, parser )
  1349. .then( function ( geometry ) {
  1350. addPrimitiveAttributes( geometry, primitive, accessors );
  1351. return geometry;
  1352. } );
  1353. cache.push( { primitive: primitive, promise: geometryPromise } );
  1354. pending.push( geometryPromise );
  1355. } else {
  1356. // Otherwise create a new geometry
  1357. var geometry = new THREE.BufferGeometry();
  1358. addPrimitiveAttributes( geometry, primitive, accessors );
  1359. var geometryPromise = Promise.resolve( geometry );
  1360. // Cache this geometry
  1361. cache.push( {
  1362. primitive: primitive,
  1363. promise: geometryPromise
  1364. } );
  1365. pending.push( geometryPromise );
  1366. }
  1367. }
  1368. return Promise.all( pending );
  1369. } );
  1370. };
  1371. /**
  1372. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#meshes
  1373. * @param {number} meshIndex
  1374. * @return {Promise<THREE.Group|THREE.Mesh|THREE.SkinnedMesh>}
  1375. */
  1376. GLTFParser.prototype.loadMesh = function ( meshIndex ) {
  1377. var scope = this;
  1378. var json = this.json;
  1379. var extensions = this.extensions;
  1380. var meshDef = this.json.meshes[ meshIndex ];
  1381. return this.getMultiDependencies( [
  1382. 'accessor',
  1383. 'material'
  1384. ] ).then( function ( dependencies ) {
  1385. var group = new THREE.Group();
  1386. var primitives = meshDef.primitives;
  1387. return scope.loadGeometries( primitives ).then( function ( geometries ) {
  1388. for ( var i = 0, il = primitives.length; i < il; i ++ ) {
  1389. var primitive = primitives[ i ];
  1390. var geometry = geometries[ i ];
  1391. var material = primitive.material === undefined
  1392. ? createDefaultMaterial()
  1393. : dependencies.materials[ primitive.material ];
  1394. if ( material.aoMap
  1395. && geometry.attributes.uv2 === undefined
  1396. && geometry.attributes.uv !== undefined ) {
  1397. console.log( 'THREE.GLTFLoader: Duplicating UVs to support aoMap.' );
  1398. geometry.addAttribute( 'uv2', new THREE.BufferAttribute( geometry.attributes.uv.array, 2 ) );
  1399. }
  1400. // If the material will be modified later on, clone it now.
  1401. var useVertexColors = geometry.attributes.color !== undefined;
  1402. var useFlatShading = geometry.attributes.normal === undefined;
  1403. var useSkinning = meshDef.isSkinnedMesh === true;
  1404. var useMorphTargets = primitive.targets !== undefined;
  1405. if ( useVertexColors || useFlatShading || useSkinning || useMorphTargets ) {
  1406. if ( material.isGLTFSpecularGlossinessMaterial ) {
  1407. var specGlossExtension = extensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ];
  1408. material = specGlossExtension.cloneMaterial( material );
  1409. } else {
  1410. material = material.clone();
  1411. }
  1412. }
  1413. if ( useVertexColors ) {
  1414. material.vertexColors = THREE.VertexColors;
  1415. material.needsUpdate = true;
  1416. }
  1417. if ( useFlatShading ) {
  1418. material.flatShading = true;
  1419. }
  1420. var mesh;
  1421. if ( primitive.mode === WEBGL_CONSTANTS.TRIANGLES ||
  1422. primitive.mode === WEBGL_CONSTANTS.TRIANGLE_STRIP ||
  1423. primitive.mode === WEBGL_CONSTANTS.TRIANGLE_FAN ||
  1424. primitive.mode === undefined ) {
  1425. if ( useSkinning ) {
  1426. mesh = new THREE.SkinnedMesh( geometry, material );
  1427. material.skinning = true;
  1428. } else {
  1429. mesh = new THREE.Mesh( geometry, material );
  1430. }
  1431. if ( primitive.mode === WEBGL_CONSTANTS.TRIANGLE_STRIP ) {
  1432. mesh.drawMode = THREE.TriangleStripDrawMode;
  1433. } else if ( primitive.mode === WEBGL_CONSTANTS.TRIANGLE_FAN ) {
  1434. mesh.drawMode = THREE.TriangleFanDrawMode;
  1435. }
  1436. } else if ( primitive.mode === WEBGL_CONSTANTS.LINES ||
  1437. primitive.mode === WEBGL_CONSTANTS.LINE_STRIP ||
  1438. primitive.mode === WEBGL_CONSTANTS.LINE_LOOP ) {
  1439. var cacheKey = 'LineBasicMaterial:' + material.uuid;
  1440. var lineMaterial = scope.cache.get( cacheKey );
  1441. if ( ! lineMaterial ) {
  1442. lineMaterial = new THREE.LineBasicMaterial();
  1443. THREE.Material.prototype.copy.call( lineMaterial, material );
  1444. lineMaterial.color.copy( material.color );
  1445. lineMaterial.lights = false; // LineBasicMaterial doesn't support lights yet
  1446. scope.cache.add( cacheKey, lineMaterial );
  1447. }
  1448. material = lineMaterial;
  1449. if ( primitive.mode === WEBGL_CONSTANTS.LINES ) {
  1450. mesh = new THREE.LineSegments( geometry, material );
  1451. } else if ( primitive.mode === WEBGL_CONSTANTS.LINE_STRIP ) {
  1452. mesh = new THREE.Line( geometry, material );
  1453. } else {
  1454. mesh = new THREE.LineLoop( geometry, material );
  1455. }
  1456. } else if ( primitive.mode === WEBGL_CONSTANTS.POINTS ) {
  1457. var cacheKey = 'PointsMaterial:' + material.uuid;
  1458. var pointsMaterial = scope.cache.get( cacheKey );
  1459. if ( ! pointsMaterial ) {
  1460. pointsMaterial = new THREE.PointsMaterial();
  1461. THREE.Material.prototype.copy.call( pointsMaterial, material );
  1462. pointsMaterial.color.copy( material.color );
  1463. pointsMaterial.map = material.map;
  1464. pointsMaterial.lights = false; // PointsMaterial doesn't support lights yet
  1465. scope.cache.add( cacheKey, pointsMaterial );
  1466. }
  1467. material = pointsMaterial;
  1468. mesh = new THREE.Points( geometry, material );
  1469. } else {
  1470. throw new Error( 'THREE.GLTFLoader: Primitive mode unsupported: ' + primitive.mode );
  1471. }
  1472. mesh.name = meshDef.name || ( 'mesh_' + meshIndex );
  1473. if ( useMorphTargets ) {
  1474. addMorphTargets( mesh, meshDef, primitive, dependencies.accessors );
  1475. material.morphTargets = true;
  1476. if ( mesh.geometry.morphAttributes.normal !== undefined ) material.morphNormals = true;
  1477. }
  1478. if ( meshDef.extras !== undefined ) mesh.userData = meshDef.extras;
  1479. if ( primitive.extras !== undefined ) mesh.geometry.userData = primitive.extras;
  1480. // for Specular-Glossiness.
  1481. if ( material.isGLTFSpecularGlossinessMaterial === true ) {
  1482. mesh.onBeforeRender = extensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ].refreshUniforms;
  1483. }
  1484. if ( primitives.length > 1 ) {
  1485. mesh.name += '_' + i;
  1486. group.add( mesh );
  1487. } else {
  1488. return mesh;
  1489. }
  1490. }
  1491. return group;
  1492. } );
  1493. } );
  1494. };
  1495. /**
  1496. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#cameras
  1497. * @param {number} cameraIndex
  1498. * @return {Promise<THREE.Camera>}
  1499. */
  1500. GLTFParser.prototype.loadCamera = function ( cameraIndex ) {
  1501. var camera;
  1502. var cameraDef = this.json.cameras[ cameraIndex ];
  1503. var params = cameraDef[ cameraDef.type ];
  1504. if ( ! params ) {
  1505. console.warn( 'THREE.GLTFLoader: Missing camera parameters.' );
  1506. return;
  1507. }
  1508. if ( cameraDef.type === 'perspective' ) {
  1509. camera = new THREE.PerspectiveCamera( THREE.Math.radToDeg( params.yfov ), params.aspectRatio || 1, params.znear || 1, params.zfar || 2e6 );
  1510. } else if ( cameraDef.type === 'orthographic' ) {
  1511. camera = new THREE.OrthographicCamera( params.xmag / - 2, params.xmag / 2, params.ymag / 2, params.ymag / - 2, params.znear, params.zfar );
  1512. }
  1513. if ( cameraDef.name !== undefined ) camera.name = cameraDef.name;
  1514. if ( cameraDef.extras ) camera.userData = cameraDef.extras;
  1515. return Promise.resolve( camera );
  1516. };
  1517. /**
  1518. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins
  1519. * @param {number} skinIndex
  1520. * @return {Promise<Object>}
  1521. */
  1522. GLTFParser.prototype.loadSkin = function ( skinIndex ) {
  1523. var skinDef = this.json.skins[ skinIndex ];
  1524. var skinEntry = { joints: skinDef.joints };
  1525. if ( skinDef.inverseBindMatrices === undefined ) {
  1526. return Promise.resolve( skinEntry );
  1527. }
  1528. return this.getDependency( 'accessor', skinDef.inverseBindMatrices ).then( function ( accessor ) {
  1529. skinEntry.inverseBindMatrices = accessor;
  1530. return skinEntry;
  1531. } );
  1532. };
  1533. /**
  1534. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#animations
  1535. * @param {number} animationIndex
  1536. * @return {Promise<THREE.AnimationClip>}
  1537. */
  1538. GLTFParser.prototype.loadAnimation = function ( animationIndex ) {
  1539. var json = this.json;
  1540. var animationDef = this.json.animations[ animationIndex ];
  1541. return this.getMultiDependencies( [
  1542. 'accessor',
  1543. 'node'
  1544. ] ).then( function ( dependencies ) {
  1545. var tracks = [];
  1546. for ( var i = 0, il = animationDef.channels.length; i < il; i ++ ) {
  1547. var channel = animationDef.channels[ i ];
  1548. var sampler = animationDef.samplers[ channel.sampler ];
  1549. if ( sampler ) {
  1550. var target = channel.target;
  1551. var name = target.node !== undefined ? target.node : target.id; // NOTE: target.id is deprecated.
  1552. var input = animationDef.parameters !== undefined ? animationDef.parameters[ sampler.input ] : sampler.input;
  1553. var output = animationDef.parameters !== undefined ? animationDef.parameters[ sampler.output ] : sampler.output;
  1554. var inputAccessor = dependencies.accessors[ input ];
  1555. var outputAccessor = dependencies.accessors[ output ];
  1556. var node = dependencies.nodes[ name ];
  1557. if ( node ) {
  1558. node.updateMatrix();
  1559. node.matrixAutoUpdate = true;
  1560. var TypedKeyframeTrack;
  1561. switch ( PATH_PROPERTIES[ target.path ] ) {
  1562. case PATH_PROPERTIES.weights:
  1563. TypedKeyframeTrack = THREE.NumberKeyframeTrack;
  1564. break;
  1565. case PATH_PROPERTIES.rotation:
  1566. TypedKeyframeTrack = THREE.QuaternionKeyframeTrack;
  1567. break;
  1568. case PATH_PROPERTIES.position:
  1569. case PATH_PROPERTIES.scale:
  1570. default:
  1571. TypedKeyframeTrack = THREE.VectorKeyframeTrack;
  1572. break;
  1573. }
  1574. var targetName = node.name ? node.name : node.uuid;
  1575. var interpolation = sampler.interpolation !== undefined ? INTERPOLATION[ sampler.interpolation ] : THREE.InterpolateLinear;
  1576. var targetNames = [];
  1577. if ( PATH_PROPERTIES[ target.path ] === PATH_PROPERTIES.weights ) {
  1578. // node should be THREE.Group here but
  1579. // PATH_PROPERTIES.weights(morphTargetInfluences) should be
  1580. // the property of a mesh object under node.
  1581. // So finding targets here.
  1582. node.traverse( function ( object ) {
  1583. if ( object.isMesh === true && object.material.morphTargets === true ) {
  1584. targetNames.push( object.name ? object.name : object.uuid );
  1585. }
  1586. } );
  1587. } else {
  1588. targetNames.push( targetName );
  1589. }
  1590. // KeyframeTrack.optimize() will modify given 'times' and 'values'
  1591. // buffers before creating a truncated copy to keep. Because buffers may
  1592. // be reused by other tracks, make copies here.
  1593. for ( var j = 0, jl = targetNames.length; j < jl; j ++ ) {
  1594. var track = new TypedKeyframeTrack(
  1595. targetNames[ j ] + '.' + PATH_PROPERTIES[ target.path ],
  1596. THREE.AnimationUtils.arraySlice( inputAccessor.array, 0 ),
  1597. THREE.AnimationUtils.arraySlice( outputAccessor.array, 0 ),
  1598. interpolation
  1599. );
  1600. // Here is the trick to enable custom interpolation.
  1601. // Overrides .createInterpolant in a factory method which creates custom interpolation.
  1602. if ( sampler.interpolation === 'CUBICSPLINE' ) {
  1603. track.createInterpolant = function InterpolantFactoryMethodGLTFCubicSpline( result ) {
  1604. // A CUBICSPLINE keyframe in glTF has three output values for each input value,
  1605. // representing inTangent, splineVertex, and outTangent. As a result, track.getValueSize()
  1606. // must be divided by three to get the interpolant's sampleSize argument.
  1607. return new GLTFCubicSplineInterpolant( this.times, this.values, this.getValueSize() / 3, result );
  1608. };
  1609. // Workaround, provide an alternate way to know if the interpolant type is cubis spline to track.
  1610. // track.getInterpolation() doesn't return valid value for custom interpolant.
  1611. track.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline = true;
  1612. }
  1613. tracks.push( track );
  1614. }
  1615. }
  1616. }
  1617. }
  1618. var name = animationDef.name !== undefined ? animationDef.name : 'animation_' + animationIndex;
  1619. return new THREE.AnimationClip( name, undefined, tracks );
  1620. } );
  1621. };
  1622. /**
  1623. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#nodes-and-hierarchy
  1624. * @param {number} nodeIndex
  1625. * @return {Promise<THREE.Object3D>}
  1626. */
  1627. GLTFParser.prototype.loadNode = function ( nodeIndex ) {
  1628. var json = this.json;
  1629. var extensions = this.extensions;
  1630. var meshReferences = this.json.meshReferences;
  1631. var meshUses = this.json.meshUses;
  1632. var nodeDef = this.json.nodes[ nodeIndex ];
  1633. return this.getMultiDependencies( [
  1634. 'mesh',
  1635. 'skin',
  1636. 'camera'
  1637. ] ).then( function ( dependencies ) {
  1638. var node;
  1639. if ( nodeDef.isBone === true ) {
  1640. node = new THREE.Bone();
  1641. } else if ( nodeDef.mesh !== undefined ) {
  1642. var mesh = dependencies.meshes[ nodeDef.mesh ];
  1643. node = mesh.clone();
  1644. // for Specular-Glossiness
  1645. if ( mesh.isGroup === true ) {
  1646. for ( var i = 0, il = mesh.children.length; i < il; i ++ ) {
  1647. var child = mesh.children[ i ];
  1648. if ( child.material && child.material.isGLTFSpecularGlossinessMaterial === true ) {
  1649. node.children[ i ].onBeforeRender = child.onBeforeRender;
  1650. }
  1651. }
  1652. } else {
  1653. if ( mesh.material && mesh.material.isGLTFSpecularGlossinessMaterial === true ) {
  1654. node.onBeforeRender = mesh.onBeforeRender;
  1655. }
  1656. }
  1657. if ( meshReferences[ nodeDef.mesh ] > 1 ) {
  1658. node.name += '_instance_' + meshUses[ nodeDef.mesh ] ++;
  1659. }
  1660. } else if ( nodeDef.camera !== undefined ) {
  1661. node = dependencies.cameras[ nodeDef.camera ];
  1662. } else if ( nodeDef.extensions
  1663. && nodeDef.extensions[ EXTENSIONS.KHR_LIGHTS ]
  1664. && nodeDef.extensions[ EXTENSIONS.KHR_LIGHTS ].light !== undefined ) {
  1665. var lights = extensions[ EXTENSIONS.KHR_LIGHTS ].lights;
  1666. node = lights[ nodeDef.extensions[ EXTENSIONS.KHR_LIGHTS ].light ];
  1667. } else {
  1668. node = new THREE.Object3D();
  1669. }
  1670. if ( nodeDef.name !== undefined ) {
  1671. node.name = THREE.PropertyBinding.sanitizeNodeName( nodeDef.name );
  1672. }
  1673. if ( nodeDef.extras ) node.userData = nodeDef.extras;
  1674. if ( nodeDef.matrix !== undefined ) {
  1675. var matrix = new THREE.Matrix4();
  1676. matrix.fromArray( nodeDef.matrix );
  1677. node.applyMatrix( matrix );
  1678. } else {
  1679. if ( nodeDef.translation !== undefined ) {
  1680. node.position.fromArray( nodeDef.translation );
  1681. }
  1682. if ( nodeDef.rotation !== undefined ) {
  1683. node.quaternion.fromArray( nodeDef.rotation );
  1684. }
  1685. if ( nodeDef.scale !== undefined ) {
  1686. node.scale.fromArray( nodeDef.scale );
  1687. }
  1688. }
  1689. return node;
  1690. } );
  1691. };
  1692. /**
  1693. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#scenes
  1694. * @param {number} sceneIndex
  1695. * @return {Promise<THREE.Scene>}
  1696. */
  1697. GLTFParser.prototype.loadScene = function () {
  1698. // scene node hierachy builder
  1699. function buildNodeHierachy( nodeId, parentObject, json, allNodes, skins ) {
  1700. var node = allNodes[ nodeId ];
  1701. var nodeDef = json.nodes[ nodeId ];
  1702. // build skeleton here as well
  1703. if ( nodeDef.skin !== undefined ) {
  1704. var meshes = node.isGroup === true ? node.children : [ node ];
  1705. for ( var i = 0, il = meshes.length; i < il; i ++ ) {
  1706. var mesh = meshes[ i ];
  1707. var skinEntry = skins[ nodeDef.skin ];
  1708. var bones = [];
  1709. var boneInverses = [];
  1710. for ( var j = 0, jl = skinEntry.joints.length; j < jl; j ++ ) {
  1711. var jointId = skinEntry.joints[ j ];
  1712. var jointNode = allNodes[ jointId ];
  1713. if ( jointNode ) {
  1714. bones.push( jointNode );
  1715. var mat = new THREE.Matrix4();
  1716. if ( skinEntry.inverseBindMatrices !== undefined ) {
  1717. mat.fromArray( skinEntry.inverseBindMatrices.array, j * 16 );
  1718. }
  1719. boneInverses.push( mat );
  1720. } else {
  1721. console.warn( 'THREE.GLTFLoader: Joint "%s" could not be found.', jointId );
  1722. }
  1723. }
  1724. mesh.bind( new THREE.Skeleton( bones, boneInverses ), mesh.matrixWorld );
  1725. }
  1726. }
  1727. // build node hierachy
  1728. parentObject.add( node );
  1729. if ( nodeDef.children ) {
  1730. var children = nodeDef.children;
  1731. for ( var i = 0, il = children.length; i < il; i ++ ) {
  1732. var child = children[ i ];
  1733. buildNodeHierachy( child, node, json, allNodes, skins );
  1734. }
  1735. }
  1736. }
  1737. return function loadScene( sceneIndex ) {
  1738. var json = this.json;
  1739. var extensions = this.extensions;
  1740. var sceneDef = this.json.scenes[ sceneIndex ];
  1741. return this.getMultiDependencies( [
  1742. 'node',
  1743. 'skin'
  1744. ] ).then( function ( dependencies ) {
  1745. var scene = new THREE.Scene();
  1746. if ( sceneDef.name !== undefined ) scene.name = sceneDef.name;
  1747. if ( sceneDef.extras ) scene.userData = sceneDef.extras;
  1748. var nodeIds = sceneDef.nodes || [];
  1749. for ( var i = 0, il = nodeIds.length; i < il; i ++ ) {
  1750. buildNodeHierachy( nodeIds[ i ], scene, json, dependencies.nodes, dependencies.skins );
  1751. }
  1752. // Ambient lighting, if present, is always attached to the scene root.
  1753. if ( sceneDef.extensions
  1754. && sceneDef.extensions[ EXTENSIONS.KHR_LIGHTS ]
  1755. && sceneDef.extensions[ EXTENSIONS.KHR_LIGHTS ].light !== undefined ) {
  1756. var lights = extensions[ EXTENSIONS.KHR_LIGHTS ].lights;
  1757. scene.add( lights[ sceneDef.extensions[ EXTENSIONS.KHR_LIGHTS ].light ] );
  1758. }
  1759. return scene;
  1760. } );
  1761. };
  1762. }();
  1763. return GLTFLoader;
  1764. } )();