GLTFLoader.js 65 KB

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