GLTFLoader.js 66 KB

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