GLTFLoader.js 79 KB

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