GLTFLoader.js 67 KB

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