GLTFLoader.js 81 KB

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