GLTFLoader.js 92 KB

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