GLTFLoader.js 89 KB

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