GLTFLoader.js 61 KB

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