GLTFLoader.js 87 KB

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