GLTFLoader.js 89 KB

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