GLTFLoader.js 89 KB

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