GLTFLoader.js 73 KB

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