GLTFLoader.js 90 KB

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