GLTFLoader.js 79 KB

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