2
0

GLTFLoader.js 89 KB

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