GLTFLoader.js 72 KB

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