GLTFLoader.js 93 KB

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