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