GLTFLoader.js 62 KB

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