GLTFLoader.js 87 KB

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