GLTFLoader.js 89 KB

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