GLTFLoader.js 88 KB

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