ionExample.4422c37a.js 1.6 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983
  1. // modules are defined as an array
  2. // [ module function, map of requires ]
  3. //
  4. // map of requires is short require name -> numeric require
  5. //
  6. // anything defined in a previous bundle is accessed via the
  7. // orig method which is the require for previous bundles
  8. parcelRequire = (function (modules, cache, entry, globalName) {
  9. // Save the require from previous bundle to this closure if any
  10. var previousRequire = typeof parcelRequire === 'function' && parcelRequire;
  11. var nodeRequire = typeof require === 'function' && require;
  12. function newRequire(name, jumped) {
  13. if (!cache[name]) {
  14. if (!modules[name]) {
  15. // if we cannot find the module within our internal map or
  16. // cache jump to the current global require ie. the last bundle
  17. // that was added to the page.
  18. var currentRequire = typeof parcelRequire === 'function' && parcelRequire;
  19. if (!jumped && currentRequire) {
  20. return currentRequire(name, true);
  21. }
  22. // If there are other bundles on this page the require from the
  23. // previous one is saved to 'previousRequire'. Repeat this as
  24. // many times as there are bundles until the module is found or
  25. // we exhaust the require chain.
  26. if (previousRequire) {
  27. return previousRequire(name, true);
  28. }
  29. // Try the node require function if it exists.
  30. if (nodeRequire && typeof name === 'string') {
  31. return nodeRequire(name);
  32. }
  33. var err = new Error('Cannot find module \'' + name + '\'');
  34. err.code = 'MODULE_NOT_FOUND';
  35. throw err;
  36. }
  37. localRequire.resolve = resolve;
  38. localRequire.cache = {};
  39. var module = cache[name] = new newRequire.Module(name);
  40. modules[name][0].call(module.exports, localRequire, module, module.exports, this);
  41. }
  42. return cache[name].exports;
  43. function localRequire(x){
  44. return newRequire(localRequire.resolve(x));
  45. }
  46. function resolve(x){
  47. return modules[name][1][x] || x;
  48. }
  49. }
  50. function Module(moduleName) {
  51. this.id = moduleName;
  52. this.bundle = newRequire;
  53. this.exports = {};
  54. }
  55. newRequire.isParcelRequire = true;
  56. newRequire.Module = Module;
  57. newRequire.modules = modules;
  58. newRequire.cache = cache;
  59. newRequire.parent = previousRequire;
  60. newRequire.register = function (id, exports) {
  61. modules[id] = [function (require, module) {
  62. module.exports = exports;
  63. }, {}];
  64. };
  65. var error;
  66. for (var i = 0; i < entry.length; i++) {
  67. try {
  68. newRequire(entry[i]);
  69. } catch (e) {
  70. // Save first error but execute all entries
  71. if (!error) {
  72. error = e;
  73. }
  74. }
  75. }
  76. if (entry.length) {
  77. // Expose entry point to Node, AMD or browser globals
  78. // Based on https://github.com/ForbesLindesay/umd/blob/master/template.js
  79. var mainExports = newRequire(entry[entry.length - 1]);
  80. // CommonJS
  81. if (typeof exports === "object" && typeof module !== "undefined") {
  82. module.exports = mainExports;
  83. // RequireJS
  84. } else if (typeof define === "function" && define.amd) {
  85. define(function () {
  86. return mainExports;
  87. });
  88. // <script>
  89. } else if (globalName) {
  90. this[globalName] = mainExports;
  91. }
  92. }
  93. // Override the current require with this new one
  94. parcelRequire = newRequire;
  95. if (error) {
  96. // throw error from earlier, _after updating parcelRequire_
  97. throw error;
  98. }
  99. return newRequire;
  100. })({"../node_modules/three/build/three.module.js":[function(require,module,exports) {
  101. "use strict";
  102. Object.defineProperty(exports, "__esModule", {
  103. value: true
  104. });
  105. exports.AmbientLight = AmbientLight;
  106. exports.AmbientLightProbe = AmbientLightProbe;
  107. exports.AnimationClip = AnimationClip;
  108. exports.AnimationLoader = AnimationLoader;
  109. exports.AnimationMixer = AnimationMixer;
  110. exports.AnimationObjectGroup = AnimationObjectGroup;
  111. exports.ArcCurve = ArcCurve;
  112. exports.ArrayCamera = ArrayCamera;
  113. exports.AudioLoader = AudioLoader;
  114. exports.AxisHelper = AxisHelper;
  115. exports.BinaryTextureLoader = BinaryTextureLoader;
  116. exports.Bone = Bone;
  117. exports.BooleanKeyframeTrack = BooleanKeyframeTrack;
  118. exports.BoundingBoxHelper = BoundingBoxHelper;
  119. exports.BufferAttribute = BufferAttribute;
  120. exports.BufferGeometry = BufferGeometry;
  121. exports.BufferGeometryLoader = BufferGeometryLoader;
  122. exports.Camera = Camera;
  123. exports.CanvasRenderer = CanvasRenderer;
  124. exports.CanvasTexture = CanvasTexture;
  125. exports.CatmullRomCurve3 = CatmullRomCurve3;
  126. exports.ClosedSplineCurve3 = ClosedSplineCurve3;
  127. exports.ColorKeyframeTrack = ColorKeyframeTrack;
  128. exports.CompressedTexture = CompressedTexture;
  129. exports.CompressedTextureLoader = CompressedTextureLoader;
  130. exports.CubeCamera = CubeCamera;
  131. exports.CubeTexture = CubeTexture;
  132. exports.CubeTextureLoader = CubeTextureLoader;
  133. exports.CubicBezierCurve = CubicBezierCurve;
  134. exports.CubicBezierCurve3 = CubicBezierCurve3;
  135. exports.CubicInterpolant = CubicInterpolant;
  136. exports.Curve = Curve;
  137. exports.CurvePath = CurvePath;
  138. exports.DataTexture = DataTexture;
  139. exports.DataTexture2DArray = DataTexture2DArray;
  140. exports.DataTexture3D = DataTexture3D;
  141. exports.DataTextureLoader = DataTextureLoader;
  142. exports.DepthTexture = DepthTexture;
  143. exports.DirectionalLight = DirectionalLight;
  144. exports.DiscreteInterpolant = DiscreteInterpolant;
  145. exports.DynamicBufferAttribute = DynamicBufferAttribute;
  146. exports.EdgesHelper = EdgesHelper;
  147. exports.EllipseCurve = EllipseCurve;
  148. exports.EventDispatcher = EventDispatcher;
  149. exports.Face4 = Face4;
  150. exports.FileLoader = FileLoader;
  151. exports.Float16BufferAttribute = Float16BufferAttribute;
  152. exports.Float32Attribute = Float32Attribute;
  153. exports.Float32BufferAttribute = Float32BufferAttribute;
  154. exports.Float64Attribute = Float64Attribute;
  155. exports.Float64BufferAttribute = Float64BufferAttribute;
  156. exports.Font = Font;
  157. exports.FontLoader = FontLoader;
  158. exports.GLBufferAttribute = GLBufferAttribute;
  159. exports.Geometry = Geometry;
  160. exports.Group = Group;
  161. exports.HemisphereLight = HemisphereLight;
  162. exports.HemisphereLightProbe = HemisphereLightProbe;
  163. exports.ImageBitmapLoader = ImageBitmapLoader;
  164. exports.ImageLoader = ImageLoader;
  165. exports.ImmediateRenderObject = ImmediateRenderObject;
  166. exports.InstancedBufferAttribute = InstancedBufferAttribute;
  167. exports.InstancedBufferGeometry = InstancedBufferGeometry;
  168. exports.InstancedInterleavedBuffer = InstancedInterleavedBuffer;
  169. exports.InstancedMesh = InstancedMesh;
  170. exports.Int16Attribute = Int16Attribute;
  171. exports.Int16BufferAttribute = Int16BufferAttribute;
  172. exports.Int32Attribute = Int32Attribute;
  173. exports.Int32BufferAttribute = Int32BufferAttribute;
  174. exports.Int8Attribute = Int8Attribute;
  175. exports.Int8BufferAttribute = Int8BufferAttribute;
  176. exports.InterleavedBuffer = InterleavedBuffer;
  177. exports.InterleavedBufferAttribute = InterleavedBufferAttribute;
  178. exports.Interpolant = Interpolant;
  179. exports.JSONLoader = JSONLoader;
  180. exports.KeyframeTrack = KeyframeTrack;
  181. exports.LOD = LOD;
  182. exports.LensFlare = LensFlare;
  183. exports.Light = Light;
  184. exports.LightProbe = LightProbe;
  185. exports.Line = Line;
  186. exports.LineBasicMaterial = LineBasicMaterial;
  187. exports.LineCurve = LineCurve;
  188. exports.LineCurve3 = LineCurve3;
  189. exports.LineDashedMaterial = LineDashedMaterial;
  190. exports.LineLoop = LineLoop;
  191. exports.LineSegments = LineSegments;
  192. exports.LinearInterpolant = LinearInterpolant;
  193. exports.Loader = Loader;
  194. exports.LoadingManager = LoadingManager;
  195. exports.Material = Material;
  196. exports.MaterialLoader = MaterialLoader;
  197. exports.Mesh = Mesh;
  198. exports.MeshBasicMaterial = MeshBasicMaterial;
  199. exports.MeshDepthMaterial = MeshDepthMaterial;
  200. exports.MeshDistanceMaterial = MeshDistanceMaterial;
  201. exports.MeshFaceMaterial = MeshFaceMaterial;
  202. exports.MeshLambertMaterial = MeshLambertMaterial;
  203. exports.MeshMatcapMaterial = MeshMatcapMaterial;
  204. exports.MeshNormalMaterial = MeshNormalMaterial;
  205. exports.MeshPhongMaterial = MeshPhongMaterial;
  206. exports.MeshPhysicalMaterial = MeshPhysicalMaterial;
  207. exports.MeshStandardMaterial = MeshStandardMaterial;
  208. exports.MeshToonMaterial = MeshToonMaterial;
  209. exports.MultiMaterial = MultiMaterial;
  210. exports.NumberKeyframeTrack = NumberKeyframeTrack;
  211. exports.Object3D = Object3D;
  212. exports.OrthographicCamera = OrthographicCamera;
  213. exports.ParametricBufferGeometry = ParametricBufferGeometry;
  214. exports.ParametricGeometry = ParametricGeometry;
  215. exports.Particle = Particle;
  216. exports.ParticleBasicMaterial = ParticleBasicMaterial;
  217. exports.ParticleSystem = ParticleSystem;
  218. exports.ParticleSystemMaterial = ParticleSystemMaterial;
  219. exports.Path = Path;
  220. exports.PerspectiveCamera = PerspectiveCamera;
  221. exports.PointCloud = PointCloud;
  222. exports.PointCloudMaterial = PointCloudMaterial;
  223. exports.PointLight = PointLight;
  224. exports.Points = Points;
  225. exports.PointsMaterial = PointsMaterial;
  226. exports.PropertyBinding = PropertyBinding;
  227. exports.PropertyMixer = PropertyMixer;
  228. exports.QuadraticBezierCurve = QuadraticBezierCurve;
  229. exports.QuadraticBezierCurve3 = QuadraticBezierCurve3;
  230. exports.QuaternionKeyframeTrack = QuaternionKeyframeTrack;
  231. exports.QuaternionLinearInterpolant = QuaternionLinearInterpolant;
  232. exports.RawShaderMaterial = RawShaderMaterial;
  233. exports.Raycaster = Raycaster;
  234. exports.RectAreaLight = RectAreaLight;
  235. exports.ShaderMaterial = ShaderMaterial;
  236. exports.ShadowMaterial = ShadowMaterial;
  237. exports.Shape = Shape;
  238. exports.ShapePath = ShapePath;
  239. exports.Skeleton = Skeleton;
  240. exports.SkinnedMesh = SkinnedMesh;
  241. exports.Spline = Spline;
  242. exports.SplineCurve = SplineCurve;
  243. exports.SplineCurve3 = SplineCurve3;
  244. exports.SpotLight = SpotLight;
  245. exports.Sprite = Sprite;
  246. exports.SpriteMaterial = SpriteMaterial;
  247. exports.StereoCamera = StereoCamera;
  248. exports.StringKeyframeTrack = StringKeyframeTrack;
  249. exports.Texture = Texture;
  250. exports.TextureLoader = TextureLoader;
  251. exports.Uint16Attribute = Uint16Attribute;
  252. exports.Uint16BufferAttribute = Uint16BufferAttribute;
  253. exports.Uint32Attribute = Uint32Attribute;
  254. exports.Uint32BufferAttribute = Uint32BufferAttribute;
  255. exports.Uint8Attribute = Uint8Attribute;
  256. exports.Uint8BufferAttribute = Uint8BufferAttribute;
  257. exports.Uint8ClampedAttribute = Uint8ClampedAttribute;
  258. exports.Uint8ClampedBufferAttribute = Uint8ClampedBufferAttribute;
  259. exports.VectorKeyframeTrack = VectorKeyframeTrack;
  260. exports.Vertex = Vertex;
  261. exports.VideoTexture = VideoTexture;
  262. exports.WebGL1Renderer = WebGL1Renderer;
  263. exports.WebGLCubeRenderTarget = WebGLCubeRenderTarget;
  264. exports.WebGLMultisampleRenderTarget = WebGLMultisampleRenderTarget;
  265. exports.WebGLRenderTarget = WebGLRenderTarget;
  266. exports.WebGLRenderTargetCube = WebGLRenderTargetCube;
  267. exports.WebGLRenderer = WebGLRenderer;
  268. exports.WebGLUtils = WebGLUtils;
  269. exports.WireframeHelper = WireframeHelper;
  270. exports.XHRLoader = XHRLoader;
  271. exports.InterpolateSmooth = exports.InterpolateLinear = exports.InterpolateDiscrete = exports.IntType = exports.IncrementWrapStencilOp = exports.IncrementStencilOp = exports.ImageUtils = exports.IcosahedronGeometry = exports.IcosahedronBufferGeometry = exports.HemisphereLightHelper = exports.HalfFloatType = exports.GridHelper = exports.GreaterStencilFunc = exports.GreaterEqualStencilFunc = exports.GreaterEqualDepth = exports.GreaterDepth = exports.GeometryUtils = exports.GammaEncoding = exports.GLSL3 = exports.GLSL1 = exports.Frustum = exports.FrontSide = exports.FogExp2 = exports.Fog = exports.FloatType = exports.FlatShading = exports.FaceColors = exports.Face3 = exports.ExtrudeGeometry = exports.ExtrudeBufferGeometry = exports.Euler = exports.EquirectangularRefractionMapping = exports.EquirectangularReflectionMapping = exports.EqualStencilFunc = exports.EqualDepth = exports.EdgesGeometry = exports.DynamicReadUsage = exports.DynamicDrawUsage = exports.DynamicCopyUsage = exports.DstColorFactor = exports.DstAlphaFactor = exports.DoubleSide = exports.DodecahedronGeometry = exports.DodecahedronBufferGeometry = exports.DirectionalLightHelper = exports.DepthStencilFormat = exports.DepthFormat = exports.DefaultLoadingManager = exports.DecrementWrapStencilOp = exports.DecrementStencilOp = exports.DataUtils = exports.Cylindrical = exports.CylinderGeometry = exports.CylinderBufferGeometry = exports.CustomToneMapping = exports.CustomBlending = exports.CullFaceNone = exports.CullFaceFrontBack = exports.CullFaceFront = exports.CullFaceBack = exports.CubeUVRefractionMapping = exports.CubeUVReflectionMapping = exports.CubeRefractionMapping = exports.CubeReflectionMapping = exports.ConeGeometry = exports.ConeBufferGeometry = exports.Color = exports.Clock = exports.ClampToEdgeWrapping = exports.CircleGeometry = exports.CircleBufferGeometry = exports.CineonToneMapping = exports.CameraHelper = exports.Cache = exports.ByteType = exports.BoxHelper = exports.CubeGeometry = exports.BoxGeometry = exports.BoxBufferGeometry = exports.Box3Helper = exports.Box3 = exports.Box2 = exports.BasicShadowMap = exports.BasicDepthPacking = exports.BackSide = exports.AxesHelper = exports.AudioListener = exports.AudioContext = exports.AudioAnalyser = exports.Audio = exports.ArrowHelper = exports.AnimationUtils = exports.AlwaysStencilFunc = exports.AlwaysDepth = exports.AlphaFormat = exports.AdditiveBlending = exports.AdditiveAnimationBlendMode = exports.AddOperation = exports.AddEquation = exports.ACESFilmicToneMapping = void 0;
  272. exports.RGBEEncoding = exports.RGBDEncoding = exports.RGBA_S3TC_DXT5_Format = exports.RGBA_S3TC_DXT3_Format = exports.RGBA_S3TC_DXT1_Format = exports.RGBA_PVRTC_4BPPV1_Format = exports.RGBA_PVRTC_2BPPV1_Format = exports.RGBA_ETC2_EAC_Format = exports.RGBA_BPTC_Format = exports.RGBA_ASTC_8x8_Format = exports.RGBA_ASTC_8x6_Format = exports.RGBA_ASTC_8x5_Format = exports.RGBA_ASTC_6x6_Format = exports.RGBA_ASTC_6x5_Format = exports.RGBA_ASTC_5x5_Format = exports.RGBA_ASTC_5x4_Format = exports.RGBA_ASTC_4x4_Format = exports.RGBA_ASTC_12x12_Format = exports.RGBA_ASTC_12x10_Format = exports.RGBA_ASTC_10x8_Format = exports.RGBA_ASTC_10x6_Format = exports.RGBA_ASTC_10x5_Format = exports.RGBA_ASTC_10x10_Format = exports.RGBAIntegerFormat = exports.RGBAFormat = exports.RGBADepthPacking = exports.REVISION = exports.Quaternion = exports.PositionalAudio = exports.PolyhedronGeometry = exports.PolyhedronBufferGeometry = exports.PolarGridHelper = exports.PointLightHelper = exports.PlaneHelper = exports.PlaneGeometry = exports.PlaneBufferGeometry = exports.Plane = exports.PMREMGenerator = exports.PCFSoftShadowMap = exports.PCFShadowMap = exports.OneMinusSrcColorFactor = exports.OneMinusSrcAlphaFactor = exports.OneMinusDstColorFactor = exports.OneMinusDstAlphaFactor = exports.OneFactor = exports.OctahedronGeometry = exports.OctahedronBufferGeometry = exports.ObjectSpaceNormalMap = exports.ObjectLoader = exports.NotEqualStencilFunc = exports.NotEqualDepth = exports.NormalBlending = exports.NormalAnimationBlendMode = exports.NoToneMapping = exports.NoColors = exports.NoBlending = exports.NeverStencilFunc = exports.NeverDepth = exports.NearestMipmapNearestFilter = exports.NearestMipmapLinearFilter = exports.NearestMipMapNearestFilter = exports.NearestMipMapLinearFilter = exports.NearestFilter = exports.MultiplyOperation = exports.MultiplyBlending = exports.MixOperation = exports.MirroredRepeatWrapping = exports.MinEquation = exports.MaxEquation = exports.Matrix4 = exports.Matrix3 = exports.MathUtils = exports.Math = exports.MOUSE = exports.LuminanceFormat = exports.LuminanceAlphaFormat = exports.LoopRepeat = exports.LoopPingPong = exports.LoopOnce = exports.LogLuvEncoding = exports.LoaderUtils = exports.LinearToneMapping = exports.LinearMipmapNearestFilter = exports.LinearMipmapLinearFilter = exports.LinearMipMapNearestFilter = exports.LinearMipMapLinearFilter = exports.LinearFilter = exports.LinearEncoding = exports.LineStrip = exports.LinePieces = exports.Line3 = exports.LessStencilFunc = exports.LessEqualStencilFunc = exports.LessEqualDepth = exports.LessDepth = exports.Layers = exports.LatheGeometry = exports.LatheBufferGeometry = exports.KeepStencilOp = exports.InvertStencilOp = void 0;
  273. exports.ZeroStencilOp = exports.ZeroSlopeEnding = exports.ZeroFactor = exports.ZeroCurvatureEnding = exports.WrapAroundEnding = exports.WireframeGeometry = exports.VertexColors = exports.Vector4 = exports.Vector3 = exports.Vector2 = exports.VSMShadowMap = exports.UnsignedShortType = exports.UnsignedShort565Type = exports.UnsignedShort5551Type = exports.UnsignedShort4444Type = exports.UnsignedIntType = exports.UnsignedInt248Type = exports.UnsignedByteType = exports.UniformsUtils = exports.UniformsLib = exports.Uniform = exports.UVMapping = exports.TubeGeometry = exports.TubeBufferGeometry = exports.TrianglesDrawMode = exports.TriangleStripDrawMode = exports.TriangleFanDrawMode = exports.Triangle = exports.TorusKnotGeometry = exports.TorusKnotBufferGeometry = exports.TorusGeometry = exports.TorusBufferGeometry = exports.TextGeometry = exports.TextBufferGeometry = exports.TetrahedronGeometry = exports.TetrahedronBufferGeometry = exports.TangentSpaceNormalMap = exports.TOUCH = exports.SubtractiveBlending = exports.SubtractEquation = exports.StreamReadUsage = exports.StreamDrawUsage = exports.StreamCopyUsage = exports.StaticReadUsage = exports.StaticDrawUsage = exports.StaticCopyUsage = exports.SrcColorFactor = exports.SrcAlphaSaturateFactor = exports.SrcAlphaFactor = exports.SpotLightHelper = exports.SphericalHarmonics3 = exports.Spherical = exports.SphereGeometry = exports.SphereBufferGeometry = exports.Sphere = exports.SmoothShading = exports.SkeletonHelper = exports.ShortType = exports.ShapeUtils = exports.ShapeGeometry = exports.ShapeBufferGeometry = exports.ShaderLib = exports.ShaderChunk = exports.SceneUtils = exports.Scene = exports.SRGB8_ALPHA8_ASTC_8x8_Format = exports.SRGB8_ALPHA8_ASTC_8x6_Format = exports.SRGB8_ALPHA8_ASTC_8x5_Format = exports.SRGB8_ALPHA8_ASTC_6x6_Format = exports.SRGB8_ALPHA8_ASTC_6x5_Format = exports.SRGB8_ALPHA8_ASTC_5x5_Format = exports.SRGB8_ALPHA8_ASTC_5x4_Format = exports.SRGB8_ALPHA8_ASTC_4x4_Format = exports.SRGB8_ALPHA8_ASTC_12x12_Format = exports.SRGB8_ALPHA8_ASTC_12x10_Format = exports.SRGB8_ALPHA8_ASTC_10x8_Format = exports.SRGB8_ALPHA8_ASTC_10x6_Format = exports.SRGB8_ALPHA8_ASTC_10x5_Format = exports.SRGB8_ALPHA8_ASTC_10x10_Format = exports.RingGeometry = exports.RingBufferGeometry = exports.ReverseSubtractEquation = exports.ReplaceStencilOp = exports.RepeatWrapping = exports.ReinhardToneMapping = exports.RedIntegerFormat = exports.RedFormat = exports.Ray = exports.RGIntegerFormat = exports.RGFormat = exports.RGB_S3TC_DXT1_Format = exports.RGB_PVRTC_4BPPV1_Format = exports.RGB_PVRTC_2BPPV1_Format = exports.RGB_ETC2_Format = exports.RGB_ETC1_Format = exports.RGBM7Encoding = exports.RGBM16Encoding = exports.RGBIntegerFormat = exports.RGBFormat = exports.RGBEFormat = void 0;
  274. exports.sRGBEncoding = void 0;
  275. // threejs.org/license
  276. const REVISION = '123';
  277. exports.REVISION = REVISION;
  278. const MOUSE = {
  279. LEFT: 0,
  280. MIDDLE: 1,
  281. RIGHT: 2,
  282. ROTATE: 0,
  283. DOLLY: 1,
  284. PAN: 2
  285. };
  286. exports.MOUSE = MOUSE;
  287. const TOUCH = {
  288. ROTATE: 0,
  289. PAN: 1,
  290. DOLLY_PAN: 2,
  291. DOLLY_ROTATE: 3
  292. };
  293. exports.TOUCH = TOUCH;
  294. const CullFaceNone = 0;
  295. exports.CullFaceNone = CullFaceNone;
  296. const CullFaceBack = 1;
  297. exports.CullFaceBack = CullFaceBack;
  298. const CullFaceFront = 2;
  299. exports.CullFaceFront = CullFaceFront;
  300. const CullFaceFrontBack = 3;
  301. exports.CullFaceFrontBack = CullFaceFrontBack;
  302. const BasicShadowMap = 0;
  303. exports.BasicShadowMap = BasicShadowMap;
  304. const PCFShadowMap = 1;
  305. exports.PCFShadowMap = PCFShadowMap;
  306. const PCFSoftShadowMap = 2;
  307. exports.PCFSoftShadowMap = PCFSoftShadowMap;
  308. const VSMShadowMap = 3;
  309. exports.VSMShadowMap = VSMShadowMap;
  310. const FrontSide = 0;
  311. exports.FrontSide = FrontSide;
  312. const BackSide = 1;
  313. exports.BackSide = BackSide;
  314. const DoubleSide = 2;
  315. exports.DoubleSide = DoubleSide;
  316. const FlatShading = 1;
  317. exports.FlatShading = FlatShading;
  318. const SmoothShading = 2;
  319. exports.SmoothShading = SmoothShading;
  320. const NoBlending = 0;
  321. exports.NoBlending = NoBlending;
  322. const NormalBlending = 1;
  323. exports.NormalBlending = NormalBlending;
  324. const AdditiveBlending = 2;
  325. exports.AdditiveBlending = AdditiveBlending;
  326. const SubtractiveBlending = 3;
  327. exports.SubtractiveBlending = SubtractiveBlending;
  328. const MultiplyBlending = 4;
  329. exports.MultiplyBlending = MultiplyBlending;
  330. const CustomBlending = 5;
  331. exports.CustomBlending = CustomBlending;
  332. const AddEquation = 100;
  333. exports.AddEquation = AddEquation;
  334. const SubtractEquation = 101;
  335. exports.SubtractEquation = SubtractEquation;
  336. const ReverseSubtractEquation = 102;
  337. exports.ReverseSubtractEquation = ReverseSubtractEquation;
  338. const MinEquation = 103;
  339. exports.MinEquation = MinEquation;
  340. const MaxEquation = 104;
  341. exports.MaxEquation = MaxEquation;
  342. const ZeroFactor = 200;
  343. exports.ZeroFactor = ZeroFactor;
  344. const OneFactor = 201;
  345. exports.OneFactor = OneFactor;
  346. const SrcColorFactor = 202;
  347. exports.SrcColorFactor = SrcColorFactor;
  348. const OneMinusSrcColorFactor = 203;
  349. exports.OneMinusSrcColorFactor = OneMinusSrcColorFactor;
  350. const SrcAlphaFactor = 204;
  351. exports.SrcAlphaFactor = SrcAlphaFactor;
  352. const OneMinusSrcAlphaFactor = 205;
  353. exports.OneMinusSrcAlphaFactor = OneMinusSrcAlphaFactor;
  354. const DstAlphaFactor = 206;
  355. exports.DstAlphaFactor = DstAlphaFactor;
  356. const OneMinusDstAlphaFactor = 207;
  357. exports.OneMinusDstAlphaFactor = OneMinusDstAlphaFactor;
  358. const DstColorFactor = 208;
  359. exports.DstColorFactor = DstColorFactor;
  360. const OneMinusDstColorFactor = 209;
  361. exports.OneMinusDstColorFactor = OneMinusDstColorFactor;
  362. const SrcAlphaSaturateFactor = 210;
  363. exports.SrcAlphaSaturateFactor = SrcAlphaSaturateFactor;
  364. const NeverDepth = 0;
  365. exports.NeverDepth = NeverDepth;
  366. const AlwaysDepth = 1;
  367. exports.AlwaysDepth = AlwaysDepth;
  368. const LessDepth = 2;
  369. exports.LessDepth = LessDepth;
  370. const LessEqualDepth = 3;
  371. exports.LessEqualDepth = LessEqualDepth;
  372. const EqualDepth = 4;
  373. exports.EqualDepth = EqualDepth;
  374. const GreaterEqualDepth = 5;
  375. exports.GreaterEqualDepth = GreaterEqualDepth;
  376. const GreaterDepth = 6;
  377. exports.GreaterDepth = GreaterDepth;
  378. const NotEqualDepth = 7;
  379. exports.NotEqualDepth = NotEqualDepth;
  380. const MultiplyOperation = 0;
  381. exports.MultiplyOperation = MultiplyOperation;
  382. const MixOperation = 1;
  383. exports.MixOperation = MixOperation;
  384. const AddOperation = 2;
  385. exports.AddOperation = AddOperation;
  386. const NoToneMapping = 0;
  387. exports.NoToneMapping = NoToneMapping;
  388. const LinearToneMapping = 1;
  389. exports.LinearToneMapping = LinearToneMapping;
  390. const ReinhardToneMapping = 2;
  391. exports.ReinhardToneMapping = ReinhardToneMapping;
  392. const CineonToneMapping = 3;
  393. exports.CineonToneMapping = CineonToneMapping;
  394. const ACESFilmicToneMapping = 4;
  395. exports.ACESFilmicToneMapping = ACESFilmicToneMapping;
  396. const CustomToneMapping = 5;
  397. exports.CustomToneMapping = CustomToneMapping;
  398. const UVMapping = 300;
  399. exports.UVMapping = UVMapping;
  400. const CubeReflectionMapping = 301;
  401. exports.CubeReflectionMapping = CubeReflectionMapping;
  402. const CubeRefractionMapping = 302;
  403. exports.CubeRefractionMapping = CubeRefractionMapping;
  404. const EquirectangularReflectionMapping = 303;
  405. exports.EquirectangularReflectionMapping = EquirectangularReflectionMapping;
  406. const EquirectangularRefractionMapping = 304;
  407. exports.EquirectangularRefractionMapping = EquirectangularRefractionMapping;
  408. const CubeUVReflectionMapping = 306;
  409. exports.CubeUVReflectionMapping = CubeUVReflectionMapping;
  410. const CubeUVRefractionMapping = 307;
  411. exports.CubeUVRefractionMapping = CubeUVRefractionMapping;
  412. const RepeatWrapping = 1000;
  413. exports.RepeatWrapping = RepeatWrapping;
  414. const ClampToEdgeWrapping = 1001;
  415. exports.ClampToEdgeWrapping = ClampToEdgeWrapping;
  416. const MirroredRepeatWrapping = 1002;
  417. exports.MirroredRepeatWrapping = MirroredRepeatWrapping;
  418. const NearestFilter = 1003;
  419. exports.NearestFilter = NearestFilter;
  420. const NearestMipmapNearestFilter = 1004;
  421. exports.NearestMipmapNearestFilter = NearestMipmapNearestFilter;
  422. const NearestMipMapNearestFilter = 1004;
  423. exports.NearestMipMapNearestFilter = NearestMipMapNearestFilter;
  424. const NearestMipmapLinearFilter = 1005;
  425. exports.NearestMipmapLinearFilter = NearestMipmapLinearFilter;
  426. const NearestMipMapLinearFilter = 1005;
  427. exports.NearestMipMapLinearFilter = NearestMipMapLinearFilter;
  428. const LinearFilter = 1006;
  429. exports.LinearFilter = LinearFilter;
  430. const LinearMipmapNearestFilter = 1007;
  431. exports.LinearMipmapNearestFilter = LinearMipmapNearestFilter;
  432. const LinearMipMapNearestFilter = 1007;
  433. exports.LinearMipMapNearestFilter = LinearMipMapNearestFilter;
  434. const LinearMipmapLinearFilter = 1008;
  435. exports.LinearMipmapLinearFilter = LinearMipmapLinearFilter;
  436. const LinearMipMapLinearFilter = 1008;
  437. exports.LinearMipMapLinearFilter = LinearMipMapLinearFilter;
  438. const UnsignedByteType = 1009;
  439. exports.UnsignedByteType = UnsignedByteType;
  440. const ByteType = 1010;
  441. exports.ByteType = ByteType;
  442. const ShortType = 1011;
  443. exports.ShortType = ShortType;
  444. const UnsignedShortType = 1012;
  445. exports.UnsignedShortType = UnsignedShortType;
  446. const IntType = 1013;
  447. exports.IntType = IntType;
  448. const UnsignedIntType = 1014;
  449. exports.UnsignedIntType = UnsignedIntType;
  450. const FloatType = 1015;
  451. exports.FloatType = FloatType;
  452. const HalfFloatType = 1016;
  453. exports.HalfFloatType = HalfFloatType;
  454. const UnsignedShort4444Type = 1017;
  455. exports.UnsignedShort4444Type = UnsignedShort4444Type;
  456. const UnsignedShort5551Type = 1018;
  457. exports.UnsignedShort5551Type = UnsignedShort5551Type;
  458. const UnsignedShort565Type = 1019;
  459. exports.UnsignedShort565Type = UnsignedShort565Type;
  460. const UnsignedInt248Type = 1020;
  461. exports.UnsignedInt248Type = UnsignedInt248Type;
  462. const AlphaFormat = 1021;
  463. exports.AlphaFormat = AlphaFormat;
  464. const RGBFormat = 1022;
  465. exports.RGBFormat = RGBFormat;
  466. const RGBAFormat = 1023;
  467. exports.RGBAFormat = RGBAFormat;
  468. const LuminanceFormat = 1024;
  469. exports.LuminanceFormat = LuminanceFormat;
  470. const LuminanceAlphaFormat = 1025;
  471. exports.LuminanceAlphaFormat = LuminanceAlphaFormat;
  472. const RGBEFormat = RGBAFormat;
  473. exports.RGBEFormat = RGBEFormat;
  474. const DepthFormat = 1026;
  475. exports.DepthFormat = DepthFormat;
  476. const DepthStencilFormat = 1027;
  477. exports.DepthStencilFormat = DepthStencilFormat;
  478. const RedFormat = 1028;
  479. exports.RedFormat = RedFormat;
  480. const RedIntegerFormat = 1029;
  481. exports.RedIntegerFormat = RedIntegerFormat;
  482. const RGFormat = 1030;
  483. exports.RGFormat = RGFormat;
  484. const RGIntegerFormat = 1031;
  485. exports.RGIntegerFormat = RGIntegerFormat;
  486. const RGBIntegerFormat = 1032;
  487. exports.RGBIntegerFormat = RGBIntegerFormat;
  488. const RGBAIntegerFormat = 1033;
  489. exports.RGBAIntegerFormat = RGBAIntegerFormat;
  490. const RGB_S3TC_DXT1_Format = 33776;
  491. exports.RGB_S3TC_DXT1_Format = RGB_S3TC_DXT1_Format;
  492. const RGBA_S3TC_DXT1_Format = 33777;
  493. exports.RGBA_S3TC_DXT1_Format = RGBA_S3TC_DXT1_Format;
  494. const RGBA_S3TC_DXT3_Format = 33778;
  495. exports.RGBA_S3TC_DXT3_Format = RGBA_S3TC_DXT3_Format;
  496. const RGBA_S3TC_DXT5_Format = 33779;
  497. exports.RGBA_S3TC_DXT5_Format = RGBA_S3TC_DXT5_Format;
  498. const RGB_PVRTC_4BPPV1_Format = 35840;
  499. exports.RGB_PVRTC_4BPPV1_Format = RGB_PVRTC_4BPPV1_Format;
  500. const RGB_PVRTC_2BPPV1_Format = 35841;
  501. exports.RGB_PVRTC_2BPPV1_Format = RGB_PVRTC_2BPPV1_Format;
  502. const RGBA_PVRTC_4BPPV1_Format = 35842;
  503. exports.RGBA_PVRTC_4BPPV1_Format = RGBA_PVRTC_4BPPV1_Format;
  504. const RGBA_PVRTC_2BPPV1_Format = 35843;
  505. exports.RGBA_PVRTC_2BPPV1_Format = RGBA_PVRTC_2BPPV1_Format;
  506. const RGB_ETC1_Format = 36196;
  507. exports.RGB_ETC1_Format = RGB_ETC1_Format;
  508. const RGB_ETC2_Format = 37492;
  509. exports.RGB_ETC2_Format = RGB_ETC2_Format;
  510. const RGBA_ETC2_EAC_Format = 37496;
  511. exports.RGBA_ETC2_EAC_Format = RGBA_ETC2_EAC_Format;
  512. const RGBA_ASTC_4x4_Format = 37808;
  513. exports.RGBA_ASTC_4x4_Format = RGBA_ASTC_4x4_Format;
  514. const RGBA_ASTC_5x4_Format = 37809;
  515. exports.RGBA_ASTC_5x4_Format = RGBA_ASTC_5x4_Format;
  516. const RGBA_ASTC_5x5_Format = 37810;
  517. exports.RGBA_ASTC_5x5_Format = RGBA_ASTC_5x5_Format;
  518. const RGBA_ASTC_6x5_Format = 37811;
  519. exports.RGBA_ASTC_6x5_Format = RGBA_ASTC_6x5_Format;
  520. const RGBA_ASTC_6x6_Format = 37812;
  521. exports.RGBA_ASTC_6x6_Format = RGBA_ASTC_6x6_Format;
  522. const RGBA_ASTC_8x5_Format = 37813;
  523. exports.RGBA_ASTC_8x5_Format = RGBA_ASTC_8x5_Format;
  524. const RGBA_ASTC_8x6_Format = 37814;
  525. exports.RGBA_ASTC_8x6_Format = RGBA_ASTC_8x6_Format;
  526. const RGBA_ASTC_8x8_Format = 37815;
  527. exports.RGBA_ASTC_8x8_Format = RGBA_ASTC_8x8_Format;
  528. const RGBA_ASTC_10x5_Format = 37816;
  529. exports.RGBA_ASTC_10x5_Format = RGBA_ASTC_10x5_Format;
  530. const RGBA_ASTC_10x6_Format = 37817;
  531. exports.RGBA_ASTC_10x6_Format = RGBA_ASTC_10x6_Format;
  532. const RGBA_ASTC_10x8_Format = 37818;
  533. exports.RGBA_ASTC_10x8_Format = RGBA_ASTC_10x8_Format;
  534. const RGBA_ASTC_10x10_Format = 37819;
  535. exports.RGBA_ASTC_10x10_Format = RGBA_ASTC_10x10_Format;
  536. const RGBA_ASTC_12x10_Format = 37820;
  537. exports.RGBA_ASTC_12x10_Format = RGBA_ASTC_12x10_Format;
  538. const RGBA_ASTC_12x12_Format = 37821;
  539. exports.RGBA_ASTC_12x12_Format = RGBA_ASTC_12x12_Format;
  540. const RGBA_BPTC_Format = 36492;
  541. exports.RGBA_BPTC_Format = RGBA_BPTC_Format;
  542. const SRGB8_ALPHA8_ASTC_4x4_Format = 37840;
  543. exports.SRGB8_ALPHA8_ASTC_4x4_Format = SRGB8_ALPHA8_ASTC_4x4_Format;
  544. const SRGB8_ALPHA8_ASTC_5x4_Format = 37841;
  545. exports.SRGB8_ALPHA8_ASTC_5x4_Format = SRGB8_ALPHA8_ASTC_5x4_Format;
  546. const SRGB8_ALPHA8_ASTC_5x5_Format = 37842;
  547. exports.SRGB8_ALPHA8_ASTC_5x5_Format = SRGB8_ALPHA8_ASTC_5x5_Format;
  548. const SRGB8_ALPHA8_ASTC_6x5_Format = 37843;
  549. exports.SRGB8_ALPHA8_ASTC_6x5_Format = SRGB8_ALPHA8_ASTC_6x5_Format;
  550. const SRGB8_ALPHA8_ASTC_6x6_Format = 37844;
  551. exports.SRGB8_ALPHA8_ASTC_6x6_Format = SRGB8_ALPHA8_ASTC_6x6_Format;
  552. const SRGB8_ALPHA8_ASTC_8x5_Format = 37845;
  553. exports.SRGB8_ALPHA8_ASTC_8x5_Format = SRGB8_ALPHA8_ASTC_8x5_Format;
  554. const SRGB8_ALPHA8_ASTC_8x6_Format = 37846;
  555. exports.SRGB8_ALPHA8_ASTC_8x6_Format = SRGB8_ALPHA8_ASTC_8x6_Format;
  556. const SRGB8_ALPHA8_ASTC_8x8_Format = 37847;
  557. exports.SRGB8_ALPHA8_ASTC_8x8_Format = SRGB8_ALPHA8_ASTC_8x8_Format;
  558. const SRGB8_ALPHA8_ASTC_10x5_Format = 37848;
  559. exports.SRGB8_ALPHA8_ASTC_10x5_Format = SRGB8_ALPHA8_ASTC_10x5_Format;
  560. const SRGB8_ALPHA8_ASTC_10x6_Format = 37849;
  561. exports.SRGB8_ALPHA8_ASTC_10x6_Format = SRGB8_ALPHA8_ASTC_10x6_Format;
  562. const SRGB8_ALPHA8_ASTC_10x8_Format = 37850;
  563. exports.SRGB8_ALPHA8_ASTC_10x8_Format = SRGB8_ALPHA8_ASTC_10x8_Format;
  564. const SRGB8_ALPHA8_ASTC_10x10_Format = 37851;
  565. exports.SRGB8_ALPHA8_ASTC_10x10_Format = SRGB8_ALPHA8_ASTC_10x10_Format;
  566. const SRGB8_ALPHA8_ASTC_12x10_Format = 37852;
  567. exports.SRGB8_ALPHA8_ASTC_12x10_Format = SRGB8_ALPHA8_ASTC_12x10_Format;
  568. const SRGB8_ALPHA8_ASTC_12x12_Format = 37853;
  569. exports.SRGB8_ALPHA8_ASTC_12x12_Format = SRGB8_ALPHA8_ASTC_12x12_Format;
  570. const LoopOnce = 2200;
  571. exports.LoopOnce = LoopOnce;
  572. const LoopRepeat = 2201;
  573. exports.LoopRepeat = LoopRepeat;
  574. const LoopPingPong = 2202;
  575. exports.LoopPingPong = LoopPingPong;
  576. const InterpolateDiscrete = 2300;
  577. exports.InterpolateDiscrete = InterpolateDiscrete;
  578. const InterpolateLinear = 2301;
  579. exports.InterpolateLinear = InterpolateLinear;
  580. const InterpolateSmooth = 2302;
  581. exports.InterpolateSmooth = InterpolateSmooth;
  582. const ZeroCurvatureEnding = 2400;
  583. exports.ZeroCurvatureEnding = ZeroCurvatureEnding;
  584. const ZeroSlopeEnding = 2401;
  585. exports.ZeroSlopeEnding = ZeroSlopeEnding;
  586. const WrapAroundEnding = 2402;
  587. exports.WrapAroundEnding = WrapAroundEnding;
  588. const NormalAnimationBlendMode = 2500;
  589. exports.NormalAnimationBlendMode = NormalAnimationBlendMode;
  590. const AdditiveAnimationBlendMode = 2501;
  591. exports.AdditiveAnimationBlendMode = AdditiveAnimationBlendMode;
  592. const TrianglesDrawMode = 0;
  593. exports.TrianglesDrawMode = TrianglesDrawMode;
  594. const TriangleStripDrawMode = 1;
  595. exports.TriangleStripDrawMode = TriangleStripDrawMode;
  596. const TriangleFanDrawMode = 2;
  597. exports.TriangleFanDrawMode = TriangleFanDrawMode;
  598. const LinearEncoding = 3000;
  599. exports.LinearEncoding = LinearEncoding;
  600. const sRGBEncoding = 3001;
  601. exports.sRGBEncoding = sRGBEncoding;
  602. const GammaEncoding = 3007;
  603. exports.GammaEncoding = GammaEncoding;
  604. const RGBEEncoding = 3002;
  605. exports.RGBEEncoding = RGBEEncoding;
  606. const LogLuvEncoding = 3003;
  607. exports.LogLuvEncoding = LogLuvEncoding;
  608. const RGBM7Encoding = 3004;
  609. exports.RGBM7Encoding = RGBM7Encoding;
  610. const RGBM16Encoding = 3005;
  611. exports.RGBM16Encoding = RGBM16Encoding;
  612. const RGBDEncoding = 3006;
  613. exports.RGBDEncoding = RGBDEncoding;
  614. const BasicDepthPacking = 3200;
  615. exports.BasicDepthPacking = BasicDepthPacking;
  616. const RGBADepthPacking = 3201;
  617. exports.RGBADepthPacking = RGBADepthPacking;
  618. const TangentSpaceNormalMap = 0;
  619. exports.TangentSpaceNormalMap = TangentSpaceNormalMap;
  620. const ObjectSpaceNormalMap = 1;
  621. exports.ObjectSpaceNormalMap = ObjectSpaceNormalMap;
  622. const ZeroStencilOp = 0;
  623. exports.ZeroStencilOp = ZeroStencilOp;
  624. const KeepStencilOp = 7680;
  625. exports.KeepStencilOp = KeepStencilOp;
  626. const ReplaceStencilOp = 7681;
  627. exports.ReplaceStencilOp = ReplaceStencilOp;
  628. const IncrementStencilOp = 7682;
  629. exports.IncrementStencilOp = IncrementStencilOp;
  630. const DecrementStencilOp = 7683;
  631. exports.DecrementStencilOp = DecrementStencilOp;
  632. const IncrementWrapStencilOp = 34055;
  633. exports.IncrementWrapStencilOp = IncrementWrapStencilOp;
  634. const DecrementWrapStencilOp = 34056;
  635. exports.DecrementWrapStencilOp = DecrementWrapStencilOp;
  636. const InvertStencilOp = 5386;
  637. exports.InvertStencilOp = InvertStencilOp;
  638. const NeverStencilFunc = 512;
  639. exports.NeverStencilFunc = NeverStencilFunc;
  640. const LessStencilFunc = 513;
  641. exports.LessStencilFunc = LessStencilFunc;
  642. const EqualStencilFunc = 514;
  643. exports.EqualStencilFunc = EqualStencilFunc;
  644. const LessEqualStencilFunc = 515;
  645. exports.LessEqualStencilFunc = LessEqualStencilFunc;
  646. const GreaterStencilFunc = 516;
  647. exports.GreaterStencilFunc = GreaterStencilFunc;
  648. const NotEqualStencilFunc = 517;
  649. exports.NotEqualStencilFunc = NotEqualStencilFunc;
  650. const GreaterEqualStencilFunc = 518;
  651. exports.GreaterEqualStencilFunc = GreaterEqualStencilFunc;
  652. const AlwaysStencilFunc = 519;
  653. exports.AlwaysStencilFunc = AlwaysStencilFunc;
  654. const StaticDrawUsage = 35044;
  655. exports.StaticDrawUsage = StaticDrawUsage;
  656. const DynamicDrawUsage = 35048;
  657. exports.DynamicDrawUsage = DynamicDrawUsage;
  658. const StreamDrawUsage = 35040;
  659. exports.StreamDrawUsage = StreamDrawUsage;
  660. const StaticReadUsage = 35045;
  661. exports.StaticReadUsage = StaticReadUsage;
  662. const DynamicReadUsage = 35049;
  663. exports.DynamicReadUsage = DynamicReadUsage;
  664. const StreamReadUsage = 35041;
  665. exports.StreamReadUsage = StreamReadUsage;
  666. const StaticCopyUsage = 35046;
  667. exports.StaticCopyUsage = StaticCopyUsage;
  668. const DynamicCopyUsage = 35050;
  669. exports.DynamicCopyUsage = DynamicCopyUsage;
  670. const StreamCopyUsage = 35042;
  671. exports.StreamCopyUsage = StreamCopyUsage;
  672. const GLSL1 = "100";
  673. exports.GLSL1 = GLSL1;
  674. const GLSL3 = "300 es";
  675. /**
  676. * https://github.com/mrdoob/eventdispatcher.js/
  677. */
  678. exports.GLSL3 = GLSL3;
  679. function EventDispatcher() {}
  680. Object.assign(EventDispatcher.prototype, {
  681. addEventListener: function (type, listener) {
  682. if (this._listeners === undefined) this._listeners = {};
  683. const listeners = this._listeners;
  684. if (listeners[type] === undefined) {
  685. listeners[type] = [];
  686. }
  687. if (listeners[type].indexOf(listener) === -1) {
  688. listeners[type].push(listener);
  689. }
  690. },
  691. hasEventListener: function (type, listener) {
  692. if (this._listeners === undefined) return false;
  693. const listeners = this._listeners;
  694. return listeners[type] !== undefined && listeners[type].indexOf(listener) !== -1;
  695. },
  696. removeEventListener: function (type, listener) {
  697. if (this._listeners === undefined) return;
  698. const listeners = this._listeners;
  699. const listenerArray = listeners[type];
  700. if (listenerArray !== undefined) {
  701. const index = listenerArray.indexOf(listener);
  702. if (index !== -1) {
  703. listenerArray.splice(index, 1);
  704. }
  705. }
  706. },
  707. dispatchEvent: function (event) {
  708. if (this._listeners === undefined) return;
  709. const listeners = this._listeners;
  710. const listenerArray = listeners[event.type];
  711. if (listenerArray !== undefined) {
  712. event.target = this; // Make a copy, in case listeners are removed while iterating.
  713. const array = listenerArray.slice(0);
  714. for (let i = 0, l = array.length; i < l; i++) {
  715. array[i].call(this, event);
  716. }
  717. }
  718. }
  719. });
  720. const _lut = [];
  721. for (let i = 0; i < 256; i++) {
  722. _lut[i] = (i < 16 ? '0' : '') + i.toString(16);
  723. }
  724. let _seed = 1234567;
  725. const MathUtils = {
  726. DEG2RAD: Math.PI / 180,
  727. RAD2DEG: 180 / Math.PI,
  728. generateUUID: function () {
  729. // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/21963136#21963136
  730. const d0 = Math.random() * 0xffffffff | 0;
  731. const d1 = Math.random() * 0xffffffff | 0;
  732. const d2 = Math.random() * 0xffffffff | 0;
  733. const d3 = Math.random() * 0xffffffff | 0;
  734. const uuid = _lut[d0 & 0xff] + _lut[d0 >> 8 & 0xff] + _lut[d0 >> 16 & 0xff] + _lut[d0 >> 24 & 0xff] + '-' + _lut[d1 & 0xff] + _lut[d1 >> 8 & 0xff] + '-' + _lut[d1 >> 16 & 0x0f | 0x40] + _lut[d1 >> 24 & 0xff] + '-' + _lut[d2 & 0x3f | 0x80] + _lut[d2 >> 8 & 0xff] + '-' + _lut[d2 >> 16 & 0xff] + _lut[d2 >> 24 & 0xff] + _lut[d3 & 0xff] + _lut[d3 >> 8 & 0xff] + _lut[d3 >> 16 & 0xff] + _lut[d3 >> 24 & 0xff]; // .toUpperCase() here flattens concatenated strings to save heap memory space.
  735. return uuid.toUpperCase();
  736. },
  737. clamp: function (value, min, max) {
  738. return Math.max(min, Math.min(max, value));
  739. },
  740. // compute euclidian modulo of m % n
  741. // https://en.wikipedia.org/wiki/Modulo_operation
  742. euclideanModulo: function (n, m) {
  743. return (n % m + m) % m;
  744. },
  745. // Linear mapping from range <a1, a2> to range <b1, b2>
  746. mapLinear: function (x, a1, a2, b1, b2) {
  747. return b1 + (x - a1) * (b2 - b1) / (a2 - a1);
  748. },
  749. // https://en.wikipedia.org/wiki/Linear_interpolation
  750. lerp: function (x, y, t) {
  751. return (1 - t) * x + t * y;
  752. },
  753. // http://en.wikipedia.org/wiki/Smoothstep
  754. smoothstep: function (x, min, max) {
  755. if (x <= min) return 0;
  756. if (x >= max) return 1;
  757. x = (x - min) / (max - min);
  758. return x * x * (3 - 2 * x);
  759. },
  760. smootherstep: function (x, min, max) {
  761. if (x <= min) return 0;
  762. if (x >= max) return 1;
  763. x = (x - min) / (max - min);
  764. return x * x * x * (x * (x * 6 - 15) + 10);
  765. },
  766. // Random integer from <low, high> interval
  767. randInt: function (low, high) {
  768. return low + Math.floor(Math.random() * (high - low + 1));
  769. },
  770. // Random float from <low, high> interval
  771. randFloat: function (low, high) {
  772. return low + Math.random() * (high - low);
  773. },
  774. // Random float from <-range/2, range/2> interval
  775. randFloatSpread: function (range) {
  776. return range * (0.5 - Math.random());
  777. },
  778. // Deterministic pseudo-random float in the interval [ 0, 1 ]
  779. seededRandom: function (s) {
  780. if (s !== undefined) _seed = s % 2147483647; // Park-Miller algorithm
  781. _seed = _seed * 16807 % 2147483647;
  782. return (_seed - 1) / 2147483646;
  783. },
  784. degToRad: function (degrees) {
  785. return degrees * MathUtils.DEG2RAD;
  786. },
  787. radToDeg: function (radians) {
  788. return radians * MathUtils.RAD2DEG;
  789. },
  790. isPowerOfTwo: function (value) {
  791. return (value & value - 1) === 0 && value !== 0;
  792. },
  793. ceilPowerOfTwo: function (value) {
  794. return Math.pow(2, Math.ceil(Math.log(value) / Math.LN2));
  795. },
  796. floorPowerOfTwo: function (value) {
  797. return Math.pow(2, Math.floor(Math.log(value) / Math.LN2));
  798. },
  799. setQuaternionFromProperEuler: function (q, a, b, c, order) {
  800. // Intrinsic Proper Euler Angles - see https://en.wikipedia.org/wiki/Euler_angles
  801. // rotations are applied to the axes in the order specified by 'order'
  802. // rotation by angle 'a' is applied first, then by angle 'b', then by angle 'c'
  803. // angles are in radians
  804. const cos = Math.cos;
  805. const sin = Math.sin;
  806. const c2 = cos(b / 2);
  807. const s2 = sin(b / 2);
  808. const c13 = cos((a + c) / 2);
  809. const s13 = sin((a + c) / 2);
  810. const c1_3 = cos((a - c) / 2);
  811. const s1_3 = sin((a - c) / 2);
  812. const c3_1 = cos((c - a) / 2);
  813. const s3_1 = sin((c - a) / 2);
  814. switch (order) {
  815. case 'XYX':
  816. q.set(c2 * s13, s2 * c1_3, s2 * s1_3, c2 * c13);
  817. break;
  818. case 'YZY':
  819. q.set(s2 * s1_3, c2 * s13, s2 * c1_3, c2 * c13);
  820. break;
  821. case 'ZXZ':
  822. q.set(s2 * c1_3, s2 * s1_3, c2 * s13, c2 * c13);
  823. break;
  824. case 'XZX':
  825. q.set(c2 * s13, s2 * s3_1, s2 * c3_1, c2 * c13);
  826. break;
  827. case 'YXY':
  828. q.set(s2 * c3_1, c2 * s13, s2 * s3_1, c2 * c13);
  829. break;
  830. case 'ZYZ':
  831. q.set(s2 * s3_1, s2 * c3_1, c2 * s13, c2 * c13);
  832. break;
  833. default:
  834. console.warn('THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: ' + order);
  835. }
  836. }
  837. };
  838. exports.MathUtils = exports.Math = MathUtils;
  839. class Vector2 {
  840. constructor(x = 0, y = 0) {
  841. Object.defineProperty(this, 'isVector2', {
  842. value: true
  843. });
  844. this.x = x;
  845. this.y = y;
  846. }
  847. get width() {
  848. return this.x;
  849. }
  850. set width(value) {
  851. this.x = value;
  852. }
  853. get height() {
  854. return this.y;
  855. }
  856. set height(value) {
  857. this.y = value;
  858. }
  859. set(x, y) {
  860. this.x = x;
  861. this.y = y;
  862. return this;
  863. }
  864. setScalar(scalar) {
  865. this.x = scalar;
  866. this.y = scalar;
  867. return this;
  868. }
  869. setX(x) {
  870. this.x = x;
  871. return this;
  872. }
  873. setY(y) {
  874. this.y = y;
  875. return this;
  876. }
  877. setComponent(index, value) {
  878. switch (index) {
  879. case 0:
  880. this.x = value;
  881. break;
  882. case 1:
  883. this.y = value;
  884. break;
  885. default:
  886. throw new Error('index is out of range: ' + index);
  887. }
  888. return this;
  889. }
  890. getComponent(index) {
  891. switch (index) {
  892. case 0:
  893. return this.x;
  894. case 1:
  895. return this.y;
  896. default:
  897. throw new Error('index is out of range: ' + index);
  898. }
  899. }
  900. clone() {
  901. return new this.constructor(this.x, this.y);
  902. }
  903. copy(v) {
  904. this.x = v.x;
  905. this.y = v.y;
  906. return this;
  907. }
  908. add(v, w) {
  909. if (w !== undefined) {
  910. console.warn('THREE.Vector2: .add() now only accepts one argument. Use .addVectors( a, b ) instead.');
  911. return this.addVectors(v, w);
  912. }
  913. this.x += v.x;
  914. this.y += v.y;
  915. return this;
  916. }
  917. addScalar(s) {
  918. this.x += s;
  919. this.y += s;
  920. return this;
  921. }
  922. addVectors(a, b) {
  923. this.x = a.x + b.x;
  924. this.y = a.y + b.y;
  925. return this;
  926. }
  927. addScaledVector(v, s) {
  928. this.x += v.x * s;
  929. this.y += v.y * s;
  930. return this;
  931. }
  932. sub(v, w) {
  933. if (w !== undefined) {
  934. console.warn('THREE.Vector2: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.');
  935. return this.subVectors(v, w);
  936. }
  937. this.x -= v.x;
  938. this.y -= v.y;
  939. return this;
  940. }
  941. subScalar(s) {
  942. this.x -= s;
  943. this.y -= s;
  944. return this;
  945. }
  946. subVectors(a, b) {
  947. this.x = a.x - b.x;
  948. this.y = a.y - b.y;
  949. return this;
  950. }
  951. multiply(v) {
  952. this.x *= v.x;
  953. this.y *= v.y;
  954. return this;
  955. }
  956. multiplyScalar(scalar) {
  957. this.x *= scalar;
  958. this.y *= scalar;
  959. return this;
  960. }
  961. divide(v) {
  962. this.x /= v.x;
  963. this.y /= v.y;
  964. return this;
  965. }
  966. divideScalar(scalar) {
  967. return this.multiplyScalar(1 / scalar);
  968. }
  969. applyMatrix3(m) {
  970. const x = this.x,
  971. y = this.y;
  972. const e = m.elements;
  973. this.x = e[0] * x + e[3] * y + e[6];
  974. this.y = e[1] * x + e[4] * y + e[7];
  975. return this;
  976. }
  977. min(v) {
  978. this.x = Math.min(this.x, v.x);
  979. this.y = Math.min(this.y, v.y);
  980. return this;
  981. }
  982. max(v) {
  983. this.x = Math.max(this.x, v.x);
  984. this.y = Math.max(this.y, v.y);
  985. return this;
  986. }
  987. clamp(min, max) {
  988. // assumes min < max, componentwise
  989. this.x = Math.max(min.x, Math.min(max.x, this.x));
  990. this.y = Math.max(min.y, Math.min(max.y, this.y));
  991. return this;
  992. }
  993. clampScalar(minVal, maxVal) {
  994. this.x = Math.max(minVal, Math.min(maxVal, this.x));
  995. this.y = Math.max(minVal, Math.min(maxVal, this.y));
  996. return this;
  997. }
  998. clampLength(min, max) {
  999. const length = this.length();
  1000. return this.divideScalar(length || 1).multiplyScalar(Math.max(min, Math.min(max, length)));
  1001. }
  1002. floor() {
  1003. this.x = Math.floor(this.x);
  1004. this.y = Math.floor(this.y);
  1005. return this;
  1006. }
  1007. ceil() {
  1008. this.x = Math.ceil(this.x);
  1009. this.y = Math.ceil(this.y);
  1010. return this;
  1011. }
  1012. round() {
  1013. this.x = Math.round(this.x);
  1014. this.y = Math.round(this.y);
  1015. return this;
  1016. }
  1017. roundToZero() {
  1018. this.x = this.x < 0 ? Math.ceil(this.x) : Math.floor(this.x);
  1019. this.y = this.y < 0 ? Math.ceil(this.y) : Math.floor(this.y);
  1020. return this;
  1021. }
  1022. negate() {
  1023. this.x = -this.x;
  1024. this.y = -this.y;
  1025. return this;
  1026. }
  1027. dot(v) {
  1028. return this.x * v.x + this.y * v.y;
  1029. }
  1030. cross(v) {
  1031. return this.x * v.y - this.y * v.x;
  1032. }
  1033. lengthSq() {
  1034. return this.x * this.x + this.y * this.y;
  1035. }
  1036. length() {
  1037. return Math.sqrt(this.x * this.x + this.y * this.y);
  1038. }
  1039. manhattanLength() {
  1040. return Math.abs(this.x) + Math.abs(this.y);
  1041. }
  1042. normalize() {
  1043. return this.divideScalar(this.length() || 1);
  1044. }
  1045. angle() {
  1046. // computes the angle in radians with respect to the positive x-axis
  1047. const angle = Math.atan2(-this.y, -this.x) + Math.PI;
  1048. return angle;
  1049. }
  1050. distanceTo(v) {
  1051. return Math.sqrt(this.distanceToSquared(v));
  1052. }
  1053. distanceToSquared(v) {
  1054. const dx = this.x - v.x,
  1055. dy = this.y - v.y;
  1056. return dx * dx + dy * dy;
  1057. }
  1058. manhattanDistanceTo(v) {
  1059. return Math.abs(this.x - v.x) + Math.abs(this.y - v.y);
  1060. }
  1061. setLength(length) {
  1062. return this.normalize().multiplyScalar(length);
  1063. }
  1064. lerp(v, alpha) {
  1065. this.x += (v.x - this.x) * alpha;
  1066. this.y += (v.y - this.y) * alpha;
  1067. return this;
  1068. }
  1069. lerpVectors(v1, v2, alpha) {
  1070. this.x = v1.x + (v2.x - v1.x) * alpha;
  1071. this.y = v1.y + (v2.y - v1.y) * alpha;
  1072. return this;
  1073. }
  1074. equals(v) {
  1075. return v.x === this.x && v.y === this.y;
  1076. }
  1077. fromArray(array, offset = 0) {
  1078. this.x = array[offset];
  1079. this.y = array[offset + 1];
  1080. return this;
  1081. }
  1082. toArray(array = [], offset = 0) {
  1083. array[offset] = this.x;
  1084. array[offset + 1] = this.y;
  1085. return array;
  1086. }
  1087. fromBufferAttribute(attribute, index, offset) {
  1088. if (offset !== undefined) {
  1089. console.warn('THREE.Vector2: offset has been removed from .fromBufferAttribute().');
  1090. }
  1091. this.x = attribute.getX(index);
  1092. this.y = attribute.getY(index);
  1093. return this;
  1094. }
  1095. rotateAround(center, angle) {
  1096. const c = Math.cos(angle),
  1097. s = Math.sin(angle);
  1098. const x = this.x - center.x;
  1099. const y = this.y - center.y;
  1100. this.x = x * c - y * s + center.x;
  1101. this.y = x * s + y * c + center.y;
  1102. return this;
  1103. }
  1104. random() {
  1105. this.x = Math.random();
  1106. this.y = Math.random();
  1107. return this;
  1108. }
  1109. }
  1110. exports.Vector2 = Vector2;
  1111. class Matrix3 {
  1112. constructor() {
  1113. Object.defineProperty(this, 'isMatrix3', {
  1114. value: true
  1115. });
  1116. this.elements = [1, 0, 0, 0, 1, 0, 0, 0, 1];
  1117. if (arguments.length > 0) {
  1118. console.error('THREE.Matrix3: the constructor no longer reads arguments. use .set() instead.');
  1119. }
  1120. }
  1121. set(n11, n12, n13, n21, n22, n23, n31, n32, n33) {
  1122. const te = this.elements;
  1123. te[0] = n11;
  1124. te[1] = n21;
  1125. te[2] = n31;
  1126. te[3] = n12;
  1127. te[4] = n22;
  1128. te[5] = n32;
  1129. te[6] = n13;
  1130. te[7] = n23;
  1131. te[8] = n33;
  1132. return this;
  1133. }
  1134. identity() {
  1135. this.set(1, 0, 0, 0, 1, 0, 0, 0, 1);
  1136. return this;
  1137. }
  1138. clone() {
  1139. return new this.constructor().fromArray(this.elements);
  1140. }
  1141. copy(m) {
  1142. const te = this.elements;
  1143. const me = m.elements;
  1144. te[0] = me[0];
  1145. te[1] = me[1];
  1146. te[2] = me[2];
  1147. te[3] = me[3];
  1148. te[4] = me[4];
  1149. te[5] = me[5];
  1150. te[6] = me[6];
  1151. te[7] = me[7];
  1152. te[8] = me[8];
  1153. return this;
  1154. }
  1155. extractBasis(xAxis, yAxis, zAxis) {
  1156. xAxis.setFromMatrix3Column(this, 0);
  1157. yAxis.setFromMatrix3Column(this, 1);
  1158. zAxis.setFromMatrix3Column(this, 2);
  1159. return this;
  1160. }
  1161. setFromMatrix4(m) {
  1162. const me = m.elements;
  1163. this.set(me[0], me[4], me[8], me[1], me[5], me[9], me[2], me[6], me[10]);
  1164. return this;
  1165. }
  1166. multiply(m) {
  1167. return this.multiplyMatrices(this, m);
  1168. }
  1169. premultiply(m) {
  1170. return this.multiplyMatrices(m, this);
  1171. }
  1172. multiplyMatrices(a, b) {
  1173. const ae = a.elements;
  1174. const be = b.elements;
  1175. const te = this.elements;
  1176. const a11 = ae[0],
  1177. a12 = ae[3],
  1178. a13 = ae[6];
  1179. const a21 = ae[1],
  1180. a22 = ae[4],
  1181. a23 = ae[7];
  1182. const a31 = ae[2],
  1183. a32 = ae[5],
  1184. a33 = ae[8];
  1185. const b11 = be[0],
  1186. b12 = be[3],
  1187. b13 = be[6];
  1188. const b21 = be[1],
  1189. b22 = be[4],
  1190. b23 = be[7];
  1191. const b31 = be[2],
  1192. b32 = be[5],
  1193. b33 = be[8];
  1194. te[0] = a11 * b11 + a12 * b21 + a13 * b31;
  1195. te[3] = a11 * b12 + a12 * b22 + a13 * b32;
  1196. te[6] = a11 * b13 + a12 * b23 + a13 * b33;
  1197. te[1] = a21 * b11 + a22 * b21 + a23 * b31;
  1198. te[4] = a21 * b12 + a22 * b22 + a23 * b32;
  1199. te[7] = a21 * b13 + a22 * b23 + a23 * b33;
  1200. te[2] = a31 * b11 + a32 * b21 + a33 * b31;
  1201. te[5] = a31 * b12 + a32 * b22 + a33 * b32;
  1202. te[8] = a31 * b13 + a32 * b23 + a33 * b33;
  1203. return this;
  1204. }
  1205. multiplyScalar(s) {
  1206. const te = this.elements;
  1207. te[0] *= s;
  1208. te[3] *= s;
  1209. te[6] *= s;
  1210. te[1] *= s;
  1211. te[4] *= s;
  1212. te[7] *= s;
  1213. te[2] *= s;
  1214. te[5] *= s;
  1215. te[8] *= s;
  1216. return this;
  1217. }
  1218. determinant() {
  1219. const te = this.elements;
  1220. const a = te[0],
  1221. b = te[1],
  1222. c = te[2],
  1223. d = te[3],
  1224. e = te[4],
  1225. f = te[5],
  1226. g = te[6],
  1227. h = te[7],
  1228. i = te[8];
  1229. return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g;
  1230. }
  1231. invert() {
  1232. const te = this.elements,
  1233. n11 = te[0],
  1234. n21 = te[1],
  1235. n31 = te[2],
  1236. n12 = te[3],
  1237. n22 = te[4],
  1238. n32 = te[5],
  1239. n13 = te[6],
  1240. n23 = te[7],
  1241. n33 = te[8],
  1242. t11 = n33 * n22 - n32 * n23,
  1243. t12 = n32 * n13 - n33 * n12,
  1244. t13 = n23 * n12 - n22 * n13,
  1245. det = n11 * t11 + n21 * t12 + n31 * t13;
  1246. if (det === 0) return this.set(0, 0, 0, 0, 0, 0, 0, 0, 0);
  1247. const detInv = 1 / det;
  1248. te[0] = t11 * detInv;
  1249. te[1] = (n31 * n23 - n33 * n21) * detInv;
  1250. te[2] = (n32 * n21 - n31 * n22) * detInv;
  1251. te[3] = t12 * detInv;
  1252. te[4] = (n33 * n11 - n31 * n13) * detInv;
  1253. te[5] = (n31 * n12 - n32 * n11) * detInv;
  1254. te[6] = t13 * detInv;
  1255. te[7] = (n21 * n13 - n23 * n11) * detInv;
  1256. te[8] = (n22 * n11 - n21 * n12) * detInv;
  1257. return this;
  1258. }
  1259. transpose() {
  1260. let tmp;
  1261. const m = this.elements;
  1262. tmp = m[1];
  1263. m[1] = m[3];
  1264. m[3] = tmp;
  1265. tmp = m[2];
  1266. m[2] = m[6];
  1267. m[6] = tmp;
  1268. tmp = m[5];
  1269. m[5] = m[7];
  1270. m[7] = tmp;
  1271. return this;
  1272. }
  1273. getNormalMatrix(matrix4) {
  1274. return this.setFromMatrix4(matrix4).copy(this).invert().transpose();
  1275. }
  1276. transposeIntoArray(r) {
  1277. const m = this.elements;
  1278. r[0] = m[0];
  1279. r[1] = m[3];
  1280. r[2] = m[6];
  1281. r[3] = m[1];
  1282. r[4] = m[4];
  1283. r[5] = m[7];
  1284. r[6] = m[2];
  1285. r[7] = m[5];
  1286. r[8] = m[8];
  1287. return this;
  1288. }
  1289. setUvTransform(tx, ty, sx, sy, rotation, cx, cy) {
  1290. const c = Math.cos(rotation);
  1291. const s = Math.sin(rotation);
  1292. this.set(sx * c, sx * s, -sx * (c * cx + s * cy) + cx + tx, -sy * s, sy * c, -sy * (-s * cx + c * cy) + cy + ty, 0, 0, 1);
  1293. }
  1294. scale(sx, sy) {
  1295. const te = this.elements;
  1296. te[0] *= sx;
  1297. te[3] *= sx;
  1298. te[6] *= sx;
  1299. te[1] *= sy;
  1300. te[4] *= sy;
  1301. te[7] *= sy;
  1302. return this;
  1303. }
  1304. rotate(theta) {
  1305. const c = Math.cos(theta);
  1306. const s = Math.sin(theta);
  1307. const te = this.elements;
  1308. const a11 = te[0],
  1309. a12 = te[3],
  1310. a13 = te[6];
  1311. const a21 = te[1],
  1312. a22 = te[4],
  1313. a23 = te[7];
  1314. te[0] = c * a11 + s * a21;
  1315. te[3] = c * a12 + s * a22;
  1316. te[6] = c * a13 + s * a23;
  1317. te[1] = -s * a11 + c * a21;
  1318. te[4] = -s * a12 + c * a22;
  1319. te[7] = -s * a13 + c * a23;
  1320. return this;
  1321. }
  1322. translate(tx, ty) {
  1323. const te = this.elements;
  1324. te[0] += tx * te[2];
  1325. te[3] += tx * te[5];
  1326. te[6] += tx * te[8];
  1327. te[1] += ty * te[2];
  1328. te[4] += ty * te[5];
  1329. te[7] += ty * te[8];
  1330. return this;
  1331. }
  1332. equals(matrix) {
  1333. const te = this.elements;
  1334. const me = matrix.elements;
  1335. for (let i = 0; i < 9; i++) {
  1336. if (te[i] !== me[i]) return false;
  1337. }
  1338. return true;
  1339. }
  1340. fromArray(array, offset = 0) {
  1341. for (let i = 0; i < 9; i++) {
  1342. this.elements[i] = array[i + offset];
  1343. }
  1344. return this;
  1345. }
  1346. toArray(array = [], offset = 0) {
  1347. const te = this.elements;
  1348. array[offset] = te[0];
  1349. array[offset + 1] = te[1];
  1350. array[offset + 2] = te[2];
  1351. array[offset + 3] = te[3];
  1352. array[offset + 4] = te[4];
  1353. array[offset + 5] = te[5];
  1354. array[offset + 6] = te[6];
  1355. array[offset + 7] = te[7];
  1356. array[offset + 8] = te[8];
  1357. return array;
  1358. }
  1359. }
  1360. exports.Matrix3 = Matrix3;
  1361. let _canvas;
  1362. const ImageUtils = {
  1363. getDataURL: function (image) {
  1364. if (/^data:/i.test(image.src)) {
  1365. return image.src;
  1366. }
  1367. if (typeof HTMLCanvasElement == 'undefined') {
  1368. return image.src;
  1369. }
  1370. let canvas;
  1371. if (image instanceof HTMLCanvasElement) {
  1372. canvas = image;
  1373. } else {
  1374. if (_canvas === undefined) _canvas = document.createElementNS('http://www.w3.org/1999/xhtml', 'canvas');
  1375. _canvas.width = image.width;
  1376. _canvas.height = image.height;
  1377. const context = _canvas.getContext('2d');
  1378. if (image instanceof ImageData) {
  1379. context.putImageData(image, 0, 0);
  1380. } else {
  1381. context.drawImage(image, 0, 0, image.width, image.height);
  1382. }
  1383. canvas = _canvas;
  1384. }
  1385. if (canvas.width > 2048 || canvas.height > 2048) {
  1386. return canvas.toDataURL('image/jpeg', 0.6);
  1387. } else {
  1388. return canvas.toDataURL('image/png');
  1389. }
  1390. }
  1391. };
  1392. exports.ImageUtils = ImageUtils;
  1393. let textureId = 0;
  1394. function Texture(image = Texture.DEFAULT_IMAGE, mapping = Texture.DEFAULT_MAPPING, wrapS = ClampToEdgeWrapping, wrapT = ClampToEdgeWrapping, magFilter = LinearFilter, minFilter = LinearMipmapLinearFilter, format = RGBAFormat, type = UnsignedByteType, anisotropy = 1, encoding = LinearEncoding) {
  1395. Object.defineProperty(this, 'id', {
  1396. value: textureId++
  1397. });
  1398. this.uuid = MathUtils.generateUUID();
  1399. this.name = '';
  1400. this.image = image;
  1401. this.mipmaps = [];
  1402. this.mapping = mapping;
  1403. this.wrapS = wrapS;
  1404. this.wrapT = wrapT;
  1405. this.magFilter = magFilter;
  1406. this.minFilter = minFilter;
  1407. this.anisotropy = anisotropy;
  1408. this.format = format;
  1409. this.internalFormat = null;
  1410. this.type = type;
  1411. this.offset = new Vector2(0, 0);
  1412. this.repeat = new Vector2(1, 1);
  1413. this.center = new Vector2(0, 0);
  1414. this.rotation = 0;
  1415. this.matrixAutoUpdate = true;
  1416. this.matrix = new Matrix3();
  1417. this.generateMipmaps = true;
  1418. this.premultiplyAlpha = false;
  1419. this.flipY = true;
  1420. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  1421. // Values of encoding !== THREE.LinearEncoding only supported on map, envMap and emissiveMap.
  1422. //
  1423. // Also changing the encoding after already used by a Material will not automatically make the Material
  1424. // update. You need to explicitly call Material.needsUpdate to trigger it to recompile.
  1425. this.encoding = encoding;
  1426. this.version = 0;
  1427. this.onUpdate = null;
  1428. }
  1429. Texture.DEFAULT_IMAGE = undefined;
  1430. Texture.DEFAULT_MAPPING = UVMapping;
  1431. Texture.prototype = Object.assign(Object.create(EventDispatcher.prototype), {
  1432. constructor: Texture,
  1433. isTexture: true,
  1434. updateMatrix: function () {
  1435. this.matrix.setUvTransform(this.offset.x, this.offset.y, this.repeat.x, this.repeat.y, this.rotation, this.center.x, this.center.y);
  1436. },
  1437. clone: function () {
  1438. return new this.constructor().copy(this);
  1439. },
  1440. copy: function (source) {
  1441. this.name = source.name;
  1442. this.image = source.image;
  1443. this.mipmaps = source.mipmaps.slice(0);
  1444. this.mapping = source.mapping;
  1445. this.wrapS = source.wrapS;
  1446. this.wrapT = source.wrapT;
  1447. this.magFilter = source.magFilter;
  1448. this.minFilter = source.minFilter;
  1449. this.anisotropy = source.anisotropy;
  1450. this.format = source.format;
  1451. this.internalFormat = source.internalFormat;
  1452. this.type = source.type;
  1453. this.offset.copy(source.offset);
  1454. this.repeat.copy(source.repeat);
  1455. this.center.copy(source.center);
  1456. this.rotation = source.rotation;
  1457. this.matrixAutoUpdate = source.matrixAutoUpdate;
  1458. this.matrix.copy(source.matrix);
  1459. this.generateMipmaps = source.generateMipmaps;
  1460. this.premultiplyAlpha = source.premultiplyAlpha;
  1461. this.flipY = source.flipY;
  1462. this.unpackAlignment = source.unpackAlignment;
  1463. this.encoding = source.encoding;
  1464. return this;
  1465. },
  1466. toJSON: function (meta) {
  1467. const isRootObject = meta === undefined || typeof meta === 'string';
  1468. if (!isRootObject && meta.textures[this.uuid] !== undefined) {
  1469. return meta.textures[this.uuid];
  1470. }
  1471. const output = {
  1472. metadata: {
  1473. version: 4.5,
  1474. type: 'Texture',
  1475. generator: 'Texture.toJSON'
  1476. },
  1477. uuid: this.uuid,
  1478. name: this.name,
  1479. mapping: this.mapping,
  1480. repeat: [this.repeat.x, this.repeat.y],
  1481. offset: [this.offset.x, this.offset.y],
  1482. center: [this.center.x, this.center.y],
  1483. rotation: this.rotation,
  1484. wrap: [this.wrapS, this.wrapT],
  1485. format: this.format,
  1486. type: this.type,
  1487. encoding: this.encoding,
  1488. minFilter: this.minFilter,
  1489. magFilter: this.magFilter,
  1490. anisotropy: this.anisotropy,
  1491. flipY: this.flipY,
  1492. premultiplyAlpha: this.premultiplyAlpha,
  1493. unpackAlignment: this.unpackAlignment
  1494. };
  1495. if (this.image !== undefined) {
  1496. // TODO: Move to THREE.Image
  1497. const image = this.image;
  1498. if (image.uuid === undefined) {
  1499. image.uuid = MathUtils.generateUUID(); // UGH
  1500. }
  1501. if (!isRootObject && meta.images[image.uuid] === undefined) {
  1502. let url;
  1503. if (Array.isArray(image)) {
  1504. // process array of images e.g. CubeTexture
  1505. url = [];
  1506. for (let i = 0, l = image.length; i < l; i++) {
  1507. // check cube texture with data textures
  1508. if (image[i].isDataTexture) {
  1509. url.push(serializeImage(image[i].image));
  1510. } else {
  1511. url.push(serializeImage(image[i]));
  1512. }
  1513. }
  1514. } else {
  1515. // process single image
  1516. url = serializeImage(image);
  1517. }
  1518. meta.images[image.uuid] = {
  1519. uuid: image.uuid,
  1520. url: url
  1521. };
  1522. }
  1523. output.image = image.uuid;
  1524. }
  1525. if (!isRootObject) {
  1526. meta.textures[this.uuid] = output;
  1527. }
  1528. return output;
  1529. },
  1530. dispose: function () {
  1531. this.dispatchEvent({
  1532. type: 'dispose'
  1533. });
  1534. },
  1535. transformUv: function (uv) {
  1536. if (this.mapping !== UVMapping) return uv;
  1537. uv.applyMatrix3(this.matrix);
  1538. if (uv.x < 0 || uv.x > 1) {
  1539. switch (this.wrapS) {
  1540. case RepeatWrapping:
  1541. uv.x = uv.x - Math.floor(uv.x);
  1542. break;
  1543. case ClampToEdgeWrapping:
  1544. uv.x = uv.x < 0 ? 0 : 1;
  1545. break;
  1546. case MirroredRepeatWrapping:
  1547. if (Math.abs(Math.floor(uv.x) % 2) === 1) {
  1548. uv.x = Math.ceil(uv.x) - uv.x;
  1549. } else {
  1550. uv.x = uv.x - Math.floor(uv.x);
  1551. }
  1552. break;
  1553. }
  1554. }
  1555. if (uv.y < 0 || uv.y > 1) {
  1556. switch (this.wrapT) {
  1557. case RepeatWrapping:
  1558. uv.y = uv.y - Math.floor(uv.y);
  1559. break;
  1560. case ClampToEdgeWrapping:
  1561. uv.y = uv.y < 0 ? 0 : 1;
  1562. break;
  1563. case MirroredRepeatWrapping:
  1564. if (Math.abs(Math.floor(uv.y) % 2) === 1) {
  1565. uv.y = Math.ceil(uv.y) - uv.y;
  1566. } else {
  1567. uv.y = uv.y - Math.floor(uv.y);
  1568. }
  1569. break;
  1570. }
  1571. }
  1572. if (this.flipY) {
  1573. uv.y = 1 - uv.y;
  1574. }
  1575. return uv;
  1576. }
  1577. });
  1578. Object.defineProperty(Texture.prototype, "needsUpdate", {
  1579. set: function (value) {
  1580. if (value === true) this.version++;
  1581. }
  1582. });
  1583. function serializeImage(image) {
  1584. if (typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement || typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement || typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap) {
  1585. // default images
  1586. return ImageUtils.getDataURL(image);
  1587. } else {
  1588. if (image.data) {
  1589. // images of DataTexture
  1590. return {
  1591. data: Array.prototype.slice.call(image.data),
  1592. width: image.width,
  1593. height: image.height,
  1594. type: image.data.constructor.name
  1595. };
  1596. } else {
  1597. console.warn('THREE.Texture: Unable to serialize Texture.');
  1598. return {};
  1599. }
  1600. }
  1601. }
  1602. class Vector4 {
  1603. constructor(x = 0, y = 0, z = 0, w = 1) {
  1604. Object.defineProperty(this, 'isVector4', {
  1605. value: true
  1606. });
  1607. this.x = x;
  1608. this.y = y;
  1609. this.z = z;
  1610. this.w = w;
  1611. }
  1612. get width() {
  1613. return this.z;
  1614. }
  1615. set width(value) {
  1616. this.z = value;
  1617. }
  1618. get height() {
  1619. return this.w;
  1620. }
  1621. set height(value) {
  1622. this.w = value;
  1623. }
  1624. set(x, y, z, w) {
  1625. this.x = x;
  1626. this.y = y;
  1627. this.z = z;
  1628. this.w = w;
  1629. return this;
  1630. }
  1631. setScalar(scalar) {
  1632. this.x = scalar;
  1633. this.y = scalar;
  1634. this.z = scalar;
  1635. this.w = scalar;
  1636. return this;
  1637. }
  1638. setX(x) {
  1639. this.x = x;
  1640. return this;
  1641. }
  1642. setY(y) {
  1643. this.y = y;
  1644. return this;
  1645. }
  1646. setZ(z) {
  1647. this.z = z;
  1648. return this;
  1649. }
  1650. setW(w) {
  1651. this.w = w;
  1652. return this;
  1653. }
  1654. setComponent(index, value) {
  1655. switch (index) {
  1656. case 0:
  1657. this.x = value;
  1658. break;
  1659. case 1:
  1660. this.y = value;
  1661. break;
  1662. case 2:
  1663. this.z = value;
  1664. break;
  1665. case 3:
  1666. this.w = value;
  1667. break;
  1668. default:
  1669. throw new Error('index is out of range: ' + index);
  1670. }
  1671. return this;
  1672. }
  1673. getComponent(index) {
  1674. switch (index) {
  1675. case 0:
  1676. return this.x;
  1677. case 1:
  1678. return this.y;
  1679. case 2:
  1680. return this.z;
  1681. case 3:
  1682. return this.w;
  1683. default:
  1684. throw new Error('index is out of range: ' + index);
  1685. }
  1686. }
  1687. clone() {
  1688. return new this.constructor(this.x, this.y, this.z, this.w);
  1689. }
  1690. copy(v) {
  1691. this.x = v.x;
  1692. this.y = v.y;
  1693. this.z = v.z;
  1694. this.w = v.w !== undefined ? v.w : 1;
  1695. return this;
  1696. }
  1697. add(v, w) {
  1698. if (w !== undefined) {
  1699. console.warn('THREE.Vector4: .add() now only accepts one argument. Use .addVectors( a, b ) instead.');
  1700. return this.addVectors(v, w);
  1701. }
  1702. this.x += v.x;
  1703. this.y += v.y;
  1704. this.z += v.z;
  1705. this.w += v.w;
  1706. return this;
  1707. }
  1708. addScalar(s) {
  1709. this.x += s;
  1710. this.y += s;
  1711. this.z += s;
  1712. this.w += s;
  1713. return this;
  1714. }
  1715. addVectors(a, b) {
  1716. this.x = a.x + b.x;
  1717. this.y = a.y + b.y;
  1718. this.z = a.z + b.z;
  1719. this.w = a.w + b.w;
  1720. return this;
  1721. }
  1722. addScaledVector(v, s) {
  1723. this.x += v.x * s;
  1724. this.y += v.y * s;
  1725. this.z += v.z * s;
  1726. this.w += v.w * s;
  1727. return this;
  1728. }
  1729. sub(v, w) {
  1730. if (w !== undefined) {
  1731. console.warn('THREE.Vector4: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.');
  1732. return this.subVectors(v, w);
  1733. }
  1734. this.x -= v.x;
  1735. this.y -= v.y;
  1736. this.z -= v.z;
  1737. this.w -= v.w;
  1738. return this;
  1739. }
  1740. subScalar(s) {
  1741. this.x -= s;
  1742. this.y -= s;
  1743. this.z -= s;
  1744. this.w -= s;
  1745. return this;
  1746. }
  1747. subVectors(a, b) {
  1748. this.x = a.x - b.x;
  1749. this.y = a.y - b.y;
  1750. this.z = a.z - b.z;
  1751. this.w = a.w - b.w;
  1752. return this;
  1753. }
  1754. multiplyScalar(scalar) {
  1755. this.x *= scalar;
  1756. this.y *= scalar;
  1757. this.z *= scalar;
  1758. this.w *= scalar;
  1759. return this;
  1760. }
  1761. applyMatrix4(m) {
  1762. const x = this.x,
  1763. y = this.y,
  1764. z = this.z,
  1765. w = this.w;
  1766. const e = m.elements;
  1767. this.x = e[0] * x + e[4] * y + e[8] * z + e[12] * w;
  1768. this.y = e[1] * x + e[5] * y + e[9] * z + e[13] * w;
  1769. this.z = e[2] * x + e[6] * y + e[10] * z + e[14] * w;
  1770. this.w = e[3] * x + e[7] * y + e[11] * z + e[15] * w;
  1771. return this;
  1772. }
  1773. divideScalar(scalar) {
  1774. return this.multiplyScalar(1 / scalar);
  1775. }
  1776. setAxisAngleFromQuaternion(q) {
  1777. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  1778. // q is assumed to be normalized
  1779. this.w = 2 * Math.acos(q.w);
  1780. const s = Math.sqrt(1 - q.w * q.w);
  1781. if (s < 0.0001) {
  1782. this.x = 1;
  1783. this.y = 0;
  1784. this.z = 0;
  1785. } else {
  1786. this.x = q.x / s;
  1787. this.y = q.y / s;
  1788. this.z = q.z / s;
  1789. }
  1790. return this;
  1791. }
  1792. setAxisAngleFromRotationMatrix(m) {
  1793. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  1794. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1795. let angle, x, y, z; // variables for result
  1796. const epsilon = 0.01,
  1797. // margin to allow for rounding errors
  1798. epsilon2 = 0.1,
  1799. // margin to distinguish between 0 and 180 degrees
  1800. te = m.elements,
  1801. m11 = te[0],
  1802. m12 = te[4],
  1803. m13 = te[8],
  1804. m21 = te[1],
  1805. m22 = te[5],
  1806. m23 = te[9],
  1807. m31 = te[2],
  1808. m32 = te[6],
  1809. m33 = te[10];
  1810. if (Math.abs(m12 - m21) < epsilon && Math.abs(m13 - m31) < epsilon && Math.abs(m23 - m32) < epsilon) {
  1811. // singularity found
  1812. // first check for identity matrix which must have +1 for all terms
  1813. // in leading diagonal and zero in other terms
  1814. if (Math.abs(m12 + m21) < epsilon2 && Math.abs(m13 + m31) < epsilon2 && Math.abs(m23 + m32) < epsilon2 && Math.abs(m11 + m22 + m33 - 3) < epsilon2) {
  1815. // this singularity is identity matrix so angle = 0
  1816. this.set(1, 0, 0, 0);
  1817. return this; // zero angle, arbitrary axis
  1818. } // otherwise this singularity is angle = 180
  1819. angle = Math.PI;
  1820. const xx = (m11 + 1) / 2;
  1821. const yy = (m22 + 1) / 2;
  1822. const zz = (m33 + 1) / 2;
  1823. const xy = (m12 + m21) / 4;
  1824. const xz = (m13 + m31) / 4;
  1825. const yz = (m23 + m32) / 4;
  1826. if (xx > yy && xx > zz) {
  1827. // m11 is the largest diagonal term
  1828. if (xx < epsilon) {
  1829. x = 0;
  1830. y = 0.707106781;
  1831. z = 0.707106781;
  1832. } else {
  1833. x = Math.sqrt(xx);
  1834. y = xy / x;
  1835. z = xz / x;
  1836. }
  1837. } else if (yy > zz) {
  1838. // m22 is the largest diagonal term
  1839. if (yy < epsilon) {
  1840. x = 0.707106781;
  1841. y = 0;
  1842. z = 0.707106781;
  1843. } else {
  1844. y = Math.sqrt(yy);
  1845. x = xy / y;
  1846. z = yz / y;
  1847. }
  1848. } else {
  1849. // m33 is the largest diagonal term so base result on this
  1850. if (zz < epsilon) {
  1851. x = 0.707106781;
  1852. y = 0.707106781;
  1853. z = 0;
  1854. } else {
  1855. z = Math.sqrt(zz);
  1856. x = xz / z;
  1857. y = yz / z;
  1858. }
  1859. }
  1860. this.set(x, y, z, angle);
  1861. return this; // return 180 deg rotation
  1862. } // as we have reached here there are no singularities so we can handle normally
  1863. let s = Math.sqrt((m32 - m23) * (m32 - m23) + (m13 - m31) * (m13 - m31) + (m21 - m12) * (m21 - m12)); // used to normalize
  1864. if (Math.abs(s) < 0.001) s = 1; // prevent divide by zero, should not happen if matrix is orthogonal and should be
  1865. // caught by singularity test above, but I've left it in just in case
  1866. this.x = (m32 - m23) / s;
  1867. this.y = (m13 - m31) / s;
  1868. this.z = (m21 - m12) / s;
  1869. this.w = Math.acos((m11 + m22 + m33 - 1) / 2);
  1870. return this;
  1871. }
  1872. min(v) {
  1873. this.x = Math.min(this.x, v.x);
  1874. this.y = Math.min(this.y, v.y);
  1875. this.z = Math.min(this.z, v.z);
  1876. this.w = Math.min(this.w, v.w);
  1877. return this;
  1878. }
  1879. max(v) {
  1880. this.x = Math.max(this.x, v.x);
  1881. this.y = Math.max(this.y, v.y);
  1882. this.z = Math.max(this.z, v.z);
  1883. this.w = Math.max(this.w, v.w);
  1884. return this;
  1885. }
  1886. clamp(min, max) {
  1887. // assumes min < max, componentwise
  1888. this.x = Math.max(min.x, Math.min(max.x, this.x));
  1889. this.y = Math.max(min.y, Math.min(max.y, this.y));
  1890. this.z = Math.max(min.z, Math.min(max.z, this.z));
  1891. this.w = Math.max(min.w, Math.min(max.w, this.w));
  1892. return this;
  1893. }
  1894. clampScalar(minVal, maxVal) {
  1895. this.x = Math.max(minVal, Math.min(maxVal, this.x));
  1896. this.y = Math.max(minVal, Math.min(maxVal, this.y));
  1897. this.z = Math.max(minVal, Math.min(maxVal, this.z));
  1898. this.w = Math.max(minVal, Math.min(maxVal, this.w));
  1899. return this;
  1900. }
  1901. clampLength(min, max) {
  1902. const length = this.length();
  1903. return this.divideScalar(length || 1).multiplyScalar(Math.max(min, Math.min(max, length)));
  1904. }
  1905. floor() {
  1906. this.x = Math.floor(this.x);
  1907. this.y = Math.floor(this.y);
  1908. this.z = Math.floor(this.z);
  1909. this.w = Math.floor(this.w);
  1910. return this;
  1911. }
  1912. ceil() {
  1913. this.x = Math.ceil(this.x);
  1914. this.y = Math.ceil(this.y);
  1915. this.z = Math.ceil(this.z);
  1916. this.w = Math.ceil(this.w);
  1917. return this;
  1918. }
  1919. round() {
  1920. this.x = Math.round(this.x);
  1921. this.y = Math.round(this.y);
  1922. this.z = Math.round(this.z);
  1923. this.w = Math.round(this.w);
  1924. return this;
  1925. }
  1926. roundToZero() {
  1927. this.x = this.x < 0 ? Math.ceil(this.x) : Math.floor(this.x);
  1928. this.y = this.y < 0 ? Math.ceil(this.y) : Math.floor(this.y);
  1929. this.z = this.z < 0 ? Math.ceil(this.z) : Math.floor(this.z);
  1930. this.w = this.w < 0 ? Math.ceil(this.w) : Math.floor(this.w);
  1931. return this;
  1932. }
  1933. negate() {
  1934. this.x = -this.x;
  1935. this.y = -this.y;
  1936. this.z = -this.z;
  1937. this.w = -this.w;
  1938. return this;
  1939. }
  1940. dot(v) {
  1941. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  1942. }
  1943. lengthSq() {
  1944. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  1945. }
  1946. length() {
  1947. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1948. }
  1949. manhattanLength() {
  1950. return Math.abs(this.x) + Math.abs(this.y) + Math.abs(this.z) + Math.abs(this.w);
  1951. }
  1952. normalize() {
  1953. return this.divideScalar(this.length() || 1);
  1954. }
  1955. setLength(length) {
  1956. return this.normalize().multiplyScalar(length);
  1957. }
  1958. lerp(v, alpha) {
  1959. this.x += (v.x - this.x) * alpha;
  1960. this.y += (v.y - this.y) * alpha;
  1961. this.z += (v.z - this.z) * alpha;
  1962. this.w += (v.w - this.w) * alpha;
  1963. return this;
  1964. }
  1965. lerpVectors(v1, v2, alpha) {
  1966. this.x = v1.x + (v2.x - v1.x) * alpha;
  1967. this.y = v1.y + (v2.y - v1.y) * alpha;
  1968. this.z = v1.z + (v2.z - v1.z) * alpha;
  1969. this.w = v1.w + (v2.w - v1.w) * alpha;
  1970. return this;
  1971. }
  1972. equals(v) {
  1973. return v.x === this.x && v.y === this.y && v.z === this.z && v.w === this.w;
  1974. }
  1975. fromArray(array, offset = 0) {
  1976. this.x = array[offset];
  1977. this.y = array[offset + 1];
  1978. this.z = array[offset + 2];
  1979. this.w = array[offset + 3];
  1980. return this;
  1981. }
  1982. toArray(array = [], offset = 0) {
  1983. array[offset] = this.x;
  1984. array[offset + 1] = this.y;
  1985. array[offset + 2] = this.z;
  1986. array[offset + 3] = this.w;
  1987. return array;
  1988. }
  1989. fromBufferAttribute(attribute, index, offset) {
  1990. if (offset !== undefined) {
  1991. console.warn('THREE.Vector4: offset has been removed from .fromBufferAttribute().');
  1992. }
  1993. this.x = attribute.getX(index);
  1994. this.y = attribute.getY(index);
  1995. this.z = attribute.getZ(index);
  1996. this.w = attribute.getW(index);
  1997. return this;
  1998. }
  1999. random() {
  2000. this.x = Math.random();
  2001. this.y = Math.random();
  2002. this.z = Math.random();
  2003. this.w = Math.random();
  2004. return this;
  2005. }
  2006. }
  2007. /*
  2008. In options, we can specify:
  2009. * Texture parameters for an auto-generated target texture
  2010. * depthBuffer/stencilBuffer: Booleans to indicate if we should generate these buffers
  2011. */
  2012. exports.Vector4 = Vector4;
  2013. function WebGLRenderTarget(width, height, options) {
  2014. this.width = width;
  2015. this.height = height;
  2016. this.scissor = new Vector4(0, 0, width, height);
  2017. this.scissorTest = false;
  2018. this.viewport = new Vector4(0, 0, width, height);
  2019. options = options || {};
  2020. this.texture = new Texture(undefined, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding);
  2021. this.texture.image = {};
  2022. this.texture.image.width = width;
  2023. this.texture.image.height = height;
  2024. this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false;
  2025. this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter;
  2026. this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
  2027. this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : false;
  2028. this.depthTexture = options.depthTexture !== undefined ? options.depthTexture : null;
  2029. }
  2030. WebGLRenderTarget.prototype = Object.assign(Object.create(EventDispatcher.prototype), {
  2031. constructor: WebGLRenderTarget,
  2032. isWebGLRenderTarget: true,
  2033. setSize: function (width, height) {
  2034. if (this.width !== width || this.height !== height) {
  2035. this.width = width;
  2036. this.height = height;
  2037. this.texture.image.width = width;
  2038. this.texture.image.height = height;
  2039. this.dispose();
  2040. }
  2041. this.viewport.set(0, 0, width, height);
  2042. this.scissor.set(0, 0, width, height);
  2043. },
  2044. clone: function () {
  2045. return new this.constructor().copy(this);
  2046. },
  2047. copy: function (source) {
  2048. this.width = source.width;
  2049. this.height = source.height;
  2050. this.viewport.copy(source.viewport);
  2051. this.texture = source.texture.clone();
  2052. this.depthBuffer = source.depthBuffer;
  2053. this.stencilBuffer = source.stencilBuffer;
  2054. this.depthTexture = source.depthTexture;
  2055. return this;
  2056. },
  2057. dispose: function () {
  2058. this.dispatchEvent({
  2059. type: 'dispose'
  2060. });
  2061. }
  2062. });
  2063. function WebGLMultisampleRenderTarget(width, height, options) {
  2064. WebGLRenderTarget.call(this, width, height, options);
  2065. this.samples = 4;
  2066. }
  2067. WebGLMultisampleRenderTarget.prototype = Object.assign(Object.create(WebGLRenderTarget.prototype), {
  2068. constructor: WebGLMultisampleRenderTarget,
  2069. isWebGLMultisampleRenderTarget: true,
  2070. copy: function (source) {
  2071. WebGLRenderTarget.prototype.copy.call(this, source);
  2072. this.samples = source.samples;
  2073. return this;
  2074. }
  2075. });
  2076. class Quaternion {
  2077. constructor(x = 0, y = 0, z = 0, w = 1) {
  2078. Object.defineProperty(this, 'isQuaternion', {
  2079. value: true
  2080. });
  2081. this._x = x;
  2082. this._y = y;
  2083. this._z = z;
  2084. this._w = w;
  2085. }
  2086. static slerp(qa, qb, qm, t) {
  2087. return qm.copy(qa).slerp(qb, t);
  2088. }
  2089. static slerpFlat(dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t) {
  2090. // fuzz-free, array-based Quaternion SLERP operation
  2091. let x0 = src0[srcOffset0 + 0],
  2092. y0 = src0[srcOffset0 + 1],
  2093. z0 = src0[srcOffset0 + 2],
  2094. w0 = src0[srcOffset0 + 3];
  2095. const x1 = src1[srcOffset1 + 0],
  2096. y1 = src1[srcOffset1 + 1],
  2097. z1 = src1[srcOffset1 + 2],
  2098. w1 = src1[srcOffset1 + 3];
  2099. if (w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1) {
  2100. let s = 1 - t;
  2101. const cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1,
  2102. dir = cos >= 0 ? 1 : -1,
  2103. sqrSin = 1 - cos * cos; // Skip the Slerp for tiny steps to avoid numeric problems:
  2104. if (sqrSin > Number.EPSILON) {
  2105. const sin = Math.sqrt(sqrSin),
  2106. len = Math.atan2(sin, cos * dir);
  2107. s = Math.sin(s * len) / sin;
  2108. t = Math.sin(t * len) / sin;
  2109. }
  2110. const tDir = t * dir;
  2111. x0 = x0 * s + x1 * tDir;
  2112. y0 = y0 * s + y1 * tDir;
  2113. z0 = z0 * s + z1 * tDir;
  2114. w0 = w0 * s + w1 * tDir; // Normalize in case we just did a lerp:
  2115. if (s === 1 - t) {
  2116. const f = 1 / Math.sqrt(x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0);
  2117. x0 *= f;
  2118. y0 *= f;
  2119. z0 *= f;
  2120. w0 *= f;
  2121. }
  2122. }
  2123. dst[dstOffset] = x0;
  2124. dst[dstOffset + 1] = y0;
  2125. dst[dstOffset + 2] = z0;
  2126. dst[dstOffset + 3] = w0;
  2127. }
  2128. static multiplyQuaternionsFlat(dst, dstOffset, src0, srcOffset0, src1, srcOffset1) {
  2129. const x0 = src0[srcOffset0];
  2130. const y0 = src0[srcOffset0 + 1];
  2131. const z0 = src0[srcOffset0 + 2];
  2132. const w0 = src0[srcOffset0 + 3];
  2133. const x1 = src1[srcOffset1];
  2134. const y1 = src1[srcOffset1 + 1];
  2135. const z1 = src1[srcOffset1 + 2];
  2136. const w1 = src1[srcOffset1 + 3];
  2137. dst[dstOffset] = x0 * w1 + w0 * x1 + y0 * z1 - z0 * y1;
  2138. dst[dstOffset + 1] = y0 * w1 + w0 * y1 + z0 * x1 - x0 * z1;
  2139. dst[dstOffset + 2] = z0 * w1 + w0 * z1 + x0 * y1 - y0 * x1;
  2140. dst[dstOffset + 3] = w0 * w1 - x0 * x1 - y0 * y1 - z0 * z1;
  2141. return dst;
  2142. }
  2143. get x() {
  2144. return this._x;
  2145. }
  2146. set x(value) {
  2147. this._x = value;
  2148. this._onChangeCallback();
  2149. }
  2150. get y() {
  2151. return this._y;
  2152. }
  2153. set y(value) {
  2154. this._y = value;
  2155. this._onChangeCallback();
  2156. }
  2157. get z() {
  2158. return this._z;
  2159. }
  2160. set z(value) {
  2161. this._z = value;
  2162. this._onChangeCallback();
  2163. }
  2164. get w() {
  2165. return this._w;
  2166. }
  2167. set w(value) {
  2168. this._w = value;
  2169. this._onChangeCallback();
  2170. }
  2171. set(x, y, z, w) {
  2172. this._x = x;
  2173. this._y = y;
  2174. this._z = z;
  2175. this._w = w;
  2176. this._onChangeCallback();
  2177. return this;
  2178. }
  2179. clone() {
  2180. return new this.constructor(this._x, this._y, this._z, this._w);
  2181. }
  2182. copy(quaternion) {
  2183. this._x = quaternion.x;
  2184. this._y = quaternion.y;
  2185. this._z = quaternion.z;
  2186. this._w = quaternion.w;
  2187. this._onChangeCallback();
  2188. return this;
  2189. }
  2190. setFromEuler(euler, update) {
  2191. if (!(euler && euler.isEuler)) {
  2192. throw new Error('THREE.Quaternion: .setFromEuler() now expects an Euler rotation rather than a Vector3 and order.');
  2193. }
  2194. const x = euler._x,
  2195. y = euler._y,
  2196. z = euler._z,
  2197. order = euler._order; // http://www.mathworks.com/matlabcentral/fileexchange/
  2198. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  2199. // content/SpinCalc.m
  2200. const cos = Math.cos;
  2201. const sin = Math.sin;
  2202. const c1 = cos(x / 2);
  2203. const c2 = cos(y / 2);
  2204. const c3 = cos(z / 2);
  2205. const s1 = sin(x / 2);
  2206. const s2 = sin(y / 2);
  2207. const s3 = sin(z / 2);
  2208. switch (order) {
  2209. case 'XYZ':
  2210. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  2211. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  2212. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  2213. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  2214. break;
  2215. case 'YXZ':
  2216. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  2217. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  2218. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  2219. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  2220. break;
  2221. case 'ZXY':
  2222. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  2223. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  2224. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  2225. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  2226. break;
  2227. case 'ZYX':
  2228. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  2229. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  2230. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  2231. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  2232. break;
  2233. case 'YZX':
  2234. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  2235. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  2236. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  2237. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  2238. break;
  2239. case 'XZY':
  2240. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  2241. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  2242. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  2243. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  2244. break;
  2245. default:
  2246. console.warn('THREE.Quaternion: .setFromEuler() encountered an unknown order: ' + order);
  2247. }
  2248. if (update !== false) this._onChangeCallback();
  2249. return this;
  2250. }
  2251. setFromAxisAngle(axis, angle) {
  2252. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  2253. // assumes axis is normalized
  2254. const halfAngle = angle / 2,
  2255. s = Math.sin(halfAngle);
  2256. this._x = axis.x * s;
  2257. this._y = axis.y * s;
  2258. this._z = axis.z * s;
  2259. this._w = Math.cos(halfAngle);
  2260. this._onChangeCallback();
  2261. return this;
  2262. }
  2263. setFromRotationMatrix(m) {
  2264. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  2265. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  2266. const te = m.elements,
  2267. m11 = te[0],
  2268. m12 = te[4],
  2269. m13 = te[8],
  2270. m21 = te[1],
  2271. m22 = te[5],
  2272. m23 = te[9],
  2273. m31 = te[2],
  2274. m32 = te[6],
  2275. m33 = te[10],
  2276. trace = m11 + m22 + m33;
  2277. if (trace > 0) {
  2278. const s = 0.5 / Math.sqrt(trace + 1.0);
  2279. this._w = 0.25 / s;
  2280. this._x = (m32 - m23) * s;
  2281. this._y = (m13 - m31) * s;
  2282. this._z = (m21 - m12) * s;
  2283. } else if (m11 > m22 && m11 > m33) {
  2284. const s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  2285. this._w = (m32 - m23) / s;
  2286. this._x = 0.25 * s;
  2287. this._y = (m12 + m21) / s;
  2288. this._z = (m13 + m31) / s;
  2289. } else if (m22 > m33) {
  2290. const s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  2291. this._w = (m13 - m31) / s;
  2292. this._x = (m12 + m21) / s;
  2293. this._y = 0.25 * s;
  2294. this._z = (m23 + m32) / s;
  2295. } else {
  2296. const s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  2297. this._w = (m21 - m12) / s;
  2298. this._x = (m13 + m31) / s;
  2299. this._y = (m23 + m32) / s;
  2300. this._z = 0.25 * s;
  2301. }
  2302. this._onChangeCallback();
  2303. return this;
  2304. }
  2305. setFromUnitVectors(vFrom, vTo) {
  2306. // assumes direction vectors vFrom and vTo are normalized
  2307. const EPS = 0.000001;
  2308. let r = vFrom.dot(vTo) + 1;
  2309. if (r < EPS) {
  2310. r = 0;
  2311. if (Math.abs(vFrom.x) > Math.abs(vFrom.z)) {
  2312. this._x = -vFrom.y;
  2313. this._y = vFrom.x;
  2314. this._z = 0;
  2315. this._w = r;
  2316. } else {
  2317. this._x = 0;
  2318. this._y = -vFrom.z;
  2319. this._z = vFrom.y;
  2320. this._w = r;
  2321. }
  2322. } else {
  2323. // crossVectors( vFrom, vTo ); // inlined to avoid cyclic dependency on Vector3
  2324. this._x = vFrom.y * vTo.z - vFrom.z * vTo.y;
  2325. this._y = vFrom.z * vTo.x - vFrom.x * vTo.z;
  2326. this._z = vFrom.x * vTo.y - vFrom.y * vTo.x;
  2327. this._w = r;
  2328. }
  2329. return this.normalize();
  2330. }
  2331. angleTo(q) {
  2332. return 2 * Math.acos(Math.abs(MathUtils.clamp(this.dot(q), -1, 1)));
  2333. }
  2334. rotateTowards(q, step) {
  2335. const angle = this.angleTo(q);
  2336. if (angle === 0) return this;
  2337. const t = Math.min(1, step / angle);
  2338. this.slerp(q, t);
  2339. return this;
  2340. }
  2341. identity() {
  2342. return this.set(0, 0, 0, 1);
  2343. }
  2344. invert() {
  2345. // quaternion is assumed to have unit length
  2346. return this.conjugate();
  2347. }
  2348. conjugate() {
  2349. this._x *= -1;
  2350. this._y *= -1;
  2351. this._z *= -1;
  2352. this._onChangeCallback();
  2353. return this;
  2354. }
  2355. dot(v) {
  2356. return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w;
  2357. }
  2358. lengthSq() {
  2359. return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  2360. }
  2361. length() {
  2362. return Math.sqrt(this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w);
  2363. }
  2364. normalize() {
  2365. let l = this.length();
  2366. if (l === 0) {
  2367. this._x = 0;
  2368. this._y = 0;
  2369. this._z = 0;
  2370. this._w = 1;
  2371. } else {
  2372. l = 1 / l;
  2373. this._x = this._x * l;
  2374. this._y = this._y * l;
  2375. this._z = this._z * l;
  2376. this._w = this._w * l;
  2377. }
  2378. this._onChangeCallback();
  2379. return this;
  2380. }
  2381. multiply(q, p) {
  2382. if (p !== undefined) {
  2383. console.warn('THREE.Quaternion: .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead.');
  2384. return this.multiplyQuaternions(q, p);
  2385. }
  2386. return this.multiplyQuaternions(this, q);
  2387. }
  2388. premultiply(q) {
  2389. return this.multiplyQuaternions(q, this);
  2390. }
  2391. multiplyQuaternions(a, b) {
  2392. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  2393. const qax = a._x,
  2394. qay = a._y,
  2395. qaz = a._z,
  2396. qaw = a._w;
  2397. const qbx = b._x,
  2398. qby = b._y,
  2399. qbz = b._z,
  2400. qbw = b._w;
  2401. this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  2402. this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  2403. this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  2404. this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  2405. this._onChangeCallback();
  2406. return this;
  2407. }
  2408. slerp(qb, t) {
  2409. if (t === 0) return this;
  2410. if (t === 1) return this.copy(qb);
  2411. const x = this._x,
  2412. y = this._y,
  2413. z = this._z,
  2414. w = this._w; // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  2415. let cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z;
  2416. if (cosHalfTheta < 0) {
  2417. this._w = -qb._w;
  2418. this._x = -qb._x;
  2419. this._y = -qb._y;
  2420. this._z = -qb._z;
  2421. cosHalfTheta = -cosHalfTheta;
  2422. } else {
  2423. this.copy(qb);
  2424. }
  2425. if (cosHalfTheta >= 1.0) {
  2426. this._w = w;
  2427. this._x = x;
  2428. this._y = y;
  2429. this._z = z;
  2430. return this;
  2431. }
  2432. const sqrSinHalfTheta = 1.0 - cosHalfTheta * cosHalfTheta;
  2433. if (sqrSinHalfTheta <= Number.EPSILON) {
  2434. const s = 1 - t;
  2435. this._w = s * w + t * this._w;
  2436. this._x = s * x + t * this._x;
  2437. this._y = s * y + t * this._y;
  2438. this._z = s * z + t * this._z;
  2439. this.normalize();
  2440. this._onChangeCallback();
  2441. return this;
  2442. }
  2443. const sinHalfTheta = Math.sqrt(sqrSinHalfTheta);
  2444. const halfTheta = Math.atan2(sinHalfTheta, cosHalfTheta);
  2445. const ratioA = Math.sin((1 - t) * halfTheta) / sinHalfTheta,
  2446. ratioB = Math.sin(t * halfTheta) / sinHalfTheta;
  2447. this._w = w * ratioA + this._w * ratioB;
  2448. this._x = x * ratioA + this._x * ratioB;
  2449. this._y = y * ratioA + this._y * ratioB;
  2450. this._z = z * ratioA + this._z * ratioB;
  2451. this._onChangeCallback();
  2452. return this;
  2453. }
  2454. equals(quaternion) {
  2455. return quaternion._x === this._x && quaternion._y === this._y && quaternion._z === this._z && quaternion._w === this._w;
  2456. }
  2457. fromArray(array, offset = 0) {
  2458. this._x = array[offset];
  2459. this._y = array[offset + 1];
  2460. this._z = array[offset + 2];
  2461. this._w = array[offset + 3];
  2462. this._onChangeCallback();
  2463. return this;
  2464. }
  2465. toArray(array = [], offset = 0) {
  2466. array[offset] = this._x;
  2467. array[offset + 1] = this._y;
  2468. array[offset + 2] = this._z;
  2469. array[offset + 3] = this._w;
  2470. return array;
  2471. }
  2472. fromBufferAttribute(attribute, index) {
  2473. this._x = attribute.getX(index);
  2474. this._y = attribute.getY(index);
  2475. this._z = attribute.getZ(index);
  2476. this._w = attribute.getW(index);
  2477. return this;
  2478. }
  2479. _onChange(callback) {
  2480. this._onChangeCallback = callback;
  2481. return this;
  2482. }
  2483. _onChangeCallback() {}
  2484. }
  2485. exports.Quaternion = Quaternion;
  2486. class Vector3 {
  2487. constructor(x = 0, y = 0, z = 0) {
  2488. Object.defineProperty(this, 'isVector3', {
  2489. value: true
  2490. });
  2491. this.x = x;
  2492. this.y = y;
  2493. this.z = z;
  2494. }
  2495. set(x, y, z) {
  2496. if (z === undefined) z = this.z; // sprite.scale.set(x,y)
  2497. this.x = x;
  2498. this.y = y;
  2499. this.z = z;
  2500. return this;
  2501. }
  2502. setScalar(scalar) {
  2503. this.x = scalar;
  2504. this.y = scalar;
  2505. this.z = scalar;
  2506. return this;
  2507. }
  2508. setX(x) {
  2509. this.x = x;
  2510. return this;
  2511. }
  2512. setY(y) {
  2513. this.y = y;
  2514. return this;
  2515. }
  2516. setZ(z) {
  2517. this.z = z;
  2518. return this;
  2519. }
  2520. setComponent(index, value) {
  2521. switch (index) {
  2522. case 0:
  2523. this.x = value;
  2524. break;
  2525. case 1:
  2526. this.y = value;
  2527. break;
  2528. case 2:
  2529. this.z = value;
  2530. break;
  2531. default:
  2532. throw new Error('index is out of range: ' + index);
  2533. }
  2534. return this;
  2535. }
  2536. getComponent(index) {
  2537. switch (index) {
  2538. case 0:
  2539. return this.x;
  2540. case 1:
  2541. return this.y;
  2542. case 2:
  2543. return this.z;
  2544. default:
  2545. throw new Error('index is out of range: ' + index);
  2546. }
  2547. }
  2548. clone() {
  2549. return new this.constructor(this.x, this.y, this.z);
  2550. }
  2551. copy(v) {
  2552. this.x = v.x;
  2553. this.y = v.y;
  2554. this.z = v.z;
  2555. return this;
  2556. }
  2557. add(v, w) {
  2558. if (w !== undefined) {
  2559. console.warn('THREE.Vector3: .add() now only accepts one argument. Use .addVectors( a, b ) instead.');
  2560. return this.addVectors(v, w);
  2561. }
  2562. this.x += v.x;
  2563. this.y += v.y;
  2564. this.z += v.z;
  2565. return this;
  2566. }
  2567. addScalar(s) {
  2568. this.x += s;
  2569. this.y += s;
  2570. this.z += s;
  2571. return this;
  2572. }
  2573. addVectors(a, b) {
  2574. this.x = a.x + b.x;
  2575. this.y = a.y + b.y;
  2576. this.z = a.z + b.z;
  2577. return this;
  2578. }
  2579. addScaledVector(v, s) {
  2580. this.x += v.x * s;
  2581. this.y += v.y * s;
  2582. this.z += v.z * s;
  2583. return this;
  2584. }
  2585. sub(v, w) {
  2586. if (w !== undefined) {
  2587. console.warn('THREE.Vector3: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.');
  2588. return this.subVectors(v, w);
  2589. }
  2590. this.x -= v.x;
  2591. this.y -= v.y;
  2592. this.z -= v.z;
  2593. return this;
  2594. }
  2595. subScalar(s) {
  2596. this.x -= s;
  2597. this.y -= s;
  2598. this.z -= s;
  2599. return this;
  2600. }
  2601. subVectors(a, b) {
  2602. this.x = a.x - b.x;
  2603. this.y = a.y - b.y;
  2604. this.z = a.z - b.z;
  2605. return this;
  2606. }
  2607. multiply(v, w) {
  2608. if (w !== undefined) {
  2609. console.warn('THREE.Vector3: .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead.');
  2610. return this.multiplyVectors(v, w);
  2611. }
  2612. this.x *= v.x;
  2613. this.y *= v.y;
  2614. this.z *= v.z;
  2615. return this;
  2616. }
  2617. multiplyScalar(scalar) {
  2618. this.x *= scalar;
  2619. this.y *= scalar;
  2620. this.z *= scalar;
  2621. return this;
  2622. }
  2623. multiplyVectors(a, b) {
  2624. this.x = a.x * b.x;
  2625. this.y = a.y * b.y;
  2626. this.z = a.z * b.z;
  2627. return this;
  2628. }
  2629. applyEuler(euler) {
  2630. if (!(euler && euler.isEuler)) {
  2631. console.error('THREE.Vector3: .applyEuler() now expects an Euler rotation rather than a Vector3 and order.');
  2632. }
  2633. return this.applyQuaternion(_quaternion.setFromEuler(euler));
  2634. }
  2635. applyAxisAngle(axis, angle) {
  2636. return this.applyQuaternion(_quaternion.setFromAxisAngle(axis, angle));
  2637. }
  2638. applyMatrix3(m) {
  2639. const x = this.x,
  2640. y = this.y,
  2641. z = this.z;
  2642. const e = m.elements;
  2643. this.x = e[0] * x + e[3] * y + e[6] * z;
  2644. this.y = e[1] * x + e[4] * y + e[7] * z;
  2645. this.z = e[2] * x + e[5] * y + e[8] * z;
  2646. return this;
  2647. }
  2648. applyNormalMatrix(m) {
  2649. return this.applyMatrix3(m).normalize();
  2650. }
  2651. applyMatrix4(m) {
  2652. const x = this.x,
  2653. y = this.y,
  2654. z = this.z;
  2655. const e = m.elements;
  2656. const w = 1 / (e[3] * x + e[7] * y + e[11] * z + e[15]);
  2657. this.x = (e[0] * x + e[4] * y + e[8] * z + e[12]) * w;
  2658. this.y = (e[1] * x + e[5] * y + e[9] * z + e[13]) * w;
  2659. this.z = (e[2] * x + e[6] * y + e[10] * z + e[14]) * w;
  2660. return this;
  2661. }
  2662. applyQuaternion(q) {
  2663. const x = this.x,
  2664. y = this.y,
  2665. z = this.z;
  2666. const qx = q.x,
  2667. qy = q.y,
  2668. qz = q.z,
  2669. qw = q.w; // calculate quat * vector
  2670. const ix = qw * x + qy * z - qz * y;
  2671. const iy = qw * y + qz * x - qx * z;
  2672. const iz = qw * z + qx * y - qy * x;
  2673. const iw = -qx * x - qy * y - qz * z; // calculate result * inverse quat
  2674. this.x = ix * qw + iw * -qx + iy * -qz - iz * -qy;
  2675. this.y = iy * qw + iw * -qy + iz * -qx - ix * -qz;
  2676. this.z = iz * qw + iw * -qz + ix * -qy - iy * -qx;
  2677. return this;
  2678. }
  2679. project(camera) {
  2680. return this.applyMatrix4(camera.matrixWorldInverse).applyMatrix4(camera.projectionMatrix);
  2681. }
  2682. unproject(camera) {
  2683. return this.applyMatrix4(camera.projectionMatrixInverse).applyMatrix4(camera.matrixWorld);
  2684. }
  2685. transformDirection(m) {
  2686. // input: THREE.Matrix4 affine matrix
  2687. // vector interpreted as a direction
  2688. const x = this.x,
  2689. y = this.y,
  2690. z = this.z;
  2691. const e = m.elements;
  2692. this.x = e[0] * x + e[4] * y + e[8] * z;
  2693. this.y = e[1] * x + e[5] * y + e[9] * z;
  2694. this.z = e[2] * x + e[6] * y + e[10] * z;
  2695. return this.normalize();
  2696. }
  2697. divide(v) {
  2698. this.x /= v.x;
  2699. this.y /= v.y;
  2700. this.z /= v.z;
  2701. return this;
  2702. }
  2703. divideScalar(scalar) {
  2704. return this.multiplyScalar(1 / scalar);
  2705. }
  2706. min(v) {
  2707. this.x = Math.min(this.x, v.x);
  2708. this.y = Math.min(this.y, v.y);
  2709. this.z = Math.min(this.z, v.z);
  2710. return this;
  2711. }
  2712. max(v) {
  2713. this.x = Math.max(this.x, v.x);
  2714. this.y = Math.max(this.y, v.y);
  2715. this.z = Math.max(this.z, v.z);
  2716. return this;
  2717. }
  2718. clamp(min, max) {
  2719. // assumes min < max, componentwise
  2720. this.x = Math.max(min.x, Math.min(max.x, this.x));
  2721. this.y = Math.max(min.y, Math.min(max.y, this.y));
  2722. this.z = Math.max(min.z, Math.min(max.z, this.z));
  2723. return this;
  2724. }
  2725. clampScalar(minVal, maxVal) {
  2726. this.x = Math.max(minVal, Math.min(maxVal, this.x));
  2727. this.y = Math.max(minVal, Math.min(maxVal, this.y));
  2728. this.z = Math.max(minVal, Math.min(maxVal, this.z));
  2729. return this;
  2730. }
  2731. clampLength(min, max) {
  2732. const length = this.length();
  2733. return this.divideScalar(length || 1).multiplyScalar(Math.max(min, Math.min(max, length)));
  2734. }
  2735. floor() {
  2736. this.x = Math.floor(this.x);
  2737. this.y = Math.floor(this.y);
  2738. this.z = Math.floor(this.z);
  2739. return this;
  2740. }
  2741. ceil() {
  2742. this.x = Math.ceil(this.x);
  2743. this.y = Math.ceil(this.y);
  2744. this.z = Math.ceil(this.z);
  2745. return this;
  2746. }
  2747. round() {
  2748. this.x = Math.round(this.x);
  2749. this.y = Math.round(this.y);
  2750. this.z = Math.round(this.z);
  2751. return this;
  2752. }
  2753. roundToZero() {
  2754. this.x = this.x < 0 ? Math.ceil(this.x) : Math.floor(this.x);
  2755. this.y = this.y < 0 ? Math.ceil(this.y) : Math.floor(this.y);
  2756. this.z = this.z < 0 ? Math.ceil(this.z) : Math.floor(this.z);
  2757. return this;
  2758. }
  2759. negate() {
  2760. this.x = -this.x;
  2761. this.y = -this.y;
  2762. this.z = -this.z;
  2763. return this;
  2764. }
  2765. dot(v) {
  2766. return this.x * v.x + this.y * v.y + this.z * v.z;
  2767. } // TODO lengthSquared?
  2768. lengthSq() {
  2769. return this.x * this.x + this.y * this.y + this.z * this.z;
  2770. }
  2771. length() {
  2772. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  2773. }
  2774. manhattanLength() {
  2775. return Math.abs(this.x) + Math.abs(this.y) + Math.abs(this.z);
  2776. }
  2777. normalize() {
  2778. return this.divideScalar(this.length() || 1);
  2779. }
  2780. setLength(length) {
  2781. return this.normalize().multiplyScalar(length);
  2782. }
  2783. lerp(v, alpha) {
  2784. this.x += (v.x - this.x) * alpha;
  2785. this.y += (v.y - this.y) * alpha;
  2786. this.z += (v.z - this.z) * alpha;
  2787. return this;
  2788. }
  2789. lerpVectors(v1, v2, alpha) {
  2790. this.x = v1.x + (v2.x - v1.x) * alpha;
  2791. this.y = v1.y + (v2.y - v1.y) * alpha;
  2792. this.z = v1.z + (v2.z - v1.z) * alpha;
  2793. return this;
  2794. }
  2795. cross(v, w) {
  2796. if (w !== undefined) {
  2797. console.warn('THREE.Vector3: .cross() now only accepts one argument. Use .crossVectors( a, b ) instead.');
  2798. return this.crossVectors(v, w);
  2799. }
  2800. return this.crossVectors(this, v);
  2801. }
  2802. crossVectors(a, b) {
  2803. const ax = a.x,
  2804. ay = a.y,
  2805. az = a.z;
  2806. const bx = b.x,
  2807. by = b.y,
  2808. bz = b.z;
  2809. this.x = ay * bz - az * by;
  2810. this.y = az * bx - ax * bz;
  2811. this.z = ax * by - ay * bx;
  2812. return this;
  2813. }
  2814. projectOnVector(v) {
  2815. const denominator = v.lengthSq();
  2816. if (denominator === 0) return this.set(0, 0, 0);
  2817. const scalar = v.dot(this) / denominator;
  2818. return this.copy(v).multiplyScalar(scalar);
  2819. }
  2820. projectOnPlane(planeNormal) {
  2821. _vector.copy(this).projectOnVector(planeNormal);
  2822. return this.sub(_vector);
  2823. }
  2824. reflect(normal) {
  2825. // reflect incident vector off plane orthogonal to normal
  2826. // normal is assumed to have unit length
  2827. return this.sub(_vector.copy(normal).multiplyScalar(2 * this.dot(normal)));
  2828. }
  2829. angleTo(v) {
  2830. const denominator = Math.sqrt(this.lengthSq() * v.lengthSq());
  2831. if (denominator === 0) return Math.PI / 2;
  2832. const theta = this.dot(v) / denominator; // clamp, to handle numerical problems
  2833. return Math.acos(MathUtils.clamp(theta, -1, 1));
  2834. }
  2835. distanceTo(v) {
  2836. return Math.sqrt(this.distanceToSquared(v));
  2837. }
  2838. distanceToSquared(v) {
  2839. const dx = this.x - v.x,
  2840. dy = this.y - v.y,
  2841. dz = this.z - v.z;
  2842. return dx * dx + dy * dy + dz * dz;
  2843. }
  2844. manhattanDistanceTo(v) {
  2845. return Math.abs(this.x - v.x) + Math.abs(this.y - v.y) + Math.abs(this.z - v.z);
  2846. }
  2847. setFromSpherical(s) {
  2848. return this.setFromSphericalCoords(s.radius, s.phi, s.theta);
  2849. }
  2850. setFromSphericalCoords(radius, phi, theta) {
  2851. const sinPhiRadius = Math.sin(phi) * radius;
  2852. this.x = sinPhiRadius * Math.sin(theta);
  2853. this.y = Math.cos(phi) * radius;
  2854. this.z = sinPhiRadius * Math.cos(theta);
  2855. return this;
  2856. }
  2857. setFromCylindrical(c) {
  2858. return this.setFromCylindricalCoords(c.radius, c.theta, c.y);
  2859. }
  2860. setFromCylindricalCoords(radius, theta, y) {
  2861. this.x = radius * Math.sin(theta);
  2862. this.y = y;
  2863. this.z = radius * Math.cos(theta);
  2864. return this;
  2865. }
  2866. setFromMatrixPosition(m) {
  2867. const e = m.elements;
  2868. this.x = e[12];
  2869. this.y = e[13];
  2870. this.z = e[14];
  2871. return this;
  2872. }
  2873. setFromMatrixScale(m) {
  2874. const sx = this.setFromMatrixColumn(m, 0).length();
  2875. const sy = this.setFromMatrixColumn(m, 1).length();
  2876. const sz = this.setFromMatrixColumn(m, 2).length();
  2877. this.x = sx;
  2878. this.y = sy;
  2879. this.z = sz;
  2880. return this;
  2881. }
  2882. setFromMatrixColumn(m, index) {
  2883. return this.fromArray(m.elements, index * 4);
  2884. }
  2885. setFromMatrix3Column(m, index) {
  2886. return this.fromArray(m.elements, index * 3);
  2887. }
  2888. equals(v) {
  2889. return v.x === this.x && v.y === this.y && v.z === this.z;
  2890. }
  2891. fromArray(array, offset = 0) {
  2892. this.x = array[offset];
  2893. this.y = array[offset + 1];
  2894. this.z = array[offset + 2];
  2895. return this;
  2896. }
  2897. toArray(array = [], offset = 0) {
  2898. array[offset] = this.x;
  2899. array[offset + 1] = this.y;
  2900. array[offset + 2] = this.z;
  2901. return array;
  2902. }
  2903. fromBufferAttribute(attribute, index, offset) {
  2904. if (offset !== undefined) {
  2905. console.warn('THREE.Vector3: offset has been removed from .fromBufferAttribute().');
  2906. }
  2907. this.x = attribute.getX(index);
  2908. this.y = attribute.getY(index);
  2909. this.z = attribute.getZ(index);
  2910. return this;
  2911. }
  2912. random() {
  2913. this.x = Math.random();
  2914. this.y = Math.random();
  2915. this.z = Math.random();
  2916. return this;
  2917. }
  2918. }
  2919. exports.Vector3 = Vector3;
  2920. const _vector =
  2921. /*@__PURE__*/
  2922. new Vector3();
  2923. const _quaternion =
  2924. /*@__PURE__*/
  2925. new Quaternion();
  2926. class Box3 {
  2927. constructor(min, max) {
  2928. Object.defineProperty(this, 'isBox3', {
  2929. value: true
  2930. });
  2931. this.min = min !== undefined ? min : new Vector3(+Infinity, +Infinity, +Infinity);
  2932. this.max = max !== undefined ? max : new Vector3(-Infinity, -Infinity, -Infinity);
  2933. }
  2934. set(min, max) {
  2935. this.min.copy(min);
  2936. this.max.copy(max);
  2937. return this;
  2938. }
  2939. setFromArray(array) {
  2940. let minX = +Infinity;
  2941. let minY = +Infinity;
  2942. let minZ = +Infinity;
  2943. let maxX = -Infinity;
  2944. let maxY = -Infinity;
  2945. let maxZ = -Infinity;
  2946. for (let i = 0, l = array.length; i < l; i += 3) {
  2947. const x = array[i];
  2948. const y = array[i + 1];
  2949. const z = array[i + 2];
  2950. if (x < minX) minX = x;
  2951. if (y < minY) minY = y;
  2952. if (z < minZ) minZ = z;
  2953. if (x > maxX) maxX = x;
  2954. if (y > maxY) maxY = y;
  2955. if (z > maxZ) maxZ = z;
  2956. }
  2957. this.min.set(minX, minY, minZ);
  2958. this.max.set(maxX, maxY, maxZ);
  2959. return this;
  2960. }
  2961. setFromBufferAttribute(attribute) {
  2962. let minX = +Infinity;
  2963. let minY = +Infinity;
  2964. let minZ = +Infinity;
  2965. let maxX = -Infinity;
  2966. let maxY = -Infinity;
  2967. let maxZ = -Infinity;
  2968. for (let i = 0, l = attribute.count; i < l; i++) {
  2969. const x = attribute.getX(i);
  2970. const y = attribute.getY(i);
  2971. const z = attribute.getZ(i);
  2972. if (x < minX) minX = x;
  2973. if (y < minY) minY = y;
  2974. if (z < minZ) minZ = z;
  2975. if (x > maxX) maxX = x;
  2976. if (y > maxY) maxY = y;
  2977. if (z > maxZ) maxZ = z;
  2978. }
  2979. this.min.set(minX, minY, minZ);
  2980. this.max.set(maxX, maxY, maxZ);
  2981. return this;
  2982. }
  2983. setFromPoints(points) {
  2984. this.makeEmpty();
  2985. for (let i = 0, il = points.length; i < il; i++) {
  2986. this.expandByPoint(points[i]);
  2987. }
  2988. return this;
  2989. }
  2990. setFromCenterAndSize(center, size) {
  2991. const halfSize = _vector$1.copy(size).multiplyScalar(0.5);
  2992. this.min.copy(center).sub(halfSize);
  2993. this.max.copy(center).add(halfSize);
  2994. return this;
  2995. }
  2996. setFromObject(object) {
  2997. this.makeEmpty();
  2998. return this.expandByObject(object);
  2999. }
  3000. clone() {
  3001. return new this.constructor().copy(this);
  3002. }
  3003. copy(box) {
  3004. this.min.copy(box.min);
  3005. this.max.copy(box.max);
  3006. return this;
  3007. }
  3008. makeEmpty() {
  3009. this.min.x = this.min.y = this.min.z = +Infinity;
  3010. this.max.x = this.max.y = this.max.z = -Infinity;
  3011. return this;
  3012. }
  3013. isEmpty() {
  3014. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  3015. return this.max.x < this.min.x || this.max.y < this.min.y || this.max.z < this.min.z;
  3016. }
  3017. getCenter(target) {
  3018. if (target === undefined) {
  3019. console.warn('THREE.Box3: .getCenter() target is now required');
  3020. target = new Vector3();
  3021. }
  3022. return this.isEmpty() ? target.set(0, 0, 0) : target.addVectors(this.min, this.max).multiplyScalar(0.5);
  3023. }
  3024. getSize(target) {
  3025. if (target === undefined) {
  3026. console.warn('THREE.Box3: .getSize() target is now required');
  3027. target = new Vector3();
  3028. }
  3029. return this.isEmpty() ? target.set(0, 0, 0) : target.subVectors(this.max, this.min);
  3030. }
  3031. expandByPoint(point) {
  3032. this.min.min(point);
  3033. this.max.max(point);
  3034. return this;
  3035. }
  3036. expandByVector(vector) {
  3037. this.min.sub(vector);
  3038. this.max.add(vector);
  3039. return this;
  3040. }
  3041. expandByScalar(scalar) {
  3042. this.min.addScalar(-scalar);
  3043. this.max.addScalar(scalar);
  3044. return this;
  3045. }
  3046. expandByObject(object) {
  3047. // Computes the world-axis-aligned bounding box of an object (including its children),
  3048. // accounting for both the object's, and children's, world transforms
  3049. object.updateWorldMatrix(false, false);
  3050. const geometry = object.geometry;
  3051. if (geometry !== undefined) {
  3052. if (geometry.boundingBox === null) {
  3053. geometry.computeBoundingBox();
  3054. }
  3055. _box.copy(geometry.boundingBox);
  3056. _box.applyMatrix4(object.matrixWorld);
  3057. this.union(_box);
  3058. }
  3059. const children = object.children;
  3060. for (let i = 0, l = children.length; i < l; i++) {
  3061. this.expandByObject(children[i]);
  3062. }
  3063. return this;
  3064. }
  3065. containsPoint(point) {
  3066. return point.x < this.min.x || point.x > this.max.x || point.y < this.min.y || point.y > this.max.y || point.z < this.min.z || point.z > this.max.z ? false : true;
  3067. }
  3068. containsBox(box) {
  3069. return this.min.x <= box.min.x && box.max.x <= this.max.x && this.min.y <= box.min.y && box.max.y <= this.max.y && this.min.z <= box.min.z && box.max.z <= this.max.z;
  3070. }
  3071. getParameter(point, target) {
  3072. // This can potentially have a divide by zero if the box
  3073. // has a size dimension of 0.
  3074. if (target === undefined) {
  3075. console.warn('THREE.Box3: .getParameter() target is now required');
  3076. target = new Vector3();
  3077. }
  3078. return target.set((point.x - this.min.x) / (this.max.x - this.min.x), (point.y - this.min.y) / (this.max.y - this.min.y), (point.z - this.min.z) / (this.max.z - this.min.z));
  3079. }
  3080. intersectsBox(box) {
  3081. // using 6 splitting planes to rule out intersections.
  3082. return box.max.x < this.min.x || box.min.x > this.max.x || box.max.y < this.min.y || box.min.y > this.max.y || box.max.z < this.min.z || box.min.z > this.max.z ? false : true;
  3083. }
  3084. intersectsSphere(sphere) {
  3085. // Find the point on the AABB closest to the sphere center.
  3086. this.clampPoint(sphere.center, _vector$1); // If that point is inside the sphere, the AABB and sphere intersect.
  3087. return _vector$1.distanceToSquared(sphere.center) <= sphere.radius * sphere.radius;
  3088. }
  3089. intersectsPlane(plane) {
  3090. // We compute the minimum and maximum dot product values. If those values
  3091. // are on the same side (back or front) of the plane, then there is no intersection.
  3092. let min, max;
  3093. if (plane.normal.x > 0) {
  3094. min = plane.normal.x * this.min.x;
  3095. max = plane.normal.x * this.max.x;
  3096. } else {
  3097. min = plane.normal.x * this.max.x;
  3098. max = plane.normal.x * this.min.x;
  3099. }
  3100. if (plane.normal.y > 0) {
  3101. min += plane.normal.y * this.min.y;
  3102. max += plane.normal.y * this.max.y;
  3103. } else {
  3104. min += plane.normal.y * this.max.y;
  3105. max += plane.normal.y * this.min.y;
  3106. }
  3107. if (plane.normal.z > 0) {
  3108. min += plane.normal.z * this.min.z;
  3109. max += plane.normal.z * this.max.z;
  3110. } else {
  3111. min += plane.normal.z * this.max.z;
  3112. max += plane.normal.z * this.min.z;
  3113. }
  3114. return min <= -plane.constant && max >= -plane.constant;
  3115. }
  3116. intersectsTriangle(triangle) {
  3117. if (this.isEmpty()) {
  3118. return false;
  3119. } // compute box center and extents
  3120. this.getCenter(_center);
  3121. _extents.subVectors(this.max, _center); // translate triangle to aabb origin
  3122. _v0.subVectors(triangle.a, _center);
  3123. _v1.subVectors(triangle.b, _center);
  3124. _v2.subVectors(triangle.c, _center); // compute edge vectors for triangle
  3125. _f0.subVectors(_v1, _v0);
  3126. _f1.subVectors(_v2, _v1);
  3127. _f2.subVectors(_v0, _v2); // test against axes that are given by cross product combinations of the edges of the triangle and the edges of the aabb
  3128. // make an axis testing of each of the 3 sides of the aabb against each of the 3 sides of the triangle = 9 axis of separation
  3129. // axis_ij = u_i x f_j (u0, u1, u2 = face normals of aabb = x,y,z axes vectors since aabb is axis aligned)
  3130. let axes = [0, -_f0.z, _f0.y, 0, -_f1.z, _f1.y, 0, -_f2.z, _f2.y, _f0.z, 0, -_f0.x, _f1.z, 0, -_f1.x, _f2.z, 0, -_f2.x, -_f0.y, _f0.x, 0, -_f1.y, _f1.x, 0, -_f2.y, _f2.x, 0];
  3131. if (!satForAxes(axes, _v0, _v1, _v2, _extents)) {
  3132. return false;
  3133. } // test 3 face normals from the aabb
  3134. axes = [1, 0, 0, 0, 1, 0, 0, 0, 1];
  3135. if (!satForAxes(axes, _v0, _v1, _v2, _extents)) {
  3136. return false;
  3137. } // finally testing the face normal of the triangle
  3138. // use already existing triangle edge vectors here
  3139. _triangleNormal.crossVectors(_f0, _f1);
  3140. axes = [_triangleNormal.x, _triangleNormal.y, _triangleNormal.z];
  3141. return satForAxes(axes, _v0, _v1, _v2, _extents);
  3142. }
  3143. clampPoint(point, target) {
  3144. if (target === undefined) {
  3145. console.warn('THREE.Box3: .clampPoint() target is now required');
  3146. target = new Vector3();
  3147. }
  3148. return target.copy(point).clamp(this.min, this.max);
  3149. }
  3150. distanceToPoint(point) {
  3151. const clampedPoint = _vector$1.copy(point).clamp(this.min, this.max);
  3152. return clampedPoint.sub(point).length();
  3153. }
  3154. getBoundingSphere(target) {
  3155. if (target === undefined) {
  3156. console.error('THREE.Box3: .getBoundingSphere() target is now required'); //target = new Sphere(); // removed to avoid cyclic dependency
  3157. }
  3158. this.getCenter(target.center);
  3159. target.radius = this.getSize(_vector$1).length() * 0.5;
  3160. return target;
  3161. }
  3162. intersect(box) {
  3163. this.min.max(box.min);
  3164. this.max.min(box.max); // ensure that if there is no overlap, the result is fully empty, not slightly empty with non-inf/+inf values that will cause subsequence intersects to erroneously return valid values.
  3165. if (this.isEmpty()) this.makeEmpty();
  3166. return this;
  3167. }
  3168. union(box) {
  3169. this.min.min(box.min);
  3170. this.max.max(box.max);
  3171. return this;
  3172. }
  3173. applyMatrix4(matrix) {
  3174. // transform of empty box is an empty box.
  3175. if (this.isEmpty()) return this; // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  3176. _points[0].set(this.min.x, this.min.y, this.min.z).applyMatrix4(matrix); // 000
  3177. _points[1].set(this.min.x, this.min.y, this.max.z).applyMatrix4(matrix); // 001
  3178. _points[2].set(this.min.x, this.max.y, this.min.z).applyMatrix4(matrix); // 010
  3179. _points[3].set(this.min.x, this.max.y, this.max.z).applyMatrix4(matrix); // 011
  3180. _points[4].set(this.max.x, this.min.y, this.min.z).applyMatrix4(matrix); // 100
  3181. _points[5].set(this.max.x, this.min.y, this.max.z).applyMatrix4(matrix); // 101
  3182. _points[6].set(this.max.x, this.max.y, this.min.z).applyMatrix4(matrix); // 110
  3183. _points[7].set(this.max.x, this.max.y, this.max.z).applyMatrix4(matrix); // 111
  3184. this.setFromPoints(_points);
  3185. return this;
  3186. }
  3187. translate(offset) {
  3188. this.min.add(offset);
  3189. this.max.add(offset);
  3190. return this;
  3191. }
  3192. equals(box) {
  3193. return box.min.equals(this.min) && box.max.equals(this.max);
  3194. }
  3195. }
  3196. exports.Box3 = Box3;
  3197. function satForAxes(axes, v0, v1, v2, extents) {
  3198. for (let i = 0, j = axes.length - 3; i <= j; i += 3) {
  3199. _testAxis.fromArray(axes, i); // project the aabb onto the seperating axis
  3200. const r = extents.x * Math.abs(_testAxis.x) + extents.y * Math.abs(_testAxis.y) + extents.z * Math.abs(_testAxis.z); // project all 3 vertices of the triangle onto the seperating axis
  3201. const p0 = v0.dot(_testAxis);
  3202. const p1 = v1.dot(_testAxis);
  3203. const p2 = v2.dot(_testAxis); // actual test, basically see if either of the most extreme of the triangle points intersects r
  3204. if (Math.max(-Math.max(p0, p1, p2), Math.min(p0, p1, p2)) > r) {
  3205. // points of the projected triangle are outside the projected half-length of the aabb
  3206. // the axis is seperating and we can exit
  3207. return false;
  3208. }
  3209. }
  3210. return true;
  3211. }
  3212. const _points = [
  3213. /*@__PURE__*/
  3214. new Vector3(),
  3215. /*@__PURE__*/
  3216. new Vector3(),
  3217. /*@__PURE__*/
  3218. new Vector3(),
  3219. /*@__PURE__*/
  3220. new Vector3(),
  3221. /*@__PURE__*/
  3222. new Vector3(),
  3223. /*@__PURE__*/
  3224. new Vector3(),
  3225. /*@__PURE__*/
  3226. new Vector3(),
  3227. /*@__PURE__*/
  3228. new Vector3()];
  3229. const _vector$1 =
  3230. /*@__PURE__*/
  3231. new Vector3();
  3232. const _box =
  3233. /*@__PURE__*/
  3234. new Box3(); // triangle centered vertices
  3235. const _v0 =
  3236. /*@__PURE__*/
  3237. new Vector3();
  3238. const _v1 =
  3239. /*@__PURE__*/
  3240. new Vector3();
  3241. const _v2 =
  3242. /*@__PURE__*/
  3243. new Vector3(); // triangle edge vectors
  3244. const _f0 =
  3245. /*@__PURE__*/
  3246. new Vector3();
  3247. const _f1 =
  3248. /*@__PURE__*/
  3249. new Vector3();
  3250. const _f2 =
  3251. /*@__PURE__*/
  3252. new Vector3();
  3253. const _center =
  3254. /*@__PURE__*/
  3255. new Vector3();
  3256. const _extents =
  3257. /*@__PURE__*/
  3258. new Vector3();
  3259. const _triangleNormal =
  3260. /*@__PURE__*/
  3261. new Vector3();
  3262. const _testAxis =
  3263. /*@__PURE__*/
  3264. new Vector3();
  3265. const _box$1 =
  3266. /*@__PURE__*/
  3267. new Box3();
  3268. class Sphere {
  3269. constructor(center, radius) {
  3270. this.center = center !== undefined ? center : new Vector3();
  3271. this.radius = radius !== undefined ? radius : -1;
  3272. }
  3273. set(center, radius) {
  3274. this.center.copy(center);
  3275. this.radius = radius;
  3276. return this;
  3277. }
  3278. setFromPoints(points, optionalCenter) {
  3279. const center = this.center;
  3280. if (optionalCenter !== undefined) {
  3281. center.copy(optionalCenter);
  3282. } else {
  3283. _box$1.setFromPoints(points).getCenter(center);
  3284. }
  3285. let maxRadiusSq = 0;
  3286. for (let i = 0, il = points.length; i < il; i++) {
  3287. maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(points[i]));
  3288. }
  3289. this.radius = Math.sqrt(maxRadiusSq);
  3290. return this;
  3291. }
  3292. clone() {
  3293. return new this.constructor().copy(this);
  3294. }
  3295. copy(sphere) {
  3296. this.center.copy(sphere.center);
  3297. this.radius = sphere.radius;
  3298. return this;
  3299. }
  3300. isEmpty() {
  3301. return this.radius < 0;
  3302. }
  3303. makeEmpty() {
  3304. this.center.set(0, 0, 0);
  3305. this.radius = -1;
  3306. return this;
  3307. }
  3308. containsPoint(point) {
  3309. return point.distanceToSquared(this.center) <= this.radius * this.radius;
  3310. }
  3311. distanceToPoint(point) {
  3312. return point.distanceTo(this.center) - this.radius;
  3313. }
  3314. intersectsSphere(sphere) {
  3315. const radiusSum = this.radius + sphere.radius;
  3316. return sphere.center.distanceToSquared(this.center) <= radiusSum * radiusSum;
  3317. }
  3318. intersectsBox(box) {
  3319. return box.intersectsSphere(this);
  3320. }
  3321. intersectsPlane(plane) {
  3322. return Math.abs(plane.distanceToPoint(this.center)) <= this.radius;
  3323. }
  3324. clampPoint(point, target) {
  3325. const deltaLengthSq = this.center.distanceToSquared(point);
  3326. if (target === undefined) {
  3327. console.warn('THREE.Sphere: .clampPoint() target is now required');
  3328. target = new Vector3();
  3329. }
  3330. target.copy(point);
  3331. if (deltaLengthSq > this.radius * this.radius) {
  3332. target.sub(this.center).normalize();
  3333. target.multiplyScalar(this.radius).add(this.center);
  3334. }
  3335. return target;
  3336. }
  3337. getBoundingBox(target) {
  3338. if (target === undefined) {
  3339. console.warn('THREE.Sphere: .getBoundingBox() target is now required');
  3340. target = new Box3();
  3341. }
  3342. if (this.isEmpty()) {
  3343. // Empty sphere produces empty bounding box
  3344. target.makeEmpty();
  3345. return target;
  3346. }
  3347. target.set(this.center, this.center);
  3348. target.expandByScalar(this.radius);
  3349. return target;
  3350. }
  3351. applyMatrix4(matrix) {
  3352. this.center.applyMatrix4(matrix);
  3353. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  3354. return this;
  3355. }
  3356. translate(offset) {
  3357. this.center.add(offset);
  3358. return this;
  3359. }
  3360. equals(sphere) {
  3361. return sphere.center.equals(this.center) && sphere.radius === this.radius;
  3362. }
  3363. }
  3364. exports.Sphere = Sphere;
  3365. const _vector$2 =
  3366. /*@__PURE__*/
  3367. new Vector3();
  3368. const _segCenter =
  3369. /*@__PURE__*/
  3370. new Vector3();
  3371. const _segDir =
  3372. /*@__PURE__*/
  3373. new Vector3();
  3374. const _diff =
  3375. /*@__PURE__*/
  3376. new Vector3();
  3377. const _edge1 =
  3378. /*@__PURE__*/
  3379. new Vector3();
  3380. const _edge2 =
  3381. /*@__PURE__*/
  3382. new Vector3();
  3383. const _normal =
  3384. /*@__PURE__*/
  3385. new Vector3();
  3386. class Ray {
  3387. constructor(origin, direction) {
  3388. this.origin = origin !== undefined ? origin : new Vector3();
  3389. this.direction = direction !== undefined ? direction : new Vector3(0, 0, -1);
  3390. }
  3391. set(origin, direction) {
  3392. this.origin.copy(origin);
  3393. this.direction.copy(direction);
  3394. return this;
  3395. }
  3396. clone() {
  3397. return new this.constructor().copy(this);
  3398. }
  3399. copy(ray) {
  3400. this.origin.copy(ray.origin);
  3401. this.direction.copy(ray.direction);
  3402. return this;
  3403. }
  3404. at(t, target) {
  3405. if (target === undefined) {
  3406. console.warn('THREE.Ray: .at() target is now required');
  3407. target = new Vector3();
  3408. }
  3409. return target.copy(this.direction).multiplyScalar(t).add(this.origin);
  3410. }
  3411. lookAt(v) {
  3412. this.direction.copy(v).sub(this.origin).normalize();
  3413. return this;
  3414. }
  3415. recast(t) {
  3416. this.origin.copy(this.at(t, _vector$2));
  3417. return this;
  3418. }
  3419. closestPointToPoint(point, target) {
  3420. if (target === undefined) {
  3421. console.warn('THREE.Ray: .closestPointToPoint() target is now required');
  3422. target = new Vector3();
  3423. }
  3424. target.subVectors(point, this.origin);
  3425. const directionDistance = target.dot(this.direction);
  3426. if (directionDistance < 0) {
  3427. return target.copy(this.origin);
  3428. }
  3429. return target.copy(this.direction).multiplyScalar(directionDistance).add(this.origin);
  3430. }
  3431. distanceToPoint(point) {
  3432. return Math.sqrt(this.distanceSqToPoint(point));
  3433. }
  3434. distanceSqToPoint(point) {
  3435. const directionDistance = _vector$2.subVectors(point, this.origin).dot(this.direction); // point behind the ray
  3436. if (directionDistance < 0) {
  3437. return this.origin.distanceToSquared(point);
  3438. }
  3439. _vector$2.copy(this.direction).multiplyScalar(directionDistance).add(this.origin);
  3440. return _vector$2.distanceToSquared(point);
  3441. }
  3442. distanceSqToSegment(v0, v1, optionalPointOnRay, optionalPointOnSegment) {
  3443. // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteDistRaySegment.h
  3444. // It returns the min distance between the ray and the segment
  3445. // defined by v0 and v1
  3446. // It can also set two optional targets :
  3447. // - The closest point on the ray
  3448. // - The closest point on the segment
  3449. _segCenter.copy(v0).add(v1).multiplyScalar(0.5);
  3450. _segDir.copy(v1).sub(v0).normalize();
  3451. _diff.copy(this.origin).sub(_segCenter);
  3452. const segExtent = v0.distanceTo(v1) * 0.5;
  3453. const a01 = -this.direction.dot(_segDir);
  3454. const b0 = _diff.dot(this.direction);
  3455. const b1 = -_diff.dot(_segDir);
  3456. const c = _diff.lengthSq();
  3457. const det = Math.abs(1 - a01 * a01);
  3458. let s0, s1, sqrDist, extDet;
  3459. if (det > 0) {
  3460. // The ray and segment are not parallel.
  3461. s0 = a01 * b1 - b0;
  3462. s1 = a01 * b0 - b1;
  3463. extDet = segExtent * det;
  3464. if (s0 >= 0) {
  3465. if (s1 >= -extDet) {
  3466. if (s1 <= extDet) {
  3467. // region 0
  3468. // Minimum at interior points of ray and segment.
  3469. const invDet = 1 / det;
  3470. s0 *= invDet;
  3471. s1 *= invDet;
  3472. sqrDist = s0 * (s0 + a01 * s1 + 2 * b0) + s1 * (a01 * s0 + s1 + 2 * b1) + c;
  3473. } else {
  3474. // region 1
  3475. s1 = segExtent;
  3476. s0 = Math.max(0, -(a01 * s1 + b0));
  3477. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  3478. }
  3479. } else {
  3480. // region 5
  3481. s1 = -segExtent;
  3482. s0 = Math.max(0, -(a01 * s1 + b0));
  3483. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  3484. }
  3485. } else {
  3486. if (s1 <= -extDet) {
  3487. // region 4
  3488. s0 = Math.max(0, -(-a01 * segExtent + b0));
  3489. s1 = s0 > 0 ? -segExtent : Math.min(Math.max(-segExtent, -b1), segExtent);
  3490. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  3491. } else if (s1 <= extDet) {
  3492. // region 3
  3493. s0 = 0;
  3494. s1 = Math.min(Math.max(-segExtent, -b1), segExtent);
  3495. sqrDist = s1 * (s1 + 2 * b1) + c;
  3496. } else {
  3497. // region 2
  3498. s0 = Math.max(0, -(a01 * segExtent + b0));
  3499. s1 = s0 > 0 ? segExtent : Math.min(Math.max(-segExtent, -b1), segExtent);
  3500. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  3501. }
  3502. }
  3503. } else {
  3504. // Ray and segment are parallel.
  3505. s1 = a01 > 0 ? -segExtent : segExtent;
  3506. s0 = Math.max(0, -(a01 * s1 + b0));
  3507. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  3508. }
  3509. if (optionalPointOnRay) {
  3510. optionalPointOnRay.copy(this.direction).multiplyScalar(s0).add(this.origin);
  3511. }
  3512. if (optionalPointOnSegment) {
  3513. optionalPointOnSegment.copy(_segDir).multiplyScalar(s1).add(_segCenter);
  3514. }
  3515. return sqrDist;
  3516. }
  3517. intersectSphere(sphere, target) {
  3518. _vector$2.subVectors(sphere.center, this.origin);
  3519. const tca = _vector$2.dot(this.direction);
  3520. const d2 = _vector$2.dot(_vector$2) - tca * tca;
  3521. const radius2 = sphere.radius * sphere.radius;
  3522. if (d2 > radius2) return null;
  3523. const thc = Math.sqrt(radius2 - d2); // t0 = first intersect point - entrance on front of sphere
  3524. const t0 = tca - thc; // t1 = second intersect point - exit point on back of sphere
  3525. const t1 = tca + thc; // test to see if both t0 and t1 are behind the ray - if so, return null
  3526. if (t0 < 0 && t1 < 0) return null; // test to see if t0 is behind the ray:
  3527. // if it is, the ray is inside the sphere, so return the second exit point scaled by t1,
  3528. // in order to always return an intersect point that is in front of the ray.
  3529. if (t0 < 0) return this.at(t1, target); // else t0 is in front of the ray, so return the first collision point scaled by t0
  3530. return this.at(t0, target);
  3531. }
  3532. intersectsSphere(sphere) {
  3533. return this.distanceSqToPoint(sphere.center) <= sphere.radius * sphere.radius;
  3534. }
  3535. distanceToPlane(plane) {
  3536. const denominator = plane.normal.dot(this.direction);
  3537. if (denominator === 0) {
  3538. // line is coplanar, return origin
  3539. if (plane.distanceToPoint(this.origin) === 0) {
  3540. return 0;
  3541. } // Null is preferable to undefined since undefined means.... it is undefined
  3542. return null;
  3543. }
  3544. const t = -(this.origin.dot(plane.normal) + plane.constant) / denominator; // Return if the ray never intersects the plane
  3545. return t >= 0 ? t : null;
  3546. }
  3547. intersectPlane(plane, target) {
  3548. const t = this.distanceToPlane(plane);
  3549. if (t === null) {
  3550. return null;
  3551. }
  3552. return this.at(t, target);
  3553. }
  3554. intersectsPlane(plane) {
  3555. // check if the ray lies on the plane first
  3556. const distToPoint = plane.distanceToPoint(this.origin);
  3557. if (distToPoint === 0) {
  3558. return true;
  3559. }
  3560. const denominator = plane.normal.dot(this.direction);
  3561. if (denominator * distToPoint < 0) {
  3562. return true;
  3563. } // ray origin is behind the plane (and is pointing behind it)
  3564. return false;
  3565. }
  3566. intersectBox(box, target) {
  3567. let tmin, tmax, tymin, tymax, tzmin, tzmax;
  3568. const invdirx = 1 / this.direction.x,
  3569. invdiry = 1 / this.direction.y,
  3570. invdirz = 1 / this.direction.z;
  3571. const origin = this.origin;
  3572. if (invdirx >= 0) {
  3573. tmin = (box.min.x - origin.x) * invdirx;
  3574. tmax = (box.max.x - origin.x) * invdirx;
  3575. } else {
  3576. tmin = (box.max.x - origin.x) * invdirx;
  3577. tmax = (box.min.x - origin.x) * invdirx;
  3578. }
  3579. if (invdiry >= 0) {
  3580. tymin = (box.min.y - origin.y) * invdiry;
  3581. tymax = (box.max.y - origin.y) * invdiry;
  3582. } else {
  3583. tymin = (box.max.y - origin.y) * invdiry;
  3584. tymax = (box.min.y - origin.y) * invdiry;
  3585. }
  3586. if (tmin > tymax || tymin > tmax) return null; // These lines also handle the case where tmin or tmax is NaN
  3587. // (result of 0 * Infinity). x !== x returns true if x is NaN
  3588. if (tymin > tmin || tmin !== tmin) tmin = tymin;
  3589. if (tymax < tmax || tmax !== tmax) tmax = tymax;
  3590. if (invdirz >= 0) {
  3591. tzmin = (box.min.z - origin.z) * invdirz;
  3592. tzmax = (box.max.z - origin.z) * invdirz;
  3593. } else {
  3594. tzmin = (box.max.z - origin.z) * invdirz;
  3595. tzmax = (box.min.z - origin.z) * invdirz;
  3596. }
  3597. if (tmin > tzmax || tzmin > tmax) return null;
  3598. if (tzmin > tmin || tmin !== tmin) tmin = tzmin;
  3599. if (tzmax < tmax || tmax !== tmax) tmax = tzmax; //return point closest to the ray (positive side)
  3600. if (tmax < 0) return null;
  3601. return this.at(tmin >= 0 ? tmin : tmax, target);
  3602. }
  3603. intersectsBox(box) {
  3604. return this.intersectBox(box, _vector$2) !== null;
  3605. }
  3606. intersectTriangle(a, b, c, backfaceCulling, target) {
  3607. // Compute the offset origin, edges, and normal.
  3608. // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h
  3609. _edge1.subVectors(b, a);
  3610. _edge2.subVectors(c, a);
  3611. _normal.crossVectors(_edge1, _edge2); // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  3612. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  3613. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  3614. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  3615. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  3616. let DdN = this.direction.dot(_normal);
  3617. let sign;
  3618. if (DdN > 0) {
  3619. if (backfaceCulling) return null;
  3620. sign = 1;
  3621. } else if (DdN < 0) {
  3622. sign = -1;
  3623. DdN = -DdN;
  3624. } else {
  3625. return null;
  3626. }
  3627. _diff.subVectors(this.origin, a);
  3628. const DdQxE2 = sign * this.direction.dot(_edge2.crossVectors(_diff, _edge2)); // b1 < 0, no intersection
  3629. if (DdQxE2 < 0) {
  3630. return null;
  3631. }
  3632. const DdE1xQ = sign * this.direction.dot(_edge1.cross(_diff)); // b2 < 0, no intersection
  3633. if (DdE1xQ < 0) {
  3634. return null;
  3635. } // b1+b2 > 1, no intersection
  3636. if (DdQxE2 + DdE1xQ > DdN) {
  3637. return null;
  3638. } // Line intersects triangle, check if ray does.
  3639. const QdN = -sign * _diff.dot(_normal); // t < 0, no intersection
  3640. if (QdN < 0) {
  3641. return null;
  3642. } // Ray intersects triangle.
  3643. return this.at(QdN / DdN, target);
  3644. }
  3645. applyMatrix4(matrix4) {
  3646. this.origin.applyMatrix4(matrix4);
  3647. this.direction.transformDirection(matrix4);
  3648. return this;
  3649. }
  3650. equals(ray) {
  3651. return ray.origin.equals(this.origin) && ray.direction.equals(this.direction);
  3652. }
  3653. }
  3654. exports.Ray = Ray;
  3655. class Matrix4 {
  3656. constructor() {
  3657. Object.defineProperty(this, 'isMatrix4', {
  3658. value: true
  3659. });
  3660. this.elements = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];
  3661. if (arguments.length > 0) {
  3662. console.error('THREE.Matrix4: the constructor no longer reads arguments. use .set() instead.');
  3663. }
  3664. }
  3665. set(n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44) {
  3666. const te = this.elements;
  3667. te[0] = n11;
  3668. te[4] = n12;
  3669. te[8] = n13;
  3670. te[12] = n14;
  3671. te[1] = n21;
  3672. te[5] = n22;
  3673. te[9] = n23;
  3674. te[13] = n24;
  3675. te[2] = n31;
  3676. te[6] = n32;
  3677. te[10] = n33;
  3678. te[14] = n34;
  3679. te[3] = n41;
  3680. te[7] = n42;
  3681. te[11] = n43;
  3682. te[15] = n44;
  3683. return this;
  3684. }
  3685. identity() {
  3686. this.set(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1);
  3687. return this;
  3688. }
  3689. clone() {
  3690. return new Matrix4().fromArray(this.elements);
  3691. }
  3692. copy(m) {
  3693. const te = this.elements;
  3694. const me = m.elements;
  3695. te[0] = me[0];
  3696. te[1] = me[1];
  3697. te[2] = me[2];
  3698. te[3] = me[3];
  3699. te[4] = me[4];
  3700. te[5] = me[5];
  3701. te[6] = me[6];
  3702. te[7] = me[7];
  3703. te[8] = me[8];
  3704. te[9] = me[9];
  3705. te[10] = me[10];
  3706. te[11] = me[11];
  3707. te[12] = me[12];
  3708. te[13] = me[13];
  3709. te[14] = me[14];
  3710. te[15] = me[15];
  3711. return this;
  3712. }
  3713. copyPosition(m) {
  3714. const te = this.elements,
  3715. me = m.elements;
  3716. te[12] = me[12];
  3717. te[13] = me[13];
  3718. te[14] = me[14];
  3719. return this;
  3720. }
  3721. extractBasis(xAxis, yAxis, zAxis) {
  3722. xAxis.setFromMatrixColumn(this, 0);
  3723. yAxis.setFromMatrixColumn(this, 1);
  3724. zAxis.setFromMatrixColumn(this, 2);
  3725. return this;
  3726. }
  3727. makeBasis(xAxis, yAxis, zAxis) {
  3728. this.set(xAxis.x, yAxis.x, zAxis.x, 0, xAxis.y, yAxis.y, zAxis.y, 0, xAxis.z, yAxis.z, zAxis.z, 0, 0, 0, 0, 1);
  3729. return this;
  3730. }
  3731. extractRotation(m) {
  3732. // this method does not support reflection matrices
  3733. const te = this.elements;
  3734. const me = m.elements;
  3735. const scaleX = 1 / _v1$1.setFromMatrixColumn(m, 0).length();
  3736. const scaleY = 1 / _v1$1.setFromMatrixColumn(m, 1).length();
  3737. const scaleZ = 1 / _v1$1.setFromMatrixColumn(m, 2).length();
  3738. te[0] = me[0] * scaleX;
  3739. te[1] = me[1] * scaleX;
  3740. te[2] = me[2] * scaleX;
  3741. te[3] = 0;
  3742. te[4] = me[4] * scaleY;
  3743. te[5] = me[5] * scaleY;
  3744. te[6] = me[6] * scaleY;
  3745. te[7] = 0;
  3746. te[8] = me[8] * scaleZ;
  3747. te[9] = me[9] * scaleZ;
  3748. te[10] = me[10] * scaleZ;
  3749. te[11] = 0;
  3750. te[12] = 0;
  3751. te[13] = 0;
  3752. te[14] = 0;
  3753. te[15] = 1;
  3754. return this;
  3755. }
  3756. makeRotationFromEuler(euler) {
  3757. if (!(euler && euler.isEuler)) {
  3758. console.error('THREE.Matrix4: .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order.');
  3759. }
  3760. const te = this.elements;
  3761. const x = euler.x,
  3762. y = euler.y,
  3763. z = euler.z;
  3764. const a = Math.cos(x),
  3765. b = Math.sin(x);
  3766. const c = Math.cos(y),
  3767. d = Math.sin(y);
  3768. const e = Math.cos(z),
  3769. f = Math.sin(z);
  3770. if (euler.order === 'XYZ') {
  3771. const ae = a * e,
  3772. af = a * f,
  3773. be = b * e,
  3774. bf = b * f;
  3775. te[0] = c * e;
  3776. te[4] = -c * f;
  3777. te[8] = d;
  3778. te[1] = af + be * d;
  3779. te[5] = ae - bf * d;
  3780. te[9] = -b * c;
  3781. te[2] = bf - ae * d;
  3782. te[6] = be + af * d;
  3783. te[10] = a * c;
  3784. } else if (euler.order === 'YXZ') {
  3785. const ce = c * e,
  3786. cf = c * f,
  3787. de = d * e,
  3788. df = d * f;
  3789. te[0] = ce + df * b;
  3790. te[4] = de * b - cf;
  3791. te[8] = a * d;
  3792. te[1] = a * f;
  3793. te[5] = a * e;
  3794. te[9] = -b;
  3795. te[2] = cf * b - de;
  3796. te[6] = df + ce * b;
  3797. te[10] = a * c;
  3798. } else if (euler.order === 'ZXY') {
  3799. const ce = c * e,
  3800. cf = c * f,
  3801. de = d * e,
  3802. df = d * f;
  3803. te[0] = ce - df * b;
  3804. te[4] = -a * f;
  3805. te[8] = de + cf * b;
  3806. te[1] = cf + de * b;
  3807. te[5] = a * e;
  3808. te[9] = df - ce * b;
  3809. te[2] = -a * d;
  3810. te[6] = b;
  3811. te[10] = a * c;
  3812. } else if (euler.order === 'ZYX') {
  3813. const ae = a * e,
  3814. af = a * f,
  3815. be = b * e,
  3816. bf = b * f;
  3817. te[0] = c * e;
  3818. te[4] = be * d - af;
  3819. te[8] = ae * d + bf;
  3820. te[1] = c * f;
  3821. te[5] = bf * d + ae;
  3822. te[9] = af * d - be;
  3823. te[2] = -d;
  3824. te[6] = b * c;
  3825. te[10] = a * c;
  3826. } else if (euler.order === 'YZX') {
  3827. const ac = a * c,
  3828. ad = a * d,
  3829. bc = b * c,
  3830. bd = b * d;
  3831. te[0] = c * e;
  3832. te[4] = bd - ac * f;
  3833. te[8] = bc * f + ad;
  3834. te[1] = f;
  3835. te[5] = a * e;
  3836. te[9] = -b * e;
  3837. te[2] = -d * e;
  3838. te[6] = ad * f + bc;
  3839. te[10] = ac - bd * f;
  3840. } else if (euler.order === 'XZY') {
  3841. const ac = a * c,
  3842. ad = a * d,
  3843. bc = b * c,
  3844. bd = b * d;
  3845. te[0] = c * e;
  3846. te[4] = -f;
  3847. te[8] = d * e;
  3848. te[1] = ac * f + bd;
  3849. te[5] = a * e;
  3850. te[9] = ad * f - bc;
  3851. te[2] = bc * f - ad;
  3852. te[6] = b * e;
  3853. te[10] = bd * f + ac;
  3854. } // bottom row
  3855. te[3] = 0;
  3856. te[7] = 0;
  3857. te[11] = 0; // last column
  3858. te[12] = 0;
  3859. te[13] = 0;
  3860. te[14] = 0;
  3861. te[15] = 1;
  3862. return this;
  3863. }
  3864. makeRotationFromQuaternion(q) {
  3865. return this.compose(_zero, q, _one);
  3866. }
  3867. lookAt(eye, target, up) {
  3868. const te = this.elements;
  3869. _z.subVectors(eye, target);
  3870. if (_z.lengthSq() === 0) {
  3871. // eye and target are in the same position
  3872. _z.z = 1;
  3873. }
  3874. _z.normalize();
  3875. _x.crossVectors(up, _z);
  3876. if (_x.lengthSq() === 0) {
  3877. // up and z are parallel
  3878. if (Math.abs(up.z) === 1) {
  3879. _z.x += 0.0001;
  3880. } else {
  3881. _z.z += 0.0001;
  3882. }
  3883. _z.normalize();
  3884. _x.crossVectors(up, _z);
  3885. }
  3886. _x.normalize();
  3887. _y.crossVectors(_z, _x);
  3888. te[0] = _x.x;
  3889. te[4] = _y.x;
  3890. te[8] = _z.x;
  3891. te[1] = _x.y;
  3892. te[5] = _y.y;
  3893. te[9] = _z.y;
  3894. te[2] = _x.z;
  3895. te[6] = _y.z;
  3896. te[10] = _z.z;
  3897. return this;
  3898. }
  3899. multiply(m, n) {
  3900. if (n !== undefined) {
  3901. console.warn('THREE.Matrix4: .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead.');
  3902. return this.multiplyMatrices(m, n);
  3903. }
  3904. return this.multiplyMatrices(this, m);
  3905. }
  3906. premultiply(m) {
  3907. return this.multiplyMatrices(m, this);
  3908. }
  3909. multiplyMatrices(a, b) {
  3910. const ae = a.elements;
  3911. const be = b.elements;
  3912. const te = this.elements;
  3913. const a11 = ae[0],
  3914. a12 = ae[4],
  3915. a13 = ae[8],
  3916. a14 = ae[12];
  3917. const a21 = ae[1],
  3918. a22 = ae[5],
  3919. a23 = ae[9],
  3920. a24 = ae[13];
  3921. const a31 = ae[2],
  3922. a32 = ae[6],
  3923. a33 = ae[10],
  3924. a34 = ae[14];
  3925. const a41 = ae[3],
  3926. a42 = ae[7],
  3927. a43 = ae[11],
  3928. a44 = ae[15];
  3929. const b11 = be[0],
  3930. b12 = be[4],
  3931. b13 = be[8],
  3932. b14 = be[12];
  3933. const b21 = be[1],
  3934. b22 = be[5],
  3935. b23 = be[9],
  3936. b24 = be[13];
  3937. const b31 = be[2],
  3938. b32 = be[6],
  3939. b33 = be[10],
  3940. b34 = be[14];
  3941. const b41 = be[3],
  3942. b42 = be[7],
  3943. b43 = be[11],
  3944. b44 = be[15];
  3945. te[0] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  3946. te[4] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  3947. te[8] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  3948. te[12] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  3949. te[1] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  3950. te[5] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  3951. te[9] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  3952. te[13] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  3953. te[2] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  3954. te[6] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  3955. te[10] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  3956. te[14] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  3957. te[3] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  3958. te[7] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  3959. te[11] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  3960. te[15] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  3961. return this;
  3962. }
  3963. multiplyScalar(s) {
  3964. const te = this.elements;
  3965. te[0] *= s;
  3966. te[4] *= s;
  3967. te[8] *= s;
  3968. te[12] *= s;
  3969. te[1] *= s;
  3970. te[5] *= s;
  3971. te[9] *= s;
  3972. te[13] *= s;
  3973. te[2] *= s;
  3974. te[6] *= s;
  3975. te[10] *= s;
  3976. te[14] *= s;
  3977. te[3] *= s;
  3978. te[7] *= s;
  3979. te[11] *= s;
  3980. te[15] *= s;
  3981. return this;
  3982. }
  3983. determinant() {
  3984. const te = this.elements;
  3985. const n11 = te[0],
  3986. n12 = te[4],
  3987. n13 = te[8],
  3988. n14 = te[12];
  3989. const n21 = te[1],
  3990. n22 = te[5],
  3991. n23 = te[9],
  3992. n24 = te[13];
  3993. const n31 = te[2],
  3994. n32 = te[6],
  3995. n33 = te[10],
  3996. n34 = te[14];
  3997. const n41 = te[3],
  3998. n42 = te[7],
  3999. n43 = te[11],
  4000. n44 = te[15]; //TODO: make this more efficient
  4001. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  4002. return n41 * (+n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34) + n42 * (+n11 * n23 * n34 - n11 * n24 * n33 + n14 * n21 * n33 - n13 * n21 * n34 + n13 * n24 * n31 - n14 * n23 * n31) + n43 * (+n11 * n24 * n32 - n11 * n22 * n34 - n14 * n21 * n32 + n12 * n21 * n34 + n14 * n22 * n31 - n12 * n24 * n31) + n44 * (-n13 * n22 * n31 - n11 * n23 * n32 + n11 * n22 * n33 + n13 * n21 * n32 - n12 * n21 * n33 + n12 * n23 * n31);
  4003. }
  4004. transpose() {
  4005. const te = this.elements;
  4006. let tmp;
  4007. tmp = te[1];
  4008. te[1] = te[4];
  4009. te[4] = tmp;
  4010. tmp = te[2];
  4011. te[2] = te[8];
  4012. te[8] = tmp;
  4013. tmp = te[6];
  4014. te[6] = te[9];
  4015. te[9] = tmp;
  4016. tmp = te[3];
  4017. te[3] = te[12];
  4018. te[12] = tmp;
  4019. tmp = te[7];
  4020. te[7] = te[13];
  4021. te[13] = tmp;
  4022. tmp = te[11];
  4023. te[11] = te[14];
  4024. te[14] = tmp;
  4025. return this;
  4026. }
  4027. setPosition(x, y, z) {
  4028. const te = this.elements;
  4029. if (x.isVector3) {
  4030. te[12] = x.x;
  4031. te[13] = x.y;
  4032. te[14] = x.z;
  4033. } else {
  4034. te[12] = x;
  4035. te[13] = y;
  4036. te[14] = z;
  4037. }
  4038. return this;
  4039. }
  4040. invert() {
  4041. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  4042. const te = this.elements,
  4043. n11 = te[0],
  4044. n21 = te[1],
  4045. n31 = te[2],
  4046. n41 = te[3],
  4047. n12 = te[4],
  4048. n22 = te[5],
  4049. n32 = te[6],
  4050. n42 = te[7],
  4051. n13 = te[8],
  4052. n23 = te[9],
  4053. n33 = te[10],
  4054. n43 = te[11],
  4055. n14 = te[12],
  4056. n24 = te[13],
  4057. n34 = te[14],
  4058. n44 = te[15],
  4059. t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44,
  4060. t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44,
  4061. t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44,
  4062. t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34;
  4063. const det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14;
  4064. if (det === 0) return this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  4065. const detInv = 1 / det;
  4066. te[0] = t11 * detInv;
  4067. te[1] = (n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44) * detInv;
  4068. te[2] = (n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44) * detInv;
  4069. te[3] = (n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43) * detInv;
  4070. te[4] = t12 * detInv;
  4071. te[5] = (n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44) * detInv;
  4072. te[6] = (n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44) * detInv;
  4073. te[7] = (n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43) * detInv;
  4074. te[8] = t13 * detInv;
  4075. te[9] = (n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44) * detInv;
  4076. te[10] = (n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44) * detInv;
  4077. te[11] = (n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43) * detInv;
  4078. te[12] = t14 * detInv;
  4079. te[13] = (n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34) * detInv;
  4080. te[14] = (n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34) * detInv;
  4081. te[15] = (n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33) * detInv;
  4082. return this;
  4083. }
  4084. scale(v) {
  4085. const te = this.elements;
  4086. const x = v.x,
  4087. y = v.y,
  4088. z = v.z;
  4089. te[0] *= x;
  4090. te[4] *= y;
  4091. te[8] *= z;
  4092. te[1] *= x;
  4093. te[5] *= y;
  4094. te[9] *= z;
  4095. te[2] *= x;
  4096. te[6] *= y;
  4097. te[10] *= z;
  4098. te[3] *= x;
  4099. te[7] *= y;
  4100. te[11] *= z;
  4101. return this;
  4102. }
  4103. getMaxScaleOnAxis() {
  4104. const te = this.elements;
  4105. const scaleXSq = te[0] * te[0] + te[1] * te[1] + te[2] * te[2];
  4106. const scaleYSq = te[4] * te[4] + te[5] * te[5] + te[6] * te[6];
  4107. const scaleZSq = te[8] * te[8] + te[9] * te[9] + te[10] * te[10];
  4108. return Math.sqrt(Math.max(scaleXSq, scaleYSq, scaleZSq));
  4109. }
  4110. makeTranslation(x, y, z) {
  4111. this.set(1, 0, 0, x, 0, 1, 0, y, 0, 0, 1, z, 0, 0, 0, 1);
  4112. return this;
  4113. }
  4114. makeRotationX(theta) {
  4115. const c = Math.cos(theta),
  4116. s = Math.sin(theta);
  4117. this.set(1, 0, 0, 0, 0, c, -s, 0, 0, s, c, 0, 0, 0, 0, 1);
  4118. return this;
  4119. }
  4120. makeRotationY(theta) {
  4121. const c = Math.cos(theta),
  4122. s = Math.sin(theta);
  4123. this.set(c, 0, s, 0, 0, 1, 0, 0, -s, 0, c, 0, 0, 0, 0, 1);
  4124. return this;
  4125. }
  4126. makeRotationZ(theta) {
  4127. const c = Math.cos(theta),
  4128. s = Math.sin(theta);
  4129. this.set(c, -s, 0, 0, s, c, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1);
  4130. return this;
  4131. }
  4132. makeRotationAxis(axis, angle) {
  4133. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  4134. const c = Math.cos(angle);
  4135. const s = Math.sin(angle);
  4136. const t = 1 - c;
  4137. const x = axis.x,
  4138. y = axis.y,
  4139. z = axis.z;
  4140. const tx = t * x,
  4141. ty = t * y;
  4142. this.set(tx * x + c, tx * y - s * z, tx * z + s * y, 0, tx * y + s * z, ty * y + c, ty * z - s * x, 0, tx * z - s * y, ty * z + s * x, t * z * z + c, 0, 0, 0, 0, 1);
  4143. return this;
  4144. }
  4145. makeScale(x, y, z) {
  4146. this.set(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1);
  4147. return this;
  4148. }
  4149. makeShear(x, y, z) {
  4150. this.set(1, y, z, 0, x, 1, z, 0, x, y, 1, 0, 0, 0, 0, 1);
  4151. return this;
  4152. }
  4153. compose(position, quaternion, scale) {
  4154. const te = this.elements;
  4155. const x = quaternion._x,
  4156. y = quaternion._y,
  4157. z = quaternion._z,
  4158. w = quaternion._w;
  4159. const x2 = x + x,
  4160. y2 = y + y,
  4161. z2 = z + z;
  4162. const xx = x * x2,
  4163. xy = x * y2,
  4164. xz = x * z2;
  4165. const yy = y * y2,
  4166. yz = y * z2,
  4167. zz = z * z2;
  4168. const wx = w * x2,
  4169. wy = w * y2,
  4170. wz = w * z2;
  4171. const sx = scale.x,
  4172. sy = scale.y,
  4173. sz = scale.z;
  4174. te[0] = (1 - (yy + zz)) * sx;
  4175. te[1] = (xy + wz) * sx;
  4176. te[2] = (xz - wy) * sx;
  4177. te[3] = 0;
  4178. te[4] = (xy - wz) * sy;
  4179. te[5] = (1 - (xx + zz)) * sy;
  4180. te[6] = (yz + wx) * sy;
  4181. te[7] = 0;
  4182. te[8] = (xz + wy) * sz;
  4183. te[9] = (yz - wx) * sz;
  4184. te[10] = (1 - (xx + yy)) * sz;
  4185. te[11] = 0;
  4186. te[12] = position.x;
  4187. te[13] = position.y;
  4188. te[14] = position.z;
  4189. te[15] = 1;
  4190. return this;
  4191. }
  4192. decompose(position, quaternion, scale) {
  4193. const te = this.elements;
  4194. let sx = _v1$1.set(te[0], te[1], te[2]).length();
  4195. const sy = _v1$1.set(te[4], te[5], te[6]).length();
  4196. const sz = _v1$1.set(te[8], te[9], te[10]).length(); // if determine is negative, we need to invert one scale
  4197. const det = this.determinant();
  4198. if (det < 0) sx = -sx;
  4199. position.x = te[12];
  4200. position.y = te[13];
  4201. position.z = te[14]; // scale the rotation part
  4202. _m1.copy(this);
  4203. const invSX = 1 / sx;
  4204. const invSY = 1 / sy;
  4205. const invSZ = 1 / sz;
  4206. _m1.elements[0] *= invSX;
  4207. _m1.elements[1] *= invSX;
  4208. _m1.elements[2] *= invSX;
  4209. _m1.elements[4] *= invSY;
  4210. _m1.elements[5] *= invSY;
  4211. _m1.elements[6] *= invSY;
  4212. _m1.elements[8] *= invSZ;
  4213. _m1.elements[9] *= invSZ;
  4214. _m1.elements[10] *= invSZ;
  4215. quaternion.setFromRotationMatrix(_m1);
  4216. scale.x = sx;
  4217. scale.y = sy;
  4218. scale.z = sz;
  4219. return this;
  4220. }
  4221. makePerspective(left, right, top, bottom, near, far) {
  4222. if (far === undefined) {
  4223. console.warn('THREE.Matrix4: .makePerspective() has been redefined and has a new signature. Please check the docs.');
  4224. }
  4225. const te = this.elements;
  4226. const x = 2 * near / (right - left);
  4227. const y = 2 * near / (top - bottom);
  4228. const a = (right + left) / (right - left);
  4229. const b = (top + bottom) / (top - bottom);
  4230. const c = -(far + near) / (far - near);
  4231. const d = -2 * far * near / (far - near);
  4232. te[0] = x;
  4233. te[4] = 0;
  4234. te[8] = a;
  4235. te[12] = 0;
  4236. te[1] = 0;
  4237. te[5] = y;
  4238. te[9] = b;
  4239. te[13] = 0;
  4240. te[2] = 0;
  4241. te[6] = 0;
  4242. te[10] = c;
  4243. te[14] = d;
  4244. te[3] = 0;
  4245. te[7] = 0;
  4246. te[11] = -1;
  4247. te[15] = 0;
  4248. return this;
  4249. }
  4250. makeOrthographic(left, right, top, bottom, near, far) {
  4251. const te = this.elements;
  4252. const w = 1.0 / (right - left);
  4253. const h = 1.0 / (top - bottom);
  4254. const p = 1.0 / (far - near);
  4255. const x = (right + left) * w;
  4256. const y = (top + bottom) * h;
  4257. const z = (far + near) * p;
  4258. te[0] = 2 * w;
  4259. te[4] = 0;
  4260. te[8] = 0;
  4261. te[12] = -x;
  4262. te[1] = 0;
  4263. te[5] = 2 * h;
  4264. te[9] = 0;
  4265. te[13] = -y;
  4266. te[2] = 0;
  4267. te[6] = 0;
  4268. te[10] = -2 * p;
  4269. te[14] = -z;
  4270. te[3] = 0;
  4271. te[7] = 0;
  4272. te[11] = 0;
  4273. te[15] = 1;
  4274. return this;
  4275. }
  4276. equals(matrix) {
  4277. const te = this.elements;
  4278. const me = matrix.elements;
  4279. for (let i = 0; i < 16; i++) {
  4280. if (te[i] !== me[i]) return false;
  4281. }
  4282. return true;
  4283. }
  4284. fromArray(array, offset = 0) {
  4285. for (let i = 0; i < 16; i++) {
  4286. this.elements[i] = array[i + offset];
  4287. }
  4288. return this;
  4289. }
  4290. toArray(array = [], offset = 0) {
  4291. const te = this.elements;
  4292. array[offset] = te[0];
  4293. array[offset + 1] = te[1];
  4294. array[offset + 2] = te[2];
  4295. array[offset + 3] = te[3];
  4296. array[offset + 4] = te[4];
  4297. array[offset + 5] = te[5];
  4298. array[offset + 6] = te[6];
  4299. array[offset + 7] = te[7];
  4300. array[offset + 8] = te[8];
  4301. array[offset + 9] = te[9];
  4302. array[offset + 10] = te[10];
  4303. array[offset + 11] = te[11];
  4304. array[offset + 12] = te[12];
  4305. array[offset + 13] = te[13];
  4306. array[offset + 14] = te[14];
  4307. array[offset + 15] = te[15];
  4308. return array;
  4309. }
  4310. }
  4311. exports.Matrix4 = Matrix4;
  4312. const _v1$1 =
  4313. /*@__PURE__*/
  4314. new Vector3();
  4315. const _m1 =
  4316. /*@__PURE__*/
  4317. new Matrix4();
  4318. const _zero =
  4319. /*@__PURE__*/
  4320. new Vector3(0, 0, 0);
  4321. const _one =
  4322. /*@__PURE__*/
  4323. new Vector3(1, 1, 1);
  4324. const _x =
  4325. /*@__PURE__*/
  4326. new Vector3();
  4327. const _y =
  4328. /*@__PURE__*/
  4329. new Vector3();
  4330. const _z =
  4331. /*@__PURE__*/
  4332. new Vector3();
  4333. class Euler {
  4334. constructor(x = 0, y = 0, z = 0, order = Euler.DefaultOrder) {
  4335. Object.defineProperty(this, 'isEuler', {
  4336. value: true
  4337. });
  4338. this._x = x;
  4339. this._y = y;
  4340. this._z = z;
  4341. this._order = order;
  4342. }
  4343. get x() {
  4344. return this._x;
  4345. }
  4346. set x(value) {
  4347. this._x = value;
  4348. this._onChangeCallback();
  4349. }
  4350. get y() {
  4351. return this._y;
  4352. }
  4353. set y(value) {
  4354. this._y = value;
  4355. this._onChangeCallback();
  4356. }
  4357. get z() {
  4358. return this._z;
  4359. }
  4360. set z(value) {
  4361. this._z = value;
  4362. this._onChangeCallback();
  4363. }
  4364. get order() {
  4365. return this._order;
  4366. }
  4367. set order(value) {
  4368. this._order = value;
  4369. this._onChangeCallback();
  4370. }
  4371. set(x, y, z, order) {
  4372. this._x = x;
  4373. this._y = y;
  4374. this._z = z;
  4375. this._order = order || this._order;
  4376. this._onChangeCallback();
  4377. return this;
  4378. }
  4379. clone() {
  4380. return new this.constructor(this._x, this._y, this._z, this._order);
  4381. }
  4382. copy(euler) {
  4383. this._x = euler._x;
  4384. this._y = euler._y;
  4385. this._z = euler._z;
  4386. this._order = euler._order;
  4387. this._onChangeCallback();
  4388. return this;
  4389. }
  4390. setFromRotationMatrix(m, order, update) {
  4391. const clamp = MathUtils.clamp; // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  4392. const te = m.elements;
  4393. const m11 = te[0],
  4394. m12 = te[4],
  4395. m13 = te[8];
  4396. const m21 = te[1],
  4397. m22 = te[5],
  4398. m23 = te[9];
  4399. const m31 = te[2],
  4400. m32 = te[6],
  4401. m33 = te[10];
  4402. order = order || this._order;
  4403. switch (order) {
  4404. case 'XYZ':
  4405. this._y = Math.asin(clamp(m13, -1, 1));
  4406. if (Math.abs(m13) < 0.9999999) {
  4407. this._x = Math.atan2(-m23, m33);
  4408. this._z = Math.atan2(-m12, m11);
  4409. } else {
  4410. this._x = Math.atan2(m32, m22);
  4411. this._z = 0;
  4412. }
  4413. break;
  4414. case 'YXZ':
  4415. this._x = Math.asin(-clamp(m23, -1, 1));
  4416. if (Math.abs(m23) < 0.9999999) {
  4417. this._y = Math.atan2(m13, m33);
  4418. this._z = Math.atan2(m21, m22);
  4419. } else {
  4420. this._y = Math.atan2(-m31, m11);
  4421. this._z = 0;
  4422. }
  4423. break;
  4424. case 'ZXY':
  4425. this._x = Math.asin(clamp(m32, -1, 1));
  4426. if (Math.abs(m32) < 0.9999999) {
  4427. this._y = Math.atan2(-m31, m33);
  4428. this._z = Math.atan2(-m12, m22);
  4429. } else {
  4430. this._y = 0;
  4431. this._z = Math.atan2(m21, m11);
  4432. }
  4433. break;
  4434. case 'ZYX':
  4435. this._y = Math.asin(-clamp(m31, -1, 1));
  4436. if (Math.abs(m31) < 0.9999999) {
  4437. this._x = Math.atan2(m32, m33);
  4438. this._z = Math.atan2(m21, m11);
  4439. } else {
  4440. this._x = 0;
  4441. this._z = Math.atan2(-m12, m22);
  4442. }
  4443. break;
  4444. case 'YZX':
  4445. this._z = Math.asin(clamp(m21, -1, 1));
  4446. if (Math.abs(m21) < 0.9999999) {
  4447. this._x = Math.atan2(-m23, m22);
  4448. this._y = Math.atan2(-m31, m11);
  4449. } else {
  4450. this._x = 0;
  4451. this._y = Math.atan2(m13, m33);
  4452. }
  4453. break;
  4454. case 'XZY':
  4455. this._z = Math.asin(-clamp(m12, -1, 1));
  4456. if (Math.abs(m12) < 0.9999999) {
  4457. this._x = Math.atan2(m32, m22);
  4458. this._y = Math.atan2(m13, m11);
  4459. } else {
  4460. this._x = Math.atan2(-m23, m33);
  4461. this._y = 0;
  4462. }
  4463. break;
  4464. default:
  4465. console.warn('THREE.Euler: .setFromRotationMatrix() encountered an unknown order: ' + order);
  4466. }
  4467. this._order = order;
  4468. if (update !== false) this._onChangeCallback();
  4469. return this;
  4470. }
  4471. setFromQuaternion(q, order, update) {
  4472. _matrix.makeRotationFromQuaternion(q);
  4473. return this.setFromRotationMatrix(_matrix, order, update);
  4474. }
  4475. setFromVector3(v, order) {
  4476. return this.set(v.x, v.y, v.z, order || this._order);
  4477. }
  4478. reorder(newOrder) {
  4479. // WARNING: this discards revolution information -bhouston
  4480. _quaternion$1.setFromEuler(this);
  4481. return this.setFromQuaternion(_quaternion$1, newOrder);
  4482. }
  4483. equals(euler) {
  4484. return euler._x === this._x && euler._y === this._y && euler._z === this._z && euler._order === this._order;
  4485. }
  4486. fromArray(array) {
  4487. this._x = array[0];
  4488. this._y = array[1];
  4489. this._z = array[2];
  4490. if (array[3] !== undefined) this._order = array[3];
  4491. this._onChangeCallback();
  4492. return this;
  4493. }
  4494. toArray(array = [], offset = 0) {
  4495. array[offset] = this._x;
  4496. array[offset + 1] = this._y;
  4497. array[offset + 2] = this._z;
  4498. array[offset + 3] = this._order;
  4499. return array;
  4500. }
  4501. toVector3(optionalResult) {
  4502. if (optionalResult) {
  4503. return optionalResult.set(this._x, this._y, this._z);
  4504. } else {
  4505. return new Vector3(this._x, this._y, this._z);
  4506. }
  4507. }
  4508. _onChange(callback) {
  4509. this._onChangeCallback = callback;
  4510. return this;
  4511. }
  4512. _onChangeCallback() {}
  4513. }
  4514. exports.Euler = Euler;
  4515. Euler.DefaultOrder = 'XYZ';
  4516. Euler.RotationOrders = ['XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX'];
  4517. const _matrix =
  4518. /*@__PURE__*/
  4519. new Matrix4();
  4520. const _quaternion$1 =
  4521. /*@__PURE__*/
  4522. new Quaternion();
  4523. class Layers {
  4524. constructor() {
  4525. this.mask = 1 | 0;
  4526. }
  4527. set(channel) {
  4528. this.mask = 1 << channel | 0;
  4529. }
  4530. enable(channel) {
  4531. this.mask |= 1 << channel | 0;
  4532. }
  4533. enableAll() {
  4534. this.mask = 0xffffffff | 0;
  4535. }
  4536. toggle(channel) {
  4537. this.mask ^= 1 << channel | 0;
  4538. }
  4539. disable(channel) {
  4540. this.mask &= ~(1 << channel | 0);
  4541. }
  4542. disableAll() {
  4543. this.mask = 0;
  4544. }
  4545. test(layers) {
  4546. return (this.mask & layers.mask) !== 0;
  4547. }
  4548. }
  4549. exports.Layers = Layers;
  4550. let _object3DId = 0;
  4551. const _v1$2 = new Vector3();
  4552. const _q1 = new Quaternion();
  4553. const _m1$1 = new Matrix4();
  4554. const _target = new Vector3();
  4555. const _position = new Vector3();
  4556. const _scale = new Vector3();
  4557. const _quaternion$2 = new Quaternion();
  4558. const _xAxis = new Vector3(1, 0, 0);
  4559. const _yAxis = new Vector3(0, 1, 0);
  4560. const _zAxis = new Vector3(0, 0, 1);
  4561. const _addedEvent = {
  4562. type: 'added'
  4563. };
  4564. const _removedEvent = {
  4565. type: 'removed'
  4566. };
  4567. function Object3D() {
  4568. Object.defineProperty(this, 'id', {
  4569. value: _object3DId++
  4570. });
  4571. this.uuid = MathUtils.generateUUID();
  4572. this.name = '';
  4573. this.type = 'Object3D';
  4574. this.parent = null;
  4575. this.children = [];
  4576. this.up = Object3D.DefaultUp.clone();
  4577. const position = new Vector3();
  4578. const rotation = new Euler();
  4579. const quaternion = new Quaternion();
  4580. const scale = new Vector3(1, 1, 1);
  4581. function onRotationChange() {
  4582. quaternion.setFromEuler(rotation, false);
  4583. }
  4584. function onQuaternionChange() {
  4585. rotation.setFromQuaternion(quaternion, undefined, false);
  4586. }
  4587. rotation._onChange(onRotationChange);
  4588. quaternion._onChange(onQuaternionChange);
  4589. Object.defineProperties(this, {
  4590. position: {
  4591. configurable: true,
  4592. enumerable: true,
  4593. value: position
  4594. },
  4595. rotation: {
  4596. configurable: true,
  4597. enumerable: true,
  4598. value: rotation
  4599. },
  4600. quaternion: {
  4601. configurable: true,
  4602. enumerable: true,
  4603. value: quaternion
  4604. },
  4605. scale: {
  4606. configurable: true,
  4607. enumerable: true,
  4608. value: scale
  4609. },
  4610. modelViewMatrix: {
  4611. value: new Matrix4()
  4612. },
  4613. normalMatrix: {
  4614. value: new Matrix3()
  4615. }
  4616. });
  4617. this.matrix = new Matrix4();
  4618. this.matrixWorld = new Matrix4();
  4619. this.matrixAutoUpdate = Object3D.DefaultMatrixAutoUpdate;
  4620. this.matrixWorldNeedsUpdate = false;
  4621. this.layers = new Layers();
  4622. this.visible = true;
  4623. this.castShadow = false;
  4624. this.receiveShadow = false;
  4625. this.frustumCulled = true;
  4626. this.renderOrder = 0;
  4627. this.animations = [];
  4628. this.userData = {};
  4629. }
  4630. Object3D.DefaultUp = new Vector3(0, 1, 0);
  4631. Object3D.DefaultMatrixAutoUpdate = true;
  4632. Object3D.prototype = Object.assign(Object.create(EventDispatcher.prototype), {
  4633. constructor: Object3D,
  4634. isObject3D: true,
  4635. onBeforeRender: function () {},
  4636. onAfterRender: function () {},
  4637. applyMatrix4: function (matrix) {
  4638. if (this.matrixAutoUpdate) this.updateMatrix();
  4639. this.matrix.premultiply(matrix);
  4640. this.matrix.decompose(this.position, this.quaternion, this.scale);
  4641. },
  4642. applyQuaternion: function (q) {
  4643. this.quaternion.premultiply(q);
  4644. return this;
  4645. },
  4646. setRotationFromAxisAngle: function (axis, angle) {
  4647. // assumes axis is normalized
  4648. this.quaternion.setFromAxisAngle(axis, angle);
  4649. },
  4650. setRotationFromEuler: function (euler) {
  4651. this.quaternion.setFromEuler(euler, true);
  4652. },
  4653. setRotationFromMatrix: function (m) {
  4654. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  4655. this.quaternion.setFromRotationMatrix(m);
  4656. },
  4657. setRotationFromQuaternion: function (q) {
  4658. // assumes q is normalized
  4659. this.quaternion.copy(q);
  4660. },
  4661. rotateOnAxis: function (axis, angle) {
  4662. // rotate object on axis in object space
  4663. // axis is assumed to be normalized
  4664. _q1.setFromAxisAngle(axis, angle);
  4665. this.quaternion.multiply(_q1);
  4666. return this;
  4667. },
  4668. rotateOnWorldAxis: function (axis, angle) {
  4669. // rotate object on axis in world space
  4670. // axis is assumed to be normalized
  4671. // method assumes no rotated parent
  4672. _q1.setFromAxisAngle(axis, angle);
  4673. this.quaternion.premultiply(_q1);
  4674. return this;
  4675. },
  4676. rotateX: function (angle) {
  4677. return this.rotateOnAxis(_xAxis, angle);
  4678. },
  4679. rotateY: function (angle) {
  4680. return this.rotateOnAxis(_yAxis, angle);
  4681. },
  4682. rotateZ: function (angle) {
  4683. return this.rotateOnAxis(_zAxis, angle);
  4684. },
  4685. translateOnAxis: function (axis, distance) {
  4686. // translate object by distance along axis in object space
  4687. // axis is assumed to be normalized
  4688. _v1$2.copy(axis).applyQuaternion(this.quaternion);
  4689. this.position.add(_v1$2.multiplyScalar(distance));
  4690. return this;
  4691. },
  4692. translateX: function (distance) {
  4693. return this.translateOnAxis(_xAxis, distance);
  4694. },
  4695. translateY: function (distance) {
  4696. return this.translateOnAxis(_yAxis, distance);
  4697. },
  4698. translateZ: function (distance) {
  4699. return this.translateOnAxis(_zAxis, distance);
  4700. },
  4701. localToWorld: function (vector) {
  4702. return vector.applyMatrix4(this.matrixWorld);
  4703. },
  4704. worldToLocal: function (vector) {
  4705. return vector.applyMatrix4(_m1$1.copy(this.matrixWorld).invert());
  4706. },
  4707. lookAt: function (x, y, z) {
  4708. // This method does not support objects having non-uniformly-scaled parent(s)
  4709. if (x.isVector3) {
  4710. _target.copy(x);
  4711. } else {
  4712. _target.set(x, y, z);
  4713. }
  4714. const parent = this.parent;
  4715. this.updateWorldMatrix(true, false);
  4716. _position.setFromMatrixPosition(this.matrixWorld);
  4717. if (this.isCamera || this.isLight) {
  4718. _m1$1.lookAt(_position, _target, this.up);
  4719. } else {
  4720. _m1$1.lookAt(_target, _position, this.up);
  4721. }
  4722. this.quaternion.setFromRotationMatrix(_m1$1);
  4723. if (parent) {
  4724. _m1$1.extractRotation(parent.matrixWorld);
  4725. _q1.setFromRotationMatrix(_m1$1);
  4726. this.quaternion.premultiply(_q1.invert());
  4727. }
  4728. },
  4729. add: function (object) {
  4730. if (arguments.length > 1) {
  4731. for (let i = 0; i < arguments.length; i++) {
  4732. this.add(arguments[i]);
  4733. }
  4734. return this;
  4735. }
  4736. if (object === this) {
  4737. console.error("THREE.Object3D.add: object can't be added as a child of itself.", object);
  4738. return this;
  4739. }
  4740. if (object && object.isObject3D) {
  4741. if (object.parent !== null) {
  4742. object.parent.remove(object);
  4743. }
  4744. object.parent = this;
  4745. this.children.push(object);
  4746. object.dispatchEvent(_addedEvent);
  4747. } else {
  4748. console.error("THREE.Object3D.add: object not an instance of THREE.Object3D.", object);
  4749. }
  4750. return this;
  4751. },
  4752. remove: function (object) {
  4753. if (arguments.length > 1) {
  4754. for (let i = 0; i < arguments.length; i++) {
  4755. this.remove(arguments[i]);
  4756. }
  4757. return this;
  4758. }
  4759. const index = this.children.indexOf(object);
  4760. if (index !== -1) {
  4761. object.parent = null;
  4762. this.children.splice(index, 1);
  4763. object.dispatchEvent(_removedEvent);
  4764. }
  4765. return this;
  4766. },
  4767. clear: function () {
  4768. for (let i = 0; i < this.children.length; i++) {
  4769. const object = this.children[i];
  4770. object.parent = null;
  4771. object.dispatchEvent(_removedEvent);
  4772. }
  4773. this.children.length = 0;
  4774. return this;
  4775. },
  4776. attach: function (object) {
  4777. // adds object as a child of this, while maintaining the object's world transform
  4778. this.updateWorldMatrix(true, false);
  4779. _m1$1.copy(this.matrixWorld).invert();
  4780. if (object.parent !== null) {
  4781. object.parent.updateWorldMatrix(true, false);
  4782. _m1$1.multiply(object.parent.matrixWorld);
  4783. }
  4784. object.applyMatrix4(_m1$1);
  4785. object.updateWorldMatrix(false, false);
  4786. this.add(object);
  4787. return this;
  4788. },
  4789. getObjectById: function (id) {
  4790. return this.getObjectByProperty('id', id);
  4791. },
  4792. getObjectByName: function (name) {
  4793. return this.getObjectByProperty('name', name);
  4794. },
  4795. getObjectByProperty: function (name, value) {
  4796. if (this[name] === value) return this;
  4797. for (let i = 0, l = this.children.length; i < l; i++) {
  4798. const child = this.children[i];
  4799. const object = child.getObjectByProperty(name, value);
  4800. if (object !== undefined) {
  4801. return object;
  4802. }
  4803. }
  4804. return undefined;
  4805. },
  4806. getWorldPosition: function (target) {
  4807. if (target === undefined) {
  4808. console.warn('THREE.Object3D: .getWorldPosition() target is now required');
  4809. target = new Vector3();
  4810. }
  4811. this.updateWorldMatrix(true, false);
  4812. return target.setFromMatrixPosition(this.matrixWorld);
  4813. },
  4814. getWorldQuaternion: function (target) {
  4815. if (target === undefined) {
  4816. console.warn('THREE.Object3D: .getWorldQuaternion() target is now required');
  4817. target = new Quaternion();
  4818. }
  4819. this.updateWorldMatrix(true, false);
  4820. this.matrixWorld.decompose(_position, target, _scale);
  4821. return target;
  4822. },
  4823. getWorldScale: function (target) {
  4824. if (target === undefined) {
  4825. console.warn('THREE.Object3D: .getWorldScale() target is now required');
  4826. target = new Vector3();
  4827. }
  4828. this.updateWorldMatrix(true, false);
  4829. this.matrixWorld.decompose(_position, _quaternion$2, target);
  4830. return target;
  4831. },
  4832. getWorldDirection: function (target) {
  4833. if (target === undefined) {
  4834. console.warn('THREE.Object3D: .getWorldDirection() target is now required');
  4835. target = new Vector3();
  4836. }
  4837. this.updateWorldMatrix(true, false);
  4838. const e = this.matrixWorld.elements;
  4839. return target.set(e[8], e[9], e[10]).normalize();
  4840. },
  4841. raycast: function () {},
  4842. traverse: function (callback) {
  4843. callback(this);
  4844. const children = this.children;
  4845. for (let i = 0, l = children.length; i < l; i++) {
  4846. children[i].traverse(callback);
  4847. }
  4848. },
  4849. traverseVisible: function (callback) {
  4850. if (this.visible === false) return;
  4851. callback(this);
  4852. const children = this.children;
  4853. for (let i = 0, l = children.length; i < l; i++) {
  4854. children[i].traverseVisible(callback);
  4855. }
  4856. },
  4857. traverseAncestors: function (callback) {
  4858. const parent = this.parent;
  4859. if (parent !== null) {
  4860. callback(parent);
  4861. parent.traverseAncestors(callback);
  4862. }
  4863. },
  4864. updateMatrix: function () {
  4865. this.matrix.compose(this.position, this.quaternion, this.scale);
  4866. this.matrixWorldNeedsUpdate = true;
  4867. },
  4868. updateMatrixWorld: function (force) {
  4869. if (this.matrixAutoUpdate) this.updateMatrix();
  4870. if (this.matrixWorldNeedsUpdate || force) {
  4871. if (this.parent === null) {
  4872. this.matrixWorld.copy(this.matrix);
  4873. } else {
  4874. this.matrixWorld.multiplyMatrices(this.parent.matrixWorld, this.matrix);
  4875. }
  4876. this.matrixWorldNeedsUpdate = false;
  4877. force = true;
  4878. } // update children
  4879. const children = this.children;
  4880. for (let i = 0, l = children.length; i < l; i++) {
  4881. children[i].updateMatrixWorld(force);
  4882. }
  4883. },
  4884. updateWorldMatrix: function (updateParents, updateChildren) {
  4885. const parent = this.parent;
  4886. if (updateParents === true && parent !== null) {
  4887. parent.updateWorldMatrix(true, false);
  4888. }
  4889. if (this.matrixAutoUpdate) this.updateMatrix();
  4890. if (this.parent === null) {
  4891. this.matrixWorld.copy(this.matrix);
  4892. } else {
  4893. this.matrixWorld.multiplyMatrices(this.parent.matrixWorld, this.matrix);
  4894. } // update children
  4895. if (updateChildren === true) {
  4896. const children = this.children;
  4897. for (let i = 0, l = children.length; i < l; i++) {
  4898. children[i].updateWorldMatrix(false, true);
  4899. }
  4900. }
  4901. },
  4902. toJSON: function (meta) {
  4903. // meta is a string when called from JSON.stringify
  4904. const isRootObject = meta === undefined || typeof meta === 'string';
  4905. const output = {}; // meta is a hash used to collect geometries, materials.
  4906. // not providing it implies that this is the root object
  4907. // being serialized.
  4908. if (isRootObject) {
  4909. // initialize meta obj
  4910. meta = {
  4911. geometries: {},
  4912. materials: {},
  4913. textures: {},
  4914. images: {},
  4915. shapes: {},
  4916. skeletons: {},
  4917. animations: {}
  4918. };
  4919. output.metadata = {
  4920. version: 4.5,
  4921. type: 'Object',
  4922. generator: 'Object3D.toJSON'
  4923. };
  4924. } // standard Object3D serialization
  4925. const object = {};
  4926. object.uuid = this.uuid;
  4927. object.type = this.type;
  4928. if (this.name !== '') object.name = this.name;
  4929. if (this.castShadow === true) object.castShadow = true;
  4930. if (this.receiveShadow === true) object.receiveShadow = true;
  4931. if (this.visible === false) object.visible = false;
  4932. if (this.frustumCulled === false) object.frustumCulled = false;
  4933. if (this.renderOrder !== 0) object.renderOrder = this.renderOrder;
  4934. if (JSON.stringify(this.userData) !== '{}') object.userData = this.userData;
  4935. object.layers = this.layers.mask;
  4936. object.matrix = this.matrix.toArray();
  4937. if (this.matrixAutoUpdate === false) object.matrixAutoUpdate = false; // object specific properties
  4938. if (this.isInstancedMesh) {
  4939. object.type = 'InstancedMesh';
  4940. object.count = this.count;
  4941. object.instanceMatrix = this.instanceMatrix.toJSON();
  4942. } //
  4943. function serialize(library, element) {
  4944. if (library[element.uuid] === undefined) {
  4945. library[element.uuid] = element.toJSON(meta);
  4946. }
  4947. return element.uuid;
  4948. }
  4949. if (this.isMesh || this.isLine || this.isPoints) {
  4950. object.geometry = serialize(meta.geometries, this.geometry);
  4951. const parameters = this.geometry.parameters;
  4952. if (parameters !== undefined && parameters.shapes !== undefined) {
  4953. const shapes = parameters.shapes;
  4954. if (Array.isArray(shapes)) {
  4955. for (let i = 0, l = shapes.length; i < l; i++) {
  4956. const shape = shapes[i];
  4957. serialize(meta.shapes, shape);
  4958. }
  4959. } else {
  4960. serialize(meta.shapes, shapes);
  4961. }
  4962. }
  4963. }
  4964. if (this.isSkinnedMesh) {
  4965. object.bindMode = this.bindMode;
  4966. object.bindMatrix = this.bindMatrix.toArray();
  4967. if (this.skeleton !== undefined) {
  4968. serialize(meta.skeletons, this.skeleton);
  4969. object.skeleton = this.skeleton.uuid;
  4970. }
  4971. }
  4972. if (this.material !== undefined) {
  4973. if (Array.isArray(this.material)) {
  4974. const uuids = [];
  4975. for (let i = 0, l = this.material.length; i < l; i++) {
  4976. uuids.push(serialize(meta.materials, this.material[i]));
  4977. }
  4978. object.material = uuids;
  4979. } else {
  4980. object.material = serialize(meta.materials, this.material);
  4981. }
  4982. } //
  4983. if (this.children.length > 0) {
  4984. object.children = [];
  4985. for (let i = 0; i < this.children.length; i++) {
  4986. object.children.push(this.children[i].toJSON(meta).object);
  4987. }
  4988. } //
  4989. if (this.animations.length > 0) {
  4990. object.animations = [];
  4991. for (let i = 0; i < this.animations.length; i++) {
  4992. const animation = this.animations[i];
  4993. object.animations.push(serialize(meta.animations, animation));
  4994. }
  4995. }
  4996. if (isRootObject) {
  4997. const geometries = extractFromCache(meta.geometries);
  4998. const materials = extractFromCache(meta.materials);
  4999. const textures = extractFromCache(meta.textures);
  5000. const images = extractFromCache(meta.images);
  5001. const shapes = extractFromCache(meta.shapes);
  5002. const skeletons = extractFromCache(meta.skeletons);
  5003. const animations = extractFromCache(meta.animations);
  5004. if (geometries.length > 0) output.geometries = geometries;
  5005. if (materials.length > 0) output.materials = materials;
  5006. if (textures.length > 0) output.textures = textures;
  5007. if (images.length > 0) output.images = images;
  5008. if (shapes.length > 0) output.shapes = shapes;
  5009. if (skeletons.length > 0) output.skeletons = skeletons;
  5010. if (animations.length > 0) output.animations = animations;
  5011. }
  5012. output.object = object;
  5013. return output; // extract data from the cache hash
  5014. // remove metadata on each item
  5015. // and return as array
  5016. function extractFromCache(cache) {
  5017. const values = [];
  5018. for (const key in cache) {
  5019. const data = cache[key];
  5020. delete data.metadata;
  5021. values.push(data);
  5022. }
  5023. return values;
  5024. }
  5025. },
  5026. clone: function (recursive) {
  5027. return new this.constructor().copy(this, recursive);
  5028. },
  5029. copy: function (source, recursive = true) {
  5030. this.name = source.name;
  5031. this.up.copy(source.up);
  5032. this.position.copy(source.position);
  5033. this.rotation.order = source.rotation.order;
  5034. this.quaternion.copy(source.quaternion);
  5035. this.scale.copy(source.scale);
  5036. this.matrix.copy(source.matrix);
  5037. this.matrixWorld.copy(source.matrixWorld);
  5038. this.matrixAutoUpdate = source.matrixAutoUpdate;
  5039. this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;
  5040. this.layers.mask = source.layers.mask;
  5041. this.visible = source.visible;
  5042. this.castShadow = source.castShadow;
  5043. this.receiveShadow = source.receiveShadow;
  5044. this.frustumCulled = source.frustumCulled;
  5045. this.renderOrder = source.renderOrder;
  5046. this.userData = JSON.parse(JSON.stringify(source.userData));
  5047. if (recursive === true) {
  5048. for (let i = 0; i < source.children.length; i++) {
  5049. const child = source.children[i];
  5050. this.add(child.clone());
  5051. }
  5052. }
  5053. return this;
  5054. }
  5055. });
  5056. const _vector1 =
  5057. /*@__PURE__*/
  5058. new Vector3();
  5059. const _vector2 =
  5060. /*@__PURE__*/
  5061. new Vector3();
  5062. const _normalMatrix =
  5063. /*@__PURE__*/
  5064. new Matrix3();
  5065. class Plane {
  5066. constructor(normal, constant) {
  5067. Object.defineProperty(this, 'isPlane', {
  5068. value: true
  5069. }); // normal is assumed to be normalized
  5070. this.normal = normal !== undefined ? normal : new Vector3(1, 0, 0);
  5071. this.constant = constant !== undefined ? constant : 0;
  5072. }
  5073. set(normal, constant) {
  5074. this.normal.copy(normal);
  5075. this.constant = constant;
  5076. return this;
  5077. }
  5078. setComponents(x, y, z, w) {
  5079. this.normal.set(x, y, z);
  5080. this.constant = w;
  5081. return this;
  5082. }
  5083. setFromNormalAndCoplanarPoint(normal, point) {
  5084. this.normal.copy(normal);
  5085. this.constant = -point.dot(this.normal);
  5086. return this;
  5087. }
  5088. setFromCoplanarPoints(a, b, c) {
  5089. const normal = _vector1.subVectors(c, b).cross(_vector2.subVectors(a, b)).normalize(); // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  5090. this.setFromNormalAndCoplanarPoint(normal, a);
  5091. return this;
  5092. }
  5093. clone() {
  5094. return new this.constructor().copy(this);
  5095. }
  5096. copy(plane) {
  5097. this.normal.copy(plane.normal);
  5098. this.constant = plane.constant;
  5099. return this;
  5100. }
  5101. normalize() {
  5102. // Note: will lead to a divide by zero if the plane is invalid.
  5103. const inverseNormalLength = 1.0 / this.normal.length();
  5104. this.normal.multiplyScalar(inverseNormalLength);
  5105. this.constant *= inverseNormalLength;
  5106. return this;
  5107. }
  5108. negate() {
  5109. this.constant *= -1;
  5110. this.normal.negate();
  5111. return this;
  5112. }
  5113. distanceToPoint(point) {
  5114. return this.normal.dot(point) + this.constant;
  5115. }
  5116. distanceToSphere(sphere) {
  5117. return this.distanceToPoint(sphere.center) - sphere.radius;
  5118. }
  5119. projectPoint(point, target) {
  5120. if (target === undefined) {
  5121. console.warn('THREE.Plane: .projectPoint() target is now required');
  5122. target = new Vector3();
  5123. }
  5124. return target.copy(this.normal).multiplyScalar(-this.distanceToPoint(point)).add(point);
  5125. }
  5126. intersectLine(line, target) {
  5127. if (target === undefined) {
  5128. console.warn('THREE.Plane: .intersectLine() target is now required');
  5129. target = new Vector3();
  5130. }
  5131. const direction = line.delta(_vector1);
  5132. const denominator = this.normal.dot(direction);
  5133. if (denominator === 0) {
  5134. // line is coplanar, return origin
  5135. if (this.distanceToPoint(line.start) === 0) {
  5136. return target.copy(line.start);
  5137. } // Unsure if this is the correct method to handle this case.
  5138. return undefined;
  5139. }
  5140. const t = -(line.start.dot(this.normal) + this.constant) / denominator;
  5141. if (t < 0 || t > 1) {
  5142. return undefined;
  5143. }
  5144. return target.copy(direction).multiplyScalar(t).add(line.start);
  5145. }
  5146. intersectsLine(line) {
  5147. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  5148. const startSign = this.distanceToPoint(line.start);
  5149. const endSign = this.distanceToPoint(line.end);
  5150. return startSign < 0 && endSign > 0 || endSign < 0 && startSign > 0;
  5151. }
  5152. intersectsBox(box) {
  5153. return box.intersectsPlane(this);
  5154. }
  5155. intersectsSphere(sphere) {
  5156. return sphere.intersectsPlane(this);
  5157. }
  5158. coplanarPoint(target) {
  5159. if (target === undefined) {
  5160. console.warn('THREE.Plane: .coplanarPoint() target is now required');
  5161. target = new Vector3();
  5162. }
  5163. return target.copy(this.normal).multiplyScalar(-this.constant);
  5164. }
  5165. applyMatrix4(matrix, optionalNormalMatrix) {
  5166. const normalMatrix = optionalNormalMatrix || _normalMatrix.getNormalMatrix(matrix);
  5167. const referencePoint = this.coplanarPoint(_vector1).applyMatrix4(matrix);
  5168. const normal = this.normal.applyMatrix3(normalMatrix).normalize();
  5169. this.constant = -referencePoint.dot(normal);
  5170. return this;
  5171. }
  5172. translate(offset) {
  5173. this.constant -= offset.dot(this.normal);
  5174. return this;
  5175. }
  5176. equals(plane) {
  5177. return plane.normal.equals(this.normal) && plane.constant === this.constant;
  5178. }
  5179. }
  5180. exports.Plane = Plane;
  5181. const _v0$1 =
  5182. /*@__PURE__*/
  5183. new Vector3();
  5184. const _v1$3 =
  5185. /*@__PURE__*/
  5186. new Vector3();
  5187. const _v2$1 =
  5188. /*@__PURE__*/
  5189. new Vector3();
  5190. const _v3 =
  5191. /*@__PURE__*/
  5192. new Vector3();
  5193. const _vab =
  5194. /*@__PURE__*/
  5195. new Vector3();
  5196. const _vac =
  5197. /*@__PURE__*/
  5198. new Vector3();
  5199. const _vbc =
  5200. /*@__PURE__*/
  5201. new Vector3();
  5202. const _vap =
  5203. /*@__PURE__*/
  5204. new Vector3();
  5205. const _vbp =
  5206. /*@__PURE__*/
  5207. new Vector3();
  5208. const _vcp =
  5209. /*@__PURE__*/
  5210. new Vector3();
  5211. class Triangle {
  5212. constructor(a, b, c) {
  5213. this.a = a !== undefined ? a : new Vector3();
  5214. this.b = b !== undefined ? b : new Vector3();
  5215. this.c = c !== undefined ? c : new Vector3();
  5216. }
  5217. static getNormal(a, b, c, target) {
  5218. if (target === undefined) {
  5219. console.warn('THREE.Triangle: .getNormal() target is now required');
  5220. target = new Vector3();
  5221. }
  5222. target.subVectors(c, b);
  5223. _v0$1.subVectors(a, b);
  5224. target.cross(_v0$1);
  5225. const targetLengthSq = target.lengthSq();
  5226. if (targetLengthSq > 0) {
  5227. return target.multiplyScalar(1 / Math.sqrt(targetLengthSq));
  5228. }
  5229. return target.set(0, 0, 0);
  5230. } // static/instance method to calculate barycentric coordinates
  5231. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  5232. static getBarycoord(point, a, b, c, target) {
  5233. _v0$1.subVectors(c, a);
  5234. _v1$3.subVectors(b, a);
  5235. _v2$1.subVectors(point, a);
  5236. const dot00 = _v0$1.dot(_v0$1);
  5237. const dot01 = _v0$1.dot(_v1$3);
  5238. const dot02 = _v0$1.dot(_v2$1);
  5239. const dot11 = _v1$3.dot(_v1$3);
  5240. const dot12 = _v1$3.dot(_v2$1);
  5241. const denom = dot00 * dot11 - dot01 * dot01;
  5242. if (target === undefined) {
  5243. console.warn('THREE.Triangle: .getBarycoord() target is now required');
  5244. target = new Vector3();
  5245. } // collinear or singular triangle
  5246. if (denom === 0) {
  5247. // arbitrary location outside of triangle?
  5248. // not sure if this is the best idea, maybe should be returning undefined
  5249. return target.set(-2, -1, -1);
  5250. }
  5251. const invDenom = 1 / denom;
  5252. const u = (dot11 * dot02 - dot01 * dot12) * invDenom;
  5253. const v = (dot00 * dot12 - dot01 * dot02) * invDenom; // barycentric coordinates must always sum to 1
  5254. return target.set(1 - u - v, v, u);
  5255. }
  5256. static containsPoint(point, a, b, c) {
  5257. this.getBarycoord(point, a, b, c, _v3);
  5258. return _v3.x >= 0 && _v3.y >= 0 && _v3.x + _v3.y <= 1;
  5259. }
  5260. static getUV(point, p1, p2, p3, uv1, uv2, uv3, target) {
  5261. this.getBarycoord(point, p1, p2, p3, _v3);
  5262. target.set(0, 0);
  5263. target.addScaledVector(uv1, _v3.x);
  5264. target.addScaledVector(uv2, _v3.y);
  5265. target.addScaledVector(uv3, _v3.z);
  5266. return target;
  5267. }
  5268. static isFrontFacing(a, b, c, direction) {
  5269. _v0$1.subVectors(c, b);
  5270. _v1$3.subVectors(a, b); // strictly front facing
  5271. return _v0$1.cross(_v1$3).dot(direction) < 0 ? true : false;
  5272. }
  5273. set(a, b, c) {
  5274. this.a.copy(a);
  5275. this.b.copy(b);
  5276. this.c.copy(c);
  5277. return this;
  5278. }
  5279. setFromPointsAndIndices(points, i0, i1, i2) {
  5280. this.a.copy(points[i0]);
  5281. this.b.copy(points[i1]);
  5282. this.c.copy(points[i2]);
  5283. return this;
  5284. }
  5285. clone() {
  5286. return new this.constructor().copy(this);
  5287. }
  5288. copy(triangle) {
  5289. this.a.copy(triangle.a);
  5290. this.b.copy(triangle.b);
  5291. this.c.copy(triangle.c);
  5292. return this;
  5293. }
  5294. getArea() {
  5295. _v0$1.subVectors(this.c, this.b);
  5296. _v1$3.subVectors(this.a, this.b);
  5297. return _v0$1.cross(_v1$3).length() * 0.5;
  5298. }
  5299. getMidpoint(target) {
  5300. if (target === undefined) {
  5301. console.warn('THREE.Triangle: .getMidpoint() target is now required');
  5302. target = new Vector3();
  5303. }
  5304. return target.addVectors(this.a, this.b).add(this.c).multiplyScalar(1 / 3);
  5305. }
  5306. getNormal(target) {
  5307. return Triangle.getNormal(this.a, this.b, this.c, target);
  5308. }
  5309. getPlane(target) {
  5310. if (target === undefined) {
  5311. console.warn('THREE.Triangle: .getPlane() target is now required');
  5312. target = new Plane();
  5313. }
  5314. return target.setFromCoplanarPoints(this.a, this.b, this.c);
  5315. }
  5316. getBarycoord(point, target) {
  5317. return Triangle.getBarycoord(point, this.a, this.b, this.c, target);
  5318. }
  5319. getUV(point, uv1, uv2, uv3, target) {
  5320. return Triangle.getUV(point, this.a, this.b, this.c, uv1, uv2, uv3, target);
  5321. }
  5322. containsPoint(point) {
  5323. return Triangle.containsPoint(point, this.a, this.b, this.c);
  5324. }
  5325. isFrontFacing(direction) {
  5326. return Triangle.isFrontFacing(this.a, this.b, this.c, direction);
  5327. }
  5328. intersectsBox(box) {
  5329. return box.intersectsTriangle(this);
  5330. }
  5331. closestPointToPoint(p, target) {
  5332. if (target === undefined) {
  5333. console.warn('THREE.Triangle: .closestPointToPoint() target is now required');
  5334. target = new Vector3();
  5335. }
  5336. const a = this.a,
  5337. b = this.b,
  5338. c = this.c;
  5339. let v, w; // algorithm thanks to Real-Time Collision Detection by Christer Ericson,
  5340. // published by Morgan Kaufmann Publishers, (c) 2005 Elsevier Inc.,
  5341. // under the accompanying license; see chapter 5.1.5 for detailed explanation.
  5342. // basically, we're distinguishing which of the voronoi regions of the triangle
  5343. // the point lies in with the minimum amount of redundant computation.
  5344. _vab.subVectors(b, a);
  5345. _vac.subVectors(c, a);
  5346. _vap.subVectors(p, a);
  5347. const d1 = _vab.dot(_vap);
  5348. const d2 = _vac.dot(_vap);
  5349. if (d1 <= 0 && d2 <= 0) {
  5350. // vertex region of A; barycentric coords (1, 0, 0)
  5351. return target.copy(a);
  5352. }
  5353. _vbp.subVectors(p, b);
  5354. const d3 = _vab.dot(_vbp);
  5355. const d4 = _vac.dot(_vbp);
  5356. if (d3 >= 0 && d4 <= d3) {
  5357. // vertex region of B; barycentric coords (0, 1, 0)
  5358. return target.copy(b);
  5359. }
  5360. const vc = d1 * d4 - d3 * d2;
  5361. if (vc <= 0 && d1 >= 0 && d3 <= 0) {
  5362. v = d1 / (d1 - d3); // edge region of AB; barycentric coords (1-v, v, 0)
  5363. return target.copy(a).addScaledVector(_vab, v);
  5364. }
  5365. _vcp.subVectors(p, c);
  5366. const d5 = _vab.dot(_vcp);
  5367. const d6 = _vac.dot(_vcp);
  5368. if (d6 >= 0 && d5 <= d6) {
  5369. // vertex region of C; barycentric coords (0, 0, 1)
  5370. return target.copy(c);
  5371. }
  5372. const vb = d5 * d2 - d1 * d6;
  5373. if (vb <= 0 && d2 >= 0 && d6 <= 0) {
  5374. w = d2 / (d2 - d6); // edge region of AC; barycentric coords (1-w, 0, w)
  5375. return target.copy(a).addScaledVector(_vac, w);
  5376. }
  5377. const va = d3 * d6 - d5 * d4;
  5378. if (va <= 0 && d4 - d3 >= 0 && d5 - d6 >= 0) {
  5379. _vbc.subVectors(c, b);
  5380. w = (d4 - d3) / (d4 - d3 + (d5 - d6)); // edge region of BC; barycentric coords (0, 1-w, w)
  5381. return target.copy(b).addScaledVector(_vbc, w); // edge region of BC
  5382. } // face region
  5383. const denom = 1 / (va + vb + vc); // u = va * denom
  5384. v = vb * denom;
  5385. w = vc * denom;
  5386. return target.copy(a).addScaledVector(_vab, v).addScaledVector(_vac, w);
  5387. }
  5388. equals(triangle) {
  5389. return triangle.a.equals(this.a) && triangle.b.equals(this.b) && triangle.c.equals(this.c);
  5390. }
  5391. }
  5392. exports.Triangle = Triangle;
  5393. const _colorKeywords = {
  5394. 'aliceblue': 0xF0F8FF,
  5395. 'antiquewhite': 0xFAEBD7,
  5396. 'aqua': 0x00FFFF,
  5397. 'aquamarine': 0x7FFFD4,
  5398. 'azure': 0xF0FFFF,
  5399. 'beige': 0xF5F5DC,
  5400. 'bisque': 0xFFE4C4,
  5401. 'black': 0x000000,
  5402. 'blanchedalmond': 0xFFEBCD,
  5403. 'blue': 0x0000FF,
  5404. 'blueviolet': 0x8A2BE2,
  5405. 'brown': 0xA52A2A,
  5406. 'burlywood': 0xDEB887,
  5407. 'cadetblue': 0x5F9EA0,
  5408. 'chartreuse': 0x7FFF00,
  5409. 'chocolate': 0xD2691E,
  5410. 'coral': 0xFF7F50,
  5411. 'cornflowerblue': 0x6495ED,
  5412. 'cornsilk': 0xFFF8DC,
  5413. 'crimson': 0xDC143C,
  5414. 'cyan': 0x00FFFF,
  5415. 'darkblue': 0x00008B,
  5416. 'darkcyan': 0x008B8B,
  5417. 'darkgoldenrod': 0xB8860B,
  5418. 'darkgray': 0xA9A9A9,
  5419. 'darkgreen': 0x006400,
  5420. 'darkgrey': 0xA9A9A9,
  5421. 'darkkhaki': 0xBDB76B,
  5422. 'darkmagenta': 0x8B008B,
  5423. 'darkolivegreen': 0x556B2F,
  5424. 'darkorange': 0xFF8C00,
  5425. 'darkorchid': 0x9932CC,
  5426. 'darkred': 0x8B0000,
  5427. 'darksalmon': 0xE9967A,
  5428. 'darkseagreen': 0x8FBC8F,
  5429. 'darkslateblue': 0x483D8B,
  5430. 'darkslategray': 0x2F4F4F,
  5431. 'darkslategrey': 0x2F4F4F,
  5432. 'darkturquoise': 0x00CED1,
  5433. 'darkviolet': 0x9400D3,
  5434. 'deeppink': 0xFF1493,
  5435. 'deepskyblue': 0x00BFFF,
  5436. 'dimgray': 0x696969,
  5437. 'dimgrey': 0x696969,
  5438. 'dodgerblue': 0x1E90FF,
  5439. 'firebrick': 0xB22222,
  5440. 'floralwhite': 0xFFFAF0,
  5441. 'forestgreen': 0x228B22,
  5442. 'fuchsia': 0xFF00FF,
  5443. 'gainsboro': 0xDCDCDC,
  5444. 'ghostwhite': 0xF8F8FF,
  5445. 'gold': 0xFFD700,
  5446. 'goldenrod': 0xDAA520,
  5447. 'gray': 0x808080,
  5448. 'green': 0x008000,
  5449. 'greenyellow': 0xADFF2F,
  5450. 'grey': 0x808080,
  5451. 'honeydew': 0xF0FFF0,
  5452. 'hotpink': 0xFF69B4,
  5453. 'indianred': 0xCD5C5C,
  5454. 'indigo': 0x4B0082,
  5455. 'ivory': 0xFFFFF0,
  5456. 'khaki': 0xF0E68C,
  5457. 'lavender': 0xE6E6FA,
  5458. 'lavenderblush': 0xFFF0F5,
  5459. 'lawngreen': 0x7CFC00,
  5460. 'lemonchiffon': 0xFFFACD,
  5461. 'lightblue': 0xADD8E6,
  5462. 'lightcoral': 0xF08080,
  5463. 'lightcyan': 0xE0FFFF,
  5464. 'lightgoldenrodyellow': 0xFAFAD2,
  5465. 'lightgray': 0xD3D3D3,
  5466. 'lightgreen': 0x90EE90,
  5467. 'lightgrey': 0xD3D3D3,
  5468. 'lightpink': 0xFFB6C1,
  5469. 'lightsalmon': 0xFFA07A,
  5470. 'lightseagreen': 0x20B2AA,
  5471. 'lightskyblue': 0x87CEFA,
  5472. 'lightslategray': 0x778899,
  5473. 'lightslategrey': 0x778899,
  5474. 'lightsteelblue': 0xB0C4DE,
  5475. 'lightyellow': 0xFFFFE0,
  5476. 'lime': 0x00FF00,
  5477. 'limegreen': 0x32CD32,
  5478. 'linen': 0xFAF0E6,
  5479. 'magenta': 0xFF00FF,
  5480. 'maroon': 0x800000,
  5481. 'mediumaquamarine': 0x66CDAA,
  5482. 'mediumblue': 0x0000CD,
  5483. 'mediumorchid': 0xBA55D3,
  5484. 'mediumpurple': 0x9370DB,
  5485. 'mediumseagreen': 0x3CB371,
  5486. 'mediumslateblue': 0x7B68EE,
  5487. 'mediumspringgreen': 0x00FA9A,
  5488. 'mediumturquoise': 0x48D1CC,
  5489. 'mediumvioletred': 0xC71585,
  5490. 'midnightblue': 0x191970,
  5491. 'mintcream': 0xF5FFFA,
  5492. 'mistyrose': 0xFFE4E1,
  5493. 'moccasin': 0xFFE4B5,
  5494. 'navajowhite': 0xFFDEAD,
  5495. 'navy': 0x000080,
  5496. 'oldlace': 0xFDF5E6,
  5497. 'olive': 0x808000,
  5498. 'olivedrab': 0x6B8E23,
  5499. 'orange': 0xFFA500,
  5500. 'orangered': 0xFF4500,
  5501. 'orchid': 0xDA70D6,
  5502. 'palegoldenrod': 0xEEE8AA,
  5503. 'palegreen': 0x98FB98,
  5504. 'paleturquoise': 0xAFEEEE,
  5505. 'palevioletred': 0xDB7093,
  5506. 'papayawhip': 0xFFEFD5,
  5507. 'peachpuff': 0xFFDAB9,
  5508. 'peru': 0xCD853F,
  5509. 'pink': 0xFFC0CB,
  5510. 'plum': 0xDDA0DD,
  5511. 'powderblue': 0xB0E0E6,
  5512. 'purple': 0x800080,
  5513. 'rebeccapurple': 0x663399,
  5514. 'red': 0xFF0000,
  5515. 'rosybrown': 0xBC8F8F,
  5516. 'royalblue': 0x4169E1,
  5517. 'saddlebrown': 0x8B4513,
  5518. 'salmon': 0xFA8072,
  5519. 'sandybrown': 0xF4A460,
  5520. 'seagreen': 0x2E8B57,
  5521. 'seashell': 0xFFF5EE,
  5522. 'sienna': 0xA0522D,
  5523. 'silver': 0xC0C0C0,
  5524. 'skyblue': 0x87CEEB,
  5525. 'slateblue': 0x6A5ACD,
  5526. 'slategray': 0x708090,
  5527. 'slategrey': 0x708090,
  5528. 'snow': 0xFFFAFA,
  5529. 'springgreen': 0x00FF7F,
  5530. 'steelblue': 0x4682B4,
  5531. 'tan': 0xD2B48C,
  5532. 'teal': 0x008080,
  5533. 'thistle': 0xD8BFD8,
  5534. 'tomato': 0xFF6347,
  5535. 'turquoise': 0x40E0D0,
  5536. 'violet': 0xEE82EE,
  5537. 'wheat': 0xF5DEB3,
  5538. 'white': 0xFFFFFF,
  5539. 'whitesmoke': 0xF5F5F5,
  5540. 'yellow': 0xFFFF00,
  5541. 'yellowgreen': 0x9ACD32
  5542. };
  5543. const _hslA = {
  5544. h: 0,
  5545. s: 0,
  5546. l: 0
  5547. };
  5548. const _hslB = {
  5549. h: 0,
  5550. s: 0,
  5551. l: 0
  5552. };
  5553. function hue2rgb(p, q, t) {
  5554. if (t < 0) t += 1;
  5555. if (t > 1) t -= 1;
  5556. if (t < 1 / 6) return p + (q - p) * 6 * t;
  5557. if (t < 1 / 2) return q;
  5558. if (t < 2 / 3) return p + (q - p) * 6 * (2 / 3 - t);
  5559. return p;
  5560. }
  5561. function SRGBToLinear(c) {
  5562. return c < 0.04045 ? c * 0.0773993808 : Math.pow(c * 0.9478672986 + 0.0521327014, 2.4);
  5563. }
  5564. function LinearToSRGB(c) {
  5565. return c < 0.0031308 ? c * 12.92 : 1.055 * Math.pow(c, 0.41666) - 0.055;
  5566. }
  5567. class Color {
  5568. constructor(r, g, b) {
  5569. Object.defineProperty(this, 'isColor', {
  5570. value: true
  5571. });
  5572. if (g === undefined && b === undefined) {
  5573. // r is THREE.Color, hex or string
  5574. return this.set(r);
  5575. }
  5576. return this.setRGB(r, g, b);
  5577. }
  5578. set(value) {
  5579. if (value && value.isColor) {
  5580. this.copy(value);
  5581. } else if (typeof value === 'number') {
  5582. this.setHex(value);
  5583. } else if (typeof value === 'string') {
  5584. this.setStyle(value);
  5585. }
  5586. return this;
  5587. }
  5588. setScalar(scalar) {
  5589. this.r = scalar;
  5590. this.g = scalar;
  5591. this.b = scalar;
  5592. return this;
  5593. }
  5594. setHex(hex) {
  5595. hex = Math.floor(hex);
  5596. this.r = (hex >> 16 & 255) / 255;
  5597. this.g = (hex >> 8 & 255) / 255;
  5598. this.b = (hex & 255) / 255;
  5599. return this;
  5600. }
  5601. setRGB(r, g, b) {
  5602. this.r = r;
  5603. this.g = g;
  5604. this.b = b;
  5605. return this;
  5606. }
  5607. setHSL(h, s, l) {
  5608. // h,s,l ranges are in 0.0 - 1.0
  5609. h = MathUtils.euclideanModulo(h, 1);
  5610. s = MathUtils.clamp(s, 0, 1);
  5611. l = MathUtils.clamp(l, 0, 1);
  5612. if (s === 0) {
  5613. this.r = this.g = this.b = l;
  5614. } else {
  5615. const p = l <= 0.5 ? l * (1 + s) : l + s - l * s;
  5616. const q = 2 * l - p;
  5617. this.r = hue2rgb(q, p, h + 1 / 3);
  5618. this.g = hue2rgb(q, p, h);
  5619. this.b = hue2rgb(q, p, h - 1 / 3);
  5620. }
  5621. return this;
  5622. }
  5623. setStyle(style) {
  5624. function handleAlpha(string) {
  5625. if (string === undefined) return;
  5626. if (parseFloat(string) < 1) {
  5627. console.warn('THREE.Color: Alpha component of ' + style + ' will be ignored.');
  5628. }
  5629. }
  5630. let m;
  5631. if (m = /^((?:rgb|hsl)a?)\(\s*([^\)]*)\)/.exec(style)) {
  5632. // rgb / hsl
  5633. let color;
  5634. const name = m[1];
  5635. const components = m[2];
  5636. switch (name) {
  5637. case 'rgb':
  5638. case 'rgba':
  5639. if (color = /^(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec(components)) {
  5640. // rgb(255,0,0) rgba(255,0,0,0.5)
  5641. this.r = Math.min(255, parseInt(color[1], 10)) / 255;
  5642. this.g = Math.min(255, parseInt(color[2], 10)) / 255;
  5643. this.b = Math.min(255, parseInt(color[3], 10)) / 255;
  5644. handleAlpha(color[5]);
  5645. return this;
  5646. }
  5647. if (color = /^(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec(components)) {
  5648. // rgb(100%,0%,0%) rgba(100%,0%,0%,0.5)
  5649. this.r = Math.min(100, parseInt(color[1], 10)) / 100;
  5650. this.g = Math.min(100, parseInt(color[2], 10)) / 100;
  5651. this.b = Math.min(100, parseInt(color[3], 10)) / 100;
  5652. handleAlpha(color[5]);
  5653. return this;
  5654. }
  5655. break;
  5656. case 'hsl':
  5657. case 'hsla':
  5658. if (color = /^([0-9]*\.?[0-9]+)\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec(components)) {
  5659. // hsl(120,50%,50%) hsla(120,50%,50%,0.5)
  5660. const h = parseFloat(color[1]) / 360;
  5661. const s = parseInt(color[2], 10) / 100;
  5662. const l = parseInt(color[3], 10) / 100;
  5663. handleAlpha(color[5]);
  5664. return this.setHSL(h, s, l);
  5665. }
  5666. break;
  5667. }
  5668. } else if (m = /^\#([A-Fa-f0-9]+)$/.exec(style)) {
  5669. // hex color
  5670. const hex = m[1];
  5671. const size = hex.length;
  5672. if (size === 3) {
  5673. // #ff0
  5674. this.r = parseInt(hex.charAt(0) + hex.charAt(0), 16) / 255;
  5675. this.g = parseInt(hex.charAt(1) + hex.charAt(1), 16) / 255;
  5676. this.b = parseInt(hex.charAt(2) + hex.charAt(2), 16) / 255;
  5677. return this;
  5678. } else if (size === 6) {
  5679. // #ff0000
  5680. this.r = parseInt(hex.charAt(0) + hex.charAt(1), 16) / 255;
  5681. this.g = parseInt(hex.charAt(2) + hex.charAt(3), 16) / 255;
  5682. this.b = parseInt(hex.charAt(4) + hex.charAt(5), 16) / 255;
  5683. return this;
  5684. }
  5685. }
  5686. if (style && style.length > 0) {
  5687. return this.setColorName(style);
  5688. }
  5689. return this;
  5690. }
  5691. setColorName(style) {
  5692. // color keywords
  5693. const hex = _colorKeywords[style];
  5694. if (hex !== undefined) {
  5695. // red
  5696. this.setHex(hex);
  5697. } else {
  5698. // unknown color
  5699. console.warn('THREE.Color: Unknown color ' + style);
  5700. }
  5701. return this;
  5702. }
  5703. clone() {
  5704. return new this.constructor(this.r, this.g, this.b);
  5705. }
  5706. copy(color) {
  5707. this.r = color.r;
  5708. this.g = color.g;
  5709. this.b = color.b;
  5710. return this;
  5711. }
  5712. copyGammaToLinear(color, gammaFactor = 2.0) {
  5713. this.r = Math.pow(color.r, gammaFactor);
  5714. this.g = Math.pow(color.g, gammaFactor);
  5715. this.b = Math.pow(color.b, gammaFactor);
  5716. return this;
  5717. }
  5718. copyLinearToGamma(color, gammaFactor = 2.0) {
  5719. const safeInverse = gammaFactor > 0 ? 1.0 / gammaFactor : 1.0;
  5720. this.r = Math.pow(color.r, safeInverse);
  5721. this.g = Math.pow(color.g, safeInverse);
  5722. this.b = Math.pow(color.b, safeInverse);
  5723. return this;
  5724. }
  5725. convertGammaToLinear(gammaFactor) {
  5726. this.copyGammaToLinear(this, gammaFactor);
  5727. return this;
  5728. }
  5729. convertLinearToGamma(gammaFactor) {
  5730. this.copyLinearToGamma(this, gammaFactor);
  5731. return this;
  5732. }
  5733. copySRGBToLinear(color) {
  5734. this.r = SRGBToLinear(color.r);
  5735. this.g = SRGBToLinear(color.g);
  5736. this.b = SRGBToLinear(color.b);
  5737. return this;
  5738. }
  5739. copyLinearToSRGB(color) {
  5740. this.r = LinearToSRGB(color.r);
  5741. this.g = LinearToSRGB(color.g);
  5742. this.b = LinearToSRGB(color.b);
  5743. return this;
  5744. }
  5745. convertSRGBToLinear() {
  5746. this.copySRGBToLinear(this);
  5747. return this;
  5748. }
  5749. convertLinearToSRGB() {
  5750. this.copyLinearToSRGB(this);
  5751. return this;
  5752. }
  5753. getHex() {
  5754. return this.r * 255 << 16 ^ this.g * 255 << 8 ^ this.b * 255 << 0;
  5755. }
  5756. getHexString() {
  5757. return ('000000' + this.getHex().toString(16)).slice(-6);
  5758. }
  5759. getHSL(target) {
  5760. // h,s,l ranges are in 0.0 - 1.0
  5761. if (target === undefined) {
  5762. console.warn('THREE.Color: .getHSL() target is now required');
  5763. target = {
  5764. h: 0,
  5765. s: 0,
  5766. l: 0
  5767. };
  5768. }
  5769. const r = this.r,
  5770. g = this.g,
  5771. b = this.b;
  5772. const max = Math.max(r, g, b);
  5773. const min = Math.min(r, g, b);
  5774. let hue, saturation;
  5775. const lightness = (min + max) / 2.0;
  5776. if (min === max) {
  5777. hue = 0;
  5778. saturation = 0;
  5779. } else {
  5780. const delta = max - min;
  5781. saturation = lightness <= 0.5 ? delta / (max + min) : delta / (2 - max - min);
  5782. switch (max) {
  5783. case r:
  5784. hue = (g - b) / delta + (g < b ? 6 : 0);
  5785. break;
  5786. case g:
  5787. hue = (b - r) / delta + 2;
  5788. break;
  5789. case b:
  5790. hue = (r - g) / delta + 4;
  5791. break;
  5792. }
  5793. hue /= 6;
  5794. }
  5795. target.h = hue;
  5796. target.s = saturation;
  5797. target.l = lightness;
  5798. return target;
  5799. }
  5800. getStyle() {
  5801. return 'rgb(' + (this.r * 255 | 0) + ',' + (this.g * 255 | 0) + ',' + (this.b * 255 | 0) + ')';
  5802. }
  5803. offsetHSL(h, s, l) {
  5804. this.getHSL(_hslA);
  5805. _hslA.h += h;
  5806. _hslA.s += s;
  5807. _hslA.l += l;
  5808. this.setHSL(_hslA.h, _hslA.s, _hslA.l);
  5809. return this;
  5810. }
  5811. add(color) {
  5812. this.r += color.r;
  5813. this.g += color.g;
  5814. this.b += color.b;
  5815. return this;
  5816. }
  5817. addColors(color1, color2) {
  5818. this.r = color1.r + color2.r;
  5819. this.g = color1.g + color2.g;
  5820. this.b = color1.b + color2.b;
  5821. return this;
  5822. }
  5823. addScalar(s) {
  5824. this.r += s;
  5825. this.g += s;
  5826. this.b += s;
  5827. return this;
  5828. }
  5829. sub(color) {
  5830. this.r = Math.max(0, this.r - color.r);
  5831. this.g = Math.max(0, this.g - color.g);
  5832. this.b = Math.max(0, this.b - color.b);
  5833. return this;
  5834. }
  5835. multiply(color) {
  5836. this.r *= color.r;
  5837. this.g *= color.g;
  5838. this.b *= color.b;
  5839. return this;
  5840. }
  5841. multiplyScalar(s) {
  5842. this.r *= s;
  5843. this.g *= s;
  5844. this.b *= s;
  5845. return this;
  5846. }
  5847. lerp(color, alpha) {
  5848. this.r += (color.r - this.r) * alpha;
  5849. this.g += (color.g - this.g) * alpha;
  5850. this.b += (color.b - this.b) * alpha;
  5851. return this;
  5852. }
  5853. lerpHSL(color, alpha) {
  5854. this.getHSL(_hslA);
  5855. color.getHSL(_hslB);
  5856. const h = MathUtils.lerp(_hslA.h, _hslB.h, alpha);
  5857. const s = MathUtils.lerp(_hslA.s, _hslB.s, alpha);
  5858. const l = MathUtils.lerp(_hslA.l, _hslB.l, alpha);
  5859. this.setHSL(h, s, l);
  5860. return this;
  5861. }
  5862. equals(c) {
  5863. return c.r === this.r && c.g === this.g && c.b === this.b;
  5864. }
  5865. fromArray(array, offset = 0) {
  5866. this.r = array[offset];
  5867. this.g = array[offset + 1];
  5868. this.b = array[offset + 2];
  5869. return this;
  5870. }
  5871. toArray(array = [], offset = 0) {
  5872. array[offset] = this.r;
  5873. array[offset + 1] = this.g;
  5874. array[offset + 2] = this.b;
  5875. return array;
  5876. }
  5877. fromBufferAttribute(attribute, index) {
  5878. this.r = attribute.getX(index);
  5879. this.g = attribute.getY(index);
  5880. this.b = attribute.getZ(index);
  5881. if (attribute.normalized === true) {
  5882. // assuming Uint8Array
  5883. this.r /= 255;
  5884. this.g /= 255;
  5885. this.b /= 255;
  5886. }
  5887. return this;
  5888. }
  5889. toJSON() {
  5890. return this.getHex();
  5891. }
  5892. }
  5893. exports.Color = Color;
  5894. Color.NAMES = _colorKeywords;
  5895. Color.prototype.r = 1;
  5896. Color.prototype.g = 1;
  5897. Color.prototype.b = 1;
  5898. class Face3 {
  5899. constructor(a, b, c, normal, color, materialIndex = 0) {
  5900. this.a = a;
  5901. this.b = b;
  5902. this.c = c;
  5903. this.normal = normal && normal.isVector3 ? normal : new Vector3();
  5904. this.vertexNormals = Array.isArray(normal) ? normal : [];
  5905. this.color = color && color.isColor ? color : new Color();
  5906. this.vertexColors = Array.isArray(color) ? color : [];
  5907. this.materialIndex = materialIndex;
  5908. }
  5909. clone() {
  5910. return new this.constructor().copy(this);
  5911. }
  5912. copy(source) {
  5913. this.a = source.a;
  5914. this.b = source.b;
  5915. this.c = source.c;
  5916. this.normal.copy(source.normal);
  5917. this.color.copy(source.color);
  5918. this.materialIndex = source.materialIndex;
  5919. for (let i = 0, il = source.vertexNormals.length; i < il; i++) {
  5920. this.vertexNormals[i] = source.vertexNormals[i].clone();
  5921. }
  5922. for (let i = 0, il = source.vertexColors.length; i < il; i++) {
  5923. this.vertexColors[i] = source.vertexColors[i].clone();
  5924. }
  5925. return this;
  5926. }
  5927. }
  5928. exports.Face3 = Face3;
  5929. let materialId = 0;
  5930. function Material() {
  5931. Object.defineProperty(this, 'id', {
  5932. value: materialId++
  5933. });
  5934. this.uuid = MathUtils.generateUUID();
  5935. this.name = '';
  5936. this.type = 'Material';
  5937. this.fog = true;
  5938. this.blending = NormalBlending;
  5939. this.side = FrontSide;
  5940. this.flatShading = false;
  5941. this.vertexColors = false;
  5942. this.opacity = 1;
  5943. this.transparent = false;
  5944. this.blendSrc = SrcAlphaFactor;
  5945. this.blendDst = OneMinusSrcAlphaFactor;
  5946. this.blendEquation = AddEquation;
  5947. this.blendSrcAlpha = null;
  5948. this.blendDstAlpha = null;
  5949. this.blendEquationAlpha = null;
  5950. this.depthFunc = LessEqualDepth;
  5951. this.depthTest = true;
  5952. this.depthWrite = true;
  5953. this.stencilWriteMask = 0xff;
  5954. this.stencilFunc = AlwaysStencilFunc;
  5955. this.stencilRef = 0;
  5956. this.stencilFuncMask = 0xff;
  5957. this.stencilFail = KeepStencilOp;
  5958. this.stencilZFail = KeepStencilOp;
  5959. this.stencilZPass = KeepStencilOp;
  5960. this.stencilWrite = false;
  5961. this.clippingPlanes = null;
  5962. this.clipIntersection = false;
  5963. this.clipShadows = false;
  5964. this.shadowSide = null;
  5965. this.colorWrite = true;
  5966. this.precision = null; // override the renderer's default precision for this material
  5967. this.polygonOffset = false;
  5968. this.polygonOffsetFactor = 0;
  5969. this.polygonOffsetUnits = 0;
  5970. this.dithering = false;
  5971. this.alphaTest = 0;
  5972. this.premultipliedAlpha = false;
  5973. this.visible = true;
  5974. this.toneMapped = true;
  5975. this.userData = {};
  5976. this.version = 0;
  5977. }
  5978. Material.prototype = Object.assign(Object.create(EventDispatcher.prototype), {
  5979. constructor: Material,
  5980. isMaterial: true,
  5981. onBeforeCompile: function ()
  5982. /* shaderobject, renderer */
  5983. {},
  5984. customProgramCacheKey: function () {
  5985. return this.onBeforeCompile.toString();
  5986. },
  5987. setValues: function (values) {
  5988. if (values === undefined) return;
  5989. for (const key in values) {
  5990. const newValue = values[key];
  5991. if (newValue === undefined) {
  5992. console.warn("THREE.Material: '" + key + "' parameter is undefined.");
  5993. continue;
  5994. } // for backward compatability if shading is set in the constructor
  5995. if (key === 'shading') {
  5996. console.warn('THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.');
  5997. this.flatShading = newValue === FlatShading ? true : false;
  5998. continue;
  5999. }
  6000. const currentValue = this[key];
  6001. if (currentValue === undefined) {
  6002. console.warn("THREE." + this.type + ": '" + key + "' is not a property of this material.");
  6003. continue;
  6004. }
  6005. if (currentValue && currentValue.isColor) {
  6006. currentValue.set(newValue);
  6007. } else if (currentValue && currentValue.isVector3 && newValue && newValue.isVector3) {
  6008. currentValue.copy(newValue);
  6009. } else {
  6010. this[key] = newValue;
  6011. }
  6012. }
  6013. },
  6014. toJSON: function (meta) {
  6015. const isRoot = meta === undefined || typeof meta === 'string';
  6016. if (isRoot) {
  6017. meta = {
  6018. textures: {},
  6019. images: {}
  6020. };
  6021. }
  6022. const data = {
  6023. metadata: {
  6024. version: 4.5,
  6025. type: 'Material',
  6026. generator: 'Material.toJSON'
  6027. }
  6028. }; // standard Material serialization
  6029. data.uuid = this.uuid;
  6030. data.type = this.type;
  6031. if (this.name !== '') data.name = this.name;
  6032. if (this.color && this.color.isColor) data.color = this.color.getHex();
  6033. if (this.roughness !== undefined) data.roughness = this.roughness;
  6034. if (this.metalness !== undefined) data.metalness = this.metalness;
  6035. if (this.sheen && this.sheen.isColor) data.sheen = this.sheen.getHex();
  6036. if (this.emissive && this.emissive.isColor) data.emissive = this.emissive.getHex();
  6037. if (this.emissiveIntensity && this.emissiveIntensity !== 1) data.emissiveIntensity = this.emissiveIntensity;
  6038. if (this.specular && this.specular.isColor) data.specular = this.specular.getHex();
  6039. if (this.shininess !== undefined) data.shininess = this.shininess;
  6040. if (this.clearcoat !== undefined) data.clearcoat = this.clearcoat;
  6041. if (this.clearcoatRoughness !== undefined) data.clearcoatRoughness = this.clearcoatRoughness;
  6042. if (this.clearcoatMap && this.clearcoatMap.isTexture) {
  6043. data.clearcoatMap = this.clearcoatMap.toJSON(meta).uuid;
  6044. }
  6045. if (this.clearcoatRoughnessMap && this.clearcoatRoughnessMap.isTexture) {
  6046. data.clearcoatRoughnessMap = this.clearcoatRoughnessMap.toJSON(meta).uuid;
  6047. }
  6048. if (this.clearcoatNormalMap && this.clearcoatNormalMap.isTexture) {
  6049. data.clearcoatNormalMap = this.clearcoatNormalMap.toJSON(meta).uuid;
  6050. data.clearcoatNormalScale = this.clearcoatNormalScale.toArray();
  6051. }
  6052. if (this.map && this.map.isTexture) data.map = this.map.toJSON(meta).uuid;
  6053. if (this.matcap && this.matcap.isTexture) data.matcap = this.matcap.toJSON(meta).uuid;
  6054. if (this.alphaMap && this.alphaMap.isTexture) data.alphaMap = this.alphaMap.toJSON(meta).uuid;
  6055. if (this.lightMap && this.lightMap.isTexture) data.lightMap = this.lightMap.toJSON(meta).uuid;
  6056. if (this.aoMap && this.aoMap.isTexture) {
  6057. data.aoMap = this.aoMap.toJSON(meta).uuid;
  6058. data.aoMapIntensity = this.aoMapIntensity;
  6059. }
  6060. if (this.bumpMap && this.bumpMap.isTexture) {
  6061. data.bumpMap = this.bumpMap.toJSON(meta).uuid;
  6062. data.bumpScale = this.bumpScale;
  6063. }
  6064. if (this.normalMap && this.normalMap.isTexture) {
  6065. data.normalMap = this.normalMap.toJSON(meta).uuid;
  6066. data.normalMapType = this.normalMapType;
  6067. data.normalScale = this.normalScale.toArray();
  6068. }
  6069. if (this.displacementMap && this.displacementMap.isTexture) {
  6070. data.displacementMap = this.displacementMap.toJSON(meta).uuid;
  6071. data.displacementScale = this.displacementScale;
  6072. data.displacementBias = this.displacementBias;
  6073. }
  6074. if (this.roughnessMap && this.roughnessMap.isTexture) data.roughnessMap = this.roughnessMap.toJSON(meta).uuid;
  6075. if (this.metalnessMap && this.metalnessMap.isTexture) data.metalnessMap = this.metalnessMap.toJSON(meta).uuid;
  6076. if (this.emissiveMap && this.emissiveMap.isTexture) data.emissiveMap = this.emissiveMap.toJSON(meta).uuid;
  6077. if (this.specularMap && this.specularMap.isTexture) data.specularMap = this.specularMap.toJSON(meta).uuid;
  6078. if (this.envMap && this.envMap.isTexture) {
  6079. data.envMap = this.envMap.toJSON(meta).uuid;
  6080. data.reflectivity = this.reflectivity; // Scale behind envMap
  6081. data.refractionRatio = this.refractionRatio;
  6082. if (this.combine !== undefined) data.combine = this.combine;
  6083. if (this.envMapIntensity !== undefined) data.envMapIntensity = this.envMapIntensity;
  6084. }
  6085. if (this.gradientMap && this.gradientMap.isTexture) {
  6086. data.gradientMap = this.gradientMap.toJSON(meta).uuid;
  6087. }
  6088. if (this.size !== undefined) data.size = this.size;
  6089. if (this.sizeAttenuation !== undefined) data.sizeAttenuation = this.sizeAttenuation;
  6090. if (this.blending !== NormalBlending) data.blending = this.blending;
  6091. if (this.flatShading === true) data.flatShading = this.flatShading;
  6092. if (this.side !== FrontSide) data.side = this.side;
  6093. if (this.vertexColors) data.vertexColors = true;
  6094. if (this.opacity < 1) data.opacity = this.opacity;
  6095. if (this.transparent === true) data.transparent = this.transparent;
  6096. data.depthFunc = this.depthFunc;
  6097. data.depthTest = this.depthTest;
  6098. data.depthWrite = this.depthWrite;
  6099. data.stencilWrite = this.stencilWrite;
  6100. data.stencilWriteMask = this.stencilWriteMask;
  6101. data.stencilFunc = this.stencilFunc;
  6102. data.stencilRef = this.stencilRef;
  6103. data.stencilFuncMask = this.stencilFuncMask;
  6104. data.stencilFail = this.stencilFail;
  6105. data.stencilZFail = this.stencilZFail;
  6106. data.stencilZPass = this.stencilZPass; // rotation (SpriteMaterial)
  6107. if (this.rotation && this.rotation !== 0) data.rotation = this.rotation;
  6108. if (this.polygonOffset === true) data.polygonOffset = true;
  6109. if (this.polygonOffsetFactor !== 0) data.polygonOffsetFactor = this.polygonOffsetFactor;
  6110. if (this.polygonOffsetUnits !== 0) data.polygonOffsetUnits = this.polygonOffsetUnits;
  6111. if (this.linewidth && this.linewidth !== 1) data.linewidth = this.linewidth;
  6112. if (this.dashSize !== undefined) data.dashSize = this.dashSize;
  6113. if (this.gapSize !== undefined) data.gapSize = this.gapSize;
  6114. if (this.scale !== undefined) data.scale = this.scale;
  6115. if (this.dithering === true) data.dithering = true;
  6116. if (this.alphaTest > 0) data.alphaTest = this.alphaTest;
  6117. if (this.premultipliedAlpha === true) data.premultipliedAlpha = this.premultipliedAlpha;
  6118. if (this.wireframe === true) data.wireframe = this.wireframe;
  6119. if (this.wireframeLinewidth > 1) data.wireframeLinewidth = this.wireframeLinewidth;
  6120. if (this.wireframeLinecap !== 'round') data.wireframeLinecap = this.wireframeLinecap;
  6121. if (this.wireframeLinejoin !== 'round') data.wireframeLinejoin = this.wireframeLinejoin;
  6122. if (this.morphTargets === true) data.morphTargets = true;
  6123. if (this.morphNormals === true) data.morphNormals = true;
  6124. if (this.skinning === true) data.skinning = true;
  6125. if (this.visible === false) data.visible = false;
  6126. if (this.toneMapped === false) data.toneMapped = false;
  6127. if (JSON.stringify(this.userData) !== '{}') data.userData = this.userData; // TODO: Copied from Object3D.toJSON
  6128. function extractFromCache(cache) {
  6129. const values = [];
  6130. for (const key in cache) {
  6131. const data = cache[key];
  6132. delete data.metadata;
  6133. values.push(data);
  6134. }
  6135. return values;
  6136. }
  6137. if (isRoot) {
  6138. const textures = extractFromCache(meta.textures);
  6139. const images = extractFromCache(meta.images);
  6140. if (textures.length > 0) data.textures = textures;
  6141. if (images.length > 0) data.images = images;
  6142. }
  6143. return data;
  6144. },
  6145. clone: function () {
  6146. return new this.constructor().copy(this);
  6147. },
  6148. copy: function (source) {
  6149. this.name = source.name;
  6150. this.fog = source.fog;
  6151. this.blending = source.blending;
  6152. this.side = source.side;
  6153. this.flatShading = source.flatShading;
  6154. this.vertexColors = source.vertexColors;
  6155. this.opacity = source.opacity;
  6156. this.transparent = source.transparent;
  6157. this.blendSrc = source.blendSrc;
  6158. this.blendDst = source.blendDst;
  6159. this.blendEquation = source.blendEquation;
  6160. this.blendSrcAlpha = source.blendSrcAlpha;
  6161. this.blendDstAlpha = source.blendDstAlpha;
  6162. this.blendEquationAlpha = source.blendEquationAlpha;
  6163. this.depthFunc = source.depthFunc;
  6164. this.depthTest = source.depthTest;
  6165. this.depthWrite = source.depthWrite;
  6166. this.stencilWriteMask = source.stencilWriteMask;
  6167. this.stencilFunc = source.stencilFunc;
  6168. this.stencilRef = source.stencilRef;
  6169. this.stencilFuncMask = source.stencilFuncMask;
  6170. this.stencilFail = source.stencilFail;
  6171. this.stencilZFail = source.stencilZFail;
  6172. this.stencilZPass = source.stencilZPass;
  6173. this.stencilWrite = source.stencilWrite;
  6174. const srcPlanes = source.clippingPlanes;
  6175. let dstPlanes = null;
  6176. if (srcPlanes !== null) {
  6177. const n = srcPlanes.length;
  6178. dstPlanes = new Array(n);
  6179. for (let i = 0; i !== n; ++i) {
  6180. dstPlanes[i] = srcPlanes[i].clone();
  6181. }
  6182. }
  6183. this.clippingPlanes = dstPlanes;
  6184. this.clipIntersection = source.clipIntersection;
  6185. this.clipShadows = source.clipShadows;
  6186. this.shadowSide = source.shadowSide;
  6187. this.colorWrite = source.colorWrite;
  6188. this.precision = source.precision;
  6189. this.polygonOffset = source.polygonOffset;
  6190. this.polygonOffsetFactor = source.polygonOffsetFactor;
  6191. this.polygonOffsetUnits = source.polygonOffsetUnits;
  6192. this.dithering = source.dithering;
  6193. this.alphaTest = source.alphaTest;
  6194. this.premultipliedAlpha = source.premultipliedAlpha;
  6195. this.visible = source.visible;
  6196. this.toneMapped = source.toneMapped;
  6197. this.userData = JSON.parse(JSON.stringify(source.userData));
  6198. return this;
  6199. },
  6200. dispose: function () {
  6201. this.dispatchEvent({
  6202. type: 'dispose'
  6203. });
  6204. }
  6205. });
  6206. Object.defineProperty(Material.prototype, 'needsUpdate', {
  6207. set: function (value) {
  6208. if (value === true) this.version++;
  6209. }
  6210. });
  6211. /**
  6212. * parameters = {
  6213. * color: <hex>,
  6214. * opacity: <float>,
  6215. * map: new THREE.Texture( <Image> ),
  6216. *
  6217. * lightMap: new THREE.Texture( <Image> ),
  6218. * lightMapIntensity: <float>
  6219. *
  6220. * aoMap: new THREE.Texture( <Image> ),
  6221. * aoMapIntensity: <float>
  6222. *
  6223. * specularMap: new THREE.Texture( <Image> ),
  6224. *
  6225. * alphaMap: new THREE.Texture( <Image> ),
  6226. *
  6227. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  6228. * combine: THREE.Multiply,
  6229. * reflectivity: <float>,
  6230. * refractionRatio: <float>,
  6231. *
  6232. * depthTest: <bool>,
  6233. * depthWrite: <bool>,
  6234. *
  6235. * wireframe: <boolean>,
  6236. * wireframeLinewidth: <float>,
  6237. *
  6238. * skinning: <bool>,
  6239. * morphTargets: <bool>
  6240. * }
  6241. */
  6242. function MeshBasicMaterial(parameters) {
  6243. Material.call(this);
  6244. this.type = 'MeshBasicMaterial';
  6245. this.color = new Color(0xffffff); // emissive
  6246. this.map = null;
  6247. this.lightMap = null;
  6248. this.lightMapIntensity = 1.0;
  6249. this.aoMap = null;
  6250. this.aoMapIntensity = 1.0;
  6251. this.specularMap = null;
  6252. this.alphaMap = null;
  6253. this.envMap = null;
  6254. this.combine = MultiplyOperation;
  6255. this.reflectivity = 1;
  6256. this.refractionRatio = 0.98;
  6257. this.wireframe = false;
  6258. this.wireframeLinewidth = 1;
  6259. this.wireframeLinecap = 'round';
  6260. this.wireframeLinejoin = 'round';
  6261. this.skinning = false;
  6262. this.morphTargets = false;
  6263. this.setValues(parameters);
  6264. }
  6265. MeshBasicMaterial.prototype = Object.create(Material.prototype);
  6266. MeshBasicMaterial.prototype.constructor = MeshBasicMaterial;
  6267. MeshBasicMaterial.prototype.isMeshBasicMaterial = true;
  6268. MeshBasicMaterial.prototype.copy = function (source) {
  6269. Material.prototype.copy.call(this, source);
  6270. this.color.copy(source.color);
  6271. this.map = source.map;
  6272. this.lightMap = source.lightMap;
  6273. this.lightMapIntensity = source.lightMapIntensity;
  6274. this.aoMap = source.aoMap;
  6275. this.aoMapIntensity = source.aoMapIntensity;
  6276. this.specularMap = source.specularMap;
  6277. this.alphaMap = source.alphaMap;
  6278. this.envMap = source.envMap;
  6279. this.combine = source.combine;
  6280. this.reflectivity = source.reflectivity;
  6281. this.refractionRatio = source.refractionRatio;
  6282. this.wireframe = source.wireframe;
  6283. this.wireframeLinewidth = source.wireframeLinewidth;
  6284. this.wireframeLinecap = source.wireframeLinecap;
  6285. this.wireframeLinejoin = source.wireframeLinejoin;
  6286. this.skinning = source.skinning;
  6287. this.morphTargets = source.morphTargets;
  6288. return this;
  6289. };
  6290. const _vector$3 = new Vector3();
  6291. const _vector2$1 = new Vector2();
  6292. function BufferAttribute(array, itemSize, normalized) {
  6293. if (Array.isArray(array)) {
  6294. throw new TypeError('THREE.BufferAttribute: array should be a Typed Array.');
  6295. }
  6296. this.name = '';
  6297. this.array = array;
  6298. this.itemSize = itemSize;
  6299. this.count = array !== undefined ? array.length / itemSize : 0;
  6300. this.normalized = normalized === true;
  6301. this.usage = StaticDrawUsage;
  6302. this.updateRange = {
  6303. offset: 0,
  6304. count: -1
  6305. };
  6306. this.version = 0;
  6307. }
  6308. Object.defineProperty(BufferAttribute.prototype, 'needsUpdate', {
  6309. set: function (value) {
  6310. if (value === true) this.version++;
  6311. }
  6312. });
  6313. Object.assign(BufferAttribute.prototype, {
  6314. isBufferAttribute: true,
  6315. onUploadCallback: function () {},
  6316. setUsage: function (value) {
  6317. this.usage = value;
  6318. return this;
  6319. },
  6320. copy: function (source) {
  6321. this.name = source.name;
  6322. this.array = new source.array.constructor(source.array);
  6323. this.itemSize = source.itemSize;
  6324. this.count = source.count;
  6325. this.normalized = source.normalized;
  6326. this.usage = source.usage;
  6327. return this;
  6328. },
  6329. copyAt: function (index1, attribute, index2) {
  6330. index1 *= this.itemSize;
  6331. index2 *= attribute.itemSize;
  6332. for (let i = 0, l = this.itemSize; i < l; i++) {
  6333. this.array[index1 + i] = attribute.array[index2 + i];
  6334. }
  6335. return this;
  6336. },
  6337. copyArray: function (array) {
  6338. this.array.set(array);
  6339. return this;
  6340. },
  6341. copyColorsArray: function (colors) {
  6342. const array = this.array;
  6343. let offset = 0;
  6344. for (let i = 0, l = colors.length; i < l; i++) {
  6345. let color = colors[i];
  6346. if (color === undefined) {
  6347. console.warn('THREE.BufferAttribute.copyColorsArray(): color is undefined', i);
  6348. color = new Color();
  6349. }
  6350. array[offset++] = color.r;
  6351. array[offset++] = color.g;
  6352. array[offset++] = color.b;
  6353. }
  6354. return this;
  6355. },
  6356. copyVector2sArray: function (vectors) {
  6357. const array = this.array;
  6358. let offset = 0;
  6359. for (let i = 0, l = vectors.length; i < l; i++) {
  6360. let vector = vectors[i];
  6361. if (vector === undefined) {
  6362. console.warn('THREE.BufferAttribute.copyVector2sArray(): vector is undefined', i);
  6363. vector = new Vector2();
  6364. }
  6365. array[offset++] = vector.x;
  6366. array[offset++] = vector.y;
  6367. }
  6368. return this;
  6369. },
  6370. copyVector3sArray: function (vectors) {
  6371. const array = this.array;
  6372. let offset = 0;
  6373. for (let i = 0, l = vectors.length; i < l; i++) {
  6374. let vector = vectors[i];
  6375. if (vector === undefined) {
  6376. console.warn('THREE.BufferAttribute.copyVector3sArray(): vector is undefined', i);
  6377. vector = new Vector3();
  6378. }
  6379. array[offset++] = vector.x;
  6380. array[offset++] = vector.y;
  6381. array[offset++] = vector.z;
  6382. }
  6383. return this;
  6384. },
  6385. copyVector4sArray: function (vectors) {
  6386. const array = this.array;
  6387. let offset = 0;
  6388. for (let i = 0, l = vectors.length; i < l; i++) {
  6389. let vector = vectors[i];
  6390. if (vector === undefined) {
  6391. console.warn('THREE.BufferAttribute.copyVector4sArray(): vector is undefined', i);
  6392. vector = new Vector4();
  6393. }
  6394. array[offset++] = vector.x;
  6395. array[offset++] = vector.y;
  6396. array[offset++] = vector.z;
  6397. array[offset++] = vector.w;
  6398. }
  6399. return this;
  6400. },
  6401. applyMatrix3: function (m) {
  6402. if (this.itemSize === 2) {
  6403. for (let i = 0, l = this.count; i < l; i++) {
  6404. _vector2$1.fromBufferAttribute(this, i);
  6405. _vector2$1.applyMatrix3(m);
  6406. this.setXY(i, _vector2$1.x, _vector2$1.y);
  6407. }
  6408. } else if (this.itemSize === 3) {
  6409. for (let i = 0, l = this.count; i < l; i++) {
  6410. _vector$3.fromBufferAttribute(this, i);
  6411. _vector$3.applyMatrix3(m);
  6412. this.setXYZ(i, _vector$3.x, _vector$3.y, _vector$3.z);
  6413. }
  6414. }
  6415. return this;
  6416. },
  6417. applyMatrix4: function (m) {
  6418. for (let i = 0, l = this.count; i < l; i++) {
  6419. _vector$3.x = this.getX(i);
  6420. _vector$3.y = this.getY(i);
  6421. _vector$3.z = this.getZ(i);
  6422. _vector$3.applyMatrix4(m);
  6423. this.setXYZ(i, _vector$3.x, _vector$3.y, _vector$3.z);
  6424. }
  6425. return this;
  6426. },
  6427. applyNormalMatrix: function (m) {
  6428. for (let i = 0, l = this.count; i < l; i++) {
  6429. _vector$3.x = this.getX(i);
  6430. _vector$3.y = this.getY(i);
  6431. _vector$3.z = this.getZ(i);
  6432. _vector$3.applyNormalMatrix(m);
  6433. this.setXYZ(i, _vector$3.x, _vector$3.y, _vector$3.z);
  6434. }
  6435. return this;
  6436. },
  6437. transformDirection: function (m) {
  6438. for (let i = 0, l = this.count; i < l; i++) {
  6439. _vector$3.x = this.getX(i);
  6440. _vector$3.y = this.getY(i);
  6441. _vector$3.z = this.getZ(i);
  6442. _vector$3.transformDirection(m);
  6443. this.setXYZ(i, _vector$3.x, _vector$3.y, _vector$3.z);
  6444. }
  6445. return this;
  6446. },
  6447. set: function (value, offset = 0) {
  6448. this.array.set(value, offset);
  6449. return this;
  6450. },
  6451. getX: function (index) {
  6452. return this.array[index * this.itemSize];
  6453. },
  6454. setX: function (index, x) {
  6455. this.array[index * this.itemSize] = x;
  6456. return this;
  6457. },
  6458. getY: function (index) {
  6459. return this.array[index * this.itemSize + 1];
  6460. },
  6461. setY: function (index, y) {
  6462. this.array[index * this.itemSize + 1] = y;
  6463. return this;
  6464. },
  6465. getZ: function (index) {
  6466. return this.array[index * this.itemSize + 2];
  6467. },
  6468. setZ: function (index, z) {
  6469. this.array[index * this.itemSize + 2] = z;
  6470. return this;
  6471. },
  6472. getW: function (index) {
  6473. return this.array[index * this.itemSize + 3];
  6474. },
  6475. setW: function (index, w) {
  6476. this.array[index * this.itemSize + 3] = w;
  6477. return this;
  6478. },
  6479. setXY: function (index, x, y) {
  6480. index *= this.itemSize;
  6481. this.array[index + 0] = x;
  6482. this.array[index + 1] = y;
  6483. return this;
  6484. },
  6485. setXYZ: function (index, x, y, z) {
  6486. index *= this.itemSize;
  6487. this.array[index + 0] = x;
  6488. this.array[index + 1] = y;
  6489. this.array[index + 2] = z;
  6490. return this;
  6491. },
  6492. setXYZW: function (index, x, y, z, w) {
  6493. index *= this.itemSize;
  6494. this.array[index + 0] = x;
  6495. this.array[index + 1] = y;
  6496. this.array[index + 2] = z;
  6497. this.array[index + 3] = w;
  6498. return this;
  6499. },
  6500. onUpload: function (callback) {
  6501. this.onUploadCallback = callback;
  6502. return this;
  6503. },
  6504. clone: function () {
  6505. return new this.constructor(this.array, this.itemSize).copy(this);
  6506. },
  6507. toJSON: function () {
  6508. return {
  6509. itemSize: this.itemSize,
  6510. type: this.array.constructor.name,
  6511. array: Array.prototype.slice.call(this.array),
  6512. normalized: this.normalized
  6513. };
  6514. }
  6515. }); //
  6516. function Int8BufferAttribute(array, itemSize, normalized) {
  6517. BufferAttribute.call(this, new Int8Array(array), itemSize, normalized);
  6518. }
  6519. Int8BufferAttribute.prototype = Object.create(BufferAttribute.prototype);
  6520. Int8BufferAttribute.prototype.constructor = Int8BufferAttribute;
  6521. function Uint8BufferAttribute(array, itemSize, normalized) {
  6522. BufferAttribute.call(this, new Uint8Array(array), itemSize, normalized);
  6523. }
  6524. Uint8BufferAttribute.prototype = Object.create(BufferAttribute.prototype);
  6525. Uint8BufferAttribute.prototype.constructor = Uint8BufferAttribute;
  6526. function Uint8ClampedBufferAttribute(array, itemSize, normalized) {
  6527. BufferAttribute.call(this, new Uint8ClampedArray(array), itemSize, normalized);
  6528. }
  6529. Uint8ClampedBufferAttribute.prototype = Object.create(BufferAttribute.prototype);
  6530. Uint8ClampedBufferAttribute.prototype.constructor = Uint8ClampedBufferAttribute;
  6531. function Int16BufferAttribute(array, itemSize, normalized) {
  6532. BufferAttribute.call(this, new Int16Array(array), itemSize, normalized);
  6533. }
  6534. Int16BufferAttribute.prototype = Object.create(BufferAttribute.prototype);
  6535. Int16BufferAttribute.prototype.constructor = Int16BufferAttribute;
  6536. function Uint16BufferAttribute(array, itemSize, normalized) {
  6537. BufferAttribute.call(this, new Uint16Array(array), itemSize, normalized);
  6538. }
  6539. Uint16BufferAttribute.prototype = Object.create(BufferAttribute.prototype);
  6540. Uint16BufferAttribute.prototype.constructor = Uint16BufferAttribute;
  6541. function Int32BufferAttribute(array, itemSize, normalized) {
  6542. BufferAttribute.call(this, new Int32Array(array), itemSize, normalized);
  6543. }
  6544. Int32BufferAttribute.prototype = Object.create(BufferAttribute.prototype);
  6545. Int32BufferAttribute.prototype.constructor = Int32BufferAttribute;
  6546. function Uint32BufferAttribute(array, itemSize, normalized) {
  6547. BufferAttribute.call(this, new Uint32Array(array), itemSize, normalized);
  6548. }
  6549. Uint32BufferAttribute.prototype = Object.create(BufferAttribute.prototype);
  6550. Uint32BufferAttribute.prototype.constructor = Uint32BufferAttribute;
  6551. function Float16BufferAttribute(array, itemSize, normalized) {
  6552. BufferAttribute.call(this, new Uint16Array(array), itemSize, normalized);
  6553. }
  6554. Float16BufferAttribute.prototype = Object.create(BufferAttribute.prototype);
  6555. Float16BufferAttribute.prototype.constructor = Float16BufferAttribute;
  6556. Float16BufferAttribute.prototype.isFloat16BufferAttribute = true;
  6557. function Float32BufferAttribute(array, itemSize, normalized) {
  6558. BufferAttribute.call(this, new Float32Array(array), itemSize, normalized);
  6559. }
  6560. Float32BufferAttribute.prototype = Object.create(BufferAttribute.prototype);
  6561. Float32BufferAttribute.prototype.constructor = Float32BufferAttribute;
  6562. function Float64BufferAttribute(array, itemSize, normalized) {
  6563. BufferAttribute.call(this, new Float64Array(array), itemSize, normalized);
  6564. }
  6565. Float64BufferAttribute.prototype = Object.create(BufferAttribute.prototype);
  6566. Float64BufferAttribute.prototype.constructor = Float64BufferAttribute;
  6567. class DirectGeometry {
  6568. constructor() {
  6569. this.vertices = [];
  6570. this.normals = [];
  6571. this.colors = [];
  6572. this.uvs = [];
  6573. this.uvs2 = [];
  6574. this.groups = [];
  6575. this.morphTargets = {};
  6576. this.skinWeights = [];
  6577. this.skinIndices = []; // this.lineDistances = [];
  6578. this.boundingBox = null;
  6579. this.boundingSphere = null; // update flags
  6580. this.verticesNeedUpdate = false;
  6581. this.normalsNeedUpdate = false;
  6582. this.colorsNeedUpdate = false;
  6583. this.uvsNeedUpdate = false;
  6584. this.groupsNeedUpdate = false;
  6585. }
  6586. computeGroups(geometry) {
  6587. const groups = [];
  6588. let group, i;
  6589. let materialIndex = undefined;
  6590. const faces = geometry.faces;
  6591. for (i = 0; i < faces.length; i++) {
  6592. const face = faces[i]; // materials
  6593. if (face.materialIndex !== materialIndex) {
  6594. materialIndex = face.materialIndex;
  6595. if (group !== undefined) {
  6596. group.count = i * 3 - group.start;
  6597. groups.push(group);
  6598. }
  6599. group = {
  6600. start: i * 3,
  6601. materialIndex: materialIndex
  6602. };
  6603. }
  6604. }
  6605. if (group !== undefined) {
  6606. group.count = i * 3 - group.start;
  6607. groups.push(group);
  6608. }
  6609. this.groups = groups;
  6610. }
  6611. fromGeometry(geometry) {
  6612. const faces = geometry.faces;
  6613. const vertices = geometry.vertices;
  6614. const faceVertexUvs = geometry.faceVertexUvs;
  6615. const hasFaceVertexUv = faceVertexUvs[0] && faceVertexUvs[0].length > 0;
  6616. const hasFaceVertexUv2 = faceVertexUvs[1] && faceVertexUvs[1].length > 0; // morphs
  6617. const morphTargets = geometry.morphTargets;
  6618. const morphTargetsLength = morphTargets.length;
  6619. let morphTargetsPosition;
  6620. if (morphTargetsLength > 0) {
  6621. morphTargetsPosition = [];
  6622. for (let i = 0; i < morphTargetsLength; i++) {
  6623. morphTargetsPosition[i] = {
  6624. name: morphTargets[i].name,
  6625. data: []
  6626. };
  6627. }
  6628. this.morphTargets.position = morphTargetsPosition;
  6629. }
  6630. const morphNormals = geometry.morphNormals;
  6631. const morphNormalsLength = morphNormals.length;
  6632. let morphTargetsNormal;
  6633. if (morphNormalsLength > 0) {
  6634. morphTargetsNormal = [];
  6635. for (let i = 0; i < morphNormalsLength; i++) {
  6636. morphTargetsNormal[i] = {
  6637. name: morphNormals[i].name,
  6638. data: []
  6639. };
  6640. }
  6641. this.morphTargets.normal = morphTargetsNormal;
  6642. } // skins
  6643. const skinIndices = geometry.skinIndices;
  6644. const skinWeights = geometry.skinWeights;
  6645. const hasSkinIndices = skinIndices.length === vertices.length;
  6646. const hasSkinWeights = skinWeights.length === vertices.length; //
  6647. if (vertices.length > 0 && faces.length === 0) {
  6648. console.error('THREE.DirectGeometry: Faceless geometries are not supported.');
  6649. }
  6650. for (let i = 0; i < faces.length; i++) {
  6651. const face = faces[i];
  6652. this.vertices.push(vertices[face.a], vertices[face.b], vertices[face.c]);
  6653. const vertexNormals = face.vertexNormals;
  6654. if (vertexNormals.length === 3) {
  6655. this.normals.push(vertexNormals[0], vertexNormals[1], vertexNormals[2]);
  6656. } else {
  6657. const normal = face.normal;
  6658. this.normals.push(normal, normal, normal);
  6659. }
  6660. const vertexColors = face.vertexColors;
  6661. if (vertexColors.length === 3) {
  6662. this.colors.push(vertexColors[0], vertexColors[1], vertexColors[2]);
  6663. } else {
  6664. const color = face.color;
  6665. this.colors.push(color, color, color);
  6666. }
  6667. if (hasFaceVertexUv === true) {
  6668. const vertexUvs = faceVertexUvs[0][i];
  6669. if (vertexUvs !== undefined) {
  6670. this.uvs.push(vertexUvs[0], vertexUvs[1], vertexUvs[2]);
  6671. } else {
  6672. console.warn('THREE.DirectGeometry.fromGeometry(): Undefined vertexUv ', i);
  6673. this.uvs.push(new Vector2(), new Vector2(), new Vector2());
  6674. }
  6675. }
  6676. if (hasFaceVertexUv2 === true) {
  6677. const vertexUvs = faceVertexUvs[1][i];
  6678. if (vertexUvs !== undefined) {
  6679. this.uvs2.push(vertexUvs[0], vertexUvs[1], vertexUvs[2]);
  6680. } else {
  6681. console.warn('THREE.DirectGeometry.fromGeometry(): Undefined vertexUv2 ', i);
  6682. this.uvs2.push(new Vector2(), new Vector2(), new Vector2());
  6683. }
  6684. } // morphs
  6685. for (let j = 0; j < morphTargetsLength; j++) {
  6686. const morphTarget = morphTargets[j].vertices;
  6687. morphTargetsPosition[j].data.push(morphTarget[face.a], morphTarget[face.b], morphTarget[face.c]);
  6688. }
  6689. for (let j = 0; j < morphNormalsLength; j++) {
  6690. const morphNormal = morphNormals[j].vertexNormals[i];
  6691. morphTargetsNormal[j].data.push(morphNormal.a, morphNormal.b, morphNormal.c);
  6692. } // skins
  6693. if (hasSkinIndices) {
  6694. this.skinIndices.push(skinIndices[face.a], skinIndices[face.b], skinIndices[face.c]);
  6695. }
  6696. if (hasSkinWeights) {
  6697. this.skinWeights.push(skinWeights[face.a], skinWeights[face.b], skinWeights[face.c]);
  6698. }
  6699. }
  6700. this.computeGroups(geometry);
  6701. this.verticesNeedUpdate = geometry.verticesNeedUpdate;
  6702. this.normalsNeedUpdate = geometry.normalsNeedUpdate;
  6703. this.colorsNeedUpdate = geometry.colorsNeedUpdate;
  6704. this.uvsNeedUpdate = geometry.uvsNeedUpdate;
  6705. this.groupsNeedUpdate = geometry.groupsNeedUpdate;
  6706. if (geometry.boundingSphere !== null) {
  6707. this.boundingSphere = geometry.boundingSphere.clone();
  6708. }
  6709. if (geometry.boundingBox !== null) {
  6710. this.boundingBox = geometry.boundingBox.clone();
  6711. }
  6712. return this;
  6713. }
  6714. }
  6715. function arrayMax(array) {
  6716. if (array.length === 0) return -Infinity;
  6717. let max = array[0];
  6718. for (let i = 1, l = array.length; i < l; ++i) {
  6719. if (array[i] > max) max = array[i];
  6720. }
  6721. return max;
  6722. }
  6723. const TYPED_ARRAYS = {
  6724. Int8Array: Int8Array,
  6725. Uint8Array: Uint8Array,
  6726. // Workaround for IE11 pre KB2929437. See #11440
  6727. Uint8ClampedArray: typeof Uint8ClampedArray !== 'undefined' ? Uint8ClampedArray : Uint8Array,
  6728. Int16Array: Int16Array,
  6729. Uint16Array: Uint16Array,
  6730. Int32Array: Int32Array,
  6731. Uint32Array: Uint32Array,
  6732. Float32Array: Float32Array,
  6733. Float64Array: Float64Array
  6734. };
  6735. function getTypedArray(type, buffer) {
  6736. return new TYPED_ARRAYS[type](buffer);
  6737. }
  6738. let _bufferGeometryId = 1; // BufferGeometry uses odd numbers as Id
  6739. const _m1$2 = new Matrix4();
  6740. const _obj = new Object3D();
  6741. const _offset = new Vector3();
  6742. const _box$2 = new Box3();
  6743. const _boxMorphTargets = new Box3();
  6744. const _vector$4 = new Vector3();
  6745. function BufferGeometry() {
  6746. Object.defineProperty(this, 'id', {
  6747. value: _bufferGeometryId += 2
  6748. });
  6749. this.uuid = MathUtils.generateUUID();
  6750. this.name = '';
  6751. this.type = 'BufferGeometry';
  6752. this.index = null;
  6753. this.attributes = {};
  6754. this.morphAttributes = {};
  6755. this.morphTargetsRelative = false;
  6756. this.groups = [];
  6757. this.boundingBox = null;
  6758. this.boundingSphere = null;
  6759. this.drawRange = {
  6760. start: 0,
  6761. count: Infinity
  6762. };
  6763. this.userData = {};
  6764. }
  6765. BufferGeometry.prototype = Object.assign(Object.create(EventDispatcher.prototype), {
  6766. constructor: BufferGeometry,
  6767. isBufferGeometry: true,
  6768. getIndex: function () {
  6769. return this.index;
  6770. },
  6771. setIndex: function (index) {
  6772. if (Array.isArray(index)) {
  6773. this.index = new (arrayMax(index) > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute)(index, 1);
  6774. } else {
  6775. this.index = index;
  6776. }
  6777. return this;
  6778. },
  6779. getAttribute: function (name) {
  6780. return this.attributes[name];
  6781. },
  6782. setAttribute: function (name, attribute) {
  6783. this.attributes[name] = attribute;
  6784. return this;
  6785. },
  6786. deleteAttribute: function (name) {
  6787. delete this.attributes[name];
  6788. return this;
  6789. },
  6790. hasAttribute: function (name) {
  6791. return this.attributes[name] !== undefined;
  6792. },
  6793. addGroup: function (start, count, materialIndex = 0) {
  6794. this.groups.push({
  6795. start: start,
  6796. count: count,
  6797. materialIndex: materialIndex
  6798. });
  6799. },
  6800. clearGroups: function () {
  6801. this.groups = [];
  6802. },
  6803. setDrawRange: function (start, count) {
  6804. this.drawRange.start = start;
  6805. this.drawRange.count = count;
  6806. },
  6807. applyMatrix4: function (matrix) {
  6808. const position = this.attributes.position;
  6809. if (position !== undefined) {
  6810. position.applyMatrix4(matrix);
  6811. position.needsUpdate = true;
  6812. }
  6813. const normal = this.attributes.normal;
  6814. if (normal !== undefined) {
  6815. const normalMatrix = new Matrix3().getNormalMatrix(matrix);
  6816. normal.applyNormalMatrix(normalMatrix);
  6817. normal.needsUpdate = true;
  6818. }
  6819. const tangent = this.attributes.tangent;
  6820. if (tangent !== undefined) {
  6821. tangent.transformDirection(matrix);
  6822. tangent.needsUpdate = true;
  6823. }
  6824. if (this.boundingBox !== null) {
  6825. this.computeBoundingBox();
  6826. }
  6827. if (this.boundingSphere !== null) {
  6828. this.computeBoundingSphere();
  6829. }
  6830. return this;
  6831. },
  6832. rotateX: function (angle) {
  6833. // rotate geometry around world x-axis
  6834. _m1$2.makeRotationX(angle);
  6835. this.applyMatrix4(_m1$2);
  6836. return this;
  6837. },
  6838. rotateY: function (angle) {
  6839. // rotate geometry around world y-axis
  6840. _m1$2.makeRotationY(angle);
  6841. this.applyMatrix4(_m1$2);
  6842. return this;
  6843. },
  6844. rotateZ: function (angle) {
  6845. // rotate geometry around world z-axis
  6846. _m1$2.makeRotationZ(angle);
  6847. this.applyMatrix4(_m1$2);
  6848. return this;
  6849. },
  6850. translate: function (x, y, z) {
  6851. // translate geometry
  6852. _m1$2.makeTranslation(x, y, z);
  6853. this.applyMatrix4(_m1$2);
  6854. return this;
  6855. },
  6856. scale: function (x, y, z) {
  6857. // scale geometry
  6858. _m1$2.makeScale(x, y, z);
  6859. this.applyMatrix4(_m1$2);
  6860. return this;
  6861. },
  6862. lookAt: function (vector) {
  6863. _obj.lookAt(vector);
  6864. _obj.updateMatrix();
  6865. this.applyMatrix4(_obj.matrix);
  6866. return this;
  6867. },
  6868. center: function () {
  6869. this.computeBoundingBox();
  6870. this.boundingBox.getCenter(_offset).negate();
  6871. this.translate(_offset.x, _offset.y, _offset.z);
  6872. return this;
  6873. },
  6874. setFromObject: function (object) {
  6875. // console.log( 'THREE.BufferGeometry.setFromObject(). Converting', object, this );
  6876. const geometry = object.geometry;
  6877. if (object.isPoints || object.isLine) {
  6878. const positions = new Float32BufferAttribute(geometry.vertices.length * 3, 3);
  6879. const colors = new Float32BufferAttribute(geometry.colors.length * 3, 3);
  6880. this.setAttribute('position', positions.copyVector3sArray(geometry.vertices));
  6881. this.setAttribute('color', colors.copyColorsArray(geometry.colors));
  6882. if (geometry.lineDistances && geometry.lineDistances.length === geometry.vertices.length) {
  6883. const lineDistances = new Float32BufferAttribute(geometry.lineDistances.length, 1);
  6884. this.setAttribute('lineDistance', lineDistances.copyArray(geometry.lineDistances));
  6885. }
  6886. if (geometry.boundingSphere !== null) {
  6887. this.boundingSphere = geometry.boundingSphere.clone();
  6888. }
  6889. if (geometry.boundingBox !== null) {
  6890. this.boundingBox = geometry.boundingBox.clone();
  6891. }
  6892. } else if (object.isMesh) {
  6893. if (geometry && geometry.isGeometry) {
  6894. this.fromGeometry(geometry);
  6895. }
  6896. }
  6897. return this;
  6898. },
  6899. setFromPoints: function (points) {
  6900. const position = [];
  6901. for (let i = 0, l = points.length; i < l; i++) {
  6902. const point = points[i];
  6903. position.push(point.x, point.y, point.z || 0);
  6904. }
  6905. this.setAttribute('position', new Float32BufferAttribute(position, 3));
  6906. return this;
  6907. },
  6908. updateFromObject: function (object) {
  6909. let geometry = object.geometry;
  6910. if (object.isMesh) {
  6911. let direct = geometry.__directGeometry;
  6912. if (geometry.elementsNeedUpdate === true) {
  6913. direct = undefined;
  6914. geometry.elementsNeedUpdate = false;
  6915. }
  6916. if (direct === undefined) {
  6917. return this.fromGeometry(geometry);
  6918. }
  6919. direct.verticesNeedUpdate = geometry.verticesNeedUpdate;
  6920. direct.normalsNeedUpdate = geometry.normalsNeedUpdate;
  6921. direct.colorsNeedUpdate = geometry.colorsNeedUpdate;
  6922. direct.uvsNeedUpdate = geometry.uvsNeedUpdate;
  6923. direct.groupsNeedUpdate = geometry.groupsNeedUpdate;
  6924. geometry.verticesNeedUpdate = false;
  6925. geometry.normalsNeedUpdate = false;
  6926. geometry.colorsNeedUpdate = false;
  6927. geometry.uvsNeedUpdate = false;
  6928. geometry.groupsNeedUpdate = false;
  6929. geometry = direct;
  6930. }
  6931. if (geometry.verticesNeedUpdate === true) {
  6932. const attribute = this.attributes.position;
  6933. if (attribute !== undefined) {
  6934. attribute.copyVector3sArray(geometry.vertices);
  6935. attribute.needsUpdate = true;
  6936. }
  6937. geometry.verticesNeedUpdate = false;
  6938. }
  6939. if (geometry.normalsNeedUpdate === true) {
  6940. const attribute = this.attributes.normal;
  6941. if (attribute !== undefined) {
  6942. attribute.copyVector3sArray(geometry.normals);
  6943. attribute.needsUpdate = true;
  6944. }
  6945. geometry.normalsNeedUpdate = false;
  6946. }
  6947. if (geometry.colorsNeedUpdate === true) {
  6948. const attribute = this.attributes.color;
  6949. if (attribute !== undefined) {
  6950. attribute.copyColorsArray(geometry.colors);
  6951. attribute.needsUpdate = true;
  6952. }
  6953. geometry.colorsNeedUpdate = false;
  6954. }
  6955. if (geometry.uvsNeedUpdate) {
  6956. const attribute = this.attributes.uv;
  6957. if (attribute !== undefined) {
  6958. attribute.copyVector2sArray(geometry.uvs);
  6959. attribute.needsUpdate = true;
  6960. }
  6961. geometry.uvsNeedUpdate = false;
  6962. }
  6963. if (geometry.lineDistancesNeedUpdate) {
  6964. const attribute = this.attributes.lineDistance;
  6965. if (attribute !== undefined) {
  6966. attribute.copyArray(geometry.lineDistances);
  6967. attribute.needsUpdate = true;
  6968. }
  6969. geometry.lineDistancesNeedUpdate = false;
  6970. }
  6971. if (geometry.groupsNeedUpdate) {
  6972. geometry.computeGroups(object.geometry);
  6973. this.groups = geometry.groups;
  6974. geometry.groupsNeedUpdate = false;
  6975. }
  6976. return this;
  6977. },
  6978. fromGeometry: function (geometry) {
  6979. geometry.__directGeometry = new DirectGeometry().fromGeometry(geometry);
  6980. return this.fromDirectGeometry(geometry.__directGeometry);
  6981. },
  6982. fromDirectGeometry: function (geometry) {
  6983. const positions = new Float32Array(geometry.vertices.length * 3);
  6984. this.setAttribute('position', new BufferAttribute(positions, 3).copyVector3sArray(geometry.vertices));
  6985. if (geometry.normals.length > 0) {
  6986. const normals = new Float32Array(geometry.normals.length * 3);
  6987. this.setAttribute('normal', new BufferAttribute(normals, 3).copyVector3sArray(geometry.normals));
  6988. }
  6989. if (geometry.colors.length > 0) {
  6990. const colors = new Float32Array(geometry.colors.length * 3);
  6991. this.setAttribute('color', new BufferAttribute(colors, 3).copyColorsArray(geometry.colors));
  6992. }
  6993. if (geometry.uvs.length > 0) {
  6994. const uvs = new Float32Array(geometry.uvs.length * 2);
  6995. this.setAttribute('uv', new BufferAttribute(uvs, 2).copyVector2sArray(geometry.uvs));
  6996. }
  6997. if (geometry.uvs2.length > 0) {
  6998. const uvs2 = new Float32Array(geometry.uvs2.length * 2);
  6999. this.setAttribute('uv2', new BufferAttribute(uvs2, 2).copyVector2sArray(geometry.uvs2));
  7000. } // groups
  7001. this.groups = geometry.groups; // morphs
  7002. for (const name in geometry.morphTargets) {
  7003. const array = [];
  7004. const morphTargets = geometry.morphTargets[name];
  7005. for (let i = 0, l = morphTargets.length; i < l; i++) {
  7006. const morphTarget = morphTargets[i];
  7007. const attribute = new Float32BufferAttribute(morphTarget.data.length * 3, 3);
  7008. attribute.name = morphTarget.name;
  7009. array.push(attribute.copyVector3sArray(morphTarget.data));
  7010. }
  7011. this.morphAttributes[name] = array;
  7012. } // skinning
  7013. if (geometry.skinIndices.length > 0) {
  7014. const skinIndices = new Float32BufferAttribute(geometry.skinIndices.length * 4, 4);
  7015. this.setAttribute('skinIndex', skinIndices.copyVector4sArray(geometry.skinIndices));
  7016. }
  7017. if (geometry.skinWeights.length > 0) {
  7018. const skinWeights = new Float32BufferAttribute(geometry.skinWeights.length * 4, 4);
  7019. this.setAttribute('skinWeight', skinWeights.copyVector4sArray(geometry.skinWeights));
  7020. } //
  7021. if (geometry.boundingSphere !== null) {
  7022. this.boundingSphere = geometry.boundingSphere.clone();
  7023. }
  7024. if (geometry.boundingBox !== null) {
  7025. this.boundingBox = geometry.boundingBox.clone();
  7026. }
  7027. return this;
  7028. },
  7029. computeBoundingBox: function () {
  7030. if (this.boundingBox === null) {
  7031. this.boundingBox = new Box3();
  7032. }
  7033. const position = this.attributes.position;
  7034. const morphAttributesPosition = this.morphAttributes.position;
  7035. if (position && position.isGLBufferAttribute) {
  7036. console.error('THREE.BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box. Alternatively set "mesh.frustumCulled" to "false".', this);
  7037. this.boundingBox.set(new Vector3(-Infinity, -Infinity, -Infinity), new Vector3(+Infinity, +Infinity, +Infinity));
  7038. return;
  7039. }
  7040. if (position !== undefined) {
  7041. this.boundingBox.setFromBufferAttribute(position); // process morph attributes if present
  7042. if (morphAttributesPosition) {
  7043. for (let i = 0, il = morphAttributesPosition.length; i < il; i++) {
  7044. const morphAttribute = morphAttributesPosition[i];
  7045. _box$2.setFromBufferAttribute(morphAttribute);
  7046. if (this.morphTargetsRelative) {
  7047. _vector$4.addVectors(this.boundingBox.min, _box$2.min);
  7048. this.boundingBox.expandByPoint(_vector$4);
  7049. _vector$4.addVectors(this.boundingBox.max, _box$2.max);
  7050. this.boundingBox.expandByPoint(_vector$4);
  7051. } else {
  7052. this.boundingBox.expandByPoint(_box$2.min);
  7053. this.boundingBox.expandByPoint(_box$2.max);
  7054. }
  7055. }
  7056. }
  7057. } else {
  7058. this.boundingBox.makeEmpty();
  7059. }
  7060. if (isNaN(this.boundingBox.min.x) || isNaN(this.boundingBox.min.y) || isNaN(this.boundingBox.min.z)) {
  7061. console.error('THREE.BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this);
  7062. }
  7063. },
  7064. computeBoundingSphere: function () {
  7065. if (this.boundingSphere === null) {
  7066. this.boundingSphere = new Sphere();
  7067. }
  7068. const position = this.attributes.position;
  7069. const morphAttributesPosition = this.morphAttributes.position;
  7070. if (position && position.isGLBufferAttribute) {
  7071. console.error('THREE.BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere. Alternatively set "mesh.frustumCulled" to "false".', this);
  7072. this.boundingSphere.set(new Vector3(), Infinity);
  7073. return;
  7074. }
  7075. if (position) {
  7076. // first, find the center of the bounding sphere
  7077. const center = this.boundingSphere.center;
  7078. _box$2.setFromBufferAttribute(position); // process morph attributes if present
  7079. if (morphAttributesPosition) {
  7080. for (let i = 0, il = morphAttributesPosition.length; i < il; i++) {
  7081. const morphAttribute = morphAttributesPosition[i];
  7082. _boxMorphTargets.setFromBufferAttribute(morphAttribute);
  7083. if (this.morphTargetsRelative) {
  7084. _vector$4.addVectors(_box$2.min, _boxMorphTargets.min);
  7085. _box$2.expandByPoint(_vector$4);
  7086. _vector$4.addVectors(_box$2.max, _boxMorphTargets.max);
  7087. _box$2.expandByPoint(_vector$4);
  7088. } else {
  7089. _box$2.expandByPoint(_boxMorphTargets.min);
  7090. _box$2.expandByPoint(_boxMorphTargets.max);
  7091. }
  7092. }
  7093. }
  7094. _box$2.getCenter(center); // second, try to find a boundingSphere with a radius smaller than the
  7095. // boundingSphere of the boundingBox: sqrt(3) smaller in the best case
  7096. let maxRadiusSq = 0;
  7097. for (let i = 0, il = position.count; i < il; i++) {
  7098. _vector$4.fromBufferAttribute(position, i);
  7099. maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(_vector$4));
  7100. } // process morph attributes if present
  7101. if (morphAttributesPosition) {
  7102. for (let i = 0, il = morphAttributesPosition.length; i < il; i++) {
  7103. const morphAttribute = morphAttributesPosition[i];
  7104. const morphTargetsRelative = this.morphTargetsRelative;
  7105. for (let j = 0, jl = morphAttribute.count; j < jl; j++) {
  7106. _vector$4.fromBufferAttribute(morphAttribute, j);
  7107. if (morphTargetsRelative) {
  7108. _offset.fromBufferAttribute(position, j);
  7109. _vector$4.add(_offset);
  7110. }
  7111. maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(_vector$4));
  7112. }
  7113. }
  7114. }
  7115. this.boundingSphere.radius = Math.sqrt(maxRadiusSq);
  7116. if (isNaN(this.boundingSphere.radius)) {
  7117. console.error('THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this);
  7118. }
  7119. }
  7120. },
  7121. computeFaceNormals: function () {// backwards compatibility
  7122. },
  7123. computeVertexNormals: function () {
  7124. const index = this.index;
  7125. const positionAttribute = this.getAttribute('position');
  7126. if (positionAttribute !== undefined) {
  7127. let normalAttribute = this.getAttribute('normal');
  7128. if (normalAttribute === undefined) {
  7129. normalAttribute = new BufferAttribute(new Float32Array(positionAttribute.count * 3), 3);
  7130. this.setAttribute('normal', normalAttribute);
  7131. } else {
  7132. // reset existing normals to zero
  7133. for (let i = 0, il = normalAttribute.count; i < il; i++) {
  7134. normalAttribute.setXYZ(i, 0, 0, 0);
  7135. }
  7136. }
  7137. const pA = new Vector3(),
  7138. pB = new Vector3(),
  7139. pC = new Vector3();
  7140. const nA = new Vector3(),
  7141. nB = new Vector3(),
  7142. nC = new Vector3();
  7143. const cb = new Vector3(),
  7144. ab = new Vector3(); // indexed elements
  7145. if (index) {
  7146. for (let i = 0, il = index.count; i < il; i += 3) {
  7147. const vA = index.getX(i + 0);
  7148. const vB = index.getX(i + 1);
  7149. const vC = index.getX(i + 2);
  7150. pA.fromBufferAttribute(positionAttribute, vA);
  7151. pB.fromBufferAttribute(positionAttribute, vB);
  7152. pC.fromBufferAttribute(positionAttribute, vC);
  7153. cb.subVectors(pC, pB);
  7154. ab.subVectors(pA, pB);
  7155. cb.cross(ab);
  7156. nA.fromBufferAttribute(normalAttribute, vA);
  7157. nB.fromBufferAttribute(normalAttribute, vB);
  7158. nC.fromBufferAttribute(normalAttribute, vC);
  7159. nA.add(cb);
  7160. nB.add(cb);
  7161. nC.add(cb);
  7162. normalAttribute.setXYZ(vA, nA.x, nA.y, nA.z);
  7163. normalAttribute.setXYZ(vB, nB.x, nB.y, nB.z);
  7164. normalAttribute.setXYZ(vC, nC.x, nC.y, nC.z);
  7165. }
  7166. } else {
  7167. // non-indexed elements (unconnected triangle soup)
  7168. for (let i = 0, il = positionAttribute.count; i < il; i += 3) {
  7169. pA.fromBufferAttribute(positionAttribute, i + 0);
  7170. pB.fromBufferAttribute(positionAttribute, i + 1);
  7171. pC.fromBufferAttribute(positionAttribute, i + 2);
  7172. cb.subVectors(pC, pB);
  7173. ab.subVectors(pA, pB);
  7174. cb.cross(ab);
  7175. normalAttribute.setXYZ(i + 0, cb.x, cb.y, cb.z);
  7176. normalAttribute.setXYZ(i + 1, cb.x, cb.y, cb.z);
  7177. normalAttribute.setXYZ(i + 2, cb.x, cb.y, cb.z);
  7178. }
  7179. }
  7180. this.normalizeNormals();
  7181. normalAttribute.needsUpdate = true;
  7182. }
  7183. },
  7184. merge: function (geometry, offset) {
  7185. if (!(geometry && geometry.isBufferGeometry)) {
  7186. console.error('THREE.BufferGeometry.merge(): geometry not an instance of THREE.BufferGeometry.', geometry);
  7187. return;
  7188. }
  7189. if (offset === undefined) {
  7190. offset = 0;
  7191. console.warn('THREE.BufferGeometry.merge(): Overwriting original geometry, starting at offset=0. ' + 'Use BufferGeometryUtils.mergeBufferGeometries() for lossless merge.');
  7192. }
  7193. const attributes = this.attributes;
  7194. for (const key in attributes) {
  7195. if (geometry.attributes[key] === undefined) continue;
  7196. const attribute1 = attributes[key];
  7197. const attributeArray1 = attribute1.array;
  7198. const attribute2 = geometry.attributes[key];
  7199. const attributeArray2 = attribute2.array;
  7200. const attributeOffset = attribute2.itemSize * offset;
  7201. const length = Math.min(attributeArray2.length, attributeArray1.length - attributeOffset);
  7202. for (let i = 0, j = attributeOffset; i < length; i++, j++) {
  7203. attributeArray1[j] = attributeArray2[i];
  7204. }
  7205. }
  7206. return this;
  7207. },
  7208. normalizeNormals: function () {
  7209. const normals = this.attributes.normal;
  7210. for (let i = 0, il = normals.count; i < il; i++) {
  7211. _vector$4.fromBufferAttribute(normals, i);
  7212. _vector$4.normalize();
  7213. normals.setXYZ(i, _vector$4.x, _vector$4.y, _vector$4.z);
  7214. }
  7215. },
  7216. toNonIndexed: function () {
  7217. function convertBufferAttribute(attribute, indices) {
  7218. const array = attribute.array;
  7219. const itemSize = attribute.itemSize;
  7220. const normalized = attribute.normalized;
  7221. const array2 = new array.constructor(indices.length * itemSize);
  7222. let index = 0,
  7223. index2 = 0;
  7224. for (let i = 0, l = indices.length; i < l; i++) {
  7225. index = indices[i] * itemSize;
  7226. for (let j = 0; j < itemSize; j++) {
  7227. array2[index2++] = array[index++];
  7228. }
  7229. }
  7230. return new BufferAttribute(array2, itemSize, normalized);
  7231. } //
  7232. if (this.index === null) {
  7233. console.warn('THREE.BufferGeometry.toNonIndexed(): Geometry is already non-indexed.');
  7234. return this;
  7235. }
  7236. const geometry2 = new BufferGeometry();
  7237. const indices = this.index.array;
  7238. const attributes = this.attributes; // attributes
  7239. for (const name in attributes) {
  7240. const attribute = attributes[name];
  7241. const newAttribute = convertBufferAttribute(attribute, indices);
  7242. geometry2.setAttribute(name, newAttribute);
  7243. } // morph attributes
  7244. const morphAttributes = this.morphAttributes;
  7245. for (const name in morphAttributes) {
  7246. const morphArray = [];
  7247. const morphAttribute = morphAttributes[name]; // morphAttribute: array of Float32BufferAttributes
  7248. for (let i = 0, il = morphAttribute.length; i < il; i++) {
  7249. const attribute = morphAttribute[i];
  7250. const newAttribute = convertBufferAttribute(attribute, indices);
  7251. morphArray.push(newAttribute);
  7252. }
  7253. geometry2.morphAttributes[name] = morphArray;
  7254. }
  7255. geometry2.morphTargetsRelative = this.morphTargetsRelative; // groups
  7256. const groups = this.groups;
  7257. for (let i = 0, l = groups.length; i < l; i++) {
  7258. const group = groups[i];
  7259. geometry2.addGroup(group.start, group.count, group.materialIndex);
  7260. }
  7261. return geometry2;
  7262. },
  7263. toJSON: function () {
  7264. const data = {
  7265. metadata: {
  7266. version: 4.5,
  7267. type: 'BufferGeometry',
  7268. generator: 'BufferGeometry.toJSON'
  7269. }
  7270. }; // standard BufferGeometry serialization
  7271. data.uuid = this.uuid;
  7272. data.type = this.type;
  7273. if (this.name !== '') data.name = this.name;
  7274. if (Object.keys(this.userData).length > 0) data.userData = this.userData;
  7275. if (this.parameters !== undefined) {
  7276. const parameters = this.parameters;
  7277. for (const key in parameters) {
  7278. if (parameters[key] !== undefined) data[key] = parameters[key];
  7279. }
  7280. return data;
  7281. }
  7282. data.data = {
  7283. attributes: {}
  7284. };
  7285. const index = this.index;
  7286. if (index !== null) {
  7287. data.data.index = {
  7288. type: index.array.constructor.name,
  7289. array: Array.prototype.slice.call(index.array)
  7290. };
  7291. }
  7292. const attributes = this.attributes;
  7293. for (const key in attributes) {
  7294. const attribute = attributes[key];
  7295. const attributeData = attribute.toJSON(data.data);
  7296. if (attribute.name !== '') attributeData.name = attribute.name;
  7297. data.data.attributes[key] = attributeData;
  7298. }
  7299. const morphAttributes = {};
  7300. let hasMorphAttributes = false;
  7301. for (const key in this.morphAttributes) {
  7302. const attributeArray = this.morphAttributes[key];
  7303. const array = [];
  7304. for (let i = 0, il = attributeArray.length; i < il; i++) {
  7305. const attribute = attributeArray[i];
  7306. const attributeData = attribute.toJSON(data.data);
  7307. if (attribute.name !== '') attributeData.name = attribute.name;
  7308. array.push(attributeData);
  7309. }
  7310. if (array.length > 0) {
  7311. morphAttributes[key] = array;
  7312. hasMorphAttributes = true;
  7313. }
  7314. }
  7315. if (hasMorphAttributes) {
  7316. data.data.morphAttributes = morphAttributes;
  7317. data.data.morphTargetsRelative = this.morphTargetsRelative;
  7318. }
  7319. const groups = this.groups;
  7320. if (groups.length > 0) {
  7321. data.data.groups = JSON.parse(JSON.stringify(groups));
  7322. }
  7323. const boundingSphere = this.boundingSphere;
  7324. if (boundingSphere !== null) {
  7325. data.data.boundingSphere = {
  7326. center: boundingSphere.center.toArray(),
  7327. radius: boundingSphere.radius
  7328. };
  7329. }
  7330. return data;
  7331. },
  7332. clone: function () {
  7333. /*
  7334. // Handle primitives
  7335. const parameters = this.parameters;
  7336. if ( parameters !== undefined ) {
  7337. const values = [];
  7338. for ( const key in parameters ) {
  7339. values.push( parameters[ key ] );
  7340. }
  7341. const geometry = Object.create( this.constructor.prototype );
  7342. this.constructor.apply( geometry, values );
  7343. return geometry;
  7344. }
  7345. return new this.constructor().copy( this );
  7346. */
  7347. return new BufferGeometry().copy(this);
  7348. },
  7349. copy: function (source) {
  7350. // reset
  7351. this.index = null;
  7352. this.attributes = {};
  7353. this.morphAttributes = {};
  7354. this.groups = [];
  7355. this.boundingBox = null;
  7356. this.boundingSphere = null; // used for storing cloned, shared data
  7357. const data = {}; // name
  7358. this.name = source.name; // index
  7359. const index = source.index;
  7360. if (index !== null) {
  7361. this.setIndex(index.clone(data));
  7362. } // attributes
  7363. const attributes = source.attributes;
  7364. for (const name in attributes) {
  7365. const attribute = attributes[name];
  7366. this.setAttribute(name, attribute.clone(data));
  7367. } // morph attributes
  7368. const morphAttributes = source.morphAttributes;
  7369. for (const name in morphAttributes) {
  7370. const array = [];
  7371. const morphAttribute = morphAttributes[name]; // morphAttribute: array of Float32BufferAttributes
  7372. for (let i = 0, l = morphAttribute.length; i < l; i++) {
  7373. array.push(morphAttribute[i].clone(data));
  7374. }
  7375. this.morphAttributes[name] = array;
  7376. }
  7377. this.morphTargetsRelative = source.morphTargetsRelative; // groups
  7378. const groups = source.groups;
  7379. for (let i = 0, l = groups.length; i < l; i++) {
  7380. const group = groups[i];
  7381. this.addGroup(group.start, group.count, group.materialIndex);
  7382. } // bounding box
  7383. const boundingBox = source.boundingBox;
  7384. if (boundingBox !== null) {
  7385. this.boundingBox = boundingBox.clone();
  7386. } // bounding sphere
  7387. const boundingSphere = source.boundingSphere;
  7388. if (boundingSphere !== null) {
  7389. this.boundingSphere = boundingSphere.clone();
  7390. } // draw range
  7391. this.drawRange.start = source.drawRange.start;
  7392. this.drawRange.count = source.drawRange.count; // user data
  7393. this.userData = source.userData;
  7394. return this;
  7395. },
  7396. dispose: function () {
  7397. this.dispatchEvent({
  7398. type: 'dispose'
  7399. });
  7400. }
  7401. });
  7402. const _inverseMatrix = new Matrix4();
  7403. const _ray = new Ray();
  7404. const _sphere = new Sphere();
  7405. const _vA = new Vector3();
  7406. const _vB = new Vector3();
  7407. const _vC = new Vector3();
  7408. const _tempA = new Vector3();
  7409. const _tempB = new Vector3();
  7410. const _tempC = new Vector3();
  7411. const _morphA = new Vector3();
  7412. const _morphB = new Vector3();
  7413. const _morphC = new Vector3();
  7414. const _uvA = new Vector2();
  7415. const _uvB = new Vector2();
  7416. const _uvC = new Vector2();
  7417. const _intersectionPoint = new Vector3();
  7418. const _intersectionPointWorld = new Vector3();
  7419. function Mesh(geometry, material) {
  7420. Object3D.call(this);
  7421. this.type = 'Mesh';
  7422. this.geometry = geometry !== undefined ? geometry : new BufferGeometry();
  7423. this.material = material !== undefined ? material : new MeshBasicMaterial();
  7424. this.updateMorphTargets();
  7425. }
  7426. Mesh.prototype = Object.assign(Object.create(Object3D.prototype), {
  7427. constructor: Mesh,
  7428. isMesh: true,
  7429. copy: function (source) {
  7430. Object3D.prototype.copy.call(this, source);
  7431. if (source.morphTargetInfluences !== undefined) {
  7432. this.morphTargetInfluences = source.morphTargetInfluences.slice();
  7433. }
  7434. if (source.morphTargetDictionary !== undefined) {
  7435. this.morphTargetDictionary = Object.assign({}, source.morphTargetDictionary);
  7436. }
  7437. this.material = source.material;
  7438. this.geometry = source.geometry;
  7439. return this;
  7440. },
  7441. updateMorphTargets: function () {
  7442. const geometry = this.geometry;
  7443. if (geometry.isBufferGeometry) {
  7444. const morphAttributes = geometry.morphAttributes;
  7445. const keys = Object.keys(morphAttributes);
  7446. if (keys.length > 0) {
  7447. const morphAttribute = morphAttributes[keys[0]];
  7448. if (morphAttribute !== undefined) {
  7449. this.morphTargetInfluences = [];
  7450. this.morphTargetDictionary = {};
  7451. for (let m = 0, ml = morphAttribute.length; m < ml; m++) {
  7452. const name = morphAttribute[m].name || String(m);
  7453. this.morphTargetInfluences.push(0);
  7454. this.morphTargetDictionary[name] = m;
  7455. }
  7456. }
  7457. }
  7458. } else {
  7459. const morphTargets = geometry.morphTargets;
  7460. if (morphTargets !== undefined && morphTargets.length > 0) {
  7461. console.error('THREE.Mesh.updateMorphTargets() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');
  7462. }
  7463. }
  7464. },
  7465. raycast: function (raycaster, intersects) {
  7466. const geometry = this.geometry;
  7467. const material = this.material;
  7468. const matrixWorld = this.matrixWorld;
  7469. if (material === undefined) return; // Checking boundingSphere distance to ray
  7470. if (geometry.boundingSphere === null) geometry.computeBoundingSphere();
  7471. _sphere.copy(geometry.boundingSphere);
  7472. _sphere.applyMatrix4(matrixWorld);
  7473. if (raycaster.ray.intersectsSphere(_sphere) === false) return; //
  7474. _inverseMatrix.copy(matrixWorld).invert();
  7475. _ray.copy(raycaster.ray).applyMatrix4(_inverseMatrix); // Check boundingBox before continuing
  7476. if (geometry.boundingBox !== null) {
  7477. if (_ray.intersectsBox(geometry.boundingBox) === false) return;
  7478. }
  7479. let intersection;
  7480. if (geometry.isBufferGeometry) {
  7481. const index = geometry.index;
  7482. const position = geometry.attributes.position;
  7483. const morphPosition = geometry.morphAttributes.position;
  7484. const morphTargetsRelative = geometry.morphTargetsRelative;
  7485. const uv = geometry.attributes.uv;
  7486. const uv2 = geometry.attributes.uv2;
  7487. const groups = geometry.groups;
  7488. const drawRange = geometry.drawRange;
  7489. if (index !== null) {
  7490. // indexed buffer geometry
  7491. if (Array.isArray(material)) {
  7492. for (let i = 0, il = groups.length; i < il; i++) {
  7493. const group = groups[i];
  7494. const groupMaterial = material[group.materialIndex];
  7495. const start = Math.max(group.start, drawRange.start);
  7496. const end = Math.min(group.start + group.count, drawRange.start + drawRange.count);
  7497. for (let j = start, jl = end; j < jl; j += 3) {
  7498. const a = index.getX(j);
  7499. const b = index.getX(j + 1);
  7500. const c = index.getX(j + 2);
  7501. intersection = checkBufferGeometryIntersection(this, groupMaterial, raycaster, _ray, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c);
  7502. if (intersection) {
  7503. intersection.faceIndex = Math.floor(j / 3); // triangle number in indexed buffer semantics
  7504. intersection.face.materialIndex = group.materialIndex;
  7505. intersects.push(intersection);
  7506. }
  7507. }
  7508. }
  7509. } else {
  7510. const start = Math.max(0, drawRange.start);
  7511. const end = Math.min(index.count, drawRange.start + drawRange.count);
  7512. for (let i = start, il = end; i < il; i += 3) {
  7513. const a = index.getX(i);
  7514. const b = index.getX(i + 1);
  7515. const c = index.getX(i + 2);
  7516. intersection = checkBufferGeometryIntersection(this, material, raycaster, _ray, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c);
  7517. if (intersection) {
  7518. intersection.faceIndex = Math.floor(i / 3); // triangle number in indexed buffer semantics
  7519. intersects.push(intersection);
  7520. }
  7521. }
  7522. }
  7523. } else if (position !== undefined) {
  7524. // non-indexed buffer geometry
  7525. if (Array.isArray(material)) {
  7526. for (let i = 0, il = groups.length; i < il; i++) {
  7527. const group = groups[i];
  7528. const groupMaterial = material[group.materialIndex];
  7529. const start = Math.max(group.start, drawRange.start);
  7530. const end = Math.min(group.start + group.count, drawRange.start + drawRange.count);
  7531. for (let j = start, jl = end; j < jl; j += 3) {
  7532. const a = j;
  7533. const b = j + 1;
  7534. const c = j + 2;
  7535. intersection = checkBufferGeometryIntersection(this, groupMaterial, raycaster, _ray, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c);
  7536. if (intersection) {
  7537. intersection.faceIndex = Math.floor(j / 3); // triangle number in non-indexed buffer semantics
  7538. intersection.face.materialIndex = group.materialIndex;
  7539. intersects.push(intersection);
  7540. }
  7541. }
  7542. }
  7543. } else {
  7544. const start = Math.max(0, drawRange.start);
  7545. const end = Math.min(position.count, drawRange.start + drawRange.count);
  7546. for (let i = start, il = end; i < il; i += 3) {
  7547. const a = i;
  7548. const b = i + 1;
  7549. const c = i + 2;
  7550. intersection = checkBufferGeometryIntersection(this, material, raycaster, _ray, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c);
  7551. if (intersection) {
  7552. intersection.faceIndex = Math.floor(i / 3); // triangle number in non-indexed buffer semantics
  7553. intersects.push(intersection);
  7554. }
  7555. }
  7556. }
  7557. }
  7558. } else if (geometry.isGeometry) {
  7559. const isMultiMaterial = Array.isArray(material);
  7560. const vertices = geometry.vertices;
  7561. const faces = geometry.faces;
  7562. let uvs;
  7563. const faceVertexUvs = geometry.faceVertexUvs[0];
  7564. if (faceVertexUvs.length > 0) uvs = faceVertexUvs;
  7565. for (let f = 0, fl = faces.length; f < fl; f++) {
  7566. const face = faces[f];
  7567. const faceMaterial = isMultiMaterial ? material[face.materialIndex] : material;
  7568. if (faceMaterial === undefined) continue;
  7569. const fvA = vertices[face.a];
  7570. const fvB = vertices[face.b];
  7571. const fvC = vertices[face.c];
  7572. intersection = checkIntersection(this, faceMaterial, raycaster, _ray, fvA, fvB, fvC, _intersectionPoint);
  7573. if (intersection) {
  7574. if (uvs && uvs[f]) {
  7575. const uvs_f = uvs[f];
  7576. _uvA.copy(uvs_f[0]);
  7577. _uvB.copy(uvs_f[1]);
  7578. _uvC.copy(uvs_f[2]);
  7579. intersection.uv = Triangle.getUV(_intersectionPoint, fvA, fvB, fvC, _uvA, _uvB, _uvC, new Vector2());
  7580. }
  7581. intersection.face = face;
  7582. intersection.faceIndex = f;
  7583. intersects.push(intersection);
  7584. }
  7585. }
  7586. }
  7587. }
  7588. });
  7589. function checkIntersection(object, material, raycaster, ray, pA, pB, pC, point) {
  7590. let intersect;
  7591. if (material.side === BackSide) {
  7592. intersect = ray.intersectTriangle(pC, pB, pA, true, point);
  7593. } else {
  7594. intersect = ray.intersectTriangle(pA, pB, pC, material.side !== DoubleSide, point);
  7595. }
  7596. if (intersect === null) return null;
  7597. _intersectionPointWorld.copy(point);
  7598. _intersectionPointWorld.applyMatrix4(object.matrixWorld);
  7599. const distance = raycaster.ray.origin.distanceTo(_intersectionPointWorld);
  7600. if (distance < raycaster.near || distance > raycaster.far) return null;
  7601. return {
  7602. distance: distance,
  7603. point: _intersectionPointWorld.clone(),
  7604. object: object
  7605. };
  7606. }
  7607. function checkBufferGeometryIntersection(object, material, raycaster, ray, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c) {
  7608. _vA.fromBufferAttribute(position, a);
  7609. _vB.fromBufferAttribute(position, b);
  7610. _vC.fromBufferAttribute(position, c);
  7611. const morphInfluences = object.morphTargetInfluences;
  7612. if (material.morphTargets && morphPosition && morphInfluences) {
  7613. _morphA.set(0, 0, 0);
  7614. _morphB.set(0, 0, 0);
  7615. _morphC.set(0, 0, 0);
  7616. for (let i = 0, il = morphPosition.length; i < il; i++) {
  7617. const influence = morphInfluences[i];
  7618. const morphAttribute = morphPosition[i];
  7619. if (influence === 0) continue;
  7620. _tempA.fromBufferAttribute(morphAttribute, a);
  7621. _tempB.fromBufferAttribute(morphAttribute, b);
  7622. _tempC.fromBufferAttribute(morphAttribute, c);
  7623. if (morphTargetsRelative) {
  7624. _morphA.addScaledVector(_tempA, influence);
  7625. _morphB.addScaledVector(_tempB, influence);
  7626. _morphC.addScaledVector(_tempC, influence);
  7627. } else {
  7628. _morphA.addScaledVector(_tempA.sub(_vA), influence);
  7629. _morphB.addScaledVector(_tempB.sub(_vB), influence);
  7630. _morphC.addScaledVector(_tempC.sub(_vC), influence);
  7631. }
  7632. }
  7633. _vA.add(_morphA);
  7634. _vB.add(_morphB);
  7635. _vC.add(_morphC);
  7636. }
  7637. if (object.isSkinnedMesh) {
  7638. object.boneTransform(a, _vA);
  7639. object.boneTransform(b, _vB);
  7640. object.boneTransform(c, _vC);
  7641. }
  7642. const intersection = checkIntersection(object, material, raycaster, ray, _vA, _vB, _vC, _intersectionPoint);
  7643. if (intersection) {
  7644. if (uv) {
  7645. _uvA.fromBufferAttribute(uv, a);
  7646. _uvB.fromBufferAttribute(uv, b);
  7647. _uvC.fromBufferAttribute(uv, c);
  7648. intersection.uv = Triangle.getUV(_intersectionPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2());
  7649. }
  7650. if (uv2) {
  7651. _uvA.fromBufferAttribute(uv2, a);
  7652. _uvB.fromBufferAttribute(uv2, b);
  7653. _uvC.fromBufferAttribute(uv2, c);
  7654. intersection.uv2 = Triangle.getUV(_intersectionPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2());
  7655. }
  7656. const face = new Face3(a, b, c);
  7657. Triangle.getNormal(_vA, _vB, _vC, face.normal);
  7658. intersection.face = face;
  7659. }
  7660. return intersection;
  7661. }
  7662. class BoxBufferGeometry extends BufferGeometry {
  7663. constructor(width = 1, height = 1, depth = 1, widthSegments = 1, heightSegments = 1, depthSegments = 1) {
  7664. super();
  7665. this.type = 'BoxBufferGeometry';
  7666. this.parameters = {
  7667. width: width,
  7668. height: height,
  7669. depth: depth,
  7670. widthSegments: widthSegments,
  7671. heightSegments: heightSegments,
  7672. depthSegments: depthSegments
  7673. };
  7674. const scope = this; // segments
  7675. widthSegments = Math.floor(widthSegments);
  7676. heightSegments = Math.floor(heightSegments);
  7677. depthSegments = Math.floor(depthSegments); // buffers
  7678. const indices = [];
  7679. const vertices = [];
  7680. const normals = [];
  7681. const uvs = []; // helper variables
  7682. let numberOfVertices = 0;
  7683. let groupStart = 0; // build each side of the box geometry
  7684. buildPlane('z', 'y', 'x', -1, -1, depth, height, width, depthSegments, heightSegments, 0); // px
  7685. buildPlane('z', 'y', 'x', 1, -1, depth, height, -width, depthSegments, heightSegments, 1); // nx
  7686. buildPlane('x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2); // py
  7687. buildPlane('x', 'z', 'y', 1, -1, width, depth, -height, widthSegments, depthSegments, 3); // ny
  7688. buildPlane('x', 'y', 'z', 1, -1, width, height, depth, widthSegments, heightSegments, 4); // pz
  7689. buildPlane('x', 'y', 'z', -1, -1, width, height, -depth, widthSegments, heightSegments, 5); // nz
  7690. // build geometry
  7691. this.setIndex(indices);
  7692. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  7693. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  7694. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  7695. function buildPlane(u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex) {
  7696. const segmentWidth = width / gridX;
  7697. const segmentHeight = height / gridY;
  7698. const widthHalf = width / 2;
  7699. const heightHalf = height / 2;
  7700. const depthHalf = depth / 2;
  7701. const gridX1 = gridX + 1;
  7702. const gridY1 = gridY + 1;
  7703. let vertexCounter = 0;
  7704. let groupCount = 0;
  7705. const vector = new Vector3(); // generate vertices, normals and uvs
  7706. for (let iy = 0; iy < gridY1; iy++) {
  7707. const y = iy * segmentHeight - heightHalf;
  7708. for (let ix = 0; ix < gridX1; ix++) {
  7709. const x = ix * segmentWidth - widthHalf; // set values to correct vector component
  7710. vector[u] = x * udir;
  7711. vector[v] = y * vdir;
  7712. vector[w] = depthHalf; // now apply vector to vertex buffer
  7713. vertices.push(vector.x, vector.y, vector.z); // set values to correct vector component
  7714. vector[u] = 0;
  7715. vector[v] = 0;
  7716. vector[w] = depth > 0 ? 1 : -1; // now apply vector to normal buffer
  7717. normals.push(vector.x, vector.y, vector.z); // uvs
  7718. uvs.push(ix / gridX);
  7719. uvs.push(1 - iy / gridY); // counters
  7720. vertexCounter += 1;
  7721. }
  7722. } // indices
  7723. // 1. you need three indices to draw a single face
  7724. // 2. a single segment consists of two faces
  7725. // 3. so we need to generate six (2*3) indices per segment
  7726. for (let iy = 0; iy < gridY; iy++) {
  7727. for (let ix = 0; ix < gridX; ix++) {
  7728. const a = numberOfVertices + ix + gridX1 * iy;
  7729. const b = numberOfVertices + ix + gridX1 * (iy + 1);
  7730. const c = numberOfVertices + (ix + 1) + gridX1 * (iy + 1);
  7731. const d = numberOfVertices + (ix + 1) + gridX1 * iy; // faces
  7732. indices.push(a, b, d);
  7733. indices.push(b, c, d); // increase counter
  7734. groupCount += 6;
  7735. }
  7736. } // add a group to the geometry. this will ensure multi material support
  7737. scope.addGroup(groupStart, groupCount, materialIndex); // calculate new start value for groups
  7738. groupStart += groupCount; // update total number of vertices
  7739. numberOfVertices += vertexCounter;
  7740. }
  7741. }
  7742. }
  7743. /**
  7744. * Uniform Utilities
  7745. */
  7746. exports.BoxBufferGeometry = BoxBufferGeometry;
  7747. function cloneUniforms(src) {
  7748. const dst = {};
  7749. for (const u in src) {
  7750. dst[u] = {};
  7751. for (const p in src[u]) {
  7752. const property = src[u][p];
  7753. if (property && (property.isColor || property.isMatrix3 || property.isMatrix4 || property.isVector2 || property.isVector3 || property.isVector4 || property.isTexture)) {
  7754. dst[u][p] = property.clone();
  7755. } else if (Array.isArray(property)) {
  7756. dst[u][p] = property.slice();
  7757. } else {
  7758. dst[u][p] = property;
  7759. }
  7760. }
  7761. }
  7762. return dst;
  7763. }
  7764. function mergeUniforms(uniforms) {
  7765. const merged = {};
  7766. for (let u = 0; u < uniforms.length; u++) {
  7767. const tmp = cloneUniforms(uniforms[u]);
  7768. for (const p in tmp) {
  7769. merged[p] = tmp[p];
  7770. }
  7771. }
  7772. return merged;
  7773. } // Legacy
  7774. const UniformsUtils = {
  7775. clone: cloneUniforms,
  7776. merge: mergeUniforms
  7777. };
  7778. exports.UniformsUtils = UniformsUtils;
  7779. var default_vertex = "void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}";
  7780. var default_fragment = "void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}";
  7781. /**
  7782. * parameters = {
  7783. * defines: { "label" : "value" },
  7784. * uniforms: { "parameter1": { value: 1.0 }, "parameter2": { value2: 2 } },
  7785. *
  7786. * fragmentShader: <string>,
  7787. * vertexShader: <string>,
  7788. *
  7789. * wireframe: <boolean>,
  7790. * wireframeLinewidth: <float>,
  7791. *
  7792. * lights: <bool>,
  7793. *
  7794. * skinning: <bool>,
  7795. * morphTargets: <bool>,
  7796. * morphNormals: <bool>
  7797. * }
  7798. */
  7799. function ShaderMaterial(parameters) {
  7800. Material.call(this);
  7801. this.type = 'ShaderMaterial';
  7802. this.defines = {};
  7803. this.uniforms = {};
  7804. this.vertexShader = default_vertex;
  7805. this.fragmentShader = default_fragment;
  7806. this.linewidth = 1;
  7807. this.wireframe = false;
  7808. this.wireframeLinewidth = 1;
  7809. this.fog = false; // set to use scene fog
  7810. this.lights = false; // set to use scene lights
  7811. this.clipping = false; // set to use user-defined clipping planes
  7812. this.skinning = false; // set to use skinning attribute streams
  7813. this.morphTargets = false; // set to use morph targets
  7814. this.morphNormals = false; // set to use morph normals
  7815. this.extensions = {
  7816. derivatives: false,
  7817. // set to use derivatives
  7818. fragDepth: false,
  7819. // set to use fragment depth values
  7820. drawBuffers: false,
  7821. // set to use draw buffers
  7822. shaderTextureLOD: false // set to use shader texture LOD
  7823. }; // When rendered geometry doesn't include these attributes but the material does,
  7824. // use these default values in WebGL. This avoids errors when buffer data is missing.
  7825. this.defaultAttributeValues = {
  7826. 'color': [1, 1, 1],
  7827. 'uv': [0, 0],
  7828. 'uv2': [0, 0]
  7829. };
  7830. this.index0AttributeName = undefined;
  7831. this.uniformsNeedUpdate = false;
  7832. this.glslVersion = null;
  7833. if (parameters !== undefined) {
  7834. if (parameters.attributes !== undefined) {
  7835. console.error('THREE.ShaderMaterial: attributes should now be defined in THREE.BufferGeometry instead.');
  7836. }
  7837. this.setValues(parameters);
  7838. }
  7839. }
  7840. ShaderMaterial.prototype = Object.create(Material.prototype);
  7841. ShaderMaterial.prototype.constructor = ShaderMaterial;
  7842. ShaderMaterial.prototype.isShaderMaterial = true;
  7843. ShaderMaterial.prototype.copy = function (source) {
  7844. Material.prototype.copy.call(this, source);
  7845. this.fragmentShader = source.fragmentShader;
  7846. this.vertexShader = source.vertexShader;
  7847. this.uniforms = cloneUniforms(source.uniforms);
  7848. this.defines = Object.assign({}, source.defines);
  7849. this.wireframe = source.wireframe;
  7850. this.wireframeLinewidth = source.wireframeLinewidth;
  7851. this.lights = source.lights;
  7852. this.clipping = source.clipping;
  7853. this.skinning = source.skinning;
  7854. this.morphTargets = source.morphTargets;
  7855. this.morphNormals = source.morphNormals;
  7856. this.extensions = Object.assign({}, source.extensions);
  7857. this.glslVersion = source.glslVersion;
  7858. return this;
  7859. };
  7860. ShaderMaterial.prototype.toJSON = function (meta) {
  7861. const data = Material.prototype.toJSON.call(this, meta);
  7862. data.glslVersion = this.glslVersion;
  7863. data.uniforms = {};
  7864. for (const name in this.uniforms) {
  7865. const uniform = this.uniforms[name];
  7866. const value = uniform.value;
  7867. if (value && value.isTexture) {
  7868. data.uniforms[name] = {
  7869. type: 't',
  7870. value: value.toJSON(meta).uuid
  7871. };
  7872. } else if (value && value.isColor) {
  7873. data.uniforms[name] = {
  7874. type: 'c',
  7875. value: value.getHex()
  7876. };
  7877. } else if (value && value.isVector2) {
  7878. data.uniforms[name] = {
  7879. type: 'v2',
  7880. value: value.toArray()
  7881. };
  7882. } else if (value && value.isVector3) {
  7883. data.uniforms[name] = {
  7884. type: 'v3',
  7885. value: value.toArray()
  7886. };
  7887. } else if (value && value.isVector4) {
  7888. data.uniforms[name] = {
  7889. type: 'v4',
  7890. value: value.toArray()
  7891. };
  7892. } else if (value && value.isMatrix3) {
  7893. data.uniforms[name] = {
  7894. type: 'm3',
  7895. value: value.toArray()
  7896. };
  7897. } else if (value && value.isMatrix4) {
  7898. data.uniforms[name] = {
  7899. type: 'm4',
  7900. value: value.toArray()
  7901. };
  7902. } else {
  7903. data.uniforms[name] = {
  7904. value: value
  7905. }; // note: the array variants v2v, v3v, v4v, m4v and tv are not supported so far
  7906. }
  7907. }
  7908. if (Object.keys(this.defines).length > 0) data.defines = this.defines;
  7909. data.vertexShader = this.vertexShader;
  7910. data.fragmentShader = this.fragmentShader;
  7911. const extensions = {};
  7912. for (const key in this.extensions) {
  7913. if (this.extensions[key] === true) extensions[key] = true;
  7914. }
  7915. if (Object.keys(extensions).length > 0) data.extensions = extensions;
  7916. return data;
  7917. };
  7918. function Camera() {
  7919. Object3D.call(this);
  7920. this.type = 'Camera';
  7921. this.matrixWorldInverse = new Matrix4();
  7922. this.projectionMatrix = new Matrix4();
  7923. this.projectionMatrixInverse = new Matrix4();
  7924. }
  7925. Camera.prototype = Object.assign(Object.create(Object3D.prototype), {
  7926. constructor: Camera,
  7927. isCamera: true,
  7928. copy: function (source, recursive) {
  7929. Object3D.prototype.copy.call(this, source, recursive);
  7930. this.matrixWorldInverse.copy(source.matrixWorldInverse);
  7931. this.projectionMatrix.copy(source.projectionMatrix);
  7932. this.projectionMatrixInverse.copy(source.projectionMatrixInverse);
  7933. return this;
  7934. },
  7935. getWorldDirection: function (target) {
  7936. if (target === undefined) {
  7937. console.warn('THREE.Camera: .getWorldDirection() target is now required');
  7938. target = new Vector3();
  7939. }
  7940. this.updateWorldMatrix(true, false);
  7941. const e = this.matrixWorld.elements;
  7942. return target.set(-e[8], -e[9], -e[10]).normalize();
  7943. },
  7944. updateMatrixWorld: function (force) {
  7945. Object3D.prototype.updateMatrixWorld.call(this, force);
  7946. this.matrixWorldInverse.copy(this.matrixWorld).invert();
  7947. },
  7948. updateWorldMatrix: function (updateParents, updateChildren) {
  7949. Object3D.prototype.updateWorldMatrix.call(this, updateParents, updateChildren);
  7950. this.matrixWorldInverse.copy(this.matrixWorld).invert();
  7951. },
  7952. clone: function () {
  7953. return new this.constructor().copy(this);
  7954. }
  7955. });
  7956. function PerspectiveCamera(fov = 50, aspect = 1, near = 0.1, far = 2000) {
  7957. Camera.call(this);
  7958. this.type = 'PerspectiveCamera';
  7959. this.fov = fov;
  7960. this.zoom = 1;
  7961. this.near = near;
  7962. this.far = far;
  7963. this.focus = 10;
  7964. this.aspect = aspect;
  7965. this.view = null;
  7966. this.filmGauge = 35; // width of the film (default in millimeters)
  7967. this.filmOffset = 0; // horizontal film offset (same unit as gauge)
  7968. this.updateProjectionMatrix();
  7969. }
  7970. PerspectiveCamera.prototype = Object.assign(Object.create(Camera.prototype), {
  7971. constructor: PerspectiveCamera,
  7972. isPerspectiveCamera: true,
  7973. copy: function (source, recursive) {
  7974. Camera.prototype.copy.call(this, source, recursive);
  7975. this.fov = source.fov;
  7976. this.zoom = source.zoom;
  7977. this.near = source.near;
  7978. this.far = source.far;
  7979. this.focus = source.focus;
  7980. this.aspect = source.aspect;
  7981. this.view = source.view === null ? null : Object.assign({}, source.view);
  7982. this.filmGauge = source.filmGauge;
  7983. this.filmOffset = source.filmOffset;
  7984. return this;
  7985. },
  7986. /**
  7987. * Sets the FOV by focal length in respect to the current .filmGauge.
  7988. *
  7989. * The default film gauge is 35, so that the focal length can be specified for
  7990. * a 35mm (full frame) camera.
  7991. *
  7992. * Values for focal length and film gauge must have the same unit.
  7993. */
  7994. setFocalLength: function (focalLength) {
  7995. // see http://www.bobatkins.com/photography/technical/field_of_view.html
  7996. const vExtentSlope = 0.5 * this.getFilmHeight() / focalLength;
  7997. this.fov = MathUtils.RAD2DEG * 2 * Math.atan(vExtentSlope);
  7998. this.updateProjectionMatrix();
  7999. },
  8000. /**
  8001. * Calculates the focal length from the current .fov and .filmGauge.
  8002. */
  8003. getFocalLength: function () {
  8004. const vExtentSlope = Math.tan(MathUtils.DEG2RAD * 0.5 * this.fov);
  8005. return 0.5 * this.getFilmHeight() / vExtentSlope;
  8006. },
  8007. getEffectiveFOV: function () {
  8008. return MathUtils.RAD2DEG * 2 * Math.atan(Math.tan(MathUtils.DEG2RAD * 0.5 * this.fov) / this.zoom);
  8009. },
  8010. getFilmWidth: function () {
  8011. // film not completely covered in portrait format (aspect < 1)
  8012. return this.filmGauge * Math.min(this.aspect, 1);
  8013. },
  8014. getFilmHeight: function () {
  8015. // film not completely covered in landscape format (aspect > 1)
  8016. return this.filmGauge / Math.max(this.aspect, 1);
  8017. },
  8018. /**
  8019. * Sets an offset in a larger frustum. This is useful for multi-window or
  8020. * multi-monitor/multi-machine setups.
  8021. *
  8022. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  8023. * the monitors are in grid like this
  8024. *
  8025. * +---+---+---+
  8026. * | A | B | C |
  8027. * +---+---+---+
  8028. * | D | E | F |
  8029. * +---+---+---+
  8030. *
  8031. * then for each monitor you would call it like this
  8032. *
  8033. * const w = 1920;
  8034. * const h = 1080;
  8035. * const fullWidth = w * 3;
  8036. * const fullHeight = h * 2;
  8037. *
  8038. * --A--
  8039. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  8040. * --B--
  8041. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  8042. * --C--
  8043. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  8044. * --D--
  8045. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  8046. * --E--
  8047. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  8048. * --F--
  8049. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  8050. *
  8051. * Note there is no reason monitors have to be the same size or in a grid.
  8052. */
  8053. setViewOffset: function (fullWidth, fullHeight, x, y, width, height) {
  8054. this.aspect = fullWidth / fullHeight;
  8055. if (this.view === null) {
  8056. this.view = {
  8057. enabled: true,
  8058. fullWidth: 1,
  8059. fullHeight: 1,
  8060. offsetX: 0,
  8061. offsetY: 0,
  8062. width: 1,
  8063. height: 1
  8064. };
  8065. }
  8066. this.view.enabled = true;
  8067. this.view.fullWidth = fullWidth;
  8068. this.view.fullHeight = fullHeight;
  8069. this.view.offsetX = x;
  8070. this.view.offsetY = y;
  8071. this.view.width = width;
  8072. this.view.height = height;
  8073. this.updateProjectionMatrix();
  8074. },
  8075. clearViewOffset: function () {
  8076. if (this.view !== null) {
  8077. this.view.enabled = false;
  8078. }
  8079. this.updateProjectionMatrix();
  8080. },
  8081. updateProjectionMatrix: function () {
  8082. const near = this.near;
  8083. let top = near * Math.tan(MathUtils.DEG2RAD * 0.5 * this.fov) / this.zoom;
  8084. let height = 2 * top;
  8085. let width = this.aspect * height;
  8086. let left = -0.5 * width;
  8087. const view = this.view;
  8088. if (this.view !== null && this.view.enabled) {
  8089. const fullWidth = view.fullWidth,
  8090. fullHeight = view.fullHeight;
  8091. left += view.offsetX * width / fullWidth;
  8092. top -= view.offsetY * height / fullHeight;
  8093. width *= view.width / fullWidth;
  8094. height *= view.height / fullHeight;
  8095. }
  8096. const skew = this.filmOffset;
  8097. if (skew !== 0) left += near * skew / this.getFilmWidth();
  8098. this.projectionMatrix.makePerspective(left, left + width, top, top - height, near, this.far);
  8099. this.projectionMatrixInverse.copy(this.projectionMatrix).invert();
  8100. },
  8101. toJSON: function (meta) {
  8102. const data = Object3D.prototype.toJSON.call(this, meta);
  8103. data.object.fov = this.fov;
  8104. data.object.zoom = this.zoom;
  8105. data.object.near = this.near;
  8106. data.object.far = this.far;
  8107. data.object.focus = this.focus;
  8108. data.object.aspect = this.aspect;
  8109. if (this.view !== null) data.object.view = Object.assign({}, this.view);
  8110. data.object.filmGauge = this.filmGauge;
  8111. data.object.filmOffset = this.filmOffset;
  8112. return data;
  8113. }
  8114. });
  8115. const fov = 90,
  8116. aspect = 1;
  8117. function CubeCamera(near, far, renderTarget) {
  8118. Object3D.call(this);
  8119. this.type = 'CubeCamera';
  8120. if (renderTarget.isWebGLCubeRenderTarget !== true) {
  8121. console.error('THREE.CubeCamera: The constructor now expects an instance of WebGLCubeRenderTarget as third parameter.');
  8122. return;
  8123. }
  8124. this.renderTarget = renderTarget;
  8125. const cameraPX = new PerspectiveCamera(fov, aspect, near, far);
  8126. cameraPX.layers = this.layers;
  8127. cameraPX.up.set(0, -1, 0);
  8128. cameraPX.lookAt(new Vector3(1, 0, 0));
  8129. this.add(cameraPX);
  8130. const cameraNX = new PerspectiveCamera(fov, aspect, near, far);
  8131. cameraNX.layers = this.layers;
  8132. cameraNX.up.set(0, -1, 0);
  8133. cameraNX.lookAt(new Vector3(-1, 0, 0));
  8134. this.add(cameraNX);
  8135. const cameraPY = new PerspectiveCamera(fov, aspect, near, far);
  8136. cameraPY.layers = this.layers;
  8137. cameraPY.up.set(0, 0, 1);
  8138. cameraPY.lookAt(new Vector3(0, 1, 0));
  8139. this.add(cameraPY);
  8140. const cameraNY = new PerspectiveCamera(fov, aspect, near, far);
  8141. cameraNY.layers = this.layers;
  8142. cameraNY.up.set(0, 0, -1);
  8143. cameraNY.lookAt(new Vector3(0, -1, 0));
  8144. this.add(cameraNY);
  8145. const cameraPZ = new PerspectiveCamera(fov, aspect, near, far);
  8146. cameraPZ.layers = this.layers;
  8147. cameraPZ.up.set(0, -1, 0);
  8148. cameraPZ.lookAt(new Vector3(0, 0, 1));
  8149. this.add(cameraPZ);
  8150. const cameraNZ = new PerspectiveCamera(fov, aspect, near, far);
  8151. cameraNZ.layers = this.layers;
  8152. cameraNZ.up.set(0, -1, 0);
  8153. cameraNZ.lookAt(new Vector3(0, 0, -1));
  8154. this.add(cameraNZ);
  8155. this.update = function (renderer, scene) {
  8156. if (this.parent === null) this.updateMatrixWorld();
  8157. const currentXrEnabled = renderer.xr.enabled;
  8158. const currentRenderTarget = renderer.getRenderTarget();
  8159. renderer.xr.enabled = false;
  8160. const generateMipmaps = renderTarget.texture.generateMipmaps;
  8161. renderTarget.texture.generateMipmaps = false;
  8162. renderer.setRenderTarget(renderTarget, 0);
  8163. renderer.render(scene, cameraPX);
  8164. renderer.setRenderTarget(renderTarget, 1);
  8165. renderer.render(scene, cameraNX);
  8166. renderer.setRenderTarget(renderTarget, 2);
  8167. renderer.render(scene, cameraPY);
  8168. renderer.setRenderTarget(renderTarget, 3);
  8169. renderer.render(scene, cameraNY);
  8170. renderer.setRenderTarget(renderTarget, 4);
  8171. renderer.render(scene, cameraPZ);
  8172. renderTarget.texture.generateMipmaps = generateMipmaps;
  8173. renderer.setRenderTarget(renderTarget, 5);
  8174. renderer.render(scene, cameraNZ);
  8175. renderer.setRenderTarget(currentRenderTarget);
  8176. renderer.xr.enabled = currentXrEnabled;
  8177. };
  8178. }
  8179. CubeCamera.prototype = Object.create(Object3D.prototype);
  8180. CubeCamera.prototype.constructor = CubeCamera;
  8181. function CubeTexture(images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding) {
  8182. images = images !== undefined ? images : [];
  8183. mapping = mapping !== undefined ? mapping : CubeReflectionMapping;
  8184. format = format !== undefined ? format : RGBFormat;
  8185. Texture.call(this, images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding);
  8186. this.flipY = false; // Why CubeTexture._needsFlipEnvMap is necessary:
  8187. //
  8188. // By convention -- likely based on the RenderMan spec from the 1990's -- cube maps are specified by WebGL (and three.js)
  8189. // in a coordinate system in which positive-x is to the right when looking up the positive-z axis -- in other words,
  8190. // in a left-handed coordinate system. By continuing this convention, preexisting cube maps continued to render correctly.
  8191. // three.js uses a right-handed coordinate system. So environment maps used in three.js appear to have px and nx swapped
  8192. // and the flag _needsFlipEnvMap controls this conversion. The flip is not required (and thus _needsFlipEnvMap is set to false)
  8193. // when using WebGLCubeRenderTarget.texture as a cube texture.
  8194. this._needsFlipEnvMap = true;
  8195. }
  8196. CubeTexture.prototype = Object.create(Texture.prototype);
  8197. CubeTexture.prototype.constructor = CubeTexture;
  8198. CubeTexture.prototype.isCubeTexture = true;
  8199. Object.defineProperty(CubeTexture.prototype, 'images', {
  8200. get: function () {
  8201. return this.image;
  8202. },
  8203. set: function (value) {
  8204. this.image = value;
  8205. }
  8206. });
  8207. function WebGLCubeRenderTarget(size, options, dummy) {
  8208. if (Number.isInteger(options)) {
  8209. console.warn('THREE.WebGLCubeRenderTarget: constructor signature is now WebGLCubeRenderTarget( size, options )');
  8210. options = dummy;
  8211. }
  8212. WebGLRenderTarget.call(this, size, size, options);
  8213. options = options || {};
  8214. this.texture = new CubeTexture(undefined, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding);
  8215. this.texture._needsFlipEnvMap = false;
  8216. }
  8217. WebGLCubeRenderTarget.prototype = Object.create(WebGLRenderTarget.prototype);
  8218. WebGLCubeRenderTarget.prototype.constructor = WebGLCubeRenderTarget;
  8219. WebGLCubeRenderTarget.prototype.isWebGLCubeRenderTarget = true;
  8220. WebGLCubeRenderTarget.prototype.fromEquirectangularTexture = function (renderer, texture) {
  8221. this.texture.type = texture.type;
  8222. this.texture.format = RGBAFormat; // see #18859
  8223. this.texture.encoding = texture.encoding;
  8224. this.texture.generateMipmaps = texture.generateMipmaps;
  8225. this.texture.minFilter = texture.minFilter;
  8226. this.texture.magFilter = texture.magFilter;
  8227. const shader = {
  8228. uniforms: {
  8229. tEquirect: {
  8230. value: null
  8231. }
  8232. },
  8233. vertexShader:
  8234. /* glsl */
  8235. `
  8236. varying vec3 vWorldDirection;
  8237. vec3 transformDirection( in vec3 dir, in mat4 matrix ) {
  8238. return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );
  8239. }
  8240. void main() {
  8241. vWorldDirection = transformDirection( position, modelMatrix );
  8242. #include <begin_vertex>
  8243. #include <project_vertex>
  8244. }
  8245. `,
  8246. fragmentShader:
  8247. /* glsl */
  8248. `
  8249. uniform sampler2D tEquirect;
  8250. varying vec3 vWorldDirection;
  8251. #include <common>
  8252. void main() {
  8253. vec3 direction = normalize( vWorldDirection );
  8254. vec2 sampleUV = equirectUv( direction );
  8255. gl_FragColor = texture2D( tEquirect, sampleUV );
  8256. }
  8257. `
  8258. };
  8259. const geometry = new BoxBufferGeometry(5, 5, 5);
  8260. const material = new ShaderMaterial({
  8261. name: 'CubemapFromEquirect',
  8262. uniforms: cloneUniforms(shader.uniforms),
  8263. vertexShader: shader.vertexShader,
  8264. fragmentShader: shader.fragmentShader,
  8265. side: BackSide,
  8266. blending: NoBlending
  8267. });
  8268. material.uniforms.tEquirect.value = texture;
  8269. const mesh = new Mesh(geometry, material);
  8270. const currentMinFilter = texture.minFilter; // Avoid blurred poles
  8271. if (texture.minFilter === LinearMipmapLinearFilter) texture.minFilter = LinearFilter;
  8272. const camera = new CubeCamera(1, 10, this);
  8273. camera.update(renderer, mesh);
  8274. texture.minFilter = currentMinFilter;
  8275. mesh.geometry.dispose();
  8276. mesh.material.dispose();
  8277. return this;
  8278. };
  8279. WebGLCubeRenderTarget.prototype.clear = function (renderer, color, depth, stencil) {
  8280. const currentRenderTarget = renderer.getRenderTarget();
  8281. for (let i = 0; i < 6; i++) {
  8282. renderer.setRenderTarget(this, i);
  8283. renderer.clear(color, depth, stencil);
  8284. }
  8285. renderer.setRenderTarget(currentRenderTarget);
  8286. };
  8287. function DataTexture(data, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding) {
  8288. Texture.call(this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding);
  8289. this.image = {
  8290. data: data || null,
  8291. width: width || 1,
  8292. height: height || 1
  8293. };
  8294. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  8295. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  8296. this.generateMipmaps = false;
  8297. this.flipY = false;
  8298. this.unpackAlignment = 1;
  8299. this.needsUpdate = true;
  8300. }
  8301. DataTexture.prototype = Object.create(Texture.prototype);
  8302. DataTexture.prototype.constructor = DataTexture;
  8303. DataTexture.prototype.isDataTexture = true;
  8304. const _sphere$1 =
  8305. /*@__PURE__*/
  8306. new Sphere();
  8307. const _vector$5 =
  8308. /*@__PURE__*/
  8309. new Vector3();
  8310. class Frustum {
  8311. constructor(p0, p1, p2, p3, p4, p5) {
  8312. this.planes = [p0 !== undefined ? p0 : new Plane(), p1 !== undefined ? p1 : new Plane(), p2 !== undefined ? p2 : new Plane(), p3 !== undefined ? p3 : new Plane(), p4 !== undefined ? p4 : new Plane(), p5 !== undefined ? p5 : new Plane()];
  8313. }
  8314. set(p0, p1, p2, p3, p4, p5) {
  8315. const planes = this.planes;
  8316. planes[0].copy(p0);
  8317. planes[1].copy(p1);
  8318. planes[2].copy(p2);
  8319. planes[3].copy(p3);
  8320. planes[4].copy(p4);
  8321. planes[5].copy(p5);
  8322. return this;
  8323. }
  8324. clone() {
  8325. return new this.constructor().copy(this);
  8326. }
  8327. copy(frustum) {
  8328. const planes = this.planes;
  8329. for (let i = 0; i < 6; i++) {
  8330. planes[i].copy(frustum.planes[i]);
  8331. }
  8332. return this;
  8333. }
  8334. setFromProjectionMatrix(m) {
  8335. const planes = this.planes;
  8336. const me = m.elements;
  8337. const me0 = me[0],
  8338. me1 = me[1],
  8339. me2 = me[2],
  8340. me3 = me[3];
  8341. const me4 = me[4],
  8342. me5 = me[5],
  8343. me6 = me[6],
  8344. me7 = me[7];
  8345. const me8 = me[8],
  8346. me9 = me[9],
  8347. me10 = me[10],
  8348. me11 = me[11];
  8349. const me12 = me[12],
  8350. me13 = me[13],
  8351. me14 = me[14],
  8352. me15 = me[15];
  8353. planes[0].setComponents(me3 - me0, me7 - me4, me11 - me8, me15 - me12).normalize();
  8354. planes[1].setComponents(me3 + me0, me7 + me4, me11 + me8, me15 + me12).normalize();
  8355. planes[2].setComponents(me3 + me1, me7 + me5, me11 + me9, me15 + me13).normalize();
  8356. planes[3].setComponents(me3 - me1, me7 - me5, me11 - me9, me15 - me13).normalize();
  8357. planes[4].setComponents(me3 - me2, me7 - me6, me11 - me10, me15 - me14).normalize();
  8358. planes[5].setComponents(me3 + me2, me7 + me6, me11 + me10, me15 + me14).normalize();
  8359. return this;
  8360. }
  8361. intersectsObject(object) {
  8362. const geometry = object.geometry;
  8363. if (geometry.boundingSphere === null) geometry.computeBoundingSphere();
  8364. _sphere$1.copy(geometry.boundingSphere).applyMatrix4(object.matrixWorld);
  8365. return this.intersectsSphere(_sphere$1);
  8366. }
  8367. intersectsSprite(sprite) {
  8368. _sphere$1.center.set(0, 0, 0);
  8369. _sphere$1.radius = 0.7071067811865476;
  8370. _sphere$1.applyMatrix4(sprite.matrixWorld);
  8371. return this.intersectsSphere(_sphere$1);
  8372. }
  8373. intersectsSphere(sphere) {
  8374. const planes = this.planes;
  8375. const center = sphere.center;
  8376. const negRadius = -sphere.radius;
  8377. for (let i = 0; i < 6; i++) {
  8378. const distance = planes[i].distanceToPoint(center);
  8379. if (distance < negRadius) {
  8380. return false;
  8381. }
  8382. }
  8383. return true;
  8384. }
  8385. intersectsBox(box) {
  8386. const planes = this.planes;
  8387. for (let i = 0; i < 6; i++) {
  8388. const plane = planes[i]; // corner at max distance
  8389. _vector$5.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  8390. _vector$5.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  8391. _vector$5.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  8392. if (plane.distanceToPoint(_vector$5) < 0) {
  8393. return false;
  8394. }
  8395. }
  8396. return true;
  8397. }
  8398. containsPoint(point) {
  8399. const planes = this.planes;
  8400. for (let i = 0; i < 6; i++) {
  8401. if (planes[i].distanceToPoint(point) < 0) {
  8402. return false;
  8403. }
  8404. }
  8405. return true;
  8406. }
  8407. }
  8408. exports.Frustum = Frustum;
  8409. function WebGLAnimation() {
  8410. let context = null;
  8411. let isAnimating = false;
  8412. let animationLoop = null;
  8413. let requestId = null;
  8414. function onAnimationFrame(time, frame) {
  8415. animationLoop(time, frame);
  8416. requestId = context.requestAnimationFrame(onAnimationFrame);
  8417. }
  8418. return {
  8419. start: function () {
  8420. if (isAnimating === true) return;
  8421. if (animationLoop === null) return;
  8422. requestId = context.requestAnimationFrame(onAnimationFrame);
  8423. isAnimating = true;
  8424. },
  8425. stop: function () {
  8426. context.cancelAnimationFrame(requestId);
  8427. isAnimating = false;
  8428. },
  8429. setAnimationLoop: function (callback) {
  8430. animationLoop = callback;
  8431. },
  8432. setContext: function (value) {
  8433. context = value;
  8434. }
  8435. };
  8436. }
  8437. function WebGLAttributes(gl, capabilities) {
  8438. const isWebGL2 = capabilities.isWebGL2;
  8439. const buffers = new WeakMap();
  8440. function createBuffer(attribute, bufferType) {
  8441. const array = attribute.array;
  8442. const usage = attribute.usage;
  8443. const buffer = gl.createBuffer();
  8444. gl.bindBuffer(bufferType, buffer);
  8445. gl.bufferData(bufferType, array, usage);
  8446. attribute.onUploadCallback();
  8447. let type = 5126;
  8448. if (array instanceof Float32Array) {
  8449. type = 5126;
  8450. } else if (array instanceof Float64Array) {
  8451. console.warn('THREE.WebGLAttributes: Unsupported data buffer format: Float64Array.');
  8452. } else if (array instanceof Uint16Array) {
  8453. if (attribute.isFloat16BufferAttribute) {
  8454. if (isWebGL2) {
  8455. type = 5131;
  8456. } else {
  8457. console.warn('THREE.WebGLAttributes: Usage of Float16BufferAttribute requires WebGL2.');
  8458. }
  8459. } else {
  8460. type = 5123;
  8461. }
  8462. } else if (array instanceof Int16Array) {
  8463. type = 5122;
  8464. } else if (array instanceof Uint32Array) {
  8465. type = 5125;
  8466. } else if (array instanceof Int32Array) {
  8467. type = 5124;
  8468. } else if (array instanceof Int8Array) {
  8469. type = 5120;
  8470. } else if (array instanceof Uint8Array) {
  8471. type = 5121;
  8472. }
  8473. return {
  8474. buffer: buffer,
  8475. type: type,
  8476. bytesPerElement: array.BYTES_PER_ELEMENT,
  8477. version: attribute.version
  8478. };
  8479. }
  8480. function updateBuffer(buffer, attribute, bufferType) {
  8481. const array = attribute.array;
  8482. const updateRange = attribute.updateRange;
  8483. gl.bindBuffer(bufferType, buffer);
  8484. if (updateRange.count === -1) {
  8485. // Not using update ranges
  8486. gl.bufferSubData(bufferType, 0, array);
  8487. } else {
  8488. if (isWebGL2) {
  8489. gl.bufferSubData(bufferType, updateRange.offset * array.BYTES_PER_ELEMENT, array, updateRange.offset, updateRange.count);
  8490. } else {
  8491. gl.bufferSubData(bufferType, updateRange.offset * array.BYTES_PER_ELEMENT, array.subarray(updateRange.offset, updateRange.offset + updateRange.count));
  8492. }
  8493. updateRange.count = -1; // reset range
  8494. }
  8495. } //
  8496. function get(attribute) {
  8497. if (attribute.isInterleavedBufferAttribute) attribute = attribute.data;
  8498. return buffers.get(attribute);
  8499. }
  8500. function remove(attribute) {
  8501. if (attribute.isInterleavedBufferAttribute) attribute = attribute.data;
  8502. const data = buffers.get(attribute);
  8503. if (data) {
  8504. gl.deleteBuffer(data.buffer);
  8505. buffers.delete(attribute);
  8506. }
  8507. }
  8508. function update(attribute, bufferType) {
  8509. if (attribute.isGLBufferAttribute) {
  8510. const cached = buffers.get(attribute);
  8511. if (!cached || cached.version < attribute.version) {
  8512. buffers.set(attribute, {
  8513. buffer: attribute.buffer,
  8514. type: attribute.type,
  8515. bytesPerElement: attribute.elementSize,
  8516. version: attribute.version
  8517. });
  8518. }
  8519. return;
  8520. }
  8521. if (attribute.isInterleavedBufferAttribute) attribute = attribute.data;
  8522. const data = buffers.get(attribute);
  8523. if (data === undefined) {
  8524. buffers.set(attribute, createBuffer(attribute, bufferType));
  8525. } else if (data.version < attribute.version) {
  8526. updateBuffer(data.buffer, attribute, bufferType);
  8527. data.version = attribute.version;
  8528. }
  8529. }
  8530. return {
  8531. get: get,
  8532. remove: remove,
  8533. update: update
  8534. };
  8535. }
  8536. class PlaneBufferGeometry extends BufferGeometry {
  8537. constructor(width = 1, height = 1, widthSegments = 1, heightSegments = 1) {
  8538. super();
  8539. this.type = 'PlaneBufferGeometry';
  8540. this.parameters = {
  8541. width: width,
  8542. height: height,
  8543. widthSegments: widthSegments,
  8544. heightSegments: heightSegments
  8545. };
  8546. const width_half = width / 2;
  8547. const height_half = height / 2;
  8548. const gridX = Math.floor(widthSegments);
  8549. const gridY = Math.floor(heightSegments);
  8550. const gridX1 = gridX + 1;
  8551. const gridY1 = gridY + 1;
  8552. const segment_width = width / gridX;
  8553. const segment_height = height / gridY; //
  8554. const indices = [];
  8555. const vertices = [];
  8556. const normals = [];
  8557. const uvs = [];
  8558. for (let iy = 0; iy < gridY1; iy++) {
  8559. const y = iy * segment_height - height_half;
  8560. for (let ix = 0; ix < gridX1; ix++) {
  8561. const x = ix * segment_width - width_half;
  8562. vertices.push(x, -y, 0);
  8563. normals.push(0, 0, 1);
  8564. uvs.push(ix / gridX);
  8565. uvs.push(1 - iy / gridY);
  8566. }
  8567. }
  8568. for (let iy = 0; iy < gridY; iy++) {
  8569. for (let ix = 0; ix < gridX; ix++) {
  8570. const a = ix + gridX1 * iy;
  8571. const b = ix + gridX1 * (iy + 1);
  8572. const c = ix + 1 + gridX1 * (iy + 1);
  8573. const d = ix + 1 + gridX1 * iy;
  8574. indices.push(a, b, d);
  8575. indices.push(b, c, d);
  8576. }
  8577. }
  8578. this.setIndex(indices);
  8579. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  8580. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  8581. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  8582. }
  8583. }
  8584. exports.PlaneBufferGeometry = PlaneBufferGeometry;
  8585. var alphamap_fragment = "#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, vUv ).g;\n#endif";
  8586. var alphamap_pars_fragment = "#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif";
  8587. var alphatest_fragment = "#ifdef ALPHATEST\n\tif ( diffuseColor.a < ALPHATEST ) discard;\n#endif";
  8588. var aomap_fragment = "#ifdef USE_AOMAP\n\tfloat ambientOcclusion = ( texture2D( aoMap, vUv2 ).r - 1.0 ) * aoMapIntensity + 1.0;\n\treflectedLight.indirectDiffuse *= ambientOcclusion;\n\t#if defined( USE_ENVMAP ) && defined( STANDARD )\n\t\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\t\treflectedLight.indirectSpecular *= computeSpecularOcclusion( dotNV, ambientOcclusion, material.specularRoughness );\n\t#endif\n#endif";
  8589. var aomap_pars_fragment = "#ifdef USE_AOMAP\n\tuniform sampler2D aoMap;\n\tuniform float aoMapIntensity;\n#endif";
  8590. var begin_vertex = "vec3 transformed = vec3( position );";
  8591. var beginnormal_vertex = "vec3 objectNormal = vec3( normal );\n#ifdef USE_TANGENT\n\tvec3 objectTangent = vec3( tangent.xyz );\n#endif";
  8592. var bsdfs = "vec2 integrateSpecularBRDF( const in float dotNV, const in float roughness ) {\n\tconst vec4 c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 );\n\tconst vec4 c1 = vec4( 1, 0.0425, 1.04, - 0.04 );\n\tvec4 r = roughness * c0 + c1;\n\tfloat a004 = min( r.x * r.x, exp2( - 9.28 * dotNV ) ) * r.x + r.y;\n\treturn vec2( -1.04, 1.04 ) * a004 + r.zw;\n}\nfloat punctualLightIntensityToIrradianceFactor( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) {\n#if defined ( PHYSICALLY_CORRECT_LIGHTS )\n\tfloat distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 );\n\tif( cutoffDistance > 0.0 ) {\n\t\tdistanceFalloff *= pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) );\n\t}\n\treturn distanceFalloff;\n#else\n\tif( cutoffDistance > 0.0 && decayExponent > 0.0 ) {\n\t\treturn pow( saturate( -lightDistance / cutoffDistance + 1.0 ), decayExponent );\n\t}\n\treturn 1.0;\n#endif\n}\nvec3 BRDF_Diffuse_Lambert( const in vec3 diffuseColor ) {\n\treturn RECIPROCAL_PI * diffuseColor;\n}\nvec3 F_Schlick( const in vec3 specularColor, const in float dotLH ) {\n\tfloat fresnel = exp2( ( -5.55473 * dotLH - 6.98316 ) * dotLH );\n\treturn ( 1.0 - specularColor ) * fresnel + specularColor;\n}\nvec3 F_Schlick_RoughnessDependent( const in vec3 F0, const in float dotNV, const in float roughness ) {\n\tfloat fresnel = exp2( ( -5.55473 * dotNV - 6.98316 ) * dotNV );\n\tvec3 Fr = max( vec3( 1.0 - roughness ), F0 ) - F0;\n\treturn Fr * fresnel + F0;\n}\nfloat G_GGX_Smith( const in float alpha, const in float dotNL, const in float dotNV ) {\n\tfloat a2 = pow2( alpha );\n\tfloat gl = dotNL + sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n\tfloat gv = dotNV + sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n\treturn 1.0 / ( gl * gv );\n}\nfloat G_GGX_SmithCorrelated( const in float alpha, const in float dotNL, const in float dotNV ) {\n\tfloat a2 = pow2( alpha );\n\tfloat gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n\tfloat gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n\treturn 0.5 / max( gv + gl, EPSILON );\n}\nfloat D_GGX( const in float alpha, const in float dotNH ) {\n\tfloat a2 = pow2( alpha );\n\tfloat denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0;\n\treturn RECIPROCAL_PI * a2 / pow2( denom );\n}\nvec3 BRDF_Specular_GGX( const in IncidentLight incidentLight, const in vec3 viewDir, const in vec3 normal, const in vec3 specularColor, const in float roughness ) {\n\tfloat alpha = pow2( roughness );\n\tvec3 halfDir = normalize( incidentLight.direction + viewDir );\n\tfloat dotNL = saturate( dot( normal, incidentLight.direction ) );\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat dotLH = saturate( dot( incidentLight.direction, halfDir ) );\n\tvec3 F = F_Schlick( specularColor, dotLH );\n\tfloat G = G_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n\tfloat D = D_GGX( alpha, dotNH );\n\treturn F * ( G * D );\n}\nvec2 LTC_Uv( const in vec3 N, const in vec3 V, const in float roughness ) {\n\tconst float LUT_SIZE = 64.0;\n\tconst float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;\n\tconst float LUT_BIAS = 0.5 / LUT_SIZE;\n\tfloat dotNV = saturate( dot( N, V ) );\n\tvec2 uv = vec2( roughness, sqrt( 1.0 - dotNV ) );\n\tuv = uv * LUT_SCALE + LUT_BIAS;\n\treturn uv;\n}\nfloat LTC_ClippedSphereFormFactor( const in vec3 f ) {\n\tfloat l = length( f );\n\treturn max( ( l * l + f.z ) / ( l + 1.0 ), 0.0 );\n}\nvec3 LTC_EdgeVectorFormFactor( const in vec3 v1, const in vec3 v2 ) {\n\tfloat x = dot( v1, v2 );\n\tfloat y = abs( x );\n\tfloat a = 0.8543985 + ( 0.4965155 + 0.0145206 * y ) * y;\n\tfloat b = 3.4175940 + ( 4.1616724 + y ) * y;\n\tfloat v = a / b;\n\tfloat theta_sintheta = ( x > 0.0 ) ? v : 0.5 * inversesqrt( max( 1.0 - x * x, 1e-7 ) ) - v;\n\treturn cross( v1, v2 ) * theta_sintheta;\n}\nvec3 LTC_Evaluate( const in vec3 N, const in vec3 V, const in vec3 P, const in mat3 mInv, const in vec3 rectCoords[ 4 ] ) {\n\tvec3 v1 = rectCoords[ 1 ] - rectCoords[ 0 ];\n\tvec3 v2 = rectCoords[ 3 ] - rectCoords[ 0 ];\n\tvec3 lightNormal = cross( v1, v2 );\n\tif( dot( lightNormal, P - rectCoords[ 0 ] ) < 0.0 ) return vec3( 0.0 );\n\tvec3 T1, T2;\n\tT1 = normalize( V - N * dot( V, N ) );\n\tT2 = - cross( N, T1 );\n\tmat3 mat = mInv * transposeMat3( mat3( T1, T2, N ) );\n\tvec3 coords[ 4 ];\n\tcoords[ 0 ] = mat * ( rectCoords[ 0 ] - P );\n\tcoords[ 1 ] = mat * ( rectCoords[ 1 ] - P );\n\tcoords[ 2 ] = mat * ( rectCoords[ 2 ] - P );\n\tcoords[ 3 ] = mat * ( rectCoords[ 3 ] - P );\n\tcoords[ 0 ] = normalize( coords[ 0 ] );\n\tcoords[ 1 ] = normalize( coords[ 1 ] );\n\tcoords[ 2 ] = normalize( coords[ 2 ] );\n\tcoords[ 3 ] = normalize( coords[ 3 ] );\n\tvec3 vectorFormFactor = vec3( 0.0 );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 0 ], coords[ 1 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 1 ], coords[ 2 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 2 ], coords[ 3 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 3 ], coords[ 0 ] );\n\tfloat result = LTC_ClippedSphereFormFactor( vectorFormFactor );\n\treturn vec3( result );\n}\nvec3 BRDF_Specular_GGX_Environment( const in vec3 viewDir, const in vec3 normal, const in vec3 specularColor, const in float roughness ) {\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tvec2 brdf = integrateSpecularBRDF( dotNV, roughness );\n\treturn specularColor * brdf.x + brdf.y;\n}\nvoid BRDF_Specular_Multiscattering_Environment( const in GeometricContext geometry, const in vec3 specularColor, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) {\n\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\tvec3 F = F_Schlick_RoughnessDependent( specularColor, dotNV, roughness );\n\tvec2 brdf = integrateSpecularBRDF( dotNV, roughness );\n\tvec3 FssEss = F * brdf.x + brdf.y;\n\tfloat Ess = brdf.x + brdf.y;\n\tfloat Ems = 1.0 - Ess;\n\tvec3 Favg = specularColor + ( 1.0 - specularColor ) * 0.047619;\tvec3 Fms = FssEss * Favg / ( 1.0 - Ems * Favg );\n\tsingleScatter += FssEss;\n\tmultiScatter += Fms * Ems;\n}\nfloat G_BlinnPhong_Implicit( ) {\n\treturn 0.25;\n}\nfloat D_BlinnPhong( const in float shininess, const in float dotNH ) {\n\treturn RECIPROCAL_PI * ( shininess * 0.5 + 1.0 ) * pow( dotNH, shininess );\n}\nvec3 BRDF_Specular_BlinnPhong( const in IncidentLight incidentLight, const in GeometricContext geometry, const in vec3 specularColor, const in float shininess ) {\n\tvec3 halfDir = normalize( incidentLight.direction + geometry.viewDir );\n\tfloat dotNH = saturate( dot( geometry.normal, halfDir ) );\n\tfloat dotLH = saturate( dot( incidentLight.direction, halfDir ) );\n\tvec3 F = F_Schlick( specularColor, dotLH );\n\tfloat G = G_BlinnPhong_Implicit( );\n\tfloat D = D_BlinnPhong( shininess, dotNH );\n\treturn F * ( G * D );\n}\nfloat GGXRoughnessToBlinnExponent( const in float ggxRoughness ) {\n\treturn ( 2.0 / pow2( ggxRoughness + 0.0001 ) - 2.0 );\n}\nfloat BlinnExponentToGGXRoughness( const in float blinnExponent ) {\n\treturn sqrt( 2.0 / ( blinnExponent + 2.0 ) );\n}\n#if defined( USE_SHEEN )\nfloat D_Charlie(float roughness, float NoH) {\n\tfloat invAlpha = 1.0 / roughness;\n\tfloat cos2h = NoH * NoH;\n\tfloat sin2h = max(1.0 - cos2h, 0.0078125);\treturn (2.0 + invAlpha) * pow(sin2h, invAlpha * 0.5) / (2.0 * PI);\n}\nfloat V_Neubelt(float NoV, float NoL) {\n\treturn saturate(1.0 / (4.0 * (NoL + NoV - NoL * NoV)));\n}\nvec3 BRDF_Specular_Sheen( const in float roughness, const in vec3 L, const in GeometricContext geometry, vec3 specularColor ) {\n\tvec3 N = geometry.normal;\n\tvec3 V = geometry.viewDir;\n\tvec3 H = normalize( V + L );\n\tfloat dotNH = saturate( dot( N, H ) );\n\treturn specularColor * D_Charlie( roughness, dotNH ) * V_Neubelt( dot(N, V), dot(N, L) );\n}\n#endif";
  8593. var bumpmap_pars_fragment = "#ifdef USE_BUMPMAP\n\tuniform sampler2D bumpMap;\n\tuniform float bumpScale;\n\tvec2 dHdxy_fwd() {\n\t\tvec2 dSTdx = dFdx( vUv );\n\t\tvec2 dSTdy = dFdy( vUv );\n\t\tfloat Hll = bumpScale * texture2D( bumpMap, vUv ).x;\n\t\tfloat dBx = bumpScale * texture2D( bumpMap, vUv + dSTdx ).x - Hll;\n\t\tfloat dBy = bumpScale * texture2D( bumpMap, vUv + dSTdy ).x - Hll;\n\t\treturn vec2( dBx, dBy );\n\t}\n\tvec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy ) {\n\t\tvec3 vSigmaX = vec3( dFdx( surf_pos.x ), dFdx( surf_pos.y ), dFdx( surf_pos.z ) );\n\t\tvec3 vSigmaY = vec3( dFdy( surf_pos.x ), dFdy( surf_pos.y ), dFdy( surf_pos.z ) );\n\t\tvec3 vN = surf_norm;\n\t\tvec3 R1 = cross( vSigmaY, vN );\n\t\tvec3 R2 = cross( vN, vSigmaX );\n\t\tfloat fDet = dot( vSigmaX, R1 );\n\t\tfDet *= ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n\t\tvec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );\n\t\treturn normalize( abs( fDet ) * surf_norm - vGrad );\n\t}\n#endif";
  8594. var clipping_planes_fragment = "#if NUM_CLIPPING_PLANES > 0\n\tvec4 plane;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) {\n\t\tplane = clippingPlanes[ i ];\n\t\tif ( dot( vClipPosition, plane.xyz ) > plane.w ) discard;\n\t}\n\t#pragma unroll_loop_end\n\t#if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES\n\t\tbool clipped = true;\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) {\n\t\t\tplane = clippingPlanes[ i ];\n\t\t\tclipped = ( dot( vClipPosition, plane.xyz ) > plane.w ) && clipped;\n\t\t}\n\t\t#pragma unroll_loop_end\n\t\tif ( clipped ) discard;\n\t#endif\n#endif";
  8595. var clipping_planes_pars_fragment = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n\tuniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];\n#endif";
  8596. var clipping_planes_pars_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n#endif";
  8597. var clipping_planes_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvClipPosition = - mvPosition.xyz;\n#endif";
  8598. var color_fragment = "#ifdef USE_COLOR\n\tdiffuseColor.rgb *= vColor;\n#endif";
  8599. var color_pars_fragment = "#ifdef USE_COLOR\n\tvarying vec3 vColor;\n#endif";
  8600. var color_pars_vertex = "#if defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR )\n\tvarying vec3 vColor;\n#endif";
  8601. var color_vertex = "#if defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR )\n\tvColor = vec3( 1.0 );\n#endif\n#ifdef USE_COLOR\n\tvColor.xyz *= color.xyz;\n#endif\n#ifdef USE_INSTANCING_COLOR\n\tvColor.xyz *= instanceColor.xyz;\n#endif";
  8602. var common = "#define PI 3.141592653589793\n#define PI2 6.283185307179586\n#define PI_HALF 1.5707963267948966\n#define RECIPROCAL_PI 0.3183098861837907\n#define RECIPROCAL_PI2 0.15915494309189535\n#define EPSILON 1e-6\n#ifndef saturate\n#define saturate(a) clamp( a, 0.0, 1.0 )\n#endif\n#define whiteComplement(a) ( 1.0 - saturate( a ) )\nfloat pow2( const in float x ) { return x*x; }\nfloat pow3( const in float x ) { return x*x*x; }\nfloat pow4( const in float x ) { float x2 = x*x; return x2*x2; }\nfloat average( const in vec3 color ) { return dot( color, vec3( 0.3333 ) ); }\nhighp float rand( const in vec2 uv ) {\n\tconst highp float a = 12.9898, b = 78.233, c = 43758.5453;\n\thighp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI );\n\treturn fract(sin(sn) * c);\n}\n#ifdef HIGH_PRECISION\n\tfloat precisionSafeLength( vec3 v ) { return length( v ); }\n#else\n\tfloat max3( vec3 v ) { return max( max( v.x, v.y ), v.z ); }\n\tfloat precisionSafeLength( vec3 v ) {\n\t\tfloat maxComponent = max3( abs( v ) );\n\t\treturn length( v / maxComponent ) * maxComponent;\n\t}\n#endif\nstruct IncidentLight {\n\tvec3 color;\n\tvec3 direction;\n\tbool visible;\n};\nstruct ReflectedLight {\n\tvec3 directDiffuse;\n\tvec3 directSpecular;\n\tvec3 indirectDiffuse;\n\tvec3 indirectSpecular;\n};\nstruct GeometricContext {\n\tvec3 position;\n\tvec3 normal;\n\tvec3 viewDir;\n#ifdef CLEARCOAT\n\tvec3 clearcoatNormal;\n#endif\n};\nvec3 transformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );\n}\nvec3 inverseTransformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );\n}\nvec3 projectOnPlane(in vec3 point, in vec3 pointOnPlane, in vec3 planeNormal ) {\n\tfloat distance = dot( planeNormal, point - pointOnPlane );\n\treturn - distance * planeNormal + point;\n}\nfloat sideOfPlane( in vec3 point, in vec3 pointOnPlane, in vec3 planeNormal ) {\n\treturn sign( dot( point - pointOnPlane, planeNormal ) );\n}\nvec3 linePlaneIntersect( in vec3 pointOnLine, in vec3 lineDirection, in vec3 pointOnPlane, in vec3 planeNormal ) {\n\treturn lineDirection * ( dot( planeNormal, pointOnPlane - pointOnLine ) / dot( planeNormal, lineDirection ) ) + pointOnLine;\n}\nmat3 transposeMat3( const in mat3 m ) {\n\tmat3 tmp;\n\ttmp[ 0 ] = vec3( m[ 0 ].x, m[ 1 ].x, m[ 2 ].x );\n\ttmp[ 1 ] = vec3( m[ 0 ].y, m[ 1 ].y, m[ 2 ].y );\n\ttmp[ 2 ] = vec3( m[ 0 ].z, m[ 1 ].z, m[ 2 ].z );\n\treturn tmp;\n}\nfloat linearToRelativeLuminance( const in vec3 color ) {\n\tvec3 weights = vec3( 0.2126, 0.7152, 0.0722 );\n\treturn dot( weights, color.rgb );\n}\nbool isPerspectiveMatrix( mat4 m ) {\n\treturn m[ 2 ][ 3 ] == - 1.0;\n}\nvec2 equirectUv( in vec3 dir ) {\n\tfloat u = atan( dir.z, dir.x ) * RECIPROCAL_PI2 + 0.5;\n\tfloat v = asin( clamp( dir.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;\n\treturn vec2( u, v );\n}";
  8603. var cube_uv_reflection_fragment = "#ifdef ENVMAP_TYPE_CUBE_UV\n\t#define cubeUV_maxMipLevel 8.0\n\t#define cubeUV_minMipLevel 4.0\n\t#define cubeUV_maxTileSize 256.0\n\t#define cubeUV_minTileSize 16.0\n\tfloat getFace( vec3 direction ) {\n\t\tvec3 absDirection = abs( direction );\n\t\tfloat face = - 1.0;\n\t\tif ( absDirection.x > absDirection.z ) {\n\t\t\tif ( absDirection.x > absDirection.y )\n\t\t\t\tface = direction.x > 0.0 ? 0.0 : 3.0;\n\t\t\telse\n\t\t\t\tface = direction.y > 0.0 ? 1.0 : 4.0;\n\t\t} else {\n\t\t\tif ( absDirection.z > absDirection.y )\n\t\t\t\tface = direction.z > 0.0 ? 2.0 : 5.0;\n\t\t\telse\n\t\t\t\tface = direction.y > 0.0 ? 1.0 : 4.0;\n\t\t}\n\t\treturn face;\n\t}\n\tvec2 getUV( vec3 direction, float face ) {\n\t\tvec2 uv;\n\t\tif ( face == 0.0 ) {\n\t\t\tuv = vec2( direction.z, direction.y ) / abs( direction.x );\n\t\t} else if ( face == 1.0 ) {\n\t\t\tuv = vec2( - direction.x, - direction.z ) / abs( direction.y );\n\t\t} else if ( face == 2.0 ) {\n\t\t\tuv = vec2( - direction.x, direction.y ) / abs( direction.z );\n\t\t} else if ( face == 3.0 ) {\n\t\t\tuv = vec2( - direction.z, direction.y ) / abs( direction.x );\n\t\t} else if ( face == 4.0 ) {\n\t\t\tuv = vec2( - direction.x, direction.z ) / abs( direction.y );\n\t\t} else {\n\t\t\tuv = vec2( direction.x, direction.y ) / abs( direction.z );\n\t\t}\n\t\treturn 0.5 * ( uv + 1.0 );\n\t}\n\tvec3 bilinearCubeUV( sampler2D envMap, vec3 direction, float mipInt ) {\n\t\tfloat face = getFace( direction );\n\t\tfloat filterInt = max( cubeUV_minMipLevel - mipInt, 0.0 );\n\t\tmipInt = max( mipInt, cubeUV_minMipLevel );\n\t\tfloat faceSize = exp2( mipInt );\n\t\tfloat texelSize = 1.0 / ( 3.0 * cubeUV_maxTileSize );\n\t\tvec2 uv = getUV( direction, face ) * ( faceSize - 1.0 );\n\t\tvec2 f = fract( uv );\n\t\tuv += 0.5 - f;\n\t\tif ( face > 2.0 ) {\n\t\t\tuv.y += faceSize;\n\t\t\tface -= 3.0;\n\t\t}\n\t\tuv.x += face * faceSize;\n\t\tif ( mipInt < cubeUV_maxMipLevel ) {\n\t\t\tuv.y += 2.0 * cubeUV_maxTileSize;\n\t\t}\n\t\tuv.y += filterInt * 2.0 * cubeUV_minTileSize;\n\t\tuv.x += 3.0 * max( 0.0, cubeUV_maxTileSize - 2.0 * faceSize );\n\t\tuv *= texelSize;\n\t\tvec3 tl = envMapTexelToLinear( texture2D( envMap, uv ) ).rgb;\n\t\tuv.x += texelSize;\n\t\tvec3 tr = envMapTexelToLinear( texture2D( envMap, uv ) ).rgb;\n\t\tuv.y += texelSize;\n\t\tvec3 br = envMapTexelToLinear( texture2D( envMap, uv ) ).rgb;\n\t\tuv.x -= texelSize;\n\t\tvec3 bl = envMapTexelToLinear( texture2D( envMap, uv ) ).rgb;\n\t\tvec3 tm = mix( tl, tr, f.x );\n\t\tvec3 bm = mix( bl, br, f.x );\n\t\treturn mix( tm, bm, f.y );\n\t}\n\t#define r0 1.0\n\t#define v0 0.339\n\t#define m0 - 2.0\n\t#define r1 0.8\n\t#define v1 0.276\n\t#define m1 - 1.0\n\t#define r4 0.4\n\t#define v4 0.046\n\t#define m4 2.0\n\t#define r5 0.305\n\t#define v5 0.016\n\t#define m5 3.0\n\t#define r6 0.21\n\t#define v6 0.0038\n\t#define m6 4.0\n\tfloat roughnessToMip( float roughness ) {\n\t\tfloat mip = 0.0;\n\t\tif ( roughness >= r1 ) {\n\t\t\tmip = ( r0 - roughness ) * ( m1 - m0 ) / ( r0 - r1 ) + m0;\n\t\t} else if ( roughness >= r4 ) {\n\t\t\tmip = ( r1 - roughness ) * ( m4 - m1 ) / ( r1 - r4 ) + m1;\n\t\t} else if ( roughness >= r5 ) {\n\t\t\tmip = ( r4 - roughness ) * ( m5 - m4 ) / ( r4 - r5 ) + m4;\n\t\t} else if ( roughness >= r6 ) {\n\t\t\tmip = ( r5 - roughness ) * ( m6 - m5 ) / ( r5 - r6 ) + m5;\n\t\t} else {\n\t\t\tmip = - 2.0 * log2( 1.16 * roughness );\t\t}\n\t\treturn mip;\n\t}\n\tvec4 textureCubeUV( sampler2D envMap, vec3 sampleDir, float roughness ) {\n\t\tfloat mip = clamp( roughnessToMip( roughness ), m0, cubeUV_maxMipLevel );\n\t\tfloat mipF = fract( mip );\n\t\tfloat mipInt = floor( mip );\n\t\tvec3 color0 = bilinearCubeUV( envMap, sampleDir, mipInt );\n\t\tif ( mipF == 0.0 ) {\n\t\t\treturn vec4( color0, 1.0 );\n\t\t} else {\n\t\t\tvec3 color1 = bilinearCubeUV( envMap, sampleDir, mipInt + 1.0 );\n\t\t\treturn vec4( mix( color0, color1, mipF ), 1.0 );\n\t\t}\n\t}\n#endif";
  8604. var defaultnormal_vertex = "vec3 transformedNormal = objectNormal;\n#ifdef USE_INSTANCING\n\tmat3 m = mat3( instanceMatrix );\n\ttransformedNormal /= vec3( dot( m[ 0 ], m[ 0 ] ), dot( m[ 1 ], m[ 1 ] ), dot( m[ 2 ], m[ 2 ] ) );\n\ttransformedNormal = m * transformedNormal;\n#endif\ntransformedNormal = normalMatrix * transformedNormal;\n#ifdef FLIP_SIDED\n\ttransformedNormal = - transformedNormal;\n#endif\n#ifdef USE_TANGENT\n\tvec3 transformedTangent = ( modelViewMatrix * vec4( objectTangent, 0.0 ) ).xyz;\n\t#ifdef FLIP_SIDED\n\t\ttransformedTangent = - transformedTangent;\n\t#endif\n#endif";
  8605. var displacementmap_pars_vertex = "#ifdef USE_DISPLACEMENTMAP\n\tuniform sampler2D displacementMap;\n\tuniform float displacementScale;\n\tuniform float displacementBias;\n#endif";
  8606. var displacementmap_vertex = "#ifdef USE_DISPLACEMENTMAP\n\ttransformed += normalize( objectNormal ) * ( texture2D( displacementMap, vUv ).x * displacementScale + displacementBias );\n#endif";
  8607. var emissivemap_fragment = "#ifdef USE_EMISSIVEMAP\n\tvec4 emissiveColor = texture2D( emissiveMap, vUv );\n\temissiveColor.rgb = emissiveMapTexelToLinear( emissiveColor ).rgb;\n\ttotalEmissiveRadiance *= emissiveColor.rgb;\n#endif";
  8608. var emissivemap_pars_fragment = "#ifdef USE_EMISSIVEMAP\n\tuniform sampler2D emissiveMap;\n#endif";
  8609. var encodings_fragment = "gl_FragColor = linearToOutputTexel( gl_FragColor );";
  8610. var encodings_pars_fragment = "\nvec4 LinearToLinear( in vec4 value ) {\n\treturn value;\n}\nvec4 GammaToLinear( in vec4 value, in float gammaFactor ) {\n\treturn vec4( pow( value.rgb, vec3( gammaFactor ) ), value.a );\n}\nvec4 LinearToGamma( in vec4 value, in float gammaFactor ) {\n\treturn vec4( pow( value.rgb, vec3( 1.0 / gammaFactor ) ), value.a );\n}\nvec4 sRGBToLinear( in vec4 value ) {\n\treturn vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.a );\n}\nvec4 LinearTosRGB( in vec4 value ) {\n\treturn vec4( mix( pow( value.rgb, vec3( 0.41666 ) ) * 1.055 - vec3( 0.055 ), value.rgb * 12.92, vec3( lessThanEqual( value.rgb, vec3( 0.0031308 ) ) ) ), value.a );\n}\nvec4 RGBEToLinear( in vec4 value ) {\n\treturn vec4( value.rgb * exp2( value.a * 255.0 - 128.0 ), 1.0 );\n}\nvec4 LinearToRGBE( in vec4 value ) {\n\tfloat maxComponent = max( max( value.r, value.g ), value.b );\n\tfloat fExp = clamp( ceil( log2( maxComponent ) ), -128.0, 127.0 );\n\treturn vec4( value.rgb / exp2( fExp ), ( fExp + 128.0 ) / 255.0 );\n}\nvec4 RGBMToLinear( in vec4 value, in float maxRange ) {\n\treturn vec4( value.rgb * value.a * maxRange, 1.0 );\n}\nvec4 LinearToRGBM( in vec4 value, in float maxRange ) {\n\tfloat maxRGB = max( value.r, max( value.g, value.b ) );\n\tfloat M = clamp( maxRGB / maxRange, 0.0, 1.0 );\n\tM = ceil( M * 255.0 ) / 255.0;\n\treturn vec4( value.rgb / ( M * maxRange ), M );\n}\nvec4 RGBDToLinear( in vec4 value, in float maxRange ) {\n\treturn vec4( value.rgb * ( ( maxRange / 255.0 ) / value.a ), 1.0 );\n}\nvec4 LinearToRGBD( in vec4 value, in float maxRange ) {\n\tfloat maxRGB = max( value.r, max( value.g, value.b ) );\n\tfloat D = max( maxRange / maxRGB, 1.0 );\n\tD = clamp( floor( D ) / 255.0, 0.0, 1.0 );\n\treturn vec4( value.rgb * ( D * ( 255.0 / maxRange ) ), D );\n}\nconst mat3 cLogLuvM = mat3( 0.2209, 0.3390, 0.4184, 0.1138, 0.6780, 0.7319, 0.0102, 0.1130, 0.2969 );\nvec4 LinearToLogLuv( in vec4 value ) {\n\tvec3 Xp_Y_XYZp = cLogLuvM * value.rgb;\n\tXp_Y_XYZp = max( Xp_Y_XYZp, vec3( 1e-6, 1e-6, 1e-6 ) );\n\tvec4 vResult;\n\tvResult.xy = Xp_Y_XYZp.xy / Xp_Y_XYZp.z;\n\tfloat Le = 2.0 * log2(Xp_Y_XYZp.y) + 127.0;\n\tvResult.w = fract( Le );\n\tvResult.z = ( Le - ( floor( vResult.w * 255.0 ) ) / 255.0 ) / 255.0;\n\treturn vResult;\n}\nconst mat3 cLogLuvInverseM = mat3( 6.0014, -2.7008, -1.7996, -1.3320, 3.1029, -5.7721, 0.3008, -1.0882, 5.6268 );\nvec4 LogLuvToLinear( in vec4 value ) {\n\tfloat Le = value.z * 255.0 + value.w;\n\tvec3 Xp_Y_XYZp;\n\tXp_Y_XYZp.y = exp2( ( Le - 127.0 ) / 2.0 );\n\tXp_Y_XYZp.z = Xp_Y_XYZp.y / value.y;\n\tXp_Y_XYZp.x = value.x * Xp_Y_XYZp.z;\n\tvec3 vRGB = cLogLuvInverseM * Xp_Y_XYZp.rgb;\n\treturn vec4( max( vRGB, 0.0 ), 1.0 );\n}";
  8611. var envmap_fragment = "#ifdef USE_ENVMAP\n\t#ifdef ENV_WORLDPOS\n\t\tvec3 cameraToFrag;\n\t\tif ( isOrthographic ) {\n\t\t\tcameraToFrag = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );\n\t\t} else {\n\t\t\tcameraToFrag = normalize( vWorldPosition - cameraPosition );\n\t\t}\n\t\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvec3 reflectVec = reflect( cameraToFrag, worldNormal );\n\t\t#else\n\t\t\tvec3 reflectVec = refract( cameraToFrag, worldNormal, refractionRatio );\n\t\t#endif\n\t#else\n\t\tvec3 reflectVec = vReflect;\n\t#endif\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tvec4 envColor = textureCube( envMap, vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );\n\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\tvec4 envColor = textureCubeUV( envMap, reflectVec, 0.0 );\n\t#else\n\t\tvec4 envColor = vec4( 0.0 );\n\t#endif\n\t#ifndef ENVMAP_TYPE_CUBE_UV\n\t\tenvColor = envMapTexelToLinear( envColor );\n\t#endif\n\t#ifdef ENVMAP_BLENDING_MULTIPLY\n\t\toutgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_MIX )\n\t\toutgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_ADD )\n\t\toutgoingLight += envColor.xyz * specularStrength * reflectivity;\n\t#endif\n#endif";
  8612. var envmap_common_pars_fragment = "#ifdef USE_ENVMAP\n\tuniform float envMapIntensity;\n\tuniform float flipEnvMap;\n\tuniform int maxMipLevel;\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tuniform samplerCube envMap;\n\t#else\n\t\tuniform sampler2D envMap;\n\t#endif\n\t\n#endif";
  8613. var envmap_pars_fragment = "#ifdef USE_ENVMAP\n\tuniform float reflectivity;\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG )\n\t\t#define ENV_WORLDPOS\n\t#endif\n\t#ifdef ENV_WORLDPOS\n\t\tvarying vec3 vWorldPosition;\n\t\tuniform float refractionRatio;\n\t#else\n\t\tvarying vec3 vReflect;\n\t#endif\n#endif";
  8614. var envmap_pars_vertex = "#ifdef USE_ENVMAP\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) ||defined( PHONG )\n\t\t#define ENV_WORLDPOS\n\t#endif\n\t#ifdef ENV_WORLDPOS\n\t\t\n\t\tvarying vec3 vWorldPosition;\n\t#else\n\t\tvarying vec3 vReflect;\n\t\tuniform float refractionRatio;\n\t#endif\n#endif";
  8615. var envmap_vertex = "#ifdef USE_ENVMAP\n\t#ifdef ENV_WORLDPOS\n\t\tvWorldPosition = worldPosition.xyz;\n\t#else\n\t\tvec3 cameraToVertex;\n\t\tif ( isOrthographic ) {\n\t\t\tcameraToVertex = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );\n\t\t} else {\n\t\t\tcameraToVertex = normalize( worldPosition.xyz - cameraPosition );\n\t\t}\n\t\tvec3 worldNormal = inverseTransformDirection( transformedNormal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvReflect = reflect( cameraToVertex, worldNormal );\n\t\t#else\n\t\t\tvReflect = refract( cameraToVertex, worldNormal, refractionRatio );\n\t\t#endif\n\t#endif\n#endif";
  8616. var fog_vertex = "#ifdef USE_FOG\n\tfogDepth = - mvPosition.z;\n#endif";
  8617. var fog_pars_vertex = "#ifdef USE_FOG\n\tvarying float fogDepth;\n#endif";
  8618. var fog_fragment = "#ifdef USE_FOG\n\t#ifdef FOG_EXP2\n\t\tfloat fogFactor = 1.0 - exp( - fogDensity * fogDensity * fogDepth * fogDepth );\n\t#else\n\t\tfloat fogFactor = smoothstep( fogNear, fogFar, fogDepth );\n\t#endif\n\tgl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor );\n#endif";
  8619. var fog_pars_fragment = "#ifdef USE_FOG\n\tuniform vec3 fogColor;\n\tvarying float fogDepth;\n\t#ifdef FOG_EXP2\n\t\tuniform float fogDensity;\n\t#else\n\t\tuniform float fogNear;\n\t\tuniform float fogFar;\n\t#endif\n#endif";
  8620. var gradientmap_pars_fragment = "#ifdef USE_GRADIENTMAP\n\tuniform sampler2D gradientMap;\n#endif\nvec3 getGradientIrradiance( vec3 normal, vec3 lightDirection ) {\n\tfloat dotNL = dot( normal, lightDirection );\n\tvec2 coord = vec2( dotNL * 0.5 + 0.5, 0.0 );\n\t#ifdef USE_GRADIENTMAP\n\t\treturn texture2D( gradientMap, coord ).rgb;\n\t#else\n\t\treturn ( coord.x < 0.7 ) ? vec3( 0.7 ) : vec3( 1.0 );\n\t#endif\n}";
  8621. var lightmap_fragment = "#ifdef USE_LIGHTMAP\n\tvec4 lightMapTexel= texture2D( lightMap, vUv2 );\n\treflectedLight.indirectDiffuse += PI * lightMapTexelToLinear( lightMapTexel ).rgb * lightMapIntensity;\n#endif";
  8622. var lightmap_pars_fragment = "#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif";
  8623. var lights_lambert_vertex = "vec3 diffuse = vec3( 1.0 );\nGeometricContext geometry;\ngeometry.position = mvPosition.xyz;\ngeometry.normal = normalize( transformedNormal );\ngeometry.viewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( -mvPosition.xyz );\nGeometricContext backGeometry;\nbackGeometry.position = geometry.position;\nbackGeometry.normal = -geometry.normal;\nbackGeometry.viewDir = geometry.viewDir;\nvLightFront = vec3( 0.0 );\nvIndirectFront = vec3( 0.0 );\n#ifdef DOUBLE_SIDED\n\tvLightBack = vec3( 0.0 );\n\tvIndirectBack = vec3( 0.0 );\n#endif\nIncidentLight directLight;\nfloat dotNL;\nvec3 directLightColor_Diffuse;\nvIndirectFront += getAmbientLightIrradiance( ambientLightColor );\nvIndirectFront += getLightProbeIrradiance( lightProbe, geometry );\n#ifdef DOUBLE_SIDED\n\tvIndirectBack += getAmbientLightIrradiance( ambientLightColor );\n\tvIndirectBack += getLightProbeIrradiance( lightProbe, backGeometry );\n#endif\n#if NUM_POINT_LIGHTS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tgetPointDirectLightIrradiance( pointLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = PI * directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if NUM_SPOT_LIGHTS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tgetSpotDirectLightIrradiance( spotLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = PI * directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if NUM_DIR_LIGHTS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tgetDirectionalDirectLightIrradiance( directionalLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = PI * directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if NUM_HEMI_LIGHTS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\t\tvIndirectFront += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry );\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvIndirectBack += getHemisphereLightIrradiance( hemisphereLights[ i ], backGeometry );\n\t\t#endif\n\t}\n\t#pragma unroll_loop_end\n#endif";
  8624. var lights_pars_begin = "uniform bool receiveShadow;\nuniform vec3 ambientLightColor;\nuniform vec3 lightProbe[ 9 ];\nvec3 shGetIrradianceAt( in vec3 normal, in vec3 shCoefficients[ 9 ] ) {\n\tfloat x = normal.x, y = normal.y, z = normal.z;\n\tvec3 result = shCoefficients[ 0 ] * 0.886227;\n\tresult += shCoefficients[ 1 ] * 2.0 * 0.511664 * y;\n\tresult += shCoefficients[ 2 ] * 2.0 * 0.511664 * z;\n\tresult += shCoefficients[ 3 ] * 2.0 * 0.511664 * x;\n\tresult += shCoefficients[ 4 ] * 2.0 * 0.429043 * x * y;\n\tresult += shCoefficients[ 5 ] * 2.0 * 0.429043 * y * z;\n\tresult += shCoefficients[ 6 ] * ( 0.743125 * z * z - 0.247708 );\n\tresult += shCoefficients[ 7 ] * 2.0 * 0.429043 * x * z;\n\tresult += shCoefficients[ 8 ] * 0.429043 * ( x * x - y * y );\n\treturn result;\n}\nvec3 getLightProbeIrradiance( const in vec3 lightProbe[ 9 ], const in GeometricContext geometry ) {\n\tvec3 worldNormal = inverseTransformDirection( geometry.normal, viewMatrix );\n\tvec3 irradiance = shGetIrradianceAt( worldNormal, lightProbe );\n\treturn irradiance;\n}\nvec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) {\n\tvec3 irradiance = ambientLightColor;\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tirradiance *= PI;\n\t#endif\n\treturn irradiance;\n}\n#if NUM_DIR_LIGHTS > 0\n\tstruct DirectionalLight {\n\t\tvec3 direction;\n\t\tvec3 color;\n\t};\n\tuniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ];\n\tvoid getDirectionalDirectLightIrradiance( const in DirectionalLight directionalLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n\t\tdirectLight.color = directionalLight.color;\n\t\tdirectLight.direction = directionalLight.direction;\n\t\tdirectLight.visible = true;\n\t}\n#endif\n#if NUM_POINT_LIGHTS > 0\n\tstruct PointLight {\n\t\tvec3 position;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t};\n\tuniform PointLight pointLights[ NUM_POINT_LIGHTS ];\n\tvoid getPointDirectLightIrradiance( const in PointLight pointLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n\t\tvec3 lVector = pointLight.position - geometry.position;\n\t\tdirectLight.direction = normalize( lVector );\n\t\tfloat lightDistance = length( lVector );\n\t\tdirectLight.color = pointLight.color;\n\t\tdirectLight.color *= punctualLightIntensityToIrradianceFactor( lightDistance, pointLight.distance, pointLight.decay );\n\t\tdirectLight.visible = ( directLight.color != vec3( 0.0 ) );\n\t}\n#endif\n#if NUM_SPOT_LIGHTS > 0\n\tstruct SpotLight {\n\t\tvec3 position;\n\t\tvec3 direction;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t\tfloat coneCos;\n\t\tfloat penumbraCos;\n\t};\n\tuniform SpotLight spotLights[ NUM_SPOT_LIGHTS ];\n\tvoid getSpotDirectLightIrradiance( const in SpotLight spotLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n\t\tvec3 lVector = spotLight.position - geometry.position;\n\t\tdirectLight.direction = normalize( lVector );\n\t\tfloat lightDistance = length( lVector );\n\t\tfloat angleCos = dot( directLight.direction, spotLight.direction );\n\t\tif ( angleCos > spotLight.coneCos ) {\n\t\t\tfloat spotEffect = smoothstep( spotLight.coneCos, spotLight.penumbraCos, angleCos );\n\t\t\tdirectLight.color = spotLight.color;\n\t\t\tdirectLight.color *= spotEffect * punctualLightIntensityToIrradianceFactor( lightDistance, spotLight.distance, spotLight.decay );\n\t\t\tdirectLight.visible = true;\n\t\t} else {\n\t\t\tdirectLight.color = vec3( 0.0 );\n\t\t\tdirectLight.visible = false;\n\t\t}\n\t}\n#endif\n#if NUM_RECT_AREA_LIGHTS > 0\n\tstruct RectAreaLight {\n\t\tvec3 color;\n\t\tvec3 position;\n\t\tvec3 halfWidth;\n\t\tvec3 halfHeight;\n\t};\n\tuniform sampler2D ltc_1;\tuniform sampler2D ltc_2;\n\tuniform RectAreaLight rectAreaLights[ NUM_RECT_AREA_LIGHTS ];\n#endif\n#if NUM_HEMI_LIGHTS > 0\n\tstruct HemisphereLight {\n\t\tvec3 direction;\n\t\tvec3 skyColor;\n\t\tvec3 groundColor;\n\t};\n\tuniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ];\n\tvec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in GeometricContext geometry ) {\n\t\tfloat dotNL = dot( geometry.normal, hemiLight.direction );\n\t\tfloat hemiDiffuseWeight = 0.5 * dotNL + 0.5;\n\t\tvec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight );\n\t\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\t\tirradiance *= PI;\n\t\t#endif\n\t\treturn irradiance;\n\t}\n#endif";
  8625. var envmap_physical_pars_fragment = "#if defined( USE_ENVMAP )\n\t#ifdef ENVMAP_MODE_REFRACTION\n\t\tuniform float refractionRatio;\n\t#endif\n\tvec3 getLightProbeIndirectIrradiance( const in GeometricContext geometry, const in int maxMIPLevel ) {\n\t\tvec3 worldNormal = inverseTransformDirection( geometry.normal, viewMatrix );\n\t\t#ifdef ENVMAP_TYPE_CUBE\n\t\t\tvec3 queryVec = vec3( flipEnvMap * worldNormal.x, worldNormal.yz );\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\t\tvec4 envMapColor = textureCubeLodEXT( envMap, queryVec, float( maxMIPLevel ) );\n\t\t\t#else\n\t\t\t\tvec4 envMapColor = textureCube( envMap, queryVec, float( maxMIPLevel ) );\n\t\t\t#endif\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\t\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, worldNormal, 1.0 );\n\t\t#else\n\t\t\tvec4 envMapColor = vec4( 0.0 );\n\t\t#endif\n\t\treturn PI * envMapColor.rgb * envMapIntensity;\n\t}\n\tfloat getSpecularMIPLevel( const in float roughness, const in int maxMIPLevel ) {\n\t\tfloat maxMIPLevelScalar = float( maxMIPLevel );\n\t\tfloat sigma = PI * roughness * roughness / ( 1.0 + roughness );\n\t\tfloat desiredMIPLevel = maxMIPLevelScalar + log2( sigma );\n\t\treturn clamp( desiredMIPLevel, 0.0, maxMIPLevelScalar );\n\t}\n\tvec3 getLightProbeIndirectRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness, const in int maxMIPLevel ) {\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvec3 reflectVec = reflect( -viewDir, normal );\n\t\t\treflectVec = normalize( mix( reflectVec, normal, roughness * roughness) );\n\t\t#else\n\t\t\tvec3 reflectVec = refract( -viewDir, normal, refractionRatio );\n\t\t#endif\n\t\treflectVec = inverseTransformDirection( reflectVec, viewMatrix );\n\t\tfloat specularMIPLevel = getSpecularMIPLevel( roughness, maxMIPLevel );\n\t\t#ifdef ENVMAP_TYPE_CUBE\n\t\t\tvec3 queryReflectVec = vec3( flipEnvMap * reflectVec.x, reflectVec.yz );\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\t\tvec4 envMapColor = textureCubeLodEXT( envMap, queryReflectVec, specularMIPLevel );\n\t\t\t#else\n\t\t\t\tvec4 envMapColor = textureCube( envMap, queryReflectVec, specularMIPLevel );\n\t\t\t#endif\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\t\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, reflectVec, roughness );\n\t\t#endif\n\t\treturn envMapColor.rgb * envMapIntensity;\n\t}\n#endif";
  8626. var lights_toon_fragment = "ToonMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;";
  8627. var lights_toon_pars_fragment = "varying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\nstruct ToonMaterial {\n\tvec3 diffuseColor;\n};\nvoid RE_Direct_Toon( const in IncidentLight directLight, const in GeometricContext geometry, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {\n\tvec3 irradiance = getGradientIrradiance( geometry.normal, directLight.direction ) * directLight.color;\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tirradiance *= PI;\n\t#endif\n\treflectedLight.directDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Toon( const in vec3 irradiance, const in GeometricContext geometry, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_Toon\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Toon\n#define Material_LightProbeLOD( material )\t(0)";
  8628. var lights_phong_fragment = "BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;";
  8629. var lights_phong_pars_fragment = "varying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\nstruct BlinnPhongMaterial {\n\tvec3 diffuseColor;\n\tvec3 specularColor;\n\tfloat specularShininess;\n\tfloat specularStrength;\n};\nvoid RE_Direct_BlinnPhong( const in IncidentLight directLight, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tirradiance *= PI;\n\t#endif\n\treflectedLight.directDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n\treflectedLight.directSpecular += irradiance * BRDF_Specular_BlinnPhong( directLight, geometry, material.specularColor, material.specularShininess ) * material.specularStrength;\n}\nvoid RE_IndirectDiffuse_BlinnPhong( const in vec3 irradiance, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_BlinnPhong\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_BlinnPhong\n#define Material_LightProbeLOD( material )\t(0)";
  8630. var lights_physical_fragment = "PhysicalMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb * ( 1.0 - metalnessFactor );\nvec3 dxy = max( abs( dFdx( geometryNormal ) ), abs( dFdy( geometryNormal ) ) );\nfloat geometryRoughness = max( max( dxy.x, dxy.y ), dxy.z );\nmaterial.specularRoughness = max( roughnessFactor, 0.0525 );material.specularRoughness += geometryRoughness;\nmaterial.specularRoughness = min( material.specularRoughness, 1.0 );\n#ifdef REFLECTIVITY\n\tmaterial.specularColor = mix( vec3( MAXIMUM_SPECULAR_COEFFICIENT * pow2( reflectivity ) ), diffuseColor.rgb, metalnessFactor );\n#else\n\tmaterial.specularColor = mix( vec3( DEFAULT_SPECULAR_COEFFICIENT ), diffuseColor.rgb, metalnessFactor );\n#endif\n#ifdef CLEARCOAT\n\tmaterial.clearcoat = clearcoat;\n\tmaterial.clearcoatRoughness = clearcoatRoughness;\n\t#ifdef USE_CLEARCOATMAP\n\t\tmaterial.clearcoat *= texture2D( clearcoatMap, vUv ).x;\n\t#endif\n\t#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\t\tmaterial.clearcoatRoughness *= texture2D( clearcoatRoughnessMap, vUv ).y;\n\t#endif\n\tmaterial.clearcoat = saturate( material.clearcoat );\tmaterial.clearcoatRoughness = max( material.clearcoatRoughness, 0.0525 );\n\tmaterial.clearcoatRoughness += geometryRoughness;\n\tmaterial.clearcoatRoughness = min( material.clearcoatRoughness, 1.0 );\n#endif\n#ifdef USE_SHEEN\n\tmaterial.sheenColor = sheen;\n#endif";
  8631. var lights_physical_pars_fragment = "struct PhysicalMaterial {\n\tvec3 diffuseColor;\n\tfloat specularRoughness;\n\tvec3 specularColor;\n#ifdef CLEARCOAT\n\tfloat clearcoat;\n\tfloat clearcoatRoughness;\n#endif\n#ifdef USE_SHEEN\n\tvec3 sheenColor;\n#endif\n};\n#define MAXIMUM_SPECULAR_COEFFICIENT 0.16\n#define DEFAULT_SPECULAR_COEFFICIENT 0.04\nfloat clearcoatDHRApprox( const in float roughness, const in float dotNL ) {\n\treturn DEFAULT_SPECULAR_COEFFICIENT + ( 1.0 - DEFAULT_SPECULAR_COEFFICIENT ) * ( pow( 1.0 - dotNL, 5.0 ) * pow( 1.0 - roughness, 2.0 ) );\n}\n#if NUM_RECT_AREA_LIGHTS > 0\n\tvoid RE_Direct_RectArea_Physical( const in RectAreaLight rectAreaLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\t\tvec3 normal = geometry.normal;\n\t\tvec3 viewDir = geometry.viewDir;\n\t\tvec3 position = geometry.position;\n\t\tvec3 lightPos = rectAreaLight.position;\n\t\tvec3 halfWidth = rectAreaLight.halfWidth;\n\t\tvec3 halfHeight = rectAreaLight.halfHeight;\n\t\tvec3 lightColor = rectAreaLight.color;\n\t\tfloat roughness = material.specularRoughness;\n\t\tvec3 rectCoords[ 4 ];\n\t\trectCoords[ 0 ] = lightPos + halfWidth - halfHeight;\t\trectCoords[ 1 ] = lightPos - halfWidth - halfHeight;\n\t\trectCoords[ 2 ] = lightPos - halfWidth + halfHeight;\n\t\trectCoords[ 3 ] = lightPos + halfWidth + halfHeight;\n\t\tvec2 uv = LTC_Uv( normal, viewDir, roughness );\n\t\tvec4 t1 = texture2D( ltc_1, uv );\n\t\tvec4 t2 = texture2D( ltc_2, uv );\n\t\tmat3 mInv = mat3(\n\t\t\tvec3( t1.x, 0, t1.y ),\n\t\t\tvec3( 0, 1, 0 ),\n\t\t\tvec3( t1.z, 0, t1.w )\n\t\t);\n\t\tvec3 fresnel = ( material.specularColor * t2.x + ( vec3( 1.0 ) - material.specularColor ) * t2.y );\n\t\treflectedLight.directSpecular += lightColor * fresnel * LTC_Evaluate( normal, viewDir, position, mInv, rectCoords );\n\t\treflectedLight.directDiffuse += lightColor * material.diffuseColor * LTC_Evaluate( normal, viewDir, position, mat3( 1.0 ), rectCoords );\n\t}\n#endif\nvoid RE_Direct_Physical( const in IncidentLight directLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tirradiance *= PI;\n\t#endif\n\t#ifdef CLEARCOAT\n\t\tfloat ccDotNL = saturate( dot( geometry.clearcoatNormal, directLight.direction ) );\n\t\tvec3 ccIrradiance = ccDotNL * directLight.color;\n\t\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\t\tccIrradiance *= PI;\n\t\t#endif\n\t\tfloat clearcoatDHR = material.clearcoat * clearcoatDHRApprox( material.clearcoatRoughness, ccDotNL );\n\t\treflectedLight.directSpecular += ccIrradiance * material.clearcoat * BRDF_Specular_GGX( directLight, geometry.viewDir, geometry.clearcoatNormal, vec3( DEFAULT_SPECULAR_COEFFICIENT ), material.clearcoatRoughness );\n\t#else\n\t\tfloat clearcoatDHR = 0.0;\n\t#endif\n\t#ifdef USE_SHEEN\n\t\treflectedLight.directSpecular += ( 1.0 - clearcoatDHR ) * irradiance * BRDF_Specular_Sheen(\n\t\t\tmaterial.specularRoughness,\n\t\t\tdirectLight.direction,\n\t\t\tgeometry,\n\t\t\tmaterial.sheenColor\n\t\t);\n\t#else\n\t\treflectedLight.directSpecular += ( 1.0 - clearcoatDHR ) * irradiance * BRDF_Specular_GGX( directLight, geometry.viewDir, geometry.normal, material.specularColor, material.specularRoughness);\n\t#endif\n\treflectedLight.directDiffuse += ( 1.0 - clearcoatDHR ) * irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Physical( const in vec3 irradiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectSpecular_Physical( const in vec3 radiance, const in vec3 irradiance, const in vec3 clearcoatRadiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight) {\n\t#ifdef CLEARCOAT\n\t\tfloat ccDotNV = saturate( dot( geometry.clearcoatNormal, geometry.viewDir ) );\n\t\treflectedLight.indirectSpecular += clearcoatRadiance * material.clearcoat * BRDF_Specular_GGX_Environment( geometry.viewDir, geometry.clearcoatNormal, vec3( DEFAULT_SPECULAR_COEFFICIENT ), material.clearcoatRoughness );\n\t\tfloat ccDotNL = ccDotNV;\n\t\tfloat clearcoatDHR = material.clearcoat * clearcoatDHRApprox( material.clearcoatRoughness, ccDotNL );\n\t#else\n\t\tfloat clearcoatDHR = 0.0;\n\t#endif\n\tfloat clearcoatInv = 1.0 - clearcoatDHR;\n\tvec3 singleScattering = vec3( 0.0 );\n\tvec3 multiScattering = vec3( 0.0 );\n\tvec3 cosineWeightedIrradiance = irradiance * RECIPROCAL_PI;\n\tBRDF_Specular_Multiscattering_Environment( geometry, material.specularColor, material.specularRoughness, singleScattering, multiScattering );\n\tvec3 diffuse = material.diffuseColor * ( 1.0 - ( singleScattering + multiScattering ) );\n\treflectedLight.indirectSpecular += clearcoatInv * radiance * singleScattering;\n\treflectedLight.indirectSpecular += multiScattering * cosineWeightedIrradiance;\n\treflectedLight.indirectDiffuse += diffuse * cosineWeightedIrradiance;\n}\n#define RE_Direct\t\t\t\tRE_Direct_Physical\n#define RE_Direct_RectArea\t\tRE_Direct_RectArea_Physical\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Physical\n#define RE_IndirectSpecular\t\tRE_IndirectSpecular_Physical\nfloat computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) {\n\treturn saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion );\n}";
  8632. var lights_fragment_begin = "\nGeometricContext geometry;\ngeometry.position = - vViewPosition;\ngeometry.normal = normal;\ngeometry.viewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition );\n#ifdef CLEARCOAT\n\tgeometry.clearcoatNormal = clearcoatNormal;\n#endif\nIncidentLight directLight;\n#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct )\n\tPointLight pointLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_POINT_LIGHT_SHADOWS > 0\n\tPointLightShadow pointLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tpointLight = pointLights[ i ];\n\t\tgetPointDirectLightIrradiance( pointLight, geometry, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS )\n\t\tpointLightShadow = pointLightShadows[ i ];\n\t\tdirectLight.color *= all( bvec2( directLight.visible, receiveShadow ) ) ? getPointShadow( pointShadowMap[ i ], pointLightShadow.shadowMapSize, pointLightShadow.shadowBias, pointLightShadow.shadowRadius, vPointShadowCoord[ i ], pointLightShadow.shadowCameraNear, pointLightShadow.shadowCameraFar ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct )\n\tSpotLight spotLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_SPOT_LIGHT_SHADOWS > 0\n\tSpotLightShadow spotLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tspotLight = spotLights[ i ];\n\t\tgetSpotDirectLightIrradiance( spotLight, geometry, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n\t\tspotLightShadow = spotLightShadows[ i ];\n\t\tdirectLight.color *= all( bvec2( directLight.visible, receiveShadow ) ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct )\n\tDirectionalLight directionalLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0\n\tDirectionalLightShadow directionalLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tdirectionalLight = directionalLights[ i ];\n\t\tgetDirectionalDirectLightIrradiance( directionalLight, geometry, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS )\n\t\tdirectionalLightShadow = directionalLightShadows[ i ];\n\t\tdirectLight.color *= all( bvec2( directLight.visible, receiveShadow ) ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea )\n\tRectAreaLight rectAreaLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) {\n\t\trectAreaLight = rectAreaLights[ i ];\n\t\tRE_Direct_RectArea( rectAreaLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if defined( RE_IndirectDiffuse )\n\tvec3 iblIrradiance = vec3( 0.0 );\n\tvec3 irradiance = getAmbientLightIrradiance( ambientLightColor );\n\tirradiance += getLightProbeIrradiance( lightProbe, geometry );\n\t#if ( NUM_HEMI_LIGHTS > 0 )\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\t\t\tirradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry );\n\t\t}\n\t\t#pragma unroll_loop_end\n\t#endif\n#endif\n#if defined( RE_IndirectSpecular )\n\tvec3 radiance = vec3( 0.0 );\n\tvec3 clearcoatRadiance = vec3( 0.0 );\n#endif";
  8633. var lights_fragment_maps = "#if defined( RE_IndirectDiffuse )\n\t#ifdef USE_LIGHTMAP\n\t\tvec4 lightMapTexel= texture2D( lightMap, vUv2 );\n\t\tvec3 lightMapIrradiance = lightMapTexelToLinear( lightMapTexel ).rgb * lightMapIntensity;\n\t\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\t\tlightMapIrradiance *= PI;\n\t\t#endif\n\t\tirradiance += lightMapIrradiance;\n\t#endif\n\t#if defined( USE_ENVMAP ) && defined( STANDARD ) && defined( ENVMAP_TYPE_CUBE_UV )\n\t\tiblIrradiance += getLightProbeIndirectIrradiance( geometry, maxMipLevel );\n\t#endif\n#endif\n#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular )\n\tradiance += getLightProbeIndirectRadiance( geometry.viewDir, geometry.normal, material.specularRoughness, maxMipLevel );\n\t#ifdef CLEARCOAT\n\t\tclearcoatRadiance += getLightProbeIndirectRadiance( geometry.viewDir, geometry.clearcoatNormal, material.clearcoatRoughness, maxMipLevel );\n\t#endif\n#endif";
  8634. var lights_fragment_end = "#if defined( RE_IndirectDiffuse )\n\tRE_IndirectDiffuse( irradiance, geometry, material, reflectedLight );\n#endif\n#if defined( RE_IndirectSpecular )\n\tRE_IndirectSpecular( radiance, iblIrradiance, clearcoatRadiance, geometry, material, reflectedLight );\n#endif";
  8635. var logdepthbuf_fragment = "#if defined( USE_LOGDEPTHBUF ) && defined( USE_LOGDEPTHBUF_EXT )\n\tgl_FragDepthEXT = vIsPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;\n#endif";
  8636. var logdepthbuf_pars_fragment = "#if defined( USE_LOGDEPTHBUF ) && defined( USE_LOGDEPTHBUF_EXT )\n\tuniform float logDepthBufFC;\n\tvarying float vFragDepth;\n\tvarying float vIsPerspective;\n#endif";
  8637. var logdepthbuf_pars_vertex = "#ifdef USE_LOGDEPTHBUF\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\t\tvarying float vFragDepth;\n\t\tvarying float vIsPerspective;\n\t#else\n\t\tuniform float logDepthBufFC;\n\t#endif\n#endif";
  8638. var logdepthbuf_vertex = "#ifdef USE_LOGDEPTHBUF\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\t\tvFragDepth = 1.0 + gl_Position.w;\n\t\tvIsPerspective = float( isPerspectiveMatrix( projectionMatrix ) );\n\t#else\n\t\tif ( isPerspectiveMatrix( projectionMatrix ) ) {\n\t\t\tgl_Position.z = log2( max( EPSILON, gl_Position.w + 1.0 ) ) * logDepthBufFC - 1.0;\n\t\t\tgl_Position.z *= gl_Position.w;\n\t\t}\n\t#endif\n#endif";
  8639. var map_fragment = "#ifdef USE_MAP\n\tvec4 texelColor = texture2D( map, vUv );\n\ttexelColor = mapTexelToLinear( texelColor );\n\tdiffuseColor *= texelColor;\n#endif";
  8640. var map_pars_fragment = "#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif";
  8641. var map_particle_fragment = "#if defined( USE_MAP ) || defined( USE_ALPHAMAP )\n\tvec2 uv = ( uvTransform * vec3( gl_PointCoord.x, 1.0 - gl_PointCoord.y, 1 ) ).xy;\n#endif\n#ifdef USE_MAP\n\tvec4 mapTexel = texture2D( map, uv );\n\tdiffuseColor *= mapTexelToLinear( mapTexel );\n#endif\n#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, uv ).g;\n#endif";
  8642. var map_particle_pars_fragment = "#if defined( USE_MAP ) || defined( USE_ALPHAMAP )\n\tuniform mat3 uvTransform;\n#endif\n#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif\n#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif";
  8643. var metalnessmap_fragment = "float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n\tvec4 texelMetalness = texture2D( metalnessMap, vUv );\n\tmetalnessFactor *= texelMetalness.b;\n#endif";
  8644. var metalnessmap_pars_fragment = "#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif";
  8645. var morphnormal_vertex = "#ifdef USE_MORPHNORMALS\n\tobjectNormal *= morphTargetBaseInfluence;\n\tobjectNormal += morphNormal0 * morphTargetInfluences[ 0 ];\n\tobjectNormal += morphNormal1 * morphTargetInfluences[ 1 ];\n\tobjectNormal += morphNormal2 * morphTargetInfluences[ 2 ];\n\tobjectNormal += morphNormal3 * morphTargetInfluences[ 3 ];\n#endif";
  8646. var morphtarget_pars_vertex = "#ifdef USE_MORPHTARGETS\n\tuniform float morphTargetBaseInfluence;\n\t#ifndef USE_MORPHNORMALS\n\t\tuniform float morphTargetInfluences[ 8 ];\n\t#else\n\t\tuniform float morphTargetInfluences[ 4 ];\n\t#endif\n#endif";
  8647. var morphtarget_vertex = "#ifdef USE_MORPHTARGETS\n\ttransformed *= morphTargetBaseInfluence;\n\ttransformed += morphTarget0 * morphTargetInfluences[ 0 ];\n\ttransformed += morphTarget1 * morphTargetInfluences[ 1 ];\n\ttransformed += morphTarget2 * morphTargetInfluences[ 2 ];\n\ttransformed += morphTarget3 * morphTargetInfluences[ 3 ];\n\t#ifndef USE_MORPHNORMALS\n\t\ttransformed += morphTarget4 * morphTargetInfluences[ 4 ];\n\t\ttransformed += morphTarget5 * morphTargetInfluences[ 5 ];\n\t\ttransformed += morphTarget6 * morphTargetInfluences[ 6 ];\n\t\ttransformed += morphTarget7 * morphTargetInfluences[ 7 ];\n\t#endif\n#endif";
  8648. var normal_fragment_begin = "#ifdef FLAT_SHADED\n\tvec3 fdx = vec3( dFdx( vViewPosition.x ), dFdx( vViewPosition.y ), dFdx( vViewPosition.z ) );\n\tvec3 fdy = vec3( dFdy( vViewPosition.x ), dFdy( vViewPosition.y ), dFdy( vViewPosition.z ) );\n\tvec3 normal = normalize( cross( fdx, fdy ) );\n#else\n\tvec3 normal = normalize( vNormal );\n\t#ifdef DOUBLE_SIDED\n\t\tnormal = normal * ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n\t#endif\n\t#ifdef USE_TANGENT\n\t\tvec3 tangent = normalize( vTangent );\n\t\tvec3 bitangent = normalize( vBitangent );\n\t\t#ifdef DOUBLE_SIDED\n\t\t\ttangent = tangent * ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n\t\t\tbitangent = bitangent * ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n\t\t#endif\n\t\t#if defined( TANGENTSPACE_NORMALMAP ) || defined( USE_CLEARCOAT_NORMALMAP )\n\t\t\tmat3 vTBN = mat3( tangent, bitangent, normal );\n\t\t#endif\n\t#endif\n#endif\nvec3 geometryNormal = normal;";
  8649. var normal_fragment_maps = "#ifdef OBJECTSPACE_NORMALMAP\n\tnormal = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;\n\t#ifdef FLIP_SIDED\n\t\tnormal = - normal;\n\t#endif\n\t#ifdef DOUBLE_SIDED\n\t\tnormal = normal * ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n\t#endif\n\tnormal = normalize( normalMatrix * normal );\n#elif defined( TANGENTSPACE_NORMALMAP )\n\tvec3 mapN = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;\n\tmapN.xy *= normalScale;\n\t#ifdef USE_TANGENT\n\t\tnormal = normalize( vTBN * mapN );\n\t#else\n\t\tnormal = perturbNormal2Arb( -vViewPosition, normal, mapN );\n\t#endif\n#elif defined( USE_BUMPMAP )\n\tnormal = perturbNormalArb( -vViewPosition, normal, dHdxy_fwd() );\n#endif";
  8650. var normalmap_pars_fragment = "#ifdef USE_NORMALMAP\n\tuniform sampler2D normalMap;\n\tuniform vec2 normalScale;\n#endif\n#ifdef OBJECTSPACE_NORMALMAP\n\tuniform mat3 normalMatrix;\n#endif\n#if ! defined ( USE_TANGENT ) && ( defined ( TANGENTSPACE_NORMALMAP ) || defined ( USE_CLEARCOAT_NORMALMAP ) )\n\tvec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm, vec3 mapN ) {\n\t\tvec3 q0 = vec3( dFdx( eye_pos.x ), dFdx( eye_pos.y ), dFdx( eye_pos.z ) );\n\t\tvec3 q1 = vec3( dFdy( eye_pos.x ), dFdy( eye_pos.y ), dFdy( eye_pos.z ) );\n\t\tvec2 st0 = dFdx( vUv.st );\n\t\tvec2 st1 = dFdy( vUv.st );\n\t\tfloat scale = sign( st1.t * st0.s - st0.t * st1.s );\n\t\tvec3 S = normalize( ( q0 * st1.t - q1 * st0.t ) * scale );\n\t\tvec3 T = normalize( ( - q0 * st1.s + q1 * st0.s ) * scale );\n\t\tvec3 N = normalize( surf_norm );\n\t\tmat3 tsn = mat3( S, T, N );\n\t\tmapN.xy *= ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n\t\treturn normalize( tsn * mapN );\n\t}\n#endif";
  8651. var clearcoat_normal_fragment_begin = "#ifdef CLEARCOAT\n\tvec3 clearcoatNormal = geometryNormal;\n#endif";
  8652. var clearcoat_normal_fragment_maps = "#ifdef USE_CLEARCOAT_NORMALMAP\n\tvec3 clearcoatMapN = texture2D( clearcoatNormalMap, vUv ).xyz * 2.0 - 1.0;\n\tclearcoatMapN.xy *= clearcoatNormalScale;\n\t#ifdef USE_TANGENT\n\t\tclearcoatNormal = normalize( vTBN * clearcoatMapN );\n\t#else\n\t\tclearcoatNormal = perturbNormal2Arb( - vViewPosition, clearcoatNormal, clearcoatMapN );\n\t#endif\n#endif";
  8653. var clearcoat_pars_fragment = "#ifdef USE_CLEARCOATMAP\n\tuniform sampler2D clearcoatMap;\n#endif\n#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\tuniform sampler2D clearcoatRoughnessMap;\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n\tuniform sampler2D clearcoatNormalMap;\n\tuniform vec2 clearcoatNormalScale;\n#endif";
  8654. var packing = "vec3 packNormalToRGB( const in vec3 normal ) {\n\treturn normalize( normal ) * 0.5 + 0.5;\n}\nvec3 unpackRGBToNormal( const in vec3 rgb ) {\n\treturn 2.0 * rgb.xyz - 1.0;\n}\nconst float PackUpscale = 256. / 255.;const float UnpackDownscale = 255. / 256.;\nconst vec3 PackFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );\nconst vec4 UnpackFactors = UnpackDownscale / vec4( PackFactors, 1. );\nconst float ShiftRight8 = 1. / 256.;\nvec4 packDepthToRGBA( const in float v ) {\n\tvec4 r = vec4( fract( v * PackFactors ), v );\n\tr.yzw -= r.xyz * ShiftRight8;\treturn r * PackUpscale;\n}\nfloat unpackRGBAToDepth( const in vec4 v ) {\n\treturn dot( v, UnpackFactors );\n}\nvec4 pack2HalfToRGBA( vec2 v ) {\n\tvec4 r = vec4( v.x, fract( v.x * 255.0 ), v.y, fract( v.y * 255.0 ));\n\treturn vec4( r.x - r.y / 255.0, r.y, r.z - r.w / 255.0, r.w);\n}\nvec2 unpackRGBATo2Half( vec4 v ) {\n\treturn vec2( v.x + ( v.y / 255.0 ), v.z + ( v.w / 255.0 ) );\n}\nfloat viewZToOrthographicDepth( const in float viewZ, const in float near, const in float far ) {\n\treturn ( viewZ + near ) / ( near - far );\n}\nfloat orthographicDepthToViewZ( const in float linearClipZ, const in float near, const in float far ) {\n\treturn linearClipZ * ( near - far ) - near;\n}\nfloat viewZToPerspectiveDepth( const in float viewZ, const in float near, const in float far ) {\n\treturn (( near + viewZ ) * far ) / (( far - near ) * viewZ );\n}\nfloat perspectiveDepthToViewZ( const in float invClipZ, const in float near, const in float far ) {\n\treturn ( near * far ) / ( ( far - near ) * invClipZ - far );\n}";
  8655. var premultiplied_alpha_fragment = "#ifdef PREMULTIPLIED_ALPHA\n\tgl_FragColor.rgb *= gl_FragColor.a;\n#endif";
  8656. var project_vertex = "vec4 mvPosition = vec4( transformed, 1.0 );\n#ifdef USE_INSTANCING\n\tmvPosition = instanceMatrix * mvPosition;\n#endif\nmvPosition = modelViewMatrix * mvPosition;\ngl_Position = projectionMatrix * mvPosition;";
  8657. var dithering_fragment = "#ifdef DITHERING\n\tgl_FragColor.rgb = dithering( gl_FragColor.rgb );\n#endif";
  8658. var dithering_pars_fragment = "#ifdef DITHERING\n\tvec3 dithering( vec3 color ) {\n\t\tfloat grid_position = rand( gl_FragCoord.xy );\n\t\tvec3 dither_shift_RGB = vec3( 0.25 / 255.0, -0.25 / 255.0, 0.25 / 255.0 );\n\t\tdither_shift_RGB = mix( 2.0 * dither_shift_RGB, -2.0 * dither_shift_RGB, grid_position );\n\t\treturn color + dither_shift_RGB;\n\t}\n#endif";
  8659. var roughnessmap_fragment = "float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n\tvec4 texelRoughness = texture2D( roughnessMap, vUv );\n\troughnessFactor *= texelRoughness.g;\n#endif";
  8660. var roughnessmap_pars_fragment = "#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif";
  8661. var shadowmap_pars_fragment = "#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tstruct DirectionalLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vSpotShadowCoord[ NUM_SPOT_LIGHT_SHADOWS ];\n\t\tstruct SpotLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D pointShadowMap[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tstruct PointLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t\tfloat shadowCameraNear;\n\t\t\tfloat shadowCameraFar;\n\t\t};\n\t\tuniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];\n\t#endif\n\tfloat texture2DCompare( sampler2D depths, vec2 uv, float compare ) {\n\t\treturn step( compare, unpackRGBAToDepth( texture2D( depths, uv ) ) );\n\t}\n\tvec2 texture2DDistribution( sampler2D shadow, vec2 uv ) {\n\t\treturn unpackRGBATo2Half( texture2D( shadow, uv ) );\n\t}\n\tfloat VSMShadow (sampler2D shadow, vec2 uv, float compare ){\n\t\tfloat occlusion = 1.0;\n\t\tvec2 distribution = texture2DDistribution( shadow, uv );\n\t\tfloat hard_shadow = step( compare , distribution.x );\n\t\tif (hard_shadow != 1.0 ) {\n\t\t\tfloat distance = compare - distribution.x ;\n\t\t\tfloat variance = max( 0.00000, distribution.y * distribution.y );\n\t\t\tfloat softness_probability = variance / (variance + distance * distance );\t\t\tsoftness_probability = clamp( ( softness_probability - 0.3 ) / ( 0.95 - 0.3 ), 0.0, 1.0 );\t\t\tocclusion = clamp( max( hard_shadow, softness_probability ), 0.0, 1.0 );\n\t\t}\n\t\treturn occlusion;\n\t}\n\tfloat getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\n\t\tfloat shadow = 1.0;\n\t\tshadowCoord.xyz /= shadowCoord.w;\n\t\tshadowCoord.z += shadowBias;\n\t\tbvec4 inFrustumVec = bvec4 ( shadowCoord.x >= 0.0, shadowCoord.x <= 1.0, shadowCoord.y >= 0.0, shadowCoord.y <= 1.0 );\n\t\tbool inFrustum = all( inFrustumVec );\n\t\tbvec2 frustumTestVec = bvec2( inFrustum, shadowCoord.z <= 1.0 );\n\t\tbool frustumTest = all( frustumTestVec );\n\t\tif ( frustumTest ) {\n\t\t#if defined( SHADOWMAP_TYPE_PCF )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\tfloat dx0 = - texelSize.x * shadowRadius;\n\t\t\tfloat dy0 = - texelSize.y * shadowRadius;\n\t\t\tfloat dx1 = + texelSize.x * shadowRadius;\n\t\t\tfloat dy1 = + texelSize.y * shadowRadius;\n\t\t\tfloat dx2 = dx0 / 2.0;\n\t\t\tfloat dy2 = dy0 / 2.0;\n\t\t\tfloat dx3 = dx1 / 2.0;\n\t\t\tfloat dy3 = dy1 / 2.0;\n\t\t\tshadow = (\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z )\n\t\t\t) * ( 1.0 / 17.0 );\n\t\t#elif defined( SHADOWMAP_TYPE_PCF_SOFT )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\tfloat dx = texelSize.x;\n\t\t\tfloat dy = texelSize.y;\n\t\t\tvec2 uv = shadowCoord.xy;\n\t\t\tvec2 f = fract( uv * shadowMapSize + 0.5 );\n\t\t\tuv -= f * texelSize;\n\t\t\tshadow = (\n\t\t\t\ttexture2DCompare( shadowMap, uv, shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + vec2( dx, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + vec2( 0.0, dy ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + texelSize, shadowCoord.z ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( -dx, 0.0 ), shadowCoord.z ), \n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 0.0 ), shadowCoord.z ),\n\t\t\t\t\t f.x ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( -dx, dy ), shadowCoord.z ), \n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, dy ), shadowCoord.z ),\n\t\t\t\t\t f.x ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( 0.0, -dy ), shadowCoord.z ), \n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 0.0, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t f.y ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( dx, -dy ), shadowCoord.z ), \n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( dx, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t f.y ) +\n\t\t\t\tmix( mix( texture2DCompare( shadowMap, uv + vec2( -dx, -dy ), shadowCoord.z ), \n\t\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, -dy ), shadowCoord.z ),\n\t\t\t\t\t\t f.x ),\n\t\t\t\t\t mix( texture2DCompare( shadowMap, uv + vec2( -dx, 2.0 * dy ), shadowCoord.z ), \n\t\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t\t f.x ),\n\t\t\t\t\t f.y )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#elif defined( SHADOWMAP_TYPE_VSM )\n\t\t\tshadow = VSMShadow( shadowMap, shadowCoord.xy, shadowCoord.z );\n\t\t#else\n\t\t\tshadow = texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z );\n\t\t#endif\n\t\t}\n\t\treturn shadow;\n\t}\n\tvec2 cubeToUV( vec3 v, float texelSizeY ) {\n\t\tvec3 absV = abs( v );\n\t\tfloat scaleToCube = 1.0 / max( absV.x, max( absV.y, absV.z ) );\n\t\tabsV *= scaleToCube;\n\t\tv *= scaleToCube * ( 1.0 - 2.0 * texelSizeY );\n\t\tvec2 planar = v.xy;\n\t\tfloat almostATexel = 1.5 * texelSizeY;\n\t\tfloat almostOne = 1.0 - almostATexel;\n\t\tif ( absV.z >= almostOne ) {\n\t\t\tif ( v.z > 0.0 )\n\t\t\t\tplanar.x = 4.0 - v.x;\n\t\t} else if ( absV.x >= almostOne ) {\n\t\t\tfloat signX = sign( v.x );\n\t\t\tplanar.x = v.z * signX + 2.0 * signX;\n\t\t} else if ( absV.y >= almostOne ) {\n\t\t\tfloat signY = sign( v.y );\n\t\t\tplanar.x = v.x + 2.0 * signY + 2.0;\n\t\t\tplanar.y = v.z * signY - 2.0;\n\t\t}\n\t\treturn vec2( 0.125, 0.25 ) * planar + vec2( 0.375, 0.75 );\n\t}\n\tfloat getPointShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) {\n\t\tvec2 texelSize = vec2( 1.0 ) / ( shadowMapSize * vec2( 4.0, 2.0 ) );\n\t\tvec3 lightToPosition = shadowCoord.xyz;\n\t\tfloat dp = ( length( lightToPosition ) - shadowCameraNear ) / ( shadowCameraFar - shadowCameraNear );\t\tdp += shadowBias;\n\t\tvec3 bd3D = normalize( lightToPosition );\n\t\t#if defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_PCF_SOFT ) || defined( SHADOWMAP_TYPE_VSM )\n\t\t\tvec2 offset = vec2( - 1, 1 ) * shadowRadius * texelSize.y;\n\t\t\treturn (\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxx, texelSize.y ), dp )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#else\n\t\t\treturn texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp );\n\t\t#endif\n\t}\n#endif";
  8662. var shadowmap_pars_vertex = "#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t\tuniform mat4 directionalShadowMatrix[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tstruct DirectionalLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\t\tuniform mat4 spotShadowMatrix[ NUM_SPOT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vSpotShadowCoord[ NUM_SPOT_LIGHT_SHADOWS ];\n\t\tstruct SpotLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t\tuniform mat4 pointShadowMatrix[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tstruct PointLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t\tfloat shadowCameraNear;\n\t\t\tfloat shadowCameraFar;\n\t\t};\n\t\tuniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];\n\t#endif\n#endif";
  8663. var shadowmap_vertex = "#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0 || NUM_SPOT_LIGHT_SHADOWS > 0 || NUM_POINT_LIGHT_SHADOWS > 0\n\t\tvec3 shadowWorldNormal = inverseTransformDirection( transformedNormal, viewMatrix );\n\t\tvec4 shadowWorldPosition;\n\t#endif\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {\n\t\tshadowWorldPosition = worldPosition + vec4( shadowWorldNormal * directionalLightShadows[ i ].shadowNormalBias, 0 );\n\t\tvDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * shadowWorldPosition;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHT_SHADOWS; i ++ ) {\n\t\tshadowWorldPosition = worldPosition + vec4( shadowWorldNormal * spotLightShadows[ i ].shadowNormalBias, 0 );\n\t\tvSpotShadowCoord[ i ] = spotShadowMatrix[ i ] * shadowWorldPosition;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {\n\t\tshadowWorldPosition = worldPosition + vec4( shadowWorldNormal * pointLightShadows[ i ].shadowNormalBias, 0 );\n\t\tvPointShadowCoord[ i ] = pointShadowMatrix[ i ] * shadowWorldPosition;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n#endif";
  8664. var shadowmask_pars_fragment = "float getShadowMask() {\n\tfloat shadow = 1.0;\n\t#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\tDirectionalLightShadow directionalLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {\n\t\tdirectionalLight = directionalLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\tSpotLightShadow spotLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHT_SHADOWS; i ++ ) {\n\t\tspotLight = spotLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowBias, spotLight.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\tPointLightShadow pointLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {\n\t\tpointLight = pointLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ], pointLight.shadowCameraNear, pointLight.shadowCameraFar ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#endif\n\treturn shadow;\n}";
  8665. var skinbase_vertex = "#ifdef USE_SKINNING\n\tmat4 boneMatX = getBoneMatrix( skinIndex.x );\n\tmat4 boneMatY = getBoneMatrix( skinIndex.y );\n\tmat4 boneMatZ = getBoneMatrix( skinIndex.z );\n\tmat4 boneMatW = getBoneMatrix( skinIndex.w );\n#endif";
  8666. var skinning_pars_vertex = "#ifdef USE_SKINNING\n\tuniform mat4 bindMatrix;\n\tuniform mat4 bindMatrixInverse;\n\t#ifdef BONE_TEXTURE\n\t\tuniform highp sampler2D boneTexture;\n\t\tuniform int boneTextureSize;\n\t\tmat4 getBoneMatrix( const in float i ) {\n\t\t\tfloat j = i * 4.0;\n\t\t\tfloat x = mod( j, float( boneTextureSize ) );\n\t\t\tfloat y = floor( j / float( boneTextureSize ) );\n\t\t\tfloat dx = 1.0 / float( boneTextureSize );\n\t\t\tfloat dy = 1.0 / float( boneTextureSize );\n\t\t\ty = dy * ( y + 0.5 );\n\t\t\tvec4 v1 = texture2D( boneTexture, vec2( dx * ( x + 0.5 ), y ) );\n\t\t\tvec4 v2 = texture2D( boneTexture, vec2( dx * ( x + 1.5 ), y ) );\n\t\t\tvec4 v3 = texture2D( boneTexture, vec2( dx * ( x + 2.5 ), y ) );\n\t\t\tvec4 v4 = texture2D( boneTexture, vec2( dx * ( x + 3.5 ), y ) );\n\t\t\tmat4 bone = mat4( v1, v2, v3, v4 );\n\t\t\treturn bone;\n\t\t}\n\t#else\n\t\tuniform mat4 boneMatrices[ MAX_BONES ];\n\t\tmat4 getBoneMatrix( const in float i ) {\n\t\t\tmat4 bone = boneMatrices[ int(i) ];\n\t\t\treturn bone;\n\t\t}\n\t#endif\n#endif";
  8667. var skinning_vertex = "#ifdef USE_SKINNING\n\tvec4 skinVertex = bindMatrix * vec4( transformed, 1.0 );\n\tvec4 skinned = vec4( 0.0 );\n\tskinned += boneMatX * skinVertex * skinWeight.x;\n\tskinned += boneMatY * skinVertex * skinWeight.y;\n\tskinned += boneMatZ * skinVertex * skinWeight.z;\n\tskinned += boneMatW * skinVertex * skinWeight.w;\n\ttransformed = ( bindMatrixInverse * skinned ).xyz;\n#endif";
  8668. var skinnormal_vertex = "#ifdef USE_SKINNING\n\tmat4 skinMatrix = mat4( 0.0 );\n\tskinMatrix += skinWeight.x * boneMatX;\n\tskinMatrix += skinWeight.y * boneMatY;\n\tskinMatrix += skinWeight.z * boneMatZ;\n\tskinMatrix += skinWeight.w * boneMatW;\n\tskinMatrix = bindMatrixInverse * skinMatrix * bindMatrix;\n\tobjectNormal = vec4( skinMatrix * vec4( objectNormal, 0.0 ) ).xyz;\n\t#ifdef USE_TANGENT\n\t\tobjectTangent = vec4( skinMatrix * vec4( objectTangent, 0.0 ) ).xyz;\n\t#endif\n#endif";
  8669. var specularmap_fragment = "float specularStrength;\n#ifdef USE_SPECULARMAP\n\tvec4 texelSpecular = texture2D( specularMap, vUv );\n\tspecularStrength = texelSpecular.r;\n#else\n\tspecularStrength = 1.0;\n#endif";
  8670. var specularmap_pars_fragment = "#ifdef USE_SPECULARMAP\n\tuniform sampler2D specularMap;\n#endif";
  8671. var tonemapping_fragment = "#if defined( TONE_MAPPING )\n\tgl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif";
  8672. var tonemapping_pars_fragment = "#ifndef saturate\n#define saturate(a) clamp( a, 0.0, 1.0 )\n#endif\nuniform float toneMappingExposure;\nvec3 LinearToneMapping( vec3 color ) {\n\treturn toneMappingExposure * color;\n}\nvec3 ReinhardToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\treturn saturate( color / ( vec3( 1.0 ) + color ) );\n}\nvec3 OptimizedCineonToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\tcolor = max( vec3( 0.0 ), color - 0.004 );\n\treturn pow( ( color * ( 6.2 * color + 0.5 ) ) / ( color * ( 6.2 * color + 1.7 ) + 0.06 ), vec3( 2.2 ) );\n}\nvec3 RRTAndODTFit( vec3 v ) {\n\tvec3 a = v * ( v + 0.0245786 ) - 0.000090537;\n\tvec3 b = v * ( 0.983729 * v + 0.4329510 ) + 0.238081;\n\treturn a / b;\n}\nvec3 ACESFilmicToneMapping( vec3 color ) {\n\tconst mat3 ACESInputMat = mat3(\n\t\tvec3( 0.59719, 0.07600, 0.02840 ),\t\tvec3( 0.35458, 0.90834, 0.13383 ),\n\t\tvec3( 0.04823, 0.01566, 0.83777 )\n\t);\n\tconst mat3 ACESOutputMat = mat3(\n\t\tvec3( 1.60475, -0.10208, -0.00327 ),\t\tvec3( -0.53108, 1.10813, -0.07276 ),\n\t\tvec3( -0.07367, -0.00605, 1.07602 )\n\t);\n\tcolor *= toneMappingExposure / 0.6;\n\tcolor = ACESInputMat * color;\n\tcolor = RRTAndODTFit( color );\n\tcolor = ACESOutputMat * color;\n\treturn saturate( color );\n}\nvec3 CustomToneMapping( vec3 color ) { return color; }";
  8673. var transmissionmap_fragment = "#ifdef USE_TRANSMISSIONMAP\n\ttotalTransmission *= texture2D( transmissionMap, vUv ).r;\n#endif";
  8674. var transmissionmap_pars_fragment = "#ifdef USE_TRANSMISSIONMAP\n\tuniform sampler2D transmissionMap;\n#endif";
  8675. var uv_pars_fragment = "#if ( defined( USE_UV ) && ! defined( UVS_VERTEX_ONLY ) )\n\tvarying vec2 vUv;\n#endif";
  8676. var uv_pars_vertex = "#ifdef USE_UV\n\t#ifdef UVS_VERTEX_ONLY\n\t\tvec2 vUv;\n\t#else\n\t\tvarying vec2 vUv;\n\t#endif\n\tuniform mat3 uvTransform;\n#endif";
  8677. var uv_vertex = "#ifdef USE_UV\n\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n#endif";
  8678. var uv2_pars_fragment = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvarying vec2 vUv2;\n#endif";
  8679. var uv2_pars_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tattribute vec2 uv2;\n\tvarying vec2 vUv2;\n\tuniform mat3 uv2Transform;\n#endif";
  8680. var uv2_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvUv2 = ( uv2Transform * vec3( uv2, 1 ) ).xy;\n#endif";
  8681. var worldpos_vertex = "#if defined( USE_ENVMAP ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP )\n\tvec4 worldPosition = vec4( transformed, 1.0 );\n\t#ifdef USE_INSTANCING\n\t\tworldPosition = instanceMatrix * worldPosition;\n\t#endif\n\tworldPosition = modelMatrix * worldPosition;\n#endif";
  8682. var background_frag = "uniform sampler2D t2D;\nvarying vec2 vUv;\nvoid main() {\n\tvec4 texColor = texture2D( t2D, vUv );\n\tgl_FragColor = mapTexelToLinear( texColor );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n}";
  8683. var background_vert = "varying vec2 vUv;\nuniform mat3 uvTransform;\nvoid main() {\n\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n\tgl_Position = vec4( position.xy, 1.0, 1.0 );\n}";
  8684. var cube_frag = "#include <envmap_common_pars_fragment>\nuniform float opacity;\nvarying vec3 vWorldDirection;\n#include <cube_uv_reflection_fragment>\nvoid main() {\n\tvec3 vReflect = vWorldDirection;\n\t#include <envmap_fragment>\n\tgl_FragColor = envColor;\n\tgl_FragColor.a *= opacity;\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n}";
  8685. var cube_vert = "varying vec3 vWorldDirection;\n#include <common>\nvoid main() {\n\tvWorldDirection = transformDirection( position, modelMatrix );\n\t#include <begin_vertex>\n\t#include <project_vertex>\n\tgl_Position.z = gl_Position.w;\n}";
  8686. var depth_frag = "#if DEPTH_PACKING == 3200\n\tuniform float opacity;\n#endif\n#include <common>\n#include <packing>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvarying vec2 vHighPrecisionZW;\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( 1.0 );\n\t#if DEPTH_PACKING == 3200\n\t\tdiffuseColor.a = opacity;\n\t#endif\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <logdepthbuf_fragment>\n\tfloat fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5;\n\t#if DEPTH_PACKING == 3200\n\t\tgl_FragColor = vec4( vec3( 1.0 - fragCoordZ ), opacity );\n\t#elif DEPTH_PACKING == 3201\n\t\tgl_FragColor = packDepthToRGBA( fragCoordZ );\n\t#endif\n}";
  8687. var depth_vert = "#include <common>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvarying vec2 vHighPrecisionZW;\nvoid main() {\n\t#include <uv_vertex>\n\t#include <skinbase_vertex>\n\t#ifdef USE_DISPLACEMENTMAP\n\t\t#include <beginnormal_vertex>\n\t\t#include <morphnormal_vertex>\n\t\t#include <skinnormal_vertex>\n\t#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvHighPrecisionZW = gl_Position.zw;\n}";
  8688. var distanceRGBA_frag = "#define DISTANCE\nuniform vec3 referencePosition;\nuniform float nearDistance;\nuniform float farDistance;\nvarying vec3 vWorldPosition;\n#include <common>\n#include <packing>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main () {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( 1.0 );\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\tfloat dist = length( vWorldPosition - referencePosition );\n\tdist = ( dist - nearDistance ) / ( farDistance - nearDistance );\n\tdist = saturate( dist );\n\tgl_FragColor = packDepthToRGBA( dist );\n}";
  8689. var distanceRGBA_vert = "#define DISTANCE\nvarying vec3 vWorldPosition;\n#include <common>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <skinbase_vertex>\n\t#ifdef USE_DISPLACEMENTMAP\n\t\t#include <beginnormal_vertex>\n\t\t#include <morphnormal_vertex>\n\t\t#include <skinnormal_vertex>\n\t#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <worldpos_vertex>\n\t#include <clipping_planes_vertex>\n\tvWorldPosition = worldPosition.xyz;\n}";
  8690. var equirect_frag = "uniform sampler2D tEquirect;\nvarying vec3 vWorldDirection;\n#include <common>\nvoid main() {\n\tvec3 direction = normalize( vWorldDirection );\n\tvec2 sampleUV = equirectUv( direction );\n\tvec4 texColor = texture2D( tEquirect, sampleUV );\n\tgl_FragColor = mapTexelToLinear( texColor );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n}";
  8691. var equirect_vert = "varying vec3 vWorldDirection;\n#include <common>\nvoid main() {\n\tvWorldDirection = transformDirection( position, modelMatrix );\n\t#include <begin_vertex>\n\t#include <project_vertex>\n}";
  8692. var linedashed_frag = "uniform vec3 diffuse;\nuniform float opacity;\nuniform float dashSize;\nuniform float totalSize;\nvarying float vLineDistance;\n#include <common>\n#include <color_pars_fragment>\n#include <fog_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tif ( mod( vLineDistance, totalSize ) > dashSize ) {\n\t\tdiscard;\n\t}\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <color_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n}";
  8693. var linedashed_vert = "uniform float scale;\nattribute float lineDistance;\nvarying float vLineDistance;\n#include <common>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\tvLineDistance = scale * lineDistance;\n\t#include <color_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <fog_vertex>\n}";
  8694. var meshbasic_frag = "uniform vec3 diffuse;\nuniform float opacity;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_pars_fragment>\n#include <cube_uv_reflection_fragment>\n#include <fog_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <specularmap_fragment>\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\t#ifdef USE_LIGHTMAP\n\t\n\t\tvec4 lightMapTexel= texture2D( lightMap, vUv2 );\n\t\treflectedLight.indirectDiffuse += lightMapTexelToLinear( lightMapTexel ).rgb * lightMapIntensity;\n\t#else\n\t\treflectedLight.indirectDiffuse += vec3( 1.0 );\n\t#endif\n\t#include <aomap_fragment>\n\treflectedLight.indirectDiffuse *= diffuseColor.rgb;\n\tvec3 outgoingLight = reflectedLight.indirectDiffuse;\n\t#include <envmap_fragment>\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  8695. var meshbasic_vert = "#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <envmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <skinbase_vertex>\n\t#ifdef USE_ENVMAP\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <worldpos_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <envmap_vertex>\n\t#include <fog_vertex>\n}";
  8696. var meshlambert_frag = "uniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\nvarying vec3 vLightFront;\nvarying vec3 vIndirectFront;\n#ifdef DOUBLE_SIDED\n\tvarying vec3 vLightBack;\n\tvarying vec3 vIndirectBack;\n#endif\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_pars_fragment>\n#include <cube_uv_reflection_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <fog_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <shadowmask_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <specularmap_fragment>\n\t#include <emissivemap_fragment>\n\t#ifdef DOUBLE_SIDED\n\t\treflectedLight.indirectDiffuse += ( gl_FrontFacing ) ? vIndirectFront : vIndirectBack;\n\t#else\n\t\treflectedLight.indirectDiffuse += vIndirectFront;\n\t#endif\n\t#include <lightmap_fragment>\n\treflectedLight.indirectDiffuse *= BRDF_Diffuse_Lambert( diffuseColor.rgb );\n\t#ifdef DOUBLE_SIDED\n\t\treflectedLight.directDiffuse = ( gl_FrontFacing ) ? vLightFront : vLightBack;\n\t#else\n\t\treflectedLight.directDiffuse = vLightFront;\n\t#endif\n\treflectedLight.directDiffuse *= BRDF_Diffuse_Lambert( diffuseColor.rgb ) * getShadowMask();\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\t#include <envmap_fragment>\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  8697. var meshlambert_vert = "#define LAMBERT\nvarying vec3 vLightFront;\nvarying vec3 vIndirectFront;\n#ifdef DOUBLE_SIDED\n\tvarying vec3 vLightBack;\n\tvarying vec3 vIndirectBack;\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <envmap_pars_vertex>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <worldpos_vertex>\n\t#include <envmap_vertex>\n\t#include <lights_lambert_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}";
  8698. var meshmatcap_frag = "#define MATCAP\nuniform vec3 diffuse;\nuniform float opacity;\nuniform sampler2D matcap;\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <fog_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\tvec3 viewDir = normalize( vViewPosition );\n\tvec3 x = normalize( vec3( viewDir.z, 0.0, - viewDir.x ) );\n\tvec3 y = cross( viewDir, x );\n\tvec2 uv = vec2( dot( x, normal ), dot( y, normal ) ) * 0.495 + 0.5;\n\t#ifdef USE_MATCAP\n\t\tvec4 matcapColor = texture2D( matcap, uv );\n\t\tmatcapColor = matcapTexelToLinear( matcapColor );\n\t#else\n\t\tvec4 matcapColor = vec4( 1.0 );\n\t#endif\n\tvec3 outgoingLight = diffuseColor.rgb * matcapColor.rgb;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  8699. var meshmatcap_vert = "#define MATCAP\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <color_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <color_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#ifndef FLAT_SHADED\n\t\tvNormal = normalize( transformedNormal );\n\t#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <fog_vertex>\n\tvViewPosition = - mvPosition.xyz;\n}";
  8700. var meshtoon_frag = "#define TOON\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <gradientmap_pars_fragment>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <lights_toon_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\t#include <emissivemap_fragment>\n\t#include <lights_toon_fragment>\n\t#include <lights_fragment_begin>\n\t#include <lights_fragment_maps>\n\t#include <lights_fragment_end>\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  8701. var meshtoon_vert = "#define TOON\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}";
  8702. var meshphong_frag = "#define PHONG\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform vec3 specular;\nuniform float shininess;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_pars_fragment>\n#include <cube_uv_reflection_fragment>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <lights_phong_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <specularmap_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\t#include <emissivemap_fragment>\n\t#include <lights_phong_fragment>\n\t#include <lights_fragment_begin>\n\t#include <lights_fragment_maps>\n\t#include <lights_fragment_end>\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n\t#include <envmap_fragment>\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  8703. var meshphong_vert = "#define PHONG\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <envmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <envmap_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}";
  8704. var meshphysical_frag = "#define STANDARD\n#ifdef PHYSICAL\n\t#define REFLECTIVITY\n\t#define CLEARCOAT\n\t#define TRANSMISSION\n#endif\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float roughness;\nuniform float metalness;\nuniform float opacity;\n#ifdef TRANSMISSION\n\tuniform float transmission;\n#endif\n#ifdef REFLECTIVITY\n\tuniform float reflectivity;\n#endif\n#ifdef CLEARCOAT\n\tuniform float clearcoat;\n\tuniform float clearcoatRoughness;\n#endif\n#ifdef USE_SHEEN\n\tuniform vec3 sheen;\n#endif\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\n#endif\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <transmissionmap_pars_fragment>\n#include <bsdfs>\n#include <cube_uv_reflection_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_physical_pars_fragment>\n#include <fog_pars_fragment>\n#include <lights_pars_begin>\n#include <lights_physical_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <clearcoat_pars_fragment>\n#include <roughnessmap_pars_fragment>\n#include <metalnessmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#ifdef TRANSMISSION\n\t\tfloat totalTransmission = transmission;\n\t#endif\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <roughnessmap_fragment>\n\t#include <metalnessmap_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\t#include <clearcoat_normal_fragment_begin>\n\t#include <clearcoat_normal_fragment_maps>\n\t#include <emissivemap_fragment>\n\t#include <transmissionmap_fragment>\n\t#include <lights_physical_fragment>\n\t#include <lights_fragment_begin>\n\t#include <lights_fragment_maps>\n\t#include <lights_fragment_end>\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n\t#ifdef TRANSMISSION\n\t\tdiffuseColor.a *= mix( saturate( 1. - totalTransmission + linearToRelativeLuminance( reflectedLight.directSpecular + reflectedLight.indirectSpecular ) ), 1.0, metalness );\n\t#endif\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  8705. var meshphysical_vert = "#define STANDARD\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n\t#ifdef USE_TANGENT\n\t\tvTangent = normalize( transformedTangent );\n\t\tvBitangent = normalize( cross( vNormal, vTangent ) * tangent.w );\n\t#endif\n#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}";
  8706. var normal_frag = "#define NORMAL\nuniform float opacity;\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP )\n\tvarying vec3 vViewPosition;\n#endif\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\n#endif\n#include <packing>\n#include <uv_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\t#include <logdepthbuf_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\tgl_FragColor = vec4( packNormalToRGB( normal ), opacity );\n}";
  8707. var normal_vert = "#define NORMAL\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP )\n\tvarying vec3 vViewPosition;\n#endif\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n\t#ifdef USE_TANGENT\n\t\tvTangent = normalize( transformedTangent );\n\t\tvBitangent = normalize( cross( vNormal, vTangent ) * tangent.w );\n\t#endif\n#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP )\n\tvViewPosition = - mvPosition.xyz;\n#endif\n}";
  8708. var points_frag = "uniform vec3 diffuse;\nuniform float opacity;\n#include <common>\n#include <color_pars_fragment>\n#include <map_particle_pars_fragment>\n#include <fog_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_particle_fragment>\n\t#include <color_fragment>\n\t#include <alphatest_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n}";
  8709. var points_vert = "uniform float size;\nuniform float scale;\n#include <common>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <color_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <project_vertex>\n\tgl_PointSize = size;\n\t#ifdef USE_SIZEATTENUATION\n\t\tbool isPerspective = isPerspectiveMatrix( projectionMatrix );\n\t\tif ( isPerspective ) gl_PointSize *= ( scale / - mvPosition.z );\n\t#endif\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <worldpos_vertex>\n\t#include <fog_vertex>\n}";
  8710. var shadow_frag = "uniform vec3 color;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <shadowmap_pars_fragment>\n#include <shadowmask_pars_fragment>\nvoid main() {\n\tgl_FragColor = vec4( color, opacity * ( 1.0 - getShadowMask() ) );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n}";
  8711. var shadow_vert = "#include <common>\n#include <fog_pars_vertex>\n#include <shadowmap_pars_vertex>\nvoid main() {\n\t#include <begin_vertex>\n\t#include <project_vertex>\n\t#include <worldpos_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}";
  8712. var sprite_frag = "uniform vec3 diffuse;\nuniform float opacity;\n#include <common>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <fog_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n}";
  8713. var sprite_vert = "uniform float rotation;\nuniform vec2 center;\n#include <common>\n#include <uv_pars_vertex>\n#include <fog_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\tvec4 mvPosition = modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );\n\tvec2 scale;\n\tscale.x = length( vec3( modelMatrix[ 0 ].x, modelMatrix[ 0 ].y, modelMatrix[ 0 ].z ) );\n\tscale.y = length( vec3( modelMatrix[ 1 ].x, modelMatrix[ 1 ].y, modelMatrix[ 1 ].z ) );\n\t#ifndef USE_SIZEATTENUATION\n\t\tbool isPerspective = isPerspectiveMatrix( projectionMatrix );\n\t\tif ( isPerspective ) scale *= - mvPosition.z;\n\t#endif\n\tvec2 alignedPosition = ( position.xy - ( center - vec2( 0.5 ) ) ) * scale;\n\tvec2 rotatedPosition;\n\trotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;\n\trotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;\n\tmvPosition.xy += rotatedPosition;\n\tgl_Position = projectionMatrix * mvPosition;\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <fog_vertex>\n}";
  8714. const ShaderChunk = {
  8715. alphamap_fragment: alphamap_fragment,
  8716. alphamap_pars_fragment: alphamap_pars_fragment,
  8717. alphatest_fragment: alphatest_fragment,
  8718. aomap_fragment: aomap_fragment,
  8719. aomap_pars_fragment: aomap_pars_fragment,
  8720. begin_vertex: begin_vertex,
  8721. beginnormal_vertex: beginnormal_vertex,
  8722. bsdfs: bsdfs,
  8723. bumpmap_pars_fragment: bumpmap_pars_fragment,
  8724. clipping_planes_fragment: clipping_planes_fragment,
  8725. clipping_planes_pars_fragment: clipping_planes_pars_fragment,
  8726. clipping_planes_pars_vertex: clipping_planes_pars_vertex,
  8727. clipping_planes_vertex: clipping_planes_vertex,
  8728. color_fragment: color_fragment,
  8729. color_pars_fragment: color_pars_fragment,
  8730. color_pars_vertex: color_pars_vertex,
  8731. color_vertex: color_vertex,
  8732. common: common,
  8733. cube_uv_reflection_fragment: cube_uv_reflection_fragment,
  8734. defaultnormal_vertex: defaultnormal_vertex,
  8735. displacementmap_pars_vertex: displacementmap_pars_vertex,
  8736. displacementmap_vertex: displacementmap_vertex,
  8737. emissivemap_fragment: emissivemap_fragment,
  8738. emissivemap_pars_fragment: emissivemap_pars_fragment,
  8739. encodings_fragment: encodings_fragment,
  8740. encodings_pars_fragment: encodings_pars_fragment,
  8741. envmap_fragment: envmap_fragment,
  8742. envmap_common_pars_fragment: envmap_common_pars_fragment,
  8743. envmap_pars_fragment: envmap_pars_fragment,
  8744. envmap_pars_vertex: envmap_pars_vertex,
  8745. envmap_physical_pars_fragment: envmap_physical_pars_fragment,
  8746. envmap_vertex: envmap_vertex,
  8747. fog_vertex: fog_vertex,
  8748. fog_pars_vertex: fog_pars_vertex,
  8749. fog_fragment: fog_fragment,
  8750. fog_pars_fragment: fog_pars_fragment,
  8751. gradientmap_pars_fragment: gradientmap_pars_fragment,
  8752. lightmap_fragment: lightmap_fragment,
  8753. lightmap_pars_fragment: lightmap_pars_fragment,
  8754. lights_lambert_vertex: lights_lambert_vertex,
  8755. lights_pars_begin: lights_pars_begin,
  8756. lights_toon_fragment: lights_toon_fragment,
  8757. lights_toon_pars_fragment: lights_toon_pars_fragment,
  8758. lights_phong_fragment: lights_phong_fragment,
  8759. lights_phong_pars_fragment: lights_phong_pars_fragment,
  8760. lights_physical_fragment: lights_physical_fragment,
  8761. lights_physical_pars_fragment: lights_physical_pars_fragment,
  8762. lights_fragment_begin: lights_fragment_begin,
  8763. lights_fragment_maps: lights_fragment_maps,
  8764. lights_fragment_end: lights_fragment_end,
  8765. logdepthbuf_fragment: logdepthbuf_fragment,
  8766. logdepthbuf_pars_fragment: logdepthbuf_pars_fragment,
  8767. logdepthbuf_pars_vertex: logdepthbuf_pars_vertex,
  8768. logdepthbuf_vertex: logdepthbuf_vertex,
  8769. map_fragment: map_fragment,
  8770. map_pars_fragment: map_pars_fragment,
  8771. map_particle_fragment: map_particle_fragment,
  8772. map_particle_pars_fragment: map_particle_pars_fragment,
  8773. metalnessmap_fragment: metalnessmap_fragment,
  8774. metalnessmap_pars_fragment: metalnessmap_pars_fragment,
  8775. morphnormal_vertex: morphnormal_vertex,
  8776. morphtarget_pars_vertex: morphtarget_pars_vertex,
  8777. morphtarget_vertex: morphtarget_vertex,
  8778. normal_fragment_begin: normal_fragment_begin,
  8779. normal_fragment_maps: normal_fragment_maps,
  8780. normalmap_pars_fragment: normalmap_pars_fragment,
  8781. clearcoat_normal_fragment_begin: clearcoat_normal_fragment_begin,
  8782. clearcoat_normal_fragment_maps: clearcoat_normal_fragment_maps,
  8783. clearcoat_pars_fragment: clearcoat_pars_fragment,
  8784. packing: packing,
  8785. premultiplied_alpha_fragment: premultiplied_alpha_fragment,
  8786. project_vertex: project_vertex,
  8787. dithering_fragment: dithering_fragment,
  8788. dithering_pars_fragment: dithering_pars_fragment,
  8789. roughnessmap_fragment: roughnessmap_fragment,
  8790. roughnessmap_pars_fragment: roughnessmap_pars_fragment,
  8791. shadowmap_pars_fragment: shadowmap_pars_fragment,
  8792. shadowmap_pars_vertex: shadowmap_pars_vertex,
  8793. shadowmap_vertex: shadowmap_vertex,
  8794. shadowmask_pars_fragment: shadowmask_pars_fragment,
  8795. skinbase_vertex: skinbase_vertex,
  8796. skinning_pars_vertex: skinning_pars_vertex,
  8797. skinning_vertex: skinning_vertex,
  8798. skinnormal_vertex: skinnormal_vertex,
  8799. specularmap_fragment: specularmap_fragment,
  8800. specularmap_pars_fragment: specularmap_pars_fragment,
  8801. tonemapping_fragment: tonemapping_fragment,
  8802. tonemapping_pars_fragment: tonemapping_pars_fragment,
  8803. transmissionmap_fragment: transmissionmap_fragment,
  8804. transmissionmap_pars_fragment: transmissionmap_pars_fragment,
  8805. uv_pars_fragment: uv_pars_fragment,
  8806. uv_pars_vertex: uv_pars_vertex,
  8807. uv_vertex: uv_vertex,
  8808. uv2_pars_fragment: uv2_pars_fragment,
  8809. uv2_pars_vertex: uv2_pars_vertex,
  8810. uv2_vertex: uv2_vertex,
  8811. worldpos_vertex: worldpos_vertex,
  8812. background_frag: background_frag,
  8813. background_vert: background_vert,
  8814. cube_frag: cube_frag,
  8815. cube_vert: cube_vert,
  8816. depth_frag: depth_frag,
  8817. depth_vert: depth_vert,
  8818. distanceRGBA_frag: distanceRGBA_frag,
  8819. distanceRGBA_vert: distanceRGBA_vert,
  8820. equirect_frag: equirect_frag,
  8821. equirect_vert: equirect_vert,
  8822. linedashed_frag: linedashed_frag,
  8823. linedashed_vert: linedashed_vert,
  8824. meshbasic_frag: meshbasic_frag,
  8825. meshbasic_vert: meshbasic_vert,
  8826. meshlambert_frag: meshlambert_frag,
  8827. meshlambert_vert: meshlambert_vert,
  8828. meshmatcap_frag: meshmatcap_frag,
  8829. meshmatcap_vert: meshmatcap_vert,
  8830. meshtoon_frag: meshtoon_frag,
  8831. meshtoon_vert: meshtoon_vert,
  8832. meshphong_frag: meshphong_frag,
  8833. meshphong_vert: meshphong_vert,
  8834. meshphysical_frag: meshphysical_frag,
  8835. meshphysical_vert: meshphysical_vert,
  8836. normal_frag: normal_frag,
  8837. normal_vert: normal_vert,
  8838. points_frag: points_frag,
  8839. points_vert: points_vert,
  8840. shadow_frag: shadow_frag,
  8841. shadow_vert: shadow_vert,
  8842. sprite_frag: sprite_frag,
  8843. sprite_vert: sprite_vert
  8844. };
  8845. /**
  8846. * Uniforms library for shared webgl shaders
  8847. */
  8848. exports.ShaderChunk = ShaderChunk;
  8849. const UniformsLib = {
  8850. common: {
  8851. diffuse: {
  8852. value: new Color(0xeeeeee)
  8853. },
  8854. opacity: {
  8855. value: 1.0
  8856. },
  8857. map: {
  8858. value: null
  8859. },
  8860. uvTransform: {
  8861. value: new Matrix3()
  8862. },
  8863. uv2Transform: {
  8864. value: new Matrix3()
  8865. },
  8866. alphaMap: {
  8867. value: null
  8868. }
  8869. },
  8870. specularmap: {
  8871. specularMap: {
  8872. value: null
  8873. }
  8874. },
  8875. envmap: {
  8876. envMap: {
  8877. value: null
  8878. },
  8879. flipEnvMap: {
  8880. value: -1
  8881. },
  8882. reflectivity: {
  8883. value: 1.0
  8884. },
  8885. refractionRatio: {
  8886. value: 0.98
  8887. },
  8888. maxMipLevel: {
  8889. value: 0
  8890. }
  8891. },
  8892. aomap: {
  8893. aoMap: {
  8894. value: null
  8895. },
  8896. aoMapIntensity: {
  8897. value: 1
  8898. }
  8899. },
  8900. lightmap: {
  8901. lightMap: {
  8902. value: null
  8903. },
  8904. lightMapIntensity: {
  8905. value: 1
  8906. }
  8907. },
  8908. emissivemap: {
  8909. emissiveMap: {
  8910. value: null
  8911. }
  8912. },
  8913. bumpmap: {
  8914. bumpMap: {
  8915. value: null
  8916. },
  8917. bumpScale: {
  8918. value: 1
  8919. }
  8920. },
  8921. normalmap: {
  8922. normalMap: {
  8923. value: null
  8924. },
  8925. normalScale: {
  8926. value: new Vector2(1, 1)
  8927. }
  8928. },
  8929. displacementmap: {
  8930. displacementMap: {
  8931. value: null
  8932. },
  8933. displacementScale: {
  8934. value: 1
  8935. },
  8936. displacementBias: {
  8937. value: 0
  8938. }
  8939. },
  8940. roughnessmap: {
  8941. roughnessMap: {
  8942. value: null
  8943. }
  8944. },
  8945. metalnessmap: {
  8946. metalnessMap: {
  8947. value: null
  8948. }
  8949. },
  8950. gradientmap: {
  8951. gradientMap: {
  8952. value: null
  8953. }
  8954. },
  8955. fog: {
  8956. fogDensity: {
  8957. value: 0.00025
  8958. },
  8959. fogNear: {
  8960. value: 1
  8961. },
  8962. fogFar: {
  8963. value: 2000
  8964. },
  8965. fogColor: {
  8966. value: new Color(0xffffff)
  8967. }
  8968. },
  8969. lights: {
  8970. ambientLightColor: {
  8971. value: []
  8972. },
  8973. lightProbe: {
  8974. value: []
  8975. },
  8976. directionalLights: {
  8977. value: [],
  8978. properties: {
  8979. direction: {},
  8980. color: {}
  8981. }
  8982. },
  8983. directionalLightShadows: {
  8984. value: [],
  8985. properties: {
  8986. shadowBias: {},
  8987. shadowNormalBias: {},
  8988. shadowRadius: {},
  8989. shadowMapSize: {}
  8990. }
  8991. },
  8992. directionalShadowMap: {
  8993. value: []
  8994. },
  8995. directionalShadowMatrix: {
  8996. value: []
  8997. },
  8998. spotLights: {
  8999. value: [],
  9000. properties: {
  9001. color: {},
  9002. position: {},
  9003. direction: {},
  9004. distance: {},
  9005. coneCos: {},
  9006. penumbraCos: {},
  9007. decay: {}
  9008. }
  9009. },
  9010. spotLightShadows: {
  9011. value: [],
  9012. properties: {
  9013. shadowBias: {},
  9014. shadowNormalBias: {},
  9015. shadowRadius: {},
  9016. shadowMapSize: {}
  9017. }
  9018. },
  9019. spotShadowMap: {
  9020. value: []
  9021. },
  9022. spotShadowMatrix: {
  9023. value: []
  9024. },
  9025. pointLights: {
  9026. value: [],
  9027. properties: {
  9028. color: {},
  9029. position: {},
  9030. decay: {},
  9031. distance: {}
  9032. }
  9033. },
  9034. pointLightShadows: {
  9035. value: [],
  9036. properties: {
  9037. shadowBias: {},
  9038. shadowNormalBias: {},
  9039. shadowRadius: {},
  9040. shadowMapSize: {},
  9041. shadowCameraNear: {},
  9042. shadowCameraFar: {}
  9043. }
  9044. },
  9045. pointShadowMap: {
  9046. value: []
  9047. },
  9048. pointShadowMatrix: {
  9049. value: []
  9050. },
  9051. hemisphereLights: {
  9052. value: [],
  9053. properties: {
  9054. direction: {},
  9055. skyColor: {},
  9056. groundColor: {}
  9057. }
  9058. },
  9059. // TODO (abelnation): RectAreaLight BRDF data needs to be moved from example to main src
  9060. rectAreaLights: {
  9061. value: [],
  9062. properties: {
  9063. color: {},
  9064. position: {},
  9065. width: {},
  9066. height: {}
  9067. }
  9068. },
  9069. ltc_1: {
  9070. value: null
  9071. },
  9072. ltc_2: {
  9073. value: null
  9074. }
  9075. },
  9076. points: {
  9077. diffuse: {
  9078. value: new Color(0xeeeeee)
  9079. },
  9080. opacity: {
  9081. value: 1.0
  9082. },
  9083. size: {
  9084. value: 1.0
  9085. },
  9086. scale: {
  9087. value: 1.0
  9088. },
  9089. map: {
  9090. value: null
  9091. },
  9092. alphaMap: {
  9093. value: null
  9094. },
  9095. uvTransform: {
  9096. value: new Matrix3()
  9097. }
  9098. },
  9099. sprite: {
  9100. diffuse: {
  9101. value: new Color(0xeeeeee)
  9102. },
  9103. opacity: {
  9104. value: 1.0
  9105. },
  9106. center: {
  9107. value: new Vector2(0.5, 0.5)
  9108. },
  9109. rotation: {
  9110. value: 0.0
  9111. },
  9112. map: {
  9113. value: null
  9114. },
  9115. alphaMap: {
  9116. value: null
  9117. },
  9118. uvTransform: {
  9119. value: new Matrix3()
  9120. }
  9121. }
  9122. };
  9123. exports.UniformsLib = UniformsLib;
  9124. const ShaderLib = {
  9125. basic: {
  9126. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.specularmap, UniformsLib.envmap, UniformsLib.aomap, UniformsLib.lightmap, UniformsLib.fog]),
  9127. vertexShader: ShaderChunk.meshbasic_vert,
  9128. fragmentShader: ShaderChunk.meshbasic_frag
  9129. },
  9130. lambert: {
  9131. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.specularmap, UniformsLib.envmap, UniformsLib.aomap, UniformsLib.lightmap, UniformsLib.emissivemap, UniformsLib.fog, UniformsLib.lights, {
  9132. emissive: {
  9133. value: new Color(0x000000)
  9134. }
  9135. }]),
  9136. vertexShader: ShaderChunk.meshlambert_vert,
  9137. fragmentShader: ShaderChunk.meshlambert_frag
  9138. },
  9139. phong: {
  9140. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.specularmap, UniformsLib.envmap, UniformsLib.aomap, UniformsLib.lightmap, UniformsLib.emissivemap, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, UniformsLib.fog, UniformsLib.lights, {
  9141. emissive: {
  9142. value: new Color(0x000000)
  9143. },
  9144. specular: {
  9145. value: new Color(0x111111)
  9146. },
  9147. shininess: {
  9148. value: 30
  9149. }
  9150. }]),
  9151. vertexShader: ShaderChunk.meshphong_vert,
  9152. fragmentShader: ShaderChunk.meshphong_frag
  9153. },
  9154. standard: {
  9155. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.envmap, UniformsLib.aomap, UniformsLib.lightmap, UniformsLib.emissivemap, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, UniformsLib.roughnessmap, UniformsLib.metalnessmap, UniformsLib.fog, UniformsLib.lights, {
  9156. emissive: {
  9157. value: new Color(0x000000)
  9158. },
  9159. roughness: {
  9160. value: 1.0
  9161. },
  9162. metalness: {
  9163. value: 0.0
  9164. },
  9165. envMapIntensity: {
  9166. value: 1
  9167. } // temporary
  9168. }]),
  9169. vertexShader: ShaderChunk.meshphysical_vert,
  9170. fragmentShader: ShaderChunk.meshphysical_frag
  9171. },
  9172. toon: {
  9173. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.aomap, UniformsLib.lightmap, UniformsLib.emissivemap, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, UniformsLib.gradientmap, UniformsLib.fog, UniformsLib.lights, {
  9174. emissive: {
  9175. value: new Color(0x000000)
  9176. }
  9177. }]),
  9178. vertexShader: ShaderChunk.meshtoon_vert,
  9179. fragmentShader: ShaderChunk.meshtoon_frag
  9180. },
  9181. matcap: {
  9182. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, UniformsLib.fog, {
  9183. matcap: {
  9184. value: null
  9185. }
  9186. }]),
  9187. vertexShader: ShaderChunk.meshmatcap_vert,
  9188. fragmentShader: ShaderChunk.meshmatcap_frag
  9189. },
  9190. points: {
  9191. uniforms: mergeUniforms([UniformsLib.points, UniformsLib.fog]),
  9192. vertexShader: ShaderChunk.points_vert,
  9193. fragmentShader: ShaderChunk.points_frag
  9194. },
  9195. dashed: {
  9196. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.fog, {
  9197. scale: {
  9198. value: 1
  9199. },
  9200. dashSize: {
  9201. value: 1
  9202. },
  9203. totalSize: {
  9204. value: 2
  9205. }
  9206. }]),
  9207. vertexShader: ShaderChunk.linedashed_vert,
  9208. fragmentShader: ShaderChunk.linedashed_frag
  9209. },
  9210. depth: {
  9211. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.displacementmap]),
  9212. vertexShader: ShaderChunk.depth_vert,
  9213. fragmentShader: ShaderChunk.depth_frag
  9214. },
  9215. normal: {
  9216. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, {
  9217. opacity: {
  9218. value: 1.0
  9219. }
  9220. }]),
  9221. vertexShader: ShaderChunk.normal_vert,
  9222. fragmentShader: ShaderChunk.normal_frag
  9223. },
  9224. sprite: {
  9225. uniforms: mergeUniforms([UniformsLib.sprite, UniformsLib.fog]),
  9226. vertexShader: ShaderChunk.sprite_vert,
  9227. fragmentShader: ShaderChunk.sprite_frag
  9228. },
  9229. background: {
  9230. uniforms: {
  9231. uvTransform: {
  9232. value: new Matrix3()
  9233. },
  9234. t2D: {
  9235. value: null
  9236. }
  9237. },
  9238. vertexShader: ShaderChunk.background_vert,
  9239. fragmentShader: ShaderChunk.background_frag
  9240. },
  9241. /* -------------------------------------------------------------------------
  9242. // Cube map shader
  9243. ------------------------------------------------------------------------- */
  9244. cube: {
  9245. uniforms: mergeUniforms([UniformsLib.envmap, {
  9246. opacity: {
  9247. value: 1.0
  9248. }
  9249. }]),
  9250. vertexShader: ShaderChunk.cube_vert,
  9251. fragmentShader: ShaderChunk.cube_frag
  9252. },
  9253. equirect: {
  9254. uniforms: {
  9255. tEquirect: {
  9256. value: null
  9257. }
  9258. },
  9259. vertexShader: ShaderChunk.equirect_vert,
  9260. fragmentShader: ShaderChunk.equirect_frag
  9261. },
  9262. distanceRGBA: {
  9263. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.displacementmap, {
  9264. referencePosition: {
  9265. value: new Vector3()
  9266. },
  9267. nearDistance: {
  9268. value: 1
  9269. },
  9270. farDistance: {
  9271. value: 1000
  9272. }
  9273. }]),
  9274. vertexShader: ShaderChunk.distanceRGBA_vert,
  9275. fragmentShader: ShaderChunk.distanceRGBA_frag
  9276. },
  9277. shadow: {
  9278. uniforms: mergeUniforms([UniformsLib.lights, UniformsLib.fog, {
  9279. color: {
  9280. value: new Color(0x00000)
  9281. },
  9282. opacity: {
  9283. value: 1.0
  9284. }
  9285. }]),
  9286. vertexShader: ShaderChunk.shadow_vert,
  9287. fragmentShader: ShaderChunk.shadow_frag
  9288. }
  9289. };
  9290. exports.ShaderLib = ShaderLib;
  9291. ShaderLib.physical = {
  9292. uniforms: mergeUniforms([ShaderLib.standard.uniforms, {
  9293. clearcoat: {
  9294. value: 0
  9295. },
  9296. clearcoatMap: {
  9297. value: null
  9298. },
  9299. clearcoatRoughness: {
  9300. value: 0
  9301. },
  9302. clearcoatRoughnessMap: {
  9303. value: null
  9304. },
  9305. clearcoatNormalScale: {
  9306. value: new Vector2(1, 1)
  9307. },
  9308. clearcoatNormalMap: {
  9309. value: null
  9310. },
  9311. sheen: {
  9312. value: new Color(0x000000)
  9313. },
  9314. transmission: {
  9315. value: 0
  9316. },
  9317. transmissionMap: {
  9318. value: null
  9319. }
  9320. }]),
  9321. vertexShader: ShaderChunk.meshphysical_vert,
  9322. fragmentShader: ShaderChunk.meshphysical_frag
  9323. };
  9324. function WebGLBackground(renderer, cubemaps, state, objects, premultipliedAlpha) {
  9325. const clearColor = new Color(0x000000);
  9326. let clearAlpha = 0;
  9327. let planeMesh;
  9328. let boxMesh;
  9329. let currentBackground = null;
  9330. let currentBackgroundVersion = 0;
  9331. let currentTonemapping = null;
  9332. function render(renderList, scene, camera, forceClear) {
  9333. let background = scene.isScene === true ? scene.background : null;
  9334. if (background && background.isTexture) {
  9335. background = cubemaps.get(background);
  9336. } // Ignore background in AR
  9337. // TODO: Reconsider this.
  9338. const xr = renderer.xr;
  9339. const session = xr.getSession && xr.getSession();
  9340. if (session && session.environmentBlendMode === 'additive') {
  9341. background = null;
  9342. }
  9343. if (background === null) {
  9344. setClear(clearColor, clearAlpha);
  9345. } else if (background && background.isColor) {
  9346. setClear(background, 1);
  9347. forceClear = true;
  9348. }
  9349. if (renderer.autoClear || forceClear) {
  9350. renderer.clear(renderer.autoClearColor, renderer.autoClearDepth, renderer.autoClearStencil);
  9351. }
  9352. if (background && (background.isCubeTexture || background.isWebGLCubeRenderTarget || background.mapping === CubeUVReflectionMapping)) {
  9353. if (boxMesh === undefined) {
  9354. boxMesh = new Mesh(new BoxBufferGeometry(1, 1, 1), new ShaderMaterial({
  9355. name: 'BackgroundCubeMaterial',
  9356. uniforms: cloneUniforms(ShaderLib.cube.uniforms),
  9357. vertexShader: ShaderLib.cube.vertexShader,
  9358. fragmentShader: ShaderLib.cube.fragmentShader,
  9359. side: BackSide,
  9360. depthTest: false,
  9361. depthWrite: false,
  9362. fog: false
  9363. }));
  9364. boxMesh.geometry.deleteAttribute('normal');
  9365. boxMesh.geometry.deleteAttribute('uv');
  9366. boxMesh.onBeforeRender = function (renderer, scene, camera) {
  9367. this.matrixWorld.copyPosition(camera.matrixWorld);
  9368. }; // enable code injection for non-built-in material
  9369. Object.defineProperty(boxMesh.material, 'envMap', {
  9370. get: function () {
  9371. return this.uniforms.envMap.value;
  9372. }
  9373. });
  9374. objects.update(boxMesh);
  9375. }
  9376. if (background.isWebGLCubeRenderTarget) {
  9377. // TODO Deprecate
  9378. background = background.texture;
  9379. }
  9380. boxMesh.material.uniforms.envMap.value = background;
  9381. boxMesh.material.uniforms.flipEnvMap.value = background.isCubeTexture && background._needsFlipEnvMap ? -1 : 1;
  9382. if (currentBackground !== background || currentBackgroundVersion !== background.version || currentTonemapping !== renderer.toneMapping) {
  9383. boxMesh.material.needsUpdate = true;
  9384. currentBackground = background;
  9385. currentBackgroundVersion = background.version;
  9386. currentTonemapping = renderer.toneMapping;
  9387. } // push to the pre-sorted opaque render list
  9388. renderList.unshift(boxMesh, boxMesh.geometry, boxMesh.material, 0, 0, null);
  9389. } else if (background && background.isTexture) {
  9390. if (planeMesh === undefined) {
  9391. planeMesh = new Mesh(new PlaneBufferGeometry(2, 2), new ShaderMaterial({
  9392. name: 'BackgroundMaterial',
  9393. uniforms: cloneUniforms(ShaderLib.background.uniforms),
  9394. vertexShader: ShaderLib.background.vertexShader,
  9395. fragmentShader: ShaderLib.background.fragmentShader,
  9396. side: FrontSide,
  9397. depthTest: false,
  9398. depthWrite: false,
  9399. fog: false
  9400. }));
  9401. planeMesh.geometry.deleteAttribute('normal'); // enable code injection for non-built-in material
  9402. Object.defineProperty(planeMesh.material, 'map', {
  9403. get: function () {
  9404. return this.uniforms.t2D.value;
  9405. }
  9406. });
  9407. objects.update(planeMesh);
  9408. }
  9409. planeMesh.material.uniforms.t2D.value = background;
  9410. if (background.matrixAutoUpdate === true) {
  9411. background.updateMatrix();
  9412. }
  9413. planeMesh.material.uniforms.uvTransform.value.copy(background.matrix);
  9414. if (currentBackground !== background || currentBackgroundVersion !== background.version || currentTonemapping !== renderer.toneMapping) {
  9415. planeMesh.material.needsUpdate = true;
  9416. currentBackground = background;
  9417. currentBackgroundVersion = background.version;
  9418. currentTonemapping = renderer.toneMapping;
  9419. } // push to the pre-sorted opaque render list
  9420. renderList.unshift(planeMesh, planeMesh.geometry, planeMesh.material, 0, 0, null);
  9421. }
  9422. }
  9423. function setClear(color, alpha) {
  9424. state.buffers.color.setClear(color.r, color.g, color.b, alpha, premultipliedAlpha);
  9425. }
  9426. return {
  9427. getClearColor: function () {
  9428. return clearColor;
  9429. },
  9430. setClearColor: function (color, alpha = 1) {
  9431. clearColor.set(color);
  9432. clearAlpha = alpha;
  9433. setClear(clearColor, clearAlpha);
  9434. },
  9435. getClearAlpha: function () {
  9436. return clearAlpha;
  9437. },
  9438. setClearAlpha: function (alpha) {
  9439. clearAlpha = alpha;
  9440. setClear(clearColor, clearAlpha);
  9441. },
  9442. render: render
  9443. };
  9444. }
  9445. function WebGLBindingStates(gl, extensions, attributes, capabilities) {
  9446. const maxVertexAttributes = gl.getParameter(34921);
  9447. const extension = capabilities.isWebGL2 ? null : extensions.get('OES_vertex_array_object');
  9448. const vaoAvailable = capabilities.isWebGL2 || extension !== null;
  9449. const bindingStates = {};
  9450. const defaultState = createBindingState(null);
  9451. let currentState = defaultState;
  9452. function setup(object, material, program, geometry, index) {
  9453. let updateBuffers = false;
  9454. if (vaoAvailable) {
  9455. const state = getBindingState(geometry, program, material);
  9456. if (currentState !== state) {
  9457. currentState = state;
  9458. bindVertexArrayObject(currentState.object);
  9459. }
  9460. updateBuffers = needsUpdate(geometry, index);
  9461. if (updateBuffers) saveCache(geometry, index);
  9462. } else {
  9463. const wireframe = material.wireframe === true;
  9464. if (currentState.geometry !== geometry.id || currentState.program !== program.id || currentState.wireframe !== wireframe) {
  9465. currentState.geometry = geometry.id;
  9466. currentState.program = program.id;
  9467. currentState.wireframe = wireframe;
  9468. updateBuffers = true;
  9469. }
  9470. }
  9471. if (object.isInstancedMesh === true) {
  9472. updateBuffers = true;
  9473. }
  9474. if (index !== null) {
  9475. attributes.update(index, 34963);
  9476. }
  9477. if (updateBuffers) {
  9478. setupVertexAttributes(object, material, program, geometry);
  9479. if (index !== null) {
  9480. gl.bindBuffer(34963, attributes.get(index).buffer);
  9481. }
  9482. }
  9483. }
  9484. function createVertexArrayObject() {
  9485. if (capabilities.isWebGL2) return gl.createVertexArray();
  9486. return extension.createVertexArrayOES();
  9487. }
  9488. function bindVertexArrayObject(vao) {
  9489. if (capabilities.isWebGL2) return gl.bindVertexArray(vao);
  9490. return extension.bindVertexArrayOES(vao);
  9491. }
  9492. function deleteVertexArrayObject(vao) {
  9493. if (capabilities.isWebGL2) return gl.deleteVertexArray(vao);
  9494. return extension.deleteVertexArrayOES(vao);
  9495. }
  9496. function getBindingState(geometry, program, material) {
  9497. const wireframe = material.wireframe === true;
  9498. let programMap = bindingStates[geometry.id];
  9499. if (programMap === undefined) {
  9500. programMap = {};
  9501. bindingStates[geometry.id] = programMap;
  9502. }
  9503. let stateMap = programMap[program.id];
  9504. if (stateMap === undefined) {
  9505. stateMap = {};
  9506. programMap[program.id] = stateMap;
  9507. }
  9508. let state = stateMap[wireframe];
  9509. if (state === undefined) {
  9510. state = createBindingState(createVertexArrayObject());
  9511. stateMap[wireframe] = state;
  9512. }
  9513. return state;
  9514. }
  9515. function createBindingState(vao) {
  9516. const newAttributes = [];
  9517. const enabledAttributes = [];
  9518. const attributeDivisors = [];
  9519. for (let i = 0; i < maxVertexAttributes; i++) {
  9520. newAttributes[i] = 0;
  9521. enabledAttributes[i] = 0;
  9522. attributeDivisors[i] = 0;
  9523. }
  9524. return {
  9525. // for backward compatibility on non-VAO support browser
  9526. geometry: null,
  9527. program: null,
  9528. wireframe: false,
  9529. newAttributes: newAttributes,
  9530. enabledAttributes: enabledAttributes,
  9531. attributeDivisors: attributeDivisors,
  9532. object: vao,
  9533. attributes: {},
  9534. index: null
  9535. };
  9536. }
  9537. function needsUpdate(geometry, index) {
  9538. const cachedAttributes = currentState.attributes;
  9539. const geometryAttributes = geometry.attributes;
  9540. let attributesNum = 0;
  9541. for (const key in geometryAttributes) {
  9542. const cachedAttribute = cachedAttributes[key];
  9543. const geometryAttribute = geometryAttributes[key];
  9544. if (cachedAttribute === undefined) return true;
  9545. if (cachedAttribute.attribute !== geometryAttribute) return true;
  9546. if (cachedAttribute.data !== geometryAttribute.data) return true;
  9547. attributesNum++;
  9548. }
  9549. if (currentState.attributesNum !== attributesNum) return true;
  9550. if (currentState.index !== index) return true;
  9551. return false;
  9552. }
  9553. function saveCache(geometry, index) {
  9554. const cache = {};
  9555. const attributes = geometry.attributes;
  9556. let attributesNum = 0;
  9557. for (const key in attributes) {
  9558. const attribute = attributes[key];
  9559. const data = {};
  9560. data.attribute = attribute;
  9561. if (attribute.data) {
  9562. data.data = attribute.data;
  9563. }
  9564. cache[key] = data;
  9565. attributesNum++;
  9566. }
  9567. currentState.attributes = cache;
  9568. currentState.attributesNum = attributesNum;
  9569. currentState.index = index;
  9570. }
  9571. function initAttributes() {
  9572. const newAttributes = currentState.newAttributes;
  9573. for (let i = 0, il = newAttributes.length; i < il; i++) {
  9574. newAttributes[i] = 0;
  9575. }
  9576. }
  9577. function enableAttribute(attribute) {
  9578. enableAttributeAndDivisor(attribute, 0);
  9579. }
  9580. function enableAttributeAndDivisor(attribute, meshPerAttribute) {
  9581. const newAttributes = currentState.newAttributes;
  9582. const enabledAttributes = currentState.enabledAttributes;
  9583. const attributeDivisors = currentState.attributeDivisors;
  9584. newAttributes[attribute] = 1;
  9585. if (enabledAttributes[attribute] === 0) {
  9586. gl.enableVertexAttribArray(attribute);
  9587. enabledAttributes[attribute] = 1;
  9588. }
  9589. if (attributeDivisors[attribute] !== meshPerAttribute) {
  9590. const extension = capabilities.isWebGL2 ? gl : extensions.get('ANGLE_instanced_arrays');
  9591. extension[capabilities.isWebGL2 ? 'vertexAttribDivisor' : 'vertexAttribDivisorANGLE'](attribute, meshPerAttribute);
  9592. attributeDivisors[attribute] = meshPerAttribute;
  9593. }
  9594. }
  9595. function disableUnusedAttributes() {
  9596. const newAttributes = currentState.newAttributes;
  9597. const enabledAttributes = currentState.enabledAttributes;
  9598. for (let i = 0, il = enabledAttributes.length; i < il; i++) {
  9599. if (enabledAttributes[i] !== newAttributes[i]) {
  9600. gl.disableVertexAttribArray(i);
  9601. enabledAttributes[i] = 0;
  9602. }
  9603. }
  9604. }
  9605. function vertexAttribPointer(index, size, type, normalized, stride, offset) {
  9606. if (capabilities.isWebGL2 === true && (type === 5124 || type === 5125)) {
  9607. gl.vertexAttribIPointer(index, size, type, stride, offset);
  9608. } else {
  9609. gl.vertexAttribPointer(index, size, type, normalized, stride, offset);
  9610. }
  9611. }
  9612. function setupVertexAttributes(object, material, program, geometry) {
  9613. if (capabilities.isWebGL2 === false && (object.isInstancedMesh || geometry.isInstancedBufferGeometry)) {
  9614. if (extensions.get('ANGLE_instanced_arrays') === null) return;
  9615. }
  9616. initAttributes();
  9617. const geometryAttributes = geometry.attributes;
  9618. const programAttributes = program.getAttributes();
  9619. const materialDefaultAttributeValues = material.defaultAttributeValues;
  9620. for (const name in programAttributes) {
  9621. const programAttribute = programAttributes[name];
  9622. if (programAttribute >= 0) {
  9623. const geometryAttribute = geometryAttributes[name];
  9624. if (geometryAttribute !== undefined) {
  9625. const normalized = geometryAttribute.normalized;
  9626. const size = geometryAttribute.itemSize;
  9627. const attribute = attributes.get(geometryAttribute); // TODO Attribute may not be available on context restore
  9628. if (attribute === undefined) continue;
  9629. const buffer = attribute.buffer;
  9630. const type = attribute.type;
  9631. const bytesPerElement = attribute.bytesPerElement;
  9632. if (geometryAttribute.isInterleavedBufferAttribute) {
  9633. const data = geometryAttribute.data;
  9634. const stride = data.stride;
  9635. const offset = geometryAttribute.offset;
  9636. if (data && data.isInstancedInterleavedBuffer) {
  9637. enableAttributeAndDivisor(programAttribute, data.meshPerAttribute);
  9638. if (geometry._maxInstanceCount === undefined) {
  9639. geometry._maxInstanceCount = data.meshPerAttribute * data.count;
  9640. }
  9641. } else {
  9642. enableAttribute(programAttribute);
  9643. }
  9644. gl.bindBuffer(34962, buffer);
  9645. vertexAttribPointer(programAttribute, size, type, normalized, stride * bytesPerElement, offset * bytesPerElement);
  9646. } else {
  9647. if (geometryAttribute.isInstancedBufferAttribute) {
  9648. enableAttributeAndDivisor(programAttribute, geometryAttribute.meshPerAttribute);
  9649. if (geometry._maxInstanceCount === undefined) {
  9650. geometry._maxInstanceCount = geometryAttribute.meshPerAttribute * geometryAttribute.count;
  9651. }
  9652. } else {
  9653. enableAttribute(programAttribute);
  9654. }
  9655. gl.bindBuffer(34962, buffer);
  9656. vertexAttribPointer(programAttribute, size, type, normalized, 0, 0);
  9657. }
  9658. } else if (name === 'instanceMatrix') {
  9659. const attribute = attributes.get(object.instanceMatrix); // TODO Attribute may not be available on context restore
  9660. if (attribute === undefined) continue;
  9661. const buffer = attribute.buffer;
  9662. const type = attribute.type;
  9663. enableAttributeAndDivisor(programAttribute + 0, 1);
  9664. enableAttributeAndDivisor(programAttribute + 1, 1);
  9665. enableAttributeAndDivisor(programAttribute + 2, 1);
  9666. enableAttributeAndDivisor(programAttribute + 3, 1);
  9667. gl.bindBuffer(34962, buffer);
  9668. gl.vertexAttribPointer(programAttribute + 0, 4, type, false, 64, 0);
  9669. gl.vertexAttribPointer(programAttribute + 1, 4, type, false, 64, 16);
  9670. gl.vertexAttribPointer(programAttribute + 2, 4, type, false, 64, 32);
  9671. gl.vertexAttribPointer(programAttribute + 3, 4, type, false, 64, 48);
  9672. } else if (name === 'instanceColor') {
  9673. const attribute = attributes.get(object.instanceColor); // TODO Attribute may not be available on context restore
  9674. if (attribute === undefined) continue;
  9675. const buffer = attribute.buffer;
  9676. const type = attribute.type;
  9677. enableAttributeAndDivisor(programAttribute, 1);
  9678. gl.bindBuffer(34962, buffer);
  9679. gl.vertexAttribPointer(programAttribute, 3, type, false, 12, 0);
  9680. } else if (materialDefaultAttributeValues !== undefined) {
  9681. const value = materialDefaultAttributeValues[name];
  9682. if (value !== undefined) {
  9683. switch (value.length) {
  9684. case 2:
  9685. gl.vertexAttrib2fv(programAttribute, value);
  9686. break;
  9687. case 3:
  9688. gl.vertexAttrib3fv(programAttribute, value);
  9689. break;
  9690. case 4:
  9691. gl.vertexAttrib4fv(programAttribute, value);
  9692. break;
  9693. default:
  9694. gl.vertexAttrib1fv(programAttribute, value);
  9695. }
  9696. }
  9697. }
  9698. }
  9699. }
  9700. disableUnusedAttributes();
  9701. }
  9702. function dispose() {
  9703. reset();
  9704. for (const geometryId in bindingStates) {
  9705. const programMap = bindingStates[geometryId];
  9706. for (const programId in programMap) {
  9707. const stateMap = programMap[programId];
  9708. for (const wireframe in stateMap) {
  9709. deleteVertexArrayObject(stateMap[wireframe].object);
  9710. delete stateMap[wireframe];
  9711. }
  9712. delete programMap[programId];
  9713. }
  9714. delete bindingStates[geometryId];
  9715. }
  9716. }
  9717. function releaseStatesOfGeometry(geometry) {
  9718. if (bindingStates[geometry.id] === undefined) return;
  9719. const programMap = bindingStates[geometry.id];
  9720. for (const programId in programMap) {
  9721. const stateMap = programMap[programId];
  9722. for (const wireframe in stateMap) {
  9723. deleteVertexArrayObject(stateMap[wireframe].object);
  9724. delete stateMap[wireframe];
  9725. }
  9726. delete programMap[programId];
  9727. }
  9728. delete bindingStates[geometry.id];
  9729. }
  9730. function releaseStatesOfProgram(program) {
  9731. for (const geometryId in bindingStates) {
  9732. const programMap = bindingStates[geometryId];
  9733. if (programMap[program.id] === undefined) continue;
  9734. const stateMap = programMap[program.id];
  9735. for (const wireframe in stateMap) {
  9736. deleteVertexArrayObject(stateMap[wireframe].object);
  9737. delete stateMap[wireframe];
  9738. }
  9739. delete programMap[program.id];
  9740. }
  9741. }
  9742. function reset() {
  9743. resetDefaultState();
  9744. if (currentState === defaultState) return;
  9745. currentState = defaultState;
  9746. bindVertexArrayObject(currentState.object);
  9747. } // for backward-compatilibity
  9748. function resetDefaultState() {
  9749. defaultState.geometry = null;
  9750. defaultState.program = null;
  9751. defaultState.wireframe = false;
  9752. }
  9753. return {
  9754. setup: setup,
  9755. reset: reset,
  9756. resetDefaultState: resetDefaultState,
  9757. dispose: dispose,
  9758. releaseStatesOfGeometry: releaseStatesOfGeometry,
  9759. releaseStatesOfProgram: releaseStatesOfProgram,
  9760. initAttributes: initAttributes,
  9761. enableAttribute: enableAttribute,
  9762. disableUnusedAttributes: disableUnusedAttributes
  9763. };
  9764. }
  9765. function WebGLBufferRenderer(gl, extensions, info, capabilities) {
  9766. const isWebGL2 = capabilities.isWebGL2;
  9767. let mode;
  9768. function setMode(value) {
  9769. mode = value;
  9770. }
  9771. function render(start, count) {
  9772. gl.drawArrays(mode, start, count);
  9773. info.update(count, mode, 1);
  9774. }
  9775. function renderInstances(start, count, primcount) {
  9776. if (primcount === 0) return;
  9777. let extension, methodName;
  9778. if (isWebGL2) {
  9779. extension = gl;
  9780. methodName = 'drawArraysInstanced';
  9781. } else {
  9782. extension = extensions.get('ANGLE_instanced_arrays');
  9783. methodName = 'drawArraysInstancedANGLE';
  9784. if (extension === null) {
  9785. console.error('THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.');
  9786. return;
  9787. }
  9788. }
  9789. extension[methodName](mode, start, count, primcount);
  9790. info.update(count, mode, primcount);
  9791. } //
  9792. this.setMode = setMode;
  9793. this.render = render;
  9794. this.renderInstances = renderInstances;
  9795. }
  9796. function WebGLCapabilities(gl, extensions, parameters) {
  9797. let maxAnisotropy;
  9798. function getMaxAnisotropy() {
  9799. if (maxAnisotropy !== undefined) return maxAnisotropy;
  9800. const extension = extensions.get('EXT_texture_filter_anisotropic');
  9801. if (extension !== null) {
  9802. maxAnisotropy = gl.getParameter(extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT);
  9803. } else {
  9804. maxAnisotropy = 0;
  9805. }
  9806. return maxAnisotropy;
  9807. }
  9808. function getMaxPrecision(precision) {
  9809. if (precision === 'highp') {
  9810. if (gl.getShaderPrecisionFormat(35633, 36338).precision > 0 && gl.getShaderPrecisionFormat(35632, 36338).precision > 0) {
  9811. return 'highp';
  9812. }
  9813. precision = 'mediump';
  9814. }
  9815. if (precision === 'mediump') {
  9816. if (gl.getShaderPrecisionFormat(35633, 36337).precision > 0 && gl.getShaderPrecisionFormat(35632, 36337).precision > 0) {
  9817. return 'mediump';
  9818. }
  9819. }
  9820. return 'lowp';
  9821. }
  9822. /* eslint-disable no-undef */
  9823. const isWebGL2 = typeof WebGL2RenderingContext !== 'undefined' && gl instanceof WebGL2RenderingContext || typeof WebGL2ComputeRenderingContext !== 'undefined' && gl instanceof WebGL2ComputeRenderingContext;
  9824. /* eslint-enable no-undef */
  9825. let precision = parameters.precision !== undefined ? parameters.precision : 'highp';
  9826. const maxPrecision = getMaxPrecision(precision);
  9827. if (maxPrecision !== precision) {
  9828. console.warn('THREE.WebGLRenderer:', precision, 'not supported, using', maxPrecision, 'instead.');
  9829. precision = maxPrecision;
  9830. }
  9831. const logarithmicDepthBuffer = parameters.logarithmicDepthBuffer === true;
  9832. const maxTextures = gl.getParameter(34930);
  9833. const maxVertexTextures = gl.getParameter(35660);
  9834. const maxTextureSize = gl.getParameter(3379);
  9835. const maxCubemapSize = gl.getParameter(34076);
  9836. const maxAttributes = gl.getParameter(34921);
  9837. const maxVertexUniforms = gl.getParameter(36347);
  9838. const maxVaryings = gl.getParameter(36348);
  9839. const maxFragmentUniforms = gl.getParameter(36349);
  9840. const vertexTextures = maxVertexTextures > 0;
  9841. const floatFragmentTextures = isWebGL2 || !!extensions.get('OES_texture_float');
  9842. const floatVertexTextures = vertexTextures && floatFragmentTextures;
  9843. const maxSamples = isWebGL2 ? gl.getParameter(36183) : 0;
  9844. return {
  9845. isWebGL2: isWebGL2,
  9846. getMaxAnisotropy: getMaxAnisotropy,
  9847. getMaxPrecision: getMaxPrecision,
  9848. precision: precision,
  9849. logarithmicDepthBuffer: logarithmicDepthBuffer,
  9850. maxTextures: maxTextures,
  9851. maxVertexTextures: maxVertexTextures,
  9852. maxTextureSize: maxTextureSize,
  9853. maxCubemapSize: maxCubemapSize,
  9854. maxAttributes: maxAttributes,
  9855. maxVertexUniforms: maxVertexUniforms,
  9856. maxVaryings: maxVaryings,
  9857. maxFragmentUniforms: maxFragmentUniforms,
  9858. vertexTextures: vertexTextures,
  9859. floatFragmentTextures: floatFragmentTextures,
  9860. floatVertexTextures: floatVertexTextures,
  9861. maxSamples: maxSamples
  9862. };
  9863. }
  9864. function WebGLClipping(properties) {
  9865. const scope = this;
  9866. let globalState = null,
  9867. numGlobalPlanes = 0,
  9868. localClippingEnabled = false,
  9869. renderingShadows = false;
  9870. const plane = new Plane(),
  9871. viewNormalMatrix = new Matrix3(),
  9872. uniform = {
  9873. value: null,
  9874. needsUpdate: false
  9875. };
  9876. this.uniform = uniform;
  9877. this.numPlanes = 0;
  9878. this.numIntersection = 0;
  9879. this.init = function (planes, enableLocalClipping, camera) {
  9880. const enabled = planes.length !== 0 || enableLocalClipping || // enable state of previous frame - the clipping code has to
  9881. // run another frame in order to reset the state:
  9882. numGlobalPlanes !== 0 || localClippingEnabled;
  9883. localClippingEnabled = enableLocalClipping;
  9884. globalState = projectPlanes(planes, camera, 0);
  9885. numGlobalPlanes = planes.length;
  9886. return enabled;
  9887. };
  9888. this.beginShadows = function () {
  9889. renderingShadows = true;
  9890. projectPlanes(null);
  9891. };
  9892. this.endShadows = function () {
  9893. renderingShadows = false;
  9894. resetGlobalState();
  9895. };
  9896. this.setState = function (material, camera, useCache) {
  9897. const planes = material.clippingPlanes,
  9898. clipIntersection = material.clipIntersection,
  9899. clipShadows = material.clipShadows;
  9900. const materialProperties = properties.get(material);
  9901. if (!localClippingEnabled || planes === null || planes.length === 0 || renderingShadows && !clipShadows) {
  9902. // there's no local clipping
  9903. if (renderingShadows) {
  9904. // there's no global clipping
  9905. projectPlanes(null);
  9906. } else {
  9907. resetGlobalState();
  9908. }
  9909. } else {
  9910. const nGlobal = renderingShadows ? 0 : numGlobalPlanes,
  9911. lGlobal = nGlobal * 4;
  9912. let dstArray = materialProperties.clippingState || null;
  9913. uniform.value = dstArray; // ensure unique state
  9914. dstArray = projectPlanes(planes, camera, lGlobal, useCache);
  9915. for (let i = 0; i !== lGlobal; ++i) {
  9916. dstArray[i] = globalState[i];
  9917. }
  9918. materialProperties.clippingState = dstArray;
  9919. this.numIntersection = clipIntersection ? this.numPlanes : 0;
  9920. this.numPlanes += nGlobal;
  9921. }
  9922. };
  9923. function resetGlobalState() {
  9924. if (uniform.value !== globalState) {
  9925. uniform.value = globalState;
  9926. uniform.needsUpdate = numGlobalPlanes > 0;
  9927. }
  9928. scope.numPlanes = numGlobalPlanes;
  9929. scope.numIntersection = 0;
  9930. }
  9931. function projectPlanes(planes, camera, dstOffset, skipTransform) {
  9932. const nPlanes = planes !== null ? planes.length : 0;
  9933. let dstArray = null;
  9934. if (nPlanes !== 0) {
  9935. dstArray = uniform.value;
  9936. if (skipTransform !== true || dstArray === null) {
  9937. const flatSize = dstOffset + nPlanes * 4,
  9938. viewMatrix = camera.matrixWorldInverse;
  9939. viewNormalMatrix.getNormalMatrix(viewMatrix);
  9940. if (dstArray === null || dstArray.length < flatSize) {
  9941. dstArray = new Float32Array(flatSize);
  9942. }
  9943. for (let i = 0, i4 = dstOffset; i !== nPlanes; ++i, i4 += 4) {
  9944. plane.copy(planes[i]).applyMatrix4(viewMatrix, viewNormalMatrix);
  9945. plane.normal.toArray(dstArray, i4);
  9946. dstArray[i4 + 3] = plane.constant;
  9947. }
  9948. }
  9949. uniform.value = dstArray;
  9950. uniform.needsUpdate = true;
  9951. }
  9952. scope.numPlanes = nPlanes;
  9953. scope.numIntersection = 0;
  9954. return dstArray;
  9955. }
  9956. }
  9957. function WebGLCubeMaps(renderer) {
  9958. let cubemaps = new WeakMap();
  9959. function mapTextureMapping(texture, mapping) {
  9960. if (mapping === EquirectangularReflectionMapping) {
  9961. texture.mapping = CubeReflectionMapping;
  9962. } else if (mapping === EquirectangularRefractionMapping) {
  9963. texture.mapping = CubeRefractionMapping;
  9964. }
  9965. return texture;
  9966. }
  9967. function get(texture) {
  9968. if (texture && texture.isTexture) {
  9969. const mapping = texture.mapping;
  9970. if (mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping) {
  9971. if (cubemaps.has(texture)) {
  9972. const cubemap = cubemaps.get(texture).texture;
  9973. return mapTextureMapping(cubemap, texture.mapping);
  9974. } else {
  9975. const image = texture.image;
  9976. if (image && image.height > 0) {
  9977. const currentRenderList = renderer.getRenderList();
  9978. const currentRenderTarget = renderer.getRenderTarget();
  9979. const currentRenderState = renderer.getRenderState();
  9980. const renderTarget = new WebGLCubeRenderTarget(image.height / 2);
  9981. renderTarget.fromEquirectangularTexture(renderer, texture);
  9982. cubemaps.set(texture, renderTarget);
  9983. renderer.setRenderTarget(currentRenderTarget);
  9984. renderer.setRenderList(currentRenderList);
  9985. renderer.setRenderState(currentRenderState);
  9986. texture.addEventListener('dispose', onTextureDispose);
  9987. return mapTextureMapping(renderTarget.texture, texture.mapping);
  9988. } else {
  9989. // image not yet ready. try the conversion next frame
  9990. return null;
  9991. }
  9992. }
  9993. }
  9994. }
  9995. return texture;
  9996. }
  9997. function onTextureDispose(event) {
  9998. const texture = event.target;
  9999. texture.removeEventListener('dispose', onTextureDispose);
  10000. const cubemap = cubemaps.get(texture);
  10001. if (cubemap !== undefined) {
  10002. cubemaps.delete(texture);
  10003. cubemap.dispose();
  10004. }
  10005. }
  10006. function dispose() {
  10007. cubemaps = new WeakMap();
  10008. }
  10009. return {
  10010. get: get,
  10011. dispose: dispose
  10012. };
  10013. }
  10014. function WebGLExtensions(gl) {
  10015. const extensions = {};
  10016. return {
  10017. has: function (name) {
  10018. if (extensions[name] !== undefined) {
  10019. return extensions[name] !== null;
  10020. }
  10021. let extension;
  10022. switch (name) {
  10023. case 'WEBGL_depth_texture':
  10024. extension = gl.getExtension('WEBGL_depth_texture') || gl.getExtension('MOZ_WEBGL_depth_texture') || gl.getExtension('WEBKIT_WEBGL_depth_texture');
  10025. break;
  10026. case 'EXT_texture_filter_anisotropic':
  10027. extension = gl.getExtension('EXT_texture_filter_anisotropic') || gl.getExtension('MOZ_EXT_texture_filter_anisotropic') || gl.getExtension('WEBKIT_EXT_texture_filter_anisotropic');
  10028. break;
  10029. case 'WEBGL_compressed_texture_s3tc':
  10030. extension = gl.getExtension('WEBGL_compressed_texture_s3tc') || gl.getExtension('MOZ_WEBGL_compressed_texture_s3tc') || gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  10031. break;
  10032. case 'WEBGL_compressed_texture_pvrtc':
  10033. extension = gl.getExtension('WEBGL_compressed_texture_pvrtc') || gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  10034. break;
  10035. default:
  10036. extension = gl.getExtension(name);
  10037. }
  10038. extensions[name] = extension;
  10039. return extension !== null;
  10040. },
  10041. get: function (name) {
  10042. if (!this.has(name)) {
  10043. console.warn('THREE.WebGLRenderer: ' + name + ' extension not supported.');
  10044. }
  10045. return extensions[name];
  10046. }
  10047. };
  10048. }
  10049. function WebGLGeometries(gl, attributes, info, bindingStates) {
  10050. const geometries = new WeakMap();
  10051. const wireframeAttributes = new WeakMap();
  10052. function onGeometryDispose(event) {
  10053. const geometry = event.target;
  10054. const buffergeometry = geometries.get(geometry);
  10055. if (buffergeometry.index !== null) {
  10056. attributes.remove(buffergeometry.index);
  10057. }
  10058. for (const name in buffergeometry.attributes) {
  10059. attributes.remove(buffergeometry.attributes[name]);
  10060. }
  10061. geometry.removeEventListener('dispose', onGeometryDispose);
  10062. geometries.delete(geometry);
  10063. const attribute = wireframeAttributes.get(buffergeometry);
  10064. if (attribute) {
  10065. attributes.remove(attribute);
  10066. wireframeAttributes.delete(buffergeometry);
  10067. }
  10068. bindingStates.releaseStatesOfGeometry(buffergeometry);
  10069. if (geometry.isInstancedBufferGeometry === true) {
  10070. delete geometry._maxInstanceCount;
  10071. } //
  10072. info.memory.geometries--;
  10073. }
  10074. function get(object, geometry) {
  10075. let buffergeometry = geometries.get(geometry);
  10076. if (buffergeometry) return buffergeometry;
  10077. geometry.addEventListener('dispose', onGeometryDispose);
  10078. if (geometry.isBufferGeometry) {
  10079. buffergeometry = geometry;
  10080. } else if (geometry.isGeometry) {
  10081. if (geometry._bufferGeometry === undefined) {
  10082. geometry._bufferGeometry = new BufferGeometry().setFromObject(object);
  10083. }
  10084. buffergeometry = geometry._bufferGeometry;
  10085. }
  10086. geometries.set(geometry, buffergeometry);
  10087. info.memory.geometries++;
  10088. return buffergeometry;
  10089. }
  10090. function update(geometry) {
  10091. const geometryAttributes = geometry.attributes; // Updating index buffer in VAO now. See WebGLBindingStates.
  10092. for (const name in geometryAttributes) {
  10093. attributes.update(geometryAttributes[name], 34962);
  10094. } // morph targets
  10095. const morphAttributes = geometry.morphAttributes;
  10096. for (const name in morphAttributes) {
  10097. const array = morphAttributes[name];
  10098. for (let i = 0, l = array.length; i < l; i++) {
  10099. attributes.update(array[i], 34962);
  10100. }
  10101. }
  10102. }
  10103. function updateWireframeAttribute(geometry) {
  10104. const indices = [];
  10105. const geometryIndex = geometry.index;
  10106. const geometryPosition = geometry.attributes.position;
  10107. let version = 0;
  10108. if (geometryIndex !== null) {
  10109. const array = geometryIndex.array;
  10110. version = geometryIndex.version;
  10111. for (let i = 0, l = array.length; i < l; i += 3) {
  10112. const a = array[i + 0];
  10113. const b = array[i + 1];
  10114. const c = array[i + 2];
  10115. indices.push(a, b, b, c, c, a);
  10116. }
  10117. } else {
  10118. const array = geometryPosition.array;
  10119. version = geometryPosition.version;
  10120. for (let i = 0, l = array.length / 3 - 1; i < l; i += 3) {
  10121. const a = i + 0;
  10122. const b = i + 1;
  10123. const c = i + 2;
  10124. indices.push(a, b, b, c, c, a);
  10125. }
  10126. }
  10127. const attribute = new (arrayMax(indices) > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute)(indices, 1);
  10128. attribute.version = version; // Updating index buffer in VAO now. See WebGLBindingStates
  10129. //
  10130. const previousAttribute = wireframeAttributes.get(geometry);
  10131. if (previousAttribute) attributes.remove(previousAttribute); //
  10132. wireframeAttributes.set(geometry, attribute);
  10133. }
  10134. function getWireframeAttribute(geometry) {
  10135. const currentAttribute = wireframeAttributes.get(geometry);
  10136. if (currentAttribute) {
  10137. const geometryIndex = geometry.index;
  10138. if (geometryIndex !== null) {
  10139. // if the attribute is obsolete, create a new one
  10140. if (currentAttribute.version < geometryIndex.version) {
  10141. updateWireframeAttribute(geometry);
  10142. }
  10143. }
  10144. } else {
  10145. updateWireframeAttribute(geometry);
  10146. }
  10147. return wireframeAttributes.get(geometry);
  10148. }
  10149. return {
  10150. get: get,
  10151. update: update,
  10152. getWireframeAttribute: getWireframeAttribute
  10153. };
  10154. }
  10155. function WebGLIndexedBufferRenderer(gl, extensions, info, capabilities) {
  10156. const isWebGL2 = capabilities.isWebGL2;
  10157. let mode;
  10158. function setMode(value) {
  10159. mode = value;
  10160. }
  10161. let type, bytesPerElement;
  10162. function setIndex(value) {
  10163. type = value.type;
  10164. bytesPerElement = value.bytesPerElement;
  10165. }
  10166. function render(start, count) {
  10167. gl.drawElements(mode, count, type, start * bytesPerElement);
  10168. info.update(count, mode, 1);
  10169. }
  10170. function renderInstances(start, count, primcount) {
  10171. if (primcount === 0) return;
  10172. let extension, methodName;
  10173. if (isWebGL2) {
  10174. extension = gl;
  10175. methodName = 'drawElementsInstanced';
  10176. } else {
  10177. extension = extensions.get('ANGLE_instanced_arrays');
  10178. methodName = 'drawElementsInstancedANGLE';
  10179. if (extension === null) {
  10180. console.error('THREE.WebGLIndexedBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.');
  10181. return;
  10182. }
  10183. }
  10184. extension[methodName](mode, count, type, start * bytesPerElement, primcount);
  10185. info.update(count, mode, primcount);
  10186. } //
  10187. this.setMode = setMode;
  10188. this.setIndex = setIndex;
  10189. this.render = render;
  10190. this.renderInstances = renderInstances;
  10191. }
  10192. function WebGLInfo(gl) {
  10193. const memory = {
  10194. geometries: 0,
  10195. textures: 0
  10196. };
  10197. const render = {
  10198. frame: 0,
  10199. calls: 0,
  10200. triangles: 0,
  10201. points: 0,
  10202. lines: 0
  10203. };
  10204. function update(count, mode, instanceCount) {
  10205. render.calls++;
  10206. switch (mode) {
  10207. case 4:
  10208. render.triangles += instanceCount * (count / 3);
  10209. break;
  10210. case 1:
  10211. render.lines += instanceCount * (count / 2);
  10212. break;
  10213. case 3:
  10214. render.lines += instanceCount * (count - 1);
  10215. break;
  10216. case 2:
  10217. render.lines += instanceCount * count;
  10218. break;
  10219. case 0:
  10220. render.points += instanceCount * count;
  10221. break;
  10222. default:
  10223. console.error('THREE.WebGLInfo: Unknown draw mode:', mode);
  10224. break;
  10225. }
  10226. }
  10227. function reset() {
  10228. render.frame++;
  10229. render.calls = 0;
  10230. render.triangles = 0;
  10231. render.points = 0;
  10232. render.lines = 0;
  10233. }
  10234. return {
  10235. memory: memory,
  10236. render: render,
  10237. programs: null,
  10238. autoReset: true,
  10239. reset: reset,
  10240. update: update
  10241. };
  10242. }
  10243. function numericalSort(a, b) {
  10244. return a[0] - b[0];
  10245. }
  10246. function absNumericalSort(a, b) {
  10247. return Math.abs(b[1]) - Math.abs(a[1]);
  10248. }
  10249. function WebGLMorphtargets(gl) {
  10250. const influencesList = {};
  10251. const morphInfluences = new Float32Array(8);
  10252. const workInfluences = [];
  10253. for (let i = 0; i < 8; i++) {
  10254. workInfluences[i] = [i, 0];
  10255. }
  10256. function update(object, geometry, material, program) {
  10257. const objectInfluences = object.morphTargetInfluences; // When object doesn't have morph target influences defined, we treat it as a 0-length array
  10258. // This is important to make sure we set up morphTargetBaseInfluence / morphTargetInfluences
  10259. const length = objectInfluences === undefined ? 0 : objectInfluences.length;
  10260. let influences = influencesList[geometry.id];
  10261. if (influences === undefined) {
  10262. // initialise list
  10263. influences = [];
  10264. for (let i = 0; i < length; i++) {
  10265. influences[i] = [i, 0];
  10266. }
  10267. influencesList[geometry.id] = influences;
  10268. } // Collect influences
  10269. for (let i = 0; i < length; i++) {
  10270. const influence = influences[i];
  10271. influence[0] = i;
  10272. influence[1] = objectInfluences[i];
  10273. }
  10274. influences.sort(absNumericalSort);
  10275. for (let i = 0; i < 8; i++) {
  10276. if (i < length && influences[i][1]) {
  10277. workInfluences[i][0] = influences[i][0];
  10278. workInfluences[i][1] = influences[i][1];
  10279. } else {
  10280. workInfluences[i][0] = Number.MAX_SAFE_INTEGER;
  10281. workInfluences[i][1] = 0;
  10282. }
  10283. }
  10284. workInfluences.sort(numericalSort);
  10285. const morphTargets = material.morphTargets && geometry.morphAttributes.position;
  10286. const morphNormals = material.morphNormals && geometry.morphAttributes.normal;
  10287. let morphInfluencesSum = 0;
  10288. for (let i = 0; i < 8; i++) {
  10289. const influence = workInfluences[i];
  10290. const index = influence[0];
  10291. const value = influence[1];
  10292. if (index !== Number.MAX_SAFE_INTEGER && value) {
  10293. if (morphTargets && geometry.getAttribute('morphTarget' + i) !== morphTargets[index]) {
  10294. geometry.setAttribute('morphTarget' + i, morphTargets[index]);
  10295. }
  10296. if (morphNormals && geometry.getAttribute('morphNormal' + i) !== morphNormals[index]) {
  10297. geometry.setAttribute('morphNormal' + i, morphNormals[index]);
  10298. }
  10299. morphInfluences[i] = value;
  10300. morphInfluencesSum += value;
  10301. } else {
  10302. if (morphTargets && geometry.hasAttribute('morphTarget' + i) === true) {
  10303. geometry.deleteAttribute('morphTarget' + i);
  10304. }
  10305. if (morphNormals && geometry.hasAttribute('morphNormal' + i) === true) {
  10306. geometry.deleteAttribute('morphNormal' + i);
  10307. }
  10308. morphInfluences[i] = 0;
  10309. }
  10310. } // GLSL shader uses formula baseinfluence * base + sum(target * influence)
  10311. // This allows us to switch between absolute morphs and relative morphs without changing shader code
  10312. // When baseinfluence = 1 - sum(influence), the above is equivalent to sum((target - base) * influence)
  10313. const morphBaseInfluence = geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
  10314. program.getUniforms().setValue(gl, 'morphTargetBaseInfluence', morphBaseInfluence);
  10315. program.getUniforms().setValue(gl, 'morphTargetInfluences', morphInfluences);
  10316. }
  10317. return {
  10318. update: update
  10319. };
  10320. }
  10321. function WebGLObjects(gl, geometries, attributes, info) {
  10322. let updateMap = new WeakMap();
  10323. function update(object) {
  10324. const frame = info.render.frame;
  10325. const geometry = object.geometry;
  10326. const buffergeometry = geometries.get(object, geometry); // Update once per frame
  10327. if (updateMap.get(buffergeometry) !== frame) {
  10328. if (geometry.isGeometry) {
  10329. buffergeometry.updateFromObject(object);
  10330. }
  10331. geometries.update(buffergeometry);
  10332. updateMap.set(buffergeometry, frame);
  10333. }
  10334. if (object.isInstancedMesh) {
  10335. attributes.update(object.instanceMatrix, 34962);
  10336. if (object.instanceColor !== null) {
  10337. attributes.update(object.instanceColor, 34962);
  10338. }
  10339. }
  10340. return buffergeometry;
  10341. }
  10342. function dispose() {
  10343. updateMap = new WeakMap();
  10344. }
  10345. return {
  10346. update: update,
  10347. dispose: dispose
  10348. };
  10349. }
  10350. function DataTexture2DArray(data = null, width = 1, height = 1, depth = 1) {
  10351. Texture.call(this, null);
  10352. this.image = {
  10353. data,
  10354. width,
  10355. height,
  10356. depth
  10357. };
  10358. this.magFilter = NearestFilter;
  10359. this.minFilter = NearestFilter;
  10360. this.wrapR = ClampToEdgeWrapping;
  10361. this.generateMipmaps = false;
  10362. this.flipY = false;
  10363. this.needsUpdate = true;
  10364. }
  10365. DataTexture2DArray.prototype = Object.create(Texture.prototype);
  10366. DataTexture2DArray.prototype.constructor = DataTexture2DArray;
  10367. DataTexture2DArray.prototype.isDataTexture2DArray = true;
  10368. function DataTexture3D(data = null, width = 1, height = 1, depth = 1) {
  10369. // We're going to add .setXXX() methods for setting properties later.
  10370. // Users can still set in DataTexture3D directly.
  10371. //
  10372. // const texture = new THREE.DataTexture3D( data, width, height, depth );
  10373. // texture.anisotropy = 16;
  10374. //
  10375. // See #14839
  10376. Texture.call(this, null);
  10377. this.image = {
  10378. data,
  10379. width,
  10380. height,
  10381. depth
  10382. };
  10383. this.magFilter = NearestFilter;
  10384. this.minFilter = NearestFilter;
  10385. this.wrapR = ClampToEdgeWrapping;
  10386. this.generateMipmaps = false;
  10387. this.flipY = false;
  10388. this.needsUpdate = true;
  10389. }
  10390. DataTexture3D.prototype = Object.create(Texture.prototype);
  10391. DataTexture3D.prototype.constructor = DataTexture3D;
  10392. DataTexture3D.prototype.isDataTexture3D = true;
  10393. /**
  10394. * Uniforms of a program.
  10395. * Those form a tree structure with a special top-level container for the root,
  10396. * which you get by calling 'new WebGLUniforms( gl, program )'.
  10397. *
  10398. *
  10399. * Properties of inner nodes including the top-level container:
  10400. *
  10401. * .seq - array of nested uniforms
  10402. * .map - nested uniforms by name
  10403. *
  10404. *
  10405. * Methods of all nodes except the top-level container:
  10406. *
  10407. * .setValue( gl, value, [textures] )
  10408. *
  10409. * uploads a uniform value(s)
  10410. * the 'textures' parameter is needed for sampler uniforms
  10411. *
  10412. *
  10413. * Static methods of the top-level container (textures factorizations):
  10414. *
  10415. * .upload( gl, seq, values, textures )
  10416. *
  10417. * sets uniforms in 'seq' to 'values[id].value'
  10418. *
  10419. * .seqWithValue( seq, values ) : filteredSeq
  10420. *
  10421. * filters 'seq' entries with corresponding entry in values
  10422. *
  10423. *
  10424. * Methods of the top-level container (textures factorizations):
  10425. *
  10426. * .setValue( gl, name, value, textures )
  10427. *
  10428. * sets uniform with name 'name' to 'value'
  10429. *
  10430. * .setOptional( gl, obj, prop )
  10431. *
  10432. * like .set for an optional property of the object
  10433. *
  10434. */
  10435. const emptyTexture = new Texture();
  10436. const emptyTexture2dArray = new DataTexture2DArray();
  10437. const emptyTexture3d = new DataTexture3D();
  10438. const emptyCubeTexture = new CubeTexture(); // --- Utilities ---
  10439. // Array Caches (provide typed arrays for temporary by size)
  10440. const arrayCacheF32 = [];
  10441. const arrayCacheI32 = []; // Float32Array caches used for uploading Matrix uniforms
  10442. const mat4array = new Float32Array(16);
  10443. const mat3array = new Float32Array(9);
  10444. const mat2array = new Float32Array(4); // Flattening for arrays of vectors and matrices
  10445. function flatten(array, nBlocks, blockSize) {
  10446. const firstElem = array[0];
  10447. if (firstElem <= 0 || firstElem > 0) return array; // unoptimized: ! isNaN( firstElem )
  10448. // see http://jacksondunstan.com/articles/983
  10449. const n = nBlocks * blockSize;
  10450. let r = arrayCacheF32[n];
  10451. if (r === undefined) {
  10452. r = new Float32Array(n);
  10453. arrayCacheF32[n] = r;
  10454. }
  10455. if (nBlocks !== 0) {
  10456. firstElem.toArray(r, 0);
  10457. for (let i = 1, offset = 0; i !== nBlocks; ++i) {
  10458. offset += blockSize;
  10459. array[i].toArray(r, offset);
  10460. }
  10461. }
  10462. return r;
  10463. }
  10464. function arraysEqual(a, b) {
  10465. if (a.length !== b.length) return false;
  10466. for (let i = 0, l = a.length; i < l; i++) {
  10467. if (a[i] !== b[i]) return false;
  10468. }
  10469. return true;
  10470. }
  10471. function copyArray(a, b) {
  10472. for (let i = 0, l = b.length; i < l; i++) {
  10473. a[i] = b[i];
  10474. }
  10475. } // Texture unit allocation
  10476. function allocTexUnits(textures, n) {
  10477. let r = arrayCacheI32[n];
  10478. if (r === undefined) {
  10479. r = new Int32Array(n);
  10480. arrayCacheI32[n] = r;
  10481. }
  10482. for (let i = 0; i !== n; ++i) {
  10483. r[i] = textures.allocateTextureUnit();
  10484. }
  10485. return r;
  10486. } // --- Setters ---
  10487. // Note: Defining these methods externally, because they come in a bunch
  10488. // and this way their names minify.
  10489. // Single scalar
  10490. function setValueV1f(gl, v) {
  10491. const cache = this.cache;
  10492. if (cache[0] === v) return;
  10493. gl.uniform1f(this.addr, v);
  10494. cache[0] = v;
  10495. } // Single float vector (from flat array or THREE.VectorN)
  10496. function setValueV2f(gl, v) {
  10497. const cache = this.cache;
  10498. if (v.x !== undefined) {
  10499. if (cache[0] !== v.x || cache[1] !== v.y) {
  10500. gl.uniform2f(this.addr, v.x, v.y);
  10501. cache[0] = v.x;
  10502. cache[1] = v.y;
  10503. }
  10504. } else {
  10505. if (arraysEqual(cache, v)) return;
  10506. gl.uniform2fv(this.addr, v);
  10507. copyArray(cache, v);
  10508. }
  10509. }
  10510. function setValueV3f(gl, v) {
  10511. const cache = this.cache;
  10512. if (v.x !== undefined) {
  10513. if (cache[0] !== v.x || cache[1] !== v.y || cache[2] !== v.z) {
  10514. gl.uniform3f(this.addr, v.x, v.y, v.z);
  10515. cache[0] = v.x;
  10516. cache[1] = v.y;
  10517. cache[2] = v.z;
  10518. }
  10519. } else if (v.r !== undefined) {
  10520. if (cache[0] !== v.r || cache[1] !== v.g || cache[2] !== v.b) {
  10521. gl.uniform3f(this.addr, v.r, v.g, v.b);
  10522. cache[0] = v.r;
  10523. cache[1] = v.g;
  10524. cache[2] = v.b;
  10525. }
  10526. } else {
  10527. if (arraysEqual(cache, v)) return;
  10528. gl.uniform3fv(this.addr, v);
  10529. copyArray(cache, v);
  10530. }
  10531. }
  10532. function setValueV4f(gl, v) {
  10533. const cache = this.cache;
  10534. if (v.x !== undefined) {
  10535. if (cache[0] !== v.x || cache[1] !== v.y || cache[2] !== v.z || cache[3] !== v.w) {
  10536. gl.uniform4f(this.addr, v.x, v.y, v.z, v.w);
  10537. cache[0] = v.x;
  10538. cache[1] = v.y;
  10539. cache[2] = v.z;
  10540. cache[3] = v.w;
  10541. }
  10542. } else {
  10543. if (arraysEqual(cache, v)) return;
  10544. gl.uniform4fv(this.addr, v);
  10545. copyArray(cache, v);
  10546. }
  10547. } // Single matrix (from flat array or MatrixN)
  10548. function setValueM2(gl, v) {
  10549. const cache = this.cache;
  10550. const elements = v.elements;
  10551. if (elements === undefined) {
  10552. if (arraysEqual(cache, v)) return;
  10553. gl.uniformMatrix2fv(this.addr, false, v);
  10554. copyArray(cache, v);
  10555. } else {
  10556. if (arraysEqual(cache, elements)) return;
  10557. mat2array.set(elements);
  10558. gl.uniformMatrix2fv(this.addr, false, mat2array);
  10559. copyArray(cache, elements);
  10560. }
  10561. }
  10562. function setValueM3(gl, v) {
  10563. const cache = this.cache;
  10564. const elements = v.elements;
  10565. if (elements === undefined) {
  10566. if (arraysEqual(cache, v)) return;
  10567. gl.uniformMatrix3fv(this.addr, false, v);
  10568. copyArray(cache, v);
  10569. } else {
  10570. if (arraysEqual(cache, elements)) return;
  10571. mat3array.set(elements);
  10572. gl.uniformMatrix3fv(this.addr, false, mat3array);
  10573. copyArray(cache, elements);
  10574. }
  10575. }
  10576. function setValueM4(gl, v) {
  10577. const cache = this.cache;
  10578. const elements = v.elements;
  10579. if (elements === undefined) {
  10580. if (arraysEqual(cache, v)) return;
  10581. gl.uniformMatrix4fv(this.addr, false, v);
  10582. copyArray(cache, v);
  10583. } else {
  10584. if (arraysEqual(cache, elements)) return;
  10585. mat4array.set(elements);
  10586. gl.uniformMatrix4fv(this.addr, false, mat4array);
  10587. copyArray(cache, elements);
  10588. }
  10589. } // Single texture (2D / Cube)
  10590. function setValueT1(gl, v, textures) {
  10591. const cache = this.cache;
  10592. const unit = textures.allocateTextureUnit();
  10593. if (cache[0] !== unit) {
  10594. gl.uniform1i(this.addr, unit);
  10595. cache[0] = unit;
  10596. }
  10597. textures.safeSetTexture2D(v || emptyTexture, unit);
  10598. }
  10599. function setValueT2DArray1(gl, v, textures) {
  10600. const cache = this.cache;
  10601. const unit = textures.allocateTextureUnit();
  10602. if (cache[0] !== unit) {
  10603. gl.uniform1i(this.addr, unit);
  10604. cache[0] = unit;
  10605. }
  10606. textures.setTexture2DArray(v || emptyTexture2dArray, unit);
  10607. }
  10608. function setValueT3D1(gl, v, textures) {
  10609. const cache = this.cache;
  10610. const unit = textures.allocateTextureUnit();
  10611. if (cache[0] !== unit) {
  10612. gl.uniform1i(this.addr, unit);
  10613. cache[0] = unit;
  10614. }
  10615. textures.setTexture3D(v || emptyTexture3d, unit);
  10616. }
  10617. function setValueT6(gl, v, textures) {
  10618. const cache = this.cache;
  10619. const unit = textures.allocateTextureUnit();
  10620. if (cache[0] !== unit) {
  10621. gl.uniform1i(this.addr, unit);
  10622. cache[0] = unit;
  10623. }
  10624. textures.safeSetTextureCube(v || emptyCubeTexture, unit);
  10625. } // Integer / Boolean vectors or arrays thereof (always flat arrays)
  10626. function setValueV1i(gl, v) {
  10627. const cache = this.cache;
  10628. if (cache[0] === v) return;
  10629. gl.uniform1i(this.addr, v);
  10630. cache[0] = v;
  10631. }
  10632. function setValueV2i(gl, v) {
  10633. const cache = this.cache;
  10634. if (arraysEqual(cache, v)) return;
  10635. gl.uniform2iv(this.addr, v);
  10636. copyArray(cache, v);
  10637. }
  10638. function setValueV3i(gl, v) {
  10639. const cache = this.cache;
  10640. if (arraysEqual(cache, v)) return;
  10641. gl.uniform3iv(this.addr, v);
  10642. copyArray(cache, v);
  10643. }
  10644. function setValueV4i(gl, v) {
  10645. const cache = this.cache;
  10646. if (arraysEqual(cache, v)) return;
  10647. gl.uniform4iv(this.addr, v);
  10648. copyArray(cache, v);
  10649. } // uint
  10650. function setValueV1ui(gl, v) {
  10651. const cache = this.cache;
  10652. if (cache[0] === v) return;
  10653. gl.uniform1ui(this.addr, v);
  10654. cache[0] = v;
  10655. } // Helper to pick the right setter for the singular case
  10656. function getSingularSetter(type) {
  10657. switch (type) {
  10658. case 0x1406:
  10659. return setValueV1f;
  10660. // FLOAT
  10661. case 0x8b50:
  10662. return setValueV2f;
  10663. // _VEC2
  10664. case 0x8b51:
  10665. return setValueV3f;
  10666. // _VEC3
  10667. case 0x8b52:
  10668. return setValueV4f;
  10669. // _VEC4
  10670. case 0x8b5a:
  10671. return setValueM2;
  10672. // _MAT2
  10673. case 0x8b5b:
  10674. return setValueM3;
  10675. // _MAT3
  10676. case 0x8b5c:
  10677. return setValueM4;
  10678. // _MAT4
  10679. case 0x1404:
  10680. case 0x8b56:
  10681. return setValueV1i;
  10682. // INT, BOOL
  10683. case 0x8b53:
  10684. case 0x8b57:
  10685. return setValueV2i;
  10686. // _VEC2
  10687. case 0x8b54:
  10688. case 0x8b58:
  10689. return setValueV3i;
  10690. // _VEC3
  10691. case 0x8b55:
  10692. case 0x8b59:
  10693. return setValueV4i;
  10694. // _VEC4
  10695. case 0x1405:
  10696. return setValueV1ui;
  10697. // UINT
  10698. case 0x8b5e: // SAMPLER_2D
  10699. case 0x8d66: // SAMPLER_EXTERNAL_OES
  10700. case 0x8dca: // INT_SAMPLER_2D
  10701. case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
  10702. case 0x8b62:
  10703. // SAMPLER_2D_SHADOW
  10704. return setValueT1;
  10705. case 0x8b5f: // SAMPLER_3D
  10706. case 0x8dcb: // INT_SAMPLER_3D
  10707. case 0x8dd3:
  10708. // UNSIGNED_INT_SAMPLER_3D
  10709. return setValueT3D1;
  10710. case 0x8b60: // SAMPLER_CUBE
  10711. case 0x8dcc: // INT_SAMPLER_CUBE
  10712. case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
  10713. case 0x8dc5:
  10714. // SAMPLER_CUBE_SHADOW
  10715. return setValueT6;
  10716. case 0x8dc1: // SAMPLER_2D_ARRAY
  10717. case 0x8dcf: // INT_SAMPLER_2D_ARRAY
  10718. case 0x8dd7: // UNSIGNED_INT_SAMPLER_2D_ARRAY
  10719. case 0x8dc4:
  10720. // SAMPLER_2D_ARRAY_SHADOW
  10721. return setValueT2DArray1;
  10722. }
  10723. } // Array of scalars
  10724. function setValueV1fArray(gl, v) {
  10725. gl.uniform1fv(this.addr, v);
  10726. } // Integer / Boolean vectors or arrays thereof (always flat arrays)
  10727. function setValueV1iArray(gl, v) {
  10728. gl.uniform1iv(this.addr, v);
  10729. }
  10730. function setValueV2iArray(gl, v) {
  10731. gl.uniform2iv(this.addr, v);
  10732. }
  10733. function setValueV3iArray(gl, v) {
  10734. gl.uniform3iv(this.addr, v);
  10735. }
  10736. function setValueV4iArray(gl, v) {
  10737. gl.uniform4iv(this.addr, v);
  10738. } // Array of vectors (flat or from THREE classes)
  10739. function setValueV2fArray(gl, v) {
  10740. const data = flatten(v, this.size, 2);
  10741. gl.uniform2fv(this.addr, data);
  10742. }
  10743. function setValueV3fArray(gl, v) {
  10744. const data = flatten(v, this.size, 3);
  10745. gl.uniform3fv(this.addr, data);
  10746. }
  10747. function setValueV4fArray(gl, v) {
  10748. const data = flatten(v, this.size, 4);
  10749. gl.uniform4fv(this.addr, data);
  10750. } // Array of matrices (flat or from THREE clases)
  10751. function setValueM2Array(gl, v) {
  10752. const data = flatten(v, this.size, 4);
  10753. gl.uniformMatrix2fv(this.addr, false, data);
  10754. }
  10755. function setValueM3Array(gl, v) {
  10756. const data = flatten(v, this.size, 9);
  10757. gl.uniformMatrix3fv(this.addr, false, data);
  10758. }
  10759. function setValueM4Array(gl, v) {
  10760. const data = flatten(v, this.size, 16);
  10761. gl.uniformMatrix4fv(this.addr, false, data);
  10762. } // Array of textures (2D / Cube)
  10763. function setValueT1Array(gl, v, textures) {
  10764. const n = v.length;
  10765. const units = allocTexUnits(textures, n);
  10766. gl.uniform1iv(this.addr, units);
  10767. for (let i = 0; i !== n; ++i) {
  10768. textures.safeSetTexture2D(v[i] || emptyTexture, units[i]);
  10769. }
  10770. }
  10771. function setValueT6Array(gl, v, textures) {
  10772. const n = v.length;
  10773. const units = allocTexUnits(textures, n);
  10774. gl.uniform1iv(this.addr, units);
  10775. for (let i = 0; i !== n; ++i) {
  10776. textures.safeSetTextureCube(v[i] || emptyCubeTexture, units[i]);
  10777. }
  10778. } // Helper to pick the right setter for a pure (bottom-level) array
  10779. function getPureArraySetter(type) {
  10780. switch (type) {
  10781. case 0x1406:
  10782. return setValueV1fArray;
  10783. // FLOAT
  10784. case 0x8b50:
  10785. return setValueV2fArray;
  10786. // _VEC2
  10787. case 0x8b51:
  10788. return setValueV3fArray;
  10789. // _VEC3
  10790. case 0x8b52:
  10791. return setValueV4fArray;
  10792. // _VEC4
  10793. case 0x8b5a:
  10794. return setValueM2Array;
  10795. // _MAT2
  10796. case 0x8b5b:
  10797. return setValueM3Array;
  10798. // _MAT3
  10799. case 0x8b5c:
  10800. return setValueM4Array;
  10801. // _MAT4
  10802. case 0x1404:
  10803. case 0x8b56:
  10804. return setValueV1iArray;
  10805. // INT, BOOL
  10806. case 0x8b53:
  10807. case 0x8b57:
  10808. return setValueV2iArray;
  10809. // _VEC2
  10810. case 0x8b54:
  10811. case 0x8b58:
  10812. return setValueV3iArray;
  10813. // _VEC3
  10814. case 0x8b55:
  10815. case 0x8b59:
  10816. return setValueV4iArray;
  10817. // _VEC4
  10818. case 0x8b5e: // SAMPLER_2D
  10819. case 0x8d66: // SAMPLER_EXTERNAL_OES
  10820. case 0x8dca: // INT_SAMPLER_2D
  10821. case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
  10822. case 0x8b62:
  10823. // SAMPLER_2D_SHADOW
  10824. return setValueT1Array;
  10825. case 0x8b60: // SAMPLER_CUBE
  10826. case 0x8dcc: // INT_SAMPLER_CUBE
  10827. case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
  10828. case 0x8dc5:
  10829. // SAMPLER_CUBE_SHADOW
  10830. return setValueT6Array;
  10831. }
  10832. } // --- Uniform Classes ---
  10833. function SingleUniform(id, activeInfo, addr) {
  10834. this.id = id;
  10835. this.addr = addr;
  10836. this.cache = [];
  10837. this.setValue = getSingularSetter(activeInfo.type); // this.path = activeInfo.name; // DEBUG
  10838. }
  10839. function PureArrayUniform(id, activeInfo, addr) {
  10840. this.id = id;
  10841. this.addr = addr;
  10842. this.cache = [];
  10843. this.size = activeInfo.size;
  10844. this.setValue = getPureArraySetter(activeInfo.type); // this.path = activeInfo.name; // DEBUG
  10845. }
  10846. PureArrayUniform.prototype.updateCache = function (data) {
  10847. const cache = this.cache;
  10848. if (data instanceof Float32Array && cache.length !== data.length) {
  10849. this.cache = new Float32Array(data.length);
  10850. }
  10851. copyArray(cache, data);
  10852. };
  10853. function StructuredUniform(id) {
  10854. this.id = id;
  10855. this.seq = [];
  10856. this.map = {};
  10857. }
  10858. StructuredUniform.prototype.setValue = function (gl, value, textures) {
  10859. const seq = this.seq;
  10860. for (let i = 0, n = seq.length; i !== n; ++i) {
  10861. const u = seq[i];
  10862. u.setValue(gl, value[u.id], textures);
  10863. }
  10864. }; // --- Top-level ---
  10865. // Parser - builds up the property tree from the path strings
  10866. const RePathPart = /([\w\d_]+)(\])?(\[|\.)?/g; // extracts
  10867. // - the identifier (member name or array index)
  10868. // - followed by an optional right bracket (found when array index)
  10869. // - followed by an optional left bracket or dot (type of subscript)
  10870. //
  10871. // Note: These portions can be read in a non-overlapping fashion and
  10872. // allow straightforward parsing of the hierarchy that WebGL encodes
  10873. // in the uniform names.
  10874. function addUniform(container, uniformObject) {
  10875. container.seq.push(uniformObject);
  10876. container.map[uniformObject.id] = uniformObject;
  10877. }
  10878. function parseUniform(activeInfo, addr, container) {
  10879. const path = activeInfo.name,
  10880. pathLength = path.length; // reset RegExp object, because of the early exit of a previous run
  10881. RePathPart.lastIndex = 0;
  10882. while (true) {
  10883. const match = RePathPart.exec(path),
  10884. matchEnd = RePathPart.lastIndex;
  10885. let id = match[1];
  10886. const idIsIndex = match[2] === ']',
  10887. subscript = match[3];
  10888. if (idIsIndex) id = id | 0; // convert to integer
  10889. if (subscript === undefined || subscript === '[' && matchEnd + 2 === pathLength) {
  10890. // bare name or "pure" bottom-level array "[0]" suffix
  10891. addUniform(container, subscript === undefined ? new SingleUniform(id, activeInfo, addr) : new PureArrayUniform(id, activeInfo, addr));
  10892. break;
  10893. } else {
  10894. // step into inner node / create it in case it doesn't exist
  10895. const map = container.map;
  10896. let next = map[id];
  10897. if (next === undefined) {
  10898. next = new StructuredUniform(id);
  10899. addUniform(container, next);
  10900. }
  10901. container = next;
  10902. }
  10903. }
  10904. } // Root Container
  10905. function WebGLUniforms(gl, program) {
  10906. this.seq = [];
  10907. this.map = {};
  10908. const n = gl.getProgramParameter(program, 35718);
  10909. for (let i = 0; i < n; ++i) {
  10910. const info = gl.getActiveUniform(program, i),
  10911. addr = gl.getUniformLocation(program, info.name);
  10912. parseUniform(info, addr, this);
  10913. }
  10914. }
  10915. WebGLUniforms.prototype.setValue = function (gl, name, value, textures) {
  10916. const u = this.map[name];
  10917. if (u !== undefined) u.setValue(gl, value, textures);
  10918. };
  10919. WebGLUniforms.prototype.setOptional = function (gl, object, name) {
  10920. const v = object[name];
  10921. if (v !== undefined) this.setValue(gl, name, v);
  10922. }; // Static interface
  10923. WebGLUniforms.upload = function (gl, seq, values, textures) {
  10924. for (let i = 0, n = seq.length; i !== n; ++i) {
  10925. const u = seq[i],
  10926. v = values[u.id];
  10927. if (v.needsUpdate !== false) {
  10928. // note: always updating when .needsUpdate is undefined
  10929. u.setValue(gl, v.value, textures);
  10930. }
  10931. }
  10932. };
  10933. WebGLUniforms.seqWithValue = function (seq, values) {
  10934. const r = [];
  10935. for (let i = 0, n = seq.length; i !== n; ++i) {
  10936. const u = seq[i];
  10937. if (u.id in values) r.push(u);
  10938. }
  10939. return r;
  10940. };
  10941. function WebGLShader(gl, type, string) {
  10942. const shader = gl.createShader(type);
  10943. gl.shaderSource(shader, string);
  10944. gl.compileShader(shader);
  10945. return shader;
  10946. }
  10947. let programIdCount = 0;
  10948. function addLineNumbers(string) {
  10949. const lines = string.split('\n');
  10950. for (let i = 0; i < lines.length; i++) {
  10951. lines[i] = i + 1 + ': ' + lines[i];
  10952. }
  10953. return lines.join('\n');
  10954. }
  10955. function getEncodingComponents(encoding) {
  10956. switch (encoding) {
  10957. case LinearEncoding:
  10958. return ['Linear', '( value )'];
  10959. case sRGBEncoding:
  10960. return ['sRGB', '( value )'];
  10961. case RGBEEncoding:
  10962. return ['RGBE', '( value )'];
  10963. case RGBM7Encoding:
  10964. return ['RGBM', '( value, 7.0 )'];
  10965. case RGBM16Encoding:
  10966. return ['RGBM', '( value, 16.0 )'];
  10967. case RGBDEncoding:
  10968. return ['RGBD', '( value, 256.0 )'];
  10969. case GammaEncoding:
  10970. return ['Gamma', '( value, float( GAMMA_FACTOR ) )'];
  10971. case LogLuvEncoding:
  10972. return ['LogLuv', '( value )'];
  10973. default:
  10974. console.warn('THREE.WebGLProgram: Unsupported encoding:', encoding);
  10975. return ['Linear', '( value )'];
  10976. }
  10977. }
  10978. function getShaderErrors(gl, shader, type) {
  10979. const status = gl.getShaderParameter(shader, 35713);
  10980. const log = gl.getShaderInfoLog(shader).trim();
  10981. if (status && log === '') return ''; // --enable-privileged-webgl-extension
  10982. // console.log( '**' + type + '**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) );
  10983. const source = gl.getShaderSource(shader);
  10984. return 'THREE.WebGLShader: gl.getShaderInfoLog() ' + type + '\n' + log + addLineNumbers(source);
  10985. }
  10986. function getTexelDecodingFunction(functionName, encoding) {
  10987. const components = getEncodingComponents(encoding);
  10988. return 'vec4 ' + functionName + '( vec4 value ) { return ' + components[0] + 'ToLinear' + components[1] + '; }';
  10989. }
  10990. function getTexelEncodingFunction(functionName, encoding) {
  10991. const components = getEncodingComponents(encoding);
  10992. return 'vec4 ' + functionName + '( vec4 value ) { return LinearTo' + components[0] + components[1] + '; }';
  10993. }
  10994. function getToneMappingFunction(functionName, toneMapping) {
  10995. let toneMappingName;
  10996. switch (toneMapping) {
  10997. case LinearToneMapping:
  10998. toneMappingName = 'Linear';
  10999. break;
  11000. case ReinhardToneMapping:
  11001. toneMappingName = 'Reinhard';
  11002. break;
  11003. case CineonToneMapping:
  11004. toneMappingName = 'OptimizedCineon';
  11005. break;
  11006. case ACESFilmicToneMapping:
  11007. toneMappingName = 'ACESFilmic';
  11008. break;
  11009. case CustomToneMapping:
  11010. toneMappingName = 'Custom';
  11011. break;
  11012. default:
  11013. console.warn('THREE.WebGLProgram: Unsupported toneMapping:', toneMapping);
  11014. toneMappingName = 'Linear';
  11015. }
  11016. return 'vec3 ' + functionName + '( vec3 color ) { return ' + toneMappingName + 'ToneMapping( color ); }';
  11017. }
  11018. function generateExtensions(parameters) {
  11019. const chunks = [parameters.extensionDerivatives || parameters.envMapCubeUV || parameters.bumpMap || parameters.tangentSpaceNormalMap || parameters.clearcoatNormalMap || parameters.flatShading || parameters.shaderID === 'physical' ? '#extension GL_OES_standard_derivatives : enable' : '', (parameters.extensionFragDepth || parameters.logarithmicDepthBuffer) && parameters.rendererExtensionFragDepth ? '#extension GL_EXT_frag_depth : enable' : '', parameters.extensionDrawBuffers && parameters.rendererExtensionDrawBuffers ? '#extension GL_EXT_draw_buffers : require' : '', (parameters.extensionShaderTextureLOD || parameters.envMap) && parameters.rendererExtensionShaderTextureLod ? '#extension GL_EXT_shader_texture_lod : enable' : ''];
  11020. return chunks.filter(filterEmptyLine).join('\n');
  11021. }
  11022. function generateDefines(defines) {
  11023. const chunks = [];
  11024. for (const name in defines) {
  11025. const value = defines[name];
  11026. if (value === false) continue;
  11027. chunks.push('#define ' + name + ' ' + value);
  11028. }
  11029. return chunks.join('\n');
  11030. }
  11031. function fetchAttributeLocations(gl, program) {
  11032. const attributes = {};
  11033. const n = gl.getProgramParameter(program, 35721);
  11034. for (let i = 0; i < n; i++) {
  11035. const info = gl.getActiveAttrib(program, i);
  11036. const name = info.name; // console.log( 'THREE.WebGLProgram: ACTIVE VERTEX ATTRIBUTE:', name, i );
  11037. attributes[name] = gl.getAttribLocation(program, name);
  11038. }
  11039. return attributes;
  11040. }
  11041. function filterEmptyLine(string) {
  11042. return string !== '';
  11043. }
  11044. function replaceLightNums(string, parameters) {
  11045. return string.replace(/NUM_DIR_LIGHTS/g, parameters.numDirLights).replace(/NUM_SPOT_LIGHTS/g, parameters.numSpotLights).replace(/NUM_RECT_AREA_LIGHTS/g, parameters.numRectAreaLights).replace(/NUM_POINT_LIGHTS/g, parameters.numPointLights).replace(/NUM_HEMI_LIGHTS/g, parameters.numHemiLights).replace(/NUM_DIR_LIGHT_SHADOWS/g, parameters.numDirLightShadows).replace(/NUM_SPOT_LIGHT_SHADOWS/g, parameters.numSpotLightShadows).replace(/NUM_POINT_LIGHT_SHADOWS/g, parameters.numPointLightShadows);
  11046. }
  11047. function replaceClippingPlaneNums(string, parameters) {
  11048. return string.replace(/NUM_CLIPPING_PLANES/g, parameters.numClippingPlanes).replace(/UNION_CLIPPING_PLANES/g, parameters.numClippingPlanes - parameters.numClipIntersection);
  11049. } // Resolve Includes
  11050. const includePattern = /^[ \t]*#include +<([\w\d./]+)>/gm;
  11051. function resolveIncludes(string) {
  11052. return string.replace(includePattern, includeReplacer);
  11053. }
  11054. function includeReplacer(match, include) {
  11055. const string = ShaderChunk[include];
  11056. if (string === undefined) {
  11057. throw new Error('Can not resolve #include <' + include + '>');
  11058. }
  11059. return resolveIncludes(string);
  11060. } // Unroll Loops
  11061. const deprecatedUnrollLoopPattern = /#pragma unroll_loop[\s]+?for \( int i \= (\d+)\; i < (\d+)\; i \+\+ \) \{([\s\S]+?)(?=\})\}/g;
  11062. const unrollLoopPattern = /#pragma unroll_loop_start\s+for\s*\(\s*int\s+i\s*=\s*(\d+)\s*;\s*i\s*<\s*(\d+)\s*;\s*i\s*\+\+\s*\)\s*{([\s\S]+?)}\s+#pragma unroll_loop_end/g;
  11063. function unrollLoops(string) {
  11064. return string.replace(unrollLoopPattern, loopReplacer).replace(deprecatedUnrollLoopPattern, deprecatedLoopReplacer);
  11065. }
  11066. function deprecatedLoopReplacer(match, start, end, snippet) {
  11067. console.warn('WebGLProgram: #pragma unroll_loop shader syntax is deprecated. Please use #pragma unroll_loop_start syntax instead.');
  11068. return loopReplacer(match, start, end, snippet);
  11069. }
  11070. function loopReplacer(match, start, end, snippet) {
  11071. let string = '';
  11072. for (let i = parseInt(start); i < parseInt(end); i++) {
  11073. string += snippet.replace(/\[\s*i\s*\]/g, '[ ' + i + ' ]').replace(/UNROLLED_LOOP_INDEX/g, i);
  11074. }
  11075. return string;
  11076. } //
  11077. function generatePrecision(parameters) {
  11078. let precisionstring = "precision " + parameters.precision + " float;\nprecision " + parameters.precision + " int;";
  11079. if (parameters.precision === "highp") {
  11080. precisionstring += "\n#define HIGH_PRECISION";
  11081. } else if (parameters.precision === "mediump") {
  11082. precisionstring += "\n#define MEDIUM_PRECISION";
  11083. } else if (parameters.precision === "lowp") {
  11084. precisionstring += "\n#define LOW_PRECISION";
  11085. }
  11086. return precisionstring;
  11087. }
  11088. function generateShadowMapTypeDefine(parameters) {
  11089. let shadowMapTypeDefine = 'SHADOWMAP_TYPE_BASIC';
  11090. if (parameters.shadowMapType === PCFShadowMap) {
  11091. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF';
  11092. } else if (parameters.shadowMapType === PCFSoftShadowMap) {
  11093. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF_SOFT';
  11094. } else if (parameters.shadowMapType === VSMShadowMap) {
  11095. shadowMapTypeDefine = 'SHADOWMAP_TYPE_VSM';
  11096. }
  11097. return shadowMapTypeDefine;
  11098. }
  11099. function generateEnvMapTypeDefine(parameters) {
  11100. let envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  11101. if (parameters.envMap) {
  11102. switch (parameters.envMapMode) {
  11103. case CubeReflectionMapping:
  11104. case CubeRefractionMapping:
  11105. envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  11106. break;
  11107. case CubeUVReflectionMapping:
  11108. case CubeUVRefractionMapping:
  11109. envMapTypeDefine = 'ENVMAP_TYPE_CUBE_UV';
  11110. break;
  11111. }
  11112. }
  11113. return envMapTypeDefine;
  11114. }
  11115. function generateEnvMapModeDefine(parameters) {
  11116. let envMapModeDefine = 'ENVMAP_MODE_REFLECTION';
  11117. if (parameters.envMap) {
  11118. switch (parameters.envMapMode) {
  11119. case CubeRefractionMapping:
  11120. case CubeUVRefractionMapping:
  11121. envMapModeDefine = 'ENVMAP_MODE_REFRACTION';
  11122. break;
  11123. }
  11124. }
  11125. return envMapModeDefine;
  11126. }
  11127. function generateEnvMapBlendingDefine(parameters) {
  11128. let envMapBlendingDefine = 'ENVMAP_BLENDING_NONE';
  11129. if (parameters.envMap) {
  11130. switch (parameters.combine) {
  11131. case MultiplyOperation:
  11132. envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  11133. break;
  11134. case MixOperation:
  11135. envMapBlendingDefine = 'ENVMAP_BLENDING_MIX';
  11136. break;
  11137. case AddOperation:
  11138. envMapBlendingDefine = 'ENVMAP_BLENDING_ADD';
  11139. break;
  11140. }
  11141. }
  11142. return envMapBlendingDefine;
  11143. }
  11144. function WebGLProgram(renderer, cacheKey, parameters, bindingStates) {
  11145. const gl = renderer.getContext();
  11146. const defines = parameters.defines;
  11147. let vertexShader = parameters.vertexShader;
  11148. let fragmentShader = parameters.fragmentShader;
  11149. const shadowMapTypeDefine = generateShadowMapTypeDefine(parameters);
  11150. const envMapTypeDefine = generateEnvMapTypeDefine(parameters);
  11151. const envMapModeDefine = generateEnvMapModeDefine(parameters);
  11152. const envMapBlendingDefine = generateEnvMapBlendingDefine(parameters);
  11153. const gammaFactorDefine = renderer.gammaFactor > 0 ? renderer.gammaFactor : 1.0;
  11154. const customExtensions = parameters.isWebGL2 ? '' : generateExtensions(parameters);
  11155. const customDefines = generateDefines(defines);
  11156. const program = gl.createProgram();
  11157. let prefixVertex, prefixFragment;
  11158. let versionString = parameters.glslVersion ? '#version ' + parameters.glslVersion + "\n" : '';
  11159. if (parameters.isRawShaderMaterial) {
  11160. prefixVertex = [customDefines].filter(filterEmptyLine).join('\n');
  11161. if (prefixVertex.length > 0) {
  11162. prefixVertex += '\n';
  11163. }
  11164. prefixFragment = [customExtensions, customDefines].filter(filterEmptyLine).join('\n');
  11165. if (prefixFragment.length > 0) {
  11166. prefixFragment += '\n';
  11167. }
  11168. } else {
  11169. prefixVertex = [generatePrecision(parameters), '#define SHADER_NAME ' + parameters.shaderName, customDefines, parameters.instancing ? '#define USE_INSTANCING' : '', parameters.instancingColor ? '#define USE_INSTANCING_COLOR' : '', parameters.supportsVertexTextures ? '#define VERTEX_TEXTURES' : '', '#define GAMMA_FACTOR ' + gammaFactorDefine, '#define MAX_BONES ' + parameters.maxBones, parameters.useFog && parameters.fog ? '#define USE_FOG' : '', parameters.useFog && parameters.fogExp2 ? '#define FOG_EXP2' : '', parameters.map ? '#define USE_MAP' : '', parameters.envMap ? '#define USE_ENVMAP' : '', parameters.envMap ? '#define ' + envMapModeDefine : '', parameters.lightMap ? '#define USE_LIGHTMAP' : '', parameters.aoMap ? '#define USE_AOMAP' : '', parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '', parameters.bumpMap ? '#define USE_BUMPMAP' : '', parameters.normalMap ? '#define USE_NORMALMAP' : '', parameters.normalMap && parameters.objectSpaceNormalMap ? '#define OBJECTSPACE_NORMALMAP' : '', parameters.normalMap && parameters.tangentSpaceNormalMap ? '#define TANGENTSPACE_NORMALMAP' : '', parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '', parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '', parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '', parameters.displacementMap && parameters.supportsVertexTextures ? '#define USE_DISPLACEMENTMAP' : '', parameters.specularMap ? '#define USE_SPECULARMAP' : '', parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '', parameters.metalnessMap ? '#define USE_METALNESSMAP' : '', parameters.alphaMap ? '#define USE_ALPHAMAP' : '', parameters.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '', parameters.vertexTangents ? '#define USE_TANGENT' : '', parameters.vertexColors ? '#define USE_COLOR' : '', parameters.vertexUvs ? '#define USE_UV' : '', parameters.uvsVertexOnly ? '#define UVS_VERTEX_ONLY' : '', parameters.flatShading ? '#define FLAT_SHADED' : '', parameters.skinning ? '#define USE_SKINNING' : '', parameters.useVertexTexture ? '#define BONE_TEXTURE' : '', parameters.morphTargets ? '#define USE_MORPHTARGETS' : '', parameters.morphNormals && parameters.flatShading === false ? '#define USE_MORPHNORMALS' : '', parameters.doubleSided ? '#define DOUBLE_SIDED' : '', parameters.flipSided ? '#define FLIP_SIDED' : '', parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '', parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '', parameters.sizeAttenuation ? '#define USE_SIZEATTENUATION' : '', parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '', parameters.logarithmicDepthBuffer && parameters.rendererExtensionFragDepth ? '#define USE_LOGDEPTHBUF_EXT' : '', 'uniform mat4 modelMatrix;', 'uniform mat4 modelViewMatrix;', 'uniform mat4 projectionMatrix;', 'uniform mat4 viewMatrix;', 'uniform mat3 normalMatrix;', 'uniform vec3 cameraPosition;', 'uniform bool isOrthographic;', '#ifdef USE_INSTANCING', ' attribute mat4 instanceMatrix;', '#endif', '#ifdef USE_INSTANCING_COLOR', ' attribute vec3 instanceColor;', '#endif', 'attribute vec3 position;', 'attribute vec3 normal;', 'attribute vec2 uv;', '#ifdef USE_TANGENT', ' attribute vec4 tangent;', '#endif', '#ifdef USE_COLOR', ' attribute vec3 color;', '#endif', '#ifdef USE_MORPHTARGETS', ' attribute vec3 morphTarget0;', ' attribute vec3 morphTarget1;', ' attribute vec3 morphTarget2;', ' attribute vec3 morphTarget3;', ' #ifdef USE_MORPHNORMALS', ' attribute vec3 morphNormal0;', ' attribute vec3 morphNormal1;', ' attribute vec3 morphNormal2;', ' attribute vec3 morphNormal3;', ' #else', ' attribute vec3 morphTarget4;', ' attribute vec3 morphTarget5;', ' attribute vec3 morphTarget6;', ' attribute vec3 morphTarget7;', ' #endif', '#endif', '#ifdef USE_SKINNING', ' attribute vec4 skinIndex;', ' attribute vec4 skinWeight;', '#endif', '\n'].filter(filterEmptyLine).join('\n');
  11170. prefixFragment = [customExtensions, generatePrecision(parameters), '#define SHADER_NAME ' + parameters.shaderName, customDefines, parameters.alphaTest ? '#define ALPHATEST ' + parameters.alphaTest + (parameters.alphaTest % 1 ? '' : '.0') : '', // add '.0' if integer
  11171. '#define GAMMA_FACTOR ' + gammaFactorDefine, parameters.useFog && parameters.fog ? '#define USE_FOG' : '', parameters.useFog && parameters.fogExp2 ? '#define FOG_EXP2' : '', parameters.map ? '#define USE_MAP' : '', parameters.matcap ? '#define USE_MATCAP' : '', parameters.envMap ? '#define USE_ENVMAP' : '', parameters.envMap ? '#define ' + envMapTypeDefine : '', parameters.envMap ? '#define ' + envMapModeDefine : '', parameters.envMap ? '#define ' + envMapBlendingDefine : '', parameters.lightMap ? '#define USE_LIGHTMAP' : '', parameters.aoMap ? '#define USE_AOMAP' : '', parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '', parameters.bumpMap ? '#define USE_BUMPMAP' : '', parameters.normalMap ? '#define USE_NORMALMAP' : '', parameters.normalMap && parameters.objectSpaceNormalMap ? '#define OBJECTSPACE_NORMALMAP' : '', parameters.normalMap && parameters.tangentSpaceNormalMap ? '#define TANGENTSPACE_NORMALMAP' : '', parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '', parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '', parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '', parameters.specularMap ? '#define USE_SPECULARMAP' : '', parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '', parameters.metalnessMap ? '#define USE_METALNESSMAP' : '', parameters.alphaMap ? '#define USE_ALPHAMAP' : '', parameters.sheen ? '#define USE_SHEEN' : '', parameters.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '', parameters.vertexTangents ? '#define USE_TANGENT' : '', parameters.vertexColors || parameters.instancingColor ? '#define USE_COLOR' : '', parameters.vertexUvs ? '#define USE_UV' : '', parameters.uvsVertexOnly ? '#define UVS_VERTEX_ONLY' : '', parameters.gradientMap ? '#define USE_GRADIENTMAP' : '', parameters.flatShading ? '#define FLAT_SHADED' : '', parameters.doubleSided ? '#define DOUBLE_SIDED' : '', parameters.flipSided ? '#define FLIP_SIDED' : '', parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '', parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '', parameters.premultipliedAlpha ? '#define PREMULTIPLIED_ALPHA' : '', parameters.physicallyCorrectLights ? '#define PHYSICALLY_CORRECT_LIGHTS' : '', parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '', parameters.logarithmicDepthBuffer && parameters.rendererExtensionFragDepth ? '#define USE_LOGDEPTHBUF_EXT' : '', (parameters.extensionShaderTextureLOD || parameters.envMap) && parameters.rendererExtensionShaderTextureLod ? '#define TEXTURE_LOD_EXT' : '', 'uniform mat4 viewMatrix;', 'uniform vec3 cameraPosition;', 'uniform bool isOrthographic;', parameters.toneMapping !== NoToneMapping ? '#define TONE_MAPPING' : '', parameters.toneMapping !== NoToneMapping ? ShaderChunk['tonemapping_pars_fragment'] : '', // this code is required here because it is used by the toneMapping() function defined below
  11172. parameters.toneMapping !== NoToneMapping ? getToneMappingFunction('toneMapping', parameters.toneMapping) : '', parameters.dithering ? '#define DITHERING' : '', ShaderChunk['encodings_pars_fragment'], // this code is required here because it is used by the various encoding/decoding function defined below
  11173. parameters.map ? getTexelDecodingFunction('mapTexelToLinear', parameters.mapEncoding) : '', parameters.matcap ? getTexelDecodingFunction('matcapTexelToLinear', parameters.matcapEncoding) : '', parameters.envMap ? getTexelDecodingFunction('envMapTexelToLinear', parameters.envMapEncoding) : '', parameters.emissiveMap ? getTexelDecodingFunction('emissiveMapTexelToLinear', parameters.emissiveMapEncoding) : '', parameters.lightMap ? getTexelDecodingFunction('lightMapTexelToLinear', parameters.lightMapEncoding) : '', getTexelEncodingFunction('linearToOutputTexel', parameters.outputEncoding), parameters.depthPacking ? '#define DEPTH_PACKING ' + parameters.depthPacking : '', '\n'].filter(filterEmptyLine).join('\n');
  11174. }
  11175. vertexShader = resolveIncludes(vertexShader);
  11176. vertexShader = replaceLightNums(vertexShader, parameters);
  11177. vertexShader = replaceClippingPlaneNums(vertexShader, parameters);
  11178. fragmentShader = resolveIncludes(fragmentShader);
  11179. fragmentShader = replaceLightNums(fragmentShader, parameters);
  11180. fragmentShader = replaceClippingPlaneNums(fragmentShader, parameters);
  11181. vertexShader = unrollLoops(vertexShader);
  11182. fragmentShader = unrollLoops(fragmentShader);
  11183. if (parameters.isWebGL2 && parameters.isRawShaderMaterial !== true) {
  11184. // GLSL 3.0 conversion for built-in materials and ShaderMaterial
  11185. versionString = '#version 300 es\n';
  11186. prefixVertex = ['#define attribute in', '#define varying out', '#define texture2D texture'].join('\n') + '\n' + prefixVertex;
  11187. prefixFragment = ['#define varying in', parameters.glslVersion === GLSL3 ? '' : 'out highp vec4 pc_fragColor;', parameters.glslVersion === GLSL3 ? '' : '#define gl_FragColor pc_fragColor', '#define gl_FragDepthEXT gl_FragDepth', '#define texture2D texture', '#define textureCube texture', '#define texture2DProj textureProj', '#define texture2DLodEXT textureLod', '#define texture2DProjLodEXT textureProjLod', '#define textureCubeLodEXT textureLod', '#define texture2DGradEXT textureGrad', '#define texture2DProjGradEXT textureProjGrad', '#define textureCubeGradEXT textureGrad'].join('\n') + '\n' + prefixFragment;
  11188. }
  11189. const vertexGlsl = versionString + prefixVertex + vertexShader;
  11190. const fragmentGlsl = versionString + prefixFragment + fragmentShader; // console.log( '*VERTEX*', vertexGlsl );
  11191. // console.log( '*FRAGMENT*', fragmentGlsl );
  11192. const glVertexShader = WebGLShader(gl, 35633, vertexGlsl);
  11193. const glFragmentShader = WebGLShader(gl, 35632, fragmentGlsl);
  11194. gl.attachShader(program, glVertexShader);
  11195. gl.attachShader(program, glFragmentShader); // Force a particular attribute to index 0.
  11196. if (parameters.index0AttributeName !== undefined) {
  11197. gl.bindAttribLocation(program, 0, parameters.index0AttributeName);
  11198. } else if (parameters.morphTargets === true) {
  11199. // programs with morphTargets displace position out of attribute 0
  11200. gl.bindAttribLocation(program, 0, 'position');
  11201. }
  11202. gl.linkProgram(program); // check for link errors
  11203. if (renderer.debug.checkShaderErrors) {
  11204. const programLog = gl.getProgramInfoLog(program).trim();
  11205. const vertexLog = gl.getShaderInfoLog(glVertexShader).trim();
  11206. const fragmentLog = gl.getShaderInfoLog(glFragmentShader).trim();
  11207. let runnable = true;
  11208. let haveDiagnostics = true;
  11209. if (gl.getProgramParameter(program, 35714) === false) {
  11210. runnable = false;
  11211. const vertexErrors = getShaderErrors(gl, glVertexShader, 'vertex');
  11212. const fragmentErrors = getShaderErrors(gl, glFragmentShader, 'fragment');
  11213. console.error('THREE.WebGLProgram: shader error: ', gl.getError(), '35715', gl.getProgramParameter(program, 35715), 'gl.getProgramInfoLog', programLog, vertexErrors, fragmentErrors);
  11214. } else if (programLog !== '') {
  11215. console.warn('THREE.WebGLProgram: gl.getProgramInfoLog()', programLog);
  11216. } else if (vertexLog === '' || fragmentLog === '') {
  11217. haveDiagnostics = false;
  11218. }
  11219. if (haveDiagnostics) {
  11220. this.diagnostics = {
  11221. runnable: runnable,
  11222. programLog: programLog,
  11223. vertexShader: {
  11224. log: vertexLog,
  11225. prefix: prefixVertex
  11226. },
  11227. fragmentShader: {
  11228. log: fragmentLog,
  11229. prefix: prefixFragment
  11230. }
  11231. };
  11232. }
  11233. } // Clean up
  11234. // Crashes in iOS9 and iOS10. #18402
  11235. // gl.detachShader( program, glVertexShader );
  11236. // gl.detachShader( program, glFragmentShader );
  11237. gl.deleteShader(glVertexShader);
  11238. gl.deleteShader(glFragmentShader); // set up caching for uniform locations
  11239. let cachedUniforms;
  11240. this.getUniforms = function () {
  11241. if (cachedUniforms === undefined) {
  11242. cachedUniforms = new WebGLUniforms(gl, program);
  11243. }
  11244. return cachedUniforms;
  11245. }; // set up caching for attribute locations
  11246. let cachedAttributes;
  11247. this.getAttributes = function () {
  11248. if (cachedAttributes === undefined) {
  11249. cachedAttributes = fetchAttributeLocations(gl, program);
  11250. }
  11251. return cachedAttributes;
  11252. }; // free resource
  11253. this.destroy = function () {
  11254. bindingStates.releaseStatesOfProgram(this);
  11255. gl.deleteProgram(program);
  11256. this.program = undefined;
  11257. }; //
  11258. this.name = parameters.shaderName;
  11259. this.id = programIdCount++;
  11260. this.cacheKey = cacheKey;
  11261. this.usedTimes = 1;
  11262. this.program = program;
  11263. this.vertexShader = glVertexShader;
  11264. this.fragmentShader = glFragmentShader;
  11265. return this;
  11266. }
  11267. function WebGLPrograms(renderer, cubemaps, extensions, capabilities, bindingStates, clipping) {
  11268. const programs = [];
  11269. const isWebGL2 = capabilities.isWebGL2;
  11270. const logarithmicDepthBuffer = capabilities.logarithmicDepthBuffer;
  11271. const floatVertexTextures = capabilities.floatVertexTextures;
  11272. const maxVertexUniforms = capabilities.maxVertexUniforms;
  11273. const vertexTextures = capabilities.vertexTextures;
  11274. let precision = capabilities.precision;
  11275. const shaderIDs = {
  11276. MeshDepthMaterial: 'depth',
  11277. MeshDistanceMaterial: 'distanceRGBA',
  11278. MeshNormalMaterial: 'normal',
  11279. MeshBasicMaterial: 'basic',
  11280. MeshLambertMaterial: 'lambert',
  11281. MeshPhongMaterial: 'phong',
  11282. MeshToonMaterial: 'toon',
  11283. MeshStandardMaterial: 'physical',
  11284. MeshPhysicalMaterial: 'physical',
  11285. MeshMatcapMaterial: 'matcap',
  11286. LineBasicMaterial: 'basic',
  11287. LineDashedMaterial: 'dashed',
  11288. PointsMaterial: 'points',
  11289. ShadowMaterial: 'shadow',
  11290. SpriteMaterial: 'sprite'
  11291. };
  11292. const parameterNames = ["precision", "isWebGL2", "supportsVertexTextures", "outputEncoding", "instancing", "instancingColor", "map", "mapEncoding", "matcap", "matcapEncoding", "envMap", "envMapMode", "envMapEncoding", "envMapCubeUV", "lightMap", "lightMapEncoding", "aoMap", "emissiveMap", "emissiveMapEncoding", "bumpMap", "normalMap", "objectSpaceNormalMap", "tangentSpaceNormalMap", "clearcoatMap", "clearcoatRoughnessMap", "clearcoatNormalMap", "displacementMap", "specularMap", "roughnessMap", "metalnessMap", "gradientMap", "alphaMap", "combine", "vertexColors", "vertexTangents", "vertexUvs", "uvsVertexOnly", "fog", "useFog", "fogExp2", "flatShading", "sizeAttenuation", "logarithmicDepthBuffer", "skinning", "maxBones", "useVertexTexture", "morphTargets", "morphNormals", "maxMorphTargets", "maxMorphNormals", "premultipliedAlpha", "numDirLights", "numPointLights", "numSpotLights", "numHemiLights", "numRectAreaLights", "numDirLightShadows", "numPointLightShadows", "numSpotLightShadows", "shadowMapEnabled", "shadowMapType", "toneMapping", 'physicallyCorrectLights', "alphaTest", "doubleSided", "flipSided", "numClippingPlanes", "numClipIntersection", "depthPacking", "dithering", "sheen", "transmissionMap"];
  11293. function getMaxBones(object) {
  11294. const skeleton = object.skeleton;
  11295. const bones = skeleton.bones;
  11296. if (floatVertexTextures) {
  11297. return 1024;
  11298. } else {
  11299. // default for when object is not specified
  11300. // ( for example when prebuilding shader to be used with multiple objects )
  11301. //
  11302. // - leave some extra space for other uniforms
  11303. // - limit here is ANGLE's 254 max uniform vectors
  11304. // (up to 54 should be safe)
  11305. const nVertexUniforms = maxVertexUniforms;
  11306. const nVertexMatrices = Math.floor((nVertexUniforms - 20) / 4);
  11307. const maxBones = Math.min(nVertexMatrices, bones.length);
  11308. if (maxBones < bones.length) {
  11309. console.warn('THREE.WebGLRenderer: Skeleton has ' + bones.length + ' bones. This GPU supports ' + maxBones + '.');
  11310. return 0;
  11311. }
  11312. return maxBones;
  11313. }
  11314. }
  11315. function getTextureEncodingFromMap(map) {
  11316. let encoding;
  11317. if (!map) {
  11318. encoding = LinearEncoding;
  11319. } else if (map.isTexture) {
  11320. encoding = map.encoding;
  11321. } else if (map.isWebGLRenderTarget) {
  11322. console.warn("THREE.WebGLPrograms.getTextureEncodingFromMap: don't use render targets as textures. Use their .texture property instead.");
  11323. encoding = map.texture.encoding;
  11324. }
  11325. return encoding;
  11326. }
  11327. function getParameters(material, lights, shadows, scene, object) {
  11328. const fog = scene.fog;
  11329. const environment = material.isMeshStandardMaterial ? scene.environment : null;
  11330. const envMap = cubemaps.get(material.envMap || environment);
  11331. const shaderID = shaderIDs[material.type]; // heuristics to create shader parameters according to lights in the scene
  11332. // (not to blow over maxLights budget)
  11333. const maxBones = object.isSkinnedMesh ? getMaxBones(object) : 0;
  11334. if (material.precision !== null) {
  11335. precision = capabilities.getMaxPrecision(material.precision);
  11336. if (precision !== material.precision) {
  11337. console.warn('THREE.WebGLProgram.getParameters:', material.precision, 'not supported, using', precision, 'instead.');
  11338. }
  11339. }
  11340. let vertexShader, fragmentShader;
  11341. if (shaderID) {
  11342. const shader = ShaderLib[shaderID];
  11343. vertexShader = shader.vertexShader;
  11344. fragmentShader = shader.fragmentShader;
  11345. } else {
  11346. vertexShader = material.vertexShader;
  11347. fragmentShader = material.fragmentShader;
  11348. }
  11349. const currentRenderTarget = renderer.getRenderTarget();
  11350. const parameters = {
  11351. isWebGL2: isWebGL2,
  11352. shaderID: shaderID,
  11353. shaderName: material.type,
  11354. vertexShader: vertexShader,
  11355. fragmentShader: fragmentShader,
  11356. defines: material.defines,
  11357. isRawShaderMaterial: material.isRawShaderMaterial === true,
  11358. glslVersion: material.glslVersion,
  11359. precision: precision,
  11360. instancing: object.isInstancedMesh === true,
  11361. instancingColor: object.isInstancedMesh === true && object.instanceColor !== null,
  11362. supportsVertexTextures: vertexTextures,
  11363. outputEncoding: currentRenderTarget !== null ? getTextureEncodingFromMap(currentRenderTarget.texture) : renderer.outputEncoding,
  11364. map: !!material.map,
  11365. mapEncoding: getTextureEncodingFromMap(material.map),
  11366. matcap: !!material.matcap,
  11367. matcapEncoding: getTextureEncodingFromMap(material.matcap),
  11368. envMap: !!envMap,
  11369. envMapMode: envMap && envMap.mapping,
  11370. envMapEncoding: getTextureEncodingFromMap(envMap),
  11371. envMapCubeUV: !!envMap && (envMap.mapping === CubeUVReflectionMapping || envMap.mapping === CubeUVRefractionMapping),
  11372. lightMap: !!material.lightMap,
  11373. lightMapEncoding: getTextureEncodingFromMap(material.lightMap),
  11374. aoMap: !!material.aoMap,
  11375. emissiveMap: !!material.emissiveMap,
  11376. emissiveMapEncoding: getTextureEncodingFromMap(material.emissiveMap),
  11377. bumpMap: !!material.bumpMap,
  11378. normalMap: !!material.normalMap,
  11379. objectSpaceNormalMap: material.normalMapType === ObjectSpaceNormalMap,
  11380. tangentSpaceNormalMap: material.normalMapType === TangentSpaceNormalMap,
  11381. clearcoatMap: !!material.clearcoatMap,
  11382. clearcoatRoughnessMap: !!material.clearcoatRoughnessMap,
  11383. clearcoatNormalMap: !!material.clearcoatNormalMap,
  11384. displacementMap: !!material.displacementMap,
  11385. roughnessMap: !!material.roughnessMap,
  11386. metalnessMap: !!material.metalnessMap,
  11387. specularMap: !!material.specularMap,
  11388. alphaMap: !!material.alphaMap,
  11389. gradientMap: !!material.gradientMap,
  11390. sheen: !!material.sheen,
  11391. transmissionMap: !!material.transmissionMap,
  11392. combine: material.combine,
  11393. vertexTangents: material.normalMap && material.vertexTangents,
  11394. vertexColors: material.vertexColors,
  11395. vertexUvs: !!material.map || !!material.bumpMap || !!material.normalMap || !!material.specularMap || !!material.alphaMap || !!material.emissiveMap || !!material.roughnessMap || !!material.metalnessMap || !!material.clearcoatMap || !!material.clearcoatRoughnessMap || !!material.clearcoatNormalMap || !!material.displacementMap || !!material.transmissionMap,
  11396. uvsVertexOnly: !(!!material.map || !!material.bumpMap || !!material.normalMap || !!material.specularMap || !!material.alphaMap || !!material.emissiveMap || !!material.roughnessMap || !!material.metalnessMap || !!material.clearcoatNormalMap || !!material.transmissionMap) && !!material.displacementMap,
  11397. fog: !!fog,
  11398. useFog: material.fog,
  11399. fogExp2: fog && fog.isFogExp2,
  11400. flatShading: material.flatShading,
  11401. sizeAttenuation: material.sizeAttenuation,
  11402. logarithmicDepthBuffer: logarithmicDepthBuffer,
  11403. skinning: material.skinning && maxBones > 0,
  11404. maxBones: maxBones,
  11405. useVertexTexture: floatVertexTextures,
  11406. morphTargets: material.morphTargets,
  11407. morphNormals: material.morphNormals,
  11408. maxMorphTargets: renderer.maxMorphTargets,
  11409. maxMorphNormals: renderer.maxMorphNormals,
  11410. numDirLights: lights.directional.length,
  11411. numPointLights: lights.point.length,
  11412. numSpotLights: lights.spot.length,
  11413. numRectAreaLights: lights.rectArea.length,
  11414. numHemiLights: lights.hemi.length,
  11415. numDirLightShadows: lights.directionalShadowMap.length,
  11416. numPointLightShadows: lights.pointShadowMap.length,
  11417. numSpotLightShadows: lights.spotShadowMap.length,
  11418. numClippingPlanes: clipping.numPlanes,
  11419. numClipIntersection: clipping.numIntersection,
  11420. dithering: material.dithering,
  11421. shadowMapEnabled: renderer.shadowMap.enabled && shadows.length > 0,
  11422. shadowMapType: renderer.shadowMap.type,
  11423. toneMapping: material.toneMapped ? renderer.toneMapping : NoToneMapping,
  11424. physicallyCorrectLights: renderer.physicallyCorrectLights,
  11425. premultipliedAlpha: material.premultipliedAlpha,
  11426. alphaTest: material.alphaTest,
  11427. doubleSided: material.side === DoubleSide,
  11428. flipSided: material.side === BackSide,
  11429. depthPacking: material.depthPacking !== undefined ? material.depthPacking : false,
  11430. index0AttributeName: material.index0AttributeName,
  11431. extensionDerivatives: material.extensions && material.extensions.derivatives,
  11432. extensionFragDepth: material.extensions && material.extensions.fragDepth,
  11433. extensionDrawBuffers: material.extensions && material.extensions.drawBuffers,
  11434. extensionShaderTextureLOD: material.extensions && material.extensions.shaderTextureLOD,
  11435. rendererExtensionFragDepth: isWebGL2 || extensions.has('EXT_frag_depth'),
  11436. rendererExtensionDrawBuffers: isWebGL2 || extensions.has('WEBGL_draw_buffers'),
  11437. rendererExtensionShaderTextureLod: isWebGL2 || extensions.has('EXT_shader_texture_lod'),
  11438. customProgramCacheKey: material.customProgramCacheKey()
  11439. };
  11440. return parameters;
  11441. }
  11442. function getProgramCacheKey(parameters) {
  11443. const array = [];
  11444. if (parameters.shaderID) {
  11445. array.push(parameters.shaderID);
  11446. } else {
  11447. array.push(parameters.fragmentShader);
  11448. array.push(parameters.vertexShader);
  11449. }
  11450. if (parameters.defines !== undefined) {
  11451. for (const name in parameters.defines) {
  11452. array.push(name);
  11453. array.push(parameters.defines[name]);
  11454. }
  11455. }
  11456. if (parameters.isRawShaderMaterial === false) {
  11457. for (let i = 0; i < parameterNames.length; i++) {
  11458. array.push(parameters[parameterNames[i]]);
  11459. }
  11460. array.push(renderer.outputEncoding);
  11461. array.push(renderer.gammaFactor);
  11462. }
  11463. array.push(parameters.customProgramCacheKey);
  11464. return array.join();
  11465. }
  11466. function getUniforms(material) {
  11467. const shaderID = shaderIDs[material.type];
  11468. let uniforms;
  11469. if (shaderID) {
  11470. const shader = ShaderLib[shaderID];
  11471. uniforms = UniformsUtils.clone(shader.uniforms);
  11472. } else {
  11473. uniforms = material.uniforms;
  11474. }
  11475. return uniforms;
  11476. }
  11477. function acquireProgram(parameters, cacheKey) {
  11478. let program; // Check if code has been already compiled
  11479. for (let p = 0, pl = programs.length; p < pl; p++) {
  11480. const preexistingProgram = programs[p];
  11481. if (preexistingProgram.cacheKey === cacheKey) {
  11482. program = preexistingProgram;
  11483. ++program.usedTimes;
  11484. break;
  11485. }
  11486. }
  11487. if (program === undefined) {
  11488. program = new WebGLProgram(renderer, cacheKey, parameters, bindingStates);
  11489. programs.push(program);
  11490. }
  11491. return program;
  11492. }
  11493. function releaseProgram(program) {
  11494. if (--program.usedTimes === 0) {
  11495. // Remove from unordered set
  11496. const i = programs.indexOf(program);
  11497. programs[i] = programs[programs.length - 1];
  11498. programs.pop(); // Free WebGL resources
  11499. program.destroy();
  11500. }
  11501. }
  11502. return {
  11503. getParameters: getParameters,
  11504. getProgramCacheKey: getProgramCacheKey,
  11505. getUniforms: getUniforms,
  11506. acquireProgram: acquireProgram,
  11507. releaseProgram: releaseProgram,
  11508. // Exposed for resource monitoring & error feedback via renderer.info:
  11509. programs: programs
  11510. };
  11511. }
  11512. function WebGLProperties() {
  11513. let properties = new WeakMap();
  11514. function get(object) {
  11515. let map = properties.get(object);
  11516. if (map === undefined) {
  11517. map = {};
  11518. properties.set(object, map);
  11519. }
  11520. return map;
  11521. }
  11522. function remove(object) {
  11523. properties.delete(object);
  11524. }
  11525. function update(object, key, value) {
  11526. properties.get(object)[key] = value;
  11527. }
  11528. function dispose() {
  11529. properties = new WeakMap();
  11530. }
  11531. return {
  11532. get: get,
  11533. remove: remove,
  11534. update: update,
  11535. dispose: dispose
  11536. };
  11537. }
  11538. function painterSortStable(a, b) {
  11539. if (a.groupOrder !== b.groupOrder) {
  11540. return a.groupOrder - b.groupOrder;
  11541. } else if (a.renderOrder !== b.renderOrder) {
  11542. return a.renderOrder - b.renderOrder;
  11543. } else if (a.program !== b.program) {
  11544. return a.program.id - b.program.id;
  11545. } else if (a.material.id !== b.material.id) {
  11546. return a.material.id - b.material.id;
  11547. } else if (a.z !== b.z) {
  11548. return a.z - b.z;
  11549. } else {
  11550. return a.id - b.id;
  11551. }
  11552. }
  11553. function reversePainterSortStable(a, b) {
  11554. if (a.groupOrder !== b.groupOrder) {
  11555. return a.groupOrder - b.groupOrder;
  11556. } else if (a.renderOrder !== b.renderOrder) {
  11557. return a.renderOrder - b.renderOrder;
  11558. } else if (a.z !== b.z) {
  11559. return b.z - a.z;
  11560. } else {
  11561. return a.id - b.id;
  11562. }
  11563. }
  11564. function WebGLRenderList(properties) {
  11565. const renderItems = [];
  11566. let renderItemsIndex = 0;
  11567. const opaque = [];
  11568. const transparent = [];
  11569. const defaultProgram = {
  11570. id: -1
  11571. };
  11572. function init() {
  11573. renderItemsIndex = 0;
  11574. opaque.length = 0;
  11575. transparent.length = 0;
  11576. }
  11577. function getNextRenderItem(object, geometry, material, groupOrder, z, group) {
  11578. let renderItem = renderItems[renderItemsIndex];
  11579. const materialProperties = properties.get(material);
  11580. if (renderItem === undefined) {
  11581. renderItem = {
  11582. id: object.id,
  11583. object: object,
  11584. geometry: geometry,
  11585. material: material,
  11586. program: materialProperties.program || defaultProgram,
  11587. groupOrder: groupOrder,
  11588. renderOrder: object.renderOrder,
  11589. z: z,
  11590. group: group
  11591. };
  11592. renderItems[renderItemsIndex] = renderItem;
  11593. } else {
  11594. renderItem.id = object.id;
  11595. renderItem.object = object;
  11596. renderItem.geometry = geometry;
  11597. renderItem.material = material;
  11598. renderItem.program = materialProperties.program || defaultProgram;
  11599. renderItem.groupOrder = groupOrder;
  11600. renderItem.renderOrder = object.renderOrder;
  11601. renderItem.z = z;
  11602. renderItem.group = group;
  11603. }
  11604. renderItemsIndex++;
  11605. return renderItem;
  11606. }
  11607. function push(object, geometry, material, groupOrder, z, group) {
  11608. const renderItem = getNextRenderItem(object, geometry, material, groupOrder, z, group);
  11609. (material.transparent === true ? transparent : opaque).push(renderItem);
  11610. }
  11611. function unshift(object, geometry, material, groupOrder, z, group) {
  11612. const renderItem = getNextRenderItem(object, geometry, material, groupOrder, z, group);
  11613. (material.transparent === true ? transparent : opaque).unshift(renderItem);
  11614. }
  11615. function sort(customOpaqueSort, customTransparentSort) {
  11616. if (opaque.length > 1) opaque.sort(customOpaqueSort || painterSortStable);
  11617. if (transparent.length > 1) transparent.sort(customTransparentSort || reversePainterSortStable);
  11618. }
  11619. function finish() {
  11620. // Clear references from inactive renderItems in the list
  11621. for (let i = renderItemsIndex, il = renderItems.length; i < il; i++) {
  11622. const renderItem = renderItems[i];
  11623. if (renderItem.id === null) break;
  11624. renderItem.id = null;
  11625. renderItem.object = null;
  11626. renderItem.geometry = null;
  11627. renderItem.material = null;
  11628. renderItem.program = null;
  11629. renderItem.group = null;
  11630. }
  11631. }
  11632. return {
  11633. opaque: opaque,
  11634. transparent: transparent,
  11635. init: init,
  11636. push: push,
  11637. unshift: unshift,
  11638. finish: finish,
  11639. sort: sort
  11640. };
  11641. }
  11642. function WebGLRenderLists(properties) {
  11643. let lists = new WeakMap();
  11644. function get(scene, camera) {
  11645. const cameras = lists.get(scene);
  11646. let list;
  11647. if (cameras === undefined) {
  11648. list = new WebGLRenderList(properties);
  11649. lists.set(scene, new WeakMap());
  11650. lists.get(scene).set(camera, list);
  11651. } else {
  11652. list = cameras.get(camera);
  11653. if (list === undefined) {
  11654. list = new WebGLRenderList(properties);
  11655. cameras.set(camera, list);
  11656. }
  11657. }
  11658. return list;
  11659. }
  11660. function dispose() {
  11661. lists = new WeakMap();
  11662. }
  11663. return {
  11664. get: get,
  11665. dispose: dispose
  11666. };
  11667. }
  11668. function UniformsCache() {
  11669. const lights = {};
  11670. return {
  11671. get: function (light) {
  11672. if (lights[light.id] !== undefined) {
  11673. return lights[light.id];
  11674. }
  11675. let uniforms;
  11676. switch (light.type) {
  11677. case 'DirectionalLight':
  11678. uniforms = {
  11679. direction: new Vector3(),
  11680. color: new Color()
  11681. };
  11682. break;
  11683. case 'SpotLight':
  11684. uniforms = {
  11685. position: new Vector3(),
  11686. direction: new Vector3(),
  11687. color: new Color(),
  11688. distance: 0,
  11689. coneCos: 0,
  11690. penumbraCos: 0,
  11691. decay: 0
  11692. };
  11693. break;
  11694. case 'PointLight':
  11695. uniforms = {
  11696. position: new Vector3(),
  11697. color: new Color(),
  11698. distance: 0,
  11699. decay: 0
  11700. };
  11701. break;
  11702. case 'HemisphereLight':
  11703. uniforms = {
  11704. direction: new Vector3(),
  11705. skyColor: new Color(),
  11706. groundColor: new Color()
  11707. };
  11708. break;
  11709. case 'RectAreaLight':
  11710. uniforms = {
  11711. color: new Color(),
  11712. position: new Vector3(),
  11713. halfWidth: new Vector3(),
  11714. halfHeight: new Vector3()
  11715. };
  11716. break;
  11717. }
  11718. lights[light.id] = uniforms;
  11719. return uniforms;
  11720. }
  11721. };
  11722. }
  11723. function ShadowUniformsCache() {
  11724. const lights = {};
  11725. return {
  11726. get: function (light) {
  11727. if (lights[light.id] !== undefined) {
  11728. return lights[light.id];
  11729. }
  11730. let uniforms;
  11731. switch (light.type) {
  11732. case 'DirectionalLight':
  11733. uniforms = {
  11734. shadowBias: 0,
  11735. shadowNormalBias: 0,
  11736. shadowRadius: 1,
  11737. shadowMapSize: new Vector2()
  11738. };
  11739. break;
  11740. case 'SpotLight':
  11741. uniforms = {
  11742. shadowBias: 0,
  11743. shadowNormalBias: 0,
  11744. shadowRadius: 1,
  11745. shadowMapSize: new Vector2()
  11746. };
  11747. break;
  11748. case 'PointLight':
  11749. uniforms = {
  11750. shadowBias: 0,
  11751. shadowNormalBias: 0,
  11752. shadowRadius: 1,
  11753. shadowMapSize: new Vector2(),
  11754. shadowCameraNear: 1,
  11755. shadowCameraFar: 1000
  11756. };
  11757. break;
  11758. // TODO (abelnation): set RectAreaLight shadow uniforms
  11759. }
  11760. lights[light.id] = uniforms;
  11761. return uniforms;
  11762. }
  11763. };
  11764. }
  11765. let nextVersion = 0;
  11766. function shadowCastingLightsFirst(lightA, lightB) {
  11767. return (lightB.castShadow ? 1 : 0) - (lightA.castShadow ? 1 : 0);
  11768. }
  11769. function WebGLLights(extensions, capabilities) {
  11770. const cache = new UniformsCache();
  11771. const shadowCache = ShadowUniformsCache();
  11772. const state = {
  11773. version: 0,
  11774. hash: {
  11775. directionalLength: -1,
  11776. pointLength: -1,
  11777. spotLength: -1,
  11778. rectAreaLength: -1,
  11779. hemiLength: -1,
  11780. numDirectionalShadows: -1,
  11781. numPointShadows: -1,
  11782. numSpotShadows: -1
  11783. },
  11784. ambient: [0, 0, 0],
  11785. probe: [],
  11786. directional: [],
  11787. directionalShadow: [],
  11788. directionalShadowMap: [],
  11789. directionalShadowMatrix: [],
  11790. spot: [],
  11791. spotShadow: [],
  11792. spotShadowMap: [],
  11793. spotShadowMatrix: [],
  11794. rectArea: [],
  11795. rectAreaLTC1: null,
  11796. rectAreaLTC2: null,
  11797. point: [],
  11798. pointShadow: [],
  11799. pointShadowMap: [],
  11800. pointShadowMatrix: [],
  11801. hemi: []
  11802. };
  11803. for (let i = 0; i < 9; i++) state.probe.push(new Vector3());
  11804. const vector3 = new Vector3();
  11805. const matrix4 = new Matrix4();
  11806. const matrix42 = new Matrix4();
  11807. function setup(lights, shadows, camera) {
  11808. let r = 0,
  11809. g = 0,
  11810. b = 0;
  11811. for (let i = 0; i < 9; i++) state.probe[i].set(0, 0, 0);
  11812. let directionalLength = 0;
  11813. let pointLength = 0;
  11814. let spotLength = 0;
  11815. let rectAreaLength = 0;
  11816. let hemiLength = 0;
  11817. let numDirectionalShadows = 0;
  11818. let numPointShadows = 0;
  11819. let numSpotShadows = 0;
  11820. const viewMatrix = camera.matrixWorldInverse;
  11821. lights.sort(shadowCastingLightsFirst);
  11822. for (let i = 0, l = lights.length; i < l; i++) {
  11823. const light = lights[i];
  11824. const color = light.color;
  11825. const intensity = light.intensity;
  11826. const distance = light.distance;
  11827. const shadowMap = light.shadow && light.shadow.map ? light.shadow.map.texture : null;
  11828. if (light.isAmbientLight) {
  11829. r += color.r * intensity;
  11830. g += color.g * intensity;
  11831. b += color.b * intensity;
  11832. } else if (light.isLightProbe) {
  11833. for (let j = 0; j < 9; j++) {
  11834. state.probe[j].addScaledVector(light.sh.coefficients[j], intensity);
  11835. }
  11836. } else if (light.isDirectionalLight) {
  11837. const uniforms = cache.get(light);
  11838. uniforms.color.copy(light.color).multiplyScalar(light.intensity);
  11839. uniforms.direction.setFromMatrixPosition(light.matrixWorld);
  11840. vector3.setFromMatrixPosition(light.target.matrixWorld);
  11841. uniforms.direction.sub(vector3);
  11842. uniforms.direction.transformDirection(viewMatrix);
  11843. if (light.castShadow) {
  11844. const shadow = light.shadow;
  11845. const shadowUniforms = shadowCache.get(light);
  11846. shadowUniforms.shadowBias = shadow.bias;
  11847. shadowUniforms.shadowNormalBias = shadow.normalBias;
  11848. shadowUniforms.shadowRadius = shadow.radius;
  11849. shadowUniforms.shadowMapSize = shadow.mapSize;
  11850. state.directionalShadow[directionalLength] = shadowUniforms;
  11851. state.directionalShadowMap[directionalLength] = shadowMap;
  11852. state.directionalShadowMatrix[directionalLength] = light.shadow.matrix;
  11853. numDirectionalShadows++;
  11854. }
  11855. state.directional[directionalLength] = uniforms;
  11856. directionalLength++;
  11857. } else if (light.isSpotLight) {
  11858. const uniforms = cache.get(light);
  11859. uniforms.position.setFromMatrixPosition(light.matrixWorld);
  11860. uniforms.position.applyMatrix4(viewMatrix);
  11861. uniforms.color.copy(color).multiplyScalar(intensity);
  11862. uniforms.distance = distance;
  11863. uniforms.direction.setFromMatrixPosition(light.matrixWorld);
  11864. vector3.setFromMatrixPosition(light.target.matrixWorld);
  11865. uniforms.direction.sub(vector3);
  11866. uniforms.direction.transformDirection(viewMatrix);
  11867. uniforms.coneCos = Math.cos(light.angle);
  11868. uniforms.penumbraCos = Math.cos(light.angle * (1 - light.penumbra));
  11869. uniforms.decay = light.decay;
  11870. if (light.castShadow) {
  11871. const shadow = light.shadow;
  11872. const shadowUniforms = shadowCache.get(light);
  11873. shadowUniforms.shadowBias = shadow.bias;
  11874. shadowUniforms.shadowNormalBias = shadow.normalBias;
  11875. shadowUniforms.shadowRadius = shadow.radius;
  11876. shadowUniforms.shadowMapSize = shadow.mapSize;
  11877. state.spotShadow[spotLength] = shadowUniforms;
  11878. state.spotShadowMap[spotLength] = shadowMap;
  11879. state.spotShadowMatrix[spotLength] = light.shadow.matrix;
  11880. numSpotShadows++;
  11881. }
  11882. state.spot[spotLength] = uniforms;
  11883. spotLength++;
  11884. } else if (light.isRectAreaLight) {
  11885. const uniforms = cache.get(light); // (a) intensity is the total visible light emitted
  11886. //uniforms.color.copy( color ).multiplyScalar( intensity / ( light.width * light.height * Math.PI ) );
  11887. // (b) intensity is the brightness of the light
  11888. uniforms.color.copy(color).multiplyScalar(intensity);
  11889. uniforms.position.setFromMatrixPosition(light.matrixWorld);
  11890. uniforms.position.applyMatrix4(viewMatrix); // extract local rotation of light to derive width/height half vectors
  11891. matrix42.identity();
  11892. matrix4.copy(light.matrixWorld);
  11893. matrix4.premultiply(viewMatrix);
  11894. matrix42.extractRotation(matrix4);
  11895. uniforms.halfWidth.set(light.width * 0.5, 0.0, 0.0);
  11896. uniforms.halfHeight.set(0.0, light.height * 0.5, 0.0);
  11897. uniforms.halfWidth.applyMatrix4(matrix42);
  11898. uniforms.halfHeight.applyMatrix4(matrix42); // TODO (abelnation): RectAreaLight distance?
  11899. // uniforms.distance = distance;
  11900. state.rectArea[rectAreaLength] = uniforms;
  11901. rectAreaLength++;
  11902. } else if (light.isPointLight) {
  11903. const uniforms = cache.get(light);
  11904. uniforms.position.setFromMatrixPosition(light.matrixWorld);
  11905. uniforms.position.applyMatrix4(viewMatrix);
  11906. uniforms.color.copy(light.color).multiplyScalar(light.intensity);
  11907. uniforms.distance = light.distance;
  11908. uniforms.decay = light.decay;
  11909. if (light.castShadow) {
  11910. const shadow = light.shadow;
  11911. const shadowUniforms = shadowCache.get(light);
  11912. shadowUniforms.shadowBias = shadow.bias;
  11913. shadowUniforms.shadowNormalBias = shadow.normalBias;
  11914. shadowUniforms.shadowRadius = shadow.radius;
  11915. shadowUniforms.shadowMapSize = shadow.mapSize;
  11916. shadowUniforms.shadowCameraNear = shadow.camera.near;
  11917. shadowUniforms.shadowCameraFar = shadow.camera.far;
  11918. state.pointShadow[pointLength] = shadowUniforms;
  11919. state.pointShadowMap[pointLength] = shadowMap;
  11920. state.pointShadowMatrix[pointLength] = light.shadow.matrix;
  11921. numPointShadows++;
  11922. }
  11923. state.point[pointLength] = uniforms;
  11924. pointLength++;
  11925. } else if (light.isHemisphereLight) {
  11926. const uniforms = cache.get(light);
  11927. uniforms.direction.setFromMatrixPosition(light.matrixWorld);
  11928. uniforms.direction.transformDirection(viewMatrix);
  11929. uniforms.direction.normalize();
  11930. uniforms.skyColor.copy(light.color).multiplyScalar(intensity);
  11931. uniforms.groundColor.copy(light.groundColor).multiplyScalar(intensity);
  11932. state.hemi[hemiLength] = uniforms;
  11933. hemiLength++;
  11934. }
  11935. }
  11936. if (rectAreaLength > 0) {
  11937. if (capabilities.isWebGL2) {
  11938. // WebGL 2
  11939. state.rectAreaLTC1 = UniformsLib.LTC_FLOAT_1;
  11940. state.rectAreaLTC2 = UniformsLib.LTC_FLOAT_2;
  11941. } else {
  11942. // WebGL 1
  11943. if (extensions.has('OES_texture_float_linear') === true) {
  11944. state.rectAreaLTC1 = UniformsLib.LTC_FLOAT_1;
  11945. state.rectAreaLTC2 = UniformsLib.LTC_FLOAT_2;
  11946. } else if (extensions.has('OES_texture_half_float_linear') === true) {
  11947. state.rectAreaLTC1 = UniformsLib.LTC_HALF_1;
  11948. state.rectAreaLTC2 = UniformsLib.LTC_HALF_2;
  11949. } else {
  11950. console.error('THREE.WebGLRenderer: Unable to use RectAreaLight. Missing WebGL extensions.');
  11951. }
  11952. }
  11953. }
  11954. state.ambient[0] = r;
  11955. state.ambient[1] = g;
  11956. state.ambient[2] = b;
  11957. const hash = state.hash;
  11958. if (hash.directionalLength !== directionalLength || hash.pointLength !== pointLength || hash.spotLength !== spotLength || hash.rectAreaLength !== rectAreaLength || hash.hemiLength !== hemiLength || hash.numDirectionalShadows !== numDirectionalShadows || hash.numPointShadows !== numPointShadows || hash.numSpotShadows !== numSpotShadows) {
  11959. state.directional.length = directionalLength;
  11960. state.spot.length = spotLength;
  11961. state.rectArea.length = rectAreaLength;
  11962. state.point.length = pointLength;
  11963. state.hemi.length = hemiLength;
  11964. state.directionalShadow.length = numDirectionalShadows;
  11965. state.directionalShadowMap.length = numDirectionalShadows;
  11966. state.pointShadow.length = numPointShadows;
  11967. state.pointShadowMap.length = numPointShadows;
  11968. state.spotShadow.length = numSpotShadows;
  11969. state.spotShadowMap.length = numSpotShadows;
  11970. state.directionalShadowMatrix.length = numDirectionalShadows;
  11971. state.pointShadowMatrix.length = numPointShadows;
  11972. state.spotShadowMatrix.length = numSpotShadows;
  11973. hash.directionalLength = directionalLength;
  11974. hash.pointLength = pointLength;
  11975. hash.spotLength = spotLength;
  11976. hash.rectAreaLength = rectAreaLength;
  11977. hash.hemiLength = hemiLength;
  11978. hash.numDirectionalShadows = numDirectionalShadows;
  11979. hash.numPointShadows = numPointShadows;
  11980. hash.numSpotShadows = numSpotShadows;
  11981. state.version = nextVersion++;
  11982. }
  11983. }
  11984. return {
  11985. setup: setup,
  11986. state: state
  11987. };
  11988. }
  11989. function WebGLRenderState(extensions, capabilities) {
  11990. const lights = new WebGLLights(extensions, capabilities);
  11991. const lightsArray = [];
  11992. const shadowsArray = [];
  11993. function init() {
  11994. lightsArray.length = 0;
  11995. shadowsArray.length = 0;
  11996. }
  11997. function pushLight(light) {
  11998. lightsArray.push(light);
  11999. }
  12000. function pushShadow(shadowLight) {
  12001. shadowsArray.push(shadowLight);
  12002. }
  12003. function setupLights(camera) {
  12004. lights.setup(lightsArray, shadowsArray, camera);
  12005. }
  12006. const state = {
  12007. lightsArray: lightsArray,
  12008. shadowsArray: shadowsArray,
  12009. lights: lights
  12010. };
  12011. return {
  12012. init: init,
  12013. state: state,
  12014. setupLights: setupLights,
  12015. pushLight: pushLight,
  12016. pushShadow: pushShadow
  12017. };
  12018. }
  12019. function WebGLRenderStates(extensions, capabilities) {
  12020. let renderStates = new WeakMap();
  12021. function get(scene, camera) {
  12022. let renderState;
  12023. if (renderStates.has(scene) === false) {
  12024. renderState = new WebGLRenderState(extensions, capabilities);
  12025. renderStates.set(scene, new WeakMap());
  12026. renderStates.get(scene).set(camera, renderState);
  12027. } else {
  12028. if (renderStates.get(scene).has(camera) === false) {
  12029. renderState = new WebGLRenderState(extensions, capabilities);
  12030. renderStates.get(scene).set(camera, renderState);
  12031. } else {
  12032. renderState = renderStates.get(scene).get(camera);
  12033. }
  12034. }
  12035. return renderState;
  12036. }
  12037. function dispose() {
  12038. renderStates = new WeakMap();
  12039. }
  12040. return {
  12041. get: get,
  12042. dispose: dispose
  12043. };
  12044. }
  12045. /**
  12046. * parameters = {
  12047. *
  12048. * opacity: <float>,
  12049. *
  12050. * map: new THREE.Texture( <Image> ),
  12051. *
  12052. * alphaMap: new THREE.Texture( <Image> ),
  12053. *
  12054. * displacementMap: new THREE.Texture( <Image> ),
  12055. * displacementScale: <float>,
  12056. * displacementBias: <float>,
  12057. *
  12058. * wireframe: <boolean>,
  12059. * wireframeLinewidth: <float>
  12060. * }
  12061. */
  12062. function MeshDepthMaterial(parameters) {
  12063. Material.call(this);
  12064. this.type = 'MeshDepthMaterial';
  12065. this.depthPacking = BasicDepthPacking;
  12066. this.skinning = false;
  12067. this.morphTargets = false;
  12068. this.map = null;
  12069. this.alphaMap = null;
  12070. this.displacementMap = null;
  12071. this.displacementScale = 1;
  12072. this.displacementBias = 0;
  12073. this.wireframe = false;
  12074. this.wireframeLinewidth = 1;
  12075. this.fog = false;
  12076. this.setValues(parameters);
  12077. }
  12078. MeshDepthMaterial.prototype = Object.create(Material.prototype);
  12079. MeshDepthMaterial.prototype.constructor = MeshDepthMaterial;
  12080. MeshDepthMaterial.prototype.isMeshDepthMaterial = true;
  12081. MeshDepthMaterial.prototype.copy = function (source) {
  12082. Material.prototype.copy.call(this, source);
  12083. this.depthPacking = source.depthPacking;
  12084. this.skinning = source.skinning;
  12085. this.morphTargets = source.morphTargets;
  12086. this.map = source.map;
  12087. this.alphaMap = source.alphaMap;
  12088. this.displacementMap = source.displacementMap;
  12089. this.displacementScale = source.displacementScale;
  12090. this.displacementBias = source.displacementBias;
  12091. this.wireframe = source.wireframe;
  12092. this.wireframeLinewidth = source.wireframeLinewidth;
  12093. return this;
  12094. };
  12095. /**
  12096. * parameters = {
  12097. *
  12098. * referencePosition: <float>,
  12099. * nearDistance: <float>,
  12100. * farDistance: <float>,
  12101. *
  12102. * skinning: <bool>,
  12103. * morphTargets: <bool>,
  12104. *
  12105. * map: new THREE.Texture( <Image> ),
  12106. *
  12107. * alphaMap: new THREE.Texture( <Image> ),
  12108. *
  12109. * displacementMap: new THREE.Texture( <Image> ),
  12110. * displacementScale: <float>,
  12111. * displacementBias: <float>
  12112. *
  12113. * }
  12114. */
  12115. function MeshDistanceMaterial(parameters) {
  12116. Material.call(this);
  12117. this.type = 'MeshDistanceMaterial';
  12118. this.referencePosition = new Vector3();
  12119. this.nearDistance = 1;
  12120. this.farDistance = 1000;
  12121. this.skinning = false;
  12122. this.morphTargets = false;
  12123. this.map = null;
  12124. this.alphaMap = null;
  12125. this.displacementMap = null;
  12126. this.displacementScale = 1;
  12127. this.displacementBias = 0;
  12128. this.fog = false;
  12129. this.setValues(parameters);
  12130. }
  12131. MeshDistanceMaterial.prototype = Object.create(Material.prototype);
  12132. MeshDistanceMaterial.prototype.constructor = MeshDistanceMaterial;
  12133. MeshDistanceMaterial.prototype.isMeshDistanceMaterial = true;
  12134. MeshDistanceMaterial.prototype.copy = function (source) {
  12135. Material.prototype.copy.call(this, source);
  12136. this.referencePosition.copy(source.referencePosition);
  12137. this.nearDistance = source.nearDistance;
  12138. this.farDistance = source.farDistance;
  12139. this.skinning = source.skinning;
  12140. this.morphTargets = source.morphTargets;
  12141. this.map = source.map;
  12142. this.alphaMap = source.alphaMap;
  12143. this.displacementMap = source.displacementMap;
  12144. this.displacementScale = source.displacementScale;
  12145. this.displacementBias = source.displacementBias;
  12146. return this;
  12147. };
  12148. var vsm_frag = "uniform sampler2D shadow_pass;\nuniform vec2 resolution;\nuniform float radius;\n#include <packing>\nvoid main() {\n\tfloat mean = 0.0;\n\tfloat squared_mean = 0.0;\n\tfloat depth = unpackRGBAToDepth( texture2D( shadow_pass, ( gl_FragCoord.xy ) / resolution ) );\n\tfor ( float i = -1.0; i < 1.0 ; i += SAMPLE_RATE) {\n\t\t#ifdef HORIZONAL_PASS\n\t\t\tvec2 distribution = unpackRGBATo2Half( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( i, 0.0 ) * radius ) / resolution ) );\n\t\t\tmean += distribution.x;\n\t\t\tsquared_mean += distribution.y * distribution.y + distribution.x * distribution.x;\n\t\t#else\n\t\t\tfloat depth = unpackRGBAToDepth( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( 0.0, i ) * radius ) / resolution ) );\n\t\t\tmean += depth;\n\t\t\tsquared_mean += depth * depth;\n\t\t#endif\n\t}\n\tmean = mean * HALF_SAMPLE_RATE;\n\tsquared_mean = squared_mean * HALF_SAMPLE_RATE;\n\tfloat std_dev = sqrt( squared_mean - mean * mean );\n\tgl_FragColor = pack2HalfToRGBA( vec2( mean, std_dev ) );\n}";
  12149. var vsm_vert = "void main() {\n\tgl_Position = vec4( position, 1.0 );\n}";
  12150. function WebGLShadowMap(_renderer, _objects, maxTextureSize) {
  12151. let _frustum = new Frustum();
  12152. const _shadowMapSize = new Vector2(),
  12153. _viewportSize = new Vector2(),
  12154. _viewport = new Vector4(),
  12155. _depthMaterials = [],
  12156. _distanceMaterials = [],
  12157. _materialCache = {};
  12158. const shadowSide = {
  12159. 0: BackSide,
  12160. 1: FrontSide,
  12161. 2: DoubleSide
  12162. };
  12163. const shadowMaterialVertical = new ShaderMaterial({
  12164. defines: {
  12165. SAMPLE_RATE: 2.0 / 8.0,
  12166. HALF_SAMPLE_RATE: 1.0 / 8.0
  12167. },
  12168. uniforms: {
  12169. shadow_pass: {
  12170. value: null
  12171. },
  12172. resolution: {
  12173. value: new Vector2()
  12174. },
  12175. radius: {
  12176. value: 4.0
  12177. }
  12178. },
  12179. vertexShader: vsm_vert,
  12180. fragmentShader: vsm_frag
  12181. });
  12182. const shadowMaterialHorizonal = shadowMaterialVertical.clone();
  12183. shadowMaterialHorizonal.defines.HORIZONAL_PASS = 1;
  12184. const fullScreenTri = new BufferGeometry();
  12185. fullScreenTri.setAttribute("position", new BufferAttribute(new Float32Array([-1, -1, 0.5, 3, -1, 0.5, -1, 3, 0.5]), 3));
  12186. const fullScreenMesh = new Mesh(fullScreenTri, shadowMaterialVertical);
  12187. const scope = this;
  12188. this.enabled = false;
  12189. this.autoUpdate = true;
  12190. this.needsUpdate = false;
  12191. this.type = PCFShadowMap;
  12192. this.render = function (lights, scene, camera) {
  12193. if (scope.enabled === false) return;
  12194. if (scope.autoUpdate === false && scope.needsUpdate === false) return;
  12195. if (lights.length === 0) return;
  12196. const currentRenderTarget = _renderer.getRenderTarget();
  12197. const activeCubeFace = _renderer.getActiveCubeFace();
  12198. const activeMipmapLevel = _renderer.getActiveMipmapLevel();
  12199. const _state = _renderer.state; // Set GL state for depth map.
  12200. _state.setBlending(NoBlending);
  12201. _state.buffers.color.setClear(1, 1, 1, 1);
  12202. _state.buffers.depth.setTest(true);
  12203. _state.setScissorTest(false); // render depth map
  12204. for (let i = 0, il = lights.length; i < il; i++) {
  12205. const light = lights[i];
  12206. const shadow = light.shadow;
  12207. if (shadow === undefined) {
  12208. console.warn('THREE.WebGLShadowMap:', light, 'has no shadow.');
  12209. continue;
  12210. }
  12211. if (shadow.autoUpdate === false && shadow.needsUpdate === false) continue;
  12212. _shadowMapSize.copy(shadow.mapSize);
  12213. const shadowFrameExtents = shadow.getFrameExtents();
  12214. _shadowMapSize.multiply(shadowFrameExtents);
  12215. _viewportSize.copy(shadow.mapSize);
  12216. if (_shadowMapSize.x > maxTextureSize || _shadowMapSize.y > maxTextureSize) {
  12217. if (_shadowMapSize.x > maxTextureSize) {
  12218. _viewportSize.x = Math.floor(maxTextureSize / shadowFrameExtents.x);
  12219. _shadowMapSize.x = _viewportSize.x * shadowFrameExtents.x;
  12220. shadow.mapSize.x = _viewportSize.x;
  12221. }
  12222. if (_shadowMapSize.y > maxTextureSize) {
  12223. _viewportSize.y = Math.floor(maxTextureSize / shadowFrameExtents.y);
  12224. _shadowMapSize.y = _viewportSize.y * shadowFrameExtents.y;
  12225. shadow.mapSize.y = _viewportSize.y;
  12226. }
  12227. }
  12228. if (shadow.map === null && !shadow.isPointLightShadow && this.type === VSMShadowMap) {
  12229. const pars = {
  12230. minFilter: LinearFilter,
  12231. magFilter: LinearFilter,
  12232. format: RGBAFormat
  12233. };
  12234. shadow.map = new WebGLRenderTarget(_shadowMapSize.x, _shadowMapSize.y, pars);
  12235. shadow.map.texture.name = light.name + ".shadowMap";
  12236. shadow.mapPass = new WebGLRenderTarget(_shadowMapSize.x, _shadowMapSize.y, pars);
  12237. shadow.camera.updateProjectionMatrix();
  12238. }
  12239. if (shadow.map === null) {
  12240. const pars = {
  12241. minFilter: NearestFilter,
  12242. magFilter: NearestFilter,
  12243. format: RGBAFormat
  12244. };
  12245. shadow.map = new WebGLRenderTarget(_shadowMapSize.x, _shadowMapSize.y, pars);
  12246. shadow.map.texture.name = light.name + ".shadowMap";
  12247. shadow.camera.updateProjectionMatrix();
  12248. }
  12249. _renderer.setRenderTarget(shadow.map);
  12250. _renderer.clear();
  12251. const viewportCount = shadow.getViewportCount();
  12252. for (let vp = 0; vp < viewportCount; vp++) {
  12253. const viewport = shadow.getViewport(vp);
  12254. _viewport.set(_viewportSize.x * viewport.x, _viewportSize.y * viewport.y, _viewportSize.x * viewport.z, _viewportSize.y * viewport.w);
  12255. _state.viewport(_viewport);
  12256. shadow.updateMatrices(light, vp);
  12257. _frustum = shadow.getFrustum();
  12258. renderObject(scene, camera, shadow.camera, light, this.type);
  12259. } // do blur pass for VSM
  12260. if (!shadow.isPointLightShadow && this.type === VSMShadowMap) {
  12261. VSMPass(shadow, camera);
  12262. }
  12263. shadow.needsUpdate = false;
  12264. }
  12265. scope.needsUpdate = false;
  12266. _renderer.setRenderTarget(currentRenderTarget, activeCubeFace, activeMipmapLevel);
  12267. };
  12268. function VSMPass(shadow, camera) {
  12269. const geometry = _objects.update(fullScreenMesh); // vertical pass
  12270. shadowMaterialVertical.uniforms.shadow_pass.value = shadow.map.texture;
  12271. shadowMaterialVertical.uniforms.resolution.value = shadow.mapSize;
  12272. shadowMaterialVertical.uniforms.radius.value = shadow.radius;
  12273. _renderer.setRenderTarget(shadow.mapPass);
  12274. _renderer.clear();
  12275. _renderer.renderBufferDirect(camera, null, geometry, shadowMaterialVertical, fullScreenMesh, null); // horizonal pass
  12276. shadowMaterialHorizonal.uniforms.shadow_pass.value = shadow.mapPass.texture;
  12277. shadowMaterialHorizonal.uniforms.resolution.value = shadow.mapSize;
  12278. shadowMaterialHorizonal.uniforms.radius.value = shadow.radius;
  12279. _renderer.setRenderTarget(shadow.map);
  12280. _renderer.clear();
  12281. _renderer.renderBufferDirect(camera, null, geometry, shadowMaterialHorizonal, fullScreenMesh, null);
  12282. }
  12283. function getDepthMaterialVariant(useMorphing, useSkinning, useInstancing) {
  12284. const index = useMorphing << 0 | useSkinning << 1 | useInstancing << 2;
  12285. let material = _depthMaterials[index];
  12286. if (material === undefined) {
  12287. material = new MeshDepthMaterial({
  12288. depthPacking: RGBADepthPacking,
  12289. morphTargets: useMorphing,
  12290. skinning: useSkinning
  12291. });
  12292. _depthMaterials[index] = material;
  12293. }
  12294. return material;
  12295. }
  12296. function getDistanceMaterialVariant(useMorphing, useSkinning, useInstancing) {
  12297. const index = useMorphing << 0 | useSkinning << 1 | useInstancing << 2;
  12298. let material = _distanceMaterials[index];
  12299. if (material === undefined) {
  12300. material = new MeshDistanceMaterial({
  12301. morphTargets: useMorphing,
  12302. skinning: useSkinning
  12303. });
  12304. _distanceMaterials[index] = material;
  12305. }
  12306. return material;
  12307. }
  12308. function getDepthMaterial(object, geometry, material, light, shadowCameraNear, shadowCameraFar, type) {
  12309. let result = null;
  12310. let getMaterialVariant = getDepthMaterialVariant;
  12311. let customMaterial = object.customDepthMaterial;
  12312. if (light.isPointLight === true) {
  12313. getMaterialVariant = getDistanceMaterialVariant;
  12314. customMaterial = object.customDistanceMaterial;
  12315. }
  12316. if (customMaterial === undefined) {
  12317. let useMorphing = false;
  12318. if (material.morphTargets === true) {
  12319. useMorphing = geometry.morphAttributes && geometry.morphAttributes.position && geometry.morphAttributes.position.length > 0;
  12320. }
  12321. let useSkinning = false;
  12322. if (object.isSkinnedMesh === true) {
  12323. if (material.skinning === true) {
  12324. useSkinning = true;
  12325. } else {
  12326. console.warn('THREE.WebGLShadowMap: THREE.SkinnedMesh with material.skinning set to false:', object);
  12327. }
  12328. }
  12329. const useInstancing = object.isInstancedMesh === true;
  12330. result = getMaterialVariant(useMorphing, useSkinning, useInstancing);
  12331. } else {
  12332. result = customMaterial;
  12333. }
  12334. if (_renderer.localClippingEnabled && material.clipShadows === true && material.clippingPlanes.length !== 0) {
  12335. // in this case we need a unique material instance reflecting the
  12336. // appropriate state
  12337. const keyA = result.uuid,
  12338. keyB = material.uuid;
  12339. let materialsForVariant = _materialCache[keyA];
  12340. if (materialsForVariant === undefined) {
  12341. materialsForVariant = {};
  12342. _materialCache[keyA] = materialsForVariant;
  12343. }
  12344. let cachedMaterial = materialsForVariant[keyB];
  12345. if (cachedMaterial === undefined) {
  12346. cachedMaterial = result.clone();
  12347. materialsForVariant[keyB] = cachedMaterial;
  12348. }
  12349. result = cachedMaterial;
  12350. }
  12351. result.visible = material.visible;
  12352. result.wireframe = material.wireframe;
  12353. if (type === VSMShadowMap) {
  12354. result.side = material.shadowSide !== null ? material.shadowSide : material.side;
  12355. } else {
  12356. result.side = material.shadowSide !== null ? material.shadowSide : shadowSide[material.side];
  12357. }
  12358. result.clipShadows = material.clipShadows;
  12359. result.clippingPlanes = material.clippingPlanes;
  12360. result.clipIntersection = material.clipIntersection;
  12361. result.wireframeLinewidth = material.wireframeLinewidth;
  12362. result.linewidth = material.linewidth;
  12363. if (light.isPointLight === true && result.isMeshDistanceMaterial === true) {
  12364. result.referencePosition.setFromMatrixPosition(light.matrixWorld);
  12365. result.nearDistance = shadowCameraNear;
  12366. result.farDistance = shadowCameraFar;
  12367. }
  12368. return result;
  12369. }
  12370. function renderObject(object, camera, shadowCamera, light, type) {
  12371. if (object.visible === false) return;
  12372. const visible = object.layers.test(camera.layers);
  12373. if (visible && (object.isMesh || object.isLine || object.isPoints)) {
  12374. if ((object.castShadow || object.receiveShadow && type === VSMShadowMap) && (!object.frustumCulled || _frustum.intersectsObject(object))) {
  12375. object.modelViewMatrix.multiplyMatrices(shadowCamera.matrixWorldInverse, object.matrixWorld);
  12376. const geometry = _objects.update(object);
  12377. const material = object.material;
  12378. if (Array.isArray(material)) {
  12379. const groups = geometry.groups;
  12380. for (let k = 0, kl = groups.length; k < kl; k++) {
  12381. const group = groups[k];
  12382. const groupMaterial = material[group.materialIndex];
  12383. if (groupMaterial && groupMaterial.visible) {
  12384. const depthMaterial = getDepthMaterial(object, geometry, groupMaterial, light, shadowCamera.near, shadowCamera.far, type);
  12385. _renderer.renderBufferDirect(shadowCamera, null, geometry, depthMaterial, object, group);
  12386. }
  12387. }
  12388. } else if (material.visible) {
  12389. const depthMaterial = getDepthMaterial(object, geometry, material, light, shadowCamera.near, shadowCamera.far, type);
  12390. _renderer.renderBufferDirect(shadowCamera, null, geometry, depthMaterial, object, null);
  12391. }
  12392. }
  12393. }
  12394. const children = object.children;
  12395. for (let i = 0, l = children.length; i < l; i++) {
  12396. renderObject(children[i], camera, shadowCamera, light, type);
  12397. }
  12398. }
  12399. }
  12400. function WebGLState(gl, extensions, capabilities) {
  12401. const isWebGL2 = capabilities.isWebGL2;
  12402. function ColorBuffer() {
  12403. let locked = false;
  12404. const color = new Vector4();
  12405. let currentColorMask = null;
  12406. const currentColorClear = new Vector4(0, 0, 0, 0);
  12407. return {
  12408. setMask: function (colorMask) {
  12409. if (currentColorMask !== colorMask && !locked) {
  12410. gl.colorMask(colorMask, colorMask, colorMask, colorMask);
  12411. currentColorMask = colorMask;
  12412. }
  12413. },
  12414. setLocked: function (lock) {
  12415. locked = lock;
  12416. },
  12417. setClear: function (r, g, b, a, premultipliedAlpha) {
  12418. if (premultipliedAlpha === true) {
  12419. r *= a;
  12420. g *= a;
  12421. b *= a;
  12422. }
  12423. color.set(r, g, b, a);
  12424. if (currentColorClear.equals(color) === false) {
  12425. gl.clearColor(r, g, b, a);
  12426. currentColorClear.copy(color);
  12427. }
  12428. },
  12429. reset: function () {
  12430. locked = false;
  12431. currentColorMask = null;
  12432. currentColorClear.set(-1, 0, 0, 0); // set to invalid state
  12433. }
  12434. };
  12435. }
  12436. function DepthBuffer() {
  12437. let locked = false;
  12438. let currentDepthMask = null;
  12439. let currentDepthFunc = null;
  12440. let currentDepthClear = null;
  12441. return {
  12442. setTest: function (depthTest) {
  12443. if (depthTest) {
  12444. enable(2929);
  12445. } else {
  12446. disable(2929);
  12447. }
  12448. },
  12449. setMask: function (depthMask) {
  12450. if (currentDepthMask !== depthMask && !locked) {
  12451. gl.depthMask(depthMask);
  12452. currentDepthMask = depthMask;
  12453. }
  12454. },
  12455. setFunc: function (depthFunc) {
  12456. if (currentDepthFunc !== depthFunc) {
  12457. if (depthFunc) {
  12458. switch (depthFunc) {
  12459. case NeverDepth:
  12460. gl.depthFunc(512);
  12461. break;
  12462. case AlwaysDepth:
  12463. gl.depthFunc(519);
  12464. break;
  12465. case LessDepth:
  12466. gl.depthFunc(513);
  12467. break;
  12468. case LessEqualDepth:
  12469. gl.depthFunc(515);
  12470. break;
  12471. case EqualDepth:
  12472. gl.depthFunc(514);
  12473. break;
  12474. case GreaterEqualDepth:
  12475. gl.depthFunc(518);
  12476. break;
  12477. case GreaterDepth:
  12478. gl.depthFunc(516);
  12479. break;
  12480. case NotEqualDepth:
  12481. gl.depthFunc(517);
  12482. break;
  12483. default:
  12484. gl.depthFunc(515);
  12485. }
  12486. } else {
  12487. gl.depthFunc(515);
  12488. }
  12489. currentDepthFunc = depthFunc;
  12490. }
  12491. },
  12492. setLocked: function (lock) {
  12493. locked = lock;
  12494. },
  12495. setClear: function (depth) {
  12496. if (currentDepthClear !== depth) {
  12497. gl.clearDepth(depth);
  12498. currentDepthClear = depth;
  12499. }
  12500. },
  12501. reset: function () {
  12502. locked = false;
  12503. currentDepthMask = null;
  12504. currentDepthFunc = null;
  12505. currentDepthClear = null;
  12506. }
  12507. };
  12508. }
  12509. function StencilBuffer() {
  12510. let locked = false;
  12511. let currentStencilMask = null;
  12512. let currentStencilFunc = null;
  12513. let currentStencilRef = null;
  12514. let currentStencilFuncMask = null;
  12515. let currentStencilFail = null;
  12516. let currentStencilZFail = null;
  12517. let currentStencilZPass = null;
  12518. let currentStencilClear = null;
  12519. return {
  12520. setTest: function (stencilTest) {
  12521. if (!locked) {
  12522. if (stencilTest) {
  12523. enable(2960);
  12524. } else {
  12525. disable(2960);
  12526. }
  12527. }
  12528. },
  12529. setMask: function (stencilMask) {
  12530. if (currentStencilMask !== stencilMask && !locked) {
  12531. gl.stencilMask(stencilMask);
  12532. currentStencilMask = stencilMask;
  12533. }
  12534. },
  12535. setFunc: function (stencilFunc, stencilRef, stencilMask) {
  12536. if (currentStencilFunc !== stencilFunc || currentStencilRef !== stencilRef || currentStencilFuncMask !== stencilMask) {
  12537. gl.stencilFunc(stencilFunc, stencilRef, stencilMask);
  12538. currentStencilFunc = stencilFunc;
  12539. currentStencilRef = stencilRef;
  12540. currentStencilFuncMask = stencilMask;
  12541. }
  12542. },
  12543. setOp: function (stencilFail, stencilZFail, stencilZPass) {
  12544. if (currentStencilFail !== stencilFail || currentStencilZFail !== stencilZFail || currentStencilZPass !== stencilZPass) {
  12545. gl.stencilOp(stencilFail, stencilZFail, stencilZPass);
  12546. currentStencilFail = stencilFail;
  12547. currentStencilZFail = stencilZFail;
  12548. currentStencilZPass = stencilZPass;
  12549. }
  12550. },
  12551. setLocked: function (lock) {
  12552. locked = lock;
  12553. },
  12554. setClear: function (stencil) {
  12555. if (currentStencilClear !== stencil) {
  12556. gl.clearStencil(stencil);
  12557. currentStencilClear = stencil;
  12558. }
  12559. },
  12560. reset: function () {
  12561. locked = false;
  12562. currentStencilMask = null;
  12563. currentStencilFunc = null;
  12564. currentStencilRef = null;
  12565. currentStencilFuncMask = null;
  12566. currentStencilFail = null;
  12567. currentStencilZFail = null;
  12568. currentStencilZPass = null;
  12569. currentStencilClear = null;
  12570. }
  12571. };
  12572. } //
  12573. const colorBuffer = new ColorBuffer();
  12574. const depthBuffer = new DepthBuffer();
  12575. const stencilBuffer = new StencilBuffer();
  12576. let enabledCapabilities = {};
  12577. let currentProgram = null;
  12578. let currentBlendingEnabled = null;
  12579. let currentBlending = null;
  12580. let currentBlendEquation = null;
  12581. let currentBlendSrc = null;
  12582. let currentBlendDst = null;
  12583. let currentBlendEquationAlpha = null;
  12584. let currentBlendSrcAlpha = null;
  12585. let currentBlendDstAlpha = null;
  12586. let currentPremultipledAlpha = false;
  12587. let currentFlipSided = null;
  12588. let currentCullFace = null;
  12589. let currentLineWidth = null;
  12590. let currentPolygonOffsetFactor = null;
  12591. let currentPolygonOffsetUnits = null;
  12592. const maxTextures = gl.getParameter(35661);
  12593. let lineWidthAvailable = false;
  12594. let version = 0;
  12595. const glVersion = gl.getParameter(7938);
  12596. if (glVersion.indexOf('WebGL') !== -1) {
  12597. version = parseFloat(/^WebGL\ ([0-9])/.exec(glVersion)[1]);
  12598. lineWidthAvailable = version >= 1.0;
  12599. } else if (glVersion.indexOf('OpenGL ES') !== -1) {
  12600. version = parseFloat(/^OpenGL\ ES\ ([0-9])/.exec(glVersion)[1]);
  12601. lineWidthAvailable = version >= 2.0;
  12602. }
  12603. let currentTextureSlot = null;
  12604. let currentBoundTextures = {};
  12605. const currentScissor = new Vector4();
  12606. const currentViewport = new Vector4();
  12607. function createTexture(type, target, count) {
  12608. const data = new Uint8Array(4); // 4 is required to match default unpack alignment of 4.
  12609. const texture = gl.createTexture();
  12610. gl.bindTexture(type, texture);
  12611. gl.texParameteri(type, 10241, 9728);
  12612. gl.texParameteri(type, 10240, 9728);
  12613. for (let i = 0; i < count; i++) {
  12614. gl.texImage2D(target + i, 0, 6408, 1, 1, 0, 6408, 5121, data);
  12615. }
  12616. return texture;
  12617. }
  12618. const emptyTextures = {};
  12619. emptyTextures[3553] = createTexture(3553, 3553, 1);
  12620. emptyTextures[34067] = createTexture(34067, 34069, 6); // init
  12621. colorBuffer.setClear(0, 0, 0, 1);
  12622. depthBuffer.setClear(1);
  12623. stencilBuffer.setClear(0);
  12624. enable(2929);
  12625. depthBuffer.setFunc(LessEqualDepth);
  12626. setFlipSided(false);
  12627. setCullFace(CullFaceBack);
  12628. enable(2884);
  12629. setBlending(NoBlending); //
  12630. function enable(id) {
  12631. if (enabledCapabilities[id] !== true) {
  12632. gl.enable(id);
  12633. enabledCapabilities[id] = true;
  12634. }
  12635. }
  12636. function disable(id) {
  12637. if (enabledCapabilities[id] !== false) {
  12638. gl.disable(id);
  12639. enabledCapabilities[id] = false;
  12640. }
  12641. }
  12642. function useProgram(program) {
  12643. if (currentProgram !== program) {
  12644. gl.useProgram(program);
  12645. currentProgram = program;
  12646. return true;
  12647. }
  12648. return false;
  12649. }
  12650. const equationToGL = {
  12651. [AddEquation]: 32774,
  12652. [SubtractEquation]: 32778,
  12653. [ReverseSubtractEquation]: 32779
  12654. };
  12655. if (isWebGL2) {
  12656. equationToGL[MinEquation] = 32775;
  12657. equationToGL[MaxEquation] = 32776;
  12658. } else {
  12659. const extension = extensions.get('EXT_blend_minmax');
  12660. if (extension !== null) {
  12661. equationToGL[MinEquation] = extension.MIN_EXT;
  12662. equationToGL[MaxEquation] = extension.MAX_EXT;
  12663. }
  12664. }
  12665. const factorToGL = {
  12666. [ZeroFactor]: 0,
  12667. [OneFactor]: 1,
  12668. [SrcColorFactor]: 768,
  12669. [SrcAlphaFactor]: 770,
  12670. [SrcAlphaSaturateFactor]: 776,
  12671. [DstColorFactor]: 774,
  12672. [DstAlphaFactor]: 772,
  12673. [OneMinusSrcColorFactor]: 769,
  12674. [OneMinusSrcAlphaFactor]: 771,
  12675. [OneMinusDstColorFactor]: 775,
  12676. [OneMinusDstAlphaFactor]: 773
  12677. };
  12678. function setBlending(blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha) {
  12679. if (blending === NoBlending) {
  12680. if (currentBlendingEnabled) {
  12681. disable(3042);
  12682. currentBlendingEnabled = false;
  12683. }
  12684. return;
  12685. }
  12686. if (!currentBlendingEnabled) {
  12687. enable(3042);
  12688. currentBlendingEnabled = true;
  12689. }
  12690. if (blending !== CustomBlending) {
  12691. if (blending !== currentBlending || premultipliedAlpha !== currentPremultipledAlpha) {
  12692. if (currentBlendEquation !== AddEquation || currentBlendEquationAlpha !== AddEquation) {
  12693. gl.blendEquation(32774);
  12694. currentBlendEquation = AddEquation;
  12695. currentBlendEquationAlpha = AddEquation;
  12696. }
  12697. if (premultipliedAlpha) {
  12698. switch (blending) {
  12699. case NormalBlending:
  12700. gl.blendFuncSeparate(1, 771, 1, 771);
  12701. break;
  12702. case AdditiveBlending:
  12703. gl.blendFunc(1, 1);
  12704. break;
  12705. case SubtractiveBlending:
  12706. gl.blendFuncSeparate(0, 0, 769, 771);
  12707. break;
  12708. case MultiplyBlending:
  12709. gl.blendFuncSeparate(0, 768, 0, 770);
  12710. break;
  12711. default:
  12712. console.error('THREE.WebGLState: Invalid blending: ', blending);
  12713. break;
  12714. }
  12715. } else {
  12716. switch (blending) {
  12717. case NormalBlending:
  12718. gl.blendFuncSeparate(770, 771, 1, 771);
  12719. break;
  12720. case AdditiveBlending:
  12721. gl.blendFunc(770, 1);
  12722. break;
  12723. case SubtractiveBlending:
  12724. gl.blendFunc(0, 769);
  12725. break;
  12726. case MultiplyBlending:
  12727. gl.blendFunc(0, 768);
  12728. break;
  12729. default:
  12730. console.error('THREE.WebGLState: Invalid blending: ', blending);
  12731. break;
  12732. }
  12733. }
  12734. currentBlendSrc = null;
  12735. currentBlendDst = null;
  12736. currentBlendSrcAlpha = null;
  12737. currentBlendDstAlpha = null;
  12738. currentBlending = blending;
  12739. currentPremultipledAlpha = premultipliedAlpha;
  12740. }
  12741. return;
  12742. } // custom blending
  12743. blendEquationAlpha = blendEquationAlpha || blendEquation;
  12744. blendSrcAlpha = blendSrcAlpha || blendSrc;
  12745. blendDstAlpha = blendDstAlpha || blendDst;
  12746. if (blendEquation !== currentBlendEquation || blendEquationAlpha !== currentBlendEquationAlpha) {
  12747. gl.blendEquationSeparate(equationToGL[blendEquation], equationToGL[blendEquationAlpha]);
  12748. currentBlendEquation = blendEquation;
  12749. currentBlendEquationAlpha = blendEquationAlpha;
  12750. }
  12751. if (blendSrc !== currentBlendSrc || blendDst !== currentBlendDst || blendSrcAlpha !== currentBlendSrcAlpha || blendDstAlpha !== currentBlendDstAlpha) {
  12752. gl.blendFuncSeparate(factorToGL[blendSrc], factorToGL[blendDst], factorToGL[blendSrcAlpha], factorToGL[blendDstAlpha]);
  12753. currentBlendSrc = blendSrc;
  12754. currentBlendDst = blendDst;
  12755. currentBlendSrcAlpha = blendSrcAlpha;
  12756. currentBlendDstAlpha = blendDstAlpha;
  12757. }
  12758. currentBlending = blending;
  12759. currentPremultipledAlpha = null;
  12760. }
  12761. function setMaterial(material, frontFaceCW) {
  12762. material.side === DoubleSide ? disable(2884) : enable(2884);
  12763. let flipSided = material.side === BackSide;
  12764. if (frontFaceCW) flipSided = !flipSided;
  12765. setFlipSided(flipSided);
  12766. material.blending === NormalBlending && material.transparent === false ? setBlending(NoBlending) : setBlending(material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha);
  12767. depthBuffer.setFunc(material.depthFunc);
  12768. depthBuffer.setTest(material.depthTest);
  12769. depthBuffer.setMask(material.depthWrite);
  12770. colorBuffer.setMask(material.colorWrite);
  12771. const stencilWrite = material.stencilWrite;
  12772. stencilBuffer.setTest(stencilWrite);
  12773. if (stencilWrite) {
  12774. stencilBuffer.setMask(material.stencilWriteMask);
  12775. stencilBuffer.setFunc(material.stencilFunc, material.stencilRef, material.stencilFuncMask);
  12776. stencilBuffer.setOp(material.stencilFail, material.stencilZFail, material.stencilZPass);
  12777. }
  12778. setPolygonOffset(material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits);
  12779. } //
  12780. function setFlipSided(flipSided) {
  12781. if (currentFlipSided !== flipSided) {
  12782. if (flipSided) {
  12783. gl.frontFace(2304);
  12784. } else {
  12785. gl.frontFace(2305);
  12786. }
  12787. currentFlipSided = flipSided;
  12788. }
  12789. }
  12790. function setCullFace(cullFace) {
  12791. if (cullFace !== CullFaceNone) {
  12792. enable(2884);
  12793. if (cullFace !== currentCullFace) {
  12794. if (cullFace === CullFaceBack) {
  12795. gl.cullFace(1029);
  12796. } else if (cullFace === CullFaceFront) {
  12797. gl.cullFace(1028);
  12798. } else {
  12799. gl.cullFace(1032);
  12800. }
  12801. }
  12802. } else {
  12803. disable(2884);
  12804. }
  12805. currentCullFace = cullFace;
  12806. }
  12807. function setLineWidth(width) {
  12808. if (width !== currentLineWidth) {
  12809. if (lineWidthAvailable) gl.lineWidth(width);
  12810. currentLineWidth = width;
  12811. }
  12812. }
  12813. function setPolygonOffset(polygonOffset, factor, units) {
  12814. if (polygonOffset) {
  12815. enable(32823);
  12816. if (currentPolygonOffsetFactor !== factor || currentPolygonOffsetUnits !== units) {
  12817. gl.polygonOffset(factor, units);
  12818. currentPolygonOffsetFactor = factor;
  12819. currentPolygonOffsetUnits = units;
  12820. }
  12821. } else {
  12822. disable(32823);
  12823. }
  12824. }
  12825. function setScissorTest(scissorTest) {
  12826. if (scissorTest) {
  12827. enable(3089);
  12828. } else {
  12829. disable(3089);
  12830. }
  12831. } // texture
  12832. function activeTexture(webglSlot) {
  12833. if (webglSlot === undefined) webglSlot = 33984 + maxTextures - 1;
  12834. if (currentTextureSlot !== webglSlot) {
  12835. gl.activeTexture(webglSlot);
  12836. currentTextureSlot = webglSlot;
  12837. }
  12838. }
  12839. function bindTexture(webglType, webglTexture) {
  12840. if (currentTextureSlot === null) {
  12841. activeTexture();
  12842. }
  12843. let boundTexture = currentBoundTextures[currentTextureSlot];
  12844. if (boundTexture === undefined) {
  12845. boundTexture = {
  12846. type: undefined,
  12847. texture: undefined
  12848. };
  12849. currentBoundTextures[currentTextureSlot] = boundTexture;
  12850. }
  12851. if (boundTexture.type !== webglType || boundTexture.texture !== webglTexture) {
  12852. gl.bindTexture(webglType, webglTexture || emptyTextures[webglType]);
  12853. boundTexture.type = webglType;
  12854. boundTexture.texture = webglTexture;
  12855. }
  12856. }
  12857. function unbindTexture() {
  12858. const boundTexture = currentBoundTextures[currentTextureSlot];
  12859. if (boundTexture !== undefined && boundTexture.type !== undefined) {
  12860. gl.bindTexture(boundTexture.type, null);
  12861. boundTexture.type = undefined;
  12862. boundTexture.texture = undefined;
  12863. }
  12864. }
  12865. function compressedTexImage2D() {
  12866. try {
  12867. gl.compressedTexImage2D.apply(gl, arguments);
  12868. } catch (error) {
  12869. console.error('THREE.WebGLState:', error);
  12870. }
  12871. }
  12872. function texImage2D() {
  12873. try {
  12874. gl.texImage2D.apply(gl, arguments);
  12875. } catch (error) {
  12876. console.error('THREE.WebGLState:', error);
  12877. }
  12878. }
  12879. function texImage3D() {
  12880. try {
  12881. gl.texImage3D.apply(gl, arguments);
  12882. } catch (error) {
  12883. console.error('THREE.WebGLState:', error);
  12884. }
  12885. } //
  12886. function scissor(scissor) {
  12887. if (currentScissor.equals(scissor) === false) {
  12888. gl.scissor(scissor.x, scissor.y, scissor.z, scissor.w);
  12889. currentScissor.copy(scissor);
  12890. }
  12891. }
  12892. function viewport(viewport) {
  12893. if (currentViewport.equals(viewport) === false) {
  12894. gl.viewport(viewport.x, viewport.y, viewport.z, viewport.w);
  12895. currentViewport.copy(viewport);
  12896. }
  12897. } //
  12898. function reset() {
  12899. enabledCapabilities = {};
  12900. currentTextureSlot = null;
  12901. currentBoundTextures = {};
  12902. currentProgram = null;
  12903. currentBlendingEnabled = null;
  12904. currentBlending = null;
  12905. currentBlendEquation = null;
  12906. currentBlendSrc = null;
  12907. currentBlendDst = null;
  12908. currentBlendEquationAlpha = null;
  12909. currentBlendSrcAlpha = null;
  12910. currentBlendDstAlpha = null;
  12911. currentPremultipledAlpha = false;
  12912. currentFlipSided = null;
  12913. currentCullFace = null;
  12914. currentLineWidth = null;
  12915. currentPolygonOffsetFactor = null;
  12916. currentPolygonOffsetUnits = null;
  12917. colorBuffer.reset();
  12918. depthBuffer.reset();
  12919. stencilBuffer.reset();
  12920. }
  12921. return {
  12922. buffers: {
  12923. color: colorBuffer,
  12924. depth: depthBuffer,
  12925. stencil: stencilBuffer
  12926. },
  12927. enable: enable,
  12928. disable: disable,
  12929. useProgram: useProgram,
  12930. setBlending: setBlending,
  12931. setMaterial: setMaterial,
  12932. setFlipSided: setFlipSided,
  12933. setCullFace: setCullFace,
  12934. setLineWidth: setLineWidth,
  12935. setPolygonOffset: setPolygonOffset,
  12936. setScissorTest: setScissorTest,
  12937. activeTexture: activeTexture,
  12938. bindTexture: bindTexture,
  12939. unbindTexture: unbindTexture,
  12940. compressedTexImage2D: compressedTexImage2D,
  12941. texImage2D: texImage2D,
  12942. texImage3D: texImage3D,
  12943. scissor: scissor,
  12944. viewport: viewport,
  12945. reset: reset
  12946. };
  12947. }
  12948. function WebGLTextures(_gl, extensions, state, properties, capabilities, utils, info) {
  12949. const isWebGL2 = capabilities.isWebGL2;
  12950. const maxTextures = capabilities.maxTextures;
  12951. const maxCubemapSize = capabilities.maxCubemapSize;
  12952. const maxTextureSize = capabilities.maxTextureSize;
  12953. const maxSamples = capabilities.maxSamples;
  12954. const _videoTextures = new WeakMap();
  12955. let _canvas; // cordova iOS (as of 5.0) still uses UIWebView, which provides OffscreenCanvas,
  12956. // also OffscreenCanvas.getContext("webgl"), but not OffscreenCanvas.getContext("2d")!
  12957. // Some implementations may only implement OffscreenCanvas partially (e.g. lacking 2d).
  12958. let useOffscreenCanvas = false;
  12959. try {
  12960. useOffscreenCanvas = typeof OffscreenCanvas !== 'undefined' && new OffscreenCanvas(1, 1).getContext("2d") !== null;
  12961. } catch (err) {// Ignore any errors
  12962. }
  12963. function createCanvas(width, height) {
  12964. // Use OffscreenCanvas when available. Specially needed in web workers
  12965. return useOffscreenCanvas ? new OffscreenCanvas(width, height) : document.createElementNS('http://www.w3.org/1999/xhtml', 'canvas');
  12966. }
  12967. function resizeImage(image, needsPowerOfTwo, needsNewCanvas, maxSize) {
  12968. let scale = 1; // handle case if texture exceeds max size
  12969. if (image.width > maxSize || image.height > maxSize) {
  12970. scale = maxSize / Math.max(image.width, image.height);
  12971. } // only perform resize if necessary
  12972. if (scale < 1 || needsPowerOfTwo === true) {
  12973. // only perform resize for certain image types
  12974. if (typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement || typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement || typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap) {
  12975. const floor = needsPowerOfTwo ? MathUtils.floorPowerOfTwo : Math.floor;
  12976. const width = floor(scale * image.width);
  12977. const height = floor(scale * image.height);
  12978. if (_canvas === undefined) _canvas = createCanvas(width, height); // cube textures can't reuse the same canvas
  12979. const canvas = needsNewCanvas ? createCanvas(width, height) : _canvas;
  12980. canvas.width = width;
  12981. canvas.height = height;
  12982. const context = canvas.getContext('2d');
  12983. context.drawImage(image, 0, 0, width, height);
  12984. console.warn('THREE.WebGLRenderer: Texture has been resized from (' + image.width + 'x' + image.height + ') to (' + width + 'x' + height + ').');
  12985. return canvas;
  12986. } else {
  12987. if ('data' in image) {
  12988. console.warn('THREE.WebGLRenderer: Image in DataTexture is too big (' + image.width + 'x' + image.height + ').');
  12989. }
  12990. return image;
  12991. }
  12992. }
  12993. return image;
  12994. }
  12995. function isPowerOfTwo(image) {
  12996. return MathUtils.isPowerOfTwo(image.width) && MathUtils.isPowerOfTwo(image.height);
  12997. }
  12998. function textureNeedsPowerOfTwo(texture) {
  12999. if (isWebGL2) return false;
  13000. return texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping || texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter;
  13001. }
  13002. function textureNeedsGenerateMipmaps(texture, supportsMips) {
  13003. return texture.generateMipmaps && supportsMips && texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter;
  13004. }
  13005. function generateMipmap(target, texture, width, height) {
  13006. _gl.generateMipmap(target);
  13007. const textureProperties = properties.get(texture); // Note: Math.log( x ) * Math.LOG2E used instead of Math.log2( x ) which is not supported by IE11
  13008. textureProperties.__maxMipLevel = Math.log(Math.max(width, height)) * Math.LOG2E;
  13009. }
  13010. function getInternalFormat(internalFormatName, glFormat, glType) {
  13011. if (isWebGL2 === false) return glFormat;
  13012. if (internalFormatName !== null) {
  13013. if (_gl[internalFormatName] !== undefined) return _gl[internalFormatName];
  13014. console.warn('THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\'');
  13015. }
  13016. let internalFormat = glFormat;
  13017. if (glFormat === 6403) {
  13018. if (glType === 5126) internalFormat = 33326;
  13019. if (glType === 5131) internalFormat = 33325;
  13020. if (glType === 5121) internalFormat = 33321;
  13021. }
  13022. if (glFormat === 6407) {
  13023. if (glType === 5126) internalFormat = 34837;
  13024. if (glType === 5131) internalFormat = 34843;
  13025. if (glType === 5121) internalFormat = 32849;
  13026. }
  13027. if (glFormat === 6408) {
  13028. if (glType === 5126) internalFormat = 34836;
  13029. if (glType === 5131) internalFormat = 34842;
  13030. if (glType === 5121) internalFormat = 32856;
  13031. }
  13032. if (internalFormat === 33325 || internalFormat === 33326 || internalFormat === 34842 || internalFormat === 34836) {
  13033. extensions.get('EXT_color_buffer_float');
  13034. }
  13035. return internalFormat;
  13036. } // Fallback filters for non-power-of-2 textures
  13037. function filterFallback(f) {
  13038. if (f === NearestFilter || f === NearestMipmapNearestFilter || f === NearestMipmapLinearFilter) {
  13039. return 9728;
  13040. }
  13041. return 9729;
  13042. } //
  13043. function onTextureDispose(event) {
  13044. const texture = event.target;
  13045. texture.removeEventListener('dispose', onTextureDispose);
  13046. deallocateTexture(texture);
  13047. if (texture.isVideoTexture) {
  13048. _videoTextures.delete(texture);
  13049. }
  13050. info.memory.textures--;
  13051. }
  13052. function onRenderTargetDispose(event) {
  13053. const renderTarget = event.target;
  13054. renderTarget.removeEventListener('dispose', onRenderTargetDispose);
  13055. deallocateRenderTarget(renderTarget);
  13056. info.memory.textures--;
  13057. } //
  13058. function deallocateTexture(texture) {
  13059. const textureProperties = properties.get(texture);
  13060. if (textureProperties.__webglInit === undefined) return;
  13061. _gl.deleteTexture(textureProperties.__webglTexture);
  13062. properties.remove(texture);
  13063. }
  13064. function deallocateRenderTarget(renderTarget) {
  13065. const renderTargetProperties = properties.get(renderTarget);
  13066. const textureProperties = properties.get(renderTarget.texture);
  13067. if (!renderTarget) return;
  13068. if (textureProperties.__webglTexture !== undefined) {
  13069. _gl.deleteTexture(textureProperties.__webglTexture);
  13070. }
  13071. if (renderTarget.depthTexture) {
  13072. renderTarget.depthTexture.dispose();
  13073. }
  13074. if (renderTarget.isWebGLCubeRenderTarget) {
  13075. for (let i = 0; i < 6; i++) {
  13076. _gl.deleteFramebuffer(renderTargetProperties.__webglFramebuffer[i]);
  13077. if (renderTargetProperties.__webglDepthbuffer) _gl.deleteRenderbuffer(renderTargetProperties.__webglDepthbuffer[i]);
  13078. }
  13079. } else {
  13080. _gl.deleteFramebuffer(renderTargetProperties.__webglFramebuffer);
  13081. if (renderTargetProperties.__webglDepthbuffer) _gl.deleteRenderbuffer(renderTargetProperties.__webglDepthbuffer);
  13082. if (renderTargetProperties.__webglMultisampledFramebuffer) _gl.deleteFramebuffer(renderTargetProperties.__webglMultisampledFramebuffer);
  13083. if (renderTargetProperties.__webglColorRenderbuffer) _gl.deleteRenderbuffer(renderTargetProperties.__webglColorRenderbuffer);
  13084. if (renderTargetProperties.__webglDepthRenderbuffer) _gl.deleteRenderbuffer(renderTargetProperties.__webglDepthRenderbuffer);
  13085. }
  13086. properties.remove(renderTarget.texture);
  13087. properties.remove(renderTarget);
  13088. } //
  13089. let textureUnits = 0;
  13090. function resetTextureUnits() {
  13091. textureUnits = 0;
  13092. }
  13093. function allocateTextureUnit() {
  13094. const textureUnit = textureUnits;
  13095. if (textureUnit >= maxTextures) {
  13096. console.warn('THREE.WebGLTextures: Trying to use ' + textureUnit + ' texture units while this GPU supports only ' + maxTextures);
  13097. }
  13098. textureUnits += 1;
  13099. return textureUnit;
  13100. } //
  13101. function setTexture2D(texture, slot) {
  13102. const textureProperties = properties.get(texture);
  13103. if (texture.isVideoTexture) updateVideoTexture(texture);
  13104. if (texture.version > 0 && textureProperties.__version !== texture.version) {
  13105. const image = texture.image;
  13106. if (image === undefined) {
  13107. console.warn('THREE.WebGLRenderer: Texture marked for update but image is undefined');
  13108. } else if (image.complete === false) {
  13109. console.warn('THREE.WebGLRenderer: Texture marked for update but image is incomplete');
  13110. } else {
  13111. uploadTexture(textureProperties, texture, slot);
  13112. return;
  13113. }
  13114. }
  13115. state.activeTexture(33984 + slot);
  13116. state.bindTexture(3553, textureProperties.__webglTexture);
  13117. }
  13118. function setTexture2DArray(texture, slot) {
  13119. const textureProperties = properties.get(texture);
  13120. if (texture.version > 0 && textureProperties.__version !== texture.version) {
  13121. uploadTexture(textureProperties, texture, slot);
  13122. return;
  13123. }
  13124. state.activeTexture(33984 + slot);
  13125. state.bindTexture(35866, textureProperties.__webglTexture);
  13126. }
  13127. function setTexture3D(texture, slot) {
  13128. const textureProperties = properties.get(texture);
  13129. if (texture.version > 0 && textureProperties.__version !== texture.version) {
  13130. uploadTexture(textureProperties, texture, slot);
  13131. return;
  13132. }
  13133. state.activeTexture(33984 + slot);
  13134. state.bindTexture(32879, textureProperties.__webglTexture);
  13135. }
  13136. function setTextureCube(texture, slot) {
  13137. const textureProperties = properties.get(texture);
  13138. if (texture.version > 0 && textureProperties.__version !== texture.version) {
  13139. uploadCubeTexture(textureProperties, texture, slot);
  13140. return;
  13141. }
  13142. state.activeTexture(33984 + slot);
  13143. state.bindTexture(34067, textureProperties.__webglTexture);
  13144. }
  13145. const wrappingToGL = {
  13146. [RepeatWrapping]: 10497,
  13147. [ClampToEdgeWrapping]: 33071,
  13148. [MirroredRepeatWrapping]: 33648
  13149. };
  13150. const filterToGL = {
  13151. [NearestFilter]: 9728,
  13152. [NearestMipmapNearestFilter]: 9984,
  13153. [NearestMipmapLinearFilter]: 9986,
  13154. [LinearFilter]: 9729,
  13155. [LinearMipmapNearestFilter]: 9985,
  13156. [LinearMipmapLinearFilter]: 9987
  13157. };
  13158. function setTextureParameters(textureType, texture, supportsMips) {
  13159. if (supportsMips) {
  13160. _gl.texParameteri(textureType, 10242, wrappingToGL[texture.wrapS]);
  13161. _gl.texParameteri(textureType, 10243, wrappingToGL[texture.wrapT]);
  13162. if (textureType === 32879 || textureType === 35866) {
  13163. _gl.texParameteri(textureType, 32882, wrappingToGL[texture.wrapR]);
  13164. }
  13165. _gl.texParameteri(textureType, 10240, filterToGL[texture.magFilter]);
  13166. _gl.texParameteri(textureType, 10241, filterToGL[texture.minFilter]);
  13167. } else {
  13168. _gl.texParameteri(textureType, 10242, 33071);
  13169. _gl.texParameteri(textureType, 10243, 33071);
  13170. if (textureType === 32879 || textureType === 35866) {
  13171. _gl.texParameteri(textureType, 32882, 33071);
  13172. }
  13173. if (texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping) {
  13174. console.warn('THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping.');
  13175. }
  13176. _gl.texParameteri(textureType, 10240, filterFallback(texture.magFilter));
  13177. _gl.texParameteri(textureType, 10241, filterFallback(texture.minFilter));
  13178. if (texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter) {
  13179. console.warn('THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.');
  13180. }
  13181. }
  13182. const extension = extensions.get('EXT_texture_filter_anisotropic');
  13183. if (extension) {
  13184. if (texture.type === FloatType && extensions.get('OES_texture_float_linear') === null) return;
  13185. if (texture.type === HalfFloatType && (isWebGL2 || extensions.get('OES_texture_half_float_linear')) === null) return;
  13186. if (texture.anisotropy > 1 || properties.get(texture).__currentAnisotropy) {
  13187. _gl.texParameterf(textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(texture.anisotropy, capabilities.getMaxAnisotropy()));
  13188. properties.get(texture).__currentAnisotropy = texture.anisotropy;
  13189. }
  13190. }
  13191. }
  13192. function initTexture(textureProperties, texture) {
  13193. if (textureProperties.__webglInit === undefined) {
  13194. textureProperties.__webglInit = true;
  13195. texture.addEventListener('dispose', onTextureDispose);
  13196. textureProperties.__webglTexture = _gl.createTexture();
  13197. info.memory.textures++;
  13198. }
  13199. }
  13200. function uploadTexture(textureProperties, texture, slot) {
  13201. let textureType = 3553;
  13202. if (texture.isDataTexture2DArray) textureType = 35866;
  13203. if (texture.isDataTexture3D) textureType = 32879;
  13204. initTexture(textureProperties, texture);
  13205. state.activeTexture(33984 + slot);
  13206. state.bindTexture(textureType, textureProperties.__webglTexture);
  13207. _gl.pixelStorei(37440, texture.flipY);
  13208. _gl.pixelStorei(37441, texture.premultiplyAlpha);
  13209. _gl.pixelStorei(3317, texture.unpackAlignment);
  13210. const needsPowerOfTwo = textureNeedsPowerOfTwo(texture) && isPowerOfTwo(texture.image) === false;
  13211. const image = resizeImage(texture.image, needsPowerOfTwo, false, maxTextureSize);
  13212. const supportsMips = isPowerOfTwo(image) || isWebGL2,
  13213. glFormat = utils.convert(texture.format);
  13214. let glType = utils.convert(texture.type),
  13215. glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType);
  13216. setTextureParameters(textureType, texture, supportsMips);
  13217. let mipmap;
  13218. const mipmaps = texture.mipmaps;
  13219. if (texture.isDepthTexture) {
  13220. // populate depth texture with dummy data
  13221. glInternalFormat = 6402;
  13222. if (isWebGL2) {
  13223. if (texture.type === FloatType) {
  13224. glInternalFormat = 36012;
  13225. } else if (texture.type === UnsignedIntType) {
  13226. glInternalFormat = 33190;
  13227. } else if (texture.type === UnsignedInt248Type) {
  13228. glInternalFormat = 35056;
  13229. } else {
  13230. glInternalFormat = 33189; // WebGL2 requires sized internalformat for glTexImage2D
  13231. }
  13232. } else {
  13233. if (texture.type === FloatType) {
  13234. console.error('WebGLRenderer: Floating point depth texture requires WebGL2.');
  13235. }
  13236. } // validation checks for WebGL 1
  13237. if (texture.format === DepthFormat && glInternalFormat === 6402) {
  13238. // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  13239. // DEPTH_COMPONENT and type is not UNSIGNED_SHORT or UNSIGNED_INT
  13240. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  13241. if (texture.type !== UnsignedShortType && texture.type !== UnsignedIntType) {
  13242. console.warn('THREE.WebGLRenderer: Use UnsignedShortType or UnsignedIntType for DepthFormat DepthTexture.');
  13243. texture.type = UnsignedShortType;
  13244. glType = utils.convert(texture.type);
  13245. }
  13246. }
  13247. if (texture.format === DepthStencilFormat && glInternalFormat === 6402) {
  13248. // Depth stencil textures need the DEPTH_STENCIL internal format
  13249. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  13250. glInternalFormat = 34041; // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  13251. // DEPTH_STENCIL and type is not UNSIGNED_INT_24_8_WEBGL.
  13252. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  13253. if (texture.type !== UnsignedInt248Type) {
  13254. console.warn('THREE.WebGLRenderer: Use UnsignedInt248Type for DepthStencilFormat DepthTexture.');
  13255. texture.type = UnsignedInt248Type;
  13256. glType = utils.convert(texture.type);
  13257. }
  13258. } //
  13259. state.texImage2D(3553, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, null);
  13260. } else if (texture.isDataTexture) {
  13261. // use manually created mipmaps if available
  13262. // if there are no manual mipmaps
  13263. // set 0 level mipmap and then use GL to generate other mipmap levels
  13264. if (mipmaps.length > 0 && supportsMips) {
  13265. for (let i = 0, il = mipmaps.length; i < il; i++) {
  13266. mipmap = mipmaps[i];
  13267. state.texImage2D(3553, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data);
  13268. }
  13269. texture.generateMipmaps = false;
  13270. textureProperties.__maxMipLevel = mipmaps.length - 1;
  13271. } else {
  13272. state.texImage2D(3553, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, image.data);
  13273. textureProperties.__maxMipLevel = 0;
  13274. }
  13275. } else if (texture.isCompressedTexture) {
  13276. for (let i = 0, il = mipmaps.length; i < il; i++) {
  13277. mipmap = mipmaps[i];
  13278. if (texture.format !== RGBAFormat && texture.format !== RGBFormat) {
  13279. if (glFormat !== null) {
  13280. state.compressedTexImage2D(3553, i, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data);
  13281. } else {
  13282. console.warn('THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()');
  13283. }
  13284. } else {
  13285. state.texImage2D(3553, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data);
  13286. }
  13287. }
  13288. textureProperties.__maxMipLevel = mipmaps.length - 1;
  13289. } else if (texture.isDataTexture2DArray) {
  13290. state.texImage3D(35866, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data);
  13291. textureProperties.__maxMipLevel = 0;
  13292. } else if (texture.isDataTexture3D) {
  13293. state.texImage3D(32879, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data);
  13294. textureProperties.__maxMipLevel = 0;
  13295. } else {
  13296. // regular Texture (image, video, canvas)
  13297. // use manually created mipmaps if available
  13298. // if there are no manual mipmaps
  13299. // set 0 level mipmap and then use GL to generate other mipmap levels
  13300. if (mipmaps.length > 0 && supportsMips) {
  13301. for (let i = 0, il = mipmaps.length; i < il; i++) {
  13302. mipmap = mipmaps[i];
  13303. state.texImage2D(3553, i, glInternalFormat, glFormat, glType, mipmap);
  13304. }
  13305. texture.generateMipmaps = false;
  13306. textureProperties.__maxMipLevel = mipmaps.length - 1;
  13307. } else {
  13308. state.texImage2D(3553, 0, glInternalFormat, glFormat, glType, image);
  13309. textureProperties.__maxMipLevel = 0;
  13310. }
  13311. }
  13312. if (textureNeedsGenerateMipmaps(texture, supportsMips)) {
  13313. generateMipmap(textureType, texture, image.width, image.height);
  13314. }
  13315. textureProperties.__version = texture.version;
  13316. if (texture.onUpdate) texture.onUpdate(texture);
  13317. }
  13318. function uploadCubeTexture(textureProperties, texture, slot) {
  13319. if (texture.image.length !== 6) return;
  13320. initTexture(textureProperties, texture);
  13321. state.activeTexture(33984 + slot);
  13322. state.bindTexture(34067, textureProperties.__webglTexture);
  13323. _gl.pixelStorei(37440, texture.flipY);
  13324. const isCompressed = texture && (texture.isCompressedTexture || texture.image[0].isCompressedTexture);
  13325. const isDataTexture = texture.image[0] && texture.image[0].isDataTexture;
  13326. const cubeImage = [];
  13327. for (let i = 0; i < 6; i++) {
  13328. if (!isCompressed && !isDataTexture) {
  13329. cubeImage[i] = resizeImage(texture.image[i], false, true, maxCubemapSize);
  13330. } else {
  13331. cubeImage[i] = isDataTexture ? texture.image[i].image : texture.image[i];
  13332. }
  13333. }
  13334. const image = cubeImage[0],
  13335. supportsMips = isPowerOfTwo(image) || isWebGL2,
  13336. glFormat = utils.convert(texture.format),
  13337. glType = utils.convert(texture.type),
  13338. glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType);
  13339. setTextureParameters(34067, texture, supportsMips);
  13340. let mipmaps;
  13341. if (isCompressed) {
  13342. for (let i = 0; i < 6; i++) {
  13343. mipmaps = cubeImage[i].mipmaps;
  13344. for (let j = 0; j < mipmaps.length; j++) {
  13345. const mipmap = mipmaps[j];
  13346. if (texture.format !== RGBAFormat && texture.format !== RGBFormat) {
  13347. if (glFormat !== null) {
  13348. state.compressedTexImage2D(34069 + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data);
  13349. } else {
  13350. console.warn('THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()');
  13351. }
  13352. } else {
  13353. state.texImage2D(34069 + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data);
  13354. }
  13355. }
  13356. }
  13357. textureProperties.__maxMipLevel = mipmaps.length - 1;
  13358. } else {
  13359. mipmaps = texture.mipmaps;
  13360. for (let i = 0; i < 6; i++) {
  13361. if (isDataTexture) {
  13362. state.texImage2D(34069 + i, 0, glInternalFormat, cubeImage[i].width, cubeImage[i].height, 0, glFormat, glType, cubeImage[i].data);
  13363. for (let j = 0; j < mipmaps.length; j++) {
  13364. const mipmap = mipmaps[j];
  13365. const mipmapImage = mipmap.image[i].image;
  13366. state.texImage2D(34069 + i, j + 1, glInternalFormat, mipmapImage.width, mipmapImage.height, 0, glFormat, glType, mipmapImage.data);
  13367. }
  13368. } else {
  13369. state.texImage2D(34069 + i, 0, glInternalFormat, glFormat, glType, cubeImage[i]);
  13370. for (let j = 0; j < mipmaps.length; j++) {
  13371. const mipmap = mipmaps[j];
  13372. state.texImage2D(34069 + i, j + 1, glInternalFormat, glFormat, glType, mipmap.image[i]);
  13373. }
  13374. }
  13375. }
  13376. textureProperties.__maxMipLevel = mipmaps.length;
  13377. }
  13378. if (textureNeedsGenerateMipmaps(texture, supportsMips)) {
  13379. // We assume images for cube map have the same size.
  13380. generateMipmap(34067, texture, image.width, image.height);
  13381. }
  13382. textureProperties.__version = texture.version;
  13383. if (texture.onUpdate) texture.onUpdate(texture);
  13384. } // Render targets
  13385. // Setup storage for target texture and bind it to correct framebuffer
  13386. function setupFrameBufferTexture(framebuffer, renderTarget, attachment, textureTarget) {
  13387. const glFormat = utils.convert(renderTarget.texture.format);
  13388. const glType = utils.convert(renderTarget.texture.type);
  13389. const glInternalFormat = getInternalFormat(renderTarget.texture.internalFormat, glFormat, glType);
  13390. state.texImage2D(textureTarget, 0, glInternalFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null);
  13391. _gl.bindFramebuffer(36160, framebuffer);
  13392. _gl.framebufferTexture2D(36160, attachment, textureTarget, properties.get(renderTarget.texture).__webglTexture, 0);
  13393. _gl.bindFramebuffer(36160, null);
  13394. } // Setup storage for internal depth/stencil buffers and bind to correct framebuffer
  13395. function setupRenderBufferStorage(renderbuffer, renderTarget, isMultisample) {
  13396. _gl.bindRenderbuffer(36161, renderbuffer);
  13397. if (renderTarget.depthBuffer && !renderTarget.stencilBuffer) {
  13398. let glInternalFormat = 33189;
  13399. if (isMultisample) {
  13400. const depthTexture = renderTarget.depthTexture;
  13401. if (depthTexture && depthTexture.isDepthTexture) {
  13402. if (depthTexture.type === FloatType) {
  13403. glInternalFormat = 36012;
  13404. } else if (depthTexture.type === UnsignedIntType) {
  13405. glInternalFormat = 33190;
  13406. }
  13407. }
  13408. const samples = getRenderTargetSamples(renderTarget);
  13409. _gl.renderbufferStorageMultisample(36161, samples, glInternalFormat, renderTarget.width, renderTarget.height);
  13410. } else {
  13411. _gl.renderbufferStorage(36161, glInternalFormat, renderTarget.width, renderTarget.height);
  13412. }
  13413. _gl.framebufferRenderbuffer(36160, 36096, 36161, renderbuffer);
  13414. } else if (renderTarget.depthBuffer && renderTarget.stencilBuffer) {
  13415. if (isMultisample) {
  13416. const samples = getRenderTargetSamples(renderTarget);
  13417. _gl.renderbufferStorageMultisample(36161, samples, 35056, renderTarget.width, renderTarget.height);
  13418. } else {
  13419. _gl.renderbufferStorage(36161, 34041, renderTarget.width, renderTarget.height);
  13420. }
  13421. _gl.framebufferRenderbuffer(36160, 33306, 36161, renderbuffer);
  13422. } else {
  13423. const glFormat = utils.convert(renderTarget.texture.format);
  13424. const glType = utils.convert(renderTarget.texture.type);
  13425. const glInternalFormat = getInternalFormat(renderTarget.texture.internalFormat, glFormat, glType);
  13426. if (isMultisample) {
  13427. const samples = getRenderTargetSamples(renderTarget);
  13428. _gl.renderbufferStorageMultisample(36161, samples, glInternalFormat, renderTarget.width, renderTarget.height);
  13429. } else {
  13430. _gl.renderbufferStorage(36161, glInternalFormat, renderTarget.width, renderTarget.height);
  13431. }
  13432. }
  13433. _gl.bindRenderbuffer(36161, null);
  13434. } // Setup resources for a Depth Texture for a FBO (needs an extension)
  13435. function setupDepthTexture(framebuffer, renderTarget) {
  13436. const isCube = renderTarget && renderTarget.isWebGLCubeRenderTarget;
  13437. if (isCube) throw new Error('Depth Texture with cube render targets is not supported');
  13438. _gl.bindFramebuffer(36160, framebuffer);
  13439. if (!(renderTarget.depthTexture && renderTarget.depthTexture.isDepthTexture)) {
  13440. throw new Error('renderTarget.depthTexture must be an instance of THREE.DepthTexture');
  13441. } // upload an empty depth texture with framebuffer size
  13442. if (!properties.get(renderTarget.depthTexture).__webglTexture || renderTarget.depthTexture.image.width !== renderTarget.width || renderTarget.depthTexture.image.height !== renderTarget.height) {
  13443. renderTarget.depthTexture.image.width = renderTarget.width;
  13444. renderTarget.depthTexture.image.height = renderTarget.height;
  13445. renderTarget.depthTexture.needsUpdate = true;
  13446. }
  13447. setTexture2D(renderTarget.depthTexture, 0);
  13448. const webglDepthTexture = properties.get(renderTarget.depthTexture).__webglTexture;
  13449. if (renderTarget.depthTexture.format === DepthFormat) {
  13450. _gl.framebufferTexture2D(36160, 36096, 3553, webglDepthTexture, 0);
  13451. } else if (renderTarget.depthTexture.format === DepthStencilFormat) {
  13452. _gl.framebufferTexture2D(36160, 33306, 3553, webglDepthTexture, 0);
  13453. } else {
  13454. throw new Error('Unknown depthTexture format');
  13455. }
  13456. } // Setup GL resources for a non-texture depth buffer
  13457. function setupDepthRenderbuffer(renderTarget) {
  13458. const renderTargetProperties = properties.get(renderTarget);
  13459. const isCube = renderTarget.isWebGLCubeRenderTarget === true;
  13460. if (renderTarget.depthTexture) {
  13461. if (isCube) throw new Error('target.depthTexture not supported in Cube render targets');
  13462. setupDepthTexture(renderTargetProperties.__webglFramebuffer, renderTarget);
  13463. } else {
  13464. if (isCube) {
  13465. renderTargetProperties.__webglDepthbuffer = [];
  13466. for (let i = 0; i < 6; i++) {
  13467. _gl.bindFramebuffer(36160, renderTargetProperties.__webglFramebuffer[i]);
  13468. renderTargetProperties.__webglDepthbuffer[i] = _gl.createRenderbuffer();
  13469. setupRenderBufferStorage(renderTargetProperties.__webglDepthbuffer[i], renderTarget, false);
  13470. }
  13471. } else {
  13472. _gl.bindFramebuffer(36160, renderTargetProperties.__webglFramebuffer);
  13473. renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer();
  13474. setupRenderBufferStorage(renderTargetProperties.__webglDepthbuffer, renderTarget, false);
  13475. }
  13476. }
  13477. _gl.bindFramebuffer(36160, null);
  13478. } // Set up GL resources for the render target
  13479. function setupRenderTarget(renderTarget) {
  13480. const renderTargetProperties = properties.get(renderTarget);
  13481. const textureProperties = properties.get(renderTarget.texture);
  13482. renderTarget.addEventListener('dispose', onRenderTargetDispose);
  13483. textureProperties.__webglTexture = _gl.createTexture();
  13484. info.memory.textures++;
  13485. const isCube = renderTarget.isWebGLCubeRenderTarget === true;
  13486. const isMultisample = renderTarget.isWebGLMultisampleRenderTarget === true;
  13487. const supportsMips = isPowerOfTwo(renderTarget) || isWebGL2; // Handles WebGL2 RGBFormat fallback - #18858
  13488. if (isWebGL2 && renderTarget.texture.format === RGBFormat && (renderTarget.texture.type === FloatType || renderTarget.texture.type === HalfFloatType)) {
  13489. renderTarget.texture.format = RGBAFormat;
  13490. console.warn('THREE.WebGLRenderer: Rendering to textures with RGB format is not supported. Using RGBA format instead.');
  13491. } // Setup framebuffer
  13492. if (isCube) {
  13493. renderTargetProperties.__webglFramebuffer = [];
  13494. for (let i = 0; i < 6; i++) {
  13495. renderTargetProperties.__webglFramebuffer[i] = _gl.createFramebuffer();
  13496. }
  13497. } else {
  13498. renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer();
  13499. if (isMultisample) {
  13500. if (isWebGL2) {
  13501. renderTargetProperties.__webglMultisampledFramebuffer = _gl.createFramebuffer();
  13502. renderTargetProperties.__webglColorRenderbuffer = _gl.createRenderbuffer();
  13503. _gl.bindRenderbuffer(36161, renderTargetProperties.__webglColorRenderbuffer);
  13504. const glFormat = utils.convert(renderTarget.texture.format);
  13505. const glType = utils.convert(renderTarget.texture.type);
  13506. const glInternalFormat = getInternalFormat(renderTarget.texture.internalFormat, glFormat, glType);
  13507. const samples = getRenderTargetSamples(renderTarget);
  13508. _gl.renderbufferStorageMultisample(36161, samples, glInternalFormat, renderTarget.width, renderTarget.height);
  13509. _gl.bindFramebuffer(36160, renderTargetProperties.__webglMultisampledFramebuffer);
  13510. _gl.framebufferRenderbuffer(36160, 36064, 36161, renderTargetProperties.__webglColorRenderbuffer);
  13511. _gl.bindRenderbuffer(36161, null);
  13512. if (renderTarget.depthBuffer) {
  13513. renderTargetProperties.__webglDepthRenderbuffer = _gl.createRenderbuffer();
  13514. setupRenderBufferStorage(renderTargetProperties.__webglDepthRenderbuffer, renderTarget, true);
  13515. }
  13516. _gl.bindFramebuffer(36160, null);
  13517. } else {
  13518. console.warn('THREE.WebGLRenderer: WebGLMultisampleRenderTarget can only be used with WebGL2.');
  13519. }
  13520. }
  13521. } // Setup color buffer
  13522. if (isCube) {
  13523. state.bindTexture(34067, textureProperties.__webglTexture);
  13524. setTextureParameters(34067, renderTarget.texture, supportsMips);
  13525. for (let i = 0; i < 6; i++) {
  13526. setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer[i], renderTarget, 36064, 34069 + i);
  13527. }
  13528. if (textureNeedsGenerateMipmaps(renderTarget.texture, supportsMips)) {
  13529. generateMipmap(34067, renderTarget.texture, renderTarget.width, renderTarget.height);
  13530. }
  13531. state.bindTexture(34067, null);
  13532. } else {
  13533. state.bindTexture(3553, textureProperties.__webglTexture);
  13534. setTextureParameters(3553, renderTarget.texture, supportsMips);
  13535. setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer, renderTarget, 36064, 3553);
  13536. if (textureNeedsGenerateMipmaps(renderTarget.texture, supportsMips)) {
  13537. generateMipmap(3553, renderTarget.texture, renderTarget.width, renderTarget.height);
  13538. }
  13539. state.bindTexture(3553, null);
  13540. } // Setup depth and stencil buffers
  13541. if (renderTarget.depthBuffer) {
  13542. setupDepthRenderbuffer(renderTarget);
  13543. }
  13544. }
  13545. function updateRenderTargetMipmap(renderTarget) {
  13546. const texture = renderTarget.texture;
  13547. const supportsMips = isPowerOfTwo(renderTarget) || isWebGL2;
  13548. if (textureNeedsGenerateMipmaps(texture, supportsMips)) {
  13549. const target = renderTarget.isWebGLCubeRenderTarget ? 34067 : 3553;
  13550. const webglTexture = properties.get(texture).__webglTexture;
  13551. state.bindTexture(target, webglTexture);
  13552. generateMipmap(target, texture, renderTarget.width, renderTarget.height);
  13553. state.bindTexture(target, null);
  13554. }
  13555. }
  13556. function updateMultisampleRenderTarget(renderTarget) {
  13557. if (renderTarget.isWebGLMultisampleRenderTarget) {
  13558. if (isWebGL2) {
  13559. const renderTargetProperties = properties.get(renderTarget);
  13560. _gl.bindFramebuffer(36008, renderTargetProperties.__webglMultisampledFramebuffer);
  13561. _gl.bindFramebuffer(36009, renderTargetProperties.__webglFramebuffer);
  13562. const width = renderTarget.width;
  13563. const height = renderTarget.height;
  13564. let mask = 16384;
  13565. if (renderTarget.depthBuffer) mask |= 256;
  13566. if (renderTarget.stencilBuffer) mask |= 1024;
  13567. _gl.blitFramebuffer(0, 0, width, height, 0, 0, width, height, mask, 9728);
  13568. _gl.bindFramebuffer(36160, renderTargetProperties.__webglMultisampledFramebuffer); // see #18905
  13569. } else {
  13570. console.warn('THREE.WebGLRenderer: WebGLMultisampleRenderTarget can only be used with WebGL2.');
  13571. }
  13572. }
  13573. }
  13574. function getRenderTargetSamples(renderTarget) {
  13575. return isWebGL2 && renderTarget.isWebGLMultisampleRenderTarget ? Math.min(maxSamples, renderTarget.samples) : 0;
  13576. }
  13577. function updateVideoTexture(texture) {
  13578. const frame = info.render.frame; // Check the last frame we updated the VideoTexture
  13579. if (_videoTextures.get(texture) !== frame) {
  13580. _videoTextures.set(texture, frame);
  13581. texture.update();
  13582. }
  13583. } // backwards compatibility
  13584. let warnedTexture2D = false;
  13585. let warnedTextureCube = false;
  13586. function safeSetTexture2D(texture, slot) {
  13587. if (texture && texture.isWebGLRenderTarget) {
  13588. if (warnedTexture2D === false) {
  13589. console.warn("THREE.WebGLTextures.safeSetTexture2D: don't use render targets as textures. Use their .texture property instead.");
  13590. warnedTexture2D = true;
  13591. }
  13592. texture = texture.texture;
  13593. }
  13594. setTexture2D(texture, slot);
  13595. }
  13596. function safeSetTextureCube(texture, slot) {
  13597. if (texture && texture.isWebGLCubeRenderTarget) {
  13598. if (warnedTextureCube === false) {
  13599. console.warn("THREE.WebGLTextures.safeSetTextureCube: don't use cube render targets as textures. Use their .texture property instead.");
  13600. warnedTextureCube = true;
  13601. }
  13602. texture = texture.texture;
  13603. }
  13604. setTextureCube(texture, slot);
  13605. } //
  13606. this.allocateTextureUnit = allocateTextureUnit;
  13607. this.resetTextureUnits = resetTextureUnits;
  13608. this.setTexture2D = setTexture2D;
  13609. this.setTexture2DArray = setTexture2DArray;
  13610. this.setTexture3D = setTexture3D;
  13611. this.setTextureCube = setTextureCube;
  13612. this.setupRenderTarget = setupRenderTarget;
  13613. this.updateRenderTargetMipmap = updateRenderTargetMipmap;
  13614. this.updateMultisampleRenderTarget = updateMultisampleRenderTarget;
  13615. this.safeSetTexture2D = safeSetTexture2D;
  13616. this.safeSetTextureCube = safeSetTextureCube;
  13617. }
  13618. function WebGLUtils(gl, extensions, capabilities) {
  13619. const isWebGL2 = capabilities.isWebGL2;
  13620. function convert(p) {
  13621. let extension;
  13622. if (p === UnsignedByteType) return 5121;
  13623. if (p === UnsignedShort4444Type) return 32819;
  13624. if (p === UnsignedShort5551Type) return 32820;
  13625. if (p === UnsignedShort565Type) return 33635;
  13626. if (p === ByteType) return 5120;
  13627. if (p === ShortType) return 5122;
  13628. if (p === UnsignedShortType) return 5123;
  13629. if (p === IntType) return 5124;
  13630. if (p === UnsignedIntType) return 5125;
  13631. if (p === FloatType) return 5126;
  13632. if (p === HalfFloatType) {
  13633. if (isWebGL2) return 5131;
  13634. extension = extensions.get('OES_texture_half_float');
  13635. if (extension !== null) {
  13636. return extension.HALF_FLOAT_OES;
  13637. } else {
  13638. return null;
  13639. }
  13640. }
  13641. if (p === AlphaFormat) return 6406;
  13642. if (p === RGBFormat) return 6407;
  13643. if (p === RGBAFormat) return 6408;
  13644. if (p === LuminanceFormat) return 6409;
  13645. if (p === LuminanceAlphaFormat) return 6410;
  13646. if (p === DepthFormat) return 6402;
  13647. if (p === DepthStencilFormat) return 34041;
  13648. if (p === RedFormat) return 6403; // WebGL2 formats.
  13649. if (p === RedIntegerFormat) return 36244;
  13650. if (p === RGFormat) return 33319;
  13651. if (p === RGIntegerFormat) return 33320;
  13652. if (p === RGBIntegerFormat) return 36248;
  13653. if (p === RGBAIntegerFormat) return 36249;
  13654. if (p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format) {
  13655. extension = extensions.get('WEBGL_compressed_texture_s3tc');
  13656. if (extension !== null) {
  13657. if (p === RGB_S3TC_DXT1_Format) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  13658. if (p === RGBA_S3TC_DXT1_Format) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  13659. if (p === RGBA_S3TC_DXT3_Format) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  13660. if (p === RGBA_S3TC_DXT5_Format) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  13661. } else {
  13662. return null;
  13663. }
  13664. }
  13665. if (p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format) {
  13666. extension = extensions.get('WEBGL_compressed_texture_pvrtc');
  13667. if (extension !== null) {
  13668. if (p === RGB_PVRTC_4BPPV1_Format) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  13669. if (p === RGB_PVRTC_2BPPV1_Format) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  13670. if (p === RGBA_PVRTC_4BPPV1_Format) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  13671. if (p === RGBA_PVRTC_2BPPV1_Format) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  13672. } else {
  13673. return null;
  13674. }
  13675. }
  13676. if (p === RGB_ETC1_Format) {
  13677. extension = extensions.get('WEBGL_compressed_texture_etc1');
  13678. if (extension !== null) {
  13679. return extension.COMPRESSED_RGB_ETC1_WEBGL;
  13680. } else {
  13681. return null;
  13682. }
  13683. }
  13684. if (p === RGB_ETC2_Format || p === RGBA_ETC2_EAC_Format) {
  13685. extension = extensions.get('WEBGL_compressed_texture_etc');
  13686. if (extension !== null) {
  13687. if (p === RGB_ETC2_Format) return extension.COMPRESSED_RGB8_ETC2;
  13688. if (p === RGBA_ETC2_EAC_Format) return extension.COMPRESSED_RGBA8_ETC2_EAC;
  13689. }
  13690. }
  13691. if (p === RGBA_ASTC_4x4_Format || p === RGBA_ASTC_5x4_Format || p === RGBA_ASTC_5x5_Format || p === RGBA_ASTC_6x5_Format || p === RGBA_ASTC_6x6_Format || p === RGBA_ASTC_8x5_Format || p === RGBA_ASTC_8x6_Format || p === RGBA_ASTC_8x8_Format || p === RGBA_ASTC_10x5_Format || p === RGBA_ASTC_10x6_Format || p === RGBA_ASTC_10x8_Format || p === RGBA_ASTC_10x10_Format || p === RGBA_ASTC_12x10_Format || p === RGBA_ASTC_12x12_Format || p === SRGB8_ALPHA8_ASTC_4x4_Format || p === SRGB8_ALPHA8_ASTC_5x4_Format || p === SRGB8_ALPHA8_ASTC_5x5_Format || p === SRGB8_ALPHA8_ASTC_6x5_Format || p === SRGB8_ALPHA8_ASTC_6x6_Format || p === SRGB8_ALPHA8_ASTC_8x5_Format || p === SRGB8_ALPHA8_ASTC_8x6_Format || p === SRGB8_ALPHA8_ASTC_8x8_Format || p === SRGB8_ALPHA8_ASTC_10x5_Format || p === SRGB8_ALPHA8_ASTC_10x6_Format || p === SRGB8_ALPHA8_ASTC_10x8_Format || p === SRGB8_ALPHA8_ASTC_10x10_Format || p === SRGB8_ALPHA8_ASTC_12x10_Format || p === SRGB8_ALPHA8_ASTC_12x12_Format) {
  13692. extension = extensions.get('WEBGL_compressed_texture_astc');
  13693. if (extension !== null) {
  13694. // TODO Complete?
  13695. return p;
  13696. } else {
  13697. return null;
  13698. }
  13699. }
  13700. if (p === RGBA_BPTC_Format) {
  13701. extension = extensions.get('EXT_texture_compression_bptc');
  13702. if (extension !== null) {
  13703. // TODO Complete?
  13704. return p;
  13705. } else {
  13706. return null;
  13707. }
  13708. }
  13709. if (p === UnsignedInt248Type) {
  13710. if (isWebGL2) return 34042;
  13711. extension = extensions.get('WEBGL_depth_texture');
  13712. if (extension !== null) {
  13713. return extension.UNSIGNED_INT_24_8_WEBGL;
  13714. } else {
  13715. return null;
  13716. }
  13717. }
  13718. }
  13719. return {
  13720. convert: convert
  13721. };
  13722. }
  13723. function ArrayCamera(array = []) {
  13724. PerspectiveCamera.call(this);
  13725. this.cameras = array;
  13726. }
  13727. ArrayCamera.prototype = Object.assign(Object.create(PerspectiveCamera.prototype), {
  13728. constructor: ArrayCamera,
  13729. isArrayCamera: true
  13730. });
  13731. function Group() {
  13732. Object3D.call(this);
  13733. this.type = 'Group';
  13734. }
  13735. Group.prototype = Object.assign(Object.create(Object3D.prototype), {
  13736. constructor: Group,
  13737. isGroup: true
  13738. });
  13739. function WebXRController() {
  13740. this._targetRay = null;
  13741. this._grip = null;
  13742. this._hand = null;
  13743. }
  13744. Object.assign(WebXRController.prototype, {
  13745. constructor: WebXRController,
  13746. getHandSpace: function () {
  13747. if (this._hand === null) {
  13748. this._hand = new Group();
  13749. this._hand.matrixAutoUpdate = false;
  13750. this._hand.visible = false;
  13751. this._hand.joints = [];
  13752. this._hand.inputState = {
  13753. pinching: false
  13754. };
  13755. if (window.XRHand) {
  13756. for (let i = 0; i <= window.XRHand.LITTLE_PHALANX_TIP; i++) {
  13757. // The transform of this joint will be updated with the joint pose on each frame
  13758. const joint = new Group();
  13759. joint.matrixAutoUpdate = false;
  13760. joint.visible = false;
  13761. this._hand.joints.push(joint); // ??
  13762. this._hand.add(joint);
  13763. }
  13764. }
  13765. }
  13766. return this._hand;
  13767. },
  13768. getTargetRaySpace: function () {
  13769. if (this._targetRay === null) {
  13770. this._targetRay = new Group();
  13771. this._targetRay.matrixAutoUpdate = false;
  13772. this._targetRay.visible = false;
  13773. }
  13774. return this._targetRay;
  13775. },
  13776. getGripSpace: function () {
  13777. if (this._grip === null) {
  13778. this._grip = new Group();
  13779. this._grip.matrixAutoUpdate = false;
  13780. this._grip.visible = false;
  13781. }
  13782. return this._grip;
  13783. },
  13784. dispatchEvent: function (event) {
  13785. if (this._targetRay !== null) {
  13786. this._targetRay.dispatchEvent(event);
  13787. }
  13788. if (this._grip !== null) {
  13789. this._grip.dispatchEvent(event);
  13790. }
  13791. if (this._hand !== null) {
  13792. this._hand.dispatchEvent(event);
  13793. }
  13794. return this;
  13795. },
  13796. disconnect: function (inputSource) {
  13797. this.dispatchEvent({
  13798. type: 'disconnected',
  13799. data: inputSource
  13800. });
  13801. if (this._targetRay !== null) {
  13802. this._targetRay.visible = false;
  13803. }
  13804. if (this._grip !== null) {
  13805. this._grip.visible = false;
  13806. }
  13807. if (this._hand !== null) {
  13808. this._hand.visible = false;
  13809. }
  13810. return this;
  13811. },
  13812. update: function (inputSource, frame, referenceSpace) {
  13813. let inputPose = null;
  13814. let gripPose = null;
  13815. let handPose = null;
  13816. const targetRay = this._targetRay;
  13817. const grip = this._grip;
  13818. const hand = this._hand;
  13819. if (inputSource && frame.session.visibilityState !== 'visible-blurred') {
  13820. if (hand && inputSource.hand) {
  13821. handPose = true;
  13822. for (let i = 0; i <= window.XRHand.LITTLE_PHALANX_TIP; i++) {
  13823. if (inputSource.hand[i]) {
  13824. // Update the joints groups with the XRJoint poses
  13825. const jointPose = frame.getJointPose(inputSource.hand[i], referenceSpace);
  13826. const joint = hand.joints[i];
  13827. if (jointPose !== null) {
  13828. joint.matrix.fromArray(jointPose.transform.matrix);
  13829. joint.matrix.decompose(joint.position, joint.rotation, joint.scale);
  13830. joint.jointRadius = jointPose.radius;
  13831. }
  13832. joint.visible = jointPose !== null; // Custom events
  13833. // Check pinch
  13834. const indexTip = hand.joints[window.XRHand.INDEX_PHALANX_TIP];
  13835. const thumbTip = hand.joints[window.XRHand.THUMB_PHALANX_TIP];
  13836. const distance = indexTip.position.distanceTo(thumbTip.position);
  13837. const distanceToPinch = 0.02;
  13838. const threshold = 0.005;
  13839. if (hand.inputState.pinching && distance > distanceToPinch + threshold) {
  13840. hand.inputState.pinching = false;
  13841. this.dispatchEvent({
  13842. type: "pinchend",
  13843. handedness: inputSource.handedness,
  13844. target: this
  13845. });
  13846. } else if (!hand.inputState.pinching && distance <= distanceToPinch - threshold) {
  13847. hand.inputState.pinching = true;
  13848. this.dispatchEvent({
  13849. type: "pinchstart",
  13850. handedness: inputSource.handedness,
  13851. target: this
  13852. });
  13853. }
  13854. }
  13855. }
  13856. } else {
  13857. if (targetRay !== null) {
  13858. inputPose = frame.getPose(inputSource.targetRaySpace, referenceSpace);
  13859. if (inputPose !== null) {
  13860. targetRay.matrix.fromArray(inputPose.transform.matrix);
  13861. targetRay.matrix.decompose(targetRay.position, targetRay.rotation, targetRay.scale);
  13862. }
  13863. }
  13864. if (grip !== null && inputSource.gripSpace) {
  13865. gripPose = frame.getPose(inputSource.gripSpace, referenceSpace);
  13866. if (gripPose !== null) {
  13867. grip.matrix.fromArray(gripPose.transform.matrix);
  13868. grip.matrix.decompose(grip.position, grip.rotation, grip.scale);
  13869. }
  13870. }
  13871. }
  13872. }
  13873. if (targetRay !== null) {
  13874. targetRay.visible = inputPose !== null;
  13875. }
  13876. if (grip !== null) {
  13877. grip.visible = gripPose !== null;
  13878. }
  13879. if (hand !== null) {
  13880. hand.visible = handPose !== null;
  13881. }
  13882. return this;
  13883. }
  13884. });
  13885. function WebXRManager(renderer, gl) {
  13886. const scope = this;
  13887. let session = null;
  13888. let framebufferScaleFactor = 1.0;
  13889. let referenceSpace = null;
  13890. let referenceSpaceType = 'local-floor';
  13891. let pose = null;
  13892. const controllers = [];
  13893. const inputSourcesMap = new Map(); //
  13894. const cameraL = new PerspectiveCamera();
  13895. cameraL.layers.enable(1);
  13896. cameraL.viewport = new Vector4();
  13897. const cameraR = new PerspectiveCamera();
  13898. cameraR.layers.enable(2);
  13899. cameraR.viewport = new Vector4();
  13900. const cameras = [cameraL, cameraR];
  13901. const cameraVR = new ArrayCamera();
  13902. cameraVR.layers.enable(1);
  13903. cameraVR.layers.enable(2);
  13904. let _currentDepthNear = null;
  13905. let _currentDepthFar = null; //
  13906. this.enabled = false;
  13907. this.isPresenting = false;
  13908. this.getController = function (index) {
  13909. let controller = controllers[index];
  13910. if (controller === undefined) {
  13911. controller = new WebXRController();
  13912. controllers[index] = controller;
  13913. }
  13914. return controller.getTargetRaySpace();
  13915. };
  13916. this.getControllerGrip = function (index) {
  13917. let controller = controllers[index];
  13918. if (controller === undefined) {
  13919. controller = new WebXRController();
  13920. controllers[index] = controller;
  13921. }
  13922. return controller.getGripSpace();
  13923. };
  13924. this.getHand = function (index) {
  13925. let controller = controllers[index];
  13926. if (controller === undefined) {
  13927. controller = new WebXRController();
  13928. controllers[index] = controller;
  13929. }
  13930. return controller.getHandSpace();
  13931. }; //
  13932. function onSessionEvent(event) {
  13933. const controller = inputSourcesMap.get(event.inputSource);
  13934. if (controller) {
  13935. controller.dispatchEvent({
  13936. type: event.type,
  13937. data: event.inputSource
  13938. });
  13939. }
  13940. }
  13941. function onSessionEnd() {
  13942. inputSourcesMap.forEach(function (controller, inputSource) {
  13943. controller.disconnect(inputSource);
  13944. });
  13945. inputSourcesMap.clear(); //
  13946. renderer.setFramebuffer(null);
  13947. renderer.setRenderTarget(renderer.getRenderTarget()); // Hack #15830
  13948. animation.stop();
  13949. scope.isPresenting = false;
  13950. scope.dispatchEvent({
  13951. type: 'sessionend'
  13952. });
  13953. }
  13954. function onRequestReferenceSpace(value) {
  13955. referenceSpace = value;
  13956. animation.setContext(session);
  13957. animation.start();
  13958. scope.isPresenting = true;
  13959. scope.dispatchEvent({
  13960. type: 'sessionstart'
  13961. });
  13962. }
  13963. this.setFramebufferScaleFactor = function (value) {
  13964. framebufferScaleFactor = value;
  13965. if (scope.isPresenting === true) {
  13966. console.warn('THREE.WebXRManager: Cannot change framebuffer scale while presenting.');
  13967. }
  13968. };
  13969. this.setReferenceSpaceType = function (value) {
  13970. referenceSpaceType = value;
  13971. if (scope.isPresenting === true) {
  13972. console.warn('THREE.WebXRManager: Cannot change reference space type while presenting.');
  13973. }
  13974. };
  13975. this.getReferenceSpace = function () {
  13976. return referenceSpace;
  13977. };
  13978. this.getSession = function () {
  13979. return session;
  13980. };
  13981. this.setSession = function (value) {
  13982. session = value;
  13983. if (session !== null) {
  13984. session.addEventListener('select', onSessionEvent);
  13985. session.addEventListener('selectstart', onSessionEvent);
  13986. session.addEventListener('selectend', onSessionEvent);
  13987. session.addEventListener('squeeze', onSessionEvent);
  13988. session.addEventListener('squeezestart', onSessionEvent);
  13989. session.addEventListener('squeezeend', onSessionEvent);
  13990. session.addEventListener('end', onSessionEnd);
  13991. const attributes = gl.getContextAttributes();
  13992. if (attributes.xrCompatible !== true) {
  13993. gl.makeXRCompatible();
  13994. }
  13995. const layerInit = {
  13996. antialias: attributes.antialias,
  13997. alpha: attributes.alpha,
  13998. depth: attributes.depth,
  13999. stencil: attributes.stencil,
  14000. framebufferScaleFactor: framebufferScaleFactor
  14001. }; // eslint-disable-next-line no-undef
  14002. const baseLayer = new XRWebGLLayer(session, gl, layerInit);
  14003. session.updateRenderState({
  14004. baseLayer: baseLayer
  14005. });
  14006. session.requestReferenceSpace(referenceSpaceType).then(onRequestReferenceSpace); //
  14007. session.addEventListener('inputsourceschange', updateInputSources);
  14008. }
  14009. };
  14010. function updateInputSources(event) {
  14011. const inputSources = session.inputSources; // Assign inputSources to available controllers
  14012. for (let i = 0; i < controllers.length; i++) {
  14013. inputSourcesMap.set(inputSources[i], controllers[i]);
  14014. } // Notify disconnected
  14015. for (let i = 0; i < event.removed.length; i++) {
  14016. const inputSource = event.removed[i];
  14017. const controller = inputSourcesMap.get(inputSource);
  14018. if (controller) {
  14019. controller.dispatchEvent({
  14020. type: 'disconnected',
  14021. data: inputSource
  14022. });
  14023. inputSourcesMap.delete(inputSource);
  14024. }
  14025. } // Notify connected
  14026. for (let i = 0; i < event.added.length; i++) {
  14027. const inputSource = event.added[i];
  14028. const controller = inputSourcesMap.get(inputSource);
  14029. if (controller) {
  14030. controller.dispatchEvent({
  14031. type: 'connected',
  14032. data: inputSource
  14033. });
  14034. }
  14035. }
  14036. } //
  14037. const cameraLPos = new Vector3();
  14038. const cameraRPos = new Vector3();
  14039. /**
  14040. * Assumes 2 cameras that are parallel and share an X-axis, and that
  14041. * the cameras' projection and world matrices have already been set.
  14042. * And that near and far planes are identical for both cameras.
  14043. * Visualization of this technique: https://computergraphics.stackexchange.com/a/4765
  14044. */
  14045. function setProjectionFromUnion(camera, cameraL, cameraR) {
  14046. cameraLPos.setFromMatrixPosition(cameraL.matrixWorld);
  14047. cameraRPos.setFromMatrixPosition(cameraR.matrixWorld);
  14048. const ipd = cameraLPos.distanceTo(cameraRPos);
  14049. const projL = cameraL.projectionMatrix.elements;
  14050. const projR = cameraR.projectionMatrix.elements; // VR systems will have identical far and near planes, and
  14051. // most likely identical top and bottom frustum extents.
  14052. // Use the left camera for these values.
  14053. const near = projL[14] / (projL[10] - 1);
  14054. const far = projL[14] / (projL[10] + 1);
  14055. const topFov = (projL[9] + 1) / projL[5];
  14056. const bottomFov = (projL[9] - 1) / projL[5];
  14057. const leftFov = (projL[8] - 1) / projL[0];
  14058. const rightFov = (projR[8] + 1) / projR[0];
  14059. const left = near * leftFov;
  14060. const right = near * rightFov; // Calculate the new camera's position offset from the
  14061. // left camera. xOffset should be roughly half `ipd`.
  14062. const zOffset = ipd / (-leftFov + rightFov);
  14063. const xOffset = zOffset * -leftFov; // TODO: Better way to apply this offset?
  14064. cameraL.matrixWorld.decompose(camera.position, camera.quaternion, camera.scale);
  14065. camera.translateX(xOffset);
  14066. camera.translateZ(zOffset);
  14067. camera.matrixWorld.compose(camera.position, camera.quaternion, camera.scale);
  14068. camera.matrixWorldInverse.copy(camera.matrixWorld).invert(); // Find the union of the frustum values of the cameras and scale
  14069. // the values so that the near plane's position does not change in world space,
  14070. // although must now be relative to the new union camera.
  14071. const near2 = near + zOffset;
  14072. const far2 = far + zOffset;
  14073. const left2 = left - xOffset;
  14074. const right2 = right + (ipd - xOffset);
  14075. const top2 = topFov * far / far2 * near2;
  14076. const bottom2 = bottomFov * far / far2 * near2;
  14077. camera.projectionMatrix.makePerspective(left2, right2, top2, bottom2, near2, far2);
  14078. }
  14079. function updateCamera(camera, parent) {
  14080. if (parent === null) {
  14081. camera.matrixWorld.copy(camera.matrix);
  14082. } else {
  14083. camera.matrixWorld.multiplyMatrices(parent.matrixWorld, camera.matrix);
  14084. }
  14085. camera.matrixWorldInverse.copy(camera.matrixWorld).invert();
  14086. }
  14087. this.getCamera = function (camera) {
  14088. cameraVR.near = cameraR.near = cameraL.near = camera.near;
  14089. cameraVR.far = cameraR.far = cameraL.far = camera.far;
  14090. if (_currentDepthNear !== cameraVR.near || _currentDepthFar !== cameraVR.far) {
  14091. // Note that the new renderState won't apply until the next frame. See #18320
  14092. session.updateRenderState({
  14093. depthNear: cameraVR.near,
  14094. depthFar: cameraVR.far
  14095. });
  14096. _currentDepthNear = cameraVR.near;
  14097. _currentDepthFar = cameraVR.far;
  14098. }
  14099. const parent = camera.parent;
  14100. const cameras = cameraVR.cameras;
  14101. updateCamera(cameraVR, parent);
  14102. for (let i = 0; i < cameras.length; i++) {
  14103. updateCamera(cameras[i], parent);
  14104. } // update camera and its children
  14105. camera.matrixWorld.copy(cameraVR.matrixWorld);
  14106. const children = camera.children;
  14107. for (let i = 0, l = children.length; i < l; i++) {
  14108. children[i].updateMatrixWorld(true);
  14109. } // update projection matrix for proper view frustum culling
  14110. if (cameras.length === 2) {
  14111. setProjectionFromUnion(cameraVR, cameraL, cameraR);
  14112. } else {
  14113. // assume single camera setup (AR)
  14114. cameraVR.projectionMatrix.copy(cameraL.projectionMatrix);
  14115. }
  14116. return cameraVR;
  14117. }; // Animation Loop
  14118. let onAnimationFrameCallback = null;
  14119. function onAnimationFrame(time, frame) {
  14120. pose = frame.getViewerPose(referenceSpace);
  14121. if (pose !== null) {
  14122. const views = pose.views;
  14123. const baseLayer = session.renderState.baseLayer;
  14124. renderer.setFramebuffer(baseLayer.framebuffer);
  14125. let cameraVRNeedsUpdate = false; // check if it's necessary to rebuild cameraVR's camera list
  14126. if (views.length !== cameraVR.cameras.length) {
  14127. cameraVR.cameras.length = 0;
  14128. cameraVRNeedsUpdate = true;
  14129. }
  14130. for (let i = 0; i < views.length; i++) {
  14131. const view = views[i];
  14132. const viewport = baseLayer.getViewport(view);
  14133. const camera = cameras[i];
  14134. camera.matrix.fromArray(view.transform.matrix);
  14135. camera.projectionMatrix.fromArray(view.projectionMatrix);
  14136. camera.viewport.set(viewport.x, viewport.y, viewport.width, viewport.height);
  14137. if (i === 0) {
  14138. cameraVR.matrix.copy(camera.matrix);
  14139. }
  14140. if (cameraVRNeedsUpdate === true) {
  14141. cameraVR.cameras.push(camera);
  14142. }
  14143. }
  14144. } //
  14145. const inputSources = session.inputSources;
  14146. for (let i = 0; i < controllers.length; i++) {
  14147. const controller = controllers[i];
  14148. const inputSource = inputSources[i];
  14149. controller.update(inputSource, frame, referenceSpace);
  14150. }
  14151. if (onAnimationFrameCallback) onAnimationFrameCallback(time, frame);
  14152. }
  14153. const animation = new WebGLAnimation();
  14154. animation.setAnimationLoop(onAnimationFrame);
  14155. this.setAnimationLoop = function (callback) {
  14156. onAnimationFrameCallback = callback;
  14157. };
  14158. this.dispose = function () {};
  14159. }
  14160. Object.assign(WebXRManager.prototype, EventDispatcher.prototype);
  14161. function WebGLMaterials(properties) {
  14162. function refreshFogUniforms(uniforms, fog) {
  14163. uniforms.fogColor.value.copy(fog.color);
  14164. if (fog.isFog) {
  14165. uniforms.fogNear.value = fog.near;
  14166. uniforms.fogFar.value = fog.far;
  14167. } else if (fog.isFogExp2) {
  14168. uniforms.fogDensity.value = fog.density;
  14169. }
  14170. }
  14171. function refreshMaterialUniforms(uniforms, material, pixelRatio, height) {
  14172. if (material.isMeshBasicMaterial) {
  14173. refreshUniformsCommon(uniforms, material);
  14174. } else if (material.isMeshLambertMaterial) {
  14175. refreshUniformsCommon(uniforms, material);
  14176. refreshUniformsLambert(uniforms, material);
  14177. } else if (material.isMeshToonMaterial) {
  14178. refreshUniformsCommon(uniforms, material);
  14179. refreshUniformsToon(uniforms, material);
  14180. } else if (material.isMeshPhongMaterial) {
  14181. refreshUniformsCommon(uniforms, material);
  14182. refreshUniformsPhong(uniforms, material);
  14183. } else if (material.isMeshStandardMaterial) {
  14184. refreshUniformsCommon(uniforms, material);
  14185. if (material.isMeshPhysicalMaterial) {
  14186. refreshUniformsPhysical(uniforms, material);
  14187. } else {
  14188. refreshUniformsStandard(uniforms, material);
  14189. }
  14190. } else if (material.isMeshMatcapMaterial) {
  14191. refreshUniformsCommon(uniforms, material);
  14192. refreshUniformsMatcap(uniforms, material);
  14193. } else if (material.isMeshDepthMaterial) {
  14194. refreshUniformsCommon(uniforms, material);
  14195. refreshUniformsDepth(uniforms, material);
  14196. } else if (material.isMeshDistanceMaterial) {
  14197. refreshUniformsCommon(uniforms, material);
  14198. refreshUniformsDistance(uniforms, material);
  14199. } else if (material.isMeshNormalMaterial) {
  14200. refreshUniformsCommon(uniforms, material);
  14201. refreshUniformsNormal(uniforms, material);
  14202. } else if (material.isLineBasicMaterial) {
  14203. refreshUniformsLine(uniforms, material);
  14204. if (material.isLineDashedMaterial) {
  14205. refreshUniformsDash(uniforms, material);
  14206. }
  14207. } else if (material.isPointsMaterial) {
  14208. refreshUniformsPoints(uniforms, material, pixelRatio, height);
  14209. } else if (material.isSpriteMaterial) {
  14210. refreshUniformsSprites(uniforms, material);
  14211. } else if (material.isShadowMaterial) {
  14212. uniforms.color.value.copy(material.color);
  14213. uniforms.opacity.value = material.opacity;
  14214. } else if (material.isShaderMaterial) {
  14215. material.uniformsNeedUpdate = false; // #15581
  14216. }
  14217. }
  14218. function refreshUniformsCommon(uniforms, material) {
  14219. uniforms.opacity.value = material.opacity;
  14220. if (material.color) {
  14221. uniforms.diffuse.value.copy(material.color);
  14222. }
  14223. if (material.emissive) {
  14224. uniforms.emissive.value.copy(material.emissive).multiplyScalar(material.emissiveIntensity);
  14225. }
  14226. if (material.map) {
  14227. uniforms.map.value = material.map;
  14228. }
  14229. if (material.alphaMap) {
  14230. uniforms.alphaMap.value = material.alphaMap;
  14231. }
  14232. if (material.specularMap) {
  14233. uniforms.specularMap.value = material.specularMap;
  14234. }
  14235. const envMap = properties.get(material).envMap;
  14236. if (envMap) {
  14237. uniforms.envMap.value = envMap;
  14238. uniforms.flipEnvMap.value = envMap.isCubeTexture && envMap._needsFlipEnvMap ? -1 : 1;
  14239. uniforms.reflectivity.value = material.reflectivity;
  14240. uniforms.refractionRatio.value = material.refractionRatio;
  14241. const maxMipLevel = properties.get(envMap).__maxMipLevel;
  14242. if (maxMipLevel !== undefined) {
  14243. uniforms.maxMipLevel.value = maxMipLevel;
  14244. }
  14245. }
  14246. if (material.lightMap) {
  14247. uniforms.lightMap.value = material.lightMap;
  14248. uniforms.lightMapIntensity.value = material.lightMapIntensity;
  14249. }
  14250. if (material.aoMap) {
  14251. uniforms.aoMap.value = material.aoMap;
  14252. uniforms.aoMapIntensity.value = material.aoMapIntensity;
  14253. } // uv repeat and offset setting priorities
  14254. // 1. color map
  14255. // 2. specular map
  14256. // 3. displacementMap map
  14257. // 4. normal map
  14258. // 5. bump map
  14259. // 6. roughnessMap map
  14260. // 7. metalnessMap map
  14261. // 8. alphaMap map
  14262. // 9. emissiveMap map
  14263. // 10. clearcoat map
  14264. // 11. clearcoat normal map
  14265. // 12. clearcoat roughnessMap map
  14266. let uvScaleMap;
  14267. if (material.map) {
  14268. uvScaleMap = material.map;
  14269. } else if (material.specularMap) {
  14270. uvScaleMap = material.specularMap;
  14271. } else if (material.displacementMap) {
  14272. uvScaleMap = material.displacementMap;
  14273. } else if (material.normalMap) {
  14274. uvScaleMap = material.normalMap;
  14275. } else if (material.bumpMap) {
  14276. uvScaleMap = material.bumpMap;
  14277. } else if (material.roughnessMap) {
  14278. uvScaleMap = material.roughnessMap;
  14279. } else if (material.metalnessMap) {
  14280. uvScaleMap = material.metalnessMap;
  14281. } else if (material.alphaMap) {
  14282. uvScaleMap = material.alphaMap;
  14283. } else if (material.emissiveMap) {
  14284. uvScaleMap = material.emissiveMap;
  14285. } else if (material.clearcoatMap) {
  14286. uvScaleMap = material.clearcoatMap;
  14287. } else if (material.clearcoatNormalMap) {
  14288. uvScaleMap = material.clearcoatNormalMap;
  14289. } else if (material.clearcoatRoughnessMap) {
  14290. uvScaleMap = material.clearcoatRoughnessMap;
  14291. }
  14292. if (uvScaleMap !== undefined) {
  14293. // backwards compatibility
  14294. if (uvScaleMap.isWebGLRenderTarget) {
  14295. uvScaleMap = uvScaleMap.texture;
  14296. }
  14297. if (uvScaleMap.matrixAutoUpdate === true) {
  14298. uvScaleMap.updateMatrix();
  14299. }
  14300. uniforms.uvTransform.value.copy(uvScaleMap.matrix);
  14301. } // uv repeat and offset setting priorities for uv2
  14302. // 1. ao map
  14303. // 2. light map
  14304. let uv2ScaleMap;
  14305. if (material.aoMap) {
  14306. uv2ScaleMap = material.aoMap;
  14307. } else if (material.lightMap) {
  14308. uv2ScaleMap = material.lightMap;
  14309. }
  14310. if (uv2ScaleMap !== undefined) {
  14311. // backwards compatibility
  14312. if (uv2ScaleMap.isWebGLRenderTarget) {
  14313. uv2ScaleMap = uv2ScaleMap.texture;
  14314. }
  14315. if (uv2ScaleMap.matrixAutoUpdate === true) {
  14316. uv2ScaleMap.updateMatrix();
  14317. }
  14318. uniforms.uv2Transform.value.copy(uv2ScaleMap.matrix);
  14319. }
  14320. }
  14321. function refreshUniformsLine(uniforms, material) {
  14322. uniforms.diffuse.value.copy(material.color);
  14323. uniforms.opacity.value = material.opacity;
  14324. }
  14325. function refreshUniformsDash(uniforms, material) {
  14326. uniforms.dashSize.value = material.dashSize;
  14327. uniforms.totalSize.value = material.dashSize + material.gapSize;
  14328. uniforms.scale.value = material.scale;
  14329. }
  14330. function refreshUniformsPoints(uniforms, material, pixelRatio, height) {
  14331. uniforms.diffuse.value.copy(material.color);
  14332. uniforms.opacity.value = material.opacity;
  14333. uniforms.size.value = material.size * pixelRatio;
  14334. uniforms.scale.value = height * 0.5;
  14335. if (material.map) {
  14336. uniforms.map.value = material.map;
  14337. }
  14338. if (material.alphaMap) {
  14339. uniforms.alphaMap.value = material.alphaMap;
  14340. } // uv repeat and offset setting priorities
  14341. // 1. color map
  14342. // 2. alpha map
  14343. let uvScaleMap;
  14344. if (material.map) {
  14345. uvScaleMap = material.map;
  14346. } else if (material.alphaMap) {
  14347. uvScaleMap = material.alphaMap;
  14348. }
  14349. if (uvScaleMap !== undefined) {
  14350. if (uvScaleMap.matrixAutoUpdate === true) {
  14351. uvScaleMap.updateMatrix();
  14352. }
  14353. uniforms.uvTransform.value.copy(uvScaleMap.matrix);
  14354. }
  14355. }
  14356. function refreshUniformsSprites(uniforms, material) {
  14357. uniforms.diffuse.value.copy(material.color);
  14358. uniforms.opacity.value = material.opacity;
  14359. uniforms.rotation.value = material.rotation;
  14360. if (material.map) {
  14361. uniforms.map.value = material.map;
  14362. }
  14363. if (material.alphaMap) {
  14364. uniforms.alphaMap.value = material.alphaMap;
  14365. } // uv repeat and offset setting priorities
  14366. // 1. color map
  14367. // 2. alpha map
  14368. let uvScaleMap;
  14369. if (material.map) {
  14370. uvScaleMap = material.map;
  14371. } else if (material.alphaMap) {
  14372. uvScaleMap = material.alphaMap;
  14373. }
  14374. if (uvScaleMap !== undefined) {
  14375. if (uvScaleMap.matrixAutoUpdate === true) {
  14376. uvScaleMap.updateMatrix();
  14377. }
  14378. uniforms.uvTransform.value.copy(uvScaleMap.matrix);
  14379. }
  14380. }
  14381. function refreshUniformsLambert(uniforms, material) {
  14382. if (material.emissiveMap) {
  14383. uniforms.emissiveMap.value = material.emissiveMap;
  14384. }
  14385. }
  14386. function refreshUniformsPhong(uniforms, material) {
  14387. uniforms.specular.value.copy(material.specular);
  14388. uniforms.shininess.value = Math.max(material.shininess, 1e-4); // to prevent pow( 0.0, 0.0 )
  14389. if (material.emissiveMap) {
  14390. uniforms.emissiveMap.value = material.emissiveMap;
  14391. }
  14392. if (material.bumpMap) {
  14393. uniforms.bumpMap.value = material.bumpMap;
  14394. uniforms.bumpScale.value = material.bumpScale;
  14395. if (material.side === BackSide) uniforms.bumpScale.value *= -1;
  14396. }
  14397. if (material.normalMap) {
  14398. uniforms.normalMap.value = material.normalMap;
  14399. uniforms.normalScale.value.copy(material.normalScale);
  14400. if (material.side === BackSide) uniforms.normalScale.value.negate();
  14401. }
  14402. if (material.displacementMap) {
  14403. uniforms.displacementMap.value = material.displacementMap;
  14404. uniforms.displacementScale.value = material.displacementScale;
  14405. uniforms.displacementBias.value = material.displacementBias;
  14406. }
  14407. }
  14408. function refreshUniformsToon(uniforms, material) {
  14409. if (material.gradientMap) {
  14410. uniforms.gradientMap.value = material.gradientMap;
  14411. }
  14412. if (material.emissiveMap) {
  14413. uniforms.emissiveMap.value = material.emissiveMap;
  14414. }
  14415. if (material.bumpMap) {
  14416. uniforms.bumpMap.value = material.bumpMap;
  14417. uniforms.bumpScale.value = material.bumpScale;
  14418. if (material.side === BackSide) uniforms.bumpScale.value *= -1;
  14419. }
  14420. if (material.normalMap) {
  14421. uniforms.normalMap.value = material.normalMap;
  14422. uniforms.normalScale.value.copy(material.normalScale);
  14423. if (material.side === BackSide) uniforms.normalScale.value.negate();
  14424. }
  14425. if (material.displacementMap) {
  14426. uniforms.displacementMap.value = material.displacementMap;
  14427. uniforms.displacementScale.value = material.displacementScale;
  14428. uniforms.displacementBias.value = material.displacementBias;
  14429. }
  14430. }
  14431. function refreshUniformsStandard(uniforms, material) {
  14432. uniforms.roughness.value = material.roughness;
  14433. uniforms.metalness.value = material.metalness;
  14434. if (material.roughnessMap) {
  14435. uniforms.roughnessMap.value = material.roughnessMap;
  14436. }
  14437. if (material.metalnessMap) {
  14438. uniforms.metalnessMap.value = material.metalnessMap;
  14439. }
  14440. if (material.emissiveMap) {
  14441. uniforms.emissiveMap.value = material.emissiveMap;
  14442. }
  14443. if (material.bumpMap) {
  14444. uniforms.bumpMap.value = material.bumpMap;
  14445. uniforms.bumpScale.value = material.bumpScale;
  14446. if (material.side === BackSide) uniforms.bumpScale.value *= -1;
  14447. }
  14448. if (material.normalMap) {
  14449. uniforms.normalMap.value = material.normalMap;
  14450. uniforms.normalScale.value.copy(material.normalScale);
  14451. if (material.side === BackSide) uniforms.normalScale.value.negate();
  14452. }
  14453. if (material.displacementMap) {
  14454. uniforms.displacementMap.value = material.displacementMap;
  14455. uniforms.displacementScale.value = material.displacementScale;
  14456. uniforms.displacementBias.value = material.displacementBias;
  14457. }
  14458. const envMap = properties.get(material).envMap;
  14459. if (envMap) {
  14460. //uniforms.envMap.value = material.envMap; // part of uniforms common
  14461. uniforms.envMapIntensity.value = material.envMapIntensity;
  14462. }
  14463. }
  14464. function refreshUniformsPhysical(uniforms, material) {
  14465. refreshUniformsStandard(uniforms, material);
  14466. uniforms.reflectivity.value = material.reflectivity; // also part of uniforms common
  14467. uniforms.clearcoat.value = material.clearcoat;
  14468. uniforms.clearcoatRoughness.value = material.clearcoatRoughness;
  14469. if (material.sheen) uniforms.sheen.value.copy(material.sheen);
  14470. if (material.clearcoatMap) {
  14471. uniforms.clearcoatMap.value = material.clearcoatMap;
  14472. }
  14473. if (material.clearcoatRoughnessMap) {
  14474. uniforms.clearcoatRoughnessMap.value = material.clearcoatRoughnessMap;
  14475. }
  14476. if (material.clearcoatNormalMap) {
  14477. uniforms.clearcoatNormalScale.value.copy(material.clearcoatNormalScale);
  14478. uniforms.clearcoatNormalMap.value = material.clearcoatNormalMap;
  14479. if (material.side === BackSide) {
  14480. uniforms.clearcoatNormalScale.value.negate();
  14481. }
  14482. }
  14483. uniforms.transmission.value = material.transmission;
  14484. if (material.transmissionMap) {
  14485. uniforms.transmissionMap.value = material.transmissionMap;
  14486. }
  14487. }
  14488. function refreshUniformsMatcap(uniforms, material) {
  14489. if (material.matcap) {
  14490. uniforms.matcap.value = material.matcap;
  14491. }
  14492. if (material.bumpMap) {
  14493. uniforms.bumpMap.value = material.bumpMap;
  14494. uniforms.bumpScale.value = material.bumpScale;
  14495. if (material.side === BackSide) uniforms.bumpScale.value *= -1;
  14496. }
  14497. if (material.normalMap) {
  14498. uniforms.normalMap.value = material.normalMap;
  14499. uniforms.normalScale.value.copy(material.normalScale);
  14500. if (material.side === BackSide) uniforms.normalScale.value.negate();
  14501. }
  14502. if (material.displacementMap) {
  14503. uniforms.displacementMap.value = material.displacementMap;
  14504. uniforms.displacementScale.value = material.displacementScale;
  14505. uniforms.displacementBias.value = material.displacementBias;
  14506. }
  14507. }
  14508. function refreshUniformsDepth(uniforms, material) {
  14509. if (material.displacementMap) {
  14510. uniforms.displacementMap.value = material.displacementMap;
  14511. uniforms.displacementScale.value = material.displacementScale;
  14512. uniforms.displacementBias.value = material.displacementBias;
  14513. }
  14514. }
  14515. function refreshUniformsDistance(uniforms, material) {
  14516. if (material.displacementMap) {
  14517. uniforms.displacementMap.value = material.displacementMap;
  14518. uniforms.displacementScale.value = material.displacementScale;
  14519. uniforms.displacementBias.value = material.displacementBias;
  14520. }
  14521. uniforms.referencePosition.value.copy(material.referencePosition);
  14522. uniforms.nearDistance.value = material.nearDistance;
  14523. uniforms.farDistance.value = material.farDistance;
  14524. }
  14525. function refreshUniformsNormal(uniforms, material) {
  14526. if (material.bumpMap) {
  14527. uniforms.bumpMap.value = material.bumpMap;
  14528. uniforms.bumpScale.value = material.bumpScale;
  14529. if (material.side === BackSide) uniforms.bumpScale.value *= -1;
  14530. }
  14531. if (material.normalMap) {
  14532. uniforms.normalMap.value = material.normalMap;
  14533. uniforms.normalScale.value.copy(material.normalScale);
  14534. if (material.side === BackSide) uniforms.normalScale.value.negate();
  14535. }
  14536. if (material.displacementMap) {
  14537. uniforms.displacementMap.value = material.displacementMap;
  14538. uniforms.displacementScale.value = material.displacementScale;
  14539. uniforms.displacementBias.value = material.displacementBias;
  14540. }
  14541. }
  14542. return {
  14543. refreshFogUniforms: refreshFogUniforms,
  14544. refreshMaterialUniforms: refreshMaterialUniforms
  14545. };
  14546. }
  14547. function createCanvasElement() {
  14548. const canvas = document.createElementNS('http://www.w3.org/1999/xhtml', 'canvas');
  14549. canvas.style.display = 'block';
  14550. return canvas;
  14551. }
  14552. function WebGLRenderer(parameters) {
  14553. parameters = parameters || {};
  14554. const _canvas = parameters.canvas !== undefined ? parameters.canvas : createCanvasElement(),
  14555. _context = parameters.context !== undefined ? parameters.context : null,
  14556. _alpha = parameters.alpha !== undefined ? parameters.alpha : false,
  14557. _depth = parameters.depth !== undefined ? parameters.depth : true,
  14558. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  14559. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  14560. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  14561. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false,
  14562. _powerPreference = parameters.powerPreference !== undefined ? parameters.powerPreference : 'default',
  14563. _failIfMajorPerformanceCaveat = parameters.failIfMajorPerformanceCaveat !== undefined ? parameters.failIfMajorPerformanceCaveat : false;
  14564. let currentRenderList = null;
  14565. let currentRenderState = null; // public properties
  14566. this.domElement = _canvas; // Debug configuration container
  14567. this.debug = {
  14568. /**
  14569. * Enables error checking and reporting when shader programs are being compiled
  14570. * @type {boolean}
  14571. */
  14572. checkShaderErrors: true
  14573. }; // clearing
  14574. this.autoClear = true;
  14575. this.autoClearColor = true;
  14576. this.autoClearDepth = true;
  14577. this.autoClearStencil = true; // scene graph
  14578. this.sortObjects = true; // user-defined clipping
  14579. this.clippingPlanes = [];
  14580. this.localClippingEnabled = false; // physically based shading
  14581. this.gammaFactor = 2.0; // for backwards compatibility
  14582. this.outputEncoding = LinearEncoding; // physical lights
  14583. this.physicallyCorrectLights = false; // tone mapping
  14584. this.toneMapping = NoToneMapping;
  14585. this.toneMappingExposure = 1.0; // morphs
  14586. this.maxMorphTargets = 8;
  14587. this.maxMorphNormals = 4; // internal properties
  14588. const _this = this;
  14589. let _isContextLost = false; // internal state cache
  14590. let _framebuffer = null;
  14591. let _currentActiveCubeFace = 0;
  14592. let _currentActiveMipmapLevel = 0;
  14593. let _currentRenderTarget = null;
  14594. let _currentFramebuffer = null;
  14595. let _currentMaterialId = -1;
  14596. let _currentCamera = null;
  14597. let _currentArrayCamera = null;
  14598. const _currentViewport = new Vector4();
  14599. const _currentScissor = new Vector4();
  14600. let _currentScissorTest = null; //
  14601. let _width = _canvas.width;
  14602. let _height = _canvas.height;
  14603. let _pixelRatio = 1;
  14604. let _opaqueSort = null;
  14605. let _transparentSort = null;
  14606. const _viewport = new Vector4(0, 0, _width, _height);
  14607. const _scissor = new Vector4(0, 0, _width, _height);
  14608. let _scissorTest = false; // frustum
  14609. const _frustum = new Frustum(); // clipping
  14610. let _clippingEnabled = false;
  14611. let _localClippingEnabled = false; // camera matrices cache
  14612. const _projScreenMatrix = new Matrix4();
  14613. const _vector3 = new Vector3();
  14614. const _emptyScene = {
  14615. background: null,
  14616. fog: null,
  14617. environment: null,
  14618. overrideMaterial: null,
  14619. isScene: true
  14620. };
  14621. function getTargetPixelRatio() {
  14622. return _currentRenderTarget === null ? _pixelRatio : 1;
  14623. } // initialize
  14624. let _gl = _context;
  14625. function getContext(contextNames, contextAttributes) {
  14626. for (let i = 0; i < contextNames.length; i++) {
  14627. const contextName = contextNames[i];
  14628. const context = _canvas.getContext(contextName, contextAttributes);
  14629. if (context !== null) return context;
  14630. }
  14631. return null;
  14632. }
  14633. try {
  14634. const contextAttributes = {
  14635. alpha: _alpha,
  14636. depth: _depth,
  14637. stencil: _stencil,
  14638. antialias: _antialias,
  14639. premultipliedAlpha: _premultipliedAlpha,
  14640. preserveDrawingBuffer: _preserveDrawingBuffer,
  14641. powerPreference: _powerPreference,
  14642. failIfMajorPerformanceCaveat: _failIfMajorPerformanceCaveat
  14643. }; // event listeners must be registered before WebGL context is created, see #12753
  14644. _canvas.addEventListener('webglcontextlost', onContextLost, false);
  14645. _canvas.addEventListener('webglcontextrestored', onContextRestore, false);
  14646. if (_gl === null) {
  14647. const contextNames = ['webgl2', 'webgl', 'experimental-webgl'];
  14648. if (_this.isWebGL1Renderer === true) {
  14649. contextNames.shift();
  14650. }
  14651. _gl = getContext(contextNames, contextAttributes);
  14652. if (_gl === null) {
  14653. if (getContext(contextNames)) {
  14654. throw new Error('Error creating WebGL context with your selected attributes.');
  14655. } else {
  14656. throw new Error('Error creating WebGL context.');
  14657. }
  14658. }
  14659. } // Some experimental-webgl implementations do not have getShaderPrecisionFormat
  14660. if (_gl.getShaderPrecisionFormat === undefined) {
  14661. _gl.getShaderPrecisionFormat = function () {
  14662. return {
  14663. 'rangeMin': 1,
  14664. 'rangeMax': 1,
  14665. 'precision': 1
  14666. };
  14667. };
  14668. }
  14669. } catch (error) {
  14670. console.error('THREE.WebGLRenderer: ' + error.message);
  14671. throw error;
  14672. }
  14673. let extensions, capabilities, state, info;
  14674. let properties, textures, cubemaps, attributes, geometries, objects;
  14675. let programCache, materials, renderLists, renderStates, clipping;
  14676. let background, morphtargets, bufferRenderer, indexedBufferRenderer;
  14677. let utils, bindingStates;
  14678. function initGLContext() {
  14679. extensions = new WebGLExtensions(_gl);
  14680. capabilities = new WebGLCapabilities(_gl, extensions, parameters);
  14681. if (capabilities.isWebGL2 === false) {
  14682. extensions.get('WEBGL_depth_texture');
  14683. extensions.get('OES_texture_float');
  14684. extensions.get('OES_texture_half_float');
  14685. extensions.get('OES_texture_half_float_linear');
  14686. extensions.get('OES_standard_derivatives');
  14687. extensions.get('OES_element_index_uint');
  14688. extensions.get('OES_vertex_array_object');
  14689. extensions.get('ANGLE_instanced_arrays');
  14690. }
  14691. extensions.get('OES_texture_float_linear');
  14692. utils = new WebGLUtils(_gl, extensions, capabilities);
  14693. state = new WebGLState(_gl, extensions, capabilities);
  14694. state.scissor(_currentScissor.copy(_scissor).multiplyScalar(_pixelRatio).floor());
  14695. state.viewport(_currentViewport.copy(_viewport).multiplyScalar(_pixelRatio).floor());
  14696. info = new WebGLInfo(_gl);
  14697. properties = new WebGLProperties();
  14698. textures = new WebGLTextures(_gl, extensions, state, properties, capabilities, utils, info);
  14699. cubemaps = new WebGLCubeMaps(_this);
  14700. attributes = new WebGLAttributes(_gl, capabilities);
  14701. bindingStates = new WebGLBindingStates(_gl, extensions, attributes, capabilities);
  14702. geometries = new WebGLGeometries(_gl, attributes, info, bindingStates);
  14703. objects = new WebGLObjects(_gl, geometries, attributes, info);
  14704. morphtargets = new WebGLMorphtargets(_gl);
  14705. clipping = new WebGLClipping(properties);
  14706. programCache = new WebGLPrograms(_this, cubemaps, extensions, capabilities, bindingStates, clipping);
  14707. materials = new WebGLMaterials(properties);
  14708. renderLists = new WebGLRenderLists(properties);
  14709. renderStates = new WebGLRenderStates(extensions, capabilities);
  14710. background = new WebGLBackground(_this, cubemaps, state, objects, _premultipliedAlpha);
  14711. bufferRenderer = new WebGLBufferRenderer(_gl, extensions, info, capabilities);
  14712. indexedBufferRenderer = new WebGLIndexedBufferRenderer(_gl, extensions, info, capabilities);
  14713. info.programs = programCache.programs;
  14714. _this.capabilities = capabilities;
  14715. _this.extensions = extensions;
  14716. _this.properties = properties;
  14717. _this.renderLists = renderLists;
  14718. _this.state = state;
  14719. _this.info = info;
  14720. }
  14721. initGLContext(); // xr
  14722. const xr = new WebXRManager(_this, _gl);
  14723. this.xr = xr; // shadow map
  14724. const shadowMap = new WebGLShadowMap(_this, objects, capabilities.maxTextureSize);
  14725. this.shadowMap = shadowMap; // API
  14726. this.getContext = function () {
  14727. return _gl;
  14728. };
  14729. this.getContextAttributes = function () {
  14730. return _gl.getContextAttributes();
  14731. };
  14732. this.forceContextLoss = function () {
  14733. const extension = extensions.get('WEBGL_lose_context');
  14734. if (extension) extension.loseContext();
  14735. };
  14736. this.forceContextRestore = function () {
  14737. const extension = extensions.get('WEBGL_lose_context');
  14738. if (extension) extension.restoreContext();
  14739. };
  14740. this.getPixelRatio = function () {
  14741. return _pixelRatio;
  14742. };
  14743. this.setPixelRatio = function (value) {
  14744. if (value === undefined) return;
  14745. _pixelRatio = value;
  14746. this.setSize(_width, _height, false);
  14747. };
  14748. this.getSize = function (target) {
  14749. if (target === undefined) {
  14750. console.warn('WebGLRenderer: .getsize() now requires a Vector2 as an argument');
  14751. target = new Vector2();
  14752. }
  14753. return target.set(_width, _height);
  14754. };
  14755. this.setSize = function (width, height, updateStyle) {
  14756. if (xr.isPresenting) {
  14757. console.warn('THREE.WebGLRenderer: Can\'t change size while VR device is presenting.');
  14758. return;
  14759. }
  14760. _width = width;
  14761. _height = height;
  14762. _canvas.width = Math.floor(width * _pixelRatio);
  14763. _canvas.height = Math.floor(height * _pixelRatio);
  14764. if (updateStyle !== false) {
  14765. _canvas.style.width = width + 'px';
  14766. _canvas.style.height = height + 'px';
  14767. }
  14768. this.setViewport(0, 0, width, height);
  14769. };
  14770. this.getDrawingBufferSize = function (target) {
  14771. if (target === undefined) {
  14772. console.warn('WebGLRenderer: .getdrawingBufferSize() now requires a Vector2 as an argument');
  14773. target = new Vector2();
  14774. }
  14775. return target.set(_width * _pixelRatio, _height * _pixelRatio).floor();
  14776. };
  14777. this.setDrawingBufferSize = function (width, height, pixelRatio) {
  14778. _width = width;
  14779. _height = height;
  14780. _pixelRatio = pixelRatio;
  14781. _canvas.width = Math.floor(width * pixelRatio);
  14782. _canvas.height = Math.floor(height * pixelRatio);
  14783. this.setViewport(0, 0, width, height);
  14784. };
  14785. this.getCurrentViewport = function (target) {
  14786. if (target === undefined) {
  14787. console.warn('WebGLRenderer: .getCurrentViewport() now requires a Vector4 as an argument');
  14788. target = new Vector4();
  14789. }
  14790. return target.copy(_currentViewport);
  14791. };
  14792. this.getViewport = function (target) {
  14793. return target.copy(_viewport);
  14794. };
  14795. this.setViewport = function (x, y, width, height) {
  14796. if (x.isVector4) {
  14797. _viewport.set(x.x, x.y, x.z, x.w);
  14798. } else {
  14799. _viewport.set(x, y, width, height);
  14800. }
  14801. state.viewport(_currentViewport.copy(_viewport).multiplyScalar(_pixelRatio).floor());
  14802. };
  14803. this.getScissor = function (target) {
  14804. return target.copy(_scissor);
  14805. };
  14806. this.setScissor = function (x, y, width, height) {
  14807. if (x.isVector4) {
  14808. _scissor.set(x.x, x.y, x.z, x.w);
  14809. } else {
  14810. _scissor.set(x, y, width, height);
  14811. }
  14812. state.scissor(_currentScissor.copy(_scissor).multiplyScalar(_pixelRatio).floor());
  14813. };
  14814. this.getScissorTest = function () {
  14815. return _scissorTest;
  14816. };
  14817. this.setScissorTest = function (boolean) {
  14818. state.setScissorTest(_scissorTest = boolean);
  14819. };
  14820. this.setOpaqueSort = function (method) {
  14821. _opaqueSort = method;
  14822. };
  14823. this.setTransparentSort = function (method) {
  14824. _transparentSort = method;
  14825. }; // Clearing
  14826. this.getClearColor = function () {
  14827. return background.getClearColor();
  14828. };
  14829. this.setClearColor = function () {
  14830. background.setClearColor.apply(background, arguments);
  14831. };
  14832. this.getClearAlpha = function () {
  14833. return background.getClearAlpha();
  14834. };
  14835. this.setClearAlpha = function () {
  14836. background.setClearAlpha.apply(background, arguments);
  14837. };
  14838. this.clear = function (color, depth, stencil) {
  14839. let bits = 0;
  14840. if (color === undefined || color) bits |= 16384;
  14841. if (depth === undefined || depth) bits |= 256;
  14842. if (stencil === undefined || stencil) bits |= 1024;
  14843. _gl.clear(bits);
  14844. };
  14845. this.clearColor = function () {
  14846. this.clear(true, false, false);
  14847. };
  14848. this.clearDepth = function () {
  14849. this.clear(false, true, false);
  14850. };
  14851. this.clearStencil = function () {
  14852. this.clear(false, false, true);
  14853. }; //
  14854. this.dispose = function () {
  14855. _canvas.removeEventListener('webglcontextlost', onContextLost, false);
  14856. _canvas.removeEventListener('webglcontextrestored', onContextRestore, false);
  14857. renderLists.dispose();
  14858. renderStates.dispose();
  14859. properties.dispose();
  14860. cubemaps.dispose();
  14861. objects.dispose();
  14862. bindingStates.dispose();
  14863. xr.dispose();
  14864. animation.stop();
  14865. }; // Events
  14866. function onContextLost(event) {
  14867. event.preventDefault();
  14868. console.log('THREE.WebGLRenderer: Context Lost.');
  14869. _isContextLost = true;
  14870. }
  14871. function onContextRestore()
  14872. /* event */
  14873. {
  14874. console.log('THREE.WebGLRenderer: Context Restored.');
  14875. _isContextLost = false;
  14876. initGLContext();
  14877. }
  14878. function onMaterialDispose(event) {
  14879. const material = event.target;
  14880. material.removeEventListener('dispose', onMaterialDispose);
  14881. deallocateMaterial(material);
  14882. } // Buffer deallocation
  14883. function deallocateMaterial(material) {
  14884. releaseMaterialProgramReference(material);
  14885. properties.remove(material);
  14886. }
  14887. function releaseMaterialProgramReference(material) {
  14888. const programInfo = properties.get(material).program;
  14889. if (programInfo !== undefined) {
  14890. programCache.releaseProgram(programInfo);
  14891. }
  14892. } // Buffer rendering
  14893. function renderObjectImmediate(object, program) {
  14894. object.render(function (object) {
  14895. _this.renderBufferImmediate(object, program);
  14896. });
  14897. }
  14898. this.renderBufferImmediate = function (object, program) {
  14899. bindingStates.initAttributes();
  14900. const buffers = properties.get(object);
  14901. if (object.hasPositions && !buffers.position) buffers.position = _gl.createBuffer();
  14902. if (object.hasNormals && !buffers.normal) buffers.normal = _gl.createBuffer();
  14903. if (object.hasUvs && !buffers.uv) buffers.uv = _gl.createBuffer();
  14904. if (object.hasColors && !buffers.color) buffers.color = _gl.createBuffer();
  14905. const programAttributes = program.getAttributes();
  14906. if (object.hasPositions) {
  14907. _gl.bindBuffer(34962, buffers.position);
  14908. _gl.bufferData(34962, object.positionArray, 35048);
  14909. bindingStates.enableAttribute(programAttributes.position);
  14910. _gl.vertexAttribPointer(programAttributes.position, 3, 5126, false, 0, 0);
  14911. }
  14912. if (object.hasNormals) {
  14913. _gl.bindBuffer(34962, buffers.normal);
  14914. _gl.bufferData(34962, object.normalArray, 35048);
  14915. bindingStates.enableAttribute(programAttributes.normal);
  14916. _gl.vertexAttribPointer(programAttributes.normal, 3, 5126, false, 0, 0);
  14917. }
  14918. if (object.hasUvs) {
  14919. _gl.bindBuffer(34962, buffers.uv);
  14920. _gl.bufferData(34962, object.uvArray, 35048);
  14921. bindingStates.enableAttribute(programAttributes.uv);
  14922. _gl.vertexAttribPointer(programAttributes.uv, 2, 5126, false, 0, 0);
  14923. }
  14924. if (object.hasColors) {
  14925. _gl.bindBuffer(34962, buffers.color);
  14926. _gl.bufferData(34962, object.colorArray, 35048);
  14927. bindingStates.enableAttribute(programAttributes.color);
  14928. _gl.vertexAttribPointer(programAttributes.color, 3, 5126, false, 0, 0);
  14929. }
  14930. bindingStates.disableUnusedAttributes();
  14931. _gl.drawArrays(4, 0, object.count);
  14932. object.count = 0;
  14933. };
  14934. this.renderBufferDirect = function (camera, scene, geometry, material, object, group) {
  14935. if (scene === null) scene = _emptyScene; // renderBufferDirect second parameter used to be fog (could be null)
  14936. const frontFaceCW = object.isMesh && object.matrixWorld.determinant() < 0;
  14937. const program = setProgram(camera, scene, material, object);
  14938. state.setMaterial(material, frontFaceCW); //
  14939. let index = geometry.index;
  14940. const position = geometry.attributes.position; //
  14941. if (index === null) {
  14942. if (position === undefined || position.count === 0) return;
  14943. } else if (index.count === 0) {
  14944. return;
  14945. } //
  14946. let rangeFactor = 1;
  14947. if (material.wireframe === true) {
  14948. index = geometries.getWireframeAttribute(geometry);
  14949. rangeFactor = 2;
  14950. }
  14951. if (material.morphTargets || material.morphNormals) {
  14952. morphtargets.update(object, geometry, material, program);
  14953. }
  14954. bindingStates.setup(object, material, program, geometry, index);
  14955. let attribute;
  14956. let renderer = bufferRenderer;
  14957. if (index !== null) {
  14958. attribute = attributes.get(index);
  14959. renderer = indexedBufferRenderer;
  14960. renderer.setIndex(attribute);
  14961. } //
  14962. const dataCount = index !== null ? index.count : position.count;
  14963. const rangeStart = geometry.drawRange.start * rangeFactor;
  14964. const rangeCount = geometry.drawRange.count * rangeFactor;
  14965. const groupStart = group !== null ? group.start * rangeFactor : 0;
  14966. const groupCount = group !== null ? group.count * rangeFactor : Infinity;
  14967. const drawStart = Math.max(rangeStart, groupStart);
  14968. const drawEnd = Math.min(dataCount, rangeStart + rangeCount, groupStart + groupCount) - 1;
  14969. const drawCount = Math.max(0, drawEnd - drawStart + 1);
  14970. if (drawCount === 0) return; //
  14971. if (object.isMesh) {
  14972. if (material.wireframe === true) {
  14973. state.setLineWidth(material.wireframeLinewidth * getTargetPixelRatio());
  14974. renderer.setMode(1);
  14975. } else {
  14976. renderer.setMode(4);
  14977. }
  14978. } else if (object.isLine) {
  14979. let lineWidth = material.linewidth;
  14980. if (lineWidth === undefined) lineWidth = 1; // Not using Line*Material
  14981. state.setLineWidth(lineWidth * getTargetPixelRatio());
  14982. if (object.isLineSegments) {
  14983. renderer.setMode(1);
  14984. } else if (object.isLineLoop) {
  14985. renderer.setMode(2);
  14986. } else {
  14987. renderer.setMode(3);
  14988. }
  14989. } else if (object.isPoints) {
  14990. renderer.setMode(0);
  14991. } else if (object.isSprite) {
  14992. renderer.setMode(4);
  14993. }
  14994. if (object.isInstancedMesh) {
  14995. renderer.renderInstances(drawStart, drawCount, object.count);
  14996. } else if (geometry.isInstancedBufferGeometry) {
  14997. const instanceCount = Math.min(geometry.instanceCount, geometry._maxInstanceCount);
  14998. renderer.renderInstances(drawStart, drawCount, instanceCount);
  14999. } else {
  15000. renderer.render(drawStart, drawCount);
  15001. }
  15002. }; // Compile
  15003. this.compile = function (scene, camera) {
  15004. currentRenderState = renderStates.get(scene, camera);
  15005. currentRenderState.init();
  15006. scene.traverseVisible(function (object) {
  15007. if (object.isLight && object.layers.test(camera.layers)) {
  15008. currentRenderState.pushLight(object);
  15009. if (object.castShadow) {
  15010. currentRenderState.pushShadow(object);
  15011. }
  15012. }
  15013. });
  15014. currentRenderState.setupLights(camera);
  15015. const compiled = new WeakMap();
  15016. scene.traverse(function (object) {
  15017. const material = object.material;
  15018. if (material) {
  15019. if (Array.isArray(material)) {
  15020. for (let i = 0; i < material.length; i++) {
  15021. const material2 = material[i];
  15022. if (compiled.has(material2) === false) {
  15023. initMaterial(material2, scene, object);
  15024. compiled.set(material2);
  15025. }
  15026. }
  15027. } else if (compiled.has(material) === false) {
  15028. initMaterial(material, scene, object);
  15029. compiled.set(material);
  15030. }
  15031. }
  15032. });
  15033. }; // Animation Loop
  15034. let onAnimationFrameCallback = null;
  15035. function onAnimationFrame(time) {
  15036. if (xr.isPresenting) return;
  15037. if (onAnimationFrameCallback) onAnimationFrameCallback(time);
  15038. }
  15039. const animation = new WebGLAnimation();
  15040. animation.setAnimationLoop(onAnimationFrame);
  15041. if (typeof window !== 'undefined') animation.setContext(window);
  15042. this.setAnimationLoop = function (callback) {
  15043. onAnimationFrameCallback = callback;
  15044. xr.setAnimationLoop(callback);
  15045. callback === null ? animation.stop() : animation.start();
  15046. }; // Rendering
  15047. this.render = function (scene, camera) {
  15048. let renderTarget, forceClear;
  15049. if (arguments[2] !== undefined) {
  15050. console.warn('THREE.WebGLRenderer.render(): the renderTarget argument has been removed. Use .setRenderTarget() instead.');
  15051. renderTarget = arguments[2];
  15052. }
  15053. if (arguments[3] !== undefined) {
  15054. console.warn('THREE.WebGLRenderer.render(): the forceClear argument has been removed. Use .clear() instead.');
  15055. forceClear = arguments[3];
  15056. }
  15057. if (camera !== undefined && camera.isCamera !== true) {
  15058. console.error('THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.');
  15059. return;
  15060. }
  15061. if (_isContextLost === true) return; // reset caching for this frame
  15062. bindingStates.resetDefaultState();
  15063. _currentMaterialId = -1;
  15064. _currentCamera = null; // update scene graph
  15065. if (scene.autoUpdate === true) scene.updateMatrixWorld(); // update camera matrices and frustum
  15066. if (camera.parent === null) camera.updateMatrixWorld();
  15067. if (xr.enabled === true && xr.isPresenting === true) {
  15068. camera = xr.getCamera(camera);
  15069. } //
  15070. if (scene.isScene === true) scene.onBeforeRender(_this, scene, camera, renderTarget || _currentRenderTarget);
  15071. currentRenderState = renderStates.get(scene, camera);
  15072. currentRenderState.init();
  15073. _projScreenMatrix.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse);
  15074. _frustum.setFromProjectionMatrix(_projScreenMatrix);
  15075. _localClippingEnabled = this.localClippingEnabled;
  15076. _clippingEnabled = clipping.init(this.clippingPlanes, _localClippingEnabled, camera);
  15077. currentRenderList = renderLists.get(scene, camera);
  15078. currentRenderList.init();
  15079. projectObject(scene, camera, 0, _this.sortObjects);
  15080. currentRenderList.finish();
  15081. if (_this.sortObjects === true) {
  15082. currentRenderList.sort(_opaqueSort, _transparentSort);
  15083. } //
  15084. if (_clippingEnabled === true) clipping.beginShadows();
  15085. const shadowsArray = currentRenderState.state.shadowsArray;
  15086. shadowMap.render(shadowsArray, scene, camera);
  15087. currentRenderState.setupLights(camera);
  15088. if (_clippingEnabled === true) clipping.endShadows(); //
  15089. if (this.info.autoReset === true) this.info.reset();
  15090. if (renderTarget !== undefined) {
  15091. this.setRenderTarget(renderTarget);
  15092. } //
  15093. background.render(currentRenderList, scene, camera, forceClear); // render scene
  15094. const opaqueObjects = currentRenderList.opaque;
  15095. const transparentObjects = currentRenderList.transparent;
  15096. if (opaqueObjects.length > 0) renderObjects(opaqueObjects, scene, camera);
  15097. if (transparentObjects.length > 0) renderObjects(transparentObjects, scene, camera); //
  15098. if (scene.isScene === true) scene.onAfterRender(_this, scene, camera); //
  15099. if (_currentRenderTarget !== null) {
  15100. // Generate mipmap if we're using any kind of mipmap filtering
  15101. textures.updateRenderTargetMipmap(_currentRenderTarget); // resolve multisample renderbuffers to a single-sample texture if necessary
  15102. textures.updateMultisampleRenderTarget(_currentRenderTarget);
  15103. } // Ensure depth buffer writing is enabled so it can be cleared on next render
  15104. state.buffers.depth.setTest(true);
  15105. state.buffers.depth.setMask(true);
  15106. state.buffers.color.setMask(true);
  15107. state.setPolygonOffset(false); // _gl.finish();
  15108. currentRenderList = null;
  15109. currentRenderState = null;
  15110. };
  15111. function projectObject(object, camera, groupOrder, sortObjects) {
  15112. if (object.visible === false) return;
  15113. const visible = object.layers.test(camera.layers);
  15114. if (visible) {
  15115. if (object.isGroup) {
  15116. groupOrder = object.renderOrder;
  15117. } else if (object.isLOD) {
  15118. if (object.autoUpdate === true) object.update(camera);
  15119. } else if (object.isLight) {
  15120. currentRenderState.pushLight(object);
  15121. if (object.castShadow) {
  15122. currentRenderState.pushShadow(object);
  15123. }
  15124. } else if (object.isSprite) {
  15125. if (!object.frustumCulled || _frustum.intersectsSprite(object)) {
  15126. if (sortObjects) {
  15127. _vector3.setFromMatrixPosition(object.matrixWorld).applyMatrix4(_projScreenMatrix);
  15128. }
  15129. const geometry = objects.update(object);
  15130. const material = object.material;
  15131. if (material.visible) {
  15132. currentRenderList.push(object, geometry, material, groupOrder, _vector3.z, null);
  15133. }
  15134. }
  15135. } else if (object.isImmediateRenderObject) {
  15136. if (sortObjects) {
  15137. _vector3.setFromMatrixPosition(object.matrixWorld).applyMatrix4(_projScreenMatrix);
  15138. }
  15139. currentRenderList.push(object, null, object.material, groupOrder, _vector3.z, null);
  15140. } else if (object.isMesh || object.isLine || object.isPoints) {
  15141. if (object.isSkinnedMesh) {
  15142. // update skeleton only once in a frame
  15143. if (object.skeleton.frame !== info.render.frame) {
  15144. object.skeleton.update();
  15145. object.skeleton.frame = info.render.frame;
  15146. }
  15147. }
  15148. if (!object.frustumCulled || _frustum.intersectsObject(object)) {
  15149. if (sortObjects) {
  15150. _vector3.setFromMatrixPosition(object.matrixWorld).applyMatrix4(_projScreenMatrix);
  15151. }
  15152. const geometry = objects.update(object);
  15153. const material = object.material;
  15154. if (Array.isArray(material)) {
  15155. const groups = geometry.groups;
  15156. for (let i = 0, l = groups.length; i < l; i++) {
  15157. const group = groups[i];
  15158. const groupMaterial = material[group.materialIndex];
  15159. if (groupMaterial && groupMaterial.visible) {
  15160. currentRenderList.push(object, geometry, groupMaterial, groupOrder, _vector3.z, group);
  15161. }
  15162. }
  15163. } else if (material.visible) {
  15164. currentRenderList.push(object, geometry, material, groupOrder, _vector3.z, null);
  15165. }
  15166. }
  15167. }
  15168. }
  15169. const children = object.children;
  15170. for (let i = 0, l = children.length; i < l; i++) {
  15171. projectObject(children[i], camera, groupOrder, sortObjects);
  15172. }
  15173. }
  15174. function renderObjects(renderList, scene, camera) {
  15175. const overrideMaterial = scene.isScene === true ? scene.overrideMaterial : null;
  15176. for (let i = 0, l = renderList.length; i < l; i++) {
  15177. const renderItem = renderList[i];
  15178. const object = renderItem.object;
  15179. const geometry = renderItem.geometry;
  15180. const material = overrideMaterial === null ? renderItem.material : overrideMaterial;
  15181. const group = renderItem.group;
  15182. if (camera.isArrayCamera) {
  15183. _currentArrayCamera = camera;
  15184. const cameras = camera.cameras;
  15185. for (let j = 0, jl = cameras.length; j < jl; j++) {
  15186. const camera2 = cameras[j];
  15187. if (object.layers.test(camera2.layers)) {
  15188. state.viewport(_currentViewport.copy(camera2.viewport));
  15189. currentRenderState.setupLights(camera2);
  15190. renderObject(object, scene, camera2, geometry, material, group);
  15191. }
  15192. }
  15193. } else {
  15194. _currentArrayCamera = null;
  15195. renderObject(object, scene, camera, geometry, material, group);
  15196. }
  15197. }
  15198. }
  15199. function renderObject(object, scene, camera, geometry, material, group) {
  15200. object.onBeforeRender(_this, scene, camera, geometry, material, group);
  15201. currentRenderState = renderStates.get(scene, _currentArrayCamera || camera);
  15202. object.modelViewMatrix.multiplyMatrices(camera.matrixWorldInverse, object.matrixWorld);
  15203. object.normalMatrix.getNormalMatrix(object.modelViewMatrix);
  15204. if (object.isImmediateRenderObject) {
  15205. const program = setProgram(camera, scene, material, object);
  15206. state.setMaterial(material);
  15207. bindingStates.reset();
  15208. renderObjectImmediate(object, program);
  15209. } else {
  15210. _this.renderBufferDirect(camera, scene, geometry, material, object, group);
  15211. }
  15212. object.onAfterRender(_this, scene, camera, geometry, material, group);
  15213. currentRenderState = renderStates.get(scene, _currentArrayCamera || camera);
  15214. }
  15215. function initMaterial(material, scene, object) {
  15216. if (scene.isScene !== true) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...
  15217. const materialProperties = properties.get(material);
  15218. const lights = currentRenderState.state.lights;
  15219. const shadowsArray = currentRenderState.state.shadowsArray;
  15220. const lightsStateVersion = lights.state.version;
  15221. const parameters = programCache.getParameters(material, lights.state, shadowsArray, scene, object);
  15222. const programCacheKey = programCache.getProgramCacheKey(parameters);
  15223. let program = materialProperties.program;
  15224. let programChange = true;
  15225. if (program === undefined) {
  15226. // new material
  15227. material.addEventListener('dispose', onMaterialDispose);
  15228. } else if (program.cacheKey !== programCacheKey) {
  15229. // changed glsl or parameters
  15230. releaseMaterialProgramReference(material);
  15231. } else if (materialProperties.lightsStateVersion !== lightsStateVersion) {
  15232. programChange = false;
  15233. } else if (parameters.shaderID !== undefined) {
  15234. // same glsl and uniform list, envMap still needs the update here to avoid a frame-late effect
  15235. const environment = material.isMeshStandardMaterial ? scene.environment : null;
  15236. materialProperties.envMap = cubemaps.get(material.envMap || environment);
  15237. return;
  15238. } else {
  15239. // only rebuild uniform list
  15240. programChange = false;
  15241. }
  15242. if (programChange) {
  15243. parameters.uniforms = programCache.getUniforms(material);
  15244. material.onBeforeCompile(parameters, _this);
  15245. program = programCache.acquireProgram(parameters, programCacheKey);
  15246. materialProperties.program = program;
  15247. materialProperties.uniforms = parameters.uniforms;
  15248. materialProperties.outputEncoding = parameters.outputEncoding;
  15249. }
  15250. const uniforms = materialProperties.uniforms;
  15251. if (!material.isShaderMaterial && !material.isRawShaderMaterial || material.clipping === true) {
  15252. materialProperties.numClippingPlanes = clipping.numPlanes;
  15253. materialProperties.numIntersection = clipping.numIntersection;
  15254. uniforms.clippingPlanes = clipping.uniform;
  15255. }
  15256. materialProperties.environment = material.isMeshStandardMaterial ? scene.environment : null;
  15257. materialProperties.fog = scene.fog;
  15258. materialProperties.envMap = cubemaps.get(material.envMap || materialProperties.environment); // store the light setup it was created for
  15259. materialProperties.needsLights = materialNeedsLights(material);
  15260. materialProperties.lightsStateVersion = lightsStateVersion;
  15261. if (materialProperties.needsLights) {
  15262. // wire up the material to this renderer's lighting state
  15263. uniforms.ambientLightColor.value = lights.state.ambient;
  15264. uniforms.lightProbe.value = lights.state.probe;
  15265. uniforms.directionalLights.value = lights.state.directional;
  15266. uniforms.directionalLightShadows.value = lights.state.directionalShadow;
  15267. uniforms.spotLights.value = lights.state.spot;
  15268. uniforms.spotLightShadows.value = lights.state.spotShadow;
  15269. uniforms.rectAreaLights.value = lights.state.rectArea;
  15270. uniforms.ltc_1.value = lights.state.rectAreaLTC1;
  15271. uniforms.ltc_2.value = lights.state.rectAreaLTC2;
  15272. uniforms.pointLights.value = lights.state.point;
  15273. uniforms.pointLightShadows.value = lights.state.pointShadow;
  15274. uniforms.hemisphereLights.value = lights.state.hemi;
  15275. uniforms.directionalShadowMap.value = lights.state.directionalShadowMap;
  15276. uniforms.directionalShadowMatrix.value = lights.state.directionalShadowMatrix;
  15277. uniforms.spotShadowMap.value = lights.state.spotShadowMap;
  15278. uniforms.spotShadowMatrix.value = lights.state.spotShadowMatrix;
  15279. uniforms.pointShadowMap.value = lights.state.pointShadowMap;
  15280. uniforms.pointShadowMatrix.value = lights.state.pointShadowMatrix; // TODO (abelnation): add area lights shadow info to uniforms
  15281. }
  15282. const progUniforms = materialProperties.program.getUniforms();
  15283. const uniformsList = WebGLUniforms.seqWithValue(progUniforms.seq, uniforms);
  15284. materialProperties.uniformsList = uniformsList;
  15285. }
  15286. function setProgram(camera, scene, material, object) {
  15287. if (scene.isScene !== true) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...
  15288. textures.resetTextureUnits();
  15289. const fog = scene.fog;
  15290. const environment = material.isMeshStandardMaterial ? scene.environment : null;
  15291. const encoding = _currentRenderTarget === null ? _this.outputEncoding : _currentRenderTarget.texture.encoding;
  15292. const envMap = cubemaps.get(material.envMap || environment);
  15293. const materialProperties = properties.get(material);
  15294. const lights = currentRenderState.state.lights;
  15295. if (_clippingEnabled === true) {
  15296. if (_localClippingEnabled === true || camera !== _currentCamera) {
  15297. const useCache = camera === _currentCamera && material.id === _currentMaterialId; // we might want to call this function with some ClippingGroup
  15298. // object instead of the material, once it becomes feasible
  15299. // (#8465, #8379)
  15300. clipping.setState(material, camera, useCache);
  15301. }
  15302. }
  15303. if (material.version === materialProperties.__version) {
  15304. if (material.fog && materialProperties.fog !== fog) {
  15305. initMaterial(material, scene, object);
  15306. } else if (materialProperties.environment !== environment) {
  15307. initMaterial(material, scene, object);
  15308. } else if (materialProperties.needsLights && materialProperties.lightsStateVersion !== lights.state.version) {
  15309. initMaterial(material, scene, object);
  15310. } else if (materialProperties.numClippingPlanes !== undefined && (materialProperties.numClippingPlanes !== clipping.numPlanes || materialProperties.numIntersection !== clipping.numIntersection)) {
  15311. initMaterial(material, scene, object);
  15312. } else if (materialProperties.outputEncoding !== encoding) {
  15313. initMaterial(material, scene, object);
  15314. } else if (materialProperties.envMap !== envMap) {
  15315. initMaterial(material, scene, object);
  15316. }
  15317. } else {
  15318. initMaterial(material, scene, object);
  15319. materialProperties.__version = material.version;
  15320. }
  15321. let refreshProgram = false;
  15322. let refreshMaterial = false;
  15323. let refreshLights = false;
  15324. const program = materialProperties.program,
  15325. p_uniforms = program.getUniforms(),
  15326. m_uniforms = materialProperties.uniforms;
  15327. if (state.useProgram(program.program)) {
  15328. refreshProgram = true;
  15329. refreshMaterial = true;
  15330. refreshLights = true;
  15331. }
  15332. if (material.id !== _currentMaterialId) {
  15333. _currentMaterialId = material.id;
  15334. refreshMaterial = true;
  15335. }
  15336. if (refreshProgram || _currentCamera !== camera) {
  15337. p_uniforms.setValue(_gl, 'projectionMatrix', camera.projectionMatrix);
  15338. if (capabilities.logarithmicDepthBuffer) {
  15339. p_uniforms.setValue(_gl, 'logDepthBufFC', 2.0 / (Math.log(camera.far + 1.0) / Math.LN2));
  15340. }
  15341. if (_currentCamera !== camera) {
  15342. _currentCamera = camera; // lighting uniforms depend on the camera so enforce an update
  15343. // now, in case this material supports lights - or later, when
  15344. // the next material that does gets activated:
  15345. refreshMaterial = true; // set to true on material change
  15346. refreshLights = true; // remains set until update done
  15347. } // load material specific uniforms
  15348. // (shader material also gets them for the sake of genericity)
  15349. if (material.isShaderMaterial || material.isMeshPhongMaterial || material.isMeshToonMaterial || material.isMeshStandardMaterial || material.envMap) {
  15350. const uCamPos = p_uniforms.map.cameraPosition;
  15351. if (uCamPos !== undefined) {
  15352. uCamPos.setValue(_gl, _vector3.setFromMatrixPosition(camera.matrixWorld));
  15353. }
  15354. }
  15355. if (material.isMeshPhongMaterial || material.isMeshToonMaterial || material.isMeshLambertMaterial || material.isMeshBasicMaterial || material.isMeshStandardMaterial || material.isShaderMaterial) {
  15356. p_uniforms.setValue(_gl, 'isOrthographic', camera.isOrthographicCamera === true);
  15357. }
  15358. if (material.isMeshPhongMaterial || material.isMeshToonMaterial || material.isMeshLambertMaterial || material.isMeshBasicMaterial || material.isMeshStandardMaterial || material.isShaderMaterial || material.isShadowMaterial || material.skinning) {
  15359. p_uniforms.setValue(_gl, 'viewMatrix', camera.matrixWorldInverse);
  15360. }
  15361. } // skinning uniforms must be set even if material didn't change
  15362. // auto-setting of texture unit for bone texture must go before other textures
  15363. // otherwise textures used for skinning can take over texture units reserved for other material textures
  15364. if (material.skinning) {
  15365. p_uniforms.setOptional(_gl, object, 'bindMatrix');
  15366. p_uniforms.setOptional(_gl, object, 'bindMatrixInverse');
  15367. const skeleton = object.skeleton;
  15368. if (skeleton) {
  15369. const bones = skeleton.bones;
  15370. if (capabilities.floatVertexTextures) {
  15371. if (skeleton.boneTexture === null) {
  15372. // layout (1 matrix = 4 pixels)
  15373. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  15374. // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8)
  15375. // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16)
  15376. // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32)
  15377. // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64)
  15378. let size = Math.sqrt(bones.length * 4); // 4 pixels needed for 1 matrix
  15379. size = MathUtils.ceilPowerOfTwo(size);
  15380. size = Math.max(size, 4);
  15381. const boneMatrices = new Float32Array(size * size * 4); // 4 floats per RGBA pixel
  15382. boneMatrices.set(skeleton.boneMatrices); // copy current values
  15383. const boneTexture = new DataTexture(boneMatrices, size, size, RGBAFormat, FloatType);
  15384. skeleton.boneMatrices = boneMatrices;
  15385. skeleton.boneTexture = boneTexture;
  15386. skeleton.boneTextureSize = size;
  15387. }
  15388. p_uniforms.setValue(_gl, 'boneTexture', skeleton.boneTexture, textures);
  15389. p_uniforms.setValue(_gl, 'boneTextureSize', skeleton.boneTextureSize);
  15390. } else {
  15391. p_uniforms.setOptional(_gl, skeleton, 'boneMatrices');
  15392. }
  15393. }
  15394. }
  15395. if (refreshMaterial || materialProperties.receiveShadow !== object.receiveShadow) {
  15396. materialProperties.receiveShadow = object.receiveShadow;
  15397. p_uniforms.setValue(_gl, 'receiveShadow', object.receiveShadow);
  15398. }
  15399. if (refreshMaterial) {
  15400. p_uniforms.setValue(_gl, 'toneMappingExposure', _this.toneMappingExposure);
  15401. if (materialProperties.needsLights) {
  15402. // the current material requires lighting info
  15403. // note: all lighting uniforms are always set correctly
  15404. // they simply reference the renderer's state for their
  15405. // values
  15406. //
  15407. // use the current material's .needsUpdate flags to set
  15408. // the GL state when required
  15409. markUniformsLightsNeedsUpdate(m_uniforms, refreshLights);
  15410. } // refresh uniforms common to several materials
  15411. if (fog && material.fog) {
  15412. materials.refreshFogUniforms(m_uniforms, fog);
  15413. }
  15414. materials.refreshMaterialUniforms(m_uniforms, material, _pixelRatio, _height);
  15415. WebGLUniforms.upload(_gl, materialProperties.uniformsList, m_uniforms, textures);
  15416. }
  15417. if (material.isShaderMaterial && material.uniformsNeedUpdate === true) {
  15418. WebGLUniforms.upload(_gl, materialProperties.uniformsList, m_uniforms, textures);
  15419. material.uniformsNeedUpdate = false;
  15420. }
  15421. if (material.isSpriteMaterial) {
  15422. p_uniforms.setValue(_gl, 'center', object.center);
  15423. } // common matrices
  15424. p_uniforms.setValue(_gl, 'modelViewMatrix', object.modelViewMatrix);
  15425. p_uniforms.setValue(_gl, 'normalMatrix', object.normalMatrix);
  15426. p_uniforms.setValue(_gl, 'modelMatrix', object.matrixWorld);
  15427. return program;
  15428. } // If uniforms are marked as clean, they don't need to be loaded to the GPU.
  15429. function markUniformsLightsNeedsUpdate(uniforms, value) {
  15430. uniforms.ambientLightColor.needsUpdate = value;
  15431. uniforms.lightProbe.needsUpdate = value;
  15432. uniforms.directionalLights.needsUpdate = value;
  15433. uniforms.directionalLightShadows.needsUpdate = value;
  15434. uniforms.pointLights.needsUpdate = value;
  15435. uniforms.pointLightShadows.needsUpdate = value;
  15436. uniforms.spotLights.needsUpdate = value;
  15437. uniforms.spotLightShadows.needsUpdate = value;
  15438. uniforms.rectAreaLights.needsUpdate = value;
  15439. uniforms.hemisphereLights.needsUpdate = value;
  15440. }
  15441. function materialNeedsLights(material) {
  15442. return material.isMeshLambertMaterial || material.isMeshToonMaterial || material.isMeshPhongMaterial || material.isMeshStandardMaterial || material.isShadowMaterial || material.isShaderMaterial && material.lights === true;
  15443. } //
  15444. this.setFramebuffer = function (value) {
  15445. if (_framebuffer !== value && _currentRenderTarget === null) _gl.bindFramebuffer(36160, value);
  15446. _framebuffer = value;
  15447. };
  15448. this.getActiveCubeFace = function () {
  15449. return _currentActiveCubeFace;
  15450. };
  15451. this.getActiveMipmapLevel = function () {
  15452. return _currentActiveMipmapLevel;
  15453. };
  15454. this.getRenderList = function () {
  15455. return currentRenderList;
  15456. };
  15457. this.setRenderList = function (renderList) {
  15458. currentRenderList = renderList;
  15459. };
  15460. this.getRenderState = function () {
  15461. return currentRenderState;
  15462. };
  15463. this.setRenderState = function (renderState) {
  15464. currentRenderState = renderState;
  15465. };
  15466. this.getRenderTarget = function () {
  15467. return _currentRenderTarget;
  15468. };
  15469. this.setRenderTarget = function (renderTarget, activeCubeFace = 0, activeMipmapLevel = 0) {
  15470. _currentRenderTarget = renderTarget;
  15471. _currentActiveCubeFace = activeCubeFace;
  15472. _currentActiveMipmapLevel = activeMipmapLevel;
  15473. if (renderTarget && properties.get(renderTarget).__webglFramebuffer === undefined) {
  15474. textures.setupRenderTarget(renderTarget);
  15475. }
  15476. let framebuffer = _framebuffer;
  15477. let isCube = false;
  15478. if (renderTarget) {
  15479. const __webglFramebuffer = properties.get(renderTarget).__webglFramebuffer;
  15480. if (renderTarget.isWebGLCubeRenderTarget) {
  15481. framebuffer = __webglFramebuffer[activeCubeFace];
  15482. isCube = true;
  15483. } else if (renderTarget.isWebGLMultisampleRenderTarget) {
  15484. framebuffer = properties.get(renderTarget).__webglMultisampledFramebuffer;
  15485. } else {
  15486. framebuffer = __webglFramebuffer;
  15487. }
  15488. _currentViewport.copy(renderTarget.viewport);
  15489. _currentScissor.copy(renderTarget.scissor);
  15490. _currentScissorTest = renderTarget.scissorTest;
  15491. } else {
  15492. _currentViewport.copy(_viewport).multiplyScalar(_pixelRatio).floor();
  15493. _currentScissor.copy(_scissor).multiplyScalar(_pixelRatio).floor();
  15494. _currentScissorTest = _scissorTest;
  15495. }
  15496. if (_currentFramebuffer !== framebuffer) {
  15497. _gl.bindFramebuffer(36160, framebuffer);
  15498. _currentFramebuffer = framebuffer;
  15499. }
  15500. state.viewport(_currentViewport);
  15501. state.scissor(_currentScissor);
  15502. state.setScissorTest(_currentScissorTest);
  15503. if (isCube) {
  15504. const textureProperties = properties.get(renderTarget.texture);
  15505. _gl.framebufferTexture2D(36160, 36064, 34069 + activeCubeFace, textureProperties.__webglTexture, activeMipmapLevel);
  15506. }
  15507. };
  15508. this.readRenderTargetPixels = function (renderTarget, x, y, width, height, buffer, activeCubeFaceIndex) {
  15509. if (!(renderTarget && renderTarget.isWebGLRenderTarget)) {
  15510. console.error('THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.');
  15511. return;
  15512. }
  15513. let framebuffer = properties.get(renderTarget).__webglFramebuffer;
  15514. if (renderTarget.isWebGLCubeRenderTarget && activeCubeFaceIndex !== undefined) {
  15515. framebuffer = framebuffer[activeCubeFaceIndex];
  15516. }
  15517. if (framebuffer) {
  15518. let restore = false;
  15519. if (framebuffer !== _currentFramebuffer) {
  15520. _gl.bindFramebuffer(36160, framebuffer);
  15521. restore = true;
  15522. }
  15523. try {
  15524. const texture = renderTarget.texture;
  15525. const textureFormat = texture.format;
  15526. const textureType = texture.type;
  15527. if (textureFormat !== RGBAFormat && utils.convert(textureFormat) !== _gl.getParameter(35739)) {
  15528. console.error('THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.');
  15529. return;
  15530. }
  15531. if (textureType !== UnsignedByteType && utils.convert(textureType) !== _gl.getParameter(35738) && // IE11, Edge and Chrome Mac < 52 (#9513)
  15532. !(textureType === FloatType && (capabilities.isWebGL2 || extensions.get('OES_texture_float') || extensions.get('WEBGL_color_buffer_float'))) && // Chrome Mac >= 52 and Firefox
  15533. !(textureType === HalfFloatType && (capabilities.isWebGL2 ? extensions.get('EXT_color_buffer_float') : extensions.get('EXT_color_buffer_half_float')))) {
  15534. console.error('THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.');
  15535. return;
  15536. }
  15537. if (_gl.checkFramebufferStatus(36160) === 36053) {
  15538. // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604)
  15539. if (x >= 0 && x <= renderTarget.width - width && y >= 0 && y <= renderTarget.height - height) {
  15540. _gl.readPixels(x, y, width, height, utils.convert(textureFormat), utils.convert(textureType), buffer);
  15541. }
  15542. } else {
  15543. console.error('THREE.WebGLRenderer.readRenderTargetPixels: readPixels from renderTarget failed. Framebuffer not complete.');
  15544. }
  15545. } finally {
  15546. if (restore) {
  15547. _gl.bindFramebuffer(36160, _currentFramebuffer);
  15548. }
  15549. }
  15550. }
  15551. };
  15552. this.copyFramebufferToTexture = function (position, texture, level = 0) {
  15553. const levelScale = Math.pow(2, -level);
  15554. const width = Math.floor(texture.image.width * levelScale);
  15555. const height = Math.floor(texture.image.height * levelScale);
  15556. const glFormat = utils.convert(texture.format);
  15557. textures.setTexture2D(texture, 0);
  15558. _gl.copyTexImage2D(3553, level, glFormat, position.x, position.y, width, height, 0);
  15559. state.unbindTexture();
  15560. };
  15561. this.copyTextureToTexture = function (position, srcTexture, dstTexture, level = 0) {
  15562. const width = srcTexture.image.width;
  15563. const height = srcTexture.image.height;
  15564. const glFormat = utils.convert(dstTexture.format);
  15565. const glType = utils.convert(dstTexture.type);
  15566. textures.setTexture2D(dstTexture, 0); // As another texture upload may have changed pixelStorei
  15567. // parameters, make sure they are correct for the dstTexture
  15568. _gl.pixelStorei(37440, dstTexture.flipY);
  15569. _gl.pixelStorei(37441, dstTexture.premultiplyAlpha);
  15570. _gl.pixelStorei(3317, dstTexture.unpackAlignment);
  15571. if (srcTexture.isDataTexture) {
  15572. _gl.texSubImage2D(3553, level, position.x, position.y, width, height, glFormat, glType, srcTexture.image.data);
  15573. } else {
  15574. if (srcTexture.isCompressedTexture) {
  15575. _gl.compressedTexSubImage2D(3553, level, position.x, position.y, srcTexture.mipmaps[0].width, srcTexture.mipmaps[0].height, glFormat, srcTexture.mipmaps[0].data);
  15576. } else {
  15577. _gl.texSubImage2D(3553, level, position.x, position.y, glFormat, glType, srcTexture.image);
  15578. }
  15579. } // Generate mipmaps only when copying level 0
  15580. if (level === 0 && dstTexture.generateMipmaps) _gl.generateMipmap(3553);
  15581. state.unbindTexture();
  15582. };
  15583. this.initTexture = function (texture) {
  15584. textures.setTexture2D(texture, 0);
  15585. state.unbindTexture();
  15586. };
  15587. if (typeof __THREE_DEVTOOLS__ !== 'undefined') {
  15588. __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent('observe', {
  15589. detail: this
  15590. })); // eslint-disable-line no-undef
  15591. }
  15592. }
  15593. function WebGL1Renderer(parameters) {
  15594. WebGLRenderer.call(this, parameters);
  15595. }
  15596. WebGL1Renderer.prototype = Object.assign(Object.create(WebGLRenderer.prototype), {
  15597. constructor: WebGL1Renderer,
  15598. isWebGL1Renderer: true
  15599. });
  15600. class FogExp2 {
  15601. constructor(color, density) {
  15602. Object.defineProperty(this, 'isFogExp2', {
  15603. value: true
  15604. });
  15605. this.name = '';
  15606. this.color = new Color(color);
  15607. this.density = density !== undefined ? density : 0.00025;
  15608. }
  15609. clone() {
  15610. return new FogExp2(this.color, this.density);
  15611. }
  15612. toJSON()
  15613. /* meta */
  15614. {
  15615. return {
  15616. type: 'FogExp2',
  15617. color: this.color.getHex(),
  15618. density: this.density
  15619. };
  15620. }
  15621. }
  15622. exports.FogExp2 = FogExp2;
  15623. class Fog {
  15624. constructor(color, near, far) {
  15625. Object.defineProperty(this, 'isFog', {
  15626. value: true
  15627. });
  15628. this.name = '';
  15629. this.color = new Color(color);
  15630. this.near = near !== undefined ? near : 1;
  15631. this.far = far !== undefined ? far : 1000;
  15632. }
  15633. clone() {
  15634. return new Fog(this.color, this.near, this.far);
  15635. }
  15636. toJSON()
  15637. /* meta */
  15638. {
  15639. return {
  15640. type: 'Fog',
  15641. color: this.color.getHex(),
  15642. near: this.near,
  15643. far: this.far
  15644. };
  15645. }
  15646. }
  15647. exports.Fog = Fog;
  15648. class Scene extends Object3D {
  15649. constructor() {
  15650. super();
  15651. Object.defineProperty(this, 'isScene', {
  15652. value: true
  15653. });
  15654. this.type = 'Scene';
  15655. this.background = null;
  15656. this.environment = null;
  15657. this.fog = null;
  15658. this.overrideMaterial = null;
  15659. this.autoUpdate = true; // checked by the renderer
  15660. if (typeof __THREE_DEVTOOLS__ !== 'undefined') {
  15661. __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent('observe', {
  15662. detail: this
  15663. })); // eslint-disable-line no-undef
  15664. }
  15665. }
  15666. copy(source, recursive) {
  15667. super.copy(source, recursive);
  15668. if (source.background !== null) this.background = source.background.clone();
  15669. if (source.environment !== null) this.environment = source.environment.clone();
  15670. if (source.fog !== null) this.fog = source.fog.clone();
  15671. if (source.overrideMaterial !== null) this.overrideMaterial = source.overrideMaterial.clone();
  15672. this.autoUpdate = source.autoUpdate;
  15673. this.matrixAutoUpdate = source.matrixAutoUpdate;
  15674. return this;
  15675. }
  15676. toJSON(meta) {
  15677. const data = super.toJSON(meta);
  15678. if (this.background !== null) data.object.background = this.background.toJSON(meta);
  15679. if (this.environment !== null) data.object.environment = this.environment.toJSON(meta);
  15680. if (this.fog !== null) data.object.fog = this.fog.toJSON();
  15681. return data;
  15682. }
  15683. }
  15684. exports.Scene = Scene;
  15685. function InterleavedBuffer(array, stride) {
  15686. this.array = array;
  15687. this.stride = stride;
  15688. this.count = array !== undefined ? array.length / stride : 0;
  15689. this.usage = StaticDrawUsage;
  15690. this.updateRange = {
  15691. offset: 0,
  15692. count: -1
  15693. };
  15694. this.version = 0;
  15695. this.uuid = MathUtils.generateUUID();
  15696. }
  15697. Object.defineProperty(InterleavedBuffer.prototype, 'needsUpdate', {
  15698. set: function (value) {
  15699. if (value === true) this.version++;
  15700. }
  15701. });
  15702. Object.assign(InterleavedBuffer.prototype, {
  15703. isInterleavedBuffer: true,
  15704. onUploadCallback: function () {},
  15705. setUsage: function (value) {
  15706. this.usage = value;
  15707. return this;
  15708. },
  15709. copy: function (source) {
  15710. this.array = new source.array.constructor(source.array);
  15711. this.count = source.count;
  15712. this.stride = source.stride;
  15713. this.usage = source.usage;
  15714. return this;
  15715. },
  15716. copyAt: function (index1, attribute, index2) {
  15717. index1 *= this.stride;
  15718. index2 *= attribute.stride;
  15719. for (let i = 0, l = this.stride; i < l; i++) {
  15720. this.array[index1 + i] = attribute.array[index2 + i];
  15721. }
  15722. return this;
  15723. },
  15724. set: function (value, offset = 0) {
  15725. this.array.set(value, offset);
  15726. return this;
  15727. },
  15728. clone: function (data) {
  15729. if (data.arrayBuffers === undefined) {
  15730. data.arrayBuffers = {};
  15731. }
  15732. if (this.array.buffer._uuid === undefined) {
  15733. this.array.buffer._uuid = MathUtils.generateUUID();
  15734. }
  15735. if (data.arrayBuffers[this.array.buffer._uuid] === undefined) {
  15736. data.arrayBuffers[this.array.buffer._uuid] = this.array.slice(0).buffer;
  15737. }
  15738. const array = new this.array.constructor(data.arrayBuffers[this.array.buffer._uuid]);
  15739. const ib = new InterleavedBuffer(array, this.stride);
  15740. ib.setUsage(this.usage);
  15741. return ib;
  15742. },
  15743. onUpload: function (callback) {
  15744. this.onUploadCallback = callback;
  15745. return this;
  15746. },
  15747. toJSON: function (data) {
  15748. if (data.arrayBuffers === undefined) {
  15749. data.arrayBuffers = {};
  15750. } // generate UUID for array buffer if necessary
  15751. if (this.array.buffer._uuid === undefined) {
  15752. this.array.buffer._uuid = MathUtils.generateUUID();
  15753. }
  15754. if (data.arrayBuffers[this.array.buffer._uuid] === undefined) {
  15755. data.arrayBuffers[this.array.buffer._uuid] = Array.prototype.slice.call(new Uint32Array(this.array.buffer));
  15756. } //
  15757. return {
  15758. uuid: this.uuid,
  15759. buffer: this.array.buffer._uuid,
  15760. type: this.array.constructor.name,
  15761. stride: this.stride
  15762. };
  15763. }
  15764. });
  15765. const _vector$6 = new Vector3();
  15766. function InterleavedBufferAttribute(interleavedBuffer, itemSize, offset, normalized) {
  15767. this.name = '';
  15768. this.data = interleavedBuffer;
  15769. this.itemSize = itemSize;
  15770. this.offset = offset;
  15771. this.normalized = normalized === true;
  15772. }
  15773. Object.defineProperties(InterleavedBufferAttribute.prototype, {
  15774. count: {
  15775. get: function () {
  15776. return this.data.count;
  15777. }
  15778. },
  15779. array: {
  15780. get: function () {
  15781. return this.data.array;
  15782. }
  15783. },
  15784. needsUpdate: {
  15785. set: function (value) {
  15786. this.data.needsUpdate = value;
  15787. }
  15788. }
  15789. });
  15790. Object.assign(InterleavedBufferAttribute.prototype, {
  15791. isInterleavedBufferAttribute: true,
  15792. applyMatrix4: function (m) {
  15793. for (let i = 0, l = this.data.count; i < l; i++) {
  15794. _vector$6.x = this.getX(i);
  15795. _vector$6.y = this.getY(i);
  15796. _vector$6.z = this.getZ(i);
  15797. _vector$6.applyMatrix4(m);
  15798. this.setXYZ(i, _vector$6.x, _vector$6.y, _vector$6.z);
  15799. }
  15800. return this;
  15801. },
  15802. setX: function (index, x) {
  15803. this.data.array[index * this.data.stride + this.offset] = x;
  15804. return this;
  15805. },
  15806. setY: function (index, y) {
  15807. this.data.array[index * this.data.stride + this.offset + 1] = y;
  15808. return this;
  15809. },
  15810. setZ: function (index, z) {
  15811. this.data.array[index * this.data.stride + this.offset + 2] = z;
  15812. return this;
  15813. },
  15814. setW: function (index, w) {
  15815. this.data.array[index * this.data.stride + this.offset + 3] = w;
  15816. return this;
  15817. },
  15818. getX: function (index) {
  15819. return this.data.array[index * this.data.stride + this.offset];
  15820. },
  15821. getY: function (index) {
  15822. return this.data.array[index * this.data.stride + this.offset + 1];
  15823. },
  15824. getZ: function (index) {
  15825. return this.data.array[index * this.data.stride + this.offset + 2];
  15826. },
  15827. getW: function (index) {
  15828. return this.data.array[index * this.data.stride + this.offset + 3];
  15829. },
  15830. setXY: function (index, x, y) {
  15831. index = index * this.data.stride + this.offset;
  15832. this.data.array[index + 0] = x;
  15833. this.data.array[index + 1] = y;
  15834. return this;
  15835. },
  15836. setXYZ: function (index, x, y, z) {
  15837. index = index * this.data.stride + this.offset;
  15838. this.data.array[index + 0] = x;
  15839. this.data.array[index + 1] = y;
  15840. this.data.array[index + 2] = z;
  15841. return this;
  15842. },
  15843. setXYZW: function (index, x, y, z, w) {
  15844. index = index * this.data.stride + this.offset;
  15845. this.data.array[index + 0] = x;
  15846. this.data.array[index + 1] = y;
  15847. this.data.array[index + 2] = z;
  15848. this.data.array[index + 3] = w;
  15849. return this;
  15850. },
  15851. clone: function (data) {
  15852. if (data === undefined) {
  15853. console.log('THREE.InterleavedBufferAttribute.clone(): Cloning an interlaved buffer attribute will deinterleave buffer data.');
  15854. const array = [];
  15855. for (let i = 0; i < this.count; i++) {
  15856. const index = i * this.data.stride + this.offset;
  15857. for (let j = 0; j < this.itemSize; j++) {
  15858. array.push(this.data.array[index + j]);
  15859. }
  15860. }
  15861. return new BufferAttribute(new this.array.constructor(array), this.itemSize, this.normalized);
  15862. } else {
  15863. if (data.interleavedBuffers === undefined) {
  15864. data.interleavedBuffers = {};
  15865. }
  15866. if (data.interleavedBuffers[this.data.uuid] === undefined) {
  15867. data.interleavedBuffers[this.data.uuid] = this.data.clone(data);
  15868. }
  15869. return new InterleavedBufferAttribute(data.interleavedBuffers[this.data.uuid], this.itemSize, this.offset, this.normalized);
  15870. }
  15871. },
  15872. toJSON: function (data) {
  15873. if (data === undefined) {
  15874. console.log('THREE.InterleavedBufferAttribute.toJSON(): Serializing an interlaved buffer attribute will deinterleave buffer data.');
  15875. const array = [];
  15876. for (let i = 0; i < this.count; i++) {
  15877. const index = i * this.data.stride + this.offset;
  15878. for (let j = 0; j < this.itemSize; j++) {
  15879. array.push(this.data.array[index + j]);
  15880. }
  15881. } // deinterleave data and save it as an ordinary buffer attribute for now
  15882. return {
  15883. itemSize: this.itemSize,
  15884. type: this.array.constructor.name,
  15885. array: array,
  15886. normalized: this.normalized
  15887. };
  15888. } else {
  15889. // save as true interlaved attribtue
  15890. if (data.interleavedBuffers === undefined) {
  15891. data.interleavedBuffers = {};
  15892. }
  15893. if (data.interleavedBuffers[this.data.uuid] === undefined) {
  15894. data.interleavedBuffers[this.data.uuid] = this.data.toJSON(data);
  15895. }
  15896. return {
  15897. isInterleavedBufferAttribute: true,
  15898. itemSize: this.itemSize,
  15899. data: this.data.uuid,
  15900. offset: this.offset,
  15901. normalized: this.normalized
  15902. };
  15903. }
  15904. }
  15905. });
  15906. /**
  15907. * parameters = {
  15908. * color: <hex>,
  15909. * map: new THREE.Texture( <Image> ),
  15910. * alphaMap: new THREE.Texture( <Image> ),
  15911. * rotation: <float>,
  15912. * sizeAttenuation: <bool>
  15913. * }
  15914. */
  15915. function SpriteMaterial(parameters) {
  15916. Material.call(this);
  15917. this.type = 'SpriteMaterial';
  15918. this.color = new Color(0xffffff);
  15919. this.map = null;
  15920. this.alphaMap = null;
  15921. this.rotation = 0;
  15922. this.sizeAttenuation = true;
  15923. this.transparent = true;
  15924. this.setValues(parameters);
  15925. }
  15926. SpriteMaterial.prototype = Object.create(Material.prototype);
  15927. SpriteMaterial.prototype.constructor = SpriteMaterial;
  15928. SpriteMaterial.prototype.isSpriteMaterial = true;
  15929. SpriteMaterial.prototype.copy = function (source) {
  15930. Material.prototype.copy.call(this, source);
  15931. this.color.copy(source.color);
  15932. this.map = source.map;
  15933. this.alphaMap = source.alphaMap;
  15934. this.rotation = source.rotation;
  15935. this.sizeAttenuation = source.sizeAttenuation;
  15936. return this;
  15937. };
  15938. let _geometry;
  15939. const _intersectPoint = new Vector3();
  15940. const _worldScale = new Vector3();
  15941. const _mvPosition = new Vector3();
  15942. const _alignedPosition = new Vector2();
  15943. const _rotatedPosition = new Vector2();
  15944. const _viewWorldMatrix = new Matrix4();
  15945. const _vA$1 = new Vector3();
  15946. const _vB$1 = new Vector3();
  15947. const _vC$1 = new Vector3();
  15948. const _uvA$1 = new Vector2();
  15949. const _uvB$1 = new Vector2();
  15950. const _uvC$1 = new Vector2();
  15951. function Sprite(material) {
  15952. Object3D.call(this);
  15953. this.type = 'Sprite';
  15954. if (_geometry === undefined) {
  15955. _geometry = new BufferGeometry();
  15956. const float32Array = new Float32Array([-0.5, -0.5, 0, 0, 0, 0.5, -0.5, 0, 1, 0, 0.5, 0.5, 0, 1, 1, -0.5, 0.5, 0, 0, 1]);
  15957. const interleavedBuffer = new InterleavedBuffer(float32Array, 5);
  15958. _geometry.setIndex([0, 1, 2, 0, 2, 3]);
  15959. _geometry.setAttribute('position', new InterleavedBufferAttribute(interleavedBuffer, 3, 0, false));
  15960. _geometry.setAttribute('uv', new InterleavedBufferAttribute(interleavedBuffer, 2, 3, false));
  15961. }
  15962. this.geometry = _geometry;
  15963. this.material = material !== undefined ? material : new SpriteMaterial();
  15964. this.center = new Vector2(0.5, 0.5);
  15965. }
  15966. Sprite.prototype = Object.assign(Object.create(Object3D.prototype), {
  15967. constructor: Sprite,
  15968. isSprite: true,
  15969. raycast: function (raycaster, intersects) {
  15970. if (raycaster.camera === null) {
  15971. console.error('THREE.Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.');
  15972. }
  15973. _worldScale.setFromMatrixScale(this.matrixWorld);
  15974. _viewWorldMatrix.copy(raycaster.camera.matrixWorld);
  15975. this.modelViewMatrix.multiplyMatrices(raycaster.camera.matrixWorldInverse, this.matrixWorld);
  15976. _mvPosition.setFromMatrixPosition(this.modelViewMatrix);
  15977. if (raycaster.camera.isPerspectiveCamera && this.material.sizeAttenuation === false) {
  15978. _worldScale.multiplyScalar(-_mvPosition.z);
  15979. }
  15980. const rotation = this.material.rotation;
  15981. let sin, cos;
  15982. if (rotation !== 0) {
  15983. cos = Math.cos(rotation);
  15984. sin = Math.sin(rotation);
  15985. }
  15986. const center = this.center;
  15987. transformVertex(_vA$1.set(-0.5, -0.5, 0), _mvPosition, center, _worldScale, sin, cos);
  15988. transformVertex(_vB$1.set(0.5, -0.5, 0), _mvPosition, center, _worldScale, sin, cos);
  15989. transformVertex(_vC$1.set(0.5, 0.5, 0), _mvPosition, center, _worldScale, sin, cos);
  15990. _uvA$1.set(0, 0);
  15991. _uvB$1.set(1, 0);
  15992. _uvC$1.set(1, 1); // check first triangle
  15993. let intersect = raycaster.ray.intersectTriangle(_vA$1, _vB$1, _vC$1, false, _intersectPoint);
  15994. if (intersect === null) {
  15995. // check second triangle
  15996. transformVertex(_vB$1.set(-0.5, 0.5, 0), _mvPosition, center, _worldScale, sin, cos);
  15997. _uvB$1.set(0, 1);
  15998. intersect = raycaster.ray.intersectTriangle(_vA$1, _vC$1, _vB$1, false, _intersectPoint);
  15999. if (intersect === null) {
  16000. return;
  16001. }
  16002. }
  16003. const distance = raycaster.ray.origin.distanceTo(_intersectPoint);
  16004. if (distance < raycaster.near || distance > raycaster.far) return;
  16005. intersects.push({
  16006. distance: distance,
  16007. point: _intersectPoint.clone(),
  16008. uv: Triangle.getUV(_intersectPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2()),
  16009. face: null,
  16010. object: this
  16011. });
  16012. },
  16013. copy: function (source) {
  16014. Object3D.prototype.copy.call(this, source);
  16015. if (source.center !== undefined) this.center.copy(source.center);
  16016. this.material = source.material;
  16017. return this;
  16018. }
  16019. });
  16020. function transformVertex(vertexPosition, mvPosition, center, scale, sin, cos) {
  16021. // compute position in camera space
  16022. _alignedPosition.subVectors(vertexPosition, center).addScalar(0.5).multiply(scale); // to check if rotation is not zero
  16023. if (sin !== undefined) {
  16024. _rotatedPosition.x = cos * _alignedPosition.x - sin * _alignedPosition.y;
  16025. _rotatedPosition.y = sin * _alignedPosition.x + cos * _alignedPosition.y;
  16026. } else {
  16027. _rotatedPosition.copy(_alignedPosition);
  16028. }
  16029. vertexPosition.copy(mvPosition);
  16030. vertexPosition.x += _rotatedPosition.x;
  16031. vertexPosition.y += _rotatedPosition.y; // transform to world space
  16032. vertexPosition.applyMatrix4(_viewWorldMatrix);
  16033. }
  16034. const _v1$4 = new Vector3();
  16035. const _v2$2 = new Vector3();
  16036. function LOD() {
  16037. Object3D.call(this);
  16038. this._currentLevel = 0;
  16039. this.type = 'LOD';
  16040. Object.defineProperties(this, {
  16041. levels: {
  16042. enumerable: true,
  16043. value: []
  16044. }
  16045. });
  16046. this.autoUpdate = true;
  16047. }
  16048. LOD.prototype = Object.assign(Object.create(Object3D.prototype), {
  16049. constructor: LOD,
  16050. isLOD: true,
  16051. copy: function (source) {
  16052. Object3D.prototype.copy.call(this, source, false);
  16053. const levels = source.levels;
  16054. for (let i = 0, l = levels.length; i < l; i++) {
  16055. const level = levels[i];
  16056. this.addLevel(level.object.clone(), level.distance);
  16057. }
  16058. this.autoUpdate = source.autoUpdate;
  16059. return this;
  16060. },
  16061. addLevel: function (object, distance = 0) {
  16062. distance = Math.abs(distance);
  16063. const levels = this.levels;
  16064. let l;
  16065. for (l = 0; l < levels.length; l++) {
  16066. if (distance < levels[l].distance) {
  16067. break;
  16068. }
  16069. }
  16070. levels.splice(l, 0, {
  16071. distance: distance,
  16072. object: object
  16073. });
  16074. this.add(object);
  16075. return this;
  16076. },
  16077. getCurrentLevel: function () {
  16078. return this._currentLevel;
  16079. },
  16080. getObjectForDistance: function (distance) {
  16081. const levels = this.levels;
  16082. if (levels.length > 0) {
  16083. let i, l;
  16084. for (i = 1, l = levels.length; i < l; i++) {
  16085. if (distance < levels[i].distance) {
  16086. break;
  16087. }
  16088. }
  16089. return levels[i - 1].object;
  16090. }
  16091. return null;
  16092. },
  16093. raycast: function (raycaster, intersects) {
  16094. const levels = this.levels;
  16095. if (levels.length > 0) {
  16096. _v1$4.setFromMatrixPosition(this.matrixWorld);
  16097. const distance = raycaster.ray.origin.distanceTo(_v1$4);
  16098. this.getObjectForDistance(distance).raycast(raycaster, intersects);
  16099. }
  16100. },
  16101. update: function (camera) {
  16102. const levels = this.levels;
  16103. if (levels.length > 1) {
  16104. _v1$4.setFromMatrixPosition(camera.matrixWorld);
  16105. _v2$2.setFromMatrixPosition(this.matrixWorld);
  16106. const distance = _v1$4.distanceTo(_v2$2) / camera.zoom;
  16107. levels[0].object.visible = true;
  16108. let i, l;
  16109. for (i = 1, l = levels.length; i < l; i++) {
  16110. if (distance >= levels[i].distance) {
  16111. levels[i - 1].object.visible = false;
  16112. levels[i].object.visible = true;
  16113. } else {
  16114. break;
  16115. }
  16116. }
  16117. this._currentLevel = i - 1;
  16118. for (; i < l; i++) {
  16119. levels[i].object.visible = false;
  16120. }
  16121. }
  16122. },
  16123. toJSON: function (meta) {
  16124. const data = Object3D.prototype.toJSON.call(this, meta);
  16125. if (this.autoUpdate === false) data.object.autoUpdate = false;
  16126. data.object.levels = [];
  16127. const levels = this.levels;
  16128. for (let i = 0, l = levels.length; i < l; i++) {
  16129. const level = levels[i];
  16130. data.object.levels.push({
  16131. object: level.object.uuid,
  16132. distance: level.distance
  16133. });
  16134. }
  16135. return data;
  16136. }
  16137. });
  16138. function SkinnedMesh(geometry, material) {
  16139. if (geometry && geometry.isGeometry) {
  16140. console.error('THREE.SkinnedMesh no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');
  16141. }
  16142. Mesh.call(this, geometry, material);
  16143. this.type = 'SkinnedMesh';
  16144. this.bindMode = 'attached';
  16145. this.bindMatrix = new Matrix4();
  16146. this.bindMatrixInverse = new Matrix4();
  16147. }
  16148. SkinnedMesh.prototype = Object.assign(Object.create(Mesh.prototype), {
  16149. constructor: SkinnedMesh,
  16150. isSkinnedMesh: true,
  16151. copy: function (source) {
  16152. Mesh.prototype.copy.call(this, source);
  16153. this.bindMode = source.bindMode;
  16154. this.bindMatrix.copy(source.bindMatrix);
  16155. this.bindMatrixInverse.copy(source.bindMatrixInverse);
  16156. this.skeleton = source.skeleton;
  16157. return this;
  16158. },
  16159. bind: function (skeleton, bindMatrix) {
  16160. this.skeleton = skeleton;
  16161. if (bindMatrix === undefined) {
  16162. this.updateMatrixWorld(true);
  16163. this.skeleton.calculateInverses();
  16164. bindMatrix = this.matrixWorld;
  16165. }
  16166. this.bindMatrix.copy(bindMatrix);
  16167. this.bindMatrixInverse.copy(bindMatrix).invert();
  16168. },
  16169. pose: function () {
  16170. this.skeleton.pose();
  16171. },
  16172. normalizeSkinWeights: function () {
  16173. const vector = new Vector4();
  16174. const skinWeight = this.geometry.attributes.skinWeight;
  16175. for (let i = 0, l = skinWeight.count; i < l; i++) {
  16176. vector.x = skinWeight.getX(i);
  16177. vector.y = skinWeight.getY(i);
  16178. vector.z = skinWeight.getZ(i);
  16179. vector.w = skinWeight.getW(i);
  16180. const scale = 1.0 / vector.manhattanLength();
  16181. if (scale !== Infinity) {
  16182. vector.multiplyScalar(scale);
  16183. } else {
  16184. vector.set(1, 0, 0, 0); // do something reasonable
  16185. }
  16186. skinWeight.setXYZW(i, vector.x, vector.y, vector.z, vector.w);
  16187. }
  16188. },
  16189. updateMatrixWorld: function (force) {
  16190. Mesh.prototype.updateMatrixWorld.call(this, force);
  16191. if (this.bindMode === 'attached') {
  16192. this.bindMatrixInverse.copy(this.matrixWorld).invert();
  16193. } else if (this.bindMode === 'detached') {
  16194. this.bindMatrixInverse.copy(this.bindMatrix).invert();
  16195. } else {
  16196. console.warn('THREE.SkinnedMesh: Unrecognized bindMode: ' + this.bindMode);
  16197. }
  16198. },
  16199. boneTransform: function () {
  16200. const basePosition = new Vector3();
  16201. const skinIndex = new Vector4();
  16202. const skinWeight = new Vector4();
  16203. const vector = new Vector3();
  16204. const matrix = new Matrix4();
  16205. return function (index, target) {
  16206. const skeleton = this.skeleton;
  16207. const geometry = this.geometry;
  16208. skinIndex.fromBufferAttribute(geometry.attributes.skinIndex, index);
  16209. skinWeight.fromBufferAttribute(geometry.attributes.skinWeight, index);
  16210. basePosition.fromBufferAttribute(geometry.attributes.position, index).applyMatrix4(this.bindMatrix);
  16211. target.set(0, 0, 0);
  16212. for (let i = 0; i < 4; i++) {
  16213. const weight = skinWeight.getComponent(i);
  16214. if (weight !== 0) {
  16215. const boneIndex = skinIndex.getComponent(i);
  16216. matrix.multiplyMatrices(skeleton.bones[boneIndex].matrixWorld, skeleton.boneInverses[boneIndex]);
  16217. target.addScaledVector(vector.copy(basePosition).applyMatrix4(matrix), weight);
  16218. }
  16219. }
  16220. return target.applyMatrix4(this.bindMatrixInverse);
  16221. };
  16222. }()
  16223. });
  16224. function Bone() {
  16225. Object3D.call(this);
  16226. this.type = 'Bone';
  16227. }
  16228. Bone.prototype = Object.assign(Object.create(Object3D.prototype), {
  16229. constructor: Bone,
  16230. isBone: true
  16231. });
  16232. const _offsetMatrix = new Matrix4();
  16233. const _identityMatrix = new Matrix4();
  16234. function Skeleton(bones = [], boneInverses = []) {
  16235. this.uuid = MathUtils.generateUUID();
  16236. this.bones = bones.slice(0);
  16237. this.boneInverses = boneInverses;
  16238. this.boneMatrices = null;
  16239. this.boneTexture = null;
  16240. this.boneTextureSize = 0;
  16241. this.frame = -1;
  16242. this.init();
  16243. }
  16244. Object.assign(Skeleton.prototype, {
  16245. init: function () {
  16246. const bones = this.bones;
  16247. const boneInverses = this.boneInverses;
  16248. this.boneMatrices = new Float32Array(bones.length * 16); // calculate inverse bone matrices if necessary
  16249. if (boneInverses.length === 0) {
  16250. this.calculateInverses();
  16251. } else {
  16252. // handle special case
  16253. if (bones.length !== boneInverses.length) {
  16254. console.warn('THREE.Skeleton: Number of inverse bone matrices does not match amount of bones.');
  16255. this.boneInverses = [];
  16256. for (let i = 0, il = this.bones.length; i < il; i++) {
  16257. this.boneInverses.push(new Matrix4());
  16258. }
  16259. }
  16260. }
  16261. },
  16262. calculateInverses: function () {
  16263. this.boneInverses.length = 0;
  16264. for (let i = 0, il = this.bones.length; i < il; i++) {
  16265. const inverse = new Matrix4();
  16266. if (this.bones[i]) {
  16267. inverse.copy(this.bones[i].matrixWorld).invert();
  16268. }
  16269. this.boneInverses.push(inverse);
  16270. }
  16271. },
  16272. pose: function () {
  16273. // recover the bind-time world matrices
  16274. for (let i = 0, il = this.bones.length; i < il; i++) {
  16275. const bone = this.bones[i];
  16276. if (bone) {
  16277. bone.matrixWorld.copy(this.boneInverses[i]).invert();
  16278. }
  16279. } // compute the local matrices, positions, rotations and scales
  16280. for (let i = 0, il = this.bones.length; i < il; i++) {
  16281. const bone = this.bones[i];
  16282. if (bone) {
  16283. if (bone.parent && bone.parent.isBone) {
  16284. bone.matrix.copy(bone.parent.matrixWorld).invert();
  16285. bone.matrix.multiply(bone.matrixWorld);
  16286. } else {
  16287. bone.matrix.copy(bone.matrixWorld);
  16288. }
  16289. bone.matrix.decompose(bone.position, bone.quaternion, bone.scale);
  16290. }
  16291. }
  16292. },
  16293. update: function () {
  16294. const bones = this.bones;
  16295. const boneInverses = this.boneInverses;
  16296. const boneMatrices = this.boneMatrices;
  16297. const boneTexture = this.boneTexture; // flatten bone matrices to array
  16298. for (let i = 0, il = bones.length; i < il; i++) {
  16299. // compute the offset between the current and the original transform
  16300. const matrix = bones[i] ? bones[i].matrixWorld : _identityMatrix;
  16301. _offsetMatrix.multiplyMatrices(matrix, boneInverses[i]);
  16302. _offsetMatrix.toArray(boneMatrices, i * 16);
  16303. }
  16304. if (boneTexture !== null) {
  16305. boneTexture.needsUpdate = true;
  16306. }
  16307. },
  16308. clone: function () {
  16309. return new Skeleton(this.bones, this.boneInverses);
  16310. },
  16311. getBoneByName: function (name) {
  16312. for (let i = 0, il = this.bones.length; i < il; i++) {
  16313. const bone = this.bones[i];
  16314. if (bone.name === name) {
  16315. return bone;
  16316. }
  16317. }
  16318. return undefined;
  16319. },
  16320. dispose: function () {
  16321. if (this.boneTexture !== null) {
  16322. this.boneTexture.dispose();
  16323. this.boneTexture = null;
  16324. }
  16325. },
  16326. fromJSON: function (json, bones) {
  16327. this.uuid = json.uuid;
  16328. for (let i = 0, l = json.bones.length; i < l; i++) {
  16329. const uuid = json.bones[i];
  16330. let bone = bones[uuid];
  16331. if (bone === undefined) {
  16332. console.warn('THREE.Skeleton: No bone found with UUID:', uuid);
  16333. bone = new Bone();
  16334. }
  16335. this.bones.push(bone);
  16336. this.boneInverses.push(new Matrix4().fromArray(json.boneInverses[i]));
  16337. }
  16338. this.init();
  16339. return this;
  16340. },
  16341. toJSON: function () {
  16342. const data = {
  16343. metadata: {
  16344. version: 4.5,
  16345. type: 'Skeleton',
  16346. generator: 'Skeleton.toJSON'
  16347. },
  16348. bones: [],
  16349. boneInverses: []
  16350. };
  16351. data.uuid = this.uuid;
  16352. const bones = this.bones;
  16353. const boneInverses = this.boneInverses;
  16354. for (let i = 0, l = bones.length; i < l; i++) {
  16355. const bone = bones[i];
  16356. data.bones.push(bone.uuid);
  16357. const boneInverse = boneInverses[i];
  16358. data.boneInverses.push(boneInverse.toArray());
  16359. }
  16360. return data;
  16361. }
  16362. });
  16363. const _instanceLocalMatrix = new Matrix4();
  16364. const _instanceWorldMatrix = new Matrix4();
  16365. const _instanceIntersects = [];
  16366. const _mesh = new Mesh();
  16367. function InstancedMesh(geometry, material, count) {
  16368. Mesh.call(this, geometry, material);
  16369. this.instanceMatrix = new BufferAttribute(new Float32Array(count * 16), 16);
  16370. this.instanceColor = null;
  16371. this.count = count;
  16372. this.frustumCulled = false;
  16373. }
  16374. InstancedMesh.prototype = Object.assign(Object.create(Mesh.prototype), {
  16375. constructor: InstancedMesh,
  16376. isInstancedMesh: true,
  16377. copy: function (source) {
  16378. Mesh.prototype.copy.call(this, source);
  16379. this.instanceMatrix.copy(source.instanceMatrix);
  16380. this.count = source.count;
  16381. return this;
  16382. },
  16383. getColorAt: function (index, color) {
  16384. color.fromArray(this.instanceColor.array, index * 3);
  16385. },
  16386. getMatrixAt: function (index, matrix) {
  16387. matrix.fromArray(this.instanceMatrix.array, index * 16);
  16388. },
  16389. raycast: function (raycaster, intersects) {
  16390. const matrixWorld = this.matrixWorld;
  16391. const raycastTimes = this.count;
  16392. _mesh.geometry = this.geometry;
  16393. _mesh.material = this.material;
  16394. if (_mesh.material === undefined) return;
  16395. for (let instanceId = 0; instanceId < raycastTimes; instanceId++) {
  16396. // calculate the world matrix for each instance
  16397. this.getMatrixAt(instanceId, _instanceLocalMatrix);
  16398. _instanceWorldMatrix.multiplyMatrices(matrixWorld, _instanceLocalMatrix); // the mesh represents this single instance
  16399. _mesh.matrixWorld = _instanceWorldMatrix;
  16400. _mesh.raycast(raycaster, _instanceIntersects); // process the result of raycast
  16401. for (let i = 0, l = _instanceIntersects.length; i < l; i++) {
  16402. const intersect = _instanceIntersects[i];
  16403. intersect.instanceId = instanceId;
  16404. intersect.object = this;
  16405. intersects.push(intersect);
  16406. }
  16407. _instanceIntersects.length = 0;
  16408. }
  16409. },
  16410. setColorAt: function (index, color) {
  16411. if (this.instanceColor === null) {
  16412. this.instanceColor = new BufferAttribute(new Float32Array(this.count * 3), 3);
  16413. }
  16414. color.toArray(this.instanceColor.array, index * 3);
  16415. },
  16416. setMatrixAt: function (index, matrix) {
  16417. matrix.toArray(this.instanceMatrix.array, index * 16);
  16418. },
  16419. updateMorphTargets: function () {}
  16420. });
  16421. /**
  16422. * parameters = {
  16423. * color: <hex>,
  16424. * opacity: <float>,
  16425. *
  16426. * linewidth: <float>,
  16427. * linecap: "round",
  16428. * linejoin: "round"
  16429. * }
  16430. */
  16431. function LineBasicMaterial(parameters) {
  16432. Material.call(this);
  16433. this.type = 'LineBasicMaterial';
  16434. this.color = new Color(0xffffff);
  16435. this.linewidth = 1;
  16436. this.linecap = 'round';
  16437. this.linejoin = 'round';
  16438. this.morphTargets = false;
  16439. this.setValues(parameters);
  16440. }
  16441. LineBasicMaterial.prototype = Object.create(Material.prototype);
  16442. LineBasicMaterial.prototype.constructor = LineBasicMaterial;
  16443. LineBasicMaterial.prototype.isLineBasicMaterial = true;
  16444. LineBasicMaterial.prototype.copy = function (source) {
  16445. Material.prototype.copy.call(this, source);
  16446. this.color.copy(source.color);
  16447. this.linewidth = source.linewidth;
  16448. this.linecap = source.linecap;
  16449. this.linejoin = source.linejoin;
  16450. this.morphTargets = source.morphTargets;
  16451. return this;
  16452. };
  16453. const _start = new Vector3();
  16454. const _end = new Vector3();
  16455. const _inverseMatrix$1 = new Matrix4();
  16456. const _ray$1 = new Ray();
  16457. const _sphere$2 = new Sphere();
  16458. function Line(geometry, material, mode) {
  16459. if (mode === 1) {
  16460. console.error('THREE.Line: parameter THREE.LinePieces no longer supported. Use THREE.LineSegments instead.');
  16461. }
  16462. Object3D.call(this);
  16463. this.type = 'Line';
  16464. this.geometry = geometry !== undefined ? geometry : new BufferGeometry();
  16465. this.material = material !== undefined ? material : new LineBasicMaterial();
  16466. this.updateMorphTargets();
  16467. }
  16468. Line.prototype = Object.assign(Object.create(Object3D.prototype), {
  16469. constructor: Line,
  16470. isLine: true,
  16471. copy: function (source) {
  16472. Object3D.prototype.copy.call(this, source);
  16473. this.material = source.material;
  16474. this.geometry = source.geometry;
  16475. return this;
  16476. },
  16477. computeLineDistances: function () {
  16478. const geometry = this.geometry;
  16479. if (geometry.isBufferGeometry) {
  16480. // we assume non-indexed geometry
  16481. if (geometry.index === null) {
  16482. const positionAttribute = geometry.attributes.position;
  16483. const lineDistances = [0];
  16484. for (let i = 1, l = positionAttribute.count; i < l; i++) {
  16485. _start.fromBufferAttribute(positionAttribute, i - 1);
  16486. _end.fromBufferAttribute(positionAttribute, i);
  16487. lineDistances[i] = lineDistances[i - 1];
  16488. lineDistances[i] += _start.distanceTo(_end);
  16489. }
  16490. geometry.setAttribute('lineDistance', new Float32BufferAttribute(lineDistances, 1));
  16491. } else {
  16492. console.warn('THREE.Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.');
  16493. }
  16494. } else if (geometry.isGeometry) {
  16495. const vertices = geometry.vertices;
  16496. const lineDistances = geometry.lineDistances;
  16497. lineDistances[0] = 0;
  16498. for (let i = 1, l = vertices.length; i < l; i++) {
  16499. lineDistances[i] = lineDistances[i - 1];
  16500. lineDistances[i] += vertices[i - 1].distanceTo(vertices[i]);
  16501. }
  16502. }
  16503. return this;
  16504. },
  16505. raycast: function (raycaster, intersects) {
  16506. const geometry = this.geometry;
  16507. const matrixWorld = this.matrixWorld;
  16508. const threshold = raycaster.params.Line.threshold; // Checking boundingSphere distance to ray
  16509. if (geometry.boundingSphere === null) geometry.computeBoundingSphere();
  16510. _sphere$2.copy(geometry.boundingSphere);
  16511. _sphere$2.applyMatrix4(matrixWorld);
  16512. _sphere$2.radius += threshold;
  16513. if (raycaster.ray.intersectsSphere(_sphere$2) === false) return; //
  16514. _inverseMatrix$1.copy(matrixWorld).invert();
  16515. _ray$1.copy(raycaster.ray).applyMatrix4(_inverseMatrix$1);
  16516. const localThreshold = threshold / ((this.scale.x + this.scale.y + this.scale.z) / 3);
  16517. const localThresholdSq = localThreshold * localThreshold;
  16518. const vStart = new Vector3();
  16519. const vEnd = new Vector3();
  16520. const interSegment = new Vector3();
  16521. const interRay = new Vector3();
  16522. const step = this.isLineSegments ? 2 : 1;
  16523. if (geometry.isBufferGeometry) {
  16524. const index = geometry.index;
  16525. const attributes = geometry.attributes;
  16526. const positionAttribute = attributes.position;
  16527. if (index !== null) {
  16528. const indices = index.array;
  16529. for (let i = 0, l = indices.length - 1; i < l; i += step) {
  16530. const a = indices[i];
  16531. const b = indices[i + 1];
  16532. vStart.fromBufferAttribute(positionAttribute, a);
  16533. vEnd.fromBufferAttribute(positionAttribute, b);
  16534. const distSq = _ray$1.distanceSqToSegment(vStart, vEnd, interRay, interSegment);
  16535. if (distSq > localThresholdSq) continue;
  16536. interRay.applyMatrix4(this.matrixWorld); //Move back to world space for distance calculation
  16537. const distance = raycaster.ray.origin.distanceTo(interRay);
  16538. if (distance < raycaster.near || distance > raycaster.far) continue;
  16539. intersects.push({
  16540. distance: distance,
  16541. // What do we want? intersection point on the ray or on the segment??
  16542. // point: raycaster.ray.at( distance ),
  16543. point: interSegment.clone().applyMatrix4(this.matrixWorld),
  16544. index: i,
  16545. face: null,
  16546. faceIndex: null,
  16547. object: this
  16548. });
  16549. }
  16550. } else {
  16551. for (let i = 0, l = positionAttribute.count - 1; i < l; i += step) {
  16552. vStart.fromBufferAttribute(positionAttribute, i);
  16553. vEnd.fromBufferAttribute(positionAttribute, i + 1);
  16554. const distSq = _ray$1.distanceSqToSegment(vStart, vEnd, interRay, interSegment);
  16555. if (distSq > localThresholdSq) continue;
  16556. interRay.applyMatrix4(this.matrixWorld); //Move back to world space for distance calculation
  16557. const distance = raycaster.ray.origin.distanceTo(interRay);
  16558. if (distance < raycaster.near || distance > raycaster.far) continue;
  16559. intersects.push({
  16560. distance: distance,
  16561. // What do we want? intersection point on the ray or on the segment??
  16562. // point: raycaster.ray.at( distance ),
  16563. point: interSegment.clone().applyMatrix4(this.matrixWorld),
  16564. index: i,
  16565. face: null,
  16566. faceIndex: null,
  16567. object: this
  16568. });
  16569. }
  16570. }
  16571. } else if (geometry.isGeometry) {
  16572. const vertices = geometry.vertices;
  16573. const nbVertices = vertices.length;
  16574. for (let i = 0; i < nbVertices - 1; i += step) {
  16575. const distSq = _ray$1.distanceSqToSegment(vertices[i], vertices[i + 1], interRay, interSegment);
  16576. if (distSq > localThresholdSq) continue;
  16577. interRay.applyMatrix4(this.matrixWorld); //Move back to world space for distance calculation
  16578. const distance = raycaster.ray.origin.distanceTo(interRay);
  16579. if (distance < raycaster.near || distance > raycaster.far) continue;
  16580. intersects.push({
  16581. distance: distance,
  16582. // What do we want? intersection point on the ray or on the segment??
  16583. // point: raycaster.ray.at( distance ),
  16584. point: interSegment.clone().applyMatrix4(this.matrixWorld),
  16585. index: i,
  16586. face: null,
  16587. faceIndex: null,
  16588. object: this
  16589. });
  16590. }
  16591. }
  16592. },
  16593. updateMorphTargets: function () {
  16594. const geometry = this.geometry;
  16595. if (geometry.isBufferGeometry) {
  16596. const morphAttributes = geometry.morphAttributes;
  16597. const keys = Object.keys(morphAttributes);
  16598. if (keys.length > 0) {
  16599. const morphAttribute = morphAttributes[keys[0]];
  16600. if (morphAttribute !== undefined) {
  16601. this.morphTargetInfluences = [];
  16602. this.morphTargetDictionary = {};
  16603. for (let m = 0, ml = morphAttribute.length; m < ml; m++) {
  16604. const name = morphAttribute[m].name || String(m);
  16605. this.morphTargetInfluences.push(0);
  16606. this.morphTargetDictionary[name] = m;
  16607. }
  16608. }
  16609. }
  16610. } else {
  16611. const morphTargets = geometry.morphTargets;
  16612. if (morphTargets !== undefined && morphTargets.length > 0) {
  16613. console.error('THREE.Line.updateMorphTargets() does not support THREE.Geometry. Use THREE.BufferGeometry instead.');
  16614. }
  16615. }
  16616. }
  16617. });
  16618. const _start$1 = new Vector3();
  16619. const _end$1 = new Vector3();
  16620. function LineSegments(geometry, material) {
  16621. Line.call(this, geometry, material);
  16622. this.type = 'LineSegments';
  16623. }
  16624. LineSegments.prototype = Object.assign(Object.create(Line.prototype), {
  16625. constructor: LineSegments,
  16626. isLineSegments: true,
  16627. computeLineDistances: function () {
  16628. const geometry = this.geometry;
  16629. if (geometry.isBufferGeometry) {
  16630. // we assume non-indexed geometry
  16631. if (geometry.index === null) {
  16632. const positionAttribute = geometry.attributes.position;
  16633. const lineDistances = [];
  16634. for (let i = 0, l = positionAttribute.count; i < l; i += 2) {
  16635. _start$1.fromBufferAttribute(positionAttribute, i);
  16636. _end$1.fromBufferAttribute(positionAttribute, i + 1);
  16637. lineDistances[i] = i === 0 ? 0 : lineDistances[i - 1];
  16638. lineDistances[i + 1] = lineDistances[i] + _start$1.distanceTo(_end$1);
  16639. }
  16640. geometry.setAttribute('lineDistance', new Float32BufferAttribute(lineDistances, 1));
  16641. } else {
  16642. console.warn('THREE.LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.');
  16643. }
  16644. } else if (geometry.isGeometry) {
  16645. const vertices = geometry.vertices;
  16646. const lineDistances = geometry.lineDistances;
  16647. for (let i = 0, l = vertices.length; i < l; i += 2) {
  16648. _start$1.copy(vertices[i]);
  16649. _end$1.copy(vertices[i + 1]);
  16650. lineDistances[i] = i === 0 ? 0 : lineDistances[i - 1];
  16651. lineDistances[i + 1] = lineDistances[i] + _start$1.distanceTo(_end$1);
  16652. }
  16653. }
  16654. return this;
  16655. }
  16656. });
  16657. function LineLoop(geometry, material) {
  16658. Line.call(this, geometry, material);
  16659. this.type = 'LineLoop';
  16660. }
  16661. LineLoop.prototype = Object.assign(Object.create(Line.prototype), {
  16662. constructor: LineLoop,
  16663. isLineLoop: true
  16664. });
  16665. /**
  16666. * parameters = {
  16667. * color: <hex>,
  16668. * opacity: <float>,
  16669. * map: new THREE.Texture( <Image> ),
  16670. * alphaMap: new THREE.Texture( <Image> ),
  16671. *
  16672. * size: <float>,
  16673. * sizeAttenuation: <bool>
  16674. *
  16675. * morphTargets: <bool>
  16676. * }
  16677. */
  16678. function PointsMaterial(parameters) {
  16679. Material.call(this);
  16680. this.type = 'PointsMaterial';
  16681. this.color = new Color(0xffffff);
  16682. this.map = null;
  16683. this.alphaMap = null;
  16684. this.size = 1;
  16685. this.sizeAttenuation = true;
  16686. this.morphTargets = false;
  16687. this.setValues(parameters);
  16688. }
  16689. PointsMaterial.prototype = Object.create(Material.prototype);
  16690. PointsMaterial.prototype.constructor = PointsMaterial;
  16691. PointsMaterial.prototype.isPointsMaterial = true;
  16692. PointsMaterial.prototype.copy = function (source) {
  16693. Material.prototype.copy.call(this, source);
  16694. this.color.copy(source.color);
  16695. this.map = source.map;
  16696. this.alphaMap = source.alphaMap;
  16697. this.size = source.size;
  16698. this.sizeAttenuation = source.sizeAttenuation;
  16699. this.morphTargets = source.morphTargets;
  16700. return this;
  16701. };
  16702. const _inverseMatrix$2 = new Matrix4();
  16703. const _ray$2 = new Ray();
  16704. const _sphere$3 = new Sphere();
  16705. const _position$1 = new Vector3();
  16706. function Points(geometry, material) {
  16707. Object3D.call(this);
  16708. this.type = 'Points';
  16709. this.geometry = geometry !== undefined ? geometry : new BufferGeometry();
  16710. this.material = material !== undefined ? material : new PointsMaterial();
  16711. this.updateMorphTargets();
  16712. }
  16713. Points.prototype = Object.assign(Object.create(Object3D.prototype), {
  16714. constructor: Points,
  16715. isPoints: true,
  16716. copy: function (source) {
  16717. Object3D.prototype.copy.call(this, source);
  16718. this.material = source.material;
  16719. this.geometry = source.geometry;
  16720. return this;
  16721. },
  16722. raycast: function (raycaster, intersects) {
  16723. const geometry = this.geometry;
  16724. const matrixWorld = this.matrixWorld;
  16725. const threshold = raycaster.params.Points.threshold; // Checking boundingSphere distance to ray
  16726. if (geometry.boundingSphere === null) geometry.computeBoundingSphere();
  16727. _sphere$3.copy(geometry.boundingSphere);
  16728. _sphere$3.applyMatrix4(matrixWorld);
  16729. _sphere$3.radius += threshold;
  16730. if (raycaster.ray.intersectsSphere(_sphere$3) === false) return; //
  16731. _inverseMatrix$2.copy(matrixWorld).invert();
  16732. _ray$2.copy(raycaster.ray).applyMatrix4(_inverseMatrix$2);
  16733. const localThreshold = threshold / ((this.scale.x + this.scale.y + this.scale.z) / 3);
  16734. const localThresholdSq = localThreshold * localThreshold;
  16735. if (geometry.isBufferGeometry) {
  16736. const index = geometry.index;
  16737. const attributes = geometry.attributes;
  16738. const positionAttribute = attributes.position;
  16739. if (index !== null) {
  16740. const indices = index.array;
  16741. for (let i = 0, il = indices.length; i < il; i++) {
  16742. const a = indices[i];
  16743. _position$1.fromBufferAttribute(positionAttribute, a);
  16744. testPoint(_position$1, a, localThresholdSq, matrixWorld, raycaster, intersects, this);
  16745. }
  16746. } else {
  16747. for (let i = 0, l = positionAttribute.count; i < l; i++) {
  16748. _position$1.fromBufferAttribute(positionAttribute, i);
  16749. testPoint(_position$1, i, localThresholdSq, matrixWorld, raycaster, intersects, this);
  16750. }
  16751. }
  16752. } else {
  16753. const vertices = geometry.vertices;
  16754. for (let i = 0, l = vertices.length; i < l; i++) {
  16755. testPoint(vertices[i], i, localThresholdSq, matrixWorld, raycaster, intersects, this);
  16756. }
  16757. }
  16758. },
  16759. updateMorphTargets: function () {
  16760. const geometry = this.geometry;
  16761. if (geometry.isBufferGeometry) {
  16762. const morphAttributes = geometry.morphAttributes;
  16763. const keys = Object.keys(morphAttributes);
  16764. if (keys.length > 0) {
  16765. const morphAttribute = morphAttributes[keys[0]];
  16766. if (morphAttribute !== undefined) {
  16767. this.morphTargetInfluences = [];
  16768. this.morphTargetDictionary = {};
  16769. for (let m = 0, ml = morphAttribute.length; m < ml; m++) {
  16770. const name = morphAttribute[m].name || String(m);
  16771. this.morphTargetInfluences.push(0);
  16772. this.morphTargetDictionary[name] = m;
  16773. }
  16774. }
  16775. }
  16776. } else {
  16777. const morphTargets = geometry.morphTargets;
  16778. if (morphTargets !== undefined && morphTargets.length > 0) {
  16779. console.error('THREE.Points.updateMorphTargets() does not support THREE.Geometry. Use THREE.BufferGeometry instead.');
  16780. }
  16781. }
  16782. }
  16783. });
  16784. function testPoint(point, index, localThresholdSq, matrixWorld, raycaster, intersects, object) {
  16785. const rayPointDistanceSq = _ray$2.distanceSqToPoint(point);
  16786. if (rayPointDistanceSq < localThresholdSq) {
  16787. const intersectPoint = new Vector3();
  16788. _ray$2.closestPointToPoint(point, intersectPoint);
  16789. intersectPoint.applyMatrix4(matrixWorld);
  16790. const distance = raycaster.ray.origin.distanceTo(intersectPoint);
  16791. if (distance < raycaster.near || distance > raycaster.far) return;
  16792. intersects.push({
  16793. distance: distance,
  16794. distanceToRay: Math.sqrt(rayPointDistanceSq),
  16795. point: intersectPoint,
  16796. index: index,
  16797. face: null,
  16798. object: object
  16799. });
  16800. }
  16801. }
  16802. function VideoTexture(video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy) {
  16803. Texture.call(this, video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy);
  16804. this.format = format !== undefined ? format : RGBFormat;
  16805. this.minFilter = minFilter !== undefined ? minFilter : LinearFilter;
  16806. this.magFilter = magFilter !== undefined ? magFilter : LinearFilter;
  16807. this.generateMipmaps = false;
  16808. const scope = this;
  16809. function updateVideo() {
  16810. scope.needsUpdate = true;
  16811. video.requestVideoFrameCallback(updateVideo);
  16812. }
  16813. if ('requestVideoFrameCallback' in video) {
  16814. video.requestVideoFrameCallback(updateVideo);
  16815. }
  16816. }
  16817. VideoTexture.prototype = Object.assign(Object.create(Texture.prototype), {
  16818. constructor: VideoTexture,
  16819. clone: function () {
  16820. return new this.constructor(this.image).copy(this);
  16821. },
  16822. isVideoTexture: true,
  16823. update: function () {
  16824. const video = this.image;
  16825. const hasVideoFrameCallback = 'requestVideoFrameCallback' in video;
  16826. if (hasVideoFrameCallback === false && video.readyState >= video.HAVE_CURRENT_DATA) {
  16827. this.needsUpdate = true;
  16828. }
  16829. }
  16830. });
  16831. function CompressedTexture(mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding) {
  16832. Texture.call(this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding);
  16833. this.image = {
  16834. width: width,
  16835. height: height
  16836. };
  16837. this.mipmaps = mipmaps; // no flipping for cube textures
  16838. // (also flipping doesn't work for compressed textures )
  16839. this.flipY = false; // can't generate mipmaps for compressed textures
  16840. // mips must be embedded in DDS files
  16841. this.generateMipmaps = false;
  16842. }
  16843. CompressedTexture.prototype = Object.create(Texture.prototype);
  16844. CompressedTexture.prototype.constructor = CompressedTexture;
  16845. CompressedTexture.prototype.isCompressedTexture = true;
  16846. function CanvasTexture(canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy) {
  16847. Texture.call(this, canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy);
  16848. this.needsUpdate = true;
  16849. }
  16850. CanvasTexture.prototype = Object.create(Texture.prototype);
  16851. CanvasTexture.prototype.constructor = CanvasTexture;
  16852. CanvasTexture.prototype.isCanvasTexture = true;
  16853. function DepthTexture(width, height, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, format) {
  16854. format = format !== undefined ? format : DepthFormat;
  16855. if (format !== DepthFormat && format !== DepthStencilFormat) {
  16856. throw new Error('DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat');
  16857. }
  16858. if (type === undefined && format === DepthFormat) type = UnsignedShortType;
  16859. if (type === undefined && format === DepthStencilFormat) type = UnsignedInt248Type;
  16860. Texture.call(this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy);
  16861. this.image = {
  16862. width: width,
  16863. height: height
  16864. };
  16865. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  16866. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  16867. this.flipY = false;
  16868. this.generateMipmaps = false;
  16869. }
  16870. DepthTexture.prototype = Object.create(Texture.prototype);
  16871. DepthTexture.prototype.constructor = DepthTexture;
  16872. DepthTexture.prototype.isDepthTexture = true;
  16873. let _geometryId = 0; // Geometry uses even numbers as Id
  16874. const _m1$3 = new Matrix4();
  16875. const _obj$1 = new Object3D();
  16876. const _offset$1 = new Vector3();
  16877. function Geometry() {
  16878. Object.defineProperty(this, 'id', {
  16879. value: _geometryId += 2
  16880. });
  16881. this.uuid = MathUtils.generateUUID();
  16882. this.name = '';
  16883. this.type = 'Geometry';
  16884. this.vertices = [];
  16885. this.colors = [];
  16886. this.faces = [];
  16887. this.faceVertexUvs = [[]];
  16888. this.morphTargets = [];
  16889. this.morphNormals = [];
  16890. this.skinWeights = [];
  16891. this.skinIndices = [];
  16892. this.lineDistances = [];
  16893. this.boundingBox = null;
  16894. this.boundingSphere = null; // update flags
  16895. this.elementsNeedUpdate = false;
  16896. this.verticesNeedUpdate = false;
  16897. this.uvsNeedUpdate = false;
  16898. this.normalsNeedUpdate = false;
  16899. this.colorsNeedUpdate = false;
  16900. this.lineDistancesNeedUpdate = false;
  16901. this.groupsNeedUpdate = false;
  16902. }
  16903. Geometry.prototype = Object.assign(Object.create(EventDispatcher.prototype), {
  16904. constructor: Geometry,
  16905. isGeometry: true,
  16906. applyMatrix4: function (matrix) {
  16907. const normalMatrix = new Matrix3().getNormalMatrix(matrix);
  16908. for (let i = 0, il = this.vertices.length; i < il; i++) {
  16909. const vertex = this.vertices[i];
  16910. vertex.applyMatrix4(matrix);
  16911. }
  16912. for (let i = 0, il = this.faces.length; i < il; i++) {
  16913. const face = this.faces[i];
  16914. face.normal.applyMatrix3(normalMatrix).normalize();
  16915. for (let j = 0, jl = face.vertexNormals.length; j < jl; j++) {
  16916. face.vertexNormals[j].applyMatrix3(normalMatrix).normalize();
  16917. }
  16918. }
  16919. if (this.boundingBox !== null) {
  16920. this.computeBoundingBox();
  16921. }
  16922. if (this.boundingSphere !== null) {
  16923. this.computeBoundingSphere();
  16924. }
  16925. this.verticesNeedUpdate = true;
  16926. this.normalsNeedUpdate = true;
  16927. return this;
  16928. },
  16929. rotateX: function (angle) {
  16930. // rotate geometry around world x-axis
  16931. _m1$3.makeRotationX(angle);
  16932. this.applyMatrix4(_m1$3);
  16933. return this;
  16934. },
  16935. rotateY: function (angle) {
  16936. // rotate geometry around world y-axis
  16937. _m1$3.makeRotationY(angle);
  16938. this.applyMatrix4(_m1$3);
  16939. return this;
  16940. },
  16941. rotateZ: function (angle) {
  16942. // rotate geometry around world z-axis
  16943. _m1$3.makeRotationZ(angle);
  16944. this.applyMatrix4(_m1$3);
  16945. return this;
  16946. },
  16947. translate: function (x, y, z) {
  16948. // translate geometry
  16949. _m1$3.makeTranslation(x, y, z);
  16950. this.applyMatrix4(_m1$3);
  16951. return this;
  16952. },
  16953. scale: function (x, y, z) {
  16954. // scale geometry
  16955. _m1$3.makeScale(x, y, z);
  16956. this.applyMatrix4(_m1$3);
  16957. return this;
  16958. },
  16959. lookAt: function (vector) {
  16960. _obj$1.lookAt(vector);
  16961. _obj$1.updateMatrix();
  16962. this.applyMatrix4(_obj$1.matrix);
  16963. return this;
  16964. },
  16965. fromBufferGeometry: function (geometry) {
  16966. const scope = this;
  16967. const index = geometry.index !== null ? geometry.index : undefined;
  16968. const attributes = geometry.attributes;
  16969. if (attributes.position === undefined) {
  16970. console.error('THREE.Geometry.fromBufferGeometry(): Position attribute required for conversion.');
  16971. return this;
  16972. }
  16973. const position = attributes.position;
  16974. const normal = attributes.normal;
  16975. const color = attributes.color;
  16976. const uv = attributes.uv;
  16977. const uv2 = attributes.uv2;
  16978. if (uv2 !== undefined) this.faceVertexUvs[1] = [];
  16979. for (let i = 0; i < position.count; i++) {
  16980. scope.vertices.push(new Vector3().fromBufferAttribute(position, i));
  16981. if (color !== undefined) {
  16982. scope.colors.push(new Color().fromBufferAttribute(color, i));
  16983. }
  16984. }
  16985. function addFace(a, b, c, materialIndex) {
  16986. const vertexColors = color === undefined ? [] : [scope.colors[a].clone(), scope.colors[b].clone(), scope.colors[c].clone()];
  16987. const vertexNormals = normal === undefined ? [] : [new Vector3().fromBufferAttribute(normal, a), new Vector3().fromBufferAttribute(normal, b), new Vector3().fromBufferAttribute(normal, c)];
  16988. const face = new Face3(a, b, c, vertexNormals, vertexColors, materialIndex);
  16989. scope.faces.push(face);
  16990. if (uv !== undefined) {
  16991. scope.faceVertexUvs[0].push([new Vector2().fromBufferAttribute(uv, a), new Vector2().fromBufferAttribute(uv, b), new Vector2().fromBufferAttribute(uv, c)]);
  16992. }
  16993. if (uv2 !== undefined) {
  16994. scope.faceVertexUvs[1].push([new Vector2().fromBufferAttribute(uv2, a), new Vector2().fromBufferAttribute(uv2, b), new Vector2().fromBufferAttribute(uv2, c)]);
  16995. }
  16996. }
  16997. const groups = geometry.groups;
  16998. if (groups.length > 0) {
  16999. for (let i = 0; i < groups.length; i++) {
  17000. const group = groups[i];
  17001. const start = group.start;
  17002. const count = group.count;
  17003. for (let j = start, jl = start + count; j < jl; j += 3) {
  17004. if (index !== undefined) {
  17005. addFace(index.getX(j), index.getX(j + 1), index.getX(j + 2), group.materialIndex);
  17006. } else {
  17007. addFace(j, j + 1, j + 2, group.materialIndex);
  17008. }
  17009. }
  17010. }
  17011. } else {
  17012. if (index !== undefined) {
  17013. for (let i = 0; i < index.count; i += 3) {
  17014. addFace(index.getX(i), index.getX(i + 1), index.getX(i + 2));
  17015. }
  17016. } else {
  17017. for (let i = 0; i < position.count; i += 3) {
  17018. addFace(i, i + 1, i + 2);
  17019. }
  17020. }
  17021. }
  17022. this.computeFaceNormals();
  17023. if (geometry.boundingBox !== null) {
  17024. this.boundingBox = geometry.boundingBox.clone();
  17025. }
  17026. if (geometry.boundingSphere !== null) {
  17027. this.boundingSphere = geometry.boundingSphere.clone();
  17028. }
  17029. return this;
  17030. },
  17031. center: function () {
  17032. this.computeBoundingBox();
  17033. this.boundingBox.getCenter(_offset$1).negate();
  17034. this.translate(_offset$1.x, _offset$1.y, _offset$1.z);
  17035. return this;
  17036. },
  17037. normalize: function () {
  17038. this.computeBoundingSphere();
  17039. const center = this.boundingSphere.center;
  17040. const radius = this.boundingSphere.radius;
  17041. const s = radius === 0 ? 1 : 1.0 / radius;
  17042. const matrix = new Matrix4();
  17043. matrix.set(s, 0, 0, -s * center.x, 0, s, 0, -s * center.y, 0, 0, s, -s * center.z, 0, 0, 0, 1);
  17044. this.applyMatrix4(matrix);
  17045. return this;
  17046. },
  17047. computeFaceNormals: function () {
  17048. const cb = new Vector3(),
  17049. ab = new Vector3();
  17050. for (let f = 0, fl = this.faces.length; f < fl; f++) {
  17051. const face = this.faces[f];
  17052. const vA = this.vertices[face.a];
  17053. const vB = this.vertices[face.b];
  17054. const vC = this.vertices[face.c];
  17055. cb.subVectors(vC, vB);
  17056. ab.subVectors(vA, vB);
  17057. cb.cross(ab);
  17058. cb.normalize();
  17059. face.normal.copy(cb);
  17060. }
  17061. },
  17062. computeVertexNormals: function (areaWeighted = true) {
  17063. const vertices = new Array(this.vertices.length);
  17064. for (let v = 0, vl = this.vertices.length; v < vl; v++) {
  17065. vertices[v] = new Vector3();
  17066. }
  17067. if (areaWeighted) {
  17068. // vertex normals weighted by triangle areas
  17069. // http://www.iquilezles.org/www/articles/normals/normals.htm
  17070. const cb = new Vector3(),
  17071. ab = new Vector3();
  17072. for (let f = 0, fl = this.faces.length; f < fl; f++) {
  17073. const face = this.faces[f];
  17074. const vA = this.vertices[face.a];
  17075. const vB = this.vertices[face.b];
  17076. const vC = this.vertices[face.c];
  17077. cb.subVectors(vC, vB);
  17078. ab.subVectors(vA, vB);
  17079. cb.cross(ab);
  17080. vertices[face.a].add(cb);
  17081. vertices[face.b].add(cb);
  17082. vertices[face.c].add(cb);
  17083. }
  17084. } else {
  17085. this.computeFaceNormals();
  17086. for (let f = 0, fl = this.faces.length; f < fl; f++) {
  17087. const face = this.faces[f];
  17088. vertices[face.a].add(face.normal);
  17089. vertices[face.b].add(face.normal);
  17090. vertices[face.c].add(face.normal);
  17091. }
  17092. }
  17093. for (let v = 0, vl = this.vertices.length; v < vl; v++) {
  17094. vertices[v].normalize();
  17095. }
  17096. for (let f = 0, fl = this.faces.length; f < fl; f++) {
  17097. const face = this.faces[f];
  17098. const vertexNormals = face.vertexNormals;
  17099. if (vertexNormals.length === 3) {
  17100. vertexNormals[0].copy(vertices[face.a]);
  17101. vertexNormals[1].copy(vertices[face.b]);
  17102. vertexNormals[2].copy(vertices[face.c]);
  17103. } else {
  17104. vertexNormals[0] = vertices[face.a].clone();
  17105. vertexNormals[1] = vertices[face.b].clone();
  17106. vertexNormals[2] = vertices[face.c].clone();
  17107. }
  17108. }
  17109. if (this.faces.length > 0) {
  17110. this.normalsNeedUpdate = true;
  17111. }
  17112. },
  17113. computeFlatVertexNormals: function () {
  17114. this.computeFaceNormals();
  17115. for (let f = 0, fl = this.faces.length; f < fl; f++) {
  17116. const face = this.faces[f];
  17117. const vertexNormals = face.vertexNormals;
  17118. if (vertexNormals.length === 3) {
  17119. vertexNormals[0].copy(face.normal);
  17120. vertexNormals[1].copy(face.normal);
  17121. vertexNormals[2].copy(face.normal);
  17122. } else {
  17123. vertexNormals[0] = face.normal.clone();
  17124. vertexNormals[1] = face.normal.clone();
  17125. vertexNormals[2] = face.normal.clone();
  17126. }
  17127. }
  17128. if (this.faces.length > 0) {
  17129. this.normalsNeedUpdate = true;
  17130. }
  17131. },
  17132. computeMorphNormals: function () {
  17133. // save original normals
  17134. // - create temp variables on first access
  17135. // otherwise just copy (for faster repeated calls)
  17136. for (let f = 0, fl = this.faces.length; f < fl; f++) {
  17137. const face = this.faces[f];
  17138. if (!face.__originalFaceNormal) {
  17139. face.__originalFaceNormal = face.normal.clone();
  17140. } else {
  17141. face.__originalFaceNormal.copy(face.normal);
  17142. }
  17143. if (!face.__originalVertexNormals) face.__originalVertexNormals = [];
  17144. for (let i = 0, il = face.vertexNormals.length; i < il; i++) {
  17145. if (!face.__originalVertexNormals[i]) {
  17146. face.__originalVertexNormals[i] = face.vertexNormals[i].clone();
  17147. } else {
  17148. face.__originalVertexNormals[i].copy(face.vertexNormals[i]);
  17149. }
  17150. }
  17151. } // use temp geometry to compute face and vertex normals for each morph
  17152. const tmpGeo = new Geometry();
  17153. tmpGeo.faces = this.faces;
  17154. for (let i = 0, il = this.morphTargets.length; i < il; i++) {
  17155. // create on first access
  17156. if (!this.morphNormals[i]) {
  17157. this.morphNormals[i] = {};
  17158. this.morphNormals[i].faceNormals = [];
  17159. this.morphNormals[i].vertexNormals = [];
  17160. const dstNormalsFace = this.morphNormals[i].faceNormals;
  17161. const dstNormalsVertex = this.morphNormals[i].vertexNormals;
  17162. for (let f = 0, fl = this.faces.length; f < fl; f++) {
  17163. const faceNormal = new Vector3();
  17164. const vertexNormals = {
  17165. a: new Vector3(),
  17166. b: new Vector3(),
  17167. c: new Vector3()
  17168. };
  17169. dstNormalsFace.push(faceNormal);
  17170. dstNormalsVertex.push(vertexNormals);
  17171. }
  17172. }
  17173. const morphNormals = this.morphNormals[i]; // set vertices to morph target
  17174. tmpGeo.vertices = this.morphTargets[i].vertices; // compute morph normals
  17175. tmpGeo.computeFaceNormals();
  17176. tmpGeo.computeVertexNormals(); // store morph normals
  17177. for (let f = 0, fl = this.faces.length; f < fl; f++) {
  17178. const face = this.faces[f];
  17179. const faceNormal = morphNormals.faceNormals[f];
  17180. const vertexNormals = morphNormals.vertexNormals[f];
  17181. faceNormal.copy(face.normal);
  17182. vertexNormals.a.copy(face.vertexNormals[0]);
  17183. vertexNormals.b.copy(face.vertexNormals[1]);
  17184. vertexNormals.c.copy(face.vertexNormals[2]);
  17185. }
  17186. } // restore original normals
  17187. for (let f = 0, fl = this.faces.length; f < fl; f++) {
  17188. const face = this.faces[f];
  17189. face.normal = face.__originalFaceNormal;
  17190. face.vertexNormals = face.__originalVertexNormals;
  17191. }
  17192. },
  17193. computeBoundingBox: function () {
  17194. if (this.boundingBox === null) {
  17195. this.boundingBox = new Box3();
  17196. }
  17197. this.boundingBox.setFromPoints(this.vertices);
  17198. },
  17199. computeBoundingSphere: function () {
  17200. if (this.boundingSphere === null) {
  17201. this.boundingSphere = new Sphere();
  17202. }
  17203. this.boundingSphere.setFromPoints(this.vertices);
  17204. },
  17205. merge: function (geometry, matrix, materialIndexOffset = 0) {
  17206. if (!(geometry && geometry.isGeometry)) {
  17207. console.error('THREE.Geometry.merge(): geometry not an instance of THREE.Geometry.', geometry);
  17208. return;
  17209. }
  17210. let normalMatrix;
  17211. const vertexOffset = this.vertices.length,
  17212. vertices1 = this.vertices,
  17213. vertices2 = geometry.vertices,
  17214. faces1 = this.faces,
  17215. faces2 = geometry.faces,
  17216. colors1 = this.colors,
  17217. colors2 = geometry.colors;
  17218. if (matrix !== undefined) {
  17219. normalMatrix = new Matrix3().getNormalMatrix(matrix);
  17220. } // vertices
  17221. for (let i = 0, il = vertices2.length; i < il; i++) {
  17222. const vertex = vertices2[i];
  17223. const vertexCopy = vertex.clone();
  17224. if (matrix !== undefined) vertexCopy.applyMatrix4(matrix);
  17225. vertices1.push(vertexCopy);
  17226. } // colors
  17227. for (let i = 0, il = colors2.length; i < il; i++) {
  17228. colors1.push(colors2[i].clone());
  17229. } // faces
  17230. for (let i = 0, il = faces2.length; i < il; i++) {
  17231. const face = faces2[i];
  17232. let normal, color;
  17233. const faceVertexNormals = face.vertexNormals,
  17234. faceVertexColors = face.vertexColors;
  17235. const faceCopy = new Face3(face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset);
  17236. faceCopy.normal.copy(face.normal);
  17237. if (normalMatrix !== undefined) {
  17238. faceCopy.normal.applyMatrix3(normalMatrix).normalize();
  17239. }
  17240. for (let j = 0, jl = faceVertexNormals.length; j < jl; j++) {
  17241. normal = faceVertexNormals[j].clone();
  17242. if (normalMatrix !== undefined) {
  17243. normal.applyMatrix3(normalMatrix).normalize();
  17244. }
  17245. faceCopy.vertexNormals.push(normal);
  17246. }
  17247. faceCopy.color.copy(face.color);
  17248. for (let j = 0, jl = faceVertexColors.length; j < jl; j++) {
  17249. color = faceVertexColors[j];
  17250. faceCopy.vertexColors.push(color.clone());
  17251. }
  17252. faceCopy.materialIndex = face.materialIndex + materialIndexOffset;
  17253. faces1.push(faceCopy);
  17254. } // uvs
  17255. for (let i = 0, il = geometry.faceVertexUvs.length; i < il; i++) {
  17256. const faceVertexUvs2 = geometry.faceVertexUvs[i];
  17257. if (this.faceVertexUvs[i] === undefined) this.faceVertexUvs[i] = [];
  17258. for (let j = 0, jl = faceVertexUvs2.length; j < jl; j++) {
  17259. const uvs2 = faceVertexUvs2[j],
  17260. uvsCopy = [];
  17261. for (let k = 0, kl = uvs2.length; k < kl; k++) {
  17262. uvsCopy.push(uvs2[k].clone());
  17263. }
  17264. this.faceVertexUvs[i].push(uvsCopy);
  17265. }
  17266. }
  17267. },
  17268. mergeMesh: function (mesh) {
  17269. if (!(mesh && mesh.isMesh)) {
  17270. console.error('THREE.Geometry.mergeMesh(): mesh not an instance of THREE.Mesh.', mesh);
  17271. return;
  17272. }
  17273. if (mesh.matrixAutoUpdate) mesh.updateMatrix();
  17274. this.merge(mesh.geometry, mesh.matrix);
  17275. },
  17276. /*
  17277. * Checks for duplicate vertices with hashmap.
  17278. * Duplicated vertices are removed
  17279. * and faces' vertices are updated.
  17280. */
  17281. mergeVertices: function (precisionPoints = 4) {
  17282. const verticesMap = {}; // Hashmap for looking up vertices by position coordinates (and making sure they are unique)
  17283. const unique = [],
  17284. changes = [];
  17285. const precision = Math.pow(10, precisionPoints);
  17286. for (let i = 0, il = this.vertices.length; i < il; i++) {
  17287. const v = this.vertices[i];
  17288. const key = Math.round(v.x * precision) + '_' + Math.round(v.y * precision) + '_' + Math.round(v.z * precision);
  17289. if (verticesMap[key] === undefined) {
  17290. verticesMap[key] = i;
  17291. unique.push(this.vertices[i]);
  17292. changes[i] = unique.length - 1;
  17293. } else {
  17294. //console.log('Duplicate vertex found. ', i, ' could be using ', verticesMap[key]);
  17295. changes[i] = changes[verticesMap[key]];
  17296. }
  17297. } // if faces are completely degenerate after merging vertices, we
  17298. // have to remove them from the geometry.
  17299. const faceIndicesToRemove = [];
  17300. for (let i = 0, il = this.faces.length; i < il; i++) {
  17301. const face = this.faces[i];
  17302. face.a = changes[face.a];
  17303. face.b = changes[face.b];
  17304. face.c = changes[face.c];
  17305. const indices = [face.a, face.b, face.c]; // if any duplicate vertices are found in a Face3
  17306. // we have to remove the face as nothing can be saved
  17307. for (let n = 0; n < 3; n++) {
  17308. if (indices[n] === indices[(n + 1) % 3]) {
  17309. faceIndicesToRemove.push(i);
  17310. break;
  17311. }
  17312. }
  17313. }
  17314. for (let i = faceIndicesToRemove.length - 1; i >= 0; i--) {
  17315. const idx = faceIndicesToRemove[i];
  17316. this.faces.splice(idx, 1);
  17317. for (let j = 0, jl = this.faceVertexUvs.length; j < jl; j++) {
  17318. this.faceVertexUvs[j].splice(idx, 1);
  17319. }
  17320. } // Use unique set of vertices
  17321. const diff = this.vertices.length - unique.length;
  17322. this.vertices = unique;
  17323. return diff;
  17324. },
  17325. setFromPoints: function (points) {
  17326. this.vertices = [];
  17327. for (let i = 0, l = points.length; i < l; i++) {
  17328. const point = points[i];
  17329. this.vertices.push(new Vector3(point.x, point.y, point.z || 0));
  17330. }
  17331. return this;
  17332. },
  17333. sortFacesByMaterialIndex: function () {
  17334. const faces = this.faces;
  17335. const length = faces.length; // tag faces
  17336. for (let i = 0; i < length; i++) {
  17337. faces[i]._id = i;
  17338. } // sort faces
  17339. function materialIndexSort(a, b) {
  17340. return a.materialIndex - b.materialIndex;
  17341. }
  17342. faces.sort(materialIndexSort); // sort uvs
  17343. const uvs1 = this.faceVertexUvs[0];
  17344. const uvs2 = this.faceVertexUvs[1];
  17345. let newUvs1, newUvs2;
  17346. if (uvs1 && uvs1.length === length) newUvs1 = [];
  17347. if (uvs2 && uvs2.length === length) newUvs2 = [];
  17348. for (let i = 0; i < length; i++) {
  17349. const id = faces[i]._id;
  17350. if (newUvs1) newUvs1.push(uvs1[id]);
  17351. if (newUvs2) newUvs2.push(uvs2[id]);
  17352. }
  17353. if (newUvs1) this.faceVertexUvs[0] = newUvs1;
  17354. if (newUvs2) this.faceVertexUvs[1] = newUvs2;
  17355. },
  17356. toJSON: function () {
  17357. const data = {
  17358. metadata: {
  17359. version: 4.5,
  17360. type: 'Geometry',
  17361. generator: 'Geometry.toJSON'
  17362. }
  17363. }; // standard Geometry serialization
  17364. data.uuid = this.uuid;
  17365. data.type = this.type;
  17366. if (this.name !== '') data.name = this.name;
  17367. if (this.parameters !== undefined) {
  17368. const parameters = this.parameters;
  17369. for (const key in parameters) {
  17370. if (parameters[key] !== undefined) data[key] = parameters[key];
  17371. }
  17372. return data;
  17373. }
  17374. const vertices = [];
  17375. for (let i = 0; i < this.vertices.length; i++) {
  17376. const vertex = this.vertices[i];
  17377. vertices.push(vertex.x, vertex.y, vertex.z);
  17378. }
  17379. const faces = [];
  17380. const normals = [];
  17381. const normalsHash = {};
  17382. const colors = [];
  17383. const colorsHash = {};
  17384. const uvs = [];
  17385. const uvsHash = {};
  17386. for (let i = 0; i < this.faces.length; i++) {
  17387. const face = this.faces[i];
  17388. const hasMaterial = true;
  17389. const hasFaceUv = false; // deprecated
  17390. const hasFaceVertexUv = this.faceVertexUvs[0][i] !== undefined;
  17391. const hasFaceNormal = face.normal.length() > 0;
  17392. const hasFaceVertexNormal = face.vertexNormals.length > 0;
  17393. const hasFaceColor = face.color.r !== 1 || face.color.g !== 1 || face.color.b !== 1;
  17394. const hasFaceVertexColor = face.vertexColors.length > 0;
  17395. let faceType = 0;
  17396. faceType = setBit(faceType, 0, 0); // isQuad
  17397. faceType = setBit(faceType, 1, hasMaterial);
  17398. faceType = setBit(faceType, 2, hasFaceUv);
  17399. faceType = setBit(faceType, 3, hasFaceVertexUv);
  17400. faceType = setBit(faceType, 4, hasFaceNormal);
  17401. faceType = setBit(faceType, 5, hasFaceVertexNormal);
  17402. faceType = setBit(faceType, 6, hasFaceColor);
  17403. faceType = setBit(faceType, 7, hasFaceVertexColor);
  17404. faces.push(faceType);
  17405. faces.push(face.a, face.b, face.c);
  17406. faces.push(face.materialIndex);
  17407. if (hasFaceVertexUv) {
  17408. const faceVertexUvs = this.faceVertexUvs[0][i];
  17409. faces.push(getUvIndex(faceVertexUvs[0]), getUvIndex(faceVertexUvs[1]), getUvIndex(faceVertexUvs[2]));
  17410. }
  17411. if (hasFaceNormal) {
  17412. faces.push(getNormalIndex(face.normal));
  17413. }
  17414. if (hasFaceVertexNormal) {
  17415. const vertexNormals = face.vertexNormals;
  17416. faces.push(getNormalIndex(vertexNormals[0]), getNormalIndex(vertexNormals[1]), getNormalIndex(vertexNormals[2]));
  17417. }
  17418. if (hasFaceColor) {
  17419. faces.push(getColorIndex(face.color));
  17420. }
  17421. if (hasFaceVertexColor) {
  17422. const vertexColors = face.vertexColors;
  17423. faces.push(getColorIndex(vertexColors[0]), getColorIndex(vertexColors[1]), getColorIndex(vertexColors[2]));
  17424. }
  17425. }
  17426. function setBit(value, position, enabled) {
  17427. return enabled ? value | 1 << position : value & ~(1 << position);
  17428. }
  17429. function getNormalIndex(normal) {
  17430. const hash = normal.x.toString() + normal.y.toString() + normal.z.toString();
  17431. if (normalsHash[hash] !== undefined) {
  17432. return normalsHash[hash];
  17433. }
  17434. normalsHash[hash] = normals.length / 3;
  17435. normals.push(normal.x, normal.y, normal.z);
  17436. return normalsHash[hash];
  17437. }
  17438. function getColorIndex(color) {
  17439. const hash = color.r.toString() + color.g.toString() + color.b.toString();
  17440. if (colorsHash[hash] !== undefined) {
  17441. return colorsHash[hash];
  17442. }
  17443. colorsHash[hash] = colors.length;
  17444. colors.push(color.getHex());
  17445. return colorsHash[hash];
  17446. }
  17447. function getUvIndex(uv) {
  17448. const hash = uv.x.toString() + uv.y.toString();
  17449. if (uvsHash[hash] !== undefined) {
  17450. return uvsHash[hash];
  17451. }
  17452. uvsHash[hash] = uvs.length / 2;
  17453. uvs.push(uv.x, uv.y);
  17454. return uvsHash[hash];
  17455. }
  17456. data.data = {};
  17457. data.data.vertices = vertices;
  17458. data.data.normals = normals;
  17459. if (colors.length > 0) data.data.colors = colors;
  17460. if (uvs.length > 0) data.data.uvs = [uvs]; // temporal backward compatibility
  17461. data.data.faces = faces;
  17462. return data;
  17463. },
  17464. clone: function () {
  17465. /*
  17466. // Handle primitives
  17467. const parameters = this.parameters;
  17468. if ( parameters !== undefined ) {
  17469. const values = [];
  17470. for ( const key in parameters ) {
  17471. values.push( parameters[ key ] );
  17472. }
  17473. const geometry = Object.create( this.constructor.prototype );
  17474. this.constructor.apply( geometry, values );
  17475. return geometry;
  17476. }
  17477. return new this.constructor().copy( this );
  17478. */
  17479. return new Geometry().copy(this);
  17480. },
  17481. copy: function (source) {
  17482. // reset
  17483. this.vertices = [];
  17484. this.colors = [];
  17485. this.faces = [];
  17486. this.faceVertexUvs = [[]];
  17487. this.morphTargets = [];
  17488. this.morphNormals = [];
  17489. this.skinWeights = [];
  17490. this.skinIndices = [];
  17491. this.lineDistances = [];
  17492. this.boundingBox = null;
  17493. this.boundingSphere = null; // name
  17494. this.name = source.name; // vertices
  17495. const vertices = source.vertices;
  17496. for (let i = 0, il = vertices.length; i < il; i++) {
  17497. this.vertices.push(vertices[i].clone());
  17498. } // colors
  17499. const colors = source.colors;
  17500. for (let i = 0, il = colors.length; i < il; i++) {
  17501. this.colors.push(colors[i].clone());
  17502. } // faces
  17503. const faces = source.faces;
  17504. for (let i = 0, il = faces.length; i < il; i++) {
  17505. this.faces.push(faces[i].clone());
  17506. } // face vertex uvs
  17507. for (let i = 0, il = source.faceVertexUvs.length; i < il; i++) {
  17508. const faceVertexUvs = source.faceVertexUvs[i];
  17509. if (this.faceVertexUvs[i] === undefined) {
  17510. this.faceVertexUvs[i] = [];
  17511. }
  17512. for (let j = 0, jl = faceVertexUvs.length; j < jl; j++) {
  17513. const uvs = faceVertexUvs[j],
  17514. uvsCopy = [];
  17515. for (let k = 0, kl = uvs.length; k < kl; k++) {
  17516. const uv = uvs[k];
  17517. uvsCopy.push(uv.clone());
  17518. }
  17519. this.faceVertexUvs[i].push(uvsCopy);
  17520. }
  17521. } // morph targets
  17522. const morphTargets = source.morphTargets;
  17523. for (let i = 0, il = morphTargets.length; i < il; i++) {
  17524. const morphTarget = {};
  17525. morphTarget.name = morphTargets[i].name; // vertices
  17526. if (morphTargets[i].vertices !== undefined) {
  17527. morphTarget.vertices = [];
  17528. for (let j = 0, jl = morphTargets[i].vertices.length; j < jl; j++) {
  17529. morphTarget.vertices.push(morphTargets[i].vertices[j].clone());
  17530. }
  17531. } // normals
  17532. if (morphTargets[i].normals !== undefined) {
  17533. morphTarget.normals = [];
  17534. for (let j = 0, jl = morphTargets[i].normals.length; j < jl; j++) {
  17535. morphTarget.normals.push(morphTargets[i].normals[j].clone());
  17536. }
  17537. }
  17538. this.morphTargets.push(morphTarget);
  17539. } // morph normals
  17540. const morphNormals = source.morphNormals;
  17541. for (let i = 0, il = morphNormals.length; i < il; i++) {
  17542. const morphNormal = {}; // vertex normals
  17543. if (morphNormals[i].vertexNormals !== undefined) {
  17544. morphNormal.vertexNormals = [];
  17545. for (let j = 0, jl = morphNormals[i].vertexNormals.length; j < jl; j++) {
  17546. const srcVertexNormal = morphNormals[i].vertexNormals[j];
  17547. const destVertexNormal = {};
  17548. destVertexNormal.a = srcVertexNormal.a.clone();
  17549. destVertexNormal.b = srcVertexNormal.b.clone();
  17550. destVertexNormal.c = srcVertexNormal.c.clone();
  17551. morphNormal.vertexNormals.push(destVertexNormal);
  17552. }
  17553. } // face normals
  17554. if (morphNormals[i].faceNormals !== undefined) {
  17555. morphNormal.faceNormals = [];
  17556. for (let j = 0, jl = morphNormals[i].faceNormals.length; j < jl; j++) {
  17557. morphNormal.faceNormals.push(morphNormals[i].faceNormals[j].clone());
  17558. }
  17559. }
  17560. this.morphNormals.push(morphNormal);
  17561. } // skin weights
  17562. const skinWeights = source.skinWeights;
  17563. for (let i = 0, il = skinWeights.length; i < il; i++) {
  17564. this.skinWeights.push(skinWeights[i].clone());
  17565. } // skin indices
  17566. const skinIndices = source.skinIndices;
  17567. for (let i = 0, il = skinIndices.length; i < il; i++) {
  17568. this.skinIndices.push(skinIndices[i].clone());
  17569. } // line distances
  17570. const lineDistances = source.lineDistances;
  17571. for (let i = 0, il = lineDistances.length; i < il; i++) {
  17572. this.lineDistances.push(lineDistances[i]);
  17573. } // bounding box
  17574. const boundingBox = source.boundingBox;
  17575. if (boundingBox !== null) {
  17576. this.boundingBox = boundingBox.clone();
  17577. } // bounding sphere
  17578. const boundingSphere = source.boundingSphere;
  17579. if (boundingSphere !== null) {
  17580. this.boundingSphere = boundingSphere.clone();
  17581. } // update flags
  17582. this.elementsNeedUpdate = source.elementsNeedUpdate;
  17583. this.verticesNeedUpdate = source.verticesNeedUpdate;
  17584. this.uvsNeedUpdate = source.uvsNeedUpdate;
  17585. this.normalsNeedUpdate = source.normalsNeedUpdate;
  17586. this.colorsNeedUpdate = source.colorsNeedUpdate;
  17587. this.lineDistancesNeedUpdate = source.lineDistancesNeedUpdate;
  17588. this.groupsNeedUpdate = source.groupsNeedUpdate;
  17589. return this;
  17590. },
  17591. dispose: function () {
  17592. this.dispatchEvent({
  17593. type: 'dispose'
  17594. });
  17595. }
  17596. });
  17597. class BoxGeometry extends Geometry {
  17598. constructor(width, height, depth, widthSegments, heightSegments, depthSegments) {
  17599. super();
  17600. this.type = 'BoxGeometry';
  17601. this.parameters = {
  17602. width: width,
  17603. height: height,
  17604. depth: depth,
  17605. widthSegments: widthSegments,
  17606. heightSegments: heightSegments,
  17607. depthSegments: depthSegments
  17608. };
  17609. this.fromBufferGeometry(new BoxBufferGeometry(width, height, depth, widthSegments, heightSegments, depthSegments));
  17610. this.mergeVertices();
  17611. }
  17612. }
  17613. exports.CubeGeometry = exports.BoxGeometry = BoxGeometry;
  17614. class CircleBufferGeometry extends BufferGeometry {
  17615. constructor(radius = 1, segments = 8, thetaStart = 0, thetaLength = Math.PI * 2) {
  17616. super();
  17617. this.type = 'CircleBufferGeometry';
  17618. this.parameters = {
  17619. radius: radius,
  17620. segments: segments,
  17621. thetaStart: thetaStart,
  17622. thetaLength: thetaLength
  17623. };
  17624. segments = Math.max(3, segments); // buffers
  17625. const indices = [];
  17626. const vertices = [];
  17627. const normals = [];
  17628. const uvs = []; // helper variables
  17629. const vertex = new Vector3();
  17630. const uv = new Vector2(); // center point
  17631. vertices.push(0, 0, 0);
  17632. normals.push(0, 0, 1);
  17633. uvs.push(0.5, 0.5);
  17634. for (let s = 0, i = 3; s <= segments; s++, i += 3) {
  17635. const segment = thetaStart + s / segments * thetaLength; // vertex
  17636. vertex.x = radius * Math.cos(segment);
  17637. vertex.y = radius * Math.sin(segment);
  17638. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  17639. normals.push(0, 0, 1); // uvs
  17640. uv.x = (vertices[i] / radius + 1) / 2;
  17641. uv.y = (vertices[i + 1] / radius + 1) / 2;
  17642. uvs.push(uv.x, uv.y);
  17643. } // indices
  17644. for (let i = 1; i <= segments; i++) {
  17645. indices.push(i, i + 1, 0);
  17646. } // build geometry
  17647. this.setIndex(indices);
  17648. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  17649. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  17650. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  17651. }
  17652. }
  17653. exports.CircleBufferGeometry = CircleBufferGeometry;
  17654. class CircleGeometry extends Geometry {
  17655. constructor(radius, segments, thetaStart, thetaLength) {
  17656. super();
  17657. this.type = 'CircleGeometry';
  17658. this.parameters = {
  17659. radius: radius,
  17660. segments: segments,
  17661. thetaStart: thetaStart,
  17662. thetaLength: thetaLength
  17663. };
  17664. this.fromBufferGeometry(new CircleBufferGeometry(radius, segments, thetaStart, thetaLength));
  17665. this.mergeVertices();
  17666. }
  17667. }
  17668. exports.CircleGeometry = CircleGeometry;
  17669. class CylinderBufferGeometry extends BufferGeometry {
  17670. constructor(radiusTop = 1, radiusBottom = 1, height = 1, radialSegments = 8, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2) {
  17671. super();
  17672. this.type = 'CylinderBufferGeometry';
  17673. this.parameters = {
  17674. radiusTop: radiusTop,
  17675. radiusBottom: radiusBottom,
  17676. height: height,
  17677. radialSegments: radialSegments,
  17678. heightSegments: heightSegments,
  17679. openEnded: openEnded,
  17680. thetaStart: thetaStart,
  17681. thetaLength: thetaLength
  17682. };
  17683. const scope = this;
  17684. radialSegments = Math.floor(radialSegments);
  17685. heightSegments = Math.floor(heightSegments); // buffers
  17686. const indices = [];
  17687. const vertices = [];
  17688. const normals = [];
  17689. const uvs = []; // helper variables
  17690. let index = 0;
  17691. const indexArray = [];
  17692. const halfHeight = height / 2;
  17693. let groupStart = 0; // generate geometry
  17694. generateTorso();
  17695. if (openEnded === false) {
  17696. if (radiusTop > 0) generateCap(true);
  17697. if (radiusBottom > 0) generateCap(false);
  17698. } // build geometry
  17699. this.setIndex(indices);
  17700. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  17701. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  17702. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  17703. function generateTorso() {
  17704. const normal = new Vector3();
  17705. const vertex = new Vector3();
  17706. let groupCount = 0; // this will be used to calculate the normal
  17707. const slope = (radiusBottom - radiusTop) / height; // generate vertices, normals and uvs
  17708. for (let y = 0; y <= heightSegments; y++) {
  17709. const indexRow = [];
  17710. const v = y / heightSegments; // calculate the radius of the current row
  17711. const radius = v * (radiusBottom - radiusTop) + radiusTop;
  17712. for (let x = 0; x <= radialSegments; x++) {
  17713. const u = x / radialSegments;
  17714. const theta = u * thetaLength + thetaStart;
  17715. const sinTheta = Math.sin(theta);
  17716. const cosTheta = Math.cos(theta); // vertex
  17717. vertex.x = radius * sinTheta;
  17718. vertex.y = -v * height + halfHeight;
  17719. vertex.z = radius * cosTheta;
  17720. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  17721. normal.set(sinTheta, slope, cosTheta).normalize();
  17722. normals.push(normal.x, normal.y, normal.z); // uv
  17723. uvs.push(u, 1 - v); // save index of vertex in respective row
  17724. indexRow.push(index++);
  17725. } // now save vertices of the row in our index array
  17726. indexArray.push(indexRow);
  17727. } // generate indices
  17728. for (let x = 0; x < radialSegments; x++) {
  17729. for (let y = 0; y < heightSegments; y++) {
  17730. // we use the index array to access the correct indices
  17731. const a = indexArray[y][x];
  17732. const b = indexArray[y + 1][x];
  17733. const c = indexArray[y + 1][x + 1];
  17734. const d = indexArray[y][x + 1]; // faces
  17735. indices.push(a, b, d);
  17736. indices.push(b, c, d); // update group counter
  17737. groupCount += 6;
  17738. }
  17739. } // add a group to the geometry. this will ensure multi material support
  17740. scope.addGroup(groupStart, groupCount, 0); // calculate new start value for groups
  17741. groupStart += groupCount;
  17742. }
  17743. function generateCap(top) {
  17744. // save the index of the first center vertex
  17745. const centerIndexStart = index;
  17746. const uv = new Vector2();
  17747. const vertex = new Vector3();
  17748. let groupCount = 0;
  17749. const radius = top === true ? radiusTop : radiusBottom;
  17750. const sign = top === true ? 1 : -1; // first we generate the center vertex data of the cap.
  17751. // because the geometry needs one set of uvs per face,
  17752. // we must generate a center vertex per face/segment
  17753. for (let x = 1; x <= radialSegments; x++) {
  17754. // vertex
  17755. vertices.push(0, halfHeight * sign, 0); // normal
  17756. normals.push(0, sign, 0); // uv
  17757. uvs.push(0.5, 0.5); // increase index
  17758. index++;
  17759. } // save the index of the last center vertex
  17760. const centerIndexEnd = index; // now we generate the surrounding vertices, normals and uvs
  17761. for (let x = 0; x <= radialSegments; x++) {
  17762. const u = x / radialSegments;
  17763. const theta = u * thetaLength + thetaStart;
  17764. const cosTheta = Math.cos(theta);
  17765. const sinTheta = Math.sin(theta); // vertex
  17766. vertex.x = radius * sinTheta;
  17767. vertex.y = halfHeight * sign;
  17768. vertex.z = radius * cosTheta;
  17769. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  17770. normals.push(0, sign, 0); // uv
  17771. uv.x = cosTheta * 0.5 + 0.5;
  17772. uv.y = sinTheta * 0.5 * sign + 0.5;
  17773. uvs.push(uv.x, uv.y); // increase index
  17774. index++;
  17775. } // generate indices
  17776. for (let x = 0; x < radialSegments; x++) {
  17777. const c = centerIndexStart + x;
  17778. const i = centerIndexEnd + x;
  17779. if (top === true) {
  17780. // face top
  17781. indices.push(i, i + 1, c);
  17782. } else {
  17783. // face bottom
  17784. indices.push(i + 1, i, c);
  17785. }
  17786. groupCount += 3;
  17787. } // add a group to the geometry. this will ensure multi material support
  17788. scope.addGroup(groupStart, groupCount, top === true ? 1 : 2); // calculate new start value for groups
  17789. groupStart += groupCount;
  17790. }
  17791. }
  17792. }
  17793. exports.CylinderBufferGeometry = CylinderBufferGeometry;
  17794. class CylinderGeometry extends Geometry {
  17795. constructor(radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength) {
  17796. super();
  17797. this.type = 'CylinderGeometry';
  17798. this.parameters = {
  17799. radiusTop: radiusTop,
  17800. radiusBottom: radiusBottom,
  17801. height: height,
  17802. radialSegments: radialSegments,
  17803. heightSegments: heightSegments,
  17804. openEnded: openEnded,
  17805. thetaStart: thetaStart,
  17806. thetaLength: thetaLength
  17807. };
  17808. this.fromBufferGeometry(new CylinderBufferGeometry(radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength));
  17809. this.mergeVertices();
  17810. }
  17811. }
  17812. exports.CylinderGeometry = CylinderGeometry;
  17813. class ConeGeometry extends CylinderGeometry {
  17814. constructor(radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength) {
  17815. super(0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength);
  17816. this.type = 'ConeGeometry';
  17817. this.parameters = {
  17818. radius: radius,
  17819. height: height,
  17820. radialSegments: radialSegments,
  17821. heightSegments: heightSegments,
  17822. openEnded: openEnded,
  17823. thetaStart: thetaStart,
  17824. thetaLength: thetaLength
  17825. };
  17826. }
  17827. }
  17828. exports.ConeGeometry = ConeGeometry;
  17829. class ConeBufferGeometry extends CylinderBufferGeometry {
  17830. constructor(radius = 1, height = 1, radialSegments = 8, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2) {
  17831. super(0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength);
  17832. this.type = 'ConeBufferGeometry';
  17833. this.parameters = {
  17834. radius: radius,
  17835. height: height,
  17836. radialSegments: radialSegments,
  17837. heightSegments: heightSegments,
  17838. openEnded: openEnded,
  17839. thetaStart: thetaStart,
  17840. thetaLength: thetaLength
  17841. };
  17842. }
  17843. }
  17844. exports.ConeBufferGeometry = ConeBufferGeometry;
  17845. class PolyhedronBufferGeometry extends BufferGeometry {
  17846. constructor(vertices, indices, radius = 1, detail = 0) {
  17847. super();
  17848. this.type = 'PolyhedronBufferGeometry';
  17849. this.parameters = {
  17850. vertices: vertices,
  17851. indices: indices,
  17852. radius: radius,
  17853. detail: detail
  17854. }; // default buffer data
  17855. const vertexBuffer = [];
  17856. const uvBuffer = []; // the subdivision creates the vertex buffer data
  17857. subdivide(detail); // all vertices should lie on a conceptual sphere with a given radius
  17858. applyRadius(radius); // finally, create the uv data
  17859. generateUVs(); // build non-indexed geometry
  17860. this.setAttribute('position', new Float32BufferAttribute(vertexBuffer, 3));
  17861. this.setAttribute('normal', new Float32BufferAttribute(vertexBuffer.slice(), 3));
  17862. this.setAttribute('uv', new Float32BufferAttribute(uvBuffer, 2));
  17863. if (detail === 0) {
  17864. this.computeVertexNormals(); // flat normals
  17865. } else {
  17866. this.normalizeNormals(); // smooth normals
  17867. } // helper functions
  17868. function subdivide(detail) {
  17869. const a = new Vector3();
  17870. const b = new Vector3();
  17871. const c = new Vector3(); // iterate over all faces and apply a subdivison with the given detail value
  17872. for (let i = 0; i < indices.length; i += 3) {
  17873. // get the vertices of the face
  17874. getVertexByIndex(indices[i + 0], a);
  17875. getVertexByIndex(indices[i + 1], b);
  17876. getVertexByIndex(indices[i + 2], c); // perform subdivision
  17877. subdivideFace(a, b, c, detail);
  17878. }
  17879. }
  17880. function subdivideFace(a, b, c, detail) {
  17881. const cols = detail + 1; // we use this multidimensional array as a data structure for creating the subdivision
  17882. const v = []; // construct all of the vertices for this subdivision
  17883. for (let i = 0; i <= cols; i++) {
  17884. v[i] = [];
  17885. const aj = a.clone().lerp(c, i / cols);
  17886. const bj = b.clone().lerp(c, i / cols);
  17887. const rows = cols - i;
  17888. for (let j = 0; j <= rows; j++) {
  17889. if (j === 0 && i === cols) {
  17890. v[i][j] = aj;
  17891. } else {
  17892. v[i][j] = aj.clone().lerp(bj, j / rows);
  17893. }
  17894. }
  17895. } // construct all of the faces
  17896. for (let i = 0; i < cols; i++) {
  17897. for (let j = 0; j < 2 * (cols - i) - 1; j++) {
  17898. const k = Math.floor(j / 2);
  17899. if (j % 2 === 0) {
  17900. pushVertex(v[i][k + 1]);
  17901. pushVertex(v[i + 1][k]);
  17902. pushVertex(v[i][k]);
  17903. } else {
  17904. pushVertex(v[i][k + 1]);
  17905. pushVertex(v[i + 1][k + 1]);
  17906. pushVertex(v[i + 1][k]);
  17907. }
  17908. }
  17909. }
  17910. }
  17911. function applyRadius(radius) {
  17912. const vertex = new Vector3(); // iterate over the entire buffer and apply the radius to each vertex
  17913. for (let i = 0; i < vertexBuffer.length; i += 3) {
  17914. vertex.x = vertexBuffer[i + 0];
  17915. vertex.y = vertexBuffer[i + 1];
  17916. vertex.z = vertexBuffer[i + 2];
  17917. vertex.normalize().multiplyScalar(radius);
  17918. vertexBuffer[i + 0] = vertex.x;
  17919. vertexBuffer[i + 1] = vertex.y;
  17920. vertexBuffer[i + 2] = vertex.z;
  17921. }
  17922. }
  17923. function generateUVs() {
  17924. const vertex = new Vector3();
  17925. for (let i = 0; i < vertexBuffer.length; i += 3) {
  17926. vertex.x = vertexBuffer[i + 0];
  17927. vertex.y = vertexBuffer[i + 1];
  17928. vertex.z = vertexBuffer[i + 2];
  17929. const u = azimuth(vertex) / 2 / Math.PI + 0.5;
  17930. const v = inclination(vertex) / Math.PI + 0.5;
  17931. uvBuffer.push(u, 1 - v);
  17932. }
  17933. correctUVs();
  17934. correctSeam();
  17935. }
  17936. function correctSeam() {
  17937. // handle case when face straddles the seam, see #3269
  17938. for (let i = 0; i < uvBuffer.length; i += 6) {
  17939. // uv data of a single face
  17940. const x0 = uvBuffer[i + 0];
  17941. const x1 = uvBuffer[i + 2];
  17942. const x2 = uvBuffer[i + 4];
  17943. const max = Math.max(x0, x1, x2);
  17944. const min = Math.min(x0, x1, x2); // 0.9 is somewhat arbitrary
  17945. if (max > 0.9 && min < 0.1) {
  17946. if (x0 < 0.2) uvBuffer[i + 0] += 1;
  17947. if (x1 < 0.2) uvBuffer[i + 2] += 1;
  17948. if (x2 < 0.2) uvBuffer[i + 4] += 1;
  17949. }
  17950. }
  17951. }
  17952. function pushVertex(vertex) {
  17953. vertexBuffer.push(vertex.x, vertex.y, vertex.z);
  17954. }
  17955. function getVertexByIndex(index, vertex) {
  17956. const stride = index * 3;
  17957. vertex.x = vertices[stride + 0];
  17958. vertex.y = vertices[stride + 1];
  17959. vertex.z = vertices[stride + 2];
  17960. }
  17961. function correctUVs() {
  17962. const a = new Vector3();
  17963. const b = new Vector3();
  17964. const c = new Vector3();
  17965. const centroid = new Vector3();
  17966. const uvA = new Vector2();
  17967. const uvB = new Vector2();
  17968. const uvC = new Vector2();
  17969. for (let i = 0, j = 0; i < vertexBuffer.length; i += 9, j += 6) {
  17970. a.set(vertexBuffer[i + 0], vertexBuffer[i + 1], vertexBuffer[i + 2]);
  17971. b.set(vertexBuffer[i + 3], vertexBuffer[i + 4], vertexBuffer[i + 5]);
  17972. c.set(vertexBuffer[i + 6], vertexBuffer[i + 7], vertexBuffer[i + 8]);
  17973. uvA.set(uvBuffer[j + 0], uvBuffer[j + 1]);
  17974. uvB.set(uvBuffer[j + 2], uvBuffer[j + 3]);
  17975. uvC.set(uvBuffer[j + 4], uvBuffer[j + 5]);
  17976. centroid.copy(a).add(b).add(c).divideScalar(3);
  17977. const azi = azimuth(centroid);
  17978. correctUV(uvA, j + 0, a, azi);
  17979. correctUV(uvB, j + 2, b, azi);
  17980. correctUV(uvC, j + 4, c, azi);
  17981. }
  17982. }
  17983. function correctUV(uv, stride, vector, azimuth) {
  17984. if (azimuth < 0 && uv.x === 1) {
  17985. uvBuffer[stride] = uv.x - 1;
  17986. }
  17987. if (vector.x === 0 && vector.z === 0) {
  17988. uvBuffer[stride] = azimuth / 2 / Math.PI + 0.5;
  17989. }
  17990. } // Angle around the Y axis, counter-clockwise when looking from above.
  17991. function azimuth(vector) {
  17992. return Math.atan2(vector.z, -vector.x);
  17993. } // Angle above the XZ plane.
  17994. function inclination(vector) {
  17995. return Math.atan2(-vector.y, Math.sqrt(vector.x * vector.x + vector.z * vector.z));
  17996. }
  17997. }
  17998. }
  17999. exports.PolyhedronBufferGeometry = PolyhedronBufferGeometry;
  18000. class DodecahedronBufferGeometry extends PolyhedronBufferGeometry {
  18001. constructor(radius = 1, detail = 0) {
  18002. const t = (1 + Math.sqrt(5)) / 2;
  18003. const r = 1 / t;
  18004. const vertices = [// (±1, ±1, ±1)
  18005. -1, -1, -1, -1, -1, 1, -1, 1, -1, -1, 1, 1, 1, -1, -1, 1, -1, 1, 1, 1, -1, 1, 1, 1, // (0, ±1/φ, ±φ)
  18006. 0, -r, -t, 0, -r, t, 0, r, -t, 0, r, t, // (±1/φ, ±φ, 0)
  18007. -r, -t, 0, -r, t, 0, r, -t, 0, r, t, 0, // (±φ, 0, ±1/φ)
  18008. -t, 0, -r, t, 0, -r, -t, 0, r, t, 0, r];
  18009. const indices = [3, 11, 7, 3, 7, 15, 3, 15, 13, 7, 19, 17, 7, 17, 6, 7, 6, 15, 17, 4, 8, 17, 8, 10, 17, 10, 6, 8, 0, 16, 8, 16, 2, 8, 2, 10, 0, 12, 1, 0, 1, 18, 0, 18, 16, 6, 10, 2, 6, 2, 13, 6, 13, 15, 2, 16, 18, 2, 18, 3, 2, 3, 13, 18, 1, 9, 18, 9, 11, 18, 11, 3, 4, 14, 12, 4, 12, 0, 4, 0, 8, 11, 9, 5, 11, 5, 19, 11, 19, 7, 19, 5, 14, 19, 14, 4, 19, 4, 17, 1, 12, 14, 1, 14, 5, 1, 5, 9];
  18010. super(vertices, indices, radius, detail);
  18011. this.type = 'DodecahedronBufferGeometry';
  18012. this.parameters = {
  18013. radius: radius,
  18014. detail: detail
  18015. };
  18016. }
  18017. }
  18018. exports.DodecahedronBufferGeometry = DodecahedronBufferGeometry;
  18019. class DodecahedronGeometry extends Geometry {
  18020. constructor(radius, detail) {
  18021. super();
  18022. this.type = 'DodecahedronGeometry';
  18023. this.parameters = {
  18024. radius: radius,
  18025. detail: detail
  18026. };
  18027. this.fromBufferGeometry(new DodecahedronBufferGeometry(radius, detail));
  18028. this.mergeVertices();
  18029. }
  18030. }
  18031. exports.DodecahedronGeometry = DodecahedronGeometry;
  18032. const _v0$2 = new Vector3();
  18033. const _v1$5 = new Vector3();
  18034. const _normal$1 = new Vector3();
  18035. const _triangle = new Triangle();
  18036. class EdgesGeometry extends BufferGeometry {
  18037. constructor(geometry, thresholdAngle) {
  18038. super();
  18039. this.type = 'EdgesGeometry';
  18040. this.parameters = {
  18041. thresholdAngle: thresholdAngle
  18042. };
  18043. thresholdAngle = thresholdAngle !== undefined ? thresholdAngle : 1;
  18044. if (geometry.isGeometry) {
  18045. geometry = new BufferGeometry().fromGeometry(geometry);
  18046. }
  18047. const precisionPoints = 4;
  18048. const precision = Math.pow(10, precisionPoints);
  18049. const thresholdDot = Math.cos(MathUtils.DEG2RAD * thresholdAngle);
  18050. const indexAttr = geometry.getIndex();
  18051. const positionAttr = geometry.getAttribute('position');
  18052. const indexCount = indexAttr ? indexAttr.count : positionAttr.count;
  18053. const indexArr = [0, 0, 0];
  18054. const vertKeys = ['a', 'b', 'c'];
  18055. const hashes = new Array(3);
  18056. const edgeData = {};
  18057. const vertices = [];
  18058. for (let i = 0; i < indexCount; i += 3) {
  18059. if (indexAttr) {
  18060. indexArr[0] = indexAttr.getX(i);
  18061. indexArr[1] = indexAttr.getX(i + 1);
  18062. indexArr[2] = indexAttr.getX(i + 2);
  18063. } else {
  18064. indexArr[0] = i;
  18065. indexArr[1] = i + 1;
  18066. indexArr[2] = i + 2;
  18067. }
  18068. const {
  18069. a,
  18070. b,
  18071. c
  18072. } = _triangle;
  18073. a.fromBufferAttribute(positionAttr, indexArr[0]);
  18074. b.fromBufferAttribute(positionAttr, indexArr[1]);
  18075. c.fromBufferAttribute(positionAttr, indexArr[2]);
  18076. _triangle.getNormal(_normal$1); // create hashes for the edge from the vertices
  18077. hashes[0] = `${Math.round(a.x * precision)},${Math.round(a.y * precision)},${Math.round(a.z * precision)}`;
  18078. hashes[1] = `${Math.round(b.x * precision)},${Math.round(b.y * precision)},${Math.round(b.z * precision)}`;
  18079. hashes[2] = `${Math.round(c.x * precision)},${Math.round(c.y * precision)},${Math.round(c.z * precision)}`; // skip degenerate triangles
  18080. if (hashes[0] === hashes[1] || hashes[1] === hashes[2] || hashes[2] === hashes[0]) {
  18081. continue;
  18082. } // iterate over every edge
  18083. for (let j = 0; j < 3; j++) {
  18084. // get the first and next vertex making up the edge
  18085. const jNext = (j + 1) % 3;
  18086. const vecHash0 = hashes[j];
  18087. const vecHash1 = hashes[jNext];
  18088. const v0 = _triangle[vertKeys[j]];
  18089. const v1 = _triangle[vertKeys[jNext]];
  18090. const hash = `${vecHash0}_${vecHash1}`;
  18091. const reverseHash = `${vecHash1}_${vecHash0}`;
  18092. if (reverseHash in edgeData && edgeData[reverseHash]) {
  18093. // if we found a sibling edge add it into the vertex array if
  18094. // it meets the angle threshold and delete the edge from the map.
  18095. if (_normal$1.dot(edgeData[reverseHash].normal) <= thresholdDot) {
  18096. vertices.push(v0.x, v0.y, v0.z);
  18097. vertices.push(v1.x, v1.y, v1.z);
  18098. }
  18099. edgeData[reverseHash] = null;
  18100. } else if (!(hash in edgeData)) {
  18101. // if we've already got an edge here then skip adding a new one
  18102. edgeData[hash] = {
  18103. index0: indexArr[j],
  18104. index1: indexArr[jNext],
  18105. normal: _normal$1.clone()
  18106. };
  18107. }
  18108. }
  18109. } // iterate over all remaining, unmatched edges and add them to the vertex array
  18110. for (const key in edgeData) {
  18111. if (edgeData[key]) {
  18112. const {
  18113. index0,
  18114. index1
  18115. } = edgeData[key];
  18116. _v0$2.fromBufferAttribute(positionAttr, index0);
  18117. _v1$5.fromBufferAttribute(positionAttr, index1);
  18118. vertices.push(_v0$2.x, _v0$2.y, _v0$2.z);
  18119. vertices.push(_v1$5.x, _v1$5.y, _v1$5.z);
  18120. }
  18121. }
  18122. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  18123. }
  18124. }
  18125. /**
  18126. * Port from https://github.com/mapbox/earcut (v2.2.2)
  18127. */
  18128. exports.EdgesGeometry = EdgesGeometry;
  18129. const Earcut = {
  18130. triangulate: function (data, holeIndices, dim) {
  18131. dim = dim || 2;
  18132. const hasHoles = holeIndices && holeIndices.length;
  18133. const outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  18134. let outerNode = linkedList(data, 0, outerLen, dim, true);
  18135. const triangles = [];
  18136. if (!outerNode || outerNode.next === outerNode.prev) return triangles;
  18137. let minX, minY, maxX, maxY, x, y, invSize;
  18138. if (hasHoles) outerNode = eliminateHoles(data, holeIndices, outerNode, dim); // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  18139. if (data.length > 80 * dim) {
  18140. minX = maxX = data[0];
  18141. minY = maxY = data[1];
  18142. for (let i = dim; i < outerLen; i += dim) {
  18143. x = data[i];
  18144. y = data[i + 1];
  18145. if (x < minX) minX = x;
  18146. if (y < minY) minY = y;
  18147. if (x > maxX) maxX = x;
  18148. if (y > maxY) maxY = y;
  18149. } // minX, minY and invSize are later used to transform coords into integers for z-order calculation
  18150. invSize = Math.max(maxX - minX, maxY - minY);
  18151. invSize = invSize !== 0 ? 1 / invSize : 0;
  18152. }
  18153. earcutLinked(outerNode, triangles, dim, minX, minY, invSize);
  18154. return triangles;
  18155. }
  18156. }; // create a circular doubly linked list from polygon points in the specified winding order
  18157. function linkedList(data, start, end, dim, clockwise) {
  18158. let i, last;
  18159. if (clockwise === signedArea(data, start, end, dim) > 0) {
  18160. for (i = start; i < end; i += dim) last = insertNode(i, data[i], data[i + 1], last);
  18161. } else {
  18162. for (i = end - dim; i >= start; i -= dim) last = insertNode(i, data[i], data[i + 1], last);
  18163. }
  18164. if (last && equals(last, last.next)) {
  18165. removeNode(last);
  18166. last = last.next;
  18167. }
  18168. return last;
  18169. } // eliminate colinear or duplicate points
  18170. function filterPoints(start, end) {
  18171. if (!start) return start;
  18172. if (!end) end = start;
  18173. let p = start,
  18174. again;
  18175. do {
  18176. again = false;
  18177. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  18178. removeNode(p);
  18179. p = end = p.prev;
  18180. if (p === p.next) break;
  18181. again = true;
  18182. } else {
  18183. p = p.next;
  18184. }
  18185. } while (again || p !== end);
  18186. return end;
  18187. } // main ear slicing loop which triangulates a polygon (given as a linked list)
  18188. function earcutLinked(ear, triangles, dim, minX, minY, invSize, pass) {
  18189. if (!ear) return; // interlink polygon nodes in z-order
  18190. if (!pass && invSize) indexCurve(ear, minX, minY, invSize);
  18191. let stop = ear,
  18192. prev,
  18193. next; // iterate through ears, slicing them one by one
  18194. while (ear.prev !== ear.next) {
  18195. prev = ear.prev;
  18196. next = ear.next;
  18197. if (invSize ? isEarHashed(ear, minX, minY, invSize) : isEar(ear)) {
  18198. // cut off the triangle
  18199. triangles.push(prev.i / dim);
  18200. triangles.push(ear.i / dim);
  18201. triangles.push(next.i / dim);
  18202. removeNode(ear); // skipping the next vertex leads to less sliver triangles
  18203. ear = next.next;
  18204. stop = next.next;
  18205. continue;
  18206. }
  18207. ear = next; // if we looped through the whole remaining polygon and can't find any more ears
  18208. if (ear === stop) {
  18209. // try filtering points and slicing again
  18210. if (!pass) {
  18211. earcutLinked(filterPoints(ear), triangles, dim, minX, minY, invSize, 1); // if this didn't work, try curing all small self-intersections locally
  18212. } else if (pass === 1) {
  18213. ear = cureLocalIntersections(filterPoints(ear), triangles, dim);
  18214. earcutLinked(ear, triangles, dim, minX, minY, invSize, 2); // as a last resort, try splitting the remaining polygon into two
  18215. } else if (pass === 2) {
  18216. splitEarcut(ear, triangles, dim, minX, minY, invSize);
  18217. }
  18218. break;
  18219. }
  18220. }
  18221. } // check whether a polygon node forms a valid ear with adjacent nodes
  18222. function isEar(ear) {
  18223. const a = ear.prev,
  18224. b = ear,
  18225. c = ear.next;
  18226. if (area(a, b, c) >= 0) return false; // reflex, can't be an ear
  18227. // now make sure we don't have other points inside the potential ear
  18228. let p = ear.next.next;
  18229. while (p !== ear.prev) {
  18230. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) && area(p.prev, p, p.next) >= 0) return false;
  18231. p = p.next;
  18232. }
  18233. return true;
  18234. }
  18235. function isEarHashed(ear, minX, minY, invSize) {
  18236. const a = ear.prev,
  18237. b = ear,
  18238. c = ear.next;
  18239. if (area(a, b, c) >= 0) return false; // reflex, can't be an ear
  18240. // triangle bbox; min & max are calculated like this for speed
  18241. const minTX = a.x < b.x ? a.x < c.x ? a.x : c.x : b.x < c.x ? b.x : c.x,
  18242. minTY = a.y < b.y ? a.y < c.y ? a.y : c.y : b.y < c.y ? b.y : c.y,
  18243. maxTX = a.x > b.x ? a.x > c.x ? a.x : c.x : b.x > c.x ? b.x : c.x,
  18244. maxTY = a.y > b.y ? a.y > c.y ? a.y : c.y : b.y > c.y ? b.y : c.y; // z-order range for the current triangle bbox;
  18245. const minZ = zOrder(minTX, minTY, minX, minY, invSize),
  18246. maxZ = zOrder(maxTX, maxTY, minX, minY, invSize);
  18247. let p = ear.prevZ,
  18248. n = ear.nextZ; // look for points inside the triangle in both directions
  18249. while (p && p.z >= minZ && n && n.z <= maxZ) {
  18250. if (p !== ear.prev && p !== ear.next && pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) && area(p.prev, p, p.next) >= 0) return false;
  18251. p = p.prevZ;
  18252. if (n !== ear.prev && n !== ear.next && pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, n.x, n.y) && area(n.prev, n, n.next) >= 0) return false;
  18253. n = n.nextZ;
  18254. } // look for remaining points in decreasing z-order
  18255. while (p && p.z >= minZ) {
  18256. if (p !== ear.prev && p !== ear.next && pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) && area(p.prev, p, p.next) >= 0) return false;
  18257. p = p.prevZ;
  18258. } // look for remaining points in increasing z-order
  18259. while (n && n.z <= maxZ) {
  18260. if (n !== ear.prev && n !== ear.next && pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, n.x, n.y) && area(n.prev, n, n.next) >= 0) return false;
  18261. n = n.nextZ;
  18262. }
  18263. return true;
  18264. } // go through all polygon nodes and cure small local self-intersections
  18265. function cureLocalIntersections(start, triangles, dim) {
  18266. let p = start;
  18267. do {
  18268. const a = p.prev,
  18269. b = p.next.next;
  18270. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  18271. triangles.push(a.i / dim);
  18272. triangles.push(p.i / dim);
  18273. triangles.push(b.i / dim); // remove two nodes involved
  18274. removeNode(p);
  18275. removeNode(p.next);
  18276. p = start = b;
  18277. }
  18278. p = p.next;
  18279. } while (p !== start);
  18280. return filterPoints(p);
  18281. } // try splitting polygon into two and triangulate them independently
  18282. function splitEarcut(start, triangles, dim, minX, minY, invSize) {
  18283. // look for a valid diagonal that divides the polygon into two
  18284. let a = start;
  18285. do {
  18286. let b = a.next.next;
  18287. while (b !== a.prev) {
  18288. if (a.i !== b.i && isValidDiagonal(a, b)) {
  18289. // split the polygon in two by the diagonal
  18290. let c = splitPolygon(a, b); // filter colinear points around the cuts
  18291. a = filterPoints(a, a.next);
  18292. c = filterPoints(c, c.next); // run earcut on each half
  18293. earcutLinked(a, triangles, dim, minX, minY, invSize);
  18294. earcutLinked(c, triangles, dim, minX, minY, invSize);
  18295. return;
  18296. }
  18297. b = b.next;
  18298. }
  18299. a = a.next;
  18300. } while (a !== start);
  18301. } // link every hole into the outer loop, producing a single-ring polygon without holes
  18302. function eliminateHoles(data, holeIndices, outerNode, dim) {
  18303. const queue = [];
  18304. let i, len, start, end, list;
  18305. for (i = 0, len = holeIndices.length; i < len; i++) {
  18306. start = holeIndices[i] * dim;
  18307. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  18308. list = linkedList(data, start, end, dim, false);
  18309. if (list === list.next) list.steiner = true;
  18310. queue.push(getLeftmost(list));
  18311. }
  18312. queue.sort(compareX); // process holes from left to right
  18313. for (i = 0; i < queue.length; i++) {
  18314. eliminateHole(queue[i], outerNode);
  18315. outerNode = filterPoints(outerNode, outerNode.next);
  18316. }
  18317. return outerNode;
  18318. }
  18319. function compareX(a, b) {
  18320. return a.x - b.x;
  18321. } // find a bridge between vertices that connects hole with an outer ring and and link it
  18322. function eliminateHole(hole, outerNode) {
  18323. outerNode = findHoleBridge(hole, outerNode);
  18324. if (outerNode) {
  18325. const b = splitPolygon(outerNode, hole); // filter collinear points around the cuts
  18326. filterPoints(outerNode, outerNode.next);
  18327. filterPoints(b, b.next);
  18328. }
  18329. } // David Eberly's algorithm for finding a bridge between hole and outer polygon
  18330. function findHoleBridge(hole, outerNode) {
  18331. let p = outerNode;
  18332. const hx = hole.x;
  18333. const hy = hole.y;
  18334. let qx = -Infinity,
  18335. m; // find a segment intersected by a ray from the hole's leftmost point to the left;
  18336. // segment's endpoint with lesser x will be potential connection point
  18337. do {
  18338. if (hy <= p.y && hy >= p.next.y && p.next.y !== p.y) {
  18339. const x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  18340. if (x <= hx && x > qx) {
  18341. qx = x;
  18342. if (x === hx) {
  18343. if (hy === p.y) return p;
  18344. if (hy === p.next.y) return p.next;
  18345. }
  18346. m = p.x < p.next.x ? p : p.next;
  18347. }
  18348. }
  18349. p = p.next;
  18350. } while (p !== outerNode);
  18351. if (!m) return null;
  18352. if (hx === qx) return m; // hole touches outer segment; pick leftmost endpoint
  18353. // look for points inside the triangle of hole point, segment intersection and endpoint;
  18354. // if there are no points found, we have a valid connection;
  18355. // otherwise choose the point of the minimum angle with the ray as connection point
  18356. const stop = m,
  18357. mx = m.x,
  18358. my = m.y;
  18359. let tanMin = Infinity,
  18360. tan;
  18361. p = m;
  18362. do {
  18363. if (hx >= p.x && p.x >= mx && hx !== p.x && pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  18364. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  18365. if (locallyInside(p, hole) && (tan < tanMin || tan === tanMin && (p.x > m.x || p.x === m.x && sectorContainsSector(m, p)))) {
  18366. m = p;
  18367. tanMin = tan;
  18368. }
  18369. }
  18370. p = p.next;
  18371. } while (p !== stop);
  18372. return m;
  18373. } // whether sector in vertex m contains sector in vertex p in the same coordinates
  18374. function sectorContainsSector(m, p) {
  18375. return area(m.prev, m, p.prev) < 0 && area(p.next, m, m.next) < 0;
  18376. } // interlink polygon nodes in z-order
  18377. function indexCurve(start, minX, minY, invSize) {
  18378. let p = start;
  18379. do {
  18380. if (p.z === null) p.z = zOrder(p.x, p.y, minX, minY, invSize);
  18381. p.prevZ = p.prev;
  18382. p.nextZ = p.next;
  18383. p = p.next;
  18384. } while (p !== start);
  18385. p.prevZ.nextZ = null;
  18386. p.prevZ = null;
  18387. sortLinked(p);
  18388. } // Simon Tatham's linked list merge sort algorithm
  18389. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  18390. function sortLinked(list) {
  18391. let i,
  18392. p,
  18393. q,
  18394. e,
  18395. tail,
  18396. numMerges,
  18397. pSize,
  18398. qSize,
  18399. inSize = 1;
  18400. do {
  18401. p = list;
  18402. list = null;
  18403. tail = null;
  18404. numMerges = 0;
  18405. while (p) {
  18406. numMerges++;
  18407. q = p;
  18408. pSize = 0;
  18409. for (i = 0; i < inSize; i++) {
  18410. pSize++;
  18411. q = q.nextZ;
  18412. if (!q) break;
  18413. }
  18414. qSize = inSize;
  18415. while (pSize > 0 || qSize > 0 && q) {
  18416. if (pSize !== 0 && (qSize === 0 || !q || p.z <= q.z)) {
  18417. e = p;
  18418. p = p.nextZ;
  18419. pSize--;
  18420. } else {
  18421. e = q;
  18422. q = q.nextZ;
  18423. qSize--;
  18424. }
  18425. if (tail) tail.nextZ = e;else list = e;
  18426. e.prevZ = tail;
  18427. tail = e;
  18428. }
  18429. p = q;
  18430. }
  18431. tail.nextZ = null;
  18432. inSize *= 2;
  18433. } while (numMerges > 1);
  18434. return list;
  18435. } // z-order of a point given coords and inverse of the longer side of data bbox
  18436. function zOrder(x, y, minX, minY, invSize) {
  18437. // coords are transformed into non-negative 15-bit integer range
  18438. x = 32767 * (x - minX) * invSize;
  18439. y = 32767 * (y - minY) * invSize;
  18440. x = (x | x << 8) & 0x00FF00FF;
  18441. x = (x | x << 4) & 0x0F0F0F0F;
  18442. x = (x | x << 2) & 0x33333333;
  18443. x = (x | x << 1) & 0x55555555;
  18444. y = (y | y << 8) & 0x00FF00FF;
  18445. y = (y | y << 4) & 0x0F0F0F0F;
  18446. y = (y | y << 2) & 0x33333333;
  18447. y = (y | y << 1) & 0x55555555;
  18448. return x | y << 1;
  18449. } // find the leftmost node of a polygon ring
  18450. function getLeftmost(start) {
  18451. let p = start,
  18452. leftmost = start;
  18453. do {
  18454. if (p.x < leftmost.x || p.x === leftmost.x && p.y < leftmost.y) leftmost = p;
  18455. p = p.next;
  18456. } while (p !== start);
  18457. return leftmost;
  18458. } // check if a point lies within a convex triangle
  18459. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  18460. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 && (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 && (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  18461. } // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  18462. function isValidDiagonal(a, b) {
  18463. return a.next.i !== b.i && a.prev.i !== b.i && !intersectsPolygon(a, b) && ( // dones't intersect other edges
  18464. locallyInside(a, b) && locallyInside(b, a) && middleInside(a, b) && ( // locally visible
  18465. area(a.prev, a, b.prev) || area(a, b.prev, b)) || // does not create opposite-facing sectors
  18466. equals(a, b) && area(a.prev, a, a.next) > 0 && area(b.prev, b, b.next) > 0); // special zero-length case
  18467. } // signed area of a triangle
  18468. function area(p, q, r) {
  18469. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  18470. } // check if two points are equal
  18471. function equals(p1, p2) {
  18472. return p1.x === p2.x && p1.y === p2.y;
  18473. } // check if two segments intersect
  18474. function intersects(p1, q1, p2, q2) {
  18475. const o1 = sign(area(p1, q1, p2));
  18476. const o2 = sign(area(p1, q1, q2));
  18477. const o3 = sign(area(p2, q2, p1));
  18478. const o4 = sign(area(p2, q2, q1));
  18479. if (o1 !== o2 && o3 !== o4) return true; // general case
  18480. if (o1 === 0 && onSegment(p1, p2, q1)) return true; // p1, q1 and p2 are collinear and p2 lies on p1q1
  18481. if (o2 === 0 && onSegment(p1, q2, q1)) return true; // p1, q1 and q2 are collinear and q2 lies on p1q1
  18482. if (o3 === 0 && onSegment(p2, p1, q2)) return true; // p2, q2 and p1 are collinear and p1 lies on p2q2
  18483. if (o4 === 0 && onSegment(p2, q1, q2)) return true; // p2, q2 and q1 are collinear and q1 lies on p2q2
  18484. return false;
  18485. } // for collinear points p, q, r, check if point q lies on segment pr
  18486. function onSegment(p, q, r) {
  18487. return q.x <= Math.max(p.x, r.x) && q.x >= Math.min(p.x, r.x) && q.y <= Math.max(p.y, r.y) && q.y >= Math.min(p.y, r.y);
  18488. }
  18489. function sign(num) {
  18490. return num > 0 ? 1 : num < 0 ? -1 : 0;
  18491. } // check if a polygon diagonal intersects any polygon segments
  18492. function intersectsPolygon(a, b) {
  18493. let p = a;
  18494. do {
  18495. if (p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i && intersects(p, p.next, a, b)) return true;
  18496. p = p.next;
  18497. } while (p !== a);
  18498. return false;
  18499. } // check if a polygon diagonal is locally inside the polygon
  18500. function locallyInside(a, b) {
  18501. return area(a.prev, a, a.next) < 0 ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0 : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  18502. } // check if the middle point of a polygon diagonal is inside the polygon
  18503. function middleInside(a, b) {
  18504. let p = a,
  18505. inside = false;
  18506. const px = (a.x + b.x) / 2,
  18507. py = (a.y + b.y) / 2;
  18508. do {
  18509. if (p.y > py !== p.next.y > py && p.next.y !== p.y && px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x) inside = !inside;
  18510. p = p.next;
  18511. } while (p !== a);
  18512. return inside;
  18513. } // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  18514. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  18515. function splitPolygon(a, b) {
  18516. const a2 = new Node(a.i, a.x, a.y),
  18517. b2 = new Node(b.i, b.x, b.y),
  18518. an = a.next,
  18519. bp = b.prev;
  18520. a.next = b;
  18521. b.prev = a;
  18522. a2.next = an;
  18523. an.prev = a2;
  18524. b2.next = a2;
  18525. a2.prev = b2;
  18526. bp.next = b2;
  18527. b2.prev = bp;
  18528. return b2;
  18529. } // create a node and optionally link it with previous one (in a circular doubly linked list)
  18530. function insertNode(i, x, y, last) {
  18531. const p = new Node(i, x, y);
  18532. if (!last) {
  18533. p.prev = p;
  18534. p.next = p;
  18535. } else {
  18536. p.next = last.next;
  18537. p.prev = last;
  18538. last.next.prev = p;
  18539. last.next = p;
  18540. }
  18541. return p;
  18542. }
  18543. function removeNode(p) {
  18544. p.next.prev = p.prev;
  18545. p.prev.next = p.next;
  18546. if (p.prevZ) p.prevZ.nextZ = p.nextZ;
  18547. if (p.nextZ) p.nextZ.prevZ = p.prevZ;
  18548. }
  18549. function Node(i, x, y) {
  18550. // vertex index in coordinates array
  18551. this.i = i; // vertex coordinates
  18552. this.x = x;
  18553. this.y = y; // previous and next vertex nodes in a polygon ring
  18554. this.prev = null;
  18555. this.next = null; // z-order curve value
  18556. this.z = null; // previous and next nodes in z-order
  18557. this.prevZ = null;
  18558. this.nextZ = null; // indicates whether this is a steiner point
  18559. this.steiner = false;
  18560. }
  18561. function signedArea(data, start, end, dim) {
  18562. let sum = 0;
  18563. for (let i = start, j = end - dim; i < end; i += dim) {
  18564. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  18565. j = i;
  18566. }
  18567. return sum;
  18568. }
  18569. const ShapeUtils = {
  18570. // calculate area of the contour polygon
  18571. area: function (contour) {
  18572. const n = contour.length;
  18573. let a = 0.0;
  18574. for (let p = n - 1, q = 0; q < n; p = q++) {
  18575. a += contour[p].x * contour[q].y - contour[q].x * contour[p].y;
  18576. }
  18577. return a * 0.5;
  18578. },
  18579. isClockWise: function (pts) {
  18580. return ShapeUtils.area(pts) < 0;
  18581. },
  18582. triangulateShape: function (contour, holes) {
  18583. const vertices = []; // flat array of vertices like [ x0,y0, x1,y1, x2,y2, ... ]
  18584. const holeIndices = []; // array of hole indices
  18585. const faces = []; // final array of vertex indices like [ [ a,b,d ], [ b,c,d ] ]
  18586. removeDupEndPts(contour);
  18587. addContour(vertices, contour); //
  18588. let holeIndex = contour.length;
  18589. holes.forEach(removeDupEndPts);
  18590. for (let i = 0; i < holes.length; i++) {
  18591. holeIndices.push(holeIndex);
  18592. holeIndex += holes[i].length;
  18593. addContour(vertices, holes[i]);
  18594. } //
  18595. const triangles = Earcut.triangulate(vertices, holeIndices); //
  18596. for (let i = 0; i < triangles.length; i += 3) {
  18597. faces.push(triangles.slice(i, i + 3));
  18598. }
  18599. return faces;
  18600. }
  18601. };
  18602. exports.ShapeUtils = ShapeUtils;
  18603. function removeDupEndPts(points) {
  18604. const l = points.length;
  18605. if (l > 2 && points[l - 1].equals(points[0])) {
  18606. points.pop();
  18607. }
  18608. }
  18609. function addContour(vertices, contour) {
  18610. for (let i = 0; i < contour.length; i++) {
  18611. vertices.push(contour[i].x);
  18612. vertices.push(contour[i].y);
  18613. }
  18614. }
  18615. /**
  18616. * Creates extruded geometry from a path shape.
  18617. *
  18618. * parameters = {
  18619. *
  18620. * curveSegments: <int>, // number of points on the curves
  18621. * steps: <int>, // number of points for z-side extrusions / used for subdividing segments of extrude spline too
  18622. * depth: <float>, // Depth to extrude the shape
  18623. *
  18624. * bevelEnabled: <bool>, // turn on bevel
  18625. * bevelThickness: <float>, // how deep into the original shape bevel goes
  18626. * bevelSize: <float>, // how far from shape outline (including bevelOffset) is bevel
  18627. * bevelOffset: <float>, // how far from shape outline does bevel start
  18628. * bevelSegments: <int>, // number of bevel layers
  18629. *
  18630. * extrudePath: <THREE.Curve> // curve to extrude shape along
  18631. *
  18632. * UVGenerator: <Object> // object that provides UV generator functions
  18633. *
  18634. * }
  18635. */
  18636. class ExtrudeBufferGeometry extends BufferGeometry {
  18637. constructor(shapes, options) {
  18638. super();
  18639. this.type = 'ExtrudeBufferGeometry';
  18640. this.parameters = {
  18641. shapes: shapes,
  18642. options: options
  18643. };
  18644. shapes = Array.isArray(shapes) ? shapes : [shapes];
  18645. const scope = this;
  18646. const verticesArray = [];
  18647. const uvArray = [];
  18648. for (let i = 0, l = shapes.length; i < l; i++) {
  18649. const shape = shapes[i];
  18650. addShape(shape);
  18651. } // build geometry
  18652. this.setAttribute('position', new Float32BufferAttribute(verticesArray, 3));
  18653. this.setAttribute('uv', new Float32BufferAttribute(uvArray, 2));
  18654. this.computeVertexNormals(); // functions
  18655. function addShape(shape) {
  18656. const placeholder = []; // options
  18657. const curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  18658. const steps = options.steps !== undefined ? options.steps : 1;
  18659. let depth = options.depth !== undefined ? options.depth : 100;
  18660. let bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true;
  18661. let bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 6;
  18662. let bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 2;
  18663. let bevelOffset = options.bevelOffset !== undefined ? options.bevelOffset : 0;
  18664. let bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  18665. const extrudePath = options.extrudePath;
  18666. const uvgen = options.UVGenerator !== undefined ? options.UVGenerator : WorldUVGenerator; // deprecated options
  18667. if (options.amount !== undefined) {
  18668. console.warn('THREE.ExtrudeBufferGeometry: amount has been renamed to depth.');
  18669. depth = options.amount;
  18670. } //
  18671. let extrudePts,
  18672. extrudeByPath = false;
  18673. let splineTube, binormal, normal, position2;
  18674. if (extrudePath) {
  18675. extrudePts = extrudePath.getSpacedPoints(steps);
  18676. extrudeByPath = true;
  18677. bevelEnabled = false; // bevels not supported for path extrusion
  18678. // SETUP TNB variables
  18679. // TODO1 - have a .isClosed in spline?
  18680. splineTube = extrudePath.computeFrenetFrames(steps, false); // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  18681. binormal = new Vector3();
  18682. normal = new Vector3();
  18683. position2 = new Vector3();
  18684. } // Safeguards if bevels are not enabled
  18685. if (!bevelEnabled) {
  18686. bevelSegments = 0;
  18687. bevelThickness = 0;
  18688. bevelSize = 0;
  18689. bevelOffset = 0;
  18690. } // Variables initialization
  18691. const shapePoints = shape.extractPoints(curveSegments);
  18692. let vertices = shapePoints.shape;
  18693. const holes = shapePoints.holes;
  18694. const reverse = !ShapeUtils.isClockWise(vertices);
  18695. if (reverse) {
  18696. vertices = vertices.reverse(); // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  18697. for (let h = 0, hl = holes.length; h < hl; h++) {
  18698. const ahole = holes[h];
  18699. if (ShapeUtils.isClockWise(ahole)) {
  18700. holes[h] = ahole.reverse();
  18701. }
  18702. }
  18703. }
  18704. const faces = ShapeUtils.triangulateShape(vertices, holes);
  18705. /* Vertices */
  18706. const contour = vertices; // vertices has all points but contour has only points of circumference
  18707. for (let h = 0, hl = holes.length; h < hl; h++) {
  18708. const ahole = holes[h];
  18709. vertices = vertices.concat(ahole);
  18710. }
  18711. function scalePt2(pt, vec, size) {
  18712. if (!vec) console.error("THREE.ExtrudeGeometry: vec does not exist");
  18713. return vec.clone().multiplyScalar(size).add(pt);
  18714. }
  18715. const vlen = vertices.length,
  18716. flen = faces.length; // Find directions for point movement
  18717. function getBevelVec(inPt, inPrev, inNext) {
  18718. // computes for inPt the corresponding point inPt' on a new contour
  18719. // shifted by 1 unit (length of normalized vector) to the left
  18720. // if we walk along contour clockwise, this new contour is outside the old one
  18721. //
  18722. // inPt' is the intersection of the two lines parallel to the two
  18723. // adjacent edges of inPt at a distance of 1 unit on the left side.
  18724. let v_trans_x, v_trans_y, shrink_by; // resulting translation vector for inPt
  18725. // good reading for geometry algorithms (here: line-line intersection)
  18726. // http://geomalgorithms.com/a05-_intersect-1.html
  18727. const v_prev_x = inPt.x - inPrev.x,
  18728. v_prev_y = inPt.y - inPrev.y;
  18729. const v_next_x = inNext.x - inPt.x,
  18730. v_next_y = inNext.y - inPt.y;
  18731. const v_prev_lensq = v_prev_x * v_prev_x + v_prev_y * v_prev_y; // check for collinear edges
  18732. const collinear0 = v_prev_x * v_next_y - v_prev_y * v_next_x;
  18733. if (Math.abs(collinear0) > Number.EPSILON) {
  18734. // not collinear
  18735. // length of vectors for normalizing
  18736. const v_prev_len = Math.sqrt(v_prev_lensq);
  18737. const v_next_len = Math.sqrt(v_next_x * v_next_x + v_next_y * v_next_y); // shift adjacent points by unit vectors to the left
  18738. const ptPrevShift_x = inPrev.x - v_prev_y / v_prev_len;
  18739. const ptPrevShift_y = inPrev.y + v_prev_x / v_prev_len;
  18740. const ptNextShift_x = inNext.x - v_next_y / v_next_len;
  18741. const ptNextShift_y = inNext.y + v_next_x / v_next_len; // scaling factor for v_prev to intersection point
  18742. const sf = ((ptNextShift_x - ptPrevShift_x) * v_next_y - (ptNextShift_y - ptPrevShift_y) * v_next_x) / (v_prev_x * v_next_y - v_prev_y * v_next_x); // vector from inPt to intersection point
  18743. v_trans_x = ptPrevShift_x + v_prev_x * sf - inPt.x;
  18744. v_trans_y = ptPrevShift_y + v_prev_y * sf - inPt.y; // Don't normalize!, otherwise sharp corners become ugly
  18745. // but prevent crazy spikes
  18746. const v_trans_lensq = v_trans_x * v_trans_x + v_trans_y * v_trans_y;
  18747. if (v_trans_lensq <= 2) {
  18748. return new Vector2(v_trans_x, v_trans_y);
  18749. } else {
  18750. shrink_by = Math.sqrt(v_trans_lensq / 2);
  18751. }
  18752. } else {
  18753. // handle special case of collinear edges
  18754. let direction_eq = false; // assumes: opposite
  18755. if (v_prev_x > Number.EPSILON) {
  18756. if (v_next_x > Number.EPSILON) {
  18757. direction_eq = true;
  18758. }
  18759. } else {
  18760. if (v_prev_x < -Number.EPSILON) {
  18761. if (v_next_x < -Number.EPSILON) {
  18762. direction_eq = true;
  18763. }
  18764. } else {
  18765. if (Math.sign(v_prev_y) === Math.sign(v_next_y)) {
  18766. direction_eq = true;
  18767. }
  18768. }
  18769. }
  18770. if (direction_eq) {
  18771. // console.log("Warning: lines are a straight sequence");
  18772. v_trans_x = -v_prev_y;
  18773. v_trans_y = v_prev_x;
  18774. shrink_by = Math.sqrt(v_prev_lensq);
  18775. } else {
  18776. // console.log("Warning: lines are a straight spike");
  18777. v_trans_x = v_prev_x;
  18778. v_trans_y = v_prev_y;
  18779. shrink_by = Math.sqrt(v_prev_lensq / 2);
  18780. }
  18781. }
  18782. return new Vector2(v_trans_x / shrink_by, v_trans_y / shrink_by);
  18783. }
  18784. const contourMovements = [];
  18785. for (let i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i++, j++, k++) {
  18786. if (j === il) j = 0;
  18787. if (k === il) k = 0; // (j)---(i)---(k)
  18788. // console.log('i,j,k', i, j , k)
  18789. contourMovements[i] = getBevelVec(contour[i], contour[j], contour[k]);
  18790. }
  18791. const holesMovements = [];
  18792. let oneHoleMovements,
  18793. verticesMovements = contourMovements.concat();
  18794. for (let h = 0, hl = holes.length; h < hl; h++) {
  18795. const ahole = holes[h];
  18796. oneHoleMovements = [];
  18797. for (let i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i++, j++, k++) {
  18798. if (j === il) j = 0;
  18799. if (k === il) k = 0; // (j)---(i)---(k)
  18800. oneHoleMovements[i] = getBevelVec(ahole[i], ahole[j], ahole[k]);
  18801. }
  18802. holesMovements.push(oneHoleMovements);
  18803. verticesMovements = verticesMovements.concat(oneHoleMovements);
  18804. } // Loop bevelSegments, 1 for the front, 1 for the back
  18805. for (let b = 0; b < bevelSegments; b++) {
  18806. //for ( b = bevelSegments; b > 0; b -- ) {
  18807. const t = b / bevelSegments;
  18808. const z = bevelThickness * Math.cos(t * Math.PI / 2);
  18809. const bs = bevelSize * Math.sin(t * Math.PI / 2) + bevelOffset; // contract shape
  18810. for (let i = 0, il = contour.length; i < il; i++) {
  18811. const vert = scalePt2(contour[i], contourMovements[i], bs);
  18812. v(vert.x, vert.y, -z);
  18813. } // expand holes
  18814. for (let h = 0, hl = holes.length; h < hl; h++) {
  18815. const ahole = holes[h];
  18816. oneHoleMovements = holesMovements[h];
  18817. for (let i = 0, il = ahole.length; i < il; i++) {
  18818. const vert = scalePt2(ahole[i], oneHoleMovements[i], bs);
  18819. v(vert.x, vert.y, -z);
  18820. }
  18821. }
  18822. }
  18823. const bs = bevelSize + bevelOffset; // Back facing vertices
  18824. for (let i = 0; i < vlen; i++) {
  18825. const vert = bevelEnabled ? scalePt2(vertices[i], verticesMovements[i], bs) : vertices[i];
  18826. if (!extrudeByPath) {
  18827. v(vert.x, vert.y, 0);
  18828. } else {
  18829. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  18830. normal.copy(splineTube.normals[0]).multiplyScalar(vert.x);
  18831. binormal.copy(splineTube.binormals[0]).multiplyScalar(vert.y);
  18832. position2.copy(extrudePts[0]).add(normal).add(binormal);
  18833. v(position2.x, position2.y, position2.z);
  18834. }
  18835. } // Add stepped vertices...
  18836. // Including front facing vertices
  18837. for (let s = 1; s <= steps; s++) {
  18838. for (let i = 0; i < vlen; i++) {
  18839. const vert = bevelEnabled ? scalePt2(vertices[i], verticesMovements[i], bs) : vertices[i];
  18840. if (!extrudeByPath) {
  18841. v(vert.x, vert.y, depth / steps * s);
  18842. } else {
  18843. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  18844. normal.copy(splineTube.normals[s]).multiplyScalar(vert.x);
  18845. binormal.copy(splineTube.binormals[s]).multiplyScalar(vert.y);
  18846. position2.copy(extrudePts[s]).add(normal).add(binormal);
  18847. v(position2.x, position2.y, position2.z);
  18848. }
  18849. }
  18850. } // Add bevel segments planes
  18851. //for ( b = 1; b <= bevelSegments; b ++ ) {
  18852. for (let b = bevelSegments - 1; b >= 0; b--) {
  18853. const t = b / bevelSegments;
  18854. const z = bevelThickness * Math.cos(t * Math.PI / 2);
  18855. const bs = bevelSize * Math.sin(t * Math.PI / 2) + bevelOffset; // contract shape
  18856. for (let i = 0, il = contour.length; i < il; i++) {
  18857. const vert = scalePt2(contour[i], contourMovements[i], bs);
  18858. v(vert.x, vert.y, depth + z);
  18859. } // expand holes
  18860. for (let h = 0, hl = holes.length; h < hl; h++) {
  18861. const ahole = holes[h];
  18862. oneHoleMovements = holesMovements[h];
  18863. for (let i = 0, il = ahole.length; i < il; i++) {
  18864. const vert = scalePt2(ahole[i], oneHoleMovements[i], bs);
  18865. if (!extrudeByPath) {
  18866. v(vert.x, vert.y, depth + z);
  18867. } else {
  18868. v(vert.x, vert.y + extrudePts[steps - 1].y, extrudePts[steps - 1].x + z);
  18869. }
  18870. }
  18871. }
  18872. }
  18873. /* Faces */
  18874. // Top and bottom faces
  18875. buildLidFaces(); // Sides faces
  18876. buildSideFaces(); ///// Internal functions
  18877. function buildLidFaces() {
  18878. const start = verticesArray.length / 3;
  18879. if (bevelEnabled) {
  18880. let layer = 0; // steps + 1
  18881. let offset = vlen * layer; // Bottom faces
  18882. for (let i = 0; i < flen; i++) {
  18883. const face = faces[i];
  18884. f3(face[2] + offset, face[1] + offset, face[0] + offset);
  18885. }
  18886. layer = steps + bevelSegments * 2;
  18887. offset = vlen * layer; // Top faces
  18888. for (let i = 0; i < flen; i++) {
  18889. const face = faces[i];
  18890. f3(face[0] + offset, face[1] + offset, face[2] + offset);
  18891. }
  18892. } else {
  18893. // Bottom faces
  18894. for (let i = 0; i < flen; i++) {
  18895. const face = faces[i];
  18896. f3(face[2], face[1], face[0]);
  18897. } // Top faces
  18898. for (let i = 0; i < flen; i++) {
  18899. const face = faces[i];
  18900. f3(face[0] + vlen * steps, face[1] + vlen * steps, face[2] + vlen * steps);
  18901. }
  18902. }
  18903. scope.addGroup(start, verticesArray.length / 3 - start, 0);
  18904. } // Create faces for the z-sides of the shape
  18905. function buildSideFaces() {
  18906. const start = verticesArray.length / 3;
  18907. let layeroffset = 0;
  18908. sidewalls(contour, layeroffset);
  18909. layeroffset += contour.length;
  18910. for (let h = 0, hl = holes.length; h < hl; h++) {
  18911. const ahole = holes[h];
  18912. sidewalls(ahole, layeroffset); //, true
  18913. layeroffset += ahole.length;
  18914. }
  18915. scope.addGroup(start, verticesArray.length / 3 - start, 1);
  18916. }
  18917. function sidewalls(contour, layeroffset) {
  18918. let i = contour.length;
  18919. while (--i >= 0) {
  18920. const j = i;
  18921. let k = i - 1;
  18922. if (k < 0) k = contour.length - 1; //console.log('b', i,j, i-1, k,vertices.length);
  18923. for (let s = 0, sl = steps + bevelSegments * 2; s < sl; s++) {
  18924. const slen1 = vlen * s;
  18925. const slen2 = vlen * (s + 1);
  18926. const a = layeroffset + j + slen1,
  18927. b = layeroffset + k + slen1,
  18928. c = layeroffset + k + slen2,
  18929. d = layeroffset + j + slen2;
  18930. f4(a, b, c, d);
  18931. }
  18932. }
  18933. }
  18934. function v(x, y, z) {
  18935. placeholder.push(x);
  18936. placeholder.push(y);
  18937. placeholder.push(z);
  18938. }
  18939. function f3(a, b, c) {
  18940. addVertex(a);
  18941. addVertex(b);
  18942. addVertex(c);
  18943. const nextIndex = verticesArray.length / 3;
  18944. const uvs = uvgen.generateTopUV(scope, verticesArray, nextIndex - 3, nextIndex - 2, nextIndex - 1);
  18945. addUV(uvs[0]);
  18946. addUV(uvs[1]);
  18947. addUV(uvs[2]);
  18948. }
  18949. function f4(a, b, c, d) {
  18950. addVertex(a);
  18951. addVertex(b);
  18952. addVertex(d);
  18953. addVertex(b);
  18954. addVertex(c);
  18955. addVertex(d);
  18956. const nextIndex = verticesArray.length / 3;
  18957. const uvs = uvgen.generateSideWallUV(scope, verticesArray, nextIndex - 6, nextIndex - 3, nextIndex - 2, nextIndex - 1);
  18958. addUV(uvs[0]);
  18959. addUV(uvs[1]);
  18960. addUV(uvs[3]);
  18961. addUV(uvs[1]);
  18962. addUV(uvs[2]);
  18963. addUV(uvs[3]);
  18964. }
  18965. function addVertex(index) {
  18966. verticesArray.push(placeholder[index * 3 + 0]);
  18967. verticesArray.push(placeholder[index * 3 + 1]);
  18968. verticesArray.push(placeholder[index * 3 + 2]);
  18969. }
  18970. function addUV(vector2) {
  18971. uvArray.push(vector2.x);
  18972. uvArray.push(vector2.y);
  18973. }
  18974. }
  18975. }
  18976. toJSON() {
  18977. const data = BufferGeometry.prototype.toJSON.call(this);
  18978. const shapes = this.parameters.shapes;
  18979. const options = this.parameters.options;
  18980. return toJSON(shapes, options, data);
  18981. }
  18982. }
  18983. exports.ExtrudeBufferGeometry = ExtrudeBufferGeometry;
  18984. const WorldUVGenerator = {
  18985. generateTopUV: function (geometry, vertices, indexA, indexB, indexC) {
  18986. const a_x = vertices[indexA * 3];
  18987. const a_y = vertices[indexA * 3 + 1];
  18988. const b_x = vertices[indexB * 3];
  18989. const b_y = vertices[indexB * 3 + 1];
  18990. const c_x = vertices[indexC * 3];
  18991. const c_y = vertices[indexC * 3 + 1];
  18992. return [new Vector2(a_x, a_y), new Vector2(b_x, b_y), new Vector2(c_x, c_y)];
  18993. },
  18994. generateSideWallUV: function (geometry, vertices, indexA, indexB, indexC, indexD) {
  18995. const a_x = vertices[indexA * 3];
  18996. const a_y = vertices[indexA * 3 + 1];
  18997. const a_z = vertices[indexA * 3 + 2];
  18998. const b_x = vertices[indexB * 3];
  18999. const b_y = vertices[indexB * 3 + 1];
  19000. const b_z = vertices[indexB * 3 + 2];
  19001. const c_x = vertices[indexC * 3];
  19002. const c_y = vertices[indexC * 3 + 1];
  19003. const c_z = vertices[indexC * 3 + 2];
  19004. const d_x = vertices[indexD * 3];
  19005. const d_y = vertices[indexD * 3 + 1];
  19006. const d_z = vertices[indexD * 3 + 2];
  19007. if (Math.abs(a_y - b_y) < 0.01) {
  19008. return [new Vector2(a_x, 1 - a_z), new Vector2(b_x, 1 - b_z), new Vector2(c_x, 1 - c_z), new Vector2(d_x, 1 - d_z)];
  19009. } else {
  19010. return [new Vector2(a_y, 1 - a_z), new Vector2(b_y, 1 - b_z), new Vector2(c_y, 1 - c_z), new Vector2(d_y, 1 - d_z)];
  19011. }
  19012. }
  19013. };
  19014. function toJSON(shapes, options, data) {
  19015. data.shapes = [];
  19016. if (Array.isArray(shapes)) {
  19017. for (let i = 0, l = shapes.length; i < l; i++) {
  19018. const shape = shapes[i];
  19019. data.shapes.push(shape.uuid);
  19020. }
  19021. } else {
  19022. data.shapes.push(shapes.uuid);
  19023. }
  19024. if (options.extrudePath !== undefined) data.options.extrudePath = options.extrudePath.toJSON();
  19025. return data;
  19026. }
  19027. /**
  19028. * Creates extruded geometry from a path shape.
  19029. *
  19030. * parameters = {
  19031. *
  19032. * curveSegments: <int>, // number of points on the curves
  19033. * steps: <int>, // number of points for z-side extrusions / used for subdividing segments of extrude spline too
  19034. * depth: <float>, // Depth to extrude the shape
  19035. *
  19036. * bevelEnabled: <bool>, // turn on bevel
  19037. * bevelThickness: <float>, // how deep into the original shape bevel goes
  19038. * bevelSize: <float>, // how far from shape outline (including bevelOffset) is bevel
  19039. * bevelOffset: <float>, // how far from shape outline does bevel start
  19040. * bevelSegments: <int>, // number of bevel layers
  19041. *
  19042. * extrudePath: <THREE.Curve> // curve to extrude shape along
  19043. *
  19044. * UVGenerator: <Object> // object that provides UV generator functions
  19045. *
  19046. * }
  19047. */
  19048. class ExtrudeGeometry extends Geometry {
  19049. constructor(shapes, options) {
  19050. super();
  19051. this.type = 'ExtrudeGeometry';
  19052. this.parameters = {
  19053. shapes: shapes,
  19054. options: options
  19055. };
  19056. this.fromBufferGeometry(new ExtrudeBufferGeometry(shapes, options));
  19057. this.mergeVertices();
  19058. }
  19059. toJSON() {
  19060. const data = super.toJSON();
  19061. const shapes = this.parameters.shapes;
  19062. const options = this.parameters.options;
  19063. return toJSON$1(shapes, options, data);
  19064. }
  19065. }
  19066. exports.ExtrudeGeometry = ExtrudeGeometry;
  19067. function toJSON$1(shapes, options, data) {
  19068. data.shapes = [];
  19069. if (Array.isArray(shapes)) {
  19070. for (let i = 0, l = shapes.length; i < l; i++) {
  19071. const shape = shapes[i];
  19072. data.shapes.push(shape.uuid);
  19073. }
  19074. } else {
  19075. data.shapes.push(shapes.uuid);
  19076. }
  19077. if (options.extrudePath !== undefined) data.options.extrudePath = options.extrudePath.toJSON();
  19078. return data;
  19079. }
  19080. class IcosahedronBufferGeometry extends PolyhedronBufferGeometry {
  19081. constructor(radius = 1, detail = 0) {
  19082. const t = (1 + Math.sqrt(5)) / 2;
  19083. const vertices = [-1, t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, 0, -1, t, 0, 1, t, 0, -1, -t, 0, 1, -t, t, 0, -1, t, 0, 1, -t, 0, -1, -t, 0, 1];
  19084. const indices = [0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 0, 10, 11, 1, 5, 9, 5, 11, 4, 11, 10, 2, 10, 7, 6, 7, 1, 8, 3, 9, 4, 3, 4, 2, 3, 2, 6, 3, 6, 8, 3, 8, 9, 4, 9, 5, 2, 4, 11, 6, 2, 10, 8, 6, 7, 9, 8, 1];
  19085. super(vertices, indices, radius, detail);
  19086. this.type = 'IcosahedronBufferGeometry';
  19087. this.parameters = {
  19088. radius: radius,
  19089. detail: detail
  19090. };
  19091. }
  19092. }
  19093. exports.IcosahedronBufferGeometry = IcosahedronBufferGeometry;
  19094. class IcosahedronGeometry extends Geometry {
  19095. constructor(radius, detail) {
  19096. super();
  19097. this.type = 'IcosahedronGeometry';
  19098. this.parameters = {
  19099. radius: radius,
  19100. detail: detail
  19101. };
  19102. this.fromBufferGeometry(new IcosahedronBufferGeometry(radius, detail));
  19103. this.mergeVertices();
  19104. }
  19105. }
  19106. exports.IcosahedronGeometry = IcosahedronGeometry;
  19107. class LatheBufferGeometry extends BufferGeometry {
  19108. constructor(points, segments = 12, phiStart = 0, phiLength = Math.PI * 2) {
  19109. super();
  19110. this.type = 'LatheBufferGeometry';
  19111. this.parameters = {
  19112. points: points,
  19113. segments: segments,
  19114. phiStart: phiStart,
  19115. phiLength: phiLength
  19116. };
  19117. segments = Math.floor(segments); // clamp phiLength so it's in range of [ 0, 2PI ]
  19118. phiLength = MathUtils.clamp(phiLength, 0, Math.PI * 2); // buffers
  19119. const indices = [];
  19120. const vertices = [];
  19121. const uvs = []; // helper variables
  19122. const inverseSegments = 1.0 / segments;
  19123. const vertex = new Vector3();
  19124. const uv = new Vector2(); // generate vertices and uvs
  19125. for (let i = 0; i <= segments; i++) {
  19126. const phi = phiStart + i * inverseSegments * phiLength;
  19127. const sin = Math.sin(phi);
  19128. const cos = Math.cos(phi);
  19129. for (let j = 0; j <= points.length - 1; j++) {
  19130. // vertex
  19131. vertex.x = points[j].x * sin;
  19132. vertex.y = points[j].y;
  19133. vertex.z = points[j].x * cos;
  19134. vertices.push(vertex.x, vertex.y, vertex.z); // uv
  19135. uv.x = i / segments;
  19136. uv.y = j / (points.length - 1);
  19137. uvs.push(uv.x, uv.y);
  19138. }
  19139. } // indices
  19140. for (let i = 0; i < segments; i++) {
  19141. for (let j = 0; j < points.length - 1; j++) {
  19142. const base = j + i * points.length;
  19143. const a = base;
  19144. const b = base + points.length;
  19145. const c = base + points.length + 1;
  19146. const d = base + 1; // faces
  19147. indices.push(a, b, d);
  19148. indices.push(b, c, d);
  19149. }
  19150. } // build geometry
  19151. this.setIndex(indices);
  19152. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  19153. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2)); // generate normals
  19154. this.computeVertexNormals(); // if the geometry is closed, we need to average the normals along the seam.
  19155. // because the corresponding vertices are identical (but still have different UVs).
  19156. if (phiLength === Math.PI * 2) {
  19157. const normals = this.attributes.normal.array;
  19158. const n1 = new Vector3();
  19159. const n2 = new Vector3();
  19160. const n = new Vector3(); // this is the buffer offset for the last line of vertices
  19161. const base = segments * points.length * 3;
  19162. for (let i = 0, j = 0; i < points.length; i++, j += 3) {
  19163. // select the normal of the vertex in the first line
  19164. n1.x = normals[j + 0];
  19165. n1.y = normals[j + 1];
  19166. n1.z = normals[j + 2]; // select the normal of the vertex in the last line
  19167. n2.x = normals[base + j + 0];
  19168. n2.y = normals[base + j + 1];
  19169. n2.z = normals[base + j + 2]; // average normals
  19170. n.addVectors(n1, n2).normalize(); // assign the new values to both normals
  19171. normals[j + 0] = normals[base + j + 0] = n.x;
  19172. normals[j + 1] = normals[base + j + 1] = n.y;
  19173. normals[j + 2] = normals[base + j + 2] = n.z;
  19174. }
  19175. }
  19176. }
  19177. }
  19178. exports.LatheBufferGeometry = LatheBufferGeometry;
  19179. class LatheGeometry extends Geometry {
  19180. constructor(points, segments, phiStart, phiLength) {
  19181. super();
  19182. this.type = 'LatheGeometry';
  19183. this.parameters = {
  19184. points: points,
  19185. segments: segments,
  19186. phiStart: phiStart,
  19187. phiLength: phiLength
  19188. };
  19189. this.fromBufferGeometry(new LatheBufferGeometry(points, segments, phiStart, phiLength));
  19190. this.mergeVertices();
  19191. }
  19192. }
  19193. exports.LatheGeometry = LatheGeometry;
  19194. class OctahedronBufferGeometry extends PolyhedronBufferGeometry {
  19195. constructor(radius = 1, detail = 0) {
  19196. const vertices = [1, 0, 0, -1, 0, 0, 0, 1, 0, 0, -1, 0, 0, 0, 1, 0, 0, -1];
  19197. const indices = [0, 2, 4, 0, 4, 3, 0, 3, 5, 0, 5, 2, 1, 2, 5, 1, 5, 3, 1, 3, 4, 1, 4, 2];
  19198. super(vertices, indices, radius, detail);
  19199. this.type = 'OctahedronBufferGeometry';
  19200. this.parameters = {
  19201. radius: radius,
  19202. detail: detail
  19203. };
  19204. }
  19205. }
  19206. exports.OctahedronBufferGeometry = OctahedronBufferGeometry;
  19207. class OctahedronGeometry extends Geometry {
  19208. constructor(radius, detail) {
  19209. super();
  19210. this.type = 'OctahedronGeometry';
  19211. this.parameters = {
  19212. radius: radius,
  19213. detail: detail
  19214. };
  19215. this.fromBufferGeometry(new OctahedronBufferGeometry(radius, detail));
  19216. this.mergeVertices();
  19217. }
  19218. }
  19219. /**
  19220. * Parametric Surfaces Geometry
  19221. * based on the brilliant article by @prideout https://prideout.net/blog/old/blog/index.html@p=44.html
  19222. */
  19223. exports.OctahedronGeometry = OctahedronGeometry;
  19224. function ParametricBufferGeometry(func, slices, stacks) {
  19225. BufferGeometry.call(this);
  19226. this.type = 'ParametricBufferGeometry';
  19227. this.parameters = {
  19228. func: func,
  19229. slices: slices,
  19230. stacks: stacks
  19231. }; // buffers
  19232. const indices = [];
  19233. const vertices = [];
  19234. const normals = [];
  19235. const uvs = [];
  19236. const EPS = 0.00001;
  19237. const normal = new Vector3();
  19238. const p0 = new Vector3(),
  19239. p1 = new Vector3();
  19240. const pu = new Vector3(),
  19241. pv = new Vector3();
  19242. if (func.length < 3) {
  19243. console.error('THREE.ParametricGeometry: Function must now modify a Vector3 as third parameter.');
  19244. } // generate vertices, normals and uvs
  19245. const sliceCount = slices + 1;
  19246. for (let i = 0; i <= stacks; i++) {
  19247. const v = i / stacks;
  19248. for (let j = 0; j <= slices; j++) {
  19249. const u = j / slices; // vertex
  19250. func(u, v, p0);
  19251. vertices.push(p0.x, p0.y, p0.z); // normal
  19252. // approximate tangent vectors via finite differences
  19253. if (u - EPS >= 0) {
  19254. func(u - EPS, v, p1);
  19255. pu.subVectors(p0, p1);
  19256. } else {
  19257. func(u + EPS, v, p1);
  19258. pu.subVectors(p1, p0);
  19259. }
  19260. if (v - EPS >= 0) {
  19261. func(u, v - EPS, p1);
  19262. pv.subVectors(p0, p1);
  19263. } else {
  19264. func(u, v + EPS, p1);
  19265. pv.subVectors(p1, p0);
  19266. } // cross product of tangent vectors returns surface normal
  19267. normal.crossVectors(pu, pv).normalize();
  19268. normals.push(normal.x, normal.y, normal.z); // uv
  19269. uvs.push(u, v);
  19270. }
  19271. } // generate indices
  19272. for (let i = 0; i < stacks; i++) {
  19273. for (let j = 0; j < slices; j++) {
  19274. const a = i * sliceCount + j;
  19275. const b = i * sliceCount + j + 1;
  19276. const c = (i + 1) * sliceCount + j + 1;
  19277. const d = (i + 1) * sliceCount + j; // faces one and two
  19278. indices.push(a, b, d);
  19279. indices.push(b, c, d);
  19280. }
  19281. } // build geometry
  19282. this.setIndex(indices);
  19283. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  19284. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  19285. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  19286. }
  19287. ParametricBufferGeometry.prototype = Object.create(BufferGeometry.prototype);
  19288. ParametricBufferGeometry.prototype.constructor = ParametricBufferGeometry;
  19289. /**
  19290. * Parametric Surfaces Geometry
  19291. * based on the brilliant article by @prideout https://prideout.net/blog/old/blog/index.html@p=44.html
  19292. */
  19293. function ParametricGeometry(func, slices, stacks) {
  19294. Geometry.call(this);
  19295. this.type = 'ParametricGeometry';
  19296. this.parameters = {
  19297. func: func,
  19298. slices: slices,
  19299. stacks: stacks
  19300. };
  19301. this.fromBufferGeometry(new ParametricBufferGeometry(func, slices, stacks));
  19302. this.mergeVertices();
  19303. }
  19304. ParametricGeometry.prototype = Object.create(Geometry.prototype);
  19305. ParametricGeometry.prototype.constructor = ParametricGeometry;
  19306. class PlaneGeometry extends Geometry {
  19307. constructor(width, height, widthSegments, heightSegments) {
  19308. super();
  19309. this.type = 'PlaneGeometry';
  19310. this.parameters = {
  19311. width: width,
  19312. height: height,
  19313. widthSegments: widthSegments,
  19314. heightSegments: heightSegments
  19315. };
  19316. this.fromBufferGeometry(new PlaneBufferGeometry(width, height, widthSegments, heightSegments));
  19317. this.mergeVertices();
  19318. }
  19319. }
  19320. exports.PlaneGeometry = PlaneGeometry;
  19321. class PolyhedronGeometry extends Geometry {
  19322. constructor(vertices, indices, radius, detail) {
  19323. super();
  19324. this.type = 'PolyhedronGeometry';
  19325. this.parameters = {
  19326. vertices: vertices,
  19327. indices: indices,
  19328. radius: radius,
  19329. detail: detail
  19330. };
  19331. this.fromBufferGeometry(new PolyhedronBufferGeometry(vertices, indices, radius, detail));
  19332. this.mergeVertices();
  19333. }
  19334. }
  19335. exports.PolyhedronGeometry = PolyhedronGeometry;
  19336. class RingBufferGeometry extends BufferGeometry {
  19337. constructor(innerRadius = 0.5, outerRadius = 1, thetaSegments = 8, phiSegments = 1, thetaStart = 0, thetaLength = Math.PI * 2) {
  19338. super();
  19339. this.type = 'RingBufferGeometry';
  19340. this.parameters = {
  19341. innerRadius: innerRadius,
  19342. outerRadius: outerRadius,
  19343. thetaSegments: thetaSegments,
  19344. phiSegments: phiSegments,
  19345. thetaStart: thetaStart,
  19346. thetaLength: thetaLength
  19347. };
  19348. thetaSegments = Math.max(3, thetaSegments);
  19349. phiSegments = Math.max(1, phiSegments); // buffers
  19350. const indices = [];
  19351. const vertices = [];
  19352. const normals = [];
  19353. const uvs = []; // some helper variables
  19354. let radius = innerRadius;
  19355. const radiusStep = (outerRadius - innerRadius) / phiSegments;
  19356. const vertex = new Vector3();
  19357. const uv = new Vector2(); // generate vertices, normals and uvs
  19358. for (let j = 0; j <= phiSegments; j++) {
  19359. for (let i = 0; i <= thetaSegments; i++) {
  19360. // values are generate from the inside of the ring to the outside
  19361. const segment = thetaStart + i / thetaSegments * thetaLength; // vertex
  19362. vertex.x = radius * Math.cos(segment);
  19363. vertex.y = radius * Math.sin(segment);
  19364. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  19365. normals.push(0, 0, 1); // uv
  19366. uv.x = (vertex.x / outerRadius + 1) / 2;
  19367. uv.y = (vertex.y / outerRadius + 1) / 2;
  19368. uvs.push(uv.x, uv.y);
  19369. } // increase the radius for next row of vertices
  19370. radius += radiusStep;
  19371. } // indices
  19372. for (let j = 0; j < phiSegments; j++) {
  19373. const thetaSegmentLevel = j * (thetaSegments + 1);
  19374. for (let i = 0; i < thetaSegments; i++) {
  19375. const segment = i + thetaSegmentLevel;
  19376. const a = segment;
  19377. const b = segment + thetaSegments + 1;
  19378. const c = segment + thetaSegments + 2;
  19379. const d = segment + 1; // faces
  19380. indices.push(a, b, d);
  19381. indices.push(b, c, d);
  19382. }
  19383. } // build geometry
  19384. this.setIndex(indices);
  19385. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  19386. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  19387. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  19388. }
  19389. }
  19390. exports.RingBufferGeometry = RingBufferGeometry;
  19391. class RingGeometry extends Geometry {
  19392. constructor(innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength) {
  19393. super();
  19394. this.type = 'RingGeometry';
  19395. this.parameters = {
  19396. innerRadius: innerRadius,
  19397. outerRadius: outerRadius,
  19398. thetaSegments: thetaSegments,
  19399. phiSegments: phiSegments,
  19400. thetaStart: thetaStart,
  19401. thetaLength: thetaLength
  19402. };
  19403. this.fromBufferGeometry(new RingBufferGeometry(innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength));
  19404. this.mergeVertices();
  19405. }
  19406. }
  19407. exports.RingGeometry = RingGeometry;
  19408. class ShapeBufferGeometry extends BufferGeometry {
  19409. constructor(shapes, curveSegments = 12) {
  19410. super();
  19411. this.type = 'ShapeBufferGeometry';
  19412. this.parameters = {
  19413. shapes: shapes,
  19414. curveSegments: curveSegments
  19415. }; // buffers
  19416. const indices = [];
  19417. const vertices = [];
  19418. const normals = [];
  19419. const uvs = []; // helper variables
  19420. let groupStart = 0;
  19421. let groupCount = 0; // allow single and array values for "shapes" parameter
  19422. if (Array.isArray(shapes) === false) {
  19423. addShape(shapes);
  19424. } else {
  19425. for (let i = 0; i < shapes.length; i++) {
  19426. addShape(shapes[i]);
  19427. this.addGroup(groupStart, groupCount, i); // enables MultiMaterial support
  19428. groupStart += groupCount;
  19429. groupCount = 0;
  19430. }
  19431. } // build geometry
  19432. this.setIndex(indices);
  19433. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  19434. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  19435. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2)); // helper functions
  19436. function addShape(shape) {
  19437. const indexOffset = vertices.length / 3;
  19438. const points = shape.extractPoints(curveSegments);
  19439. let shapeVertices = points.shape;
  19440. const shapeHoles = points.holes; // check direction of vertices
  19441. if (ShapeUtils.isClockWise(shapeVertices) === false) {
  19442. shapeVertices = shapeVertices.reverse();
  19443. }
  19444. for (let i = 0, l = shapeHoles.length; i < l; i++) {
  19445. const shapeHole = shapeHoles[i];
  19446. if (ShapeUtils.isClockWise(shapeHole) === true) {
  19447. shapeHoles[i] = shapeHole.reverse();
  19448. }
  19449. }
  19450. const faces = ShapeUtils.triangulateShape(shapeVertices, shapeHoles); // join vertices of inner and outer paths to a single array
  19451. for (let i = 0, l = shapeHoles.length; i < l; i++) {
  19452. const shapeHole = shapeHoles[i];
  19453. shapeVertices = shapeVertices.concat(shapeHole);
  19454. } // vertices, normals, uvs
  19455. for (let i = 0, l = shapeVertices.length; i < l; i++) {
  19456. const vertex = shapeVertices[i];
  19457. vertices.push(vertex.x, vertex.y, 0);
  19458. normals.push(0, 0, 1);
  19459. uvs.push(vertex.x, vertex.y); // world uvs
  19460. } // incides
  19461. for (let i = 0, l = faces.length; i < l; i++) {
  19462. const face = faces[i];
  19463. const a = face[0] + indexOffset;
  19464. const b = face[1] + indexOffset;
  19465. const c = face[2] + indexOffset;
  19466. indices.push(a, b, c);
  19467. groupCount += 3;
  19468. }
  19469. }
  19470. }
  19471. toJSON() {
  19472. const data = BufferGeometry.prototype.toJSON.call(this);
  19473. const shapes = this.parameters.shapes;
  19474. return toJSON$2(shapes, data);
  19475. }
  19476. }
  19477. exports.ShapeBufferGeometry = ShapeBufferGeometry;
  19478. function toJSON$2(shapes, data) {
  19479. data.shapes = [];
  19480. if (Array.isArray(shapes)) {
  19481. for (let i = 0, l = shapes.length; i < l; i++) {
  19482. const shape = shapes[i];
  19483. data.shapes.push(shape.uuid);
  19484. }
  19485. } else {
  19486. data.shapes.push(shapes.uuid);
  19487. }
  19488. return data;
  19489. }
  19490. class ShapeGeometry extends Geometry {
  19491. constructor(shapes, curveSegments) {
  19492. super();
  19493. this.type = 'ShapeGeometry';
  19494. if (typeof curveSegments === 'object') {
  19495. console.warn('THREE.ShapeGeometry: Options parameter has been removed.');
  19496. curveSegments = curveSegments.curveSegments;
  19497. }
  19498. this.parameters = {
  19499. shapes: shapes,
  19500. curveSegments: curveSegments
  19501. };
  19502. this.fromBufferGeometry(new ShapeBufferGeometry(shapes, curveSegments));
  19503. this.mergeVertices();
  19504. }
  19505. toJSON() {
  19506. const data = Geometry.prototype.toJSON.call(this);
  19507. const shapes = this.parameters.shapes;
  19508. return toJSON$3(shapes, data);
  19509. }
  19510. }
  19511. exports.ShapeGeometry = ShapeGeometry;
  19512. function toJSON$3(shapes, data) {
  19513. data.shapes = [];
  19514. if (Array.isArray(shapes)) {
  19515. for (let i = 0, l = shapes.length; i < l; i++) {
  19516. const shape = shapes[i];
  19517. data.shapes.push(shape.uuid);
  19518. }
  19519. } else {
  19520. data.shapes.push(shapes.uuid);
  19521. }
  19522. return data;
  19523. }
  19524. class SphereBufferGeometry extends BufferGeometry {
  19525. constructor(radius = 1, widthSegments = 8, heightSegments = 6, phiStart = 0, phiLength = Math.PI * 2, thetaStart = 0, thetaLength = Math.PI) {
  19526. super();
  19527. this.type = 'SphereBufferGeometry';
  19528. this.parameters = {
  19529. radius: radius,
  19530. widthSegments: widthSegments,
  19531. heightSegments: heightSegments,
  19532. phiStart: phiStart,
  19533. phiLength: phiLength,
  19534. thetaStart: thetaStart,
  19535. thetaLength: thetaLength
  19536. };
  19537. widthSegments = Math.max(3, Math.floor(widthSegments));
  19538. heightSegments = Math.max(2, Math.floor(heightSegments));
  19539. const thetaEnd = Math.min(thetaStart + thetaLength, Math.PI);
  19540. let index = 0;
  19541. const grid = [];
  19542. const vertex = new Vector3();
  19543. const normal = new Vector3(); // buffers
  19544. const indices = [];
  19545. const vertices = [];
  19546. const normals = [];
  19547. const uvs = []; // generate vertices, normals and uvs
  19548. for (let iy = 0; iy <= heightSegments; iy++) {
  19549. const verticesRow = [];
  19550. const v = iy / heightSegments; // special case for the poles
  19551. let uOffset = 0;
  19552. if (iy == 0 && thetaStart == 0) {
  19553. uOffset = 0.5 / widthSegments;
  19554. } else if (iy == heightSegments && thetaEnd == Math.PI) {
  19555. uOffset = -0.5 / widthSegments;
  19556. }
  19557. for (let ix = 0; ix <= widthSegments; ix++) {
  19558. const u = ix / widthSegments; // vertex
  19559. vertex.x = -radius * Math.cos(phiStart + u * phiLength) * Math.sin(thetaStart + v * thetaLength);
  19560. vertex.y = radius * Math.cos(thetaStart + v * thetaLength);
  19561. vertex.z = radius * Math.sin(phiStart + u * phiLength) * Math.sin(thetaStart + v * thetaLength);
  19562. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  19563. normal.copy(vertex).normalize();
  19564. normals.push(normal.x, normal.y, normal.z); // uv
  19565. uvs.push(u + uOffset, 1 - v);
  19566. verticesRow.push(index++);
  19567. }
  19568. grid.push(verticesRow);
  19569. } // indices
  19570. for (let iy = 0; iy < heightSegments; iy++) {
  19571. for (let ix = 0; ix < widthSegments; ix++) {
  19572. const a = grid[iy][ix + 1];
  19573. const b = grid[iy][ix];
  19574. const c = grid[iy + 1][ix];
  19575. const d = grid[iy + 1][ix + 1];
  19576. if (iy !== 0 || thetaStart > 0) indices.push(a, b, d);
  19577. if (iy !== heightSegments - 1 || thetaEnd < Math.PI) indices.push(b, c, d);
  19578. }
  19579. } // build geometry
  19580. this.setIndex(indices);
  19581. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  19582. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  19583. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  19584. }
  19585. }
  19586. exports.SphereBufferGeometry = SphereBufferGeometry;
  19587. class SphereGeometry extends Geometry {
  19588. constructor(radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength) {
  19589. super();
  19590. this.type = 'SphereGeometry';
  19591. this.parameters = {
  19592. radius: radius,
  19593. widthSegments: widthSegments,
  19594. heightSegments: heightSegments,
  19595. phiStart: phiStart,
  19596. phiLength: phiLength,
  19597. thetaStart: thetaStart,
  19598. thetaLength: thetaLength
  19599. };
  19600. this.fromBufferGeometry(new SphereBufferGeometry(radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength));
  19601. this.mergeVertices();
  19602. }
  19603. }
  19604. exports.SphereGeometry = SphereGeometry;
  19605. class TetrahedronBufferGeometry extends PolyhedronBufferGeometry {
  19606. constructor(radius = 1, detail = 0) {
  19607. const vertices = [1, 1, 1, -1, -1, 1, -1, 1, -1, 1, -1, -1];
  19608. const indices = [2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1];
  19609. super(vertices, indices, radius, detail);
  19610. this.type = 'TetrahedronBufferGeometry';
  19611. this.parameters = {
  19612. radius: radius,
  19613. detail: detail
  19614. };
  19615. }
  19616. }
  19617. exports.TetrahedronBufferGeometry = TetrahedronBufferGeometry;
  19618. class TetrahedronGeometry extends Geometry {
  19619. constructor(radius, detail) {
  19620. super();
  19621. this.type = 'TetrahedronGeometry';
  19622. this.parameters = {
  19623. radius: radius,
  19624. detail: detail
  19625. };
  19626. this.fromBufferGeometry(new TetrahedronBufferGeometry(radius, detail));
  19627. this.mergeVertices();
  19628. }
  19629. }
  19630. /**
  19631. * Text = 3D Text
  19632. *
  19633. * parameters = {
  19634. * font: <THREE.Font>, // font
  19635. *
  19636. * size: <float>, // size of the text
  19637. * height: <float>, // thickness to extrude text
  19638. * curveSegments: <int>, // number of points on the curves
  19639. *
  19640. * bevelEnabled: <bool>, // turn on bevel
  19641. * bevelThickness: <float>, // how deep into text bevel goes
  19642. * bevelSize: <float>, // how far from text outline (including bevelOffset) is bevel
  19643. * bevelOffset: <float> // how far from text outline does bevel start
  19644. * }
  19645. */
  19646. exports.TetrahedronGeometry = TetrahedronGeometry;
  19647. class TextBufferGeometry extends ExtrudeBufferGeometry {
  19648. constructor(text, parameters = {}) {
  19649. const font = parameters.font;
  19650. if (!(font && font.isFont)) {
  19651. console.error('THREE.TextGeometry: font parameter is not an instance of THREE.Font.');
  19652. return new BufferGeometry();
  19653. }
  19654. const shapes = font.generateShapes(text, parameters.size); // translate parameters to ExtrudeGeometry API
  19655. parameters.depth = parameters.height !== undefined ? parameters.height : 50; // defaults
  19656. if (parameters.bevelThickness === undefined) parameters.bevelThickness = 10;
  19657. if (parameters.bevelSize === undefined) parameters.bevelSize = 8;
  19658. if (parameters.bevelEnabled === undefined) parameters.bevelEnabled = false;
  19659. super(shapes, parameters);
  19660. this.type = 'TextBufferGeometry';
  19661. }
  19662. }
  19663. /**
  19664. * Text = 3D Text
  19665. *
  19666. * parameters = {
  19667. * font: <THREE.Font>, // font
  19668. *
  19669. * size: <float>, // size of the text
  19670. * height: <float>, // thickness to extrude text
  19671. * curveSegments: <int>, // number of points on the curves
  19672. *
  19673. * bevelEnabled: <bool>, // turn on bevel
  19674. * bevelThickness: <float>, // how deep into text bevel goes
  19675. * bevelSize: <float>, // how far from text outline (including bevelOffset) is bevel
  19676. * bevelOffset: <float> // how far from text outline does bevel start
  19677. * }
  19678. */
  19679. exports.TextBufferGeometry = TextBufferGeometry;
  19680. class TextGeometry extends Geometry {
  19681. constructor(text, parameters) {
  19682. super();
  19683. this.type = 'TextGeometry';
  19684. this.parameters = {
  19685. text: text,
  19686. parameters: parameters
  19687. };
  19688. this.fromBufferGeometry(new TextBufferGeometry(text, parameters));
  19689. this.mergeVertices();
  19690. }
  19691. }
  19692. exports.TextGeometry = TextGeometry;
  19693. class TorusBufferGeometry extends BufferGeometry {
  19694. constructor(radius = 1, tube = 0.4, radialSegments = 8, tubularSegments = 6, arc = Math.PI * 2) {
  19695. super();
  19696. this.type = 'TorusBufferGeometry';
  19697. this.parameters = {
  19698. radius: radius,
  19699. tube: tube,
  19700. radialSegments: radialSegments,
  19701. tubularSegments: tubularSegments,
  19702. arc: arc
  19703. };
  19704. radialSegments = Math.floor(radialSegments);
  19705. tubularSegments = Math.floor(tubularSegments); // buffers
  19706. const indices = [];
  19707. const vertices = [];
  19708. const normals = [];
  19709. const uvs = []; // helper variables
  19710. const center = new Vector3();
  19711. const vertex = new Vector3();
  19712. const normal = new Vector3(); // generate vertices, normals and uvs
  19713. for (let j = 0; j <= radialSegments; j++) {
  19714. for (let i = 0; i <= tubularSegments; i++) {
  19715. const u = i / tubularSegments * arc;
  19716. const v = j / radialSegments * Math.PI * 2; // vertex
  19717. vertex.x = (radius + tube * Math.cos(v)) * Math.cos(u);
  19718. vertex.y = (radius + tube * Math.cos(v)) * Math.sin(u);
  19719. vertex.z = tube * Math.sin(v);
  19720. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  19721. center.x = radius * Math.cos(u);
  19722. center.y = radius * Math.sin(u);
  19723. normal.subVectors(vertex, center).normalize();
  19724. normals.push(normal.x, normal.y, normal.z); // uv
  19725. uvs.push(i / tubularSegments);
  19726. uvs.push(j / radialSegments);
  19727. }
  19728. } // generate indices
  19729. for (let j = 1; j <= radialSegments; j++) {
  19730. for (let i = 1; i <= tubularSegments; i++) {
  19731. // indices
  19732. const a = (tubularSegments + 1) * j + i - 1;
  19733. const b = (tubularSegments + 1) * (j - 1) + i - 1;
  19734. const c = (tubularSegments + 1) * (j - 1) + i;
  19735. const d = (tubularSegments + 1) * j + i; // faces
  19736. indices.push(a, b, d);
  19737. indices.push(b, c, d);
  19738. }
  19739. } // build geometry
  19740. this.setIndex(indices);
  19741. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  19742. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  19743. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  19744. }
  19745. }
  19746. exports.TorusBufferGeometry = TorusBufferGeometry;
  19747. class TorusGeometry extends Geometry {
  19748. constructor(radius, tube, radialSegments, tubularSegments, arc) {
  19749. super();
  19750. this.type = 'TorusGeometry';
  19751. this.parameters = {
  19752. radius: radius,
  19753. tube: tube,
  19754. radialSegments: radialSegments,
  19755. tubularSegments: tubularSegments,
  19756. arc: arc
  19757. };
  19758. this.fromBufferGeometry(new TorusBufferGeometry(radius, tube, radialSegments, tubularSegments, arc));
  19759. this.mergeVertices();
  19760. }
  19761. }
  19762. exports.TorusGeometry = TorusGeometry;
  19763. class TorusKnotBufferGeometry extends BufferGeometry {
  19764. constructor(radius = 1, tube = 0.4, tubularSegments = 64, radialSegments = 8, p = 2, q = 3) {
  19765. super();
  19766. this.type = 'TorusKnotBufferGeometry';
  19767. this.parameters = {
  19768. radius: radius,
  19769. tube: tube,
  19770. tubularSegments: tubularSegments,
  19771. radialSegments: radialSegments,
  19772. p: p,
  19773. q: q
  19774. };
  19775. tubularSegments = Math.floor(tubularSegments);
  19776. radialSegments = Math.floor(radialSegments); // buffers
  19777. const indices = [];
  19778. const vertices = [];
  19779. const normals = [];
  19780. const uvs = []; // helper variables
  19781. const vertex = new Vector3();
  19782. const normal = new Vector3();
  19783. const P1 = new Vector3();
  19784. const P2 = new Vector3();
  19785. const B = new Vector3();
  19786. const T = new Vector3();
  19787. const N = new Vector3(); // generate vertices, normals and uvs
  19788. for (let i = 0; i <= tubularSegments; ++i) {
  19789. // the radian "u" is used to calculate the position on the torus curve of the current tubular segement
  19790. const u = i / tubularSegments * p * Math.PI * 2; // now we calculate two points. P1 is our current position on the curve, P2 is a little farther ahead.
  19791. // these points are used to create a special "coordinate space", which is necessary to calculate the correct vertex positions
  19792. calculatePositionOnCurve(u, p, q, radius, P1);
  19793. calculatePositionOnCurve(u + 0.01, p, q, radius, P2); // calculate orthonormal basis
  19794. T.subVectors(P2, P1);
  19795. N.addVectors(P2, P1);
  19796. B.crossVectors(T, N);
  19797. N.crossVectors(B, T); // normalize B, N. T can be ignored, we don't use it
  19798. B.normalize();
  19799. N.normalize();
  19800. for (let j = 0; j <= radialSegments; ++j) {
  19801. // now calculate the vertices. they are nothing more than an extrusion of the torus curve.
  19802. // because we extrude a shape in the xy-plane, there is no need to calculate a z-value.
  19803. const v = j / radialSegments * Math.PI * 2;
  19804. const cx = -tube * Math.cos(v);
  19805. const cy = tube * Math.sin(v); // now calculate the final vertex position.
  19806. // first we orient the extrusion with our basis vectos, then we add it to the current position on the curve
  19807. vertex.x = P1.x + (cx * N.x + cy * B.x);
  19808. vertex.y = P1.y + (cx * N.y + cy * B.y);
  19809. vertex.z = P1.z + (cx * N.z + cy * B.z);
  19810. vertices.push(vertex.x, vertex.y, vertex.z); // normal (P1 is always the center/origin of the extrusion, thus we can use it to calculate the normal)
  19811. normal.subVectors(vertex, P1).normalize();
  19812. normals.push(normal.x, normal.y, normal.z); // uv
  19813. uvs.push(i / tubularSegments);
  19814. uvs.push(j / radialSegments);
  19815. }
  19816. } // generate indices
  19817. for (let j = 1; j <= tubularSegments; j++) {
  19818. for (let i = 1; i <= radialSegments; i++) {
  19819. // indices
  19820. const a = (radialSegments + 1) * (j - 1) + (i - 1);
  19821. const b = (radialSegments + 1) * j + (i - 1);
  19822. const c = (radialSegments + 1) * j + i;
  19823. const d = (radialSegments + 1) * (j - 1) + i; // faces
  19824. indices.push(a, b, d);
  19825. indices.push(b, c, d);
  19826. }
  19827. } // build geometry
  19828. this.setIndex(indices);
  19829. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  19830. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  19831. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2)); // this function calculates the current position on the torus curve
  19832. function calculatePositionOnCurve(u, p, q, radius, position) {
  19833. const cu = Math.cos(u);
  19834. const su = Math.sin(u);
  19835. const quOverP = q / p * u;
  19836. const cs = Math.cos(quOverP);
  19837. position.x = radius * (2 + cs) * 0.5 * cu;
  19838. position.y = radius * (2 + cs) * su * 0.5;
  19839. position.z = radius * Math.sin(quOverP) * 0.5;
  19840. }
  19841. }
  19842. }
  19843. exports.TorusKnotBufferGeometry = TorusKnotBufferGeometry;
  19844. class TorusKnotGeometry extends Geometry {
  19845. constructor(radius, tube, tubularSegments, radialSegments, p, q, heightScale) {
  19846. super();
  19847. this.type = 'TorusKnotGeometry';
  19848. this.parameters = {
  19849. radius: radius,
  19850. tube: tube,
  19851. tubularSegments: tubularSegments,
  19852. radialSegments: radialSegments,
  19853. p: p,
  19854. q: q
  19855. };
  19856. if (heightScale !== undefined) console.warn('THREE.TorusKnotGeometry: heightScale has been deprecated. Use .scale( x, y, z ) instead.');
  19857. this.fromBufferGeometry(new TorusKnotBufferGeometry(radius, tube, tubularSegments, radialSegments, p, q));
  19858. this.mergeVertices();
  19859. }
  19860. }
  19861. exports.TorusKnotGeometry = TorusKnotGeometry;
  19862. class TubeBufferGeometry extends BufferGeometry {
  19863. constructor(path, tubularSegments = 64, radius = 1, radialSegments = 8, closed = false) {
  19864. super();
  19865. this.type = 'TubeBufferGeometry';
  19866. this.parameters = {
  19867. path: path,
  19868. tubularSegments: tubularSegments,
  19869. radius: radius,
  19870. radialSegments: radialSegments,
  19871. closed: closed
  19872. };
  19873. const frames = path.computeFrenetFrames(tubularSegments, closed); // expose internals
  19874. this.tangents = frames.tangents;
  19875. this.normals = frames.normals;
  19876. this.binormals = frames.binormals; // helper variables
  19877. const vertex = new Vector3();
  19878. const normal = new Vector3();
  19879. const uv = new Vector2();
  19880. let P = new Vector3(); // buffer
  19881. const vertices = [];
  19882. const normals = [];
  19883. const uvs = [];
  19884. const indices = []; // create buffer data
  19885. generateBufferData(); // build geometry
  19886. this.setIndex(indices);
  19887. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  19888. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  19889. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2)); // functions
  19890. function generateBufferData() {
  19891. for (let i = 0; i < tubularSegments; i++) {
  19892. generateSegment(i);
  19893. } // if the geometry is not closed, generate the last row of vertices and normals
  19894. // at the regular position on the given path
  19895. //
  19896. // if the geometry is closed, duplicate the first row of vertices and normals (uvs will differ)
  19897. generateSegment(closed === false ? tubularSegments : 0); // uvs are generated in a separate function.
  19898. // this makes it easy compute correct values for closed geometries
  19899. generateUVs(); // finally create faces
  19900. generateIndices();
  19901. }
  19902. function generateSegment(i) {
  19903. // we use getPointAt to sample evenly distributed points from the given path
  19904. P = path.getPointAt(i / tubularSegments, P); // retrieve corresponding normal and binormal
  19905. const N = frames.normals[i];
  19906. const B = frames.binormals[i]; // generate normals and vertices for the current segment
  19907. for (let j = 0; j <= radialSegments; j++) {
  19908. const v = j / radialSegments * Math.PI * 2;
  19909. const sin = Math.sin(v);
  19910. const cos = -Math.cos(v); // normal
  19911. normal.x = cos * N.x + sin * B.x;
  19912. normal.y = cos * N.y + sin * B.y;
  19913. normal.z = cos * N.z + sin * B.z;
  19914. normal.normalize();
  19915. normals.push(normal.x, normal.y, normal.z); // vertex
  19916. vertex.x = P.x + radius * normal.x;
  19917. vertex.y = P.y + radius * normal.y;
  19918. vertex.z = P.z + radius * normal.z;
  19919. vertices.push(vertex.x, vertex.y, vertex.z);
  19920. }
  19921. }
  19922. function generateIndices() {
  19923. for (let j = 1; j <= tubularSegments; j++) {
  19924. for (let i = 1; i <= radialSegments; i++) {
  19925. const a = (radialSegments + 1) * (j - 1) + (i - 1);
  19926. const b = (radialSegments + 1) * j + (i - 1);
  19927. const c = (radialSegments + 1) * j + i;
  19928. const d = (radialSegments + 1) * (j - 1) + i; // faces
  19929. indices.push(a, b, d);
  19930. indices.push(b, c, d);
  19931. }
  19932. }
  19933. }
  19934. function generateUVs() {
  19935. for (let i = 0; i <= tubularSegments; i++) {
  19936. for (let j = 0; j <= radialSegments; j++) {
  19937. uv.x = i / tubularSegments;
  19938. uv.y = j / radialSegments;
  19939. uvs.push(uv.x, uv.y);
  19940. }
  19941. }
  19942. }
  19943. }
  19944. toJSON() {
  19945. const data = BufferGeometry.prototype.toJSON.call(this);
  19946. data.path = this.parameters.path.toJSON();
  19947. return data;
  19948. }
  19949. }
  19950. exports.TubeBufferGeometry = TubeBufferGeometry;
  19951. class TubeGeometry extends Geometry {
  19952. constructor(path, tubularSegments, radius, radialSegments, closed, taper) {
  19953. super();
  19954. this.type = 'TubeGeometry';
  19955. this.parameters = {
  19956. path: path,
  19957. tubularSegments: tubularSegments,
  19958. radius: radius,
  19959. radialSegments: radialSegments,
  19960. closed: closed
  19961. };
  19962. if (taper !== undefined) console.warn('THREE.TubeGeometry: taper has been removed.');
  19963. const bufferGeometry = new TubeBufferGeometry(path, tubularSegments, radius, radialSegments, closed); // expose internals
  19964. this.tangents = bufferGeometry.tangents;
  19965. this.normals = bufferGeometry.normals;
  19966. this.binormals = bufferGeometry.binormals; // create geometry
  19967. this.fromBufferGeometry(bufferGeometry);
  19968. this.mergeVertices();
  19969. }
  19970. }
  19971. exports.TubeGeometry = TubeGeometry;
  19972. class WireframeGeometry extends BufferGeometry {
  19973. constructor(geometry) {
  19974. super();
  19975. this.type = 'WireframeGeometry'; // buffer
  19976. const vertices = []; // helper variables
  19977. const edge = [0, 0],
  19978. edges = {};
  19979. const keys = ['a', 'b', 'c']; // different logic for Geometry and BufferGeometry
  19980. if (geometry && geometry.isGeometry) {
  19981. // create a data structure that contains all edges without duplicates
  19982. const faces = geometry.faces;
  19983. for (let i = 0, l = faces.length; i < l; i++) {
  19984. const face = faces[i];
  19985. for (let j = 0; j < 3; j++) {
  19986. const edge1 = face[keys[j]];
  19987. const edge2 = face[keys[(j + 1) % 3]];
  19988. edge[0] = Math.min(edge1, edge2); // sorting prevents duplicates
  19989. edge[1] = Math.max(edge1, edge2);
  19990. const key = edge[0] + ',' + edge[1];
  19991. if (edges[key] === undefined) {
  19992. edges[key] = {
  19993. index1: edge[0],
  19994. index2: edge[1]
  19995. };
  19996. }
  19997. }
  19998. } // generate vertices
  19999. for (const key in edges) {
  20000. const e = edges[key];
  20001. let vertex = geometry.vertices[e.index1];
  20002. vertices.push(vertex.x, vertex.y, vertex.z);
  20003. vertex = geometry.vertices[e.index2];
  20004. vertices.push(vertex.x, vertex.y, vertex.z);
  20005. }
  20006. } else if (geometry && geometry.isBufferGeometry) {
  20007. const vertex = new Vector3();
  20008. if (geometry.index !== null) {
  20009. // indexed BufferGeometry
  20010. const position = geometry.attributes.position;
  20011. const indices = geometry.index;
  20012. let groups = geometry.groups;
  20013. if (groups.length === 0) {
  20014. groups = [{
  20015. start: 0,
  20016. count: indices.count,
  20017. materialIndex: 0
  20018. }];
  20019. } // create a data structure that contains all eges without duplicates
  20020. for (let o = 0, ol = groups.length; o < ol; ++o) {
  20021. const group = groups[o];
  20022. const start = group.start;
  20023. const count = group.count;
  20024. for (let i = start, l = start + count; i < l; i += 3) {
  20025. for (let j = 0; j < 3; j++) {
  20026. const edge1 = indices.getX(i + j);
  20027. const edge2 = indices.getX(i + (j + 1) % 3);
  20028. edge[0] = Math.min(edge1, edge2); // sorting prevents duplicates
  20029. edge[1] = Math.max(edge1, edge2);
  20030. const key = edge[0] + ',' + edge[1];
  20031. if (edges[key] === undefined) {
  20032. edges[key] = {
  20033. index1: edge[0],
  20034. index2: edge[1]
  20035. };
  20036. }
  20037. }
  20038. }
  20039. } // generate vertices
  20040. for (const key in edges) {
  20041. const e = edges[key];
  20042. vertex.fromBufferAttribute(position, e.index1);
  20043. vertices.push(vertex.x, vertex.y, vertex.z);
  20044. vertex.fromBufferAttribute(position, e.index2);
  20045. vertices.push(vertex.x, vertex.y, vertex.z);
  20046. }
  20047. } else {
  20048. // non-indexed BufferGeometry
  20049. const position = geometry.attributes.position;
  20050. for (let i = 0, l = position.count / 3; i < l; i++) {
  20051. for (let j = 0; j < 3; j++) {
  20052. // three edges per triangle, an edge is represented as (index1, index2)
  20053. // e.g. the first triangle has the following edges: (0,1),(1,2),(2,0)
  20054. const index1 = 3 * i + j;
  20055. vertex.fromBufferAttribute(position, index1);
  20056. vertices.push(vertex.x, vertex.y, vertex.z);
  20057. const index2 = 3 * i + (j + 1) % 3;
  20058. vertex.fromBufferAttribute(position, index2);
  20059. vertices.push(vertex.x, vertex.y, vertex.z);
  20060. }
  20061. }
  20062. }
  20063. } // build geometry
  20064. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  20065. }
  20066. }
  20067. exports.WireframeGeometry = WireframeGeometry;
  20068. var Geometries =
  20069. /*#__PURE__*/
  20070. Object.freeze({
  20071. __proto__: null,
  20072. BoxGeometry: BoxGeometry,
  20073. BoxBufferGeometry: BoxBufferGeometry,
  20074. CircleGeometry: CircleGeometry,
  20075. CircleBufferGeometry: CircleBufferGeometry,
  20076. ConeGeometry: ConeGeometry,
  20077. ConeBufferGeometry: ConeBufferGeometry,
  20078. CylinderGeometry: CylinderGeometry,
  20079. CylinderBufferGeometry: CylinderBufferGeometry,
  20080. DodecahedronGeometry: DodecahedronGeometry,
  20081. DodecahedronBufferGeometry: DodecahedronBufferGeometry,
  20082. EdgesGeometry: EdgesGeometry,
  20083. ExtrudeGeometry: ExtrudeGeometry,
  20084. ExtrudeBufferGeometry: ExtrudeBufferGeometry,
  20085. IcosahedronGeometry: IcosahedronGeometry,
  20086. IcosahedronBufferGeometry: IcosahedronBufferGeometry,
  20087. LatheGeometry: LatheGeometry,
  20088. LatheBufferGeometry: LatheBufferGeometry,
  20089. OctahedronGeometry: OctahedronGeometry,
  20090. OctahedronBufferGeometry: OctahedronBufferGeometry,
  20091. ParametricGeometry: ParametricGeometry,
  20092. ParametricBufferGeometry: ParametricBufferGeometry,
  20093. PlaneGeometry: PlaneGeometry,
  20094. PlaneBufferGeometry: PlaneBufferGeometry,
  20095. PolyhedronGeometry: PolyhedronGeometry,
  20096. PolyhedronBufferGeometry: PolyhedronBufferGeometry,
  20097. RingGeometry: RingGeometry,
  20098. RingBufferGeometry: RingBufferGeometry,
  20099. ShapeGeometry: ShapeGeometry,
  20100. ShapeBufferGeometry: ShapeBufferGeometry,
  20101. SphereGeometry: SphereGeometry,
  20102. SphereBufferGeometry: SphereBufferGeometry,
  20103. TetrahedronGeometry: TetrahedronGeometry,
  20104. TetrahedronBufferGeometry: TetrahedronBufferGeometry,
  20105. TextGeometry: TextGeometry,
  20106. TextBufferGeometry: TextBufferGeometry,
  20107. TorusGeometry: TorusGeometry,
  20108. TorusBufferGeometry: TorusBufferGeometry,
  20109. TorusKnotGeometry: TorusKnotGeometry,
  20110. TorusKnotBufferGeometry: TorusKnotBufferGeometry,
  20111. TubeGeometry: TubeGeometry,
  20112. TubeBufferGeometry: TubeBufferGeometry,
  20113. WireframeGeometry: WireframeGeometry
  20114. });
  20115. /**
  20116. * parameters = {
  20117. * color: <THREE.Color>
  20118. * }
  20119. */
  20120. function ShadowMaterial(parameters) {
  20121. Material.call(this);
  20122. this.type = 'ShadowMaterial';
  20123. this.color = new Color(0x000000);
  20124. this.transparent = true;
  20125. this.setValues(parameters);
  20126. }
  20127. ShadowMaterial.prototype = Object.create(Material.prototype);
  20128. ShadowMaterial.prototype.constructor = ShadowMaterial;
  20129. ShadowMaterial.prototype.isShadowMaterial = true;
  20130. ShadowMaterial.prototype.copy = function (source) {
  20131. Material.prototype.copy.call(this, source);
  20132. this.color.copy(source.color);
  20133. return this;
  20134. };
  20135. function RawShaderMaterial(parameters) {
  20136. ShaderMaterial.call(this, parameters);
  20137. this.type = 'RawShaderMaterial';
  20138. }
  20139. RawShaderMaterial.prototype = Object.create(ShaderMaterial.prototype);
  20140. RawShaderMaterial.prototype.constructor = RawShaderMaterial;
  20141. RawShaderMaterial.prototype.isRawShaderMaterial = true;
  20142. /**
  20143. * parameters = {
  20144. * color: <hex>,
  20145. * roughness: <float>,
  20146. * metalness: <float>,
  20147. * opacity: <float>,
  20148. *
  20149. * map: new THREE.Texture( <Image> ),
  20150. *
  20151. * lightMap: new THREE.Texture( <Image> ),
  20152. * lightMapIntensity: <float>
  20153. *
  20154. * aoMap: new THREE.Texture( <Image> ),
  20155. * aoMapIntensity: <float>
  20156. *
  20157. * emissive: <hex>,
  20158. * emissiveIntensity: <float>
  20159. * emissiveMap: new THREE.Texture( <Image> ),
  20160. *
  20161. * bumpMap: new THREE.Texture( <Image> ),
  20162. * bumpScale: <float>,
  20163. *
  20164. * normalMap: new THREE.Texture( <Image> ),
  20165. * normalMapType: THREE.TangentSpaceNormalMap,
  20166. * normalScale: <Vector2>,
  20167. *
  20168. * displacementMap: new THREE.Texture( <Image> ),
  20169. * displacementScale: <float>,
  20170. * displacementBias: <float>,
  20171. *
  20172. * roughnessMap: new THREE.Texture( <Image> ),
  20173. *
  20174. * metalnessMap: new THREE.Texture( <Image> ),
  20175. *
  20176. * alphaMap: new THREE.Texture( <Image> ),
  20177. *
  20178. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  20179. * envMapIntensity: <float>
  20180. *
  20181. * refractionRatio: <float>,
  20182. *
  20183. * wireframe: <boolean>,
  20184. * wireframeLinewidth: <float>,
  20185. *
  20186. * skinning: <bool>,
  20187. * morphTargets: <bool>,
  20188. * morphNormals: <bool>
  20189. * }
  20190. */
  20191. function MeshStandardMaterial(parameters) {
  20192. Material.call(this);
  20193. this.defines = {
  20194. 'STANDARD': ''
  20195. };
  20196. this.type = 'MeshStandardMaterial';
  20197. this.color = new Color(0xffffff); // diffuse
  20198. this.roughness = 1.0;
  20199. this.metalness = 0.0;
  20200. this.map = null;
  20201. this.lightMap = null;
  20202. this.lightMapIntensity = 1.0;
  20203. this.aoMap = null;
  20204. this.aoMapIntensity = 1.0;
  20205. this.emissive = new Color(0x000000);
  20206. this.emissiveIntensity = 1.0;
  20207. this.emissiveMap = null;
  20208. this.bumpMap = null;
  20209. this.bumpScale = 1;
  20210. this.normalMap = null;
  20211. this.normalMapType = TangentSpaceNormalMap;
  20212. this.normalScale = new Vector2(1, 1);
  20213. this.displacementMap = null;
  20214. this.displacementScale = 1;
  20215. this.displacementBias = 0;
  20216. this.roughnessMap = null;
  20217. this.metalnessMap = null;
  20218. this.alphaMap = null;
  20219. this.envMap = null;
  20220. this.envMapIntensity = 1.0;
  20221. this.refractionRatio = 0.98;
  20222. this.wireframe = false;
  20223. this.wireframeLinewidth = 1;
  20224. this.wireframeLinecap = 'round';
  20225. this.wireframeLinejoin = 'round';
  20226. this.skinning = false;
  20227. this.morphTargets = false;
  20228. this.morphNormals = false;
  20229. this.vertexTangents = false;
  20230. this.setValues(parameters);
  20231. }
  20232. MeshStandardMaterial.prototype = Object.create(Material.prototype);
  20233. MeshStandardMaterial.prototype.constructor = MeshStandardMaterial;
  20234. MeshStandardMaterial.prototype.isMeshStandardMaterial = true;
  20235. MeshStandardMaterial.prototype.copy = function (source) {
  20236. Material.prototype.copy.call(this, source);
  20237. this.defines = {
  20238. 'STANDARD': ''
  20239. };
  20240. this.color.copy(source.color);
  20241. this.roughness = source.roughness;
  20242. this.metalness = source.metalness;
  20243. this.map = source.map;
  20244. this.lightMap = source.lightMap;
  20245. this.lightMapIntensity = source.lightMapIntensity;
  20246. this.aoMap = source.aoMap;
  20247. this.aoMapIntensity = source.aoMapIntensity;
  20248. this.emissive.copy(source.emissive);
  20249. this.emissiveMap = source.emissiveMap;
  20250. this.emissiveIntensity = source.emissiveIntensity;
  20251. this.bumpMap = source.bumpMap;
  20252. this.bumpScale = source.bumpScale;
  20253. this.normalMap = source.normalMap;
  20254. this.normalMapType = source.normalMapType;
  20255. this.normalScale.copy(source.normalScale);
  20256. this.displacementMap = source.displacementMap;
  20257. this.displacementScale = source.displacementScale;
  20258. this.displacementBias = source.displacementBias;
  20259. this.roughnessMap = source.roughnessMap;
  20260. this.metalnessMap = source.metalnessMap;
  20261. this.alphaMap = source.alphaMap;
  20262. this.envMap = source.envMap;
  20263. this.envMapIntensity = source.envMapIntensity;
  20264. this.refractionRatio = source.refractionRatio;
  20265. this.wireframe = source.wireframe;
  20266. this.wireframeLinewidth = source.wireframeLinewidth;
  20267. this.wireframeLinecap = source.wireframeLinecap;
  20268. this.wireframeLinejoin = source.wireframeLinejoin;
  20269. this.skinning = source.skinning;
  20270. this.morphTargets = source.morphTargets;
  20271. this.morphNormals = source.morphNormals;
  20272. this.vertexTangents = source.vertexTangents;
  20273. return this;
  20274. };
  20275. /**
  20276. * parameters = {
  20277. * clearcoat: <float>,
  20278. * clearcoatMap: new THREE.Texture( <Image> ),
  20279. * clearcoatRoughness: <float>,
  20280. * clearcoatRoughnessMap: new THREE.Texture( <Image> ),
  20281. * clearcoatNormalScale: <Vector2>,
  20282. * clearcoatNormalMap: new THREE.Texture( <Image> ),
  20283. *
  20284. * reflectivity: <float>,
  20285. * ior: <float>,
  20286. *
  20287. * sheen: <Color>,
  20288. *
  20289. * transmission: <float>,
  20290. * transmissionMap: new THREE.Texture( <Image> )
  20291. * }
  20292. */
  20293. function MeshPhysicalMaterial(parameters) {
  20294. MeshStandardMaterial.call(this);
  20295. this.defines = {
  20296. 'STANDARD': '',
  20297. 'PHYSICAL': ''
  20298. };
  20299. this.type = 'MeshPhysicalMaterial';
  20300. this.clearcoat = 0.0;
  20301. this.clearcoatMap = null;
  20302. this.clearcoatRoughness = 0.0;
  20303. this.clearcoatRoughnessMap = null;
  20304. this.clearcoatNormalScale = new Vector2(1, 1);
  20305. this.clearcoatNormalMap = null;
  20306. this.reflectivity = 0.5; // maps to F0 = 0.04
  20307. Object.defineProperty(this, 'ior', {
  20308. get: function () {
  20309. return (1 + 0.4 * this.reflectivity) / (1 - 0.4 * this.reflectivity);
  20310. },
  20311. set: function (ior) {
  20312. this.reflectivity = MathUtils.clamp(2.5 * (ior - 1) / (ior + 1), 0, 1);
  20313. }
  20314. });
  20315. this.sheen = null; // null will disable sheen bsdf
  20316. this.transmission = 0.0;
  20317. this.transmissionMap = null;
  20318. this.setValues(parameters);
  20319. }
  20320. MeshPhysicalMaterial.prototype = Object.create(MeshStandardMaterial.prototype);
  20321. MeshPhysicalMaterial.prototype.constructor = MeshPhysicalMaterial;
  20322. MeshPhysicalMaterial.prototype.isMeshPhysicalMaterial = true;
  20323. MeshPhysicalMaterial.prototype.copy = function (source) {
  20324. MeshStandardMaterial.prototype.copy.call(this, source);
  20325. this.defines = {
  20326. 'STANDARD': '',
  20327. 'PHYSICAL': ''
  20328. };
  20329. this.clearcoat = source.clearcoat;
  20330. this.clearcoatMap = source.clearcoatMap;
  20331. this.clearcoatRoughness = source.clearcoatRoughness;
  20332. this.clearcoatRoughnessMap = source.clearcoatRoughnessMap;
  20333. this.clearcoatNormalMap = source.clearcoatNormalMap;
  20334. this.clearcoatNormalScale.copy(source.clearcoatNormalScale);
  20335. this.reflectivity = source.reflectivity;
  20336. if (source.sheen) {
  20337. this.sheen = (this.sheen || new Color()).copy(source.sheen);
  20338. } else {
  20339. this.sheen = null;
  20340. }
  20341. this.transmission = source.transmission;
  20342. this.transmissionMap = source.transmissionMap;
  20343. return this;
  20344. };
  20345. /**
  20346. * parameters = {
  20347. * color: <hex>,
  20348. * specular: <hex>,
  20349. * shininess: <float>,
  20350. * opacity: <float>,
  20351. *
  20352. * map: new THREE.Texture( <Image> ),
  20353. *
  20354. * lightMap: new THREE.Texture( <Image> ),
  20355. * lightMapIntensity: <float>
  20356. *
  20357. * aoMap: new THREE.Texture( <Image> ),
  20358. * aoMapIntensity: <float>
  20359. *
  20360. * emissive: <hex>,
  20361. * emissiveIntensity: <float>
  20362. * emissiveMap: new THREE.Texture( <Image> ),
  20363. *
  20364. * bumpMap: new THREE.Texture( <Image> ),
  20365. * bumpScale: <float>,
  20366. *
  20367. * normalMap: new THREE.Texture( <Image> ),
  20368. * normalMapType: THREE.TangentSpaceNormalMap,
  20369. * normalScale: <Vector2>,
  20370. *
  20371. * displacementMap: new THREE.Texture( <Image> ),
  20372. * displacementScale: <float>,
  20373. * displacementBias: <float>,
  20374. *
  20375. * specularMap: new THREE.Texture( <Image> ),
  20376. *
  20377. * alphaMap: new THREE.Texture( <Image> ),
  20378. *
  20379. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  20380. * combine: THREE.MultiplyOperation,
  20381. * reflectivity: <float>,
  20382. * refractionRatio: <float>,
  20383. *
  20384. * wireframe: <boolean>,
  20385. * wireframeLinewidth: <float>,
  20386. *
  20387. * skinning: <bool>,
  20388. * morphTargets: <bool>,
  20389. * morphNormals: <bool>
  20390. * }
  20391. */
  20392. function MeshPhongMaterial(parameters) {
  20393. Material.call(this);
  20394. this.type = 'MeshPhongMaterial';
  20395. this.color = new Color(0xffffff); // diffuse
  20396. this.specular = new Color(0x111111);
  20397. this.shininess = 30;
  20398. this.map = null;
  20399. this.lightMap = null;
  20400. this.lightMapIntensity = 1.0;
  20401. this.aoMap = null;
  20402. this.aoMapIntensity = 1.0;
  20403. this.emissive = new Color(0x000000);
  20404. this.emissiveIntensity = 1.0;
  20405. this.emissiveMap = null;
  20406. this.bumpMap = null;
  20407. this.bumpScale = 1;
  20408. this.normalMap = null;
  20409. this.normalMapType = TangentSpaceNormalMap;
  20410. this.normalScale = new Vector2(1, 1);
  20411. this.displacementMap = null;
  20412. this.displacementScale = 1;
  20413. this.displacementBias = 0;
  20414. this.specularMap = null;
  20415. this.alphaMap = null;
  20416. this.envMap = null;
  20417. this.combine = MultiplyOperation;
  20418. this.reflectivity = 1;
  20419. this.refractionRatio = 0.98;
  20420. this.wireframe = false;
  20421. this.wireframeLinewidth = 1;
  20422. this.wireframeLinecap = 'round';
  20423. this.wireframeLinejoin = 'round';
  20424. this.skinning = false;
  20425. this.morphTargets = false;
  20426. this.morphNormals = false;
  20427. this.setValues(parameters);
  20428. }
  20429. MeshPhongMaterial.prototype = Object.create(Material.prototype);
  20430. MeshPhongMaterial.prototype.constructor = MeshPhongMaterial;
  20431. MeshPhongMaterial.prototype.isMeshPhongMaterial = true;
  20432. MeshPhongMaterial.prototype.copy = function (source) {
  20433. Material.prototype.copy.call(this, source);
  20434. this.color.copy(source.color);
  20435. this.specular.copy(source.specular);
  20436. this.shininess = source.shininess;
  20437. this.map = source.map;
  20438. this.lightMap = source.lightMap;
  20439. this.lightMapIntensity = source.lightMapIntensity;
  20440. this.aoMap = source.aoMap;
  20441. this.aoMapIntensity = source.aoMapIntensity;
  20442. this.emissive.copy(source.emissive);
  20443. this.emissiveMap = source.emissiveMap;
  20444. this.emissiveIntensity = source.emissiveIntensity;
  20445. this.bumpMap = source.bumpMap;
  20446. this.bumpScale = source.bumpScale;
  20447. this.normalMap = source.normalMap;
  20448. this.normalMapType = source.normalMapType;
  20449. this.normalScale.copy(source.normalScale);
  20450. this.displacementMap = source.displacementMap;
  20451. this.displacementScale = source.displacementScale;
  20452. this.displacementBias = source.displacementBias;
  20453. this.specularMap = source.specularMap;
  20454. this.alphaMap = source.alphaMap;
  20455. this.envMap = source.envMap;
  20456. this.combine = source.combine;
  20457. this.reflectivity = source.reflectivity;
  20458. this.refractionRatio = source.refractionRatio;
  20459. this.wireframe = source.wireframe;
  20460. this.wireframeLinewidth = source.wireframeLinewidth;
  20461. this.wireframeLinecap = source.wireframeLinecap;
  20462. this.wireframeLinejoin = source.wireframeLinejoin;
  20463. this.skinning = source.skinning;
  20464. this.morphTargets = source.morphTargets;
  20465. this.morphNormals = source.morphNormals;
  20466. return this;
  20467. };
  20468. /**
  20469. * parameters = {
  20470. * color: <hex>,
  20471. *
  20472. * map: new THREE.Texture( <Image> ),
  20473. * gradientMap: new THREE.Texture( <Image> ),
  20474. *
  20475. * lightMap: new THREE.Texture( <Image> ),
  20476. * lightMapIntensity: <float>
  20477. *
  20478. * aoMap: new THREE.Texture( <Image> ),
  20479. * aoMapIntensity: <float>
  20480. *
  20481. * emissive: <hex>,
  20482. * emissiveIntensity: <float>
  20483. * emissiveMap: new THREE.Texture( <Image> ),
  20484. *
  20485. * bumpMap: new THREE.Texture( <Image> ),
  20486. * bumpScale: <float>,
  20487. *
  20488. * normalMap: new THREE.Texture( <Image> ),
  20489. * normalMapType: THREE.TangentSpaceNormalMap,
  20490. * normalScale: <Vector2>,
  20491. *
  20492. * displacementMap: new THREE.Texture( <Image> ),
  20493. * displacementScale: <float>,
  20494. * displacementBias: <float>,
  20495. *
  20496. * alphaMap: new THREE.Texture( <Image> ),
  20497. *
  20498. * wireframe: <boolean>,
  20499. * wireframeLinewidth: <float>,
  20500. *
  20501. * skinning: <bool>,
  20502. * morphTargets: <bool>,
  20503. * morphNormals: <bool>
  20504. * }
  20505. */
  20506. function MeshToonMaterial(parameters) {
  20507. Material.call(this);
  20508. this.defines = {
  20509. 'TOON': ''
  20510. };
  20511. this.type = 'MeshToonMaterial';
  20512. this.color = new Color(0xffffff);
  20513. this.map = null;
  20514. this.gradientMap = null;
  20515. this.lightMap = null;
  20516. this.lightMapIntensity = 1.0;
  20517. this.aoMap = null;
  20518. this.aoMapIntensity = 1.0;
  20519. this.emissive = new Color(0x000000);
  20520. this.emissiveIntensity = 1.0;
  20521. this.emissiveMap = null;
  20522. this.bumpMap = null;
  20523. this.bumpScale = 1;
  20524. this.normalMap = null;
  20525. this.normalMapType = TangentSpaceNormalMap;
  20526. this.normalScale = new Vector2(1, 1);
  20527. this.displacementMap = null;
  20528. this.displacementScale = 1;
  20529. this.displacementBias = 0;
  20530. this.alphaMap = null;
  20531. this.wireframe = false;
  20532. this.wireframeLinewidth = 1;
  20533. this.wireframeLinecap = 'round';
  20534. this.wireframeLinejoin = 'round';
  20535. this.skinning = false;
  20536. this.morphTargets = false;
  20537. this.morphNormals = false;
  20538. this.setValues(parameters);
  20539. }
  20540. MeshToonMaterial.prototype = Object.create(Material.prototype);
  20541. MeshToonMaterial.prototype.constructor = MeshToonMaterial;
  20542. MeshToonMaterial.prototype.isMeshToonMaterial = true;
  20543. MeshToonMaterial.prototype.copy = function (source) {
  20544. Material.prototype.copy.call(this, source);
  20545. this.color.copy(source.color);
  20546. this.map = source.map;
  20547. this.gradientMap = source.gradientMap;
  20548. this.lightMap = source.lightMap;
  20549. this.lightMapIntensity = source.lightMapIntensity;
  20550. this.aoMap = source.aoMap;
  20551. this.aoMapIntensity = source.aoMapIntensity;
  20552. this.emissive.copy(source.emissive);
  20553. this.emissiveMap = source.emissiveMap;
  20554. this.emissiveIntensity = source.emissiveIntensity;
  20555. this.bumpMap = source.bumpMap;
  20556. this.bumpScale = source.bumpScale;
  20557. this.normalMap = source.normalMap;
  20558. this.normalMapType = source.normalMapType;
  20559. this.normalScale.copy(source.normalScale);
  20560. this.displacementMap = source.displacementMap;
  20561. this.displacementScale = source.displacementScale;
  20562. this.displacementBias = source.displacementBias;
  20563. this.alphaMap = source.alphaMap;
  20564. this.wireframe = source.wireframe;
  20565. this.wireframeLinewidth = source.wireframeLinewidth;
  20566. this.wireframeLinecap = source.wireframeLinecap;
  20567. this.wireframeLinejoin = source.wireframeLinejoin;
  20568. this.skinning = source.skinning;
  20569. this.morphTargets = source.morphTargets;
  20570. this.morphNormals = source.morphNormals;
  20571. return this;
  20572. };
  20573. /**
  20574. * parameters = {
  20575. * opacity: <float>,
  20576. *
  20577. * bumpMap: new THREE.Texture( <Image> ),
  20578. * bumpScale: <float>,
  20579. *
  20580. * normalMap: new THREE.Texture( <Image> ),
  20581. * normalMapType: THREE.TangentSpaceNormalMap,
  20582. * normalScale: <Vector2>,
  20583. *
  20584. * displacementMap: new THREE.Texture( <Image> ),
  20585. * displacementScale: <float>,
  20586. * displacementBias: <float>,
  20587. *
  20588. * wireframe: <boolean>,
  20589. * wireframeLinewidth: <float>
  20590. *
  20591. * skinning: <bool>,
  20592. * morphTargets: <bool>,
  20593. * morphNormals: <bool>
  20594. * }
  20595. */
  20596. function MeshNormalMaterial(parameters) {
  20597. Material.call(this);
  20598. this.type = 'MeshNormalMaterial';
  20599. this.bumpMap = null;
  20600. this.bumpScale = 1;
  20601. this.normalMap = null;
  20602. this.normalMapType = TangentSpaceNormalMap;
  20603. this.normalScale = new Vector2(1, 1);
  20604. this.displacementMap = null;
  20605. this.displacementScale = 1;
  20606. this.displacementBias = 0;
  20607. this.wireframe = false;
  20608. this.wireframeLinewidth = 1;
  20609. this.fog = false;
  20610. this.skinning = false;
  20611. this.morphTargets = false;
  20612. this.morphNormals = false;
  20613. this.setValues(parameters);
  20614. }
  20615. MeshNormalMaterial.prototype = Object.create(Material.prototype);
  20616. MeshNormalMaterial.prototype.constructor = MeshNormalMaterial;
  20617. MeshNormalMaterial.prototype.isMeshNormalMaterial = true;
  20618. MeshNormalMaterial.prototype.copy = function (source) {
  20619. Material.prototype.copy.call(this, source);
  20620. this.bumpMap = source.bumpMap;
  20621. this.bumpScale = source.bumpScale;
  20622. this.normalMap = source.normalMap;
  20623. this.normalMapType = source.normalMapType;
  20624. this.normalScale.copy(source.normalScale);
  20625. this.displacementMap = source.displacementMap;
  20626. this.displacementScale = source.displacementScale;
  20627. this.displacementBias = source.displacementBias;
  20628. this.wireframe = source.wireframe;
  20629. this.wireframeLinewidth = source.wireframeLinewidth;
  20630. this.skinning = source.skinning;
  20631. this.morphTargets = source.morphTargets;
  20632. this.morphNormals = source.morphNormals;
  20633. return this;
  20634. };
  20635. /**
  20636. * parameters = {
  20637. * color: <hex>,
  20638. * opacity: <float>,
  20639. *
  20640. * map: new THREE.Texture( <Image> ),
  20641. *
  20642. * lightMap: new THREE.Texture( <Image> ),
  20643. * lightMapIntensity: <float>
  20644. *
  20645. * aoMap: new THREE.Texture( <Image> ),
  20646. * aoMapIntensity: <float>
  20647. *
  20648. * emissive: <hex>,
  20649. * emissiveIntensity: <float>
  20650. * emissiveMap: new THREE.Texture( <Image> ),
  20651. *
  20652. * specularMap: new THREE.Texture( <Image> ),
  20653. *
  20654. * alphaMap: new THREE.Texture( <Image> ),
  20655. *
  20656. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  20657. * combine: THREE.Multiply,
  20658. * reflectivity: <float>,
  20659. * refractionRatio: <float>,
  20660. *
  20661. * wireframe: <boolean>,
  20662. * wireframeLinewidth: <float>,
  20663. *
  20664. * skinning: <bool>,
  20665. * morphTargets: <bool>,
  20666. * morphNormals: <bool>
  20667. * }
  20668. */
  20669. function MeshLambertMaterial(parameters) {
  20670. Material.call(this);
  20671. this.type = 'MeshLambertMaterial';
  20672. this.color = new Color(0xffffff); // diffuse
  20673. this.map = null;
  20674. this.lightMap = null;
  20675. this.lightMapIntensity = 1.0;
  20676. this.aoMap = null;
  20677. this.aoMapIntensity = 1.0;
  20678. this.emissive = new Color(0x000000);
  20679. this.emissiveIntensity = 1.0;
  20680. this.emissiveMap = null;
  20681. this.specularMap = null;
  20682. this.alphaMap = null;
  20683. this.envMap = null;
  20684. this.combine = MultiplyOperation;
  20685. this.reflectivity = 1;
  20686. this.refractionRatio = 0.98;
  20687. this.wireframe = false;
  20688. this.wireframeLinewidth = 1;
  20689. this.wireframeLinecap = 'round';
  20690. this.wireframeLinejoin = 'round';
  20691. this.skinning = false;
  20692. this.morphTargets = false;
  20693. this.morphNormals = false;
  20694. this.setValues(parameters);
  20695. }
  20696. MeshLambertMaterial.prototype = Object.create(Material.prototype);
  20697. MeshLambertMaterial.prototype.constructor = MeshLambertMaterial;
  20698. MeshLambertMaterial.prototype.isMeshLambertMaterial = true;
  20699. MeshLambertMaterial.prototype.copy = function (source) {
  20700. Material.prototype.copy.call(this, source);
  20701. this.color.copy(source.color);
  20702. this.map = source.map;
  20703. this.lightMap = source.lightMap;
  20704. this.lightMapIntensity = source.lightMapIntensity;
  20705. this.aoMap = source.aoMap;
  20706. this.aoMapIntensity = source.aoMapIntensity;
  20707. this.emissive.copy(source.emissive);
  20708. this.emissiveMap = source.emissiveMap;
  20709. this.emissiveIntensity = source.emissiveIntensity;
  20710. this.specularMap = source.specularMap;
  20711. this.alphaMap = source.alphaMap;
  20712. this.envMap = source.envMap;
  20713. this.combine = source.combine;
  20714. this.reflectivity = source.reflectivity;
  20715. this.refractionRatio = source.refractionRatio;
  20716. this.wireframe = source.wireframe;
  20717. this.wireframeLinewidth = source.wireframeLinewidth;
  20718. this.wireframeLinecap = source.wireframeLinecap;
  20719. this.wireframeLinejoin = source.wireframeLinejoin;
  20720. this.skinning = source.skinning;
  20721. this.morphTargets = source.morphTargets;
  20722. this.morphNormals = source.morphNormals;
  20723. return this;
  20724. };
  20725. /**
  20726. * parameters = {
  20727. * color: <hex>,
  20728. * opacity: <float>,
  20729. *
  20730. * matcap: new THREE.Texture( <Image> ),
  20731. *
  20732. * map: new THREE.Texture( <Image> ),
  20733. *
  20734. * bumpMap: new THREE.Texture( <Image> ),
  20735. * bumpScale: <float>,
  20736. *
  20737. * normalMap: new THREE.Texture( <Image> ),
  20738. * normalMapType: THREE.TangentSpaceNormalMap,
  20739. * normalScale: <Vector2>,
  20740. *
  20741. * displacementMap: new THREE.Texture( <Image> ),
  20742. * displacementScale: <float>,
  20743. * displacementBias: <float>,
  20744. *
  20745. * alphaMap: new THREE.Texture( <Image> ),
  20746. *
  20747. * skinning: <bool>,
  20748. * morphTargets: <bool>,
  20749. * morphNormals: <bool>
  20750. * }
  20751. */
  20752. function MeshMatcapMaterial(parameters) {
  20753. Material.call(this);
  20754. this.defines = {
  20755. 'MATCAP': ''
  20756. };
  20757. this.type = 'MeshMatcapMaterial';
  20758. this.color = new Color(0xffffff); // diffuse
  20759. this.matcap = null;
  20760. this.map = null;
  20761. this.bumpMap = null;
  20762. this.bumpScale = 1;
  20763. this.normalMap = null;
  20764. this.normalMapType = TangentSpaceNormalMap;
  20765. this.normalScale = new Vector2(1, 1);
  20766. this.displacementMap = null;
  20767. this.displacementScale = 1;
  20768. this.displacementBias = 0;
  20769. this.alphaMap = null;
  20770. this.skinning = false;
  20771. this.morphTargets = false;
  20772. this.morphNormals = false;
  20773. this.setValues(parameters);
  20774. }
  20775. MeshMatcapMaterial.prototype = Object.create(Material.prototype);
  20776. MeshMatcapMaterial.prototype.constructor = MeshMatcapMaterial;
  20777. MeshMatcapMaterial.prototype.isMeshMatcapMaterial = true;
  20778. MeshMatcapMaterial.prototype.copy = function (source) {
  20779. Material.prototype.copy.call(this, source);
  20780. this.defines = {
  20781. 'MATCAP': ''
  20782. };
  20783. this.color.copy(source.color);
  20784. this.matcap = source.matcap;
  20785. this.map = source.map;
  20786. this.bumpMap = source.bumpMap;
  20787. this.bumpScale = source.bumpScale;
  20788. this.normalMap = source.normalMap;
  20789. this.normalMapType = source.normalMapType;
  20790. this.normalScale.copy(source.normalScale);
  20791. this.displacementMap = source.displacementMap;
  20792. this.displacementScale = source.displacementScale;
  20793. this.displacementBias = source.displacementBias;
  20794. this.alphaMap = source.alphaMap;
  20795. this.skinning = source.skinning;
  20796. this.morphTargets = source.morphTargets;
  20797. this.morphNormals = source.morphNormals;
  20798. return this;
  20799. };
  20800. /**
  20801. * parameters = {
  20802. * color: <hex>,
  20803. * opacity: <float>,
  20804. *
  20805. * linewidth: <float>,
  20806. *
  20807. * scale: <float>,
  20808. * dashSize: <float>,
  20809. * gapSize: <float>
  20810. * }
  20811. */
  20812. function LineDashedMaterial(parameters) {
  20813. LineBasicMaterial.call(this);
  20814. this.type = 'LineDashedMaterial';
  20815. this.scale = 1;
  20816. this.dashSize = 3;
  20817. this.gapSize = 1;
  20818. this.setValues(parameters);
  20819. }
  20820. LineDashedMaterial.prototype = Object.create(LineBasicMaterial.prototype);
  20821. LineDashedMaterial.prototype.constructor = LineDashedMaterial;
  20822. LineDashedMaterial.prototype.isLineDashedMaterial = true;
  20823. LineDashedMaterial.prototype.copy = function (source) {
  20824. LineBasicMaterial.prototype.copy.call(this, source);
  20825. this.scale = source.scale;
  20826. this.dashSize = source.dashSize;
  20827. this.gapSize = source.gapSize;
  20828. return this;
  20829. };
  20830. var Materials =
  20831. /*#__PURE__*/
  20832. Object.freeze({
  20833. __proto__: null,
  20834. ShadowMaterial: ShadowMaterial,
  20835. SpriteMaterial: SpriteMaterial,
  20836. RawShaderMaterial: RawShaderMaterial,
  20837. ShaderMaterial: ShaderMaterial,
  20838. PointsMaterial: PointsMaterial,
  20839. MeshPhysicalMaterial: MeshPhysicalMaterial,
  20840. MeshStandardMaterial: MeshStandardMaterial,
  20841. MeshPhongMaterial: MeshPhongMaterial,
  20842. MeshToonMaterial: MeshToonMaterial,
  20843. MeshNormalMaterial: MeshNormalMaterial,
  20844. MeshLambertMaterial: MeshLambertMaterial,
  20845. MeshDepthMaterial: MeshDepthMaterial,
  20846. MeshDistanceMaterial: MeshDistanceMaterial,
  20847. MeshBasicMaterial: MeshBasicMaterial,
  20848. MeshMatcapMaterial: MeshMatcapMaterial,
  20849. LineDashedMaterial: LineDashedMaterial,
  20850. LineBasicMaterial: LineBasicMaterial,
  20851. Material: Material
  20852. });
  20853. const AnimationUtils = {
  20854. // same as Array.prototype.slice, but also works on typed arrays
  20855. arraySlice: function (array, from, to) {
  20856. if (AnimationUtils.isTypedArray(array)) {
  20857. // in ios9 array.subarray(from, undefined) will return empty array
  20858. // but array.subarray(from) or array.subarray(from, len) is correct
  20859. return new array.constructor(array.subarray(from, to !== undefined ? to : array.length));
  20860. }
  20861. return array.slice(from, to);
  20862. },
  20863. // converts an array to a specific type
  20864. convertArray: function (array, type, forceClone) {
  20865. if (!array || // let 'undefined' and 'null' pass
  20866. !forceClone && array.constructor === type) return array;
  20867. if (typeof type.BYTES_PER_ELEMENT === 'number') {
  20868. return new type(array); // create typed array
  20869. }
  20870. return Array.prototype.slice.call(array); // create Array
  20871. },
  20872. isTypedArray: function (object) {
  20873. return ArrayBuffer.isView(object) && !(object instanceof DataView);
  20874. },
  20875. // returns an array by which times and values can be sorted
  20876. getKeyframeOrder: function (times) {
  20877. function compareTime(i, j) {
  20878. return times[i] - times[j];
  20879. }
  20880. const n = times.length;
  20881. const result = new Array(n);
  20882. for (let i = 0; i !== n; ++i) result[i] = i;
  20883. result.sort(compareTime);
  20884. return result;
  20885. },
  20886. // uses the array previously returned by 'getKeyframeOrder' to sort data
  20887. sortedArray: function (values, stride, order) {
  20888. const nValues = values.length;
  20889. const result = new values.constructor(nValues);
  20890. for (let i = 0, dstOffset = 0; dstOffset !== nValues; ++i) {
  20891. const srcOffset = order[i] * stride;
  20892. for (let j = 0; j !== stride; ++j) {
  20893. result[dstOffset++] = values[srcOffset + j];
  20894. }
  20895. }
  20896. return result;
  20897. },
  20898. // function for parsing AOS keyframe formats
  20899. flattenJSON: function (jsonKeys, times, values, valuePropertyName) {
  20900. let i = 1,
  20901. key = jsonKeys[0];
  20902. while (key !== undefined && key[valuePropertyName] === undefined) {
  20903. key = jsonKeys[i++];
  20904. }
  20905. if (key === undefined) return; // no data
  20906. let value = key[valuePropertyName];
  20907. if (value === undefined) return; // no data
  20908. if (Array.isArray(value)) {
  20909. do {
  20910. value = key[valuePropertyName];
  20911. if (value !== undefined) {
  20912. times.push(key.time);
  20913. values.push.apply(values, value); // push all elements
  20914. }
  20915. key = jsonKeys[i++];
  20916. } while (key !== undefined);
  20917. } else if (value.toArray !== undefined) {
  20918. // ...assume THREE.Math-ish
  20919. do {
  20920. value = key[valuePropertyName];
  20921. if (value !== undefined) {
  20922. times.push(key.time);
  20923. value.toArray(values, values.length);
  20924. }
  20925. key = jsonKeys[i++];
  20926. } while (key !== undefined);
  20927. } else {
  20928. // otherwise push as-is
  20929. do {
  20930. value = key[valuePropertyName];
  20931. if (value !== undefined) {
  20932. times.push(key.time);
  20933. values.push(value);
  20934. }
  20935. key = jsonKeys[i++];
  20936. } while (key !== undefined);
  20937. }
  20938. },
  20939. subclip: function (sourceClip, name, startFrame, endFrame, fps = 30) {
  20940. const clip = sourceClip.clone();
  20941. clip.name = name;
  20942. const tracks = [];
  20943. for (let i = 0; i < clip.tracks.length; ++i) {
  20944. const track = clip.tracks[i];
  20945. const valueSize = track.getValueSize();
  20946. const times = [];
  20947. const values = [];
  20948. for (let j = 0; j < track.times.length; ++j) {
  20949. const frame = track.times[j] * fps;
  20950. if (frame < startFrame || frame >= endFrame) continue;
  20951. times.push(track.times[j]);
  20952. for (let k = 0; k < valueSize; ++k) {
  20953. values.push(track.values[j * valueSize + k]);
  20954. }
  20955. }
  20956. if (times.length === 0) continue;
  20957. track.times = AnimationUtils.convertArray(times, track.times.constructor);
  20958. track.values = AnimationUtils.convertArray(values, track.values.constructor);
  20959. tracks.push(track);
  20960. }
  20961. clip.tracks = tracks; // find minimum .times value across all tracks in the trimmed clip
  20962. let minStartTime = Infinity;
  20963. for (let i = 0; i < clip.tracks.length; ++i) {
  20964. if (minStartTime > clip.tracks[i].times[0]) {
  20965. minStartTime = clip.tracks[i].times[0];
  20966. }
  20967. } // shift all tracks such that clip begins at t=0
  20968. for (let i = 0; i < clip.tracks.length; ++i) {
  20969. clip.tracks[i].shift(-1 * minStartTime);
  20970. }
  20971. clip.resetDuration();
  20972. return clip;
  20973. },
  20974. makeClipAdditive: function (targetClip, referenceFrame = 0, referenceClip = targetClip, fps = 30) {
  20975. if (fps <= 0) fps = 30;
  20976. const numTracks = referenceClip.tracks.length;
  20977. const referenceTime = referenceFrame / fps; // Make each track's values relative to the values at the reference frame
  20978. for (let i = 0; i < numTracks; ++i) {
  20979. const referenceTrack = referenceClip.tracks[i];
  20980. const referenceTrackType = referenceTrack.ValueTypeName; // Skip this track if it's non-numeric
  20981. if (referenceTrackType === 'bool' || referenceTrackType === 'string') continue; // Find the track in the target clip whose name and type matches the reference track
  20982. const targetTrack = targetClip.tracks.find(function (track) {
  20983. return track.name === referenceTrack.name && track.ValueTypeName === referenceTrackType;
  20984. });
  20985. if (targetTrack === undefined) continue;
  20986. let referenceOffset = 0;
  20987. const referenceValueSize = referenceTrack.getValueSize();
  20988. if (referenceTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline) {
  20989. referenceOffset = referenceValueSize / 3;
  20990. }
  20991. let targetOffset = 0;
  20992. const targetValueSize = targetTrack.getValueSize();
  20993. if (targetTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline) {
  20994. targetOffset = targetValueSize / 3;
  20995. }
  20996. const lastIndex = referenceTrack.times.length - 1;
  20997. let referenceValue; // Find the value to subtract out of the track
  20998. if (referenceTime <= referenceTrack.times[0]) {
  20999. // Reference frame is earlier than the first keyframe, so just use the first keyframe
  21000. const startIndex = referenceOffset;
  21001. const endIndex = referenceValueSize - referenceOffset;
  21002. referenceValue = AnimationUtils.arraySlice(referenceTrack.values, startIndex, endIndex);
  21003. } else if (referenceTime >= referenceTrack.times[lastIndex]) {
  21004. // Reference frame is after the last keyframe, so just use the last keyframe
  21005. const startIndex = lastIndex * referenceValueSize + referenceOffset;
  21006. const endIndex = startIndex + referenceValueSize - referenceOffset;
  21007. referenceValue = AnimationUtils.arraySlice(referenceTrack.values, startIndex, endIndex);
  21008. } else {
  21009. // Interpolate to the reference value
  21010. const interpolant = referenceTrack.createInterpolant();
  21011. const startIndex = referenceOffset;
  21012. const endIndex = referenceValueSize - referenceOffset;
  21013. interpolant.evaluate(referenceTime);
  21014. referenceValue = AnimationUtils.arraySlice(interpolant.resultBuffer, startIndex, endIndex);
  21015. } // Conjugate the quaternion
  21016. if (referenceTrackType === 'quaternion') {
  21017. const referenceQuat = new Quaternion().fromArray(referenceValue).normalize().conjugate();
  21018. referenceQuat.toArray(referenceValue);
  21019. } // Subtract the reference value from all of the track values
  21020. const numTimes = targetTrack.times.length;
  21021. for (let j = 0; j < numTimes; ++j) {
  21022. const valueStart = j * targetValueSize + targetOffset;
  21023. if (referenceTrackType === 'quaternion') {
  21024. // Multiply the conjugate for quaternion track types
  21025. Quaternion.multiplyQuaternionsFlat(targetTrack.values, valueStart, referenceValue, 0, targetTrack.values, valueStart);
  21026. } else {
  21027. const valueEnd = targetValueSize - targetOffset * 2; // Subtract each value for all other numeric track types
  21028. for (let k = 0; k < valueEnd; ++k) {
  21029. targetTrack.values[valueStart + k] -= referenceValue[k];
  21030. }
  21031. }
  21032. }
  21033. }
  21034. targetClip.blendMode = AdditiveAnimationBlendMode;
  21035. return targetClip;
  21036. }
  21037. };
  21038. /**
  21039. * Abstract base class of interpolants over parametric samples.
  21040. *
  21041. * The parameter domain is one dimensional, typically the time or a path
  21042. * along a curve defined by the data.
  21043. *
  21044. * The sample values can have any dimensionality and derived classes may
  21045. * apply special interpretations to the data.
  21046. *
  21047. * This class provides the interval seek in a Template Method, deferring
  21048. * the actual interpolation to derived classes.
  21049. *
  21050. * Time complexity is O(1) for linear access crossing at most two points
  21051. * and O(log N) for random access, where N is the number of positions.
  21052. *
  21053. * References:
  21054. *
  21055. * http://www.oodesign.com/template-method-pattern.html
  21056. *
  21057. */
  21058. exports.AnimationUtils = AnimationUtils;
  21059. function Interpolant(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  21060. this.parameterPositions = parameterPositions;
  21061. this._cachedIndex = 0;
  21062. this.resultBuffer = resultBuffer !== undefined ? resultBuffer : new sampleValues.constructor(sampleSize);
  21063. this.sampleValues = sampleValues;
  21064. this.valueSize = sampleSize;
  21065. }
  21066. Object.assign(Interpolant.prototype, {
  21067. evaluate: function (t) {
  21068. const pp = this.parameterPositions;
  21069. let i1 = this._cachedIndex,
  21070. t1 = pp[i1],
  21071. t0 = pp[i1 - 1];
  21072. validate_interval: {
  21073. seek: {
  21074. let right;
  21075. linear_scan: {
  21076. //- See http://jsperf.com/comparison-to-undefined/3
  21077. //- slower code:
  21078. //-
  21079. //- if ( t >= t1 || t1 === undefined ) {
  21080. forward_scan: if (!(t < t1)) {
  21081. for (let giveUpAt = i1 + 2;;) {
  21082. if (t1 === undefined) {
  21083. if (t < t0) break forward_scan; // after end
  21084. i1 = pp.length;
  21085. this._cachedIndex = i1;
  21086. return this.afterEnd_(i1 - 1, t, t0);
  21087. }
  21088. if (i1 === giveUpAt) break; // this loop
  21089. t0 = t1;
  21090. t1 = pp[++i1];
  21091. if (t < t1) {
  21092. // we have arrived at the sought interval
  21093. break seek;
  21094. }
  21095. } // prepare binary search on the right side of the index
  21096. right = pp.length;
  21097. break linear_scan;
  21098. } //- slower code:
  21099. //- if ( t < t0 || t0 === undefined ) {
  21100. if (!(t >= t0)) {
  21101. // looping?
  21102. const t1global = pp[1];
  21103. if (t < t1global) {
  21104. i1 = 2; // + 1, using the scan for the details
  21105. t0 = t1global;
  21106. } // linear reverse scan
  21107. for (let giveUpAt = i1 - 2;;) {
  21108. if (t0 === undefined) {
  21109. // before start
  21110. this._cachedIndex = 0;
  21111. return this.beforeStart_(0, t, t1);
  21112. }
  21113. if (i1 === giveUpAt) break; // this loop
  21114. t1 = t0;
  21115. t0 = pp[--i1 - 1];
  21116. if (t >= t0) {
  21117. // we have arrived at the sought interval
  21118. break seek;
  21119. }
  21120. } // prepare binary search on the left side of the index
  21121. right = i1;
  21122. i1 = 0;
  21123. break linear_scan;
  21124. } // the interval is valid
  21125. break validate_interval;
  21126. } // linear scan
  21127. // binary search
  21128. while (i1 < right) {
  21129. const mid = i1 + right >>> 1;
  21130. if (t < pp[mid]) {
  21131. right = mid;
  21132. } else {
  21133. i1 = mid + 1;
  21134. }
  21135. }
  21136. t1 = pp[i1];
  21137. t0 = pp[i1 - 1]; // check boundary cases, again
  21138. if (t0 === undefined) {
  21139. this._cachedIndex = 0;
  21140. return this.beforeStart_(0, t, t1);
  21141. }
  21142. if (t1 === undefined) {
  21143. i1 = pp.length;
  21144. this._cachedIndex = i1;
  21145. return this.afterEnd_(i1 - 1, t0, t);
  21146. }
  21147. } // seek
  21148. this._cachedIndex = i1;
  21149. this.intervalChanged_(i1, t0, t1);
  21150. } // validate_interval
  21151. return this.interpolate_(i1, t0, t, t1);
  21152. },
  21153. settings: null,
  21154. // optional, subclass-specific settings structure
  21155. // Note: The indirection allows central control of many interpolants.
  21156. // --- Protected interface
  21157. DefaultSettings_: {},
  21158. getSettings_: function () {
  21159. return this.settings || this.DefaultSettings_;
  21160. },
  21161. copySampleValue_: function (index) {
  21162. // copies a sample value to the result buffer
  21163. const result = this.resultBuffer,
  21164. values = this.sampleValues,
  21165. stride = this.valueSize,
  21166. offset = index * stride;
  21167. for (let i = 0; i !== stride; ++i) {
  21168. result[i] = values[offset + i];
  21169. }
  21170. return result;
  21171. },
  21172. // Template methods for derived classes:
  21173. interpolate_: function ()
  21174. /* i1, t0, t, t1 */
  21175. {
  21176. throw new Error('call to abstract method'); // implementations shall return this.resultBuffer
  21177. },
  21178. intervalChanged_: function ()
  21179. /* i1, t0, t1 */
  21180. {// empty
  21181. }
  21182. }); // DECLARE ALIAS AFTER assign prototype
  21183. Object.assign(Interpolant.prototype, {
  21184. //( 0, t, t0 ), returns this.resultBuffer
  21185. beforeStart_: Interpolant.prototype.copySampleValue_,
  21186. //( N-1, tN-1, t ), returns this.resultBuffer
  21187. afterEnd_: Interpolant.prototype.copySampleValue_
  21188. });
  21189. /**
  21190. * Fast and simple cubic spline interpolant.
  21191. *
  21192. * It was derived from a Hermitian construction setting the first derivative
  21193. * at each sample position to the linear slope between neighboring positions
  21194. * over their parameter interval.
  21195. */
  21196. function CubicInterpolant(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  21197. Interpolant.call(this, parameterPositions, sampleValues, sampleSize, resultBuffer);
  21198. this._weightPrev = -0;
  21199. this._offsetPrev = -0;
  21200. this._weightNext = -0;
  21201. this._offsetNext = -0;
  21202. }
  21203. CubicInterpolant.prototype = Object.assign(Object.create(Interpolant.prototype), {
  21204. constructor: CubicInterpolant,
  21205. DefaultSettings_: {
  21206. endingStart: ZeroCurvatureEnding,
  21207. endingEnd: ZeroCurvatureEnding
  21208. },
  21209. intervalChanged_: function (i1, t0, t1) {
  21210. const pp = this.parameterPositions;
  21211. let iPrev = i1 - 2,
  21212. iNext = i1 + 1,
  21213. tPrev = pp[iPrev],
  21214. tNext = pp[iNext];
  21215. if (tPrev === undefined) {
  21216. switch (this.getSettings_().endingStart) {
  21217. case ZeroSlopeEnding:
  21218. // f'(t0) = 0
  21219. iPrev = i1;
  21220. tPrev = 2 * t0 - t1;
  21221. break;
  21222. case WrapAroundEnding:
  21223. // use the other end of the curve
  21224. iPrev = pp.length - 2;
  21225. tPrev = t0 + pp[iPrev] - pp[iPrev + 1];
  21226. break;
  21227. default:
  21228. // ZeroCurvatureEnding
  21229. // f''(t0) = 0 a.k.a. Natural Spline
  21230. iPrev = i1;
  21231. tPrev = t1;
  21232. }
  21233. }
  21234. if (tNext === undefined) {
  21235. switch (this.getSettings_().endingEnd) {
  21236. case ZeroSlopeEnding:
  21237. // f'(tN) = 0
  21238. iNext = i1;
  21239. tNext = 2 * t1 - t0;
  21240. break;
  21241. case WrapAroundEnding:
  21242. // use the other end of the curve
  21243. iNext = 1;
  21244. tNext = t1 + pp[1] - pp[0];
  21245. break;
  21246. default:
  21247. // ZeroCurvatureEnding
  21248. // f''(tN) = 0, a.k.a. Natural Spline
  21249. iNext = i1 - 1;
  21250. tNext = t0;
  21251. }
  21252. }
  21253. const halfDt = (t1 - t0) * 0.5,
  21254. stride = this.valueSize;
  21255. this._weightPrev = halfDt / (t0 - tPrev);
  21256. this._weightNext = halfDt / (tNext - t1);
  21257. this._offsetPrev = iPrev * stride;
  21258. this._offsetNext = iNext * stride;
  21259. },
  21260. interpolate_: function (i1, t0, t, t1) {
  21261. const result = this.resultBuffer,
  21262. values = this.sampleValues,
  21263. stride = this.valueSize,
  21264. o1 = i1 * stride,
  21265. o0 = o1 - stride,
  21266. oP = this._offsetPrev,
  21267. oN = this._offsetNext,
  21268. wP = this._weightPrev,
  21269. wN = this._weightNext,
  21270. p = (t - t0) / (t1 - t0),
  21271. pp = p * p,
  21272. ppp = pp * p; // evaluate polynomials
  21273. const sP = -wP * ppp + 2 * wP * pp - wP * p;
  21274. const s0 = (1 + wP) * ppp + (-1.5 - 2 * wP) * pp + (-0.5 + wP) * p + 1;
  21275. const s1 = (-1 - wN) * ppp + (1.5 + wN) * pp + 0.5 * p;
  21276. const sN = wN * ppp - wN * pp; // combine data linearly
  21277. for (let i = 0; i !== stride; ++i) {
  21278. result[i] = sP * values[oP + i] + s0 * values[o0 + i] + s1 * values[o1 + i] + sN * values[oN + i];
  21279. }
  21280. return result;
  21281. }
  21282. });
  21283. function LinearInterpolant(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  21284. Interpolant.call(this, parameterPositions, sampleValues, sampleSize, resultBuffer);
  21285. }
  21286. LinearInterpolant.prototype = Object.assign(Object.create(Interpolant.prototype), {
  21287. constructor: LinearInterpolant,
  21288. interpolate_: function (i1, t0, t, t1) {
  21289. const result = this.resultBuffer,
  21290. values = this.sampleValues,
  21291. stride = this.valueSize,
  21292. offset1 = i1 * stride,
  21293. offset0 = offset1 - stride,
  21294. weight1 = (t - t0) / (t1 - t0),
  21295. weight0 = 1 - weight1;
  21296. for (let i = 0; i !== stride; ++i) {
  21297. result[i] = values[offset0 + i] * weight0 + values[offset1 + i] * weight1;
  21298. }
  21299. return result;
  21300. }
  21301. });
  21302. /**
  21303. *
  21304. * Interpolant that evaluates to the sample value at the position preceeding
  21305. * the parameter.
  21306. */
  21307. function DiscreteInterpolant(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  21308. Interpolant.call(this, parameterPositions, sampleValues, sampleSize, resultBuffer);
  21309. }
  21310. DiscreteInterpolant.prototype = Object.assign(Object.create(Interpolant.prototype), {
  21311. constructor: DiscreteInterpolant,
  21312. interpolate_: function (i1
  21313. /*, t0, t, t1 */
  21314. ) {
  21315. return this.copySampleValue_(i1 - 1);
  21316. }
  21317. });
  21318. function KeyframeTrack(name, times, values, interpolation) {
  21319. if (name === undefined) throw new Error('THREE.KeyframeTrack: track name is undefined');
  21320. if (times === undefined || times.length === 0) throw new Error('THREE.KeyframeTrack: no keyframes in track named ' + name);
  21321. this.name = name;
  21322. this.times = AnimationUtils.convertArray(times, this.TimeBufferType);
  21323. this.values = AnimationUtils.convertArray(values, this.ValueBufferType);
  21324. this.setInterpolation(interpolation || this.DefaultInterpolation);
  21325. } // Static methods
  21326. Object.assign(KeyframeTrack, {
  21327. // Serialization (in static context, because of constructor invocation
  21328. // and automatic invocation of .toJSON):
  21329. toJSON: function (track) {
  21330. const trackType = track.constructor;
  21331. let json; // derived classes can define a static toJSON method
  21332. if (trackType.toJSON !== undefined) {
  21333. json = trackType.toJSON(track);
  21334. } else {
  21335. // by default, we assume the data can be serialized as-is
  21336. json = {
  21337. 'name': track.name,
  21338. 'times': AnimationUtils.convertArray(track.times, Array),
  21339. 'values': AnimationUtils.convertArray(track.values, Array)
  21340. };
  21341. const interpolation = track.getInterpolation();
  21342. if (interpolation !== track.DefaultInterpolation) {
  21343. json.interpolation = interpolation;
  21344. }
  21345. }
  21346. json.type = track.ValueTypeName; // mandatory
  21347. return json;
  21348. }
  21349. });
  21350. Object.assign(KeyframeTrack.prototype, {
  21351. constructor: KeyframeTrack,
  21352. TimeBufferType: Float32Array,
  21353. ValueBufferType: Float32Array,
  21354. DefaultInterpolation: InterpolateLinear,
  21355. InterpolantFactoryMethodDiscrete: function (result) {
  21356. return new DiscreteInterpolant(this.times, this.values, this.getValueSize(), result);
  21357. },
  21358. InterpolantFactoryMethodLinear: function (result) {
  21359. return new LinearInterpolant(this.times, this.values, this.getValueSize(), result);
  21360. },
  21361. InterpolantFactoryMethodSmooth: function (result) {
  21362. return new CubicInterpolant(this.times, this.values, this.getValueSize(), result);
  21363. },
  21364. setInterpolation: function (interpolation) {
  21365. let factoryMethod;
  21366. switch (interpolation) {
  21367. case InterpolateDiscrete:
  21368. factoryMethod = this.InterpolantFactoryMethodDiscrete;
  21369. break;
  21370. case InterpolateLinear:
  21371. factoryMethod = this.InterpolantFactoryMethodLinear;
  21372. break;
  21373. case InterpolateSmooth:
  21374. factoryMethod = this.InterpolantFactoryMethodSmooth;
  21375. break;
  21376. }
  21377. if (factoryMethod === undefined) {
  21378. const message = "unsupported interpolation for " + this.ValueTypeName + " keyframe track named " + this.name;
  21379. if (this.createInterpolant === undefined) {
  21380. // fall back to default, unless the default itself is messed up
  21381. if (interpolation !== this.DefaultInterpolation) {
  21382. this.setInterpolation(this.DefaultInterpolation);
  21383. } else {
  21384. throw new Error(message); // fatal, in this case
  21385. }
  21386. }
  21387. console.warn('THREE.KeyframeTrack:', message);
  21388. return this;
  21389. }
  21390. this.createInterpolant = factoryMethod;
  21391. return this;
  21392. },
  21393. getInterpolation: function () {
  21394. switch (this.createInterpolant) {
  21395. case this.InterpolantFactoryMethodDiscrete:
  21396. return InterpolateDiscrete;
  21397. case this.InterpolantFactoryMethodLinear:
  21398. return InterpolateLinear;
  21399. case this.InterpolantFactoryMethodSmooth:
  21400. return InterpolateSmooth;
  21401. }
  21402. },
  21403. getValueSize: function () {
  21404. return this.values.length / this.times.length;
  21405. },
  21406. // move all keyframes either forwards or backwards in time
  21407. shift: function (timeOffset) {
  21408. if (timeOffset !== 0.0) {
  21409. const times = this.times;
  21410. for (let i = 0, n = times.length; i !== n; ++i) {
  21411. times[i] += timeOffset;
  21412. }
  21413. }
  21414. return this;
  21415. },
  21416. // scale all keyframe times by a factor (useful for frame <-> seconds conversions)
  21417. scale: function (timeScale) {
  21418. if (timeScale !== 1.0) {
  21419. const times = this.times;
  21420. for (let i = 0, n = times.length; i !== n; ++i) {
  21421. times[i] *= timeScale;
  21422. }
  21423. }
  21424. return this;
  21425. },
  21426. // removes keyframes before and after animation without changing any values within the range [startTime, endTime].
  21427. // IMPORTANT: We do not shift around keys to the start of the track time, because for interpolated keys this will change their values
  21428. trim: function (startTime, endTime) {
  21429. const times = this.times,
  21430. nKeys = times.length;
  21431. let from = 0,
  21432. to = nKeys - 1;
  21433. while (from !== nKeys && times[from] < startTime) {
  21434. ++from;
  21435. }
  21436. while (to !== -1 && times[to] > endTime) {
  21437. --to;
  21438. }
  21439. ++to; // inclusive -> exclusive bound
  21440. if (from !== 0 || to !== nKeys) {
  21441. // empty tracks are forbidden, so keep at least one keyframe
  21442. if (from >= to) {
  21443. to = Math.max(to, 1);
  21444. from = to - 1;
  21445. }
  21446. const stride = this.getValueSize();
  21447. this.times = AnimationUtils.arraySlice(times, from, to);
  21448. this.values = AnimationUtils.arraySlice(this.values, from * stride, to * stride);
  21449. }
  21450. return this;
  21451. },
  21452. // ensure we do not get a GarbageInGarbageOut situation, make sure tracks are at least minimally viable
  21453. validate: function () {
  21454. let valid = true;
  21455. const valueSize = this.getValueSize();
  21456. if (valueSize - Math.floor(valueSize) !== 0) {
  21457. console.error('THREE.KeyframeTrack: Invalid value size in track.', this);
  21458. valid = false;
  21459. }
  21460. const times = this.times,
  21461. values = this.values,
  21462. nKeys = times.length;
  21463. if (nKeys === 0) {
  21464. console.error('THREE.KeyframeTrack: Track is empty.', this);
  21465. valid = false;
  21466. }
  21467. let prevTime = null;
  21468. for (let i = 0; i !== nKeys; i++) {
  21469. const currTime = times[i];
  21470. if (typeof currTime === 'number' && isNaN(currTime)) {
  21471. console.error('THREE.KeyframeTrack: Time is not a valid number.', this, i, currTime);
  21472. valid = false;
  21473. break;
  21474. }
  21475. if (prevTime !== null && prevTime > currTime) {
  21476. console.error('THREE.KeyframeTrack: Out of order keys.', this, i, currTime, prevTime);
  21477. valid = false;
  21478. break;
  21479. }
  21480. prevTime = currTime;
  21481. }
  21482. if (values !== undefined) {
  21483. if (AnimationUtils.isTypedArray(values)) {
  21484. for (let i = 0, n = values.length; i !== n; ++i) {
  21485. const value = values[i];
  21486. if (isNaN(value)) {
  21487. console.error('THREE.KeyframeTrack: Value is not a valid number.', this, i, value);
  21488. valid = false;
  21489. break;
  21490. }
  21491. }
  21492. }
  21493. }
  21494. return valid;
  21495. },
  21496. // removes equivalent sequential keys as common in morph target sequences
  21497. // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0)
  21498. optimize: function () {
  21499. // times or values may be shared with other tracks, so overwriting is unsafe
  21500. const times = AnimationUtils.arraySlice(this.times),
  21501. values = AnimationUtils.arraySlice(this.values),
  21502. stride = this.getValueSize(),
  21503. smoothInterpolation = this.getInterpolation() === InterpolateSmooth,
  21504. lastIndex = times.length - 1;
  21505. let writeIndex = 1;
  21506. for (let i = 1; i < lastIndex; ++i) {
  21507. let keep = false;
  21508. const time = times[i];
  21509. const timeNext = times[i + 1]; // remove adjacent keyframes scheduled at the same time
  21510. if (time !== timeNext && (i !== 1 || time !== time[0])) {
  21511. if (!smoothInterpolation) {
  21512. // remove unnecessary keyframes same as their neighbors
  21513. const offset = i * stride,
  21514. offsetP = offset - stride,
  21515. offsetN = offset + stride;
  21516. for (let j = 0; j !== stride; ++j) {
  21517. const value = values[offset + j];
  21518. if (value !== values[offsetP + j] || value !== values[offsetN + j]) {
  21519. keep = true;
  21520. break;
  21521. }
  21522. }
  21523. } else {
  21524. keep = true;
  21525. }
  21526. } // in-place compaction
  21527. if (keep) {
  21528. if (i !== writeIndex) {
  21529. times[writeIndex] = times[i];
  21530. const readOffset = i * stride,
  21531. writeOffset = writeIndex * stride;
  21532. for (let j = 0; j !== stride; ++j) {
  21533. values[writeOffset + j] = values[readOffset + j];
  21534. }
  21535. }
  21536. ++writeIndex;
  21537. }
  21538. } // flush last keyframe (compaction looks ahead)
  21539. if (lastIndex > 0) {
  21540. times[writeIndex] = times[lastIndex];
  21541. for (let readOffset = lastIndex * stride, writeOffset = writeIndex * stride, j = 0; j !== stride; ++j) {
  21542. values[writeOffset + j] = values[readOffset + j];
  21543. }
  21544. ++writeIndex;
  21545. }
  21546. if (writeIndex !== times.length) {
  21547. this.times = AnimationUtils.arraySlice(times, 0, writeIndex);
  21548. this.values = AnimationUtils.arraySlice(values, 0, writeIndex * stride);
  21549. } else {
  21550. this.times = times;
  21551. this.values = values;
  21552. }
  21553. return this;
  21554. },
  21555. clone: function () {
  21556. const times = AnimationUtils.arraySlice(this.times, 0);
  21557. const values = AnimationUtils.arraySlice(this.values, 0);
  21558. const TypedKeyframeTrack = this.constructor;
  21559. const track = new TypedKeyframeTrack(this.name, times, values); // Interpolant argument to constructor is not saved, so copy the factory method directly.
  21560. track.createInterpolant = this.createInterpolant;
  21561. return track;
  21562. }
  21563. });
  21564. /**
  21565. * A Track of Boolean keyframe values.
  21566. */
  21567. function BooleanKeyframeTrack(name, times, values) {
  21568. KeyframeTrack.call(this, name, times, values);
  21569. }
  21570. BooleanKeyframeTrack.prototype = Object.assign(Object.create(KeyframeTrack.prototype), {
  21571. constructor: BooleanKeyframeTrack,
  21572. ValueTypeName: 'bool',
  21573. ValueBufferType: Array,
  21574. DefaultInterpolation: InterpolateDiscrete,
  21575. InterpolantFactoryMethodLinear: undefined,
  21576. InterpolantFactoryMethodSmooth: undefined // Note: Actually this track could have a optimized / compressed
  21577. // representation of a single value and a custom interpolant that
  21578. // computes "firstValue ^ isOdd( index )".
  21579. });
  21580. /**
  21581. * A Track of keyframe values that represent color.
  21582. */
  21583. function ColorKeyframeTrack(name, times, values, interpolation) {
  21584. KeyframeTrack.call(this, name, times, values, interpolation);
  21585. }
  21586. ColorKeyframeTrack.prototype = Object.assign(Object.create(KeyframeTrack.prototype), {
  21587. constructor: ColorKeyframeTrack,
  21588. ValueTypeName: 'color' // ValueBufferType is inherited
  21589. // DefaultInterpolation is inherited
  21590. // Note: Very basic implementation and nothing special yet.
  21591. // However, this is the place for color space parameterization.
  21592. });
  21593. /**
  21594. * A Track of numeric keyframe values.
  21595. */
  21596. function NumberKeyframeTrack(name, times, values, interpolation) {
  21597. KeyframeTrack.call(this, name, times, values, interpolation);
  21598. }
  21599. NumberKeyframeTrack.prototype = Object.assign(Object.create(KeyframeTrack.prototype), {
  21600. constructor: NumberKeyframeTrack,
  21601. ValueTypeName: 'number' // ValueBufferType is inherited
  21602. // DefaultInterpolation is inherited
  21603. });
  21604. /**
  21605. * Spherical linear unit quaternion interpolant.
  21606. */
  21607. function QuaternionLinearInterpolant(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  21608. Interpolant.call(this, parameterPositions, sampleValues, sampleSize, resultBuffer);
  21609. }
  21610. QuaternionLinearInterpolant.prototype = Object.assign(Object.create(Interpolant.prototype), {
  21611. constructor: QuaternionLinearInterpolant,
  21612. interpolate_: function (i1, t0, t, t1) {
  21613. const result = this.resultBuffer,
  21614. values = this.sampleValues,
  21615. stride = this.valueSize,
  21616. alpha = (t - t0) / (t1 - t0);
  21617. let offset = i1 * stride;
  21618. for (let end = offset + stride; offset !== end; offset += 4) {
  21619. Quaternion.slerpFlat(result, 0, values, offset - stride, values, offset, alpha);
  21620. }
  21621. return result;
  21622. }
  21623. });
  21624. /**
  21625. * A Track of quaternion keyframe values.
  21626. */
  21627. function QuaternionKeyframeTrack(name, times, values, interpolation) {
  21628. KeyframeTrack.call(this, name, times, values, interpolation);
  21629. }
  21630. QuaternionKeyframeTrack.prototype = Object.assign(Object.create(KeyframeTrack.prototype), {
  21631. constructor: QuaternionKeyframeTrack,
  21632. ValueTypeName: 'quaternion',
  21633. // ValueBufferType is inherited
  21634. DefaultInterpolation: InterpolateLinear,
  21635. InterpolantFactoryMethodLinear: function (result) {
  21636. return new QuaternionLinearInterpolant(this.times, this.values, this.getValueSize(), result);
  21637. },
  21638. InterpolantFactoryMethodSmooth: undefined // not yet implemented
  21639. });
  21640. /**
  21641. * A Track that interpolates Strings
  21642. */
  21643. function StringKeyframeTrack(name, times, values, interpolation) {
  21644. KeyframeTrack.call(this, name, times, values, interpolation);
  21645. }
  21646. StringKeyframeTrack.prototype = Object.assign(Object.create(KeyframeTrack.prototype), {
  21647. constructor: StringKeyframeTrack,
  21648. ValueTypeName: 'string',
  21649. ValueBufferType: Array,
  21650. DefaultInterpolation: InterpolateDiscrete,
  21651. InterpolantFactoryMethodLinear: undefined,
  21652. InterpolantFactoryMethodSmooth: undefined
  21653. });
  21654. /**
  21655. * A Track of vectored keyframe values.
  21656. */
  21657. function VectorKeyframeTrack(name, times, values, interpolation) {
  21658. KeyframeTrack.call(this, name, times, values, interpolation);
  21659. }
  21660. VectorKeyframeTrack.prototype = Object.assign(Object.create(KeyframeTrack.prototype), {
  21661. constructor: VectorKeyframeTrack,
  21662. ValueTypeName: 'vector' // ValueBufferType is inherited
  21663. // DefaultInterpolation is inherited
  21664. });
  21665. function AnimationClip(name, duration, tracks, blendMode) {
  21666. this.name = name;
  21667. this.tracks = tracks;
  21668. this.duration = duration !== undefined ? duration : -1;
  21669. this.blendMode = blendMode !== undefined ? blendMode : NormalAnimationBlendMode;
  21670. this.uuid = MathUtils.generateUUID(); // this means it should figure out its duration by scanning the tracks
  21671. if (this.duration < 0) {
  21672. this.resetDuration();
  21673. }
  21674. }
  21675. function getTrackTypeForValueTypeName(typeName) {
  21676. switch (typeName.toLowerCase()) {
  21677. case 'scalar':
  21678. case 'double':
  21679. case 'float':
  21680. case 'number':
  21681. case 'integer':
  21682. return NumberKeyframeTrack;
  21683. case 'vector':
  21684. case 'vector2':
  21685. case 'vector3':
  21686. case 'vector4':
  21687. return VectorKeyframeTrack;
  21688. case 'color':
  21689. return ColorKeyframeTrack;
  21690. case 'quaternion':
  21691. return QuaternionKeyframeTrack;
  21692. case 'bool':
  21693. case 'boolean':
  21694. return BooleanKeyframeTrack;
  21695. case 'string':
  21696. return StringKeyframeTrack;
  21697. }
  21698. throw new Error('THREE.KeyframeTrack: Unsupported typeName: ' + typeName);
  21699. }
  21700. function parseKeyframeTrack(json) {
  21701. if (json.type === undefined) {
  21702. throw new Error('THREE.KeyframeTrack: track type undefined, can not parse');
  21703. }
  21704. const trackType = getTrackTypeForValueTypeName(json.type);
  21705. if (json.times === undefined) {
  21706. const times = [],
  21707. values = [];
  21708. AnimationUtils.flattenJSON(json.keys, times, values, 'value');
  21709. json.times = times;
  21710. json.values = values;
  21711. } // derived classes can define a static parse method
  21712. if (trackType.parse !== undefined) {
  21713. return trackType.parse(json);
  21714. } else {
  21715. // by default, we assume a constructor compatible with the base
  21716. return new trackType(json.name, json.times, json.values, json.interpolation);
  21717. }
  21718. }
  21719. Object.assign(AnimationClip, {
  21720. parse: function (json) {
  21721. const tracks = [],
  21722. jsonTracks = json.tracks,
  21723. frameTime = 1.0 / (json.fps || 1.0);
  21724. for (let i = 0, n = jsonTracks.length; i !== n; ++i) {
  21725. tracks.push(parseKeyframeTrack(jsonTracks[i]).scale(frameTime));
  21726. }
  21727. const clip = new AnimationClip(json.name, json.duration, tracks, json.blendMode);
  21728. clip.uuid = json.uuid;
  21729. return clip;
  21730. },
  21731. toJSON: function (clip) {
  21732. const tracks = [],
  21733. clipTracks = clip.tracks;
  21734. const json = {
  21735. 'name': clip.name,
  21736. 'duration': clip.duration,
  21737. 'tracks': tracks,
  21738. 'uuid': clip.uuid,
  21739. 'blendMode': clip.blendMode
  21740. };
  21741. for (let i = 0, n = clipTracks.length; i !== n; ++i) {
  21742. tracks.push(KeyframeTrack.toJSON(clipTracks[i]));
  21743. }
  21744. return json;
  21745. },
  21746. CreateFromMorphTargetSequence: function (name, morphTargetSequence, fps, noLoop) {
  21747. const numMorphTargets = morphTargetSequence.length;
  21748. const tracks = [];
  21749. for (let i = 0; i < numMorphTargets; i++) {
  21750. let times = [];
  21751. let values = [];
  21752. times.push((i + numMorphTargets - 1) % numMorphTargets, i, (i + 1) % numMorphTargets);
  21753. values.push(0, 1, 0);
  21754. const order = AnimationUtils.getKeyframeOrder(times);
  21755. times = AnimationUtils.sortedArray(times, 1, order);
  21756. values = AnimationUtils.sortedArray(values, 1, order); // if there is a key at the first frame, duplicate it as the
  21757. // last frame as well for perfect loop.
  21758. if (!noLoop && times[0] === 0) {
  21759. times.push(numMorphTargets);
  21760. values.push(values[0]);
  21761. }
  21762. tracks.push(new NumberKeyframeTrack('.morphTargetInfluences[' + morphTargetSequence[i].name + ']', times, values).scale(1.0 / fps));
  21763. }
  21764. return new AnimationClip(name, -1, tracks);
  21765. },
  21766. findByName: function (objectOrClipArray, name) {
  21767. let clipArray = objectOrClipArray;
  21768. if (!Array.isArray(objectOrClipArray)) {
  21769. const o = objectOrClipArray;
  21770. clipArray = o.geometry && o.geometry.animations || o.animations;
  21771. }
  21772. for (let i = 0; i < clipArray.length; i++) {
  21773. if (clipArray[i].name === name) {
  21774. return clipArray[i];
  21775. }
  21776. }
  21777. return null;
  21778. },
  21779. CreateClipsFromMorphTargetSequences: function (morphTargets, fps, noLoop) {
  21780. const animationToMorphTargets = {}; // tested with https://regex101.com/ on trick sequences
  21781. // such flamingo_flyA_003, flamingo_run1_003, crdeath0059
  21782. const pattern = /^([\w-]*?)([\d]+)$/; // sort morph target names into animation groups based
  21783. // patterns like Walk_001, Walk_002, Run_001, Run_002
  21784. for (let i = 0, il = morphTargets.length; i < il; i++) {
  21785. const morphTarget = morphTargets[i];
  21786. const parts = morphTarget.name.match(pattern);
  21787. if (parts && parts.length > 1) {
  21788. const name = parts[1];
  21789. let animationMorphTargets = animationToMorphTargets[name];
  21790. if (!animationMorphTargets) {
  21791. animationToMorphTargets[name] = animationMorphTargets = [];
  21792. }
  21793. animationMorphTargets.push(morphTarget);
  21794. }
  21795. }
  21796. const clips = [];
  21797. for (const name in animationToMorphTargets) {
  21798. clips.push(AnimationClip.CreateFromMorphTargetSequence(name, animationToMorphTargets[name], fps, noLoop));
  21799. }
  21800. return clips;
  21801. },
  21802. // parse the animation.hierarchy format
  21803. parseAnimation: function (animation, bones) {
  21804. if (!animation) {
  21805. console.error('THREE.AnimationClip: No animation in JSONLoader data.');
  21806. return null;
  21807. }
  21808. const addNonemptyTrack = function (trackType, trackName, animationKeys, propertyName, destTracks) {
  21809. // only return track if there are actually keys.
  21810. if (animationKeys.length !== 0) {
  21811. const times = [];
  21812. const values = [];
  21813. AnimationUtils.flattenJSON(animationKeys, times, values, propertyName); // empty keys are filtered out, so check again
  21814. if (times.length !== 0) {
  21815. destTracks.push(new trackType(trackName, times, values));
  21816. }
  21817. }
  21818. };
  21819. const tracks = [];
  21820. const clipName = animation.name || 'default';
  21821. const fps = animation.fps || 30;
  21822. const blendMode = animation.blendMode; // automatic length determination in AnimationClip.
  21823. let duration = animation.length || -1;
  21824. const hierarchyTracks = animation.hierarchy || [];
  21825. for (let h = 0; h < hierarchyTracks.length; h++) {
  21826. const animationKeys = hierarchyTracks[h].keys; // skip empty tracks
  21827. if (!animationKeys || animationKeys.length === 0) continue; // process morph targets
  21828. if (animationKeys[0].morphTargets) {
  21829. // figure out all morph targets used in this track
  21830. const morphTargetNames = {};
  21831. let k;
  21832. for (k = 0; k < animationKeys.length; k++) {
  21833. if (animationKeys[k].morphTargets) {
  21834. for (let m = 0; m < animationKeys[k].morphTargets.length; m++) {
  21835. morphTargetNames[animationKeys[k].morphTargets[m]] = -1;
  21836. }
  21837. }
  21838. } // create a track for each morph target with all zero
  21839. // morphTargetInfluences except for the keys in which
  21840. // the morphTarget is named.
  21841. for (const morphTargetName in morphTargetNames) {
  21842. const times = [];
  21843. const values = [];
  21844. for (let m = 0; m !== animationKeys[k].morphTargets.length; ++m) {
  21845. const animationKey = animationKeys[k];
  21846. times.push(animationKey.time);
  21847. values.push(animationKey.morphTarget === morphTargetName ? 1 : 0);
  21848. }
  21849. tracks.push(new NumberKeyframeTrack('.morphTargetInfluence[' + morphTargetName + ']', times, values));
  21850. }
  21851. duration = morphTargetNames.length * (fps || 1.0);
  21852. } else {
  21853. // ...assume skeletal animation
  21854. const boneName = '.bones[' + bones[h].name + ']';
  21855. addNonemptyTrack(VectorKeyframeTrack, boneName + '.position', animationKeys, 'pos', tracks);
  21856. addNonemptyTrack(QuaternionKeyframeTrack, boneName + '.quaternion', animationKeys, 'rot', tracks);
  21857. addNonemptyTrack(VectorKeyframeTrack, boneName + '.scale', animationKeys, 'scl', tracks);
  21858. }
  21859. }
  21860. if (tracks.length === 0) {
  21861. return null;
  21862. }
  21863. const clip = new AnimationClip(clipName, duration, tracks, blendMode);
  21864. return clip;
  21865. }
  21866. });
  21867. Object.assign(AnimationClip.prototype, {
  21868. resetDuration: function () {
  21869. const tracks = this.tracks;
  21870. let duration = 0;
  21871. for (let i = 0, n = tracks.length; i !== n; ++i) {
  21872. const track = this.tracks[i];
  21873. duration = Math.max(duration, track.times[track.times.length - 1]);
  21874. }
  21875. this.duration = duration;
  21876. return this;
  21877. },
  21878. trim: function () {
  21879. for (let i = 0; i < this.tracks.length; i++) {
  21880. this.tracks[i].trim(0, this.duration);
  21881. }
  21882. return this;
  21883. },
  21884. validate: function () {
  21885. let valid = true;
  21886. for (let i = 0; i < this.tracks.length; i++) {
  21887. valid = valid && this.tracks[i].validate();
  21888. }
  21889. return valid;
  21890. },
  21891. optimize: function () {
  21892. for (let i = 0; i < this.tracks.length; i++) {
  21893. this.tracks[i].optimize();
  21894. }
  21895. return this;
  21896. },
  21897. clone: function () {
  21898. const tracks = [];
  21899. for (let i = 0; i < this.tracks.length; i++) {
  21900. tracks.push(this.tracks[i].clone());
  21901. }
  21902. return new AnimationClip(this.name, this.duration, tracks, this.blendMode);
  21903. },
  21904. toJSON: function () {
  21905. return AnimationClip.toJSON(this);
  21906. }
  21907. });
  21908. const Cache = {
  21909. enabled: false,
  21910. files: {},
  21911. add: function (key, file) {
  21912. if (this.enabled === false) return; // console.log( 'THREE.Cache', 'Adding key:', key );
  21913. this.files[key] = file;
  21914. },
  21915. get: function (key) {
  21916. if (this.enabled === false) return; // console.log( 'THREE.Cache', 'Checking key:', key );
  21917. return this.files[key];
  21918. },
  21919. remove: function (key) {
  21920. delete this.files[key];
  21921. },
  21922. clear: function () {
  21923. this.files = {};
  21924. }
  21925. };
  21926. exports.Cache = Cache;
  21927. function LoadingManager(onLoad, onProgress, onError) {
  21928. const scope = this;
  21929. let isLoading = false;
  21930. let itemsLoaded = 0;
  21931. let itemsTotal = 0;
  21932. let urlModifier = undefined;
  21933. const handlers = []; // Refer to #5689 for the reason why we don't set .onStart
  21934. // in the constructor
  21935. this.onStart = undefined;
  21936. this.onLoad = onLoad;
  21937. this.onProgress = onProgress;
  21938. this.onError = onError;
  21939. this.itemStart = function (url) {
  21940. itemsTotal++;
  21941. if (isLoading === false) {
  21942. if (scope.onStart !== undefined) {
  21943. scope.onStart(url, itemsLoaded, itemsTotal);
  21944. }
  21945. }
  21946. isLoading = true;
  21947. };
  21948. this.itemEnd = function (url) {
  21949. itemsLoaded++;
  21950. if (scope.onProgress !== undefined) {
  21951. scope.onProgress(url, itemsLoaded, itemsTotal);
  21952. }
  21953. if (itemsLoaded === itemsTotal) {
  21954. isLoading = false;
  21955. if (scope.onLoad !== undefined) {
  21956. scope.onLoad();
  21957. }
  21958. }
  21959. };
  21960. this.itemError = function (url) {
  21961. if (scope.onError !== undefined) {
  21962. scope.onError(url);
  21963. }
  21964. };
  21965. this.resolveURL = function (url) {
  21966. if (urlModifier) {
  21967. return urlModifier(url);
  21968. }
  21969. return url;
  21970. };
  21971. this.setURLModifier = function (transform) {
  21972. urlModifier = transform;
  21973. return this;
  21974. };
  21975. this.addHandler = function (regex, loader) {
  21976. handlers.push(regex, loader);
  21977. return this;
  21978. };
  21979. this.removeHandler = function (regex) {
  21980. const index = handlers.indexOf(regex);
  21981. if (index !== -1) {
  21982. handlers.splice(index, 2);
  21983. }
  21984. return this;
  21985. };
  21986. this.getHandler = function (file) {
  21987. for (let i = 0, l = handlers.length; i < l; i += 2) {
  21988. const regex = handlers[i];
  21989. const loader = handlers[i + 1];
  21990. if (regex.global) regex.lastIndex = 0; // see #17920
  21991. if (regex.test(file)) {
  21992. return loader;
  21993. }
  21994. }
  21995. return null;
  21996. };
  21997. }
  21998. const DefaultLoadingManager = new LoadingManager();
  21999. exports.DefaultLoadingManager = DefaultLoadingManager;
  22000. function Loader(manager) {
  22001. this.manager = manager !== undefined ? manager : DefaultLoadingManager;
  22002. this.crossOrigin = 'anonymous';
  22003. this.withCredentials = false;
  22004. this.path = '';
  22005. this.resourcePath = '';
  22006. this.requestHeader = {};
  22007. }
  22008. Object.assign(Loader.prototype, {
  22009. load: function ()
  22010. /* url, onLoad, onProgress, onError */
  22011. {},
  22012. loadAsync: function (url, onProgress) {
  22013. const scope = this;
  22014. return new Promise(function (resolve, reject) {
  22015. scope.load(url, resolve, onProgress, reject);
  22016. });
  22017. },
  22018. parse: function ()
  22019. /* data */
  22020. {},
  22021. setCrossOrigin: function (crossOrigin) {
  22022. this.crossOrigin = crossOrigin;
  22023. return this;
  22024. },
  22025. setWithCredentials: function (value) {
  22026. this.withCredentials = value;
  22027. return this;
  22028. },
  22029. setPath: function (path) {
  22030. this.path = path;
  22031. return this;
  22032. },
  22033. setResourcePath: function (resourcePath) {
  22034. this.resourcePath = resourcePath;
  22035. return this;
  22036. },
  22037. setRequestHeader: function (requestHeader) {
  22038. this.requestHeader = requestHeader;
  22039. return this;
  22040. }
  22041. });
  22042. const loading = {};
  22043. function FileLoader(manager) {
  22044. Loader.call(this, manager);
  22045. }
  22046. FileLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  22047. constructor: FileLoader,
  22048. load: function (url, onLoad, onProgress, onError) {
  22049. if (url === undefined) url = '';
  22050. if (this.path !== undefined) url = this.path + url;
  22051. url = this.manager.resolveURL(url);
  22052. const scope = this;
  22053. const cached = Cache.get(url);
  22054. if (cached !== undefined) {
  22055. scope.manager.itemStart(url);
  22056. setTimeout(function () {
  22057. if (onLoad) onLoad(cached);
  22058. scope.manager.itemEnd(url);
  22059. }, 0);
  22060. return cached;
  22061. } // Check if request is duplicate
  22062. if (loading[url] !== undefined) {
  22063. loading[url].push({
  22064. onLoad: onLoad,
  22065. onProgress: onProgress,
  22066. onError: onError
  22067. });
  22068. return;
  22069. } // Check for data: URI
  22070. const dataUriRegex = /^data:(.*?)(;base64)?,(.*)$/;
  22071. const dataUriRegexResult = url.match(dataUriRegex);
  22072. let request; // Safari can not handle Data URIs through XMLHttpRequest so process manually
  22073. if (dataUriRegexResult) {
  22074. const mimeType = dataUriRegexResult[1];
  22075. const isBase64 = !!dataUriRegexResult[2];
  22076. let data = dataUriRegexResult[3];
  22077. data = decodeURIComponent(data);
  22078. if (isBase64) data = atob(data);
  22079. try {
  22080. let response;
  22081. const responseType = (this.responseType || '').toLowerCase();
  22082. switch (responseType) {
  22083. case 'arraybuffer':
  22084. case 'blob':
  22085. const view = new Uint8Array(data.length);
  22086. for (let i = 0; i < data.length; i++) {
  22087. view[i] = data.charCodeAt(i);
  22088. }
  22089. if (responseType === 'blob') {
  22090. response = new Blob([view.buffer], {
  22091. type: mimeType
  22092. });
  22093. } else {
  22094. response = view.buffer;
  22095. }
  22096. break;
  22097. case 'document':
  22098. const parser = new DOMParser();
  22099. response = parser.parseFromString(data, mimeType);
  22100. break;
  22101. case 'json':
  22102. response = JSON.parse(data);
  22103. break;
  22104. default:
  22105. // 'text' or other
  22106. response = data;
  22107. break;
  22108. } // Wait for next browser tick like standard XMLHttpRequest event dispatching does
  22109. setTimeout(function () {
  22110. if (onLoad) onLoad(response);
  22111. scope.manager.itemEnd(url);
  22112. }, 0);
  22113. } catch (error) {
  22114. // Wait for next browser tick like standard XMLHttpRequest event dispatching does
  22115. setTimeout(function () {
  22116. if (onError) onError(error);
  22117. scope.manager.itemError(url);
  22118. scope.manager.itemEnd(url);
  22119. }, 0);
  22120. }
  22121. } else {
  22122. // Initialise array for duplicate requests
  22123. loading[url] = [];
  22124. loading[url].push({
  22125. onLoad: onLoad,
  22126. onProgress: onProgress,
  22127. onError: onError
  22128. });
  22129. request = new XMLHttpRequest();
  22130. request.open('GET', url, true);
  22131. request.addEventListener('load', function (event) {
  22132. const response = this.response;
  22133. const callbacks = loading[url];
  22134. delete loading[url];
  22135. if (this.status === 200 || this.status === 0) {
  22136. // Some browsers return HTTP Status 0 when using non-http protocol
  22137. // e.g. 'file://' or 'data://'. Handle as success.
  22138. if (this.status === 0) console.warn('THREE.FileLoader: HTTP Status 0 received.'); // Add to cache only on HTTP success, so that we do not cache
  22139. // error response bodies as proper responses to requests.
  22140. Cache.add(url, response);
  22141. for (let i = 0, il = callbacks.length; i < il; i++) {
  22142. const callback = callbacks[i];
  22143. if (callback.onLoad) callback.onLoad(response);
  22144. }
  22145. scope.manager.itemEnd(url);
  22146. } else {
  22147. for (let i = 0, il = callbacks.length; i < il; i++) {
  22148. const callback = callbacks[i];
  22149. if (callback.onError) callback.onError(event);
  22150. }
  22151. scope.manager.itemError(url);
  22152. scope.manager.itemEnd(url);
  22153. }
  22154. }, false);
  22155. request.addEventListener('progress', function (event) {
  22156. const callbacks = loading[url];
  22157. for (let i = 0, il = callbacks.length; i < il; i++) {
  22158. const callback = callbacks[i];
  22159. if (callback.onProgress) callback.onProgress(event);
  22160. }
  22161. }, false);
  22162. request.addEventListener('error', function (event) {
  22163. const callbacks = loading[url];
  22164. delete loading[url];
  22165. for (let i = 0, il = callbacks.length; i < il; i++) {
  22166. const callback = callbacks[i];
  22167. if (callback.onError) callback.onError(event);
  22168. }
  22169. scope.manager.itemError(url);
  22170. scope.manager.itemEnd(url);
  22171. }, false);
  22172. request.addEventListener('abort', function (event) {
  22173. const callbacks = loading[url];
  22174. delete loading[url];
  22175. for (let i = 0, il = callbacks.length; i < il; i++) {
  22176. const callback = callbacks[i];
  22177. if (callback.onError) callback.onError(event);
  22178. }
  22179. scope.manager.itemError(url);
  22180. scope.manager.itemEnd(url);
  22181. }, false);
  22182. if (this.responseType !== undefined) request.responseType = this.responseType;
  22183. if (this.withCredentials !== undefined) request.withCredentials = this.withCredentials;
  22184. if (request.overrideMimeType) request.overrideMimeType(this.mimeType !== undefined ? this.mimeType : 'text/plain');
  22185. for (const header in this.requestHeader) {
  22186. request.setRequestHeader(header, this.requestHeader[header]);
  22187. }
  22188. request.send(null);
  22189. }
  22190. scope.manager.itemStart(url);
  22191. return request;
  22192. },
  22193. setResponseType: function (value) {
  22194. this.responseType = value;
  22195. return this;
  22196. },
  22197. setMimeType: function (value) {
  22198. this.mimeType = value;
  22199. return this;
  22200. }
  22201. });
  22202. function AnimationLoader(manager) {
  22203. Loader.call(this, manager);
  22204. }
  22205. AnimationLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  22206. constructor: AnimationLoader,
  22207. load: function (url, onLoad, onProgress, onError) {
  22208. const scope = this;
  22209. const loader = new FileLoader(scope.manager);
  22210. loader.setPath(scope.path);
  22211. loader.setRequestHeader(scope.requestHeader);
  22212. loader.setWithCredentials(scope.withCredentials);
  22213. loader.load(url, function (text) {
  22214. try {
  22215. onLoad(scope.parse(JSON.parse(text)));
  22216. } catch (e) {
  22217. if (onError) {
  22218. onError(e);
  22219. } else {
  22220. console.error(e);
  22221. }
  22222. scope.manager.itemError(url);
  22223. }
  22224. }, onProgress, onError);
  22225. },
  22226. parse: function (json) {
  22227. const animations = [];
  22228. for (let i = 0; i < json.length; i++) {
  22229. const clip = AnimationClip.parse(json[i]);
  22230. animations.push(clip);
  22231. }
  22232. return animations;
  22233. }
  22234. });
  22235. /**
  22236. * Abstract Base class to block based textures loader (dds, pvr, ...)
  22237. *
  22238. * Sub classes have to implement the parse() method which will be used in load().
  22239. */
  22240. function CompressedTextureLoader(manager) {
  22241. Loader.call(this, manager);
  22242. }
  22243. CompressedTextureLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  22244. constructor: CompressedTextureLoader,
  22245. load: function (url, onLoad, onProgress, onError) {
  22246. const scope = this;
  22247. const images = [];
  22248. const texture = new CompressedTexture();
  22249. texture.image = images;
  22250. const loader = new FileLoader(this.manager);
  22251. loader.setPath(this.path);
  22252. loader.setResponseType('arraybuffer');
  22253. loader.setRequestHeader(this.requestHeader);
  22254. loader.setWithCredentials(scope.withCredentials);
  22255. let loaded = 0;
  22256. function loadTexture(i) {
  22257. loader.load(url[i], function (buffer) {
  22258. const texDatas = scope.parse(buffer, true);
  22259. images[i] = {
  22260. width: texDatas.width,
  22261. height: texDatas.height,
  22262. format: texDatas.format,
  22263. mipmaps: texDatas.mipmaps
  22264. };
  22265. loaded += 1;
  22266. if (loaded === 6) {
  22267. if (texDatas.mipmapCount === 1) texture.minFilter = LinearFilter;
  22268. texture.format = texDatas.format;
  22269. texture.needsUpdate = true;
  22270. if (onLoad) onLoad(texture);
  22271. }
  22272. }, onProgress, onError);
  22273. }
  22274. if (Array.isArray(url)) {
  22275. for (let i = 0, il = url.length; i < il; ++i) {
  22276. loadTexture(i);
  22277. }
  22278. } else {
  22279. // compressed cubemap texture stored in a single DDS file
  22280. loader.load(url, function (buffer) {
  22281. const texDatas = scope.parse(buffer, true);
  22282. if (texDatas.isCubemap) {
  22283. const faces = texDatas.mipmaps.length / texDatas.mipmapCount;
  22284. for (let f = 0; f < faces; f++) {
  22285. images[f] = {
  22286. mipmaps: []
  22287. };
  22288. for (let i = 0; i < texDatas.mipmapCount; i++) {
  22289. images[f].mipmaps.push(texDatas.mipmaps[f * texDatas.mipmapCount + i]);
  22290. images[f].format = texDatas.format;
  22291. images[f].width = texDatas.width;
  22292. images[f].height = texDatas.height;
  22293. }
  22294. }
  22295. } else {
  22296. texture.image.width = texDatas.width;
  22297. texture.image.height = texDatas.height;
  22298. texture.mipmaps = texDatas.mipmaps;
  22299. }
  22300. if (texDatas.mipmapCount === 1) {
  22301. texture.minFilter = LinearFilter;
  22302. }
  22303. texture.format = texDatas.format;
  22304. texture.needsUpdate = true;
  22305. if (onLoad) onLoad(texture);
  22306. }, onProgress, onError);
  22307. }
  22308. return texture;
  22309. }
  22310. });
  22311. function ImageLoader(manager) {
  22312. Loader.call(this, manager);
  22313. }
  22314. ImageLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  22315. constructor: ImageLoader,
  22316. load: function (url, onLoad, onProgress, onError) {
  22317. if (this.path !== undefined) url = this.path + url;
  22318. url = this.manager.resolveURL(url);
  22319. const scope = this;
  22320. const cached = Cache.get(url);
  22321. if (cached !== undefined) {
  22322. scope.manager.itemStart(url);
  22323. setTimeout(function () {
  22324. if (onLoad) onLoad(cached);
  22325. scope.manager.itemEnd(url);
  22326. }, 0);
  22327. return cached;
  22328. }
  22329. const image = document.createElementNS('http://www.w3.org/1999/xhtml', 'img');
  22330. function onImageLoad() {
  22331. image.removeEventListener('load', onImageLoad, false);
  22332. image.removeEventListener('error', onImageError, false);
  22333. Cache.add(url, this);
  22334. if (onLoad) onLoad(this);
  22335. scope.manager.itemEnd(url);
  22336. }
  22337. function onImageError(event) {
  22338. image.removeEventListener('load', onImageLoad, false);
  22339. image.removeEventListener('error', onImageError, false);
  22340. if (onError) onError(event);
  22341. scope.manager.itemError(url);
  22342. scope.manager.itemEnd(url);
  22343. }
  22344. image.addEventListener('load', onImageLoad, false);
  22345. image.addEventListener('error', onImageError, false);
  22346. if (url.substr(0, 5) !== 'data:') {
  22347. if (this.crossOrigin !== undefined) image.crossOrigin = this.crossOrigin;
  22348. }
  22349. scope.manager.itemStart(url);
  22350. image.src = url;
  22351. return image;
  22352. }
  22353. });
  22354. function CubeTextureLoader(manager) {
  22355. Loader.call(this, manager);
  22356. }
  22357. CubeTextureLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  22358. constructor: CubeTextureLoader,
  22359. load: function (urls, onLoad, onProgress, onError) {
  22360. const texture = new CubeTexture();
  22361. const loader = new ImageLoader(this.manager);
  22362. loader.setCrossOrigin(this.crossOrigin);
  22363. loader.setPath(this.path);
  22364. let loaded = 0;
  22365. function loadTexture(i) {
  22366. loader.load(urls[i], function (image) {
  22367. texture.images[i] = image;
  22368. loaded++;
  22369. if (loaded === 6) {
  22370. texture.needsUpdate = true;
  22371. if (onLoad) onLoad(texture);
  22372. }
  22373. }, undefined, onError);
  22374. }
  22375. for (let i = 0; i < urls.length; ++i) {
  22376. loadTexture(i);
  22377. }
  22378. return texture;
  22379. }
  22380. });
  22381. /**
  22382. * Abstract Base class to load generic binary textures formats (rgbe, hdr, ...)
  22383. *
  22384. * Sub classes have to implement the parse() method which will be used in load().
  22385. */
  22386. function DataTextureLoader(manager) {
  22387. Loader.call(this, manager);
  22388. }
  22389. DataTextureLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  22390. constructor: DataTextureLoader,
  22391. load: function (url, onLoad, onProgress, onError) {
  22392. const scope = this;
  22393. const texture = new DataTexture();
  22394. const loader = new FileLoader(this.manager);
  22395. loader.setResponseType('arraybuffer');
  22396. loader.setRequestHeader(this.requestHeader);
  22397. loader.setPath(this.path);
  22398. loader.setWithCredentials(scope.withCredentials);
  22399. loader.load(url, function (buffer) {
  22400. const texData = scope.parse(buffer);
  22401. if (!texData) return;
  22402. if (texData.image !== undefined) {
  22403. texture.image = texData.image;
  22404. } else if (texData.data !== undefined) {
  22405. texture.image.width = texData.width;
  22406. texture.image.height = texData.height;
  22407. texture.image.data = texData.data;
  22408. }
  22409. texture.wrapS = texData.wrapS !== undefined ? texData.wrapS : ClampToEdgeWrapping;
  22410. texture.wrapT = texData.wrapT !== undefined ? texData.wrapT : ClampToEdgeWrapping;
  22411. texture.magFilter = texData.magFilter !== undefined ? texData.magFilter : LinearFilter;
  22412. texture.minFilter = texData.minFilter !== undefined ? texData.minFilter : LinearFilter;
  22413. texture.anisotropy = texData.anisotropy !== undefined ? texData.anisotropy : 1;
  22414. if (texData.format !== undefined) {
  22415. texture.format = texData.format;
  22416. }
  22417. if (texData.type !== undefined) {
  22418. texture.type = texData.type;
  22419. }
  22420. if (texData.mipmaps !== undefined) {
  22421. texture.mipmaps = texData.mipmaps;
  22422. texture.minFilter = LinearMipmapLinearFilter; // presumably...
  22423. }
  22424. if (texData.mipmapCount === 1) {
  22425. texture.minFilter = LinearFilter;
  22426. }
  22427. texture.needsUpdate = true;
  22428. if (onLoad) onLoad(texture, texData);
  22429. }, onProgress, onError);
  22430. return texture;
  22431. }
  22432. });
  22433. function TextureLoader(manager) {
  22434. Loader.call(this, manager);
  22435. }
  22436. TextureLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  22437. constructor: TextureLoader,
  22438. load: function (url, onLoad, onProgress, onError) {
  22439. const texture = new Texture();
  22440. const loader = new ImageLoader(this.manager);
  22441. loader.setCrossOrigin(this.crossOrigin);
  22442. loader.setPath(this.path);
  22443. loader.load(url, function (image) {
  22444. texture.image = image; // JPEGs can't have an alpha channel, so memory can be saved by storing them as RGB.
  22445. const isJPEG = url.search(/\.jpe?g($|\?)/i) > 0 || url.search(/^data\:image\/jpeg/) === 0;
  22446. texture.format = isJPEG ? RGBFormat : RGBAFormat;
  22447. texture.needsUpdate = true;
  22448. if (onLoad !== undefined) {
  22449. onLoad(texture);
  22450. }
  22451. }, onProgress, onError);
  22452. return texture;
  22453. }
  22454. });
  22455. /**
  22456. * Extensible curve object.
  22457. *
  22458. * Some common of curve methods:
  22459. * .getPoint( t, optionalTarget ), .getTangent( t, optionalTarget )
  22460. * .getPointAt( u, optionalTarget ), .getTangentAt( u, optionalTarget )
  22461. * .getPoints(), .getSpacedPoints()
  22462. * .getLength()
  22463. * .updateArcLengths()
  22464. *
  22465. * This following curves inherit from THREE.Curve:
  22466. *
  22467. * -- 2D curves --
  22468. * THREE.ArcCurve
  22469. * THREE.CubicBezierCurve
  22470. * THREE.EllipseCurve
  22471. * THREE.LineCurve
  22472. * THREE.QuadraticBezierCurve
  22473. * THREE.SplineCurve
  22474. *
  22475. * -- 3D curves --
  22476. * THREE.CatmullRomCurve3
  22477. * THREE.CubicBezierCurve3
  22478. * THREE.LineCurve3
  22479. * THREE.QuadraticBezierCurve3
  22480. *
  22481. * A series of curves can be represented as a THREE.CurvePath.
  22482. *
  22483. **/
  22484. function Curve() {
  22485. this.type = 'Curve';
  22486. this.arcLengthDivisions = 200;
  22487. }
  22488. Object.assign(Curve.prototype, {
  22489. // Virtual base class method to overwrite and implement in subclasses
  22490. // - t [0 .. 1]
  22491. getPoint: function ()
  22492. /* t, optionalTarget */
  22493. {
  22494. console.warn('THREE.Curve: .getPoint() not implemented.');
  22495. return null;
  22496. },
  22497. // Get point at relative position in curve according to arc length
  22498. // - u [0 .. 1]
  22499. getPointAt: function (u, optionalTarget) {
  22500. const t = this.getUtoTmapping(u);
  22501. return this.getPoint(t, optionalTarget);
  22502. },
  22503. // Get sequence of points using getPoint( t )
  22504. getPoints: function (divisions = 5) {
  22505. const points = [];
  22506. for (let d = 0; d <= divisions; d++) {
  22507. points.push(this.getPoint(d / divisions));
  22508. }
  22509. return points;
  22510. },
  22511. // Get sequence of points using getPointAt( u )
  22512. getSpacedPoints: function (divisions = 5) {
  22513. const points = [];
  22514. for (let d = 0; d <= divisions; d++) {
  22515. points.push(this.getPointAt(d / divisions));
  22516. }
  22517. return points;
  22518. },
  22519. // Get total curve arc length
  22520. getLength: function () {
  22521. const lengths = this.getLengths();
  22522. return lengths[lengths.length - 1];
  22523. },
  22524. // Get list of cumulative segment lengths
  22525. getLengths: function (divisions) {
  22526. if (divisions === undefined) divisions = this.arcLengthDivisions;
  22527. if (this.cacheArcLengths && this.cacheArcLengths.length === divisions + 1 && !this.needsUpdate) {
  22528. return this.cacheArcLengths;
  22529. }
  22530. this.needsUpdate = false;
  22531. const cache = [];
  22532. let current,
  22533. last = this.getPoint(0);
  22534. let sum = 0;
  22535. cache.push(0);
  22536. for (let p = 1; p <= divisions; p++) {
  22537. current = this.getPoint(p / divisions);
  22538. sum += current.distanceTo(last);
  22539. cache.push(sum);
  22540. last = current;
  22541. }
  22542. this.cacheArcLengths = cache;
  22543. return cache; // { sums: cache, sum: sum }; Sum is in the last element.
  22544. },
  22545. updateArcLengths: function () {
  22546. this.needsUpdate = true;
  22547. this.getLengths();
  22548. },
  22549. // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equidistant
  22550. getUtoTmapping: function (u, distance) {
  22551. const arcLengths = this.getLengths();
  22552. let i = 0;
  22553. const il = arcLengths.length;
  22554. let targetArcLength; // The targeted u distance value to get
  22555. if (distance) {
  22556. targetArcLength = distance;
  22557. } else {
  22558. targetArcLength = u * arcLengths[il - 1];
  22559. } // binary search for the index with largest value smaller than target u distance
  22560. let low = 0,
  22561. high = il - 1,
  22562. comparison;
  22563. while (low <= high) {
  22564. i = Math.floor(low + (high - low) / 2); // less likely to overflow, though probably not issue here, JS doesn't really have integers, all numbers are floats
  22565. comparison = arcLengths[i] - targetArcLength;
  22566. if (comparison < 0) {
  22567. low = i + 1;
  22568. } else if (comparison > 0) {
  22569. high = i - 1;
  22570. } else {
  22571. high = i;
  22572. break; // DONE
  22573. }
  22574. }
  22575. i = high;
  22576. if (arcLengths[i] === targetArcLength) {
  22577. return i / (il - 1);
  22578. } // we could get finer grain at lengths, or use simple interpolation between two points
  22579. const lengthBefore = arcLengths[i];
  22580. const lengthAfter = arcLengths[i + 1];
  22581. const segmentLength = lengthAfter - lengthBefore; // determine where we are between the 'before' and 'after' points
  22582. const segmentFraction = (targetArcLength - lengthBefore) / segmentLength; // add that fractional amount to t
  22583. const t = (i + segmentFraction) / (il - 1);
  22584. return t;
  22585. },
  22586. // Returns a unit vector tangent at t
  22587. // In case any sub curve does not implement its tangent derivation,
  22588. // 2 points a small delta apart will be used to find its gradient
  22589. // which seems to give a reasonable approximation
  22590. getTangent: function (t, optionalTarget) {
  22591. const delta = 0.0001;
  22592. let t1 = t - delta;
  22593. let t2 = t + delta; // Capping in case of danger
  22594. if (t1 < 0) t1 = 0;
  22595. if (t2 > 1) t2 = 1;
  22596. const pt1 = this.getPoint(t1);
  22597. const pt2 = this.getPoint(t2);
  22598. const tangent = optionalTarget || (pt1.isVector2 ? new Vector2() : new Vector3());
  22599. tangent.copy(pt2).sub(pt1).normalize();
  22600. return tangent;
  22601. },
  22602. getTangentAt: function (u, optionalTarget) {
  22603. const t = this.getUtoTmapping(u);
  22604. return this.getTangent(t, optionalTarget);
  22605. },
  22606. computeFrenetFrames: function (segments, closed) {
  22607. // see http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  22608. const normal = new Vector3();
  22609. const tangents = [];
  22610. const normals = [];
  22611. const binormals = [];
  22612. const vec = new Vector3();
  22613. const mat = new Matrix4(); // compute the tangent vectors for each segment on the curve
  22614. for (let i = 0; i <= segments; i++) {
  22615. const u = i / segments;
  22616. tangents[i] = this.getTangentAt(u, new Vector3());
  22617. tangents[i].normalize();
  22618. } // select an initial normal vector perpendicular to the first tangent vector,
  22619. // and in the direction of the minimum tangent xyz component
  22620. normals[0] = new Vector3();
  22621. binormals[0] = new Vector3();
  22622. let min = Number.MAX_VALUE;
  22623. const tx = Math.abs(tangents[0].x);
  22624. const ty = Math.abs(tangents[0].y);
  22625. const tz = Math.abs(tangents[0].z);
  22626. if (tx <= min) {
  22627. min = tx;
  22628. normal.set(1, 0, 0);
  22629. }
  22630. if (ty <= min) {
  22631. min = ty;
  22632. normal.set(0, 1, 0);
  22633. }
  22634. if (tz <= min) {
  22635. normal.set(0, 0, 1);
  22636. }
  22637. vec.crossVectors(tangents[0], normal).normalize();
  22638. normals[0].crossVectors(tangents[0], vec);
  22639. binormals[0].crossVectors(tangents[0], normals[0]); // compute the slowly-varying normal and binormal vectors for each segment on the curve
  22640. for (let i = 1; i <= segments; i++) {
  22641. normals[i] = normals[i - 1].clone();
  22642. binormals[i] = binormals[i - 1].clone();
  22643. vec.crossVectors(tangents[i - 1], tangents[i]);
  22644. if (vec.length() > Number.EPSILON) {
  22645. vec.normalize();
  22646. const theta = Math.acos(MathUtils.clamp(tangents[i - 1].dot(tangents[i]), -1, 1)); // clamp for floating pt errors
  22647. normals[i].applyMatrix4(mat.makeRotationAxis(vec, theta));
  22648. }
  22649. binormals[i].crossVectors(tangents[i], normals[i]);
  22650. } // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  22651. if (closed === true) {
  22652. let theta = Math.acos(MathUtils.clamp(normals[0].dot(normals[segments]), -1, 1));
  22653. theta /= segments;
  22654. if (tangents[0].dot(vec.crossVectors(normals[0], normals[segments])) > 0) {
  22655. theta = -theta;
  22656. }
  22657. for (let i = 1; i <= segments; i++) {
  22658. // twist a little...
  22659. normals[i].applyMatrix4(mat.makeRotationAxis(tangents[i], theta * i));
  22660. binormals[i].crossVectors(tangents[i], normals[i]);
  22661. }
  22662. }
  22663. return {
  22664. tangents: tangents,
  22665. normals: normals,
  22666. binormals: binormals
  22667. };
  22668. },
  22669. clone: function () {
  22670. return new this.constructor().copy(this);
  22671. },
  22672. copy: function (source) {
  22673. this.arcLengthDivisions = source.arcLengthDivisions;
  22674. return this;
  22675. },
  22676. toJSON: function () {
  22677. const data = {
  22678. metadata: {
  22679. version: 4.5,
  22680. type: 'Curve',
  22681. generator: 'Curve.toJSON'
  22682. }
  22683. };
  22684. data.arcLengthDivisions = this.arcLengthDivisions;
  22685. data.type = this.type;
  22686. return data;
  22687. },
  22688. fromJSON: function (json) {
  22689. this.arcLengthDivisions = json.arcLengthDivisions;
  22690. return this;
  22691. }
  22692. });
  22693. function EllipseCurve(aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation) {
  22694. Curve.call(this);
  22695. this.type = 'EllipseCurve';
  22696. this.aX = aX || 0;
  22697. this.aY = aY || 0;
  22698. this.xRadius = xRadius || 1;
  22699. this.yRadius = yRadius || 1;
  22700. this.aStartAngle = aStartAngle || 0;
  22701. this.aEndAngle = aEndAngle || 2 * Math.PI;
  22702. this.aClockwise = aClockwise || false;
  22703. this.aRotation = aRotation || 0;
  22704. }
  22705. EllipseCurve.prototype = Object.create(Curve.prototype);
  22706. EllipseCurve.prototype.constructor = EllipseCurve;
  22707. EllipseCurve.prototype.isEllipseCurve = true;
  22708. EllipseCurve.prototype.getPoint = function (t, optionalTarget) {
  22709. const point = optionalTarget || new Vector2();
  22710. const twoPi = Math.PI * 2;
  22711. let deltaAngle = this.aEndAngle - this.aStartAngle;
  22712. const samePoints = Math.abs(deltaAngle) < Number.EPSILON; // ensures that deltaAngle is 0 .. 2 PI
  22713. while (deltaAngle < 0) deltaAngle += twoPi;
  22714. while (deltaAngle > twoPi) deltaAngle -= twoPi;
  22715. if (deltaAngle < Number.EPSILON) {
  22716. if (samePoints) {
  22717. deltaAngle = 0;
  22718. } else {
  22719. deltaAngle = twoPi;
  22720. }
  22721. }
  22722. if (this.aClockwise === true && !samePoints) {
  22723. if (deltaAngle === twoPi) {
  22724. deltaAngle = -twoPi;
  22725. } else {
  22726. deltaAngle = deltaAngle - twoPi;
  22727. }
  22728. }
  22729. const angle = this.aStartAngle + t * deltaAngle;
  22730. let x = this.aX + this.xRadius * Math.cos(angle);
  22731. let y = this.aY + this.yRadius * Math.sin(angle);
  22732. if (this.aRotation !== 0) {
  22733. const cos = Math.cos(this.aRotation);
  22734. const sin = Math.sin(this.aRotation);
  22735. const tx = x - this.aX;
  22736. const ty = y - this.aY; // Rotate the point about the center of the ellipse.
  22737. x = tx * cos - ty * sin + this.aX;
  22738. y = tx * sin + ty * cos + this.aY;
  22739. }
  22740. return point.set(x, y);
  22741. };
  22742. EllipseCurve.prototype.copy = function (source) {
  22743. Curve.prototype.copy.call(this, source);
  22744. this.aX = source.aX;
  22745. this.aY = source.aY;
  22746. this.xRadius = source.xRadius;
  22747. this.yRadius = source.yRadius;
  22748. this.aStartAngle = source.aStartAngle;
  22749. this.aEndAngle = source.aEndAngle;
  22750. this.aClockwise = source.aClockwise;
  22751. this.aRotation = source.aRotation;
  22752. return this;
  22753. };
  22754. EllipseCurve.prototype.toJSON = function () {
  22755. const data = Curve.prototype.toJSON.call(this);
  22756. data.aX = this.aX;
  22757. data.aY = this.aY;
  22758. data.xRadius = this.xRadius;
  22759. data.yRadius = this.yRadius;
  22760. data.aStartAngle = this.aStartAngle;
  22761. data.aEndAngle = this.aEndAngle;
  22762. data.aClockwise = this.aClockwise;
  22763. data.aRotation = this.aRotation;
  22764. return data;
  22765. };
  22766. EllipseCurve.prototype.fromJSON = function (json) {
  22767. Curve.prototype.fromJSON.call(this, json);
  22768. this.aX = json.aX;
  22769. this.aY = json.aY;
  22770. this.xRadius = json.xRadius;
  22771. this.yRadius = json.yRadius;
  22772. this.aStartAngle = json.aStartAngle;
  22773. this.aEndAngle = json.aEndAngle;
  22774. this.aClockwise = json.aClockwise;
  22775. this.aRotation = json.aRotation;
  22776. return this;
  22777. };
  22778. function ArcCurve(aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise) {
  22779. EllipseCurve.call(this, aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise);
  22780. this.type = 'ArcCurve';
  22781. }
  22782. ArcCurve.prototype = Object.create(EllipseCurve.prototype);
  22783. ArcCurve.prototype.constructor = ArcCurve;
  22784. ArcCurve.prototype.isArcCurve = true;
  22785. /**
  22786. * Centripetal CatmullRom Curve - which is useful for avoiding
  22787. * cusps and self-intersections in non-uniform catmull rom curves.
  22788. * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf
  22789. *
  22790. * curve.type accepts centripetal(default), chordal and catmullrom
  22791. * curve.tension is used for catmullrom which defaults to 0.5
  22792. */
  22793. /*
  22794. Based on an optimized c++ solution in
  22795. - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/
  22796. - http://ideone.com/NoEbVM
  22797. This CubicPoly class could be used for reusing some variables and calculations,
  22798. but for three.js curve use, it could be possible inlined and flatten into a single function call
  22799. which can be placed in CurveUtils.
  22800. */
  22801. function CubicPoly() {
  22802. let c0 = 0,
  22803. c1 = 0,
  22804. c2 = 0,
  22805. c3 = 0;
  22806. /*
  22807. * Compute coefficients for a cubic polynomial
  22808. * p(s) = c0 + c1*s + c2*s^2 + c3*s^3
  22809. * such that
  22810. * p(0) = x0, p(1) = x1
  22811. * and
  22812. * p'(0) = t0, p'(1) = t1.
  22813. */
  22814. function init(x0, x1, t0, t1) {
  22815. c0 = x0;
  22816. c1 = t0;
  22817. c2 = -3 * x0 + 3 * x1 - 2 * t0 - t1;
  22818. c3 = 2 * x0 - 2 * x1 + t0 + t1;
  22819. }
  22820. return {
  22821. initCatmullRom: function (x0, x1, x2, x3, tension) {
  22822. init(x1, x2, tension * (x2 - x0), tension * (x3 - x1));
  22823. },
  22824. initNonuniformCatmullRom: function (x0, x1, x2, x3, dt0, dt1, dt2) {
  22825. // compute tangents when parameterized in [t1,t2]
  22826. let t1 = (x1 - x0) / dt0 - (x2 - x0) / (dt0 + dt1) + (x2 - x1) / dt1;
  22827. let t2 = (x2 - x1) / dt1 - (x3 - x1) / (dt1 + dt2) + (x3 - x2) / dt2; // rescale tangents for parametrization in [0,1]
  22828. t1 *= dt1;
  22829. t2 *= dt1;
  22830. init(x1, x2, t1, t2);
  22831. },
  22832. calc: function (t) {
  22833. const t2 = t * t;
  22834. const t3 = t2 * t;
  22835. return c0 + c1 * t + c2 * t2 + c3 * t3;
  22836. }
  22837. };
  22838. } //
  22839. const tmp = new Vector3();
  22840. const px = new CubicPoly(),
  22841. py = new CubicPoly(),
  22842. pz = new CubicPoly();
  22843. function CatmullRomCurve3(points = [], closed = false, curveType = 'centripetal', tension = 0.5) {
  22844. Curve.call(this);
  22845. this.type = 'CatmullRomCurve3';
  22846. this.points = points;
  22847. this.closed = closed;
  22848. this.curveType = curveType;
  22849. this.tension = tension;
  22850. }
  22851. CatmullRomCurve3.prototype = Object.create(Curve.prototype);
  22852. CatmullRomCurve3.prototype.constructor = CatmullRomCurve3;
  22853. CatmullRomCurve3.prototype.isCatmullRomCurve3 = true;
  22854. CatmullRomCurve3.prototype.getPoint = function (t, optionalTarget = new Vector3()) {
  22855. const point = optionalTarget;
  22856. const points = this.points;
  22857. const l = points.length;
  22858. const p = (l - (this.closed ? 0 : 1)) * t;
  22859. let intPoint = Math.floor(p);
  22860. let weight = p - intPoint;
  22861. if (this.closed) {
  22862. intPoint += intPoint > 0 ? 0 : (Math.floor(Math.abs(intPoint) / l) + 1) * l;
  22863. } else if (weight === 0 && intPoint === l - 1) {
  22864. intPoint = l - 2;
  22865. weight = 1;
  22866. }
  22867. let p0, p3; // 4 points (p1 & p2 defined below)
  22868. if (this.closed || intPoint > 0) {
  22869. p0 = points[(intPoint - 1) % l];
  22870. } else {
  22871. // extrapolate first point
  22872. tmp.subVectors(points[0], points[1]).add(points[0]);
  22873. p0 = tmp;
  22874. }
  22875. const p1 = points[intPoint % l];
  22876. const p2 = points[(intPoint + 1) % l];
  22877. if (this.closed || intPoint + 2 < l) {
  22878. p3 = points[(intPoint + 2) % l];
  22879. } else {
  22880. // extrapolate last point
  22881. tmp.subVectors(points[l - 1], points[l - 2]).add(points[l - 1]);
  22882. p3 = tmp;
  22883. }
  22884. if (this.curveType === 'centripetal' || this.curveType === 'chordal') {
  22885. // init Centripetal / Chordal Catmull-Rom
  22886. const pow = this.curveType === 'chordal' ? 0.5 : 0.25;
  22887. let dt0 = Math.pow(p0.distanceToSquared(p1), pow);
  22888. let dt1 = Math.pow(p1.distanceToSquared(p2), pow);
  22889. let dt2 = Math.pow(p2.distanceToSquared(p3), pow); // safety check for repeated points
  22890. if (dt1 < 1e-4) dt1 = 1.0;
  22891. if (dt0 < 1e-4) dt0 = dt1;
  22892. if (dt2 < 1e-4) dt2 = dt1;
  22893. px.initNonuniformCatmullRom(p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2);
  22894. py.initNonuniformCatmullRom(p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2);
  22895. pz.initNonuniformCatmullRom(p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2);
  22896. } else if (this.curveType === 'catmullrom') {
  22897. px.initCatmullRom(p0.x, p1.x, p2.x, p3.x, this.tension);
  22898. py.initCatmullRom(p0.y, p1.y, p2.y, p3.y, this.tension);
  22899. pz.initCatmullRom(p0.z, p1.z, p2.z, p3.z, this.tension);
  22900. }
  22901. point.set(px.calc(weight), py.calc(weight), pz.calc(weight));
  22902. return point;
  22903. };
  22904. CatmullRomCurve3.prototype.copy = function (source) {
  22905. Curve.prototype.copy.call(this, source);
  22906. this.points = [];
  22907. for (let i = 0, l = source.points.length; i < l; i++) {
  22908. const point = source.points[i];
  22909. this.points.push(point.clone());
  22910. }
  22911. this.closed = source.closed;
  22912. this.curveType = source.curveType;
  22913. this.tension = source.tension;
  22914. return this;
  22915. };
  22916. CatmullRomCurve3.prototype.toJSON = function () {
  22917. const data = Curve.prototype.toJSON.call(this);
  22918. data.points = [];
  22919. for (let i = 0, l = this.points.length; i < l; i++) {
  22920. const point = this.points[i];
  22921. data.points.push(point.toArray());
  22922. }
  22923. data.closed = this.closed;
  22924. data.curveType = this.curveType;
  22925. data.tension = this.tension;
  22926. return data;
  22927. };
  22928. CatmullRomCurve3.prototype.fromJSON = function (json) {
  22929. Curve.prototype.fromJSON.call(this, json);
  22930. this.points = [];
  22931. for (let i = 0, l = json.points.length; i < l; i++) {
  22932. const point = json.points[i];
  22933. this.points.push(new Vector3().fromArray(point));
  22934. }
  22935. this.closed = json.closed;
  22936. this.curveType = json.curveType;
  22937. this.tension = json.tension;
  22938. return this;
  22939. };
  22940. /**
  22941. * Bezier Curves formulas obtained from
  22942. * http://en.wikipedia.org/wiki/Bézier_curve
  22943. */
  22944. function CatmullRom(t, p0, p1, p2, p3) {
  22945. const v0 = (p2 - p0) * 0.5;
  22946. const v1 = (p3 - p1) * 0.5;
  22947. const t2 = t * t;
  22948. const t3 = t * t2;
  22949. return (2 * p1 - 2 * p2 + v0 + v1) * t3 + (-3 * p1 + 3 * p2 - 2 * v0 - v1) * t2 + v0 * t + p1;
  22950. } //
  22951. function QuadraticBezierP0(t, p) {
  22952. const k = 1 - t;
  22953. return k * k * p;
  22954. }
  22955. function QuadraticBezierP1(t, p) {
  22956. return 2 * (1 - t) * t * p;
  22957. }
  22958. function QuadraticBezierP2(t, p) {
  22959. return t * t * p;
  22960. }
  22961. function QuadraticBezier(t, p0, p1, p2) {
  22962. return QuadraticBezierP0(t, p0) + QuadraticBezierP1(t, p1) + QuadraticBezierP2(t, p2);
  22963. } //
  22964. function CubicBezierP0(t, p) {
  22965. const k = 1 - t;
  22966. return k * k * k * p;
  22967. }
  22968. function CubicBezierP1(t, p) {
  22969. const k = 1 - t;
  22970. return 3 * k * k * t * p;
  22971. }
  22972. function CubicBezierP2(t, p) {
  22973. return 3 * (1 - t) * t * t * p;
  22974. }
  22975. function CubicBezierP3(t, p) {
  22976. return t * t * t * p;
  22977. }
  22978. function CubicBezier(t, p0, p1, p2, p3) {
  22979. return CubicBezierP0(t, p0) + CubicBezierP1(t, p1) + CubicBezierP2(t, p2) + CubicBezierP3(t, p3);
  22980. }
  22981. function CubicBezierCurve(v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2(), v3 = new Vector2()) {
  22982. Curve.call(this);
  22983. this.type = 'CubicBezierCurve';
  22984. this.v0 = v0;
  22985. this.v1 = v1;
  22986. this.v2 = v2;
  22987. this.v3 = v3;
  22988. }
  22989. CubicBezierCurve.prototype = Object.create(Curve.prototype);
  22990. CubicBezierCurve.prototype.constructor = CubicBezierCurve;
  22991. CubicBezierCurve.prototype.isCubicBezierCurve = true;
  22992. CubicBezierCurve.prototype.getPoint = function (t, optionalTarget = new Vector2()) {
  22993. const point = optionalTarget;
  22994. const v0 = this.v0,
  22995. v1 = this.v1,
  22996. v2 = this.v2,
  22997. v3 = this.v3;
  22998. point.set(CubicBezier(t, v0.x, v1.x, v2.x, v3.x), CubicBezier(t, v0.y, v1.y, v2.y, v3.y));
  22999. return point;
  23000. };
  23001. CubicBezierCurve.prototype.copy = function (source) {
  23002. Curve.prototype.copy.call(this, source);
  23003. this.v0.copy(source.v0);
  23004. this.v1.copy(source.v1);
  23005. this.v2.copy(source.v2);
  23006. this.v3.copy(source.v3);
  23007. return this;
  23008. };
  23009. CubicBezierCurve.prototype.toJSON = function () {
  23010. const data = Curve.prototype.toJSON.call(this);
  23011. data.v0 = this.v0.toArray();
  23012. data.v1 = this.v1.toArray();
  23013. data.v2 = this.v2.toArray();
  23014. data.v3 = this.v3.toArray();
  23015. return data;
  23016. };
  23017. CubicBezierCurve.prototype.fromJSON = function (json) {
  23018. Curve.prototype.fromJSON.call(this, json);
  23019. this.v0.fromArray(json.v0);
  23020. this.v1.fromArray(json.v1);
  23021. this.v2.fromArray(json.v2);
  23022. this.v3.fromArray(json.v3);
  23023. return this;
  23024. };
  23025. function CubicBezierCurve3(v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3(), v3 = new Vector3()) {
  23026. Curve.call(this);
  23027. this.type = 'CubicBezierCurve3';
  23028. this.v0 = v0;
  23029. this.v1 = v1;
  23030. this.v2 = v2;
  23031. this.v3 = v3;
  23032. }
  23033. CubicBezierCurve3.prototype = Object.create(Curve.prototype);
  23034. CubicBezierCurve3.prototype.constructor = CubicBezierCurve3;
  23035. CubicBezierCurve3.prototype.isCubicBezierCurve3 = true;
  23036. CubicBezierCurve3.prototype.getPoint = function (t, optionalTarget = new Vector3()) {
  23037. const point = optionalTarget;
  23038. const v0 = this.v0,
  23039. v1 = this.v1,
  23040. v2 = this.v2,
  23041. v3 = this.v3;
  23042. point.set(CubicBezier(t, v0.x, v1.x, v2.x, v3.x), CubicBezier(t, v0.y, v1.y, v2.y, v3.y), CubicBezier(t, v0.z, v1.z, v2.z, v3.z));
  23043. return point;
  23044. };
  23045. CubicBezierCurve3.prototype.copy = function (source) {
  23046. Curve.prototype.copy.call(this, source);
  23047. this.v0.copy(source.v0);
  23048. this.v1.copy(source.v1);
  23049. this.v2.copy(source.v2);
  23050. this.v3.copy(source.v3);
  23051. return this;
  23052. };
  23053. CubicBezierCurve3.prototype.toJSON = function () {
  23054. const data = Curve.prototype.toJSON.call(this);
  23055. data.v0 = this.v0.toArray();
  23056. data.v1 = this.v1.toArray();
  23057. data.v2 = this.v2.toArray();
  23058. data.v3 = this.v3.toArray();
  23059. return data;
  23060. };
  23061. CubicBezierCurve3.prototype.fromJSON = function (json) {
  23062. Curve.prototype.fromJSON.call(this, json);
  23063. this.v0.fromArray(json.v0);
  23064. this.v1.fromArray(json.v1);
  23065. this.v2.fromArray(json.v2);
  23066. this.v3.fromArray(json.v3);
  23067. return this;
  23068. };
  23069. function LineCurve(v1 = new Vector2(), v2 = new Vector2()) {
  23070. Curve.call(this);
  23071. this.type = 'LineCurve';
  23072. this.v1 = v1;
  23073. this.v2 = v2;
  23074. }
  23075. LineCurve.prototype = Object.create(Curve.prototype);
  23076. LineCurve.prototype.constructor = LineCurve;
  23077. LineCurve.prototype.isLineCurve = true;
  23078. LineCurve.prototype.getPoint = function (t, optionalTarget = new Vector2()) {
  23079. const point = optionalTarget;
  23080. if (t === 1) {
  23081. point.copy(this.v2);
  23082. } else {
  23083. point.copy(this.v2).sub(this.v1);
  23084. point.multiplyScalar(t).add(this.v1);
  23085. }
  23086. return point;
  23087. }; // Line curve is linear, so we can overwrite default getPointAt
  23088. LineCurve.prototype.getPointAt = function (u, optionalTarget) {
  23089. return this.getPoint(u, optionalTarget);
  23090. };
  23091. LineCurve.prototype.getTangent = function (t, optionalTarget) {
  23092. const tangent = optionalTarget || new Vector2();
  23093. tangent.copy(this.v2).sub(this.v1).normalize();
  23094. return tangent;
  23095. };
  23096. LineCurve.prototype.copy = function (source) {
  23097. Curve.prototype.copy.call(this, source);
  23098. this.v1.copy(source.v1);
  23099. this.v2.copy(source.v2);
  23100. return this;
  23101. };
  23102. LineCurve.prototype.toJSON = function () {
  23103. const data = Curve.prototype.toJSON.call(this);
  23104. data.v1 = this.v1.toArray();
  23105. data.v2 = this.v2.toArray();
  23106. return data;
  23107. };
  23108. LineCurve.prototype.fromJSON = function (json) {
  23109. Curve.prototype.fromJSON.call(this, json);
  23110. this.v1.fromArray(json.v1);
  23111. this.v2.fromArray(json.v2);
  23112. return this;
  23113. };
  23114. function LineCurve3(v1 = new Vector3(), v2 = new Vector3()) {
  23115. Curve.call(this);
  23116. this.type = 'LineCurve3';
  23117. this.v1 = v1;
  23118. this.v2 = v2;
  23119. }
  23120. LineCurve3.prototype = Object.create(Curve.prototype);
  23121. LineCurve3.prototype.constructor = LineCurve3;
  23122. LineCurve3.prototype.isLineCurve3 = true;
  23123. LineCurve3.prototype.getPoint = function (t, optionalTarget = new Vector3()) {
  23124. const point = optionalTarget;
  23125. if (t === 1) {
  23126. point.copy(this.v2);
  23127. } else {
  23128. point.copy(this.v2).sub(this.v1);
  23129. point.multiplyScalar(t).add(this.v1);
  23130. }
  23131. return point;
  23132. }; // Line curve is linear, so we can overwrite default getPointAt
  23133. LineCurve3.prototype.getPointAt = function (u, optionalTarget) {
  23134. return this.getPoint(u, optionalTarget);
  23135. };
  23136. LineCurve3.prototype.copy = function (source) {
  23137. Curve.prototype.copy.call(this, source);
  23138. this.v1.copy(source.v1);
  23139. this.v2.copy(source.v2);
  23140. return this;
  23141. };
  23142. LineCurve3.prototype.toJSON = function () {
  23143. const data = Curve.prototype.toJSON.call(this);
  23144. data.v1 = this.v1.toArray();
  23145. data.v2 = this.v2.toArray();
  23146. return data;
  23147. };
  23148. LineCurve3.prototype.fromJSON = function (json) {
  23149. Curve.prototype.fromJSON.call(this, json);
  23150. this.v1.fromArray(json.v1);
  23151. this.v2.fromArray(json.v2);
  23152. return this;
  23153. };
  23154. function QuadraticBezierCurve(v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2()) {
  23155. Curve.call(this);
  23156. this.type = 'QuadraticBezierCurve';
  23157. this.v0 = v0;
  23158. this.v1 = v1;
  23159. this.v2 = v2;
  23160. }
  23161. QuadraticBezierCurve.prototype = Object.create(Curve.prototype);
  23162. QuadraticBezierCurve.prototype.constructor = QuadraticBezierCurve;
  23163. QuadraticBezierCurve.prototype.isQuadraticBezierCurve = true;
  23164. QuadraticBezierCurve.prototype.getPoint = function (t, optionalTarget = new Vector2()) {
  23165. const point = optionalTarget;
  23166. const v0 = this.v0,
  23167. v1 = this.v1,
  23168. v2 = this.v2;
  23169. point.set(QuadraticBezier(t, v0.x, v1.x, v2.x), QuadraticBezier(t, v0.y, v1.y, v2.y));
  23170. return point;
  23171. };
  23172. QuadraticBezierCurve.prototype.copy = function (source) {
  23173. Curve.prototype.copy.call(this, source);
  23174. this.v0.copy(source.v0);
  23175. this.v1.copy(source.v1);
  23176. this.v2.copy(source.v2);
  23177. return this;
  23178. };
  23179. QuadraticBezierCurve.prototype.toJSON = function () {
  23180. const data = Curve.prototype.toJSON.call(this);
  23181. data.v0 = this.v0.toArray();
  23182. data.v1 = this.v1.toArray();
  23183. data.v2 = this.v2.toArray();
  23184. return data;
  23185. };
  23186. QuadraticBezierCurve.prototype.fromJSON = function (json) {
  23187. Curve.prototype.fromJSON.call(this, json);
  23188. this.v0.fromArray(json.v0);
  23189. this.v1.fromArray(json.v1);
  23190. this.v2.fromArray(json.v2);
  23191. return this;
  23192. };
  23193. function QuadraticBezierCurve3(v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3()) {
  23194. Curve.call(this);
  23195. this.type = 'QuadraticBezierCurve3';
  23196. this.v0 = v0;
  23197. this.v1 = v1;
  23198. this.v2 = v2;
  23199. }
  23200. QuadraticBezierCurve3.prototype = Object.create(Curve.prototype);
  23201. QuadraticBezierCurve3.prototype.constructor = QuadraticBezierCurve3;
  23202. QuadraticBezierCurve3.prototype.isQuadraticBezierCurve3 = true;
  23203. QuadraticBezierCurve3.prototype.getPoint = function (t, optionalTarget = new Vector3()) {
  23204. const point = optionalTarget;
  23205. const v0 = this.v0,
  23206. v1 = this.v1,
  23207. v2 = this.v2;
  23208. point.set(QuadraticBezier(t, v0.x, v1.x, v2.x), QuadraticBezier(t, v0.y, v1.y, v2.y), QuadraticBezier(t, v0.z, v1.z, v2.z));
  23209. return point;
  23210. };
  23211. QuadraticBezierCurve3.prototype.copy = function (source) {
  23212. Curve.prototype.copy.call(this, source);
  23213. this.v0.copy(source.v0);
  23214. this.v1.copy(source.v1);
  23215. this.v2.copy(source.v2);
  23216. return this;
  23217. };
  23218. QuadraticBezierCurve3.prototype.toJSON = function () {
  23219. const data = Curve.prototype.toJSON.call(this);
  23220. data.v0 = this.v0.toArray();
  23221. data.v1 = this.v1.toArray();
  23222. data.v2 = this.v2.toArray();
  23223. return data;
  23224. };
  23225. QuadraticBezierCurve3.prototype.fromJSON = function (json) {
  23226. Curve.prototype.fromJSON.call(this, json);
  23227. this.v0.fromArray(json.v0);
  23228. this.v1.fromArray(json.v1);
  23229. this.v2.fromArray(json.v2);
  23230. return this;
  23231. };
  23232. function SplineCurve(points = []) {
  23233. Curve.call(this);
  23234. this.type = 'SplineCurve';
  23235. this.points = points;
  23236. }
  23237. SplineCurve.prototype = Object.create(Curve.prototype);
  23238. SplineCurve.prototype.constructor = SplineCurve;
  23239. SplineCurve.prototype.isSplineCurve = true;
  23240. SplineCurve.prototype.getPoint = function (t, optionalTarget = new Vector2()) {
  23241. const point = optionalTarget;
  23242. const points = this.points;
  23243. const p = (points.length - 1) * t;
  23244. const intPoint = Math.floor(p);
  23245. const weight = p - intPoint;
  23246. const p0 = points[intPoint === 0 ? intPoint : intPoint - 1];
  23247. const p1 = points[intPoint];
  23248. const p2 = points[intPoint > points.length - 2 ? points.length - 1 : intPoint + 1];
  23249. const p3 = points[intPoint > points.length - 3 ? points.length - 1 : intPoint + 2];
  23250. point.set(CatmullRom(weight, p0.x, p1.x, p2.x, p3.x), CatmullRom(weight, p0.y, p1.y, p2.y, p3.y));
  23251. return point;
  23252. };
  23253. SplineCurve.prototype.copy = function (source) {
  23254. Curve.prototype.copy.call(this, source);
  23255. this.points = [];
  23256. for (let i = 0, l = source.points.length; i < l; i++) {
  23257. const point = source.points[i];
  23258. this.points.push(point.clone());
  23259. }
  23260. return this;
  23261. };
  23262. SplineCurve.prototype.toJSON = function () {
  23263. const data = Curve.prototype.toJSON.call(this);
  23264. data.points = [];
  23265. for (let i = 0, l = this.points.length; i < l; i++) {
  23266. const point = this.points[i];
  23267. data.points.push(point.toArray());
  23268. }
  23269. return data;
  23270. };
  23271. SplineCurve.prototype.fromJSON = function (json) {
  23272. Curve.prototype.fromJSON.call(this, json);
  23273. this.points = [];
  23274. for (let i = 0, l = json.points.length; i < l; i++) {
  23275. const point = json.points[i];
  23276. this.points.push(new Vector2().fromArray(point));
  23277. }
  23278. return this;
  23279. };
  23280. var Curves =
  23281. /*#__PURE__*/
  23282. Object.freeze({
  23283. __proto__: null,
  23284. ArcCurve: ArcCurve,
  23285. CatmullRomCurve3: CatmullRomCurve3,
  23286. CubicBezierCurve: CubicBezierCurve,
  23287. CubicBezierCurve3: CubicBezierCurve3,
  23288. EllipseCurve: EllipseCurve,
  23289. LineCurve: LineCurve,
  23290. LineCurve3: LineCurve3,
  23291. QuadraticBezierCurve: QuadraticBezierCurve,
  23292. QuadraticBezierCurve3: QuadraticBezierCurve3,
  23293. SplineCurve: SplineCurve
  23294. });
  23295. /**************************************************************
  23296. * Curved Path - a curve path is simply a array of connected
  23297. * curves, but retains the api of a curve
  23298. **************************************************************/
  23299. function CurvePath() {
  23300. Curve.call(this);
  23301. this.type = 'CurvePath';
  23302. this.curves = [];
  23303. this.autoClose = false; // Automatically closes the path
  23304. }
  23305. CurvePath.prototype = Object.assign(Object.create(Curve.prototype), {
  23306. constructor: CurvePath,
  23307. add: function (curve) {
  23308. this.curves.push(curve);
  23309. },
  23310. closePath: function () {
  23311. // Add a line curve if start and end of lines are not connected
  23312. const startPoint = this.curves[0].getPoint(0);
  23313. const endPoint = this.curves[this.curves.length - 1].getPoint(1);
  23314. if (!startPoint.equals(endPoint)) {
  23315. this.curves.push(new LineCurve(endPoint, startPoint));
  23316. }
  23317. },
  23318. // To get accurate point with reference to
  23319. // entire path distance at time t,
  23320. // following has to be done:
  23321. // 1. Length of each sub path have to be known
  23322. // 2. Locate and identify type of curve
  23323. // 3. Get t for the curve
  23324. // 4. Return curve.getPointAt(t')
  23325. getPoint: function (t) {
  23326. const d = t * this.getLength();
  23327. const curveLengths = this.getCurveLengths();
  23328. let i = 0; // To think about boundaries points.
  23329. while (i < curveLengths.length) {
  23330. if (curveLengths[i] >= d) {
  23331. const diff = curveLengths[i] - d;
  23332. const curve = this.curves[i];
  23333. const segmentLength = curve.getLength();
  23334. const u = segmentLength === 0 ? 0 : 1 - diff / segmentLength;
  23335. return curve.getPointAt(u);
  23336. }
  23337. i++;
  23338. }
  23339. return null; // loop where sum != 0, sum > d , sum+1 <d
  23340. },
  23341. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  23342. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  23343. // getPoint() depends on getLength
  23344. getLength: function () {
  23345. const lens = this.getCurveLengths();
  23346. return lens[lens.length - 1];
  23347. },
  23348. // cacheLengths must be recalculated.
  23349. updateArcLengths: function () {
  23350. this.needsUpdate = true;
  23351. this.cacheLengths = null;
  23352. this.getCurveLengths();
  23353. },
  23354. // Compute lengths and cache them
  23355. // We cannot overwrite getLengths() because UtoT mapping uses it.
  23356. getCurveLengths: function () {
  23357. // We use cache values if curves and cache array are same length
  23358. if (this.cacheLengths && this.cacheLengths.length === this.curves.length) {
  23359. return this.cacheLengths;
  23360. } // Get length of sub-curve
  23361. // Push sums into cached array
  23362. const lengths = [];
  23363. let sums = 0;
  23364. for (let i = 0, l = this.curves.length; i < l; i++) {
  23365. sums += this.curves[i].getLength();
  23366. lengths.push(sums);
  23367. }
  23368. this.cacheLengths = lengths;
  23369. return lengths;
  23370. },
  23371. getSpacedPoints: function (divisions = 40) {
  23372. const points = [];
  23373. for (let i = 0; i <= divisions; i++) {
  23374. points.push(this.getPoint(i / divisions));
  23375. }
  23376. if (this.autoClose) {
  23377. points.push(points[0]);
  23378. }
  23379. return points;
  23380. },
  23381. getPoints: function (divisions = 12) {
  23382. const points = [];
  23383. let last;
  23384. for (let i = 0, curves = this.curves; i < curves.length; i++) {
  23385. const curve = curves[i];
  23386. const resolution = curve && curve.isEllipseCurve ? divisions * 2 : curve && (curve.isLineCurve || curve.isLineCurve3) ? 1 : curve && curve.isSplineCurve ? divisions * curve.points.length : divisions;
  23387. const pts = curve.getPoints(resolution);
  23388. for (let j = 0; j < pts.length; j++) {
  23389. const point = pts[j];
  23390. if (last && last.equals(point)) continue; // ensures no consecutive points are duplicates
  23391. points.push(point);
  23392. last = point;
  23393. }
  23394. }
  23395. if (this.autoClose && points.length > 1 && !points[points.length - 1].equals(points[0])) {
  23396. points.push(points[0]);
  23397. }
  23398. return points;
  23399. },
  23400. copy: function (source) {
  23401. Curve.prototype.copy.call(this, source);
  23402. this.curves = [];
  23403. for (let i = 0, l = source.curves.length; i < l; i++) {
  23404. const curve = source.curves[i];
  23405. this.curves.push(curve.clone());
  23406. }
  23407. this.autoClose = source.autoClose;
  23408. return this;
  23409. },
  23410. toJSON: function () {
  23411. const data = Curve.prototype.toJSON.call(this);
  23412. data.autoClose = this.autoClose;
  23413. data.curves = [];
  23414. for (let i = 0, l = this.curves.length; i < l; i++) {
  23415. const curve = this.curves[i];
  23416. data.curves.push(curve.toJSON());
  23417. }
  23418. return data;
  23419. },
  23420. fromJSON: function (json) {
  23421. Curve.prototype.fromJSON.call(this, json);
  23422. this.autoClose = json.autoClose;
  23423. this.curves = [];
  23424. for (let i = 0, l = json.curves.length; i < l; i++) {
  23425. const curve = json.curves[i];
  23426. this.curves.push(new Curves[curve.type]().fromJSON(curve));
  23427. }
  23428. return this;
  23429. }
  23430. });
  23431. function Path(points) {
  23432. CurvePath.call(this);
  23433. this.type = 'Path';
  23434. this.currentPoint = new Vector2();
  23435. if (points) {
  23436. this.setFromPoints(points);
  23437. }
  23438. }
  23439. Path.prototype = Object.assign(Object.create(CurvePath.prototype), {
  23440. constructor: Path,
  23441. setFromPoints: function (points) {
  23442. this.moveTo(points[0].x, points[0].y);
  23443. for (let i = 1, l = points.length; i < l; i++) {
  23444. this.lineTo(points[i].x, points[i].y);
  23445. }
  23446. return this;
  23447. },
  23448. moveTo: function (x, y) {
  23449. this.currentPoint.set(x, y); // TODO consider referencing vectors instead of copying?
  23450. return this;
  23451. },
  23452. lineTo: function (x, y) {
  23453. const curve = new LineCurve(this.currentPoint.clone(), new Vector2(x, y));
  23454. this.curves.push(curve);
  23455. this.currentPoint.set(x, y);
  23456. return this;
  23457. },
  23458. quadraticCurveTo: function (aCPx, aCPy, aX, aY) {
  23459. const curve = new QuadraticBezierCurve(this.currentPoint.clone(), new Vector2(aCPx, aCPy), new Vector2(aX, aY));
  23460. this.curves.push(curve);
  23461. this.currentPoint.set(aX, aY);
  23462. return this;
  23463. },
  23464. bezierCurveTo: function (aCP1x, aCP1y, aCP2x, aCP2y, aX, aY) {
  23465. const curve = new CubicBezierCurve(this.currentPoint.clone(), new Vector2(aCP1x, aCP1y), new Vector2(aCP2x, aCP2y), new Vector2(aX, aY));
  23466. this.curves.push(curve);
  23467. this.currentPoint.set(aX, aY);
  23468. return this;
  23469. },
  23470. splineThru: function (pts
  23471. /*Array of Vector*/
  23472. ) {
  23473. const npts = [this.currentPoint.clone()].concat(pts);
  23474. const curve = new SplineCurve(npts);
  23475. this.curves.push(curve);
  23476. this.currentPoint.copy(pts[pts.length - 1]);
  23477. return this;
  23478. },
  23479. arc: function (aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise) {
  23480. const x0 = this.currentPoint.x;
  23481. const y0 = this.currentPoint.y;
  23482. this.absarc(aX + x0, aY + y0, aRadius, aStartAngle, aEndAngle, aClockwise);
  23483. return this;
  23484. },
  23485. absarc: function (aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise) {
  23486. this.absellipse(aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise);
  23487. return this;
  23488. },
  23489. ellipse: function (aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation) {
  23490. const x0 = this.currentPoint.x;
  23491. const y0 = this.currentPoint.y;
  23492. this.absellipse(aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation);
  23493. return this;
  23494. },
  23495. absellipse: function (aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation) {
  23496. const curve = new EllipseCurve(aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation);
  23497. if (this.curves.length > 0) {
  23498. // if a previous curve is present, attempt to join
  23499. const firstPoint = curve.getPoint(0);
  23500. if (!firstPoint.equals(this.currentPoint)) {
  23501. this.lineTo(firstPoint.x, firstPoint.y);
  23502. }
  23503. }
  23504. this.curves.push(curve);
  23505. const lastPoint = curve.getPoint(1);
  23506. this.currentPoint.copy(lastPoint);
  23507. return this;
  23508. },
  23509. copy: function (source) {
  23510. CurvePath.prototype.copy.call(this, source);
  23511. this.currentPoint.copy(source.currentPoint);
  23512. return this;
  23513. },
  23514. toJSON: function () {
  23515. const data = CurvePath.prototype.toJSON.call(this);
  23516. data.currentPoint = this.currentPoint.toArray();
  23517. return data;
  23518. },
  23519. fromJSON: function (json) {
  23520. CurvePath.prototype.fromJSON.call(this, json);
  23521. this.currentPoint.fromArray(json.currentPoint);
  23522. return this;
  23523. }
  23524. });
  23525. function Shape(points) {
  23526. Path.call(this, points);
  23527. this.uuid = MathUtils.generateUUID();
  23528. this.type = 'Shape';
  23529. this.holes = [];
  23530. }
  23531. Shape.prototype = Object.assign(Object.create(Path.prototype), {
  23532. constructor: Shape,
  23533. getPointsHoles: function (divisions) {
  23534. const holesPts = [];
  23535. for (let i = 0, l = this.holes.length; i < l; i++) {
  23536. holesPts[i] = this.holes[i].getPoints(divisions);
  23537. }
  23538. return holesPts;
  23539. },
  23540. // get points of shape and holes (keypoints based on segments parameter)
  23541. extractPoints: function (divisions) {
  23542. return {
  23543. shape: this.getPoints(divisions),
  23544. holes: this.getPointsHoles(divisions)
  23545. };
  23546. },
  23547. copy: function (source) {
  23548. Path.prototype.copy.call(this, source);
  23549. this.holes = [];
  23550. for (let i = 0, l = source.holes.length; i < l; i++) {
  23551. const hole = source.holes[i];
  23552. this.holes.push(hole.clone());
  23553. }
  23554. return this;
  23555. },
  23556. toJSON: function () {
  23557. const data = Path.prototype.toJSON.call(this);
  23558. data.uuid = this.uuid;
  23559. data.holes = [];
  23560. for (let i = 0, l = this.holes.length; i < l; i++) {
  23561. const hole = this.holes[i];
  23562. data.holes.push(hole.toJSON());
  23563. }
  23564. return data;
  23565. },
  23566. fromJSON: function (json) {
  23567. Path.prototype.fromJSON.call(this, json);
  23568. this.uuid = json.uuid;
  23569. this.holes = [];
  23570. for (let i = 0, l = json.holes.length; i < l; i++) {
  23571. const hole = json.holes[i];
  23572. this.holes.push(new Path().fromJSON(hole));
  23573. }
  23574. return this;
  23575. }
  23576. });
  23577. function Light(color, intensity = 1) {
  23578. Object3D.call(this);
  23579. this.type = 'Light';
  23580. this.color = new Color(color);
  23581. this.intensity = intensity;
  23582. }
  23583. Light.prototype = Object.assign(Object.create(Object3D.prototype), {
  23584. constructor: Light,
  23585. isLight: true,
  23586. copy: function (source) {
  23587. Object3D.prototype.copy.call(this, source);
  23588. this.color.copy(source.color);
  23589. this.intensity = source.intensity;
  23590. return this;
  23591. },
  23592. toJSON: function (meta) {
  23593. const data = Object3D.prototype.toJSON.call(this, meta);
  23594. data.object.color = this.color.getHex();
  23595. data.object.intensity = this.intensity;
  23596. if (this.groundColor !== undefined) data.object.groundColor = this.groundColor.getHex();
  23597. if (this.distance !== undefined) data.object.distance = this.distance;
  23598. if (this.angle !== undefined) data.object.angle = this.angle;
  23599. if (this.decay !== undefined) data.object.decay = this.decay;
  23600. if (this.penumbra !== undefined) data.object.penumbra = this.penumbra;
  23601. if (this.shadow !== undefined) data.object.shadow = this.shadow.toJSON();
  23602. return data;
  23603. }
  23604. });
  23605. function HemisphereLight(skyColor, groundColor, intensity) {
  23606. Light.call(this, skyColor, intensity);
  23607. this.type = 'HemisphereLight';
  23608. this.position.copy(Object3D.DefaultUp);
  23609. this.updateMatrix();
  23610. this.groundColor = new Color(groundColor);
  23611. }
  23612. HemisphereLight.prototype = Object.assign(Object.create(Light.prototype), {
  23613. constructor: HemisphereLight,
  23614. isHemisphereLight: true,
  23615. copy: function (source) {
  23616. Light.prototype.copy.call(this, source);
  23617. this.groundColor.copy(source.groundColor);
  23618. return this;
  23619. }
  23620. });
  23621. function LightShadow(camera) {
  23622. this.camera = camera;
  23623. this.bias = 0;
  23624. this.normalBias = 0;
  23625. this.radius = 1;
  23626. this.mapSize = new Vector2(512, 512);
  23627. this.map = null;
  23628. this.mapPass = null;
  23629. this.matrix = new Matrix4();
  23630. this.autoUpdate = true;
  23631. this.needsUpdate = false;
  23632. this._frustum = new Frustum();
  23633. this._frameExtents = new Vector2(1, 1);
  23634. this._viewportCount = 1;
  23635. this._viewports = [new Vector4(0, 0, 1, 1)];
  23636. }
  23637. Object.assign(LightShadow.prototype, {
  23638. _projScreenMatrix: new Matrix4(),
  23639. _lightPositionWorld: new Vector3(),
  23640. _lookTarget: new Vector3(),
  23641. getViewportCount: function () {
  23642. return this._viewportCount;
  23643. },
  23644. getFrustum: function () {
  23645. return this._frustum;
  23646. },
  23647. updateMatrices: function (light) {
  23648. const shadowCamera = this.camera,
  23649. shadowMatrix = this.matrix,
  23650. projScreenMatrix = this._projScreenMatrix,
  23651. lookTarget = this._lookTarget,
  23652. lightPositionWorld = this._lightPositionWorld;
  23653. lightPositionWorld.setFromMatrixPosition(light.matrixWorld);
  23654. shadowCamera.position.copy(lightPositionWorld);
  23655. lookTarget.setFromMatrixPosition(light.target.matrixWorld);
  23656. shadowCamera.lookAt(lookTarget);
  23657. shadowCamera.updateMatrixWorld();
  23658. projScreenMatrix.multiplyMatrices(shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse);
  23659. this._frustum.setFromProjectionMatrix(projScreenMatrix);
  23660. shadowMatrix.set(0.5, 0.0, 0.0, 0.5, 0.0, 0.5, 0.0, 0.5, 0.0, 0.0, 0.5, 0.5, 0.0, 0.0, 0.0, 1.0);
  23661. shadowMatrix.multiply(shadowCamera.projectionMatrix);
  23662. shadowMatrix.multiply(shadowCamera.matrixWorldInverse);
  23663. },
  23664. getViewport: function (viewportIndex) {
  23665. return this._viewports[viewportIndex];
  23666. },
  23667. getFrameExtents: function () {
  23668. return this._frameExtents;
  23669. },
  23670. copy: function (source) {
  23671. this.camera = source.camera.clone();
  23672. this.bias = source.bias;
  23673. this.radius = source.radius;
  23674. this.mapSize.copy(source.mapSize);
  23675. return this;
  23676. },
  23677. clone: function () {
  23678. return new this.constructor().copy(this);
  23679. },
  23680. toJSON: function () {
  23681. const object = {};
  23682. if (this.bias !== 0) object.bias = this.bias;
  23683. if (this.normalBias !== 0) object.normalBias = this.normalBias;
  23684. if (this.radius !== 1) object.radius = this.radius;
  23685. if (this.mapSize.x !== 512 || this.mapSize.y !== 512) object.mapSize = this.mapSize.toArray();
  23686. object.camera = this.camera.toJSON(false).object;
  23687. delete object.camera.matrix;
  23688. return object;
  23689. }
  23690. });
  23691. function SpotLightShadow() {
  23692. LightShadow.call(this, new PerspectiveCamera(50, 1, 0.5, 500));
  23693. this.focus = 1;
  23694. }
  23695. SpotLightShadow.prototype = Object.assign(Object.create(LightShadow.prototype), {
  23696. constructor: SpotLightShadow,
  23697. isSpotLightShadow: true,
  23698. updateMatrices: function (light) {
  23699. const camera = this.camera;
  23700. const fov = MathUtils.RAD2DEG * 2 * light.angle * this.focus;
  23701. const aspect = this.mapSize.width / this.mapSize.height;
  23702. const far = light.distance || camera.far;
  23703. if (fov !== camera.fov || aspect !== camera.aspect || far !== camera.far) {
  23704. camera.fov = fov;
  23705. camera.aspect = aspect;
  23706. camera.far = far;
  23707. camera.updateProjectionMatrix();
  23708. }
  23709. LightShadow.prototype.updateMatrices.call(this, light);
  23710. }
  23711. });
  23712. function SpotLight(color, intensity, distance, angle, penumbra, decay) {
  23713. Light.call(this, color, intensity);
  23714. this.type = 'SpotLight';
  23715. this.position.copy(Object3D.DefaultUp);
  23716. this.updateMatrix();
  23717. this.target = new Object3D();
  23718. Object.defineProperty(this, 'power', {
  23719. get: function () {
  23720. // intensity = power per solid angle.
  23721. // ref: equation (17) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  23722. return this.intensity * Math.PI;
  23723. },
  23724. set: function (power) {
  23725. // intensity = power per solid angle.
  23726. // ref: equation (17) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  23727. this.intensity = power / Math.PI;
  23728. }
  23729. });
  23730. this.distance = distance !== undefined ? distance : 0;
  23731. this.angle = angle !== undefined ? angle : Math.PI / 3;
  23732. this.penumbra = penumbra !== undefined ? penumbra : 0;
  23733. this.decay = decay !== undefined ? decay : 1; // for physically correct lights, should be 2.
  23734. this.shadow = new SpotLightShadow();
  23735. }
  23736. SpotLight.prototype = Object.assign(Object.create(Light.prototype), {
  23737. constructor: SpotLight,
  23738. isSpotLight: true,
  23739. copy: function (source) {
  23740. Light.prototype.copy.call(this, source);
  23741. this.distance = source.distance;
  23742. this.angle = source.angle;
  23743. this.penumbra = source.penumbra;
  23744. this.decay = source.decay;
  23745. this.target = source.target.clone();
  23746. this.shadow = source.shadow.clone();
  23747. return this;
  23748. }
  23749. });
  23750. function PointLightShadow() {
  23751. LightShadow.call(this, new PerspectiveCamera(90, 1, 0.5, 500));
  23752. this._frameExtents = new Vector2(4, 2);
  23753. this._viewportCount = 6;
  23754. this._viewports = [// These viewports map a cube-map onto a 2D texture with the
  23755. // following orientation:
  23756. //
  23757. // xzXZ
  23758. // y Y
  23759. //
  23760. // X - Positive x direction
  23761. // x - Negative x direction
  23762. // Y - Positive y direction
  23763. // y - Negative y direction
  23764. // Z - Positive z direction
  23765. // z - Negative z direction
  23766. // positive X
  23767. new Vector4(2, 1, 1, 1), // negative X
  23768. new Vector4(0, 1, 1, 1), // positive Z
  23769. new Vector4(3, 1, 1, 1), // negative Z
  23770. new Vector4(1, 1, 1, 1), // positive Y
  23771. new Vector4(3, 0, 1, 1), // negative Y
  23772. new Vector4(1, 0, 1, 1)];
  23773. this._cubeDirections = [new Vector3(1, 0, 0), new Vector3(-1, 0, 0), new Vector3(0, 0, 1), new Vector3(0, 0, -1), new Vector3(0, 1, 0), new Vector3(0, -1, 0)];
  23774. this._cubeUps = [new Vector3(0, 1, 0), new Vector3(0, 1, 0), new Vector3(0, 1, 0), new Vector3(0, 1, 0), new Vector3(0, 0, 1), new Vector3(0, 0, -1)];
  23775. }
  23776. PointLightShadow.prototype = Object.assign(Object.create(LightShadow.prototype), {
  23777. constructor: PointLightShadow,
  23778. isPointLightShadow: true,
  23779. updateMatrices: function (light, viewportIndex = 0) {
  23780. const camera = this.camera,
  23781. shadowMatrix = this.matrix,
  23782. lightPositionWorld = this._lightPositionWorld,
  23783. lookTarget = this._lookTarget,
  23784. projScreenMatrix = this._projScreenMatrix;
  23785. lightPositionWorld.setFromMatrixPosition(light.matrixWorld);
  23786. camera.position.copy(lightPositionWorld);
  23787. lookTarget.copy(camera.position);
  23788. lookTarget.add(this._cubeDirections[viewportIndex]);
  23789. camera.up.copy(this._cubeUps[viewportIndex]);
  23790. camera.lookAt(lookTarget);
  23791. camera.updateMatrixWorld();
  23792. shadowMatrix.makeTranslation(-lightPositionWorld.x, -lightPositionWorld.y, -lightPositionWorld.z);
  23793. projScreenMatrix.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse);
  23794. this._frustum.setFromProjectionMatrix(projScreenMatrix);
  23795. }
  23796. });
  23797. function PointLight(color, intensity, distance, decay) {
  23798. Light.call(this, color, intensity);
  23799. this.type = 'PointLight';
  23800. Object.defineProperty(this, 'power', {
  23801. get: function () {
  23802. // intensity = power per solid angle.
  23803. // ref: equation (15) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  23804. return this.intensity * 4 * Math.PI;
  23805. },
  23806. set: function (power) {
  23807. // intensity = power per solid angle.
  23808. // ref: equation (15) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  23809. this.intensity = power / (4 * Math.PI);
  23810. }
  23811. });
  23812. this.distance = distance !== undefined ? distance : 0;
  23813. this.decay = decay !== undefined ? decay : 1; // for physically correct lights, should be 2.
  23814. this.shadow = new PointLightShadow();
  23815. }
  23816. PointLight.prototype = Object.assign(Object.create(Light.prototype), {
  23817. constructor: PointLight,
  23818. isPointLight: true,
  23819. copy: function (source) {
  23820. Light.prototype.copy.call(this, source);
  23821. this.distance = source.distance;
  23822. this.decay = source.decay;
  23823. this.shadow = source.shadow.clone();
  23824. return this;
  23825. }
  23826. });
  23827. function OrthographicCamera(left, right, top, bottom, near, far) {
  23828. Camera.call(this);
  23829. this.type = 'OrthographicCamera';
  23830. this.zoom = 1;
  23831. this.view = null;
  23832. this.left = left !== undefined ? left : -1;
  23833. this.right = right !== undefined ? right : 1;
  23834. this.top = top !== undefined ? top : 1;
  23835. this.bottom = bottom !== undefined ? bottom : -1;
  23836. this.near = near !== undefined ? near : 0.1;
  23837. this.far = far !== undefined ? far : 2000;
  23838. this.updateProjectionMatrix();
  23839. }
  23840. OrthographicCamera.prototype = Object.assign(Object.create(Camera.prototype), {
  23841. constructor: OrthographicCamera,
  23842. isOrthographicCamera: true,
  23843. copy: function (source, recursive) {
  23844. Camera.prototype.copy.call(this, source, recursive);
  23845. this.left = source.left;
  23846. this.right = source.right;
  23847. this.top = source.top;
  23848. this.bottom = source.bottom;
  23849. this.near = source.near;
  23850. this.far = source.far;
  23851. this.zoom = source.zoom;
  23852. this.view = source.view === null ? null : Object.assign({}, source.view);
  23853. return this;
  23854. },
  23855. setViewOffset: function (fullWidth, fullHeight, x, y, width, height) {
  23856. if (this.view === null) {
  23857. this.view = {
  23858. enabled: true,
  23859. fullWidth: 1,
  23860. fullHeight: 1,
  23861. offsetX: 0,
  23862. offsetY: 0,
  23863. width: 1,
  23864. height: 1
  23865. };
  23866. }
  23867. this.view.enabled = true;
  23868. this.view.fullWidth = fullWidth;
  23869. this.view.fullHeight = fullHeight;
  23870. this.view.offsetX = x;
  23871. this.view.offsetY = y;
  23872. this.view.width = width;
  23873. this.view.height = height;
  23874. this.updateProjectionMatrix();
  23875. },
  23876. clearViewOffset: function () {
  23877. if (this.view !== null) {
  23878. this.view.enabled = false;
  23879. }
  23880. this.updateProjectionMatrix();
  23881. },
  23882. updateProjectionMatrix: function () {
  23883. const dx = (this.right - this.left) / (2 * this.zoom);
  23884. const dy = (this.top - this.bottom) / (2 * this.zoom);
  23885. const cx = (this.right + this.left) / 2;
  23886. const cy = (this.top + this.bottom) / 2;
  23887. let left = cx - dx;
  23888. let right = cx + dx;
  23889. let top = cy + dy;
  23890. let bottom = cy - dy;
  23891. if (this.view !== null && this.view.enabled) {
  23892. const scaleW = (this.right - this.left) / this.view.fullWidth / this.zoom;
  23893. const scaleH = (this.top - this.bottom) / this.view.fullHeight / this.zoom;
  23894. left += scaleW * this.view.offsetX;
  23895. right = left + scaleW * this.view.width;
  23896. top -= scaleH * this.view.offsetY;
  23897. bottom = top - scaleH * this.view.height;
  23898. }
  23899. this.projectionMatrix.makeOrthographic(left, right, top, bottom, this.near, this.far);
  23900. this.projectionMatrixInverse.copy(this.projectionMatrix).invert();
  23901. },
  23902. toJSON: function (meta) {
  23903. const data = Object3D.prototype.toJSON.call(this, meta);
  23904. data.object.zoom = this.zoom;
  23905. data.object.left = this.left;
  23906. data.object.right = this.right;
  23907. data.object.top = this.top;
  23908. data.object.bottom = this.bottom;
  23909. data.object.near = this.near;
  23910. data.object.far = this.far;
  23911. if (this.view !== null) data.object.view = Object.assign({}, this.view);
  23912. return data;
  23913. }
  23914. });
  23915. function DirectionalLightShadow() {
  23916. LightShadow.call(this, new OrthographicCamera(-5, 5, 5, -5, 0.5, 500));
  23917. }
  23918. DirectionalLightShadow.prototype = Object.assign(Object.create(LightShadow.prototype), {
  23919. constructor: DirectionalLightShadow,
  23920. isDirectionalLightShadow: true,
  23921. updateMatrices: function (light) {
  23922. LightShadow.prototype.updateMatrices.call(this, light);
  23923. }
  23924. });
  23925. function DirectionalLight(color, intensity) {
  23926. Light.call(this, color, intensity);
  23927. this.type = 'DirectionalLight';
  23928. this.position.copy(Object3D.DefaultUp);
  23929. this.updateMatrix();
  23930. this.target = new Object3D();
  23931. this.shadow = new DirectionalLightShadow();
  23932. }
  23933. DirectionalLight.prototype = Object.assign(Object.create(Light.prototype), {
  23934. constructor: DirectionalLight,
  23935. isDirectionalLight: true,
  23936. copy: function (source) {
  23937. Light.prototype.copy.call(this, source);
  23938. this.target = source.target.clone();
  23939. this.shadow = source.shadow.clone();
  23940. return this;
  23941. }
  23942. });
  23943. function AmbientLight(color, intensity) {
  23944. Light.call(this, color, intensity);
  23945. this.type = 'AmbientLight';
  23946. }
  23947. AmbientLight.prototype = Object.assign(Object.create(Light.prototype), {
  23948. constructor: AmbientLight,
  23949. isAmbientLight: true
  23950. });
  23951. function RectAreaLight(color, intensity, width, height) {
  23952. Light.call(this, color, intensity);
  23953. this.type = 'RectAreaLight';
  23954. this.width = width !== undefined ? width : 10;
  23955. this.height = height !== undefined ? height : 10;
  23956. }
  23957. RectAreaLight.prototype = Object.assign(Object.create(Light.prototype), {
  23958. constructor: RectAreaLight,
  23959. isRectAreaLight: true,
  23960. copy: function (source) {
  23961. Light.prototype.copy.call(this, source);
  23962. this.width = source.width;
  23963. this.height = source.height;
  23964. return this;
  23965. },
  23966. toJSON: function (meta) {
  23967. const data = Light.prototype.toJSON.call(this, meta);
  23968. data.object.width = this.width;
  23969. data.object.height = this.height;
  23970. return data;
  23971. }
  23972. });
  23973. /**
  23974. * Primary reference:
  23975. * https://graphics.stanford.edu/papers/envmap/envmap.pdf
  23976. *
  23977. * Secondary reference:
  23978. * https://www.ppsloan.org/publications/StupidSH36.pdf
  23979. */
  23980. // 3-band SH defined by 9 coefficients
  23981. class SphericalHarmonics3 {
  23982. constructor() {
  23983. Object.defineProperty(this, 'isSphericalHarmonics3', {
  23984. value: true
  23985. });
  23986. this.coefficients = [];
  23987. for (let i = 0; i < 9; i++) {
  23988. this.coefficients.push(new Vector3());
  23989. }
  23990. }
  23991. set(coefficients) {
  23992. for (let i = 0; i < 9; i++) {
  23993. this.coefficients[i].copy(coefficients[i]);
  23994. }
  23995. return this;
  23996. }
  23997. zero() {
  23998. for (let i = 0; i < 9; i++) {
  23999. this.coefficients[i].set(0, 0, 0);
  24000. }
  24001. return this;
  24002. } // get the radiance in the direction of the normal
  24003. // target is a Vector3
  24004. getAt(normal, target) {
  24005. // normal is assumed to be unit length
  24006. const x = normal.x,
  24007. y = normal.y,
  24008. z = normal.z;
  24009. const coeff = this.coefficients; // band 0
  24010. target.copy(coeff[0]).multiplyScalar(0.282095); // band 1
  24011. target.addScaledVector(coeff[1], 0.488603 * y);
  24012. target.addScaledVector(coeff[2], 0.488603 * z);
  24013. target.addScaledVector(coeff[3], 0.488603 * x); // band 2
  24014. target.addScaledVector(coeff[4], 1.092548 * (x * y));
  24015. target.addScaledVector(coeff[5], 1.092548 * (y * z));
  24016. target.addScaledVector(coeff[6], 0.315392 * (3.0 * z * z - 1.0));
  24017. target.addScaledVector(coeff[7], 1.092548 * (x * z));
  24018. target.addScaledVector(coeff[8], 0.546274 * (x * x - y * y));
  24019. return target;
  24020. } // get the irradiance (radiance convolved with cosine lobe) in the direction of the normal
  24021. // target is a Vector3
  24022. // https://graphics.stanford.edu/papers/envmap/envmap.pdf
  24023. getIrradianceAt(normal, target) {
  24024. // normal is assumed to be unit length
  24025. const x = normal.x,
  24026. y = normal.y,
  24027. z = normal.z;
  24028. const coeff = this.coefficients; // band 0
  24029. target.copy(coeff[0]).multiplyScalar(0.886227); // π * 0.282095
  24030. // band 1
  24031. target.addScaledVector(coeff[1], 2.0 * 0.511664 * y); // ( 2 * π / 3 ) * 0.488603
  24032. target.addScaledVector(coeff[2], 2.0 * 0.511664 * z);
  24033. target.addScaledVector(coeff[3], 2.0 * 0.511664 * x); // band 2
  24034. target.addScaledVector(coeff[4], 2.0 * 0.429043 * x * y); // ( π / 4 ) * 1.092548
  24035. target.addScaledVector(coeff[5], 2.0 * 0.429043 * y * z);
  24036. target.addScaledVector(coeff[6], 0.743125 * z * z - 0.247708); // ( π / 4 ) * 0.315392 * 3
  24037. target.addScaledVector(coeff[7], 2.0 * 0.429043 * x * z);
  24038. target.addScaledVector(coeff[8], 0.429043 * (x * x - y * y)); // ( π / 4 ) * 0.546274
  24039. return target;
  24040. }
  24041. add(sh) {
  24042. for (let i = 0; i < 9; i++) {
  24043. this.coefficients[i].add(sh.coefficients[i]);
  24044. }
  24045. return this;
  24046. }
  24047. addScaledSH(sh, s) {
  24048. for (let i = 0; i < 9; i++) {
  24049. this.coefficients[i].addScaledVector(sh.coefficients[i], s);
  24050. }
  24051. return this;
  24052. }
  24053. scale(s) {
  24054. for (let i = 0; i < 9; i++) {
  24055. this.coefficients[i].multiplyScalar(s);
  24056. }
  24057. return this;
  24058. }
  24059. lerp(sh, alpha) {
  24060. for (let i = 0; i < 9; i++) {
  24061. this.coefficients[i].lerp(sh.coefficients[i], alpha);
  24062. }
  24063. return this;
  24064. }
  24065. equals(sh) {
  24066. for (let i = 0; i < 9; i++) {
  24067. if (!this.coefficients[i].equals(sh.coefficients[i])) {
  24068. return false;
  24069. }
  24070. }
  24071. return true;
  24072. }
  24073. copy(sh) {
  24074. return this.set(sh.coefficients);
  24075. }
  24076. clone() {
  24077. return new this.constructor().copy(this);
  24078. }
  24079. fromArray(array, offset = 0) {
  24080. const coefficients = this.coefficients;
  24081. for (let i = 0; i < 9; i++) {
  24082. coefficients[i].fromArray(array, offset + i * 3);
  24083. }
  24084. return this;
  24085. }
  24086. toArray(array = [], offset = 0) {
  24087. const coefficients = this.coefficients;
  24088. for (let i = 0; i < 9; i++) {
  24089. coefficients[i].toArray(array, offset + i * 3);
  24090. }
  24091. return array;
  24092. } // evaluate the basis functions
  24093. // shBasis is an Array[ 9 ]
  24094. static getBasisAt(normal, shBasis) {
  24095. // normal is assumed to be unit length
  24096. const x = normal.x,
  24097. y = normal.y,
  24098. z = normal.z; // band 0
  24099. shBasis[0] = 0.282095; // band 1
  24100. shBasis[1] = 0.488603 * y;
  24101. shBasis[2] = 0.488603 * z;
  24102. shBasis[3] = 0.488603 * x; // band 2
  24103. shBasis[4] = 1.092548 * x * y;
  24104. shBasis[5] = 1.092548 * y * z;
  24105. shBasis[6] = 0.315392 * (3 * z * z - 1);
  24106. shBasis[7] = 1.092548 * x * z;
  24107. shBasis[8] = 0.546274 * (x * x - y * y);
  24108. }
  24109. }
  24110. exports.SphericalHarmonics3 = SphericalHarmonics3;
  24111. function LightProbe(sh, intensity) {
  24112. Light.call(this, undefined, intensity);
  24113. this.type = 'LightProbe';
  24114. this.sh = sh !== undefined ? sh : new SphericalHarmonics3();
  24115. }
  24116. LightProbe.prototype = Object.assign(Object.create(Light.prototype), {
  24117. constructor: LightProbe,
  24118. isLightProbe: true,
  24119. copy: function (source) {
  24120. Light.prototype.copy.call(this, source);
  24121. this.sh.copy(source.sh);
  24122. return this;
  24123. },
  24124. fromJSON: function (json) {
  24125. this.intensity = json.intensity; // TODO: Move this bit to Light.fromJSON();
  24126. this.sh.fromArray(json.sh);
  24127. return this;
  24128. },
  24129. toJSON: function (meta) {
  24130. const data = Light.prototype.toJSON.call(this, meta);
  24131. data.object.sh = this.sh.toArray();
  24132. return data;
  24133. }
  24134. });
  24135. function MaterialLoader(manager) {
  24136. Loader.call(this, manager);
  24137. this.textures = {};
  24138. }
  24139. MaterialLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  24140. constructor: MaterialLoader,
  24141. load: function (url, onLoad, onProgress, onError) {
  24142. const scope = this;
  24143. const loader = new FileLoader(scope.manager);
  24144. loader.setPath(scope.path);
  24145. loader.setRequestHeader(scope.requestHeader);
  24146. loader.setWithCredentials(scope.withCredentials);
  24147. loader.load(url, function (text) {
  24148. try {
  24149. onLoad(scope.parse(JSON.parse(text)));
  24150. } catch (e) {
  24151. if (onError) {
  24152. onError(e);
  24153. } else {
  24154. console.error(e);
  24155. }
  24156. scope.manager.itemError(url);
  24157. }
  24158. }, onProgress, onError);
  24159. },
  24160. parse: function (json) {
  24161. const textures = this.textures;
  24162. function getTexture(name) {
  24163. if (textures[name] === undefined) {
  24164. console.warn('THREE.MaterialLoader: Undefined texture', name);
  24165. }
  24166. return textures[name];
  24167. }
  24168. const material = new Materials[json.type]();
  24169. if (json.uuid !== undefined) material.uuid = json.uuid;
  24170. if (json.name !== undefined) material.name = json.name;
  24171. if (json.color !== undefined && material.color !== undefined) material.color.setHex(json.color);
  24172. if (json.roughness !== undefined) material.roughness = json.roughness;
  24173. if (json.metalness !== undefined) material.metalness = json.metalness;
  24174. if (json.sheen !== undefined) material.sheen = new Color().setHex(json.sheen);
  24175. if (json.emissive !== undefined && material.emissive !== undefined) material.emissive.setHex(json.emissive);
  24176. if (json.specular !== undefined && material.specular !== undefined) material.specular.setHex(json.specular);
  24177. if (json.shininess !== undefined) material.shininess = json.shininess;
  24178. if (json.clearcoat !== undefined) material.clearcoat = json.clearcoat;
  24179. if (json.clearcoatRoughness !== undefined) material.clearcoatRoughness = json.clearcoatRoughness;
  24180. if (json.fog !== undefined) material.fog = json.fog;
  24181. if (json.flatShading !== undefined) material.flatShading = json.flatShading;
  24182. if (json.blending !== undefined) material.blending = json.blending;
  24183. if (json.combine !== undefined) material.combine = json.combine;
  24184. if (json.side !== undefined) material.side = json.side;
  24185. if (json.opacity !== undefined) material.opacity = json.opacity;
  24186. if (json.transparent !== undefined) material.transparent = json.transparent;
  24187. if (json.alphaTest !== undefined) material.alphaTest = json.alphaTest;
  24188. if (json.depthTest !== undefined) material.depthTest = json.depthTest;
  24189. if (json.depthWrite !== undefined) material.depthWrite = json.depthWrite;
  24190. if (json.colorWrite !== undefined) material.colorWrite = json.colorWrite;
  24191. if (json.stencilWrite !== undefined) material.stencilWrite = json.stencilWrite;
  24192. if (json.stencilWriteMask !== undefined) material.stencilWriteMask = json.stencilWriteMask;
  24193. if (json.stencilFunc !== undefined) material.stencilFunc = json.stencilFunc;
  24194. if (json.stencilRef !== undefined) material.stencilRef = json.stencilRef;
  24195. if (json.stencilFuncMask !== undefined) material.stencilFuncMask = json.stencilFuncMask;
  24196. if (json.stencilFail !== undefined) material.stencilFail = json.stencilFail;
  24197. if (json.stencilZFail !== undefined) material.stencilZFail = json.stencilZFail;
  24198. if (json.stencilZPass !== undefined) material.stencilZPass = json.stencilZPass;
  24199. if (json.wireframe !== undefined) material.wireframe = json.wireframe;
  24200. if (json.wireframeLinewidth !== undefined) material.wireframeLinewidth = json.wireframeLinewidth;
  24201. if (json.wireframeLinecap !== undefined) material.wireframeLinecap = json.wireframeLinecap;
  24202. if (json.wireframeLinejoin !== undefined) material.wireframeLinejoin = json.wireframeLinejoin;
  24203. if (json.rotation !== undefined) material.rotation = json.rotation;
  24204. if (json.linewidth !== 1) material.linewidth = json.linewidth;
  24205. if (json.dashSize !== undefined) material.dashSize = json.dashSize;
  24206. if (json.gapSize !== undefined) material.gapSize = json.gapSize;
  24207. if (json.scale !== undefined) material.scale = json.scale;
  24208. if (json.polygonOffset !== undefined) material.polygonOffset = json.polygonOffset;
  24209. if (json.polygonOffsetFactor !== undefined) material.polygonOffsetFactor = json.polygonOffsetFactor;
  24210. if (json.polygonOffsetUnits !== undefined) material.polygonOffsetUnits = json.polygonOffsetUnits;
  24211. if (json.skinning !== undefined) material.skinning = json.skinning;
  24212. if (json.morphTargets !== undefined) material.morphTargets = json.morphTargets;
  24213. if (json.morphNormals !== undefined) material.morphNormals = json.morphNormals;
  24214. if (json.dithering !== undefined) material.dithering = json.dithering;
  24215. if (json.vertexTangents !== undefined) material.vertexTangents = json.vertexTangents;
  24216. if (json.visible !== undefined) material.visible = json.visible;
  24217. if (json.toneMapped !== undefined) material.toneMapped = json.toneMapped;
  24218. if (json.userData !== undefined) material.userData = json.userData;
  24219. if (json.vertexColors !== undefined) {
  24220. if (typeof json.vertexColors === 'number') {
  24221. material.vertexColors = json.vertexColors > 0 ? true : false;
  24222. } else {
  24223. material.vertexColors = json.vertexColors;
  24224. }
  24225. } // Shader Material
  24226. if (json.uniforms !== undefined) {
  24227. for (const name in json.uniforms) {
  24228. const uniform = json.uniforms[name];
  24229. material.uniforms[name] = {};
  24230. switch (uniform.type) {
  24231. case 't':
  24232. material.uniforms[name].value = getTexture(uniform.value);
  24233. break;
  24234. case 'c':
  24235. material.uniforms[name].value = new Color().setHex(uniform.value);
  24236. break;
  24237. case 'v2':
  24238. material.uniforms[name].value = new Vector2().fromArray(uniform.value);
  24239. break;
  24240. case 'v3':
  24241. material.uniforms[name].value = new Vector3().fromArray(uniform.value);
  24242. break;
  24243. case 'v4':
  24244. material.uniforms[name].value = new Vector4().fromArray(uniform.value);
  24245. break;
  24246. case 'm3':
  24247. material.uniforms[name].value = new Matrix3().fromArray(uniform.value);
  24248. break;
  24249. case 'm4':
  24250. material.uniforms[name].value = new Matrix4().fromArray(uniform.value);
  24251. break;
  24252. default:
  24253. material.uniforms[name].value = uniform.value;
  24254. }
  24255. }
  24256. }
  24257. if (json.defines !== undefined) material.defines = json.defines;
  24258. if (json.vertexShader !== undefined) material.vertexShader = json.vertexShader;
  24259. if (json.fragmentShader !== undefined) material.fragmentShader = json.fragmentShader;
  24260. if (json.extensions !== undefined) {
  24261. for (const key in json.extensions) {
  24262. material.extensions[key] = json.extensions[key];
  24263. }
  24264. } // Deprecated
  24265. if (json.shading !== undefined) material.flatShading = json.shading === 1; // THREE.FlatShading
  24266. // for PointsMaterial
  24267. if (json.size !== undefined) material.size = json.size;
  24268. if (json.sizeAttenuation !== undefined) material.sizeAttenuation = json.sizeAttenuation; // maps
  24269. if (json.map !== undefined) material.map = getTexture(json.map);
  24270. if (json.matcap !== undefined) material.matcap = getTexture(json.matcap);
  24271. if (json.alphaMap !== undefined) material.alphaMap = getTexture(json.alphaMap);
  24272. if (json.bumpMap !== undefined) material.bumpMap = getTexture(json.bumpMap);
  24273. if (json.bumpScale !== undefined) material.bumpScale = json.bumpScale;
  24274. if (json.normalMap !== undefined) material.normalMap = getTexture(json.normalMap);
  24275. if (json.normalMapType !== undefined) material.normalMapType = json.normalMapType;
  24276. if (json.normalScale !== undefined) {
  24277. let normalScale = json.normalScale;
  24278. if (Array.isArray(normalScale) === false) {
  24279. // Blender exporter used to export a scalar. See #7459
  24280. normalScale = [normalScale, normalScale];
  24281. }
  24282. material.normalScale = new Vector2().fromArray(normalScale);
  24283. }
  24284. if (json.displacementMap !== undefined) material.displacementMap = getTexture(json.displacementMap);
  24285. if (json.displacementScale !== undefined) material.displacementScale = json.displacementScale;
  24286. if (json.displacementBias !== undefined) material.displacementBias = json.displacementBias;
  24287. if (json.roughnessMap !== undefined) material.roughnessMap = getTexture(json.roughnessMap);
  24288. if (json.metalnessMap !== undefined) material.metalnessMap = getTexture(json.metalnessMap);
  24289. if (json.emissiveMap !== undefined) material.emissiveMap = getTexture(json.emissiveMap);
  24290. if (json.emissiveIntensity !== undefined) material.emissiveIntensity = json.emissiveIntensity;
  24291. if (json.specularMap !== undefined) material.specularMap = getTexture(json.specularMap);
  24292. if (json.envMap !== undefined) material.envMap = getTexture(json.envMap);
  24293. if (json.envMapIntensity !== undefined) material.envMapIntensity = json.envMapIntensity;
  24294. if (json.reflectivity !== undefined) material.reflectivity = json.reflectivity;
  24295. if (json.refractionRatio !== undefined) material.refractionRatio = json.refractionRatio;
  24296. if (json.lightMap !== undefined) material.lightMap = getTexture(json.lightMap);
  24297. if (json.lightMapIntensity !== undefined) material.lightMapIntensity = json.lightMapIntensity;
  24298. if (json.aoMap !== undefined) material.aoMap = getTexture(json.aoMap);
  24299. if (json.aoMapIntensity !== undefined) material.aoMapIntensity = json.aoMapIntensity;
  24300. if (json.gradientMap !== undefined) material.gradientMap = getTexture(json.gradientMap);
  24301. if (json.clearcoatMap !== undefined) material.clearcoatMap = getTexture(json.clearcoatMap);
  24302. if (json.clearcoatRoughnessMap !== undefined) material.clearcoatRoughnessMap = getTexture(json.clearcoatRoughnessMap);
  24303. if (json.clearcoatNormalMap !== undefined) material.clearcoatNormalMap = getTexture(json.clearcoatNormalMap);
  24304. if (json.clearcoatNormalScale !== undefined) material.clearcoatNormalScale = new Vector2().fromArray(json.clearcoatNormalScale);
  24305. if (json.transmission !== undefined) material.transmission = json.transmission;
  24306. if (json.transmissionMap !== undefined) material.transmissionMap = getTexture(json.transmissionMap);
  24307. return material;
  24308. },
  24309. setTextures: function (value) {
  24310. this.textures = value;
  24311. return this;
  24312. }
  24313. });
  24314. const LoaderUtils = {
  24315. decodeText: function (array) {
  24316. if (typeof TextDecoder !== 'undefined') {
  24317. return new TextDecoder().decode(array);
  24318. } // Avoid the String.fromCharCode.apply(null, array) shortcut, which
  24319. // throws a "maximum call stack size exceeded" error for large arrays.
  24320. let s = '';
  24321. for (let i = 0, il = array.length; i < il; i++) {
  24322. // Implicitly assumes little-endian.
  24323. s += String.fromCharCode(array[i]);
  24324. }
  24325. try {
  24326. // merges multi-byte utf-8 characters.
  24327. return decodeURIComponent(escape(s));
  24328. } catch (e) {
  24329. // see #16358
  24330. return s;
  24331. }
  24332. },
  24333. extractUrlBase: function (url) {
  24334. const index = url.lastIndexOf('/');
  24335. if (index === -1) return './';
  24336. return url.substr(0, index + 1);
  24337. }
  24338. };
  24339. exports.LoaderUtils = LoaderUtils;
  24340. function InstancedBufferGeometry() {
  24341. BufferGeometry.call(this);
  24342. this.type = 'InstancedBufferGeometry';
  24343. this.instanceCount = Infinity;
  24344. }
  24345. InstancedBufferGeometry.prototype = Object.assign(Object.create(BufferGeometry.prototype), {
  24346. constructor: InstancedBufferGeometry,
  24347. isInstancedBufferGeometry: true,
  24348. copy: function (source) {
  24349. BufferGeometry.prototype.copy.call(this, source);
  24350. this.instanceCount = source.instanceCount;
  24351. return this;
  24352. },
  24353. clone: function () {
  24354. return new this.constructor().copy(this);
  24355. },
  24356. toJSON: function () {
  24357. const data = BufferGeometry.prototype.toJSON.call(this);
  24358. data.instanceCount = this.instanceCount;
  24359. data.isInstancedBufferGeometry = true;
  24360. return data;
  24361. }
  24362. });
  24363. function InstancedBufferAttribute(array, itemSize, normalized, meshPerAttribute) {
  24364. if (typeof normalized === 'number') {
  24365. meshPerAttribute = normalized;
  24366. normalized = false;
  24367. console.error('THREE.InstancedBufferAttribute: The constructor now expects normalized as the third argument.');
  24368. }
  24369. BufferAttribute.call(this, array, itemSize, normalized);
  24370. this.meshPerAttribute = meshPerAttribute || 1;
  24371. }
  24372. InstancedBufferAttribute.prototype = Object.assign(Object.create(BufferAttribute.prototype), {
  24373. constructor: InstancedBufferAttribute,
  24374. isInstancedBufferAttribute: true,
  24375. copy: function (source) {
  24376. BufferAttribute.prototype.copy.call(this, source);
  24377. this.meshPerAttribute = source.meshPerAttribute;
  24378. return this;
  24379. },
  24380. toJSON: function () {
  24381. const data = BufferAttribute.prototype.toJSON.call(this);
  24382. data.meshPerAttribute = this.meshPerAttribute;
  24383. data.isInstancedBufferAttribute = true;
  24384. return data;
  24385. }
  24386. });
  24387. function BufferGeometryLoader(manager) {
  24388. Loader.call(this, manager);
  24389. }
  24390. BufferGeometryLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  24391. constructor: BufferGeometryLoader,
  24392. load: function (url, onLoad, onProgress, onError) {
  24393. const scope = this;
  24394. const loader = new FileLoader(scope.manager);
  24395. loader.setPath(scope.path);
  24396. loader.setRequestHeader(scope.requestHeader);
  24397. loader.setWithCredentials(scope.withCredentials);
  24398. loader.load(url, function (text) {
  24399. try {
  24400. onLoad(scope.parse(JSON.parse(text)));
  24401. } catch (e) {
  24402. if (onError) {
  24403. onError(e);
  24404. } else {
  24405. console.error(e);
  24406. }
  24407. scope.manager.itemError(url);
  24408. }
  24409. }, onProgress, onError);
  24410. },
  24411. parse: function (json) {
  24412. const interleavedBufferMap = {};
  24413. const arrayBufferMap = {};
  24414. function getInterleavedBuffer(json, uuid) {
  24415. if (interleavedBufferMap[uuid] !== undefined) return interleavedBufferMap[uuid];
  24416. const interleavedBuffers = json.interleavedBuffers;
  24417. const interleavedBuffer = interleavedBuffers[uuid];
  24418. const buffer = getArrayBuffer(json, interleavedBuffer.buffer);
  24419. const array = getTypedArray(interleavedBuffer.type, buffer);
  24420. const ib = new InterleavedBuffer(array, interleavedBuffer.stride);
  24421. ib.uuid = interleavedBuffer.uuid;
  24422. interleavedBufferMap[uuid] = ib;
  24423. return ib;
  24424. }
  24425. function getArrayBuffer(json, uuid) {
  24426. if (arrayBufferMap[uuid] !== undefined) return arrayBufferMap[uuid];
  24427. const arrayBuffers = json.arrayBuffers;
  24428. const arrayBuffer = arrayBuffers[uuid];
  24429. const ab = new Uint32Array(arrayBuffer).buffer;
  24430. arrayBufferMap[uuid] = ab;
  24431. return ab;
  24432. }
  24433. const geometry = json.isInstancedBufferGeometry ? new InstancedBufferGeometry() : new BufferGeometry();
  24434. const index = json.data.index;
  24435. if (index !== undefined) {
  24436. const typedArray = getTypedArray(index.type, index.array);
  24437. geometry.setIndex(new BufferAttribute(typedArray, 1));
  24438. }
  24439. const attributes = json.data.attributes;
  24440. for (const key in attributes) {
  24441. const attribute = attributes[key];
  24442. let bufferAttribute;
  24443. if (attribute.isInterleavedBufferAttribute) {
  24444. const interleavedBuffer = getInterleavedBuffer(json.data, attribute.data);
  24445. bufferAttribute = new InterleavedBufferAttribute(interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized);
  24446. } else {
  24447. const typedArray = getTypedArray(attribute.type, attribute.array);
  24448. const bufferAttributeConstr = attribute.isInstancedBufferAttribute ? InstancedBufferAttribute : BufferAttribute;
  24449. bufferAttribute = new bufferAttributeConstr(typedArray, attribute.itemSize, attribute.normalized);
  24450. }
  24451. if (attribute.name !== undefined) bufferAttribute.name = attribute.name;
  24452. geometry.setAttribute(key, bufferAttribute);
  24453. }
  24454. const morphAttributes = json.data.morphAttributes;
  24455. if (morphAttributes) {
  24456. for (const key in morphAttributes) {
  24457. const attributeArray = morphAttributes[key];
  24458. const array = [];
  24459. for (let i = 0, il = attributeArray.length; i < il; i++) {
  24460. const attribute = attributeArray[i];
  24461. let bufferAttribute;
  24462. if (attribute.isInterleavedBufferAttribute) {
  24463. const interleavedBuffer = getInterleavedBuffer(json.data, attribute.data);
  24464. bufferAttribute = new InterleavedBufferAttribute(interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized);
  24465. } else {
  24466. const typedArray = getTypedArray(attribute.type, attribute.array);
  24467. bufferAttribute = new BufferAttribute(typedArray, attribute.itemSize, attribute.normalized);
  24468. }
  24469. if (attribute.name !== undefined) bufferAttribute.name = attribute.name;
  24470. array.push(bufferAttribute);
  24471. }
  24472. geometry.morphAttributes[key] = array;
  24473. }
  24474. }
  24475. const morphTargetsRelative = json.data.morphTargetsRelative;
  24476. if (morphTargetsRelative) {
  24477. geometry.morphTargetsRelative = true;
  24478. }
  24479. const groups = json.data.groups || json.data.drawcalls || json.data.offsets;
  24480. if (groups !== undefined) {
  24481. for (let i = 0, n = groups.length; i !== n; ++i) {
  24482. const group = groups[i];
  24483. geometry.addGroup(group.start, group.count, group.materialIndex);
  24484. }
  24485. }
  24486. const boundingSphere = json.data.boundingSphere;
  24487. if (boundingSphere !== undefined) {
  24488. const center = new Vector3();
  24489. if (boundingSphere.center !== undefined) {
  24490. center.fromArray(boundingSphere.center);
  24491. }
  24492. geometry.boundingSphere = new Sphere(center, boundingSphere.radius);
  24493. }
  24494. if (json.name) geometry.name = json.name;
  24495. if (json.userData) geometry.userData = json.userData;
  24496. return geometry;
  24497. }
  24498. });
  24499. class ObjectLoader extends Loader {
  24500. constructor(manager) {
  24501. super(manager);
  24502. }
  24503. load(url, onLoad, onProgress, onError) {
  24504. const scope = this;
  24505. const path = this.path === '' ? LoaderUtils.extractUrlBase(url) : this.path;
  24506. this.resourcePath = this.resourcePath || path;
  24507. const loader = new FileLoader(this.manager);
  24508. loader.setPath(this.path);
  24509. loader.setRequestHeader(this.requestHeader);
  24510. loader.setWithCredentials(this.withCredentials);
  24511. loader.load(url, function (text) {
  24512. let json = null;
  24513. try {
  24514. json = JSON.parse(text);
  24515. } catch (error) {
  24516. if (onError !== undefined) onError(error);
  24517. console.error('THREE:ObjectLoader: Can\'t parse ' + url + '.', error.message);
  24518. return;
  24519. }
  24520. const metadata = json.metadata;
  24521. if (metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry') {
  24522. console.error('THREE.ObjectLoader: Can\'t load ' + url);
  24523. return;
  24524. }
  24525. scope.parse(json, onLoad);
  24526. }, onProgress, onError);
  24527. }
  24528. parse(json, onLoad) {
  24529. const animations = this.parseAnimations(json.animations);
  24530. const shapes = this.parseShapes(json.shapes);
  24531. const geometries = this.parseGeometries(json.geometries, shapes);
  24532. const images = this.parseImages(json.images, function () {
  24533. if (onLoad !== undefined) onLoad(object);
  24534. });
  24535. const textures = this.parseTextures(json.textures, images);
  24536. const materials = this.parseMaterials(json.materials, textures);
  24537. const object = this.parseObject(json.object, geometries, materials, animations);
  24538. const skeletons = this.parseSkeletons(json.skeletons, object);
  24539. this.bindSkeletons(object, skeletons); //
  24540. if (onLoad !== undefined) {
  24541. let hasImages = false;
  24542. for (const uuid in images) {
  24543. if (images[uuid] instanceof HTMLImageElement) {
  24544. hasImages = true;
  24545. break;
  24546. }
  24547. }
  24548. if (hasImages === false) onLoad(object);
  24549. }
  24550. return object;
  24551. }
  24552. parseShapes(json) {
  24553. const shapes = {};
  24554. if (json !== undefined) {
  24555. for (let i = 0, l = json.length; i < l; i++) {
  24556. const shape = new Shape().fromJSON(json[i]);
  24557. shapes[shape.uuid] = shape;
  24558. }
  24559. }
  24560. return shapes;
  24561. }
  24562. parseSkeletons(json, object) {
  24563. const skeletons = {};
  24564. const bones = {}; // generate bone lookup table
  24565. object.traverse(function (child) {
  24566. if (child.isBone) bones[child.uuid] = child;
  24567. }); // create skeletons
  24568. if (json !== undefined) {
  24569. for (let i = 0, l = json.length; i < l; i++) {
  24570. const skeleton = new Skeleton().fromJSON(json[i], bones);
  24571. skeletons[skeleton.uuid] = skeleton;
  24572. }
  24573. }
  24574. return skeletons;
  24575. }
  24576. parseGeometries(json, shapes) {
  24577. const geometries = {};
  24578. let geometryShapes;
  24579. if (json !== undefined) {
  24580. const bufferGeometryLoader = new BufferGeometryLoader();
  24581. for (let i = 0, l = json.length; i < l; i++) {
  24582. let geometry;
  24583. const data = json[i];
  24584. switch (data.type) {
  24585. case 'PlaneGeometry':
  24586. case 'PlaneBufferGeometry':
  24587. geometry = new Geometries[data.type](data.width, data.height, data.widthSegments, data.heightSegments);
  24588. break;
  24589. case 'BoxGeometry':
  24590. case 'BoxBufferGeometry':
  24591. case 'CubeGeometry':
  24592. // backwards compatible
  24593. geometry = new Geometries[data.type](data.width, data.height, data.depth, data.widthSegments, data.heightSegments, data.depthSegments);
  24594. break;
  24595. case 'CircleGeometry':
  24596. case 'CircleBufferGeometry':
  24597. geometry = new Geometries[data.type](data.radius, data.segments, data.thetaStart, data.thetaLength);
  24598. break;
  24599. case 'CylinderGeometry':
  24600. case 'CylinderBufferGeometry':
  24601. geometry = new Geometries[data.type](data.radiusTop, data.radiusBottom, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength);
  24602. break;
  24603. case 'ConeGeometry':
  24604. case 'ConeBufferGeometry':
  24605. geometry = new Geometries[data.type](data.radius, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength);
  24606. break;
  24607. case 'SphereGeometry':
  24608. case 'SphereBufferGeometry':
  24609. geometry = new Geometries[data.type](data.radius, data.widthSegments, data.heightSegments, data.phiStart, data.phiLength, data.thetaStart, data.thetaLength);
  24610. break;
  24611. case 'DodecahedronGeometry':
  24612. case 'DodecahedronBufferGeometry':
  24613. case 'IcosahedronGeometry':
  24614. case 'IcosahedronBufferGeometry':
  24615. case 'OctahedronGeometry':
  24616. case 'OctahedronBufferGeometry':
  24617. case 'TetrahedronGeometry':
  24618. case 'TetrahedronBufferGeometry':
  24619. geometry = new Geometries[data.type](data.radius, data.detail);
  24620. break;
  24621. case 'RingGeometry':
  24622. case 'RingBufferGeometry':
  24623. geometry = new Geometries[data.type](data.innerRadius, data.outerRadius, data.thetaSegments, data.phiSegments, data.thetaStart, data.thetaLength);
  24624. break;
  24625. case 'TorusGeometry':
  24626. case 'TorusBufferGeometry':
  24627. geometry = new Geometries[data.type](data.radius, data.tube, data.radialSegments, data.tubularSegments, data.arc);
  24628. break;
  24629. case 'TorusKnotGeometry':
  24630. case 'TorusKnotBufferGeometry':
  24631. geometry = new Geometries[data.type](data.radius, data.tube, data.tubularSegments, data.radialSegments, data.p, data.q);
  24632. break;
  24633. case 'TubeGeometry':
  24634. case 'TubeBufferGeometry':
  24635. // This only works for built-in curves (e.g. CatmullRomCurve3).
  24636. // User defined curves or instances of CurvePath will not be deserialized.
  24637. geometry = new Geometries[data.type](new Curves[data.path.type]().fromJSON(data.path), data.tubularSegments, data.radius, data.radialSegments, data.closed);
  24638. break;
  24639. case 'LatheGeometry':
  24640. case 'LatheBufferGeometry':
  24641. geometry = new Geometries[data.type](data.points, data.segments, data.phiStart, data.phiLength);
  24642. break;
  24643. case 'PolyhedronGeometry':
  24644. case 'PolyhedronBufferGeometry':
  24645. geometry = new Geometries[data.type](data.vertices, data.indices, data.radius, data.details);
  24646. break;
  24647. case 'ShapeGeometry':
  24648. case 'ShapeBufferGeometry':
  24649. geometryShapes = [];
  24650. for (let j = 0, jl = data.shapes.length; j < jl; j++) {
  24651. const shape = shapes[data.shapes[j]];
  24652. geometryShapes.push(shape);
  24653. }
  24654. geometry = new Geometries[data.type](geometryShapes, data.curveSegments);
  24655. break;
  24656. case 'ExtrudeGeometry':
  24657. case 'ExtrudeBufferGeometry':
  24658. geometryShapes = [];
  24659. for (let j = 0, jl = data.shapes.length; j < jl; j++) {
  24660. const shape = shapes[data.shapes[j]];
  24661. geometryShapes.push(shape);
  24662. }
  24663. const extrudePath = data.options.extrudePath;
  24664. if (extrudePath !== undefined) {
  24665. data.options.extrudePath = new Curves[extrudePath.type]().fromJSON(extrudePath);
  24666. }
  24667. geometry = new Geometries[data.type](geometryShapes, data.options);
  24668. break;
  24669. case 'BufferGeometry':
  24670. case 'InstancedBufferGeometry':
  24671. geometry = bufferGeometryLoader.parse(data);
  24672. break;
  24673. case 'Geometry':
  24674. console.error('THREE.ObjectLoader: Loading "Geometry" is not supported anymore.');
  24675. break;
  24676. default:
  24677. console.warn('THREE.ObjectLoader: Unsupported geometry type "' + data.type + '"');
  24678. continue;
  24679. }
  24680. geometry.uuid = data.uuid;
  24681. if (data.name !== undefined) geometry.name = data.name;
  24682. if (geometry.isBufferGeometry === true && data.userData !== undefined) geometry.userData = data.userData;
  24683. geometries[data.uuid] = geometry;
  24684. }
  24685. }
  24686. return geometries;
  24687. }
  24688. parseMaterials(json, textures) {
  24689. const cache = {}; // MultiMaterial
  24690. const materials = {};
  24691. if (json !== undefined) {
  24692. const loader = new MaterialLoader();
  24693. loader.setTextures(textures);
  24694. for (let i = 0, l = json.length; i < l; i++) {
  24695. const data = json[i];
  24696. if (data.type === 'MultiMaterial') {
  24697. // Deprecated
  24698. const array = [];
  24699. for (let j = 0; j < data.materials.length; j++) {
  24700. const material = data.materials[j];
  24701. if (cache[material.uuid] === undefined) {
  24702. cache[material.uuid] = loader.parse(material);
  24703. }
  24704. array.push(cache[material.uuid]);
  24705. }
  24706. materials[data.uuid] = array;
  24707. } else {
  24708. if (cache[data.uuid] === undefined) {
  24709. cache[data.uuid] = loader.parse(data);
  24710. }
  24711. materials[data.uuid] = cache[data.uuid];
  24712. }
  24713. }
  24714. }
  24715. return materials;
  24716. }
  24717. parseAnimations(json) {
  24718. const animations = {};
  24719. if (json !== undefined) {
  24720. for (let i = 0; i < json.length; i++) {
  24721. const data = json[i];
  24722. const clip = AnimationClip.parse(data);
  24723. animations[clip.uuid] = clip;
  24724. }
  24725. }
  24726. return animations;
  24727. }
  24728. parseImages(json, onLoad) {
  24729. const scope = this;
  24730. const images = {};
  24731. let loader;
  24732. function loadImage(url) {
  24733. scope.manager.itemStart(url);
  24734. return loader.load(url, function () {
  24735. scope.manager.itemEnd(url);
  24736. }, undefined, function () {
  24737. scope.manager.itemError(url);
  24738. scope.manager.itemEnd(url);
  24739. });
  24740. }
  24741. function deserializeImage(image) {
  24742. if (typeof image === 'string') {
  24743. const url = image;
  24744. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test(url) ? url : scope.resourcePath + url;
  24745. return loadImage(path);
  24746. } else {
  24747. if (image.data) {
  24748. return {
  24749. data: getTypedArray(image.type, image.data),
  24750. width: image.width,
  24751. height: image.height
  24752. };
  24753. } else {
  24754. return null;
  24755. }
  24756. }
  24757. }
  24758. if (json !== undefined && json.length > 0) {
  24759. const manager = new LoadingManager(onLoad);
  24760. loader = new ImageLoader(manager);
  24761. loader.setCrossOrigin(this.crossOrigin);
  24762. for (let i = 0, il = json.length; i < il; i++) {
  24763. const image = json[i];
  24764. const url = image.url;
  24765. if (Array.isArray(url)) {
  24766. // load array of images e.g CubeTexture
  24767. images[image.uuid] = [];
  24768. for (let j = 0, jl = url.length; j < jl; j++) {
  24769. const currentUrl = url[j];
  24770. const deserializedImage = deserializeImage(currentUrl);
  24771. if (deserializedImage !== null) {
  24772. if (deserializedImage instanceof HTMLImageElement) {
  24773. images[image.uuid].push(deserializedImage);
  24774. } else {
  24775. // special case: handle array of data textures for cube textures
  24776. images[image.uuid].push(new DataTexture(deserializedImage.data, deserializedImage.width, deserializedImage.height));
  24777. }
  24778. }
  24779. }
  24780. } else {
  24781. // load single image
  24782. const deserializedImage = deserializeImage(image.url);
  24783. if (deserializedImage !== null) {
  24784. images[image.uuid] = deserializedImage;
  24785. }
  24786. }
  24787. }
  24788. }
  24789. return images;
  24790. }
  24791. parseTextures(json, images) {
  24792. function parseConstant(value, type) {
  24793. if (typeof value === 'number') return value;
  24794. console.warn('THREE.ObjectLoader.parseTexture: Constant should be in numeric form.', value);
  24795. return type[value];
  24796. }
  24797. const textures = {};
  24798. if (json !== undefined) {
  24799. for (let i = 0, l = json.length; i < l; i++) {
  24800. const data = json[i];
  24801. if (data.image === undefined) {
  24802. console.warn('THREE.ObjectLoader: No "image" specified for', data.uuid);
  24803. }
  24804. if (images[data.image] === undefined) {
  24805. console.warn('THREE.ObjectLoader: Undefined image', data.image);
  24806. }
  24807. let texture;
  24808. const image = images[data.image];
  24809. if (Array.isArray(image)) {
  24810. texture = new CubeTexture(image);
  24811. if (image.length === 6) texture.needsUpdate = true;
  24812. } else {
  24813. if (image && image.data) {
  24814. texture = new DataTexture(image.data, image.width, image.height);
  24815. } else {
  24816. texture = new Texture(image);
  24817. }
  24818. if (image) texture.needsUpdate = true; // textures can have undefined image data
  24819. }
  24820. texture.uuid = data.uuid;
  24821. if (data.name !== undefined) texture.name = data.name;
  24822. if (data.mapping !== undefined) texture.mapping = parseConstant(data.mapping, TEXTURE_MAPPING);
  24823. if (data.offset !== undefined) texture.offset.fromArray(data.offset);
  24824. if (data.repeat !== undefined) texture.repeat.fromArray(data.repeat);
  24825. if (data.center !== undefined) texture.center.fromArray(data.center);
  24826. if (data.rotation !== undefined) texture.rotation = data.rotation;
  24827. if (data.wrap !== undefined) {
  24828. texture.wrapS = parseConstant(data.wrap[0], TEXTURE_WRAPPING);
  24829. texture.wrapT = parseConstant(data.wrap[1], TEXTURE_WRAPPING);
  24830. }
  24831. if (data.format !== undefined) texture.format = data.format;
  24832. if (data.type !== undefined) texture.type = data.type;
  24833. if (data.encoding !== undefined) texture.encoding = data.encoding;
  24834. if (data.minFilter !== undefined) texture.minFilter = parseConstant(data.minFilter, TEXTURE_FILTER);
  24835. if (data.magFilter !== undefined) texture.magFilter = parseConstant(data.magFilter, TEXTURE_FILTER);
  24836. if (data.anisotropy !== undefined) texture.anisotropy = data.anisotropy;
  24837. if (data.flipY !== undefined) texture.flipY = data.flipY;
  24838. if (data.premultiplyAlpha !== undefined) texture.premultiplyAlpha = data.premultiplyAlpha;
  24839. if (data.unpackAlignment !== undefined) texture.unpackAlignment = data.unpackAlignment;
  24840. textures[data.uuid] = texture;
  24841. }
  24842. }
  24843. return textures;
  24844. }
  24845. parseObject(data, geometries, materials, animations) {
  24846. let object;
  24847. function getGeometry(name) {
  24848. if (geometries[name] === undefined) {
  24849. console.warn('THREE.ObjectLoader: Undefined geometry', name);
  24850. }
  24851. return geometries[name];
  24852. }
  24853. function getMaterial(name) {
  24854. if (name === undefined) return undefined;
  24855. if (Array.isArray(name)) {
  24856. const array = [];
  24857. for (let i = 0, l = name.length; i < l; i++) {
  24858. const uuid = name[i];
  24859. if (materials[uuid] === undefined) {
  24860. console.warn('THREE.ObjectLoader: Undefined material', uuid);
  24861. }
  24862. array.push(materials[uuid]);
  24863. }
  24864. return array;
  24865. }
  24866. if (materials[name] === undefined) {
  24867. console.warn('THREE.ObjectLoader: Undefined material', name);
  24868. }
  24869. return materials[name];
  24870. }
  24871. let geometry, material;
  24872. switch (data.type) {
  24873. case 'Scene':
  24874. object = new Scene();
  24875. if (data.background !== undefined) {
  24876. if (Number.isInteger(data.background)) {
  24877. object.background = new Color(data.background);
  24878. }
  24879. }
  24880. if (data.fog !== undefined) {
  24881. if (data.fog.type === 'Fog') {
  24882. object.fog = new Fog(data.fog.color, data.fog.near, data.fog.far);
  24883. } else if (data.fog.type === 'FogExp2') {
  24884. object.fog = new FogExp2(data.fog.color, data.fog.density);
  24885. }
  24886. }
  24887. break;
  24888. case 'PerspectiveCamera':
  24889. object = new PerspectiveCamera(data.fov, data.aspect, data.near, data.far);
  24890. if (data.focus !== undefined) object.focus = data.focus;
  24891. if (data.zoom !== undefined) object.zoom = data.zoom;
  24892. if (data.filmGauge !== undefined) object.filmGauge = data.filmGauge;
  24893. if (data.filmOffset !== undefined) object.filmOffset = data.filmOffset;
  24894. if (data.view !== undefined) object.view = Object.assign({}, data.view);
  24895. break;
  24896. case 'OrthographicCamera':
  24897. object = new OrthographicCamera(data.left, data.right, data.top, data.bottom, data.near, data.far);
  24898. if (data.zoom !== undefined) object.zoom = data.zoom;
  24899. if (data.view !== undefined) object.view = Object.assign({}, data.view);
  24900. break;
  24901. case 'AmbientLight':
  24902. object = new AmbientLight(data.color, data.intensity);
  24903. break;
  24904. case 'DirectionalLight':
  24905. object = new DirectionalLight(data.color, data.intensity);
  24906. break;
  24907. case 'PointLight':
  24908. object = new PointLight(data.color, data.intensity, data.distance, data.decay);
  24909. break;
  24910. case 'RectAreaLight':
  24911. object = new RectAreaLight(data.color, data.intensity, data.width, data.height);
  24912. break;
  24913. case 'SpotLight':
  24914. object = new SpotLight(data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay);
  24915. break;
  24916. case 'HemisphereLight':
  24917. object = new HemisphereLight(data.color, data.groundColor, data.intensity);
  24918. break;
  24919. case 'LightProbe':
  24920. object = new LightProbe().fromJSON(data);
  24921. break;
  24922. case 'SkinnedMesh':
  24923. geometry = getGeometry(data.geometry);
  24924. material = getMaterial(data.material);
  24925. object = new SkinnedMesh(geometry, material);
  24926. if (data.bindMode !== undefined) object.bindMode = data.bindMode;
  24927. if (data.bindMatrix !== undefined) object.bindMatrix.fromArray(data.bindMatrix);
  24928. if (data.skeleton !== undefined) object.skeleton = data.skeleton;
  24929. break;
  24930. case 'Mesh':
  24931. geometry = getGeometry(data.geometry);
  24932. material = getMaterial(data.material);
  24933. object = new Mesh(geometry, material);
  24934. break;
  24935. case 'InstancedMesh':
  24936. geometry = getGeometry(data.geometry);
  24937. material = getMaterial(data.material);
  24938. const count = data.count;
  24939. const instanceMatrix = data.instanceMatrix;
  24940. object = new InstancedMesh(geometry, material, count);
  24941. object.instanceMatrix = new BufferAttribute(new Float32Array(instanceMatrix.array), 16);
  24942. break;
  24943. case 'LOD':
  24944. object = new LOD();
  24945. break;
  24946. case 'Line':
  24947. object = new Line(getGeometry(data.geometry), getMaterial(data.material), data.mode);
  24948. break;
  24949. case 'LineLoop':
  24950. object = new LineLoop(getGeometry(data.geometry), getMaterial(data.material));
  24951. break;
  24952. case 'LineSegments':
  24953. object = new LineSegments(getGeometry(data.geometry), getMaterial(data.material));
  24954. break;
  24955. case 'PointCloud':
  24956. case 'Points':
  24957. object = new Points(getGeometry(data.geometry), getMaterial(data.material));
  24958. break;
  24959. case 'Sprite':
  24960. object = new Sprite(getMaterial(data.material));
  24961. break;
  24962. case 'Group':
  24963. object = new Group();
  24964. break;
  24965. case 'Bone':
  24966. object = new Bone();
  24967. break;
  24968. default:
  24969. object = new Object3D();
  24970. }
  24971. object.uuid = data.uuid;
  24972. if (data.name !== undefined) object.name = data.name;
  24973. if (data.matrix !== undefined) {
  24974. object.matrix.fromArray(data.matrix);
  24975. if (data.matrixAutoUpdate !== undefined) object.matrixAutoUpdate = data.matrixAutoUpdate;
  24976. if (object.matrixAutoUpdate) object.matrix.decompose(object.position, object.quaternion, object.scale);
  24977. } else {
  24978. if (data.position !== undefined) object.position.fromArray(data.position);
  24979. if (data.rotation !== undefined) object.rotation.fromArray(data.rotation);
  24980. if (data.quaternion !== undefined) object.quaternion.fromArray(data.quaternion);
  24981. if (data.scale !== undefined) object.scale.fromArray(data.scale);
  24982. }
  24983. if (data.castShadow !== undefined) object.castShadow = data.castShadow;
  24984. if (data.receiveShadow !== undefined) object.receiveShadow = data.receiveShadow;
  24985. if (data.shadow) {
  24986. if (data.shadow.bias !== undefined) object.shadow.bias = data.shadow.bias;
  24987. if (data.shadow.normalBias !== undefined) object.shadow.normalBias = data.shadow.normalBias;
  24988. if (data.shadow.radius !== undefined) object.shadow.radius = data.shadow.radius;
  24989. if (data.shadow.mapSize !== undefined) object.shadow.mapSize.fromArray(data.shadow.mapSize);
  24990. if (data.shadow.camera !== undefined) object.shadow.camera = this.parseObject(data.shadow.camera);
  24991. }
  24992. if (data.visible !== undefined) object.visible = data.visible;
  24993. if (data.frustumCulled !== undefined) object.frustumCulled = data.frustumCulled;
  24994. if (data.renderOrder !== undefined) object.renderOrder = data.renderOrder;
  24995. if (data.userData !== undefined) object.userData = data.userData;
  24996. if (data.layers !== undefined) object.layers.mask = data.layers;
  24997. if (data.children !== undefined) {
  24998. const children = data.children;
  24999. for (let i = 0; i < children.length; i++) {
  25000. object.add(this.parseObject(children[i], geometries, materials, animations));
  25001. }
  25002. }
  25003. if (data.animations !== undefined) {
  25004. const objectAnimations = data.animations;
  25005. for (let i = 0; i < objectAnimations.length; i++) {
  25006. const uuid = objectAnimations[i];
  25007. object.animations.push(animations[uuid]);
  25008. }
  25009. }
  25010. if (data.type === 'LOD') {
  25011. if (data.autoUpdate !== undefined) object.autoUpdate = data.autoUpdate;
  25012. const levels = data.levels;
  25013. for (let l = 0; l < levels.length; l++) {
  25014. const level = levels[l];
  25015. const child = object.getObjectByProperty('uuid', level.object);
  25016. if (child !== undefined) {
  25017. object.addLevel(child, level.distance);
  25018. }
  25019. }
  25020. }
  25021. return object;
  25022. }
  25023. bindSkeletons(object, skeletons) {
  25024. if (Object.keys(skeletons).length === 0) return;
  25025. object.traverse(function (child) {
  25026. if (child.isSkinnedMesh === true && child.skeleton !== undefined) {
  25027. const skeleton = skeletons[child.skeleton];
  25028. if (skeleton === undefined) {
  25029. console.warn('THREE.ObjectLoader: No skeleton found with UUID:', child.skeleton);
  25030. } else {
  25031. child.bind(skeleton, child.bindMatrix);
  25032. }
  25033. }
  25034. });
  25035. }
  25036. /* DEPRECATED */
  25037. setTexturePath(value) {
  25038. console.warn('THREE.ObjectLoader: .setTexturePath() has been renamed to .setResourcePath().');
  25039. return this.setResourcePath(value);
  25040. }
  25041. }
  25042. exports.ObjectLoader = ObjectLoader;
  25043. const TEXTURE_MAPPING = {
  25044. UVMapping: UVMapping,
  25045. CubeReflectionMapping: CubeReflectionMapping,
  25046. CubeRefractionMapping: CubeRefractionMapping,
  25047. EquirectangularReflectionMapping: EquirectangularReflectionMapping,
  25048. EquirectangularRefractionMapping: EquirectangularRefractionMapping,
  25049. CubeUVReflectionMapping: CubeUVReflectionMapping,
  25050. CubeUVRefractionMapping: CubeUVRefractionMapping
  25051. };
  25052. const TEXTURE_WRAPPING = {
  25053. RepeatWrapping: RepeatWrapping,
  25054. ClampToEdgeWrapping: ClampToEdgeWrapping,
  25055. MirroredRepeatWrapping: MirroredRepeatWrapping
  25056. };
  25057. const TEXTURE_FILTER = {
  25058. NearestFilter: NearestFilter,
  25059. NearestMipmapNearestFilter: NearestMipmapNearestFilter,
  25060. NearestMipmapLinearFilter: NearestMipmapLinearFilter,
  25061. LinearFilter: LinearFilter,
  25062. LinearMipmapNearestFilter: LinearMipmapNearestFilter,
  25063. LinearMipmapLinearFilter: LinearMipmapLinearFilter
  25064. };
  25065. function ImageBitmapLoader(manager) {
  25066. if (typeof createImageBitmap === 'undefined') {
  25067. console.warn('THREE.ImageBitmapLoader: createImageBitmap() not supported.');
  25068. }
  25069. if (typeof fetch === 'undefined') {
  25070. console.warn('THREE.ImageBitmapLoader: fetch() not supported.');
  25071. }
  25072. Loader.call(this, manager);
  25073. this.options = {
  25074. premultiplyAlpha: 'none'
  25075. };
  25076. }
  25077. ImageBitmapLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  25078. constructor: ImageBitmapLoader,
  25079. isImageBitmapLoader: true,
  25080. setOptions: function setOptions(options) {
  25081. this.options = options;
  25082. return this;
  25083. },
  25084. load: function (url, onLoad, onProgress, onError) {
  25085. if (url === undefined) url = '';
  25086. if (this.path !== undefined) url = this.path + url;
  25087. url = this.manager.resolveURL(url);
  25088. const scope = this;
  25089. const cached = Cache.get(url);
  25090. if (cached !== undefined) {
  25091. scope.manager.itemStart(url);
  25092. setTimeout(function () {
  25093. if (onLoad) onLoad(cached);
  25094. scope.manager.itemEnd(url);
  25095. }, 0);
  25096. return cached;
  25097. }
  25098. const fetchOptions = {};
  25099. fetchOptions.credentials = this.crossOrigin === 'anonymous' ? 'same-origin' : 'include';
  25100. fetch(url, fetchOptions).then(function (res) {
  25101. return res.blob();
  25102. }).then(function (blob) {
  25103. return createImageBitmap(blob, scope.options);
  25104. }).then(function (imageBitmap) {
  25105. Cache.add(url, imageBitmap);
  25106. if (onLoad) onLoad(imageBitmap);
  25107. scope.manager.itemEnd(url);
  25108. }).catch(function (e) {
  25109. if (onError) onError(e);
  25110. scope.manager.itemError(url);
  25111. scope.manager.itemEnd(url);
  25112. });
  25113. scope.manager.itemStart(url);
  25114. }
  25115. });
  25116. function ShapePath() {
  25117. this.type = 'ShapePath';
  25118. this.color = new Color();
  25119. this.subPaths = [];
  25120. this.currentPath = null;
  25121. }
  25122. Object.assign(ShapePath.prototype, {
  25123. moveTo: function (x, y) {
  25124. this.currentPath = new Path();
  25125. this.subPaths.push(this.currentPath);
  25126. this.currentPath.moveTo(x, y);
  25127. return this;
  25128. },
  25129. lineTo: function (x, y) {
  25130. this.currentPath.lineTo(x, y);
  25131. return this;
  25132. },
  25133. quadraticCurveTo: function (aCPx, aCPy, aX, aY) {
  25134. this.currentPath.quadraticCurveTo(aCPx, aCPy, aX, aY);
  25135. return this;
  25136. },
  25137. bezierCurveTo: function (aCP1x, aCP1y, aCP2x, aCP2y, aX, aY) {
  25138. this.currentPath.bezierCurveTo(aCP1x, aCP1y, aCP2x, aCP2y, aX, aY);
  25139. return this;
  25140. },
  25141. splineThru: function (pts) {
  25142. this.currentPath.splineThru(pts);
  25143. return this;
  25144. },
  25145. toShapes: function (isCCW, noHoles) {
  25146. function toShapesNoHoles(inSubpaths) {
  25147. const shapes = [];
  25148. for (let i = 0, l = inSubpaths.length; i < l; i++) {
  25149. const tmpPath = inSubpaths[i];
  25150. const tmpShape = new Shape();
  25151. tmpShape.curves = tmpPath.curves;
  25152. shapes.push(tmpShape);
  25153. }
  25154. return shapes;
  25155. }
  25156. function isPointInsidePolygon(inPt, inPolygon) {
  25157. const polyLen = inPolygon.length; // inPt on polygon contour => immediate success or
  25158. // toggling of inside/outside at every single! intersection point of an edge
  25159. // with the horizontal line through inPt, left of inPt
  25160. // not counting lowerY endpoints of edges and whole edges on that line
  25161. let inside = false;
  25162. for (let p = polyLen - 1, q = 0; q < polyLen; p = q++) {
  25163. let edgeLowPt = inPolygon[p];
  25164. let edgeHighPt = inPolygon[q];
  25165. let edgeDx = edgeHighPt.x - edgeLowPt.x;
  25166. let edgeDy = edgeHighPt.y - edgeLowPt.y;
  25167. if (Math.abs(edgeDy) > Number.EPSILON) {
  25168. // not parallel
  25169. if (edgeDy < 0) {
  25170. edgeLowPt = inPolygon[q];
  25171. edgeDx = -edgeDx;
  25172. edgeHighPt = inPolygon[p];
  25173. edgeDy = -edgeDy;
  25174. }
  25175. if (inPt.y < edgeLowPt.y || inPt.y > edgeHighPt.y) continue;
  25176. if (inPt.y === edgeLowPt.y) {
  25177. if (inPt.x === edgeLowPt.x) return true; // inPt is on contour ?
  25178. // continue; // no intersection or edgeLowPt => doesn't count !!!
  25179. } else {
  25180. const perpEdge = edgeDy * (inPt.x - edgeLowPt.x) - edgeDx * (inPt.y - edgeLowPt.y);
  25181. if (perpEdge === 0) return true; // inPt is on contour ?
  25182. if (perpEdge < 0) continue;
  25183. inside = !inside; // true intersection left of inPt
  25184. }
  25185. } else {
  25186. // parallel or collinear
  25187. if (inPt.y !== edgeLowPt.y) continue; // parallel
  25188. // edge lies on the same horizontal line as inPt
  25189. if (edgeHighPt.x <= inPt.x && inPt.x <= edgeLowPt.x || edgeLowPt.x <= inPt.x && inPt.x <= edgeHighPt.x) return true; // inPt: Point on contour !
  25190. // continue;
  25191. }
  25192. }
  25193. return inside;
  25194. }
  25195. const isClockWise = ShapeUtils.isClockWise;
  25196. const subPaths = this.subPaths;
  25197. if (subPaths.length === 0) return [];
  25198. if (noHoles === true) return toShapesNoHoles(subPaths);
  25199. let solid, tmpPath, tmpShape;
  25200. const shapes = [];
  25201. if (subPaths.length === 1) {
  25202. tmpPath = subPaths[0];
  25203. tmpShape = new Shape();
  25204. tmpShape.curves = tmpPath.curves;
  25205. shapes.push(tmpShape);
  25206. return shapes;
  25207. }
  25208. let holesFirst = !isClockWise(subPaths[0].getPoints());
  25209. holesFirst = isCCW ? !holesFirst : holesFirst; // console.log("Holes first", holesFirst);
  25210. const betterShapeHoles = [];
  25211. const newShapes = [];
  25212. let newShapeHoles = [];
  25213. let mainIdx = 0;
  25214. let tmpPoints;
  25215. newShapes[mainIdx] = undefined;
  25216. newShapeHoles[mainIdx] = [];
  25217. for (let i = 0, l = subPaths.length; i < l; i++) {
  25218. tmpPath = subPaths[i];
  25219. tmpPoints = tmpPath.getPoints();
  25220. solid = isClockWise(tmpPoints);
  25221. solid = isCCW ? !solid : solid;
  25222. if (solid) {
  25223. if (!holesFirst && newShapes[mainIdx]) mainIdx++;
  25224. newShapes[mainIdx] = {
  25225. s: new Shape(),
  25226. p: tmpPoints
  25227. };
  25228. newShapes[mainIdx].s.curves = tmpPath.curves;
  25229. if (holesFirst) mainIdx++;
  25230. newShapeHoles[mainIdx] = []; //console.log('cw', i);
  25231. } else {
  25232. newShapeHoles[mainIdx].push({
  25233. h: tmpPath,
  25234. p: tmpPoints[0]
  25235. }); //console.log('ccw', i);
  25236. }
  25237. } // only Holes? -> probably all Shapes with wrong orientation
  25238. if (!newShapes[0]) return toShapesNoHoles(subPaths);
  25239. if (newShapes.length > 1) {
  25240. let ambiguous = false;
  25241. const toChange = [];
  25242. for (let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx++) {
  25243. betterShapeHoles[sIdx] = [];
  25244. }
  25245. for (let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx++) {
  25246. const sho = newShapeHoles[sIdx];
  25247. for (let hIdx = 0; hIdx < sho.length; hIdx++) {
  25248. const ho = sho[hIdx];
  25249. let hole_unassigned = true;
  25250. for (let s2Idx = 0; s2Idx < newShapes.length; s2Idx++) {
  25251. if (isPointInsidePolygon(ho.p, newShapes[s2Idx].p)) {
  25252. if (sIdx !== s2Idx) toChange.push({
  25253. froms: sIdx,
  25254. tos: s2Idx,
  25255. hole: hIdx
  25256. });
  25257. if (hole_unassigned) {
  25258. hole_unassigned = false;
  25259. betterShapeHoles[s2Idx].push(ho);
  25260. } else {
  25261. ambiguous = true;
  25262. }
  25263. }
  25264. }
  25265. if (hole_unassigned) {
  25266. betterShapeHoles[sIdx].push(ho);
  25267. }
  25268. }
  25269. } // console.log("ambiguous: ", ambiguous);
  25270. if (toChange.length > 0) {
  25271. // console.log("to change: ", toChange);
  25272. if (!ambiguous) newShapeHoles = betterShapeHoles;
  25273. }
  25274. }
  25275. let tmpHoles;
  25276. for (let i = 0, il = newShapes.length; i < il; i++) {
  25277. tmpShape = newShapes[i].s;
  25278. shapes.push(tmpShape);
  25279. tmpHoles = newShapeHoles[i];
  25280. for (let j = 0, jl = tmpHoles.length; j < jl; j++) {
  25281. tmpShape.holes.push(tmpHoles[j].h);
  25282. }
  25283. } //console.log("shape", shapes);
  25284. return shapes;
  25285. }
  25286. });
  25287. function Font(data) {
  25288. this.type = 'Font';
  25289. this.data = data;
  25290. }
  25291. Object.assign(Font.prototype, {
  25292. isFont: true,
  25293. generateShapes: function (text, size = 100) {
  25294. const shapes = [];
  25295. const paths = createPaths(text, size, this.data);
  25296. for (let p = 0, pl = paths.length; p < pl; p++) {
  25297. Array.prototype.push.apply(shapes, paths[p].toShapes());
  25298. }
  25299. return shapes;
  25300. }
  25301. });
  25302. function createPaths(text, size, data) {
  25303. const chars = Array.from ? Array.from(text) : String(text).split(''); // workaround for IE11, see #13988
  25304. const scale = size / data.resolution;
  25305. const line_height = (data.boundingBox.yMax - data.boundingBox.yMin + data.underlineThickness) * scale;
  25306. const paths = [];
  25307. let offsetX = 0,
  25308. offsetY = 0;
  25309. for (let i = 0; i < chars.length; i++) {
  25310. const char = chars[i];
  25311. if (char === '\n') {
  25312. offsetX = 0;
  25313. offsetY -= line_height;
  25314. } else {
  25315. const ret = createPath(char, scale, offsetX, offsetY, data);
  25316. offsetX += ret.offsetX;
  25317. paths.push(ret.path);
  25318. }
  25319. }
  25320. return paths;
  25321. }
  25322. function createPath(char, scale, offsetX, offsetY, data) {
  25323. const glyph = data.glyphs[char] || data.glyphs['?'];
  25324. if (!glyph) {
  25325. console.error('THREE.Font: character "' + char + '" does not exists in font family ' + data.familyName + '.');
  25326. return;
  25327. }
  25328. const path = new ShapePath();
  25329. let x, y, cpx, cpy, cpx1, cpy1, cpx2, cpy2;
  25330. if (glyph.o) {
  25331. const outline = glyph._cachedOutline || (glyph._cachedOutline = glyph.o.split(' '));
  25332. for (let i = 0, l = outline.length; i < l;) {
  25333. const action = outline[i++];
  25334. switch (action) {
  25335. case 'm':
  25336. // moveTo
  25337. x = outline[i++] * scale + offsetX;
  25338. y = outline[i++] * scale + offsetY;
  25339. path.moveTo(x, y);
  25340. break;
  25341. case 'l':
  25342. // lineTo
  25343. x = outline[i++] * scale + offsetX;
  25344. y = outline[i++] * scale + offsetY;
  25345. path.lineTo(x, y);
  25346. break;
  25347. case 'q':
  25348. // quadraticCurveTo
  25349. cpx = outline[i++] * scale + offsetX;
  25350. cpy = outline[i++] * scale + offsetY;
  25351. cpx1 = outline[i++] * scale + offsetX;
  25352. cpy1 = outline[i++] * scale + offsetY;
  25353. path.quadraticCurveTo(cpx1, cpy1, cpx, cpy);
  25354. break;
  25355. case 'b':
  25356. // bezierCurveTo
  25357. cpx = outline[i++] * scale + offsetX;
  25358. cpy = outline[i++] * scale + offsetY;
  25359. cpx1 = outline[i++] * scale + offsetX;
  25360. cpy1 = outline[i++] * scale + offsetY;
  25361. cpx2 = outline[i++] * scale + offsetX;
  25362. cpy2 = outline[i++] * scale + offsetY;
  25363. path.bezierCurveTo(cpx1, cpy1, cpx2, cpy2, cpx, cpy);
  25364. break;
  25365. }
  25366. }
  25367. }
  25368. return {
  25369. offsetX: glyph.ha * scale,
  25370. path: path
  25371. };
  25372. }
  25373. function FontLoader(manager) {
  25374. Loader.call(this, manager);
  25375. }
  25376. FontLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  25377. constructor: FontLoader,
  25378. load: function (url, onLoad, onProgress, onError) {
  25379. const scope = this;
  25380. const loader = new FileLoader(this.manager);
  25381. loader.setPath(this.path);
  25382. loader.setRequestHeader(this.requestHeader);
  25383. loader.setWithCredentials(scope.withCredentials);
  25384. loader.load(url, function (text) {
  25385. let json;
  25386. try {
  25387. json = JSON.parse(text);
  25388. } catch (e) {
  25389. console.warn('THREE.FontLoader: typeface.js support is being deprecated. Use typeface.json instead.');
  25390. json = JSON.parse(text.substring(65, text.length - 2));
  25391. }
  25392. const font = scope.parse(json);
  25393. if (onLoad) onLoad(font);
  25394. }, onProgress, onError);
  25395. },
  25396. parse: function (json) {
  25397. return new Font(json);
  25398. }
  25399. });
  25400. let _context;
  25401. const AudioContext = {
  25402. getContext: function () {
  25403. if (_context === undefined) {
  25404. _context = new (window.AudioContext || window.webkitAudioContext)();
  25405. }
  25406. return _context;
  25407. },
  25408. setContext: function (value) {
  25409. _context = value;
  25410. }
  25411. };
  25412. exports.AudioContext = AudioContext;
  25413. function AudioLoader(manager) {
  25414. Loader.call(this, manager);
  25415. }
  25416. AudioLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  25417. constructor: AudioLoader,
  25418. load: function (url, onLoad, onProgress, onError) {
  25419. const scope = this;
  25420. const loader = new FileLoader(scope.manager);
  25421. loader.setResponseType('arraybuffer');
  25422. loader.setPath(scope.path);
  25423. loader.setRequestHeader(scope.requestHeader);
  25424. loader.setWithCredentials(scope.withCredentials);
  25425. loader.load(url, function (buffer) {
  25426. try {
  25427. // Create a copy of the buffer. The `decodeAudioData` method
  25428. // detaches the buffer when complete, preventing reuse.
  25429. const bufferCopy = buffer.slice(0);
  25430. const context = AudioContext.getContext();
  25431. context.decodeAudioData(bufferCopy, function (audioBuffer) {
  25432. onLoad(audioBuffer);
  25433. });
  25434. } catch (e) {
  25435. if (onError) {
  25436. onError(e);
  25437. } else {
  25438. console.error(e);
  25439. }
  25440. scope.manager.itemError(url);
  25441. }
  25442. }, onProgress, onError);
  25443. }
  25444. });
  25445. function HemisphereLightProbe(skyColor, groundColor, intensity) {
  25446. LightProbe.call(this, undefined, intensity);
  25447. const color1 = new Color().set(skyColor);
  25448. const color2 = new Color().set(groundColor);
  25449. const sky = new Vector3(color1.r, color1.g, color1.b);
  25450. const ground = new Vector3(color2.r, color2.g, color2.b); // without extra factor of PI in the shader, should = 1 / Math.sqrt( Math.PI );
  25451. const c0 = Math.sqrt(Math.PI);
  25452. const c1 = c0 * Math.sqrt(0.75);
  25453. this.sh.coefficients[0].copy(sky).add(ground).multiplyScalar(c0);
  25454. this.sh.coefficients[1].copy(sky).sub(ground).multiplyScalar(c1);
  25455. }
  25456. HemisphereLightProbe.prototype = Object.assign(Object.create(LightProbe.prototype), {
  25457. constructor: HemisphereLightProbe,
  25458. isHemisphereLightProbe: true,
  25459. copy: function (source) {
  25460. // modifying colors not currently supported
  25461. LightProbe.prototype.copy.call(this, source);
  25462. return this;
  25463. },
  25464. toJSON: function (meta) {
  25465. const data = LightProbe.prototype.toJSON.call(this, meta); // data.sh = this.sh.toArray(); // todo
  25466. return data;
  25467. }
  25468. });
  25469. function AmbientLightProbe(color, intensity) {
  25470. LightProbe.call(this, undefined, intensity);
  25471. const color1 = new Color().set(color); // without extra factor of PI in the shader, would be 2 / Math.sqrt( Math.PI );
  25472. this.sh.coefficients[0].set(color1.r, color1.g, color1.b).multiplyScalar(2 * Math.sqrt(Math.PI));
  25473. }
  25474. AmbientLightProbe.prototype = Object.assign(Object.create(LightProbe.prototype), {
  25475. constructor: AmbientLightProbe,
  25476. isAmbientLightProbe: true,
  25477. copy: function (source) {
  25478. // modifying color not currently supported
  25479. LightProbe.prototype.copy.call(this, source);
  25480. return this;
  25481. },
  25482. toJSON: function (meta) {
  25483. const data = LightProbe.prototype.toJSON.call(this, meta); // data.sh = this.sh.toArray(); // todo
  25484. return data;
  25485. }
  25486. });
  25487. const _eyeRight = new Matrix4();
  25488. const _eyeLeft = new Matrix4();
  25489. function StereoCamera() {
  25490. this.type = 'StereoCamera';
  25491. this.aspect = 1;
  25492. this.eyeSep = 0.064;
  25493. this.cameraL = new PerspectiveCamera();
  25494. this.cameraL.layers.enable(1);
  25495. this.cameraL.matrixAutoUpdate = false;
  25496. this.cameraR = new PerspectiveCamera();
  25497. this.cameraR.layers.enable(2);
  25498. this.cameraR.matrixAutoUpdate = false;
  25499. this._cache = {
  25500. focus: null,
  25501. fov: null,
  25502. aspect: null,
  25503. near: null,
  25504. far: null,
  25505. zoom: null,
  25506. eyeSep: null
  25507. };
  25508. }
  25509. Object.assign(StereoCamera.prototype, {
  25510. update: function (camera) {
  25511. const cache = this._cache;
  25512. const needsUpdate = cache.focus !== camera.focus || cache.fov !== camera.fov || cache.aspect !== camera.aspect * this.aspect || cache.near !== camera.near || cache.far !== camera.far || cache.zoom !== camera.zoom || cache.eyeSep !== this.eyeSep;
  25513. if (needsUpdate) {
  25514. cache.focus = camera.focus;
  25515. cache.fov = camera.fov;
  25516. cache.aspect = camera.aspect * this.aspect;
  25517. cache.near = camera.near;
  25518. cache.far = camera.far;
  25519. cache.zoom = camera.zoom;
  25520. cache.eyeSep = this.eyeSep; // Off-axis stereoscopic effect based on
  25521. // http://paulbourke.net/stereographics/stereorender/
  25522. const projectionMatrix = camera.projectionMatrix.clone();
  25523. const eyeSepHalf = cache.eyeSep / 2;
  25524. const eyeSepOnProjection = eyeSepHalf * cache.near / cache.focus;
  25525. const ymax = cache.near * Math.tan(MathUtils.DEG2RAD * cache.fov * 0.5) / cache.zoom;
  25526. let xmin, xmax; // translate xOffset
  25527. _eyeLeft.elements[12] = -eyeSepHalf;
  25528. _eyeRight.elements[12] = eyeSepHalf; // for left eye
  25529. xmin = -ymax * cache.aspect + eyeSepOnProjection;
  25530. xmax = ymax * cache.aspect + eyeSepOnProjection;
  25531. projectionMatrix.elements[0] = 2 * cache.near / (xmax - xmin);
  25532. projectionMatrix.elements[8] = (xmax + xmin) / (xmax - xmin);
  25533. this.cameraL.projectionMatrix.copy(projectionMatrix); // for right eye
  25534. xmin = -ymax * cache.aspect - eyeSepOnProjection;
  25535. xmax = ymax * cache.aspect - eyeSepOnProjection;
  25536. projectionMatrix.elements[0] = 2 * cache.near / (xmax - xmin);
  25537. projectionMatrix.elements[8] = (xmax + xmin) / (xmax - xmin);
  25538. this.cameraR.projectionMatrix.copy(projectionMatrix);
  25539. }
  25540. this.cameraL.matrixWorld.copy(camera.matrixWorld).multiply(_eyeLeft);
  25541. this.cameraR.matrixWorld.copy(camera.matrixWorld).multiply(_eyeRight);
  25542. }
  25543. });
  25544. class Clock {
  25545. constructor(autoStart) {
  25546. this.autoStart = autoStart !== undefined ? autoStart : true;
  25547. this.startTime = 0;
  25548. this.oldTime = 0;
  25549. this.elapsedTime = 0;
  25550. this.running = false;
  25551. }
  25552. start() {
  25553. this.startTime = now();
  25554. this.oldTime = this.startTime;
  25555. this.elapsedTime = 0;
  25556. this.running = true;
  25557. }
  25558. stop() {
  25559. this.getElapsedTime();
  25560. this.running = false;
  25561. this.autoStart = false;
  25562. }
  25563. getElapsedTime() {
  25564. this.getDelta();
  25565. return this.elapsedTime;
  25566. }
  25567. getDelta() {
  25568. let diff = 0;
  25569. if (this.autoStart && !this.running) {
  25570. this.start();
  25571. return 0;
  25572. }
  25573. if (this.running) {
  25574. const newTime = now();
  25575. diff = (newTime - this.oldTime) / 1000;
  25576. this.oldTime = newTime;
  25577. this.elapsedTime += diff;
  25578. }
  25579. return diff;
  25580. }
  25581. }
  25582. exports.Clock = Clock;
  25583. function now() {
  25584. return (typeof performance === 'undefined' ? Date : performance).now(); // see #10732
  25585. }
  25586. const _position$2 =
  25587. /*@__PURE__*/
  25588. new Vector3();
  25589. const _quaternion$3 =
  25590. /*@__PURE__*/
  25591. new Quaternion();
  25592. const _scale$1 =
  25593. /*@__PURE__*/
  25594. new Vector3();
  25595. const _orientation =
  25596. /*@__PURE__*/
  25597. new Vector3();
  25598. class AudioListener extends Object3D {
  25599. constructor() {
  25600. super();
  25601. this.type = 'AudioListener';
  25602. this.context = AudioContext.getContext();
  25603. this.gain = this.context.createGain();
  25604. this.gain.connect(this.context.destination);
  25605. this.filter = null;
  25606. this.timeDelta = 0; // private
  25607. this._clock = new Clock();
  25608. }
  25609. getInput() {
  25610. return this.gain;
  25611. }
  25612. removeFilter() {
  25613. if (this.filter !== null) {
  25614. this.gain.disconnect(this.filter);
  25615. this.filter.disconnect(this.context.destination);
  25616. this.gain.connect(this.context.destination);
  25617. this.filter = null;
  25618. }
  25619. return this;
  25620. }
  25621. getFilter() {
  25622. return this.filter;
  25623. }
  25624. setFilter(value) {
  25625. if (this.filter !== null) {
  25626. this.gain.disconnect(this.filter);
  25627. this.filter.disconnect(this.context.destination);
  25628. } else {
  25629. this.gain.disconnect(this.context.destination);
  25630. }
  25631. this.filter = value;
  25632. this.gain.connect(this.filter);
  25633. this.filter.connect(this.context.destination);
  25634. return this;
  25635. }
  25636. getMasterVolume() {
  25637. return this.gain.gain.value;
  25638. }
  25639. setMasterVolume(value) {
  25640. this.gain.gain.setTargetAtTime(value, this.context.currentTime, 0.01);
  25641. return this;
  25642. }
  25643. updateMatrixWorld(force) {
  25644. super.updateMatrixWorld(force);
  25645. const listener = this.context.listener;
  25646. const up = this.up;
  25647. this.timeDelta = this._clock.getDelta();
  25648. this.matrixWorld.decompose(_position$2, _quaternion$3, _scale$1);
  25649. _orientation.set(0, 0, -1).applyQuaternion(_quaternion$3);
  25650. if (listener.positionX) {
  25651. // code path for Chrome (see #14393)
  25652. const endTime = this.context.currentTime + this.timeDelta;
  25653. listener.positionX.linearRampToValueAtTime(_position$2.x, endTime);
  25654. listener.positionY.linearRampToValueAtTime(_position$2.y, endTime);
  25655. listener.positionZ.linearRampToValueAtTime(_position$2.z, endTime);
  25656. listener.forwardX.linearRampToValueAtTime(_orientation.x, endTime);
  25657. listener.forwardY.linearRampToValueAtTime(_orientation.y, endTime);
  25658. listener.forwardZ.linearRampToValueAtTime(_orientation.z, endTime);
  25659. listener.upX.linearRampToValueAtTime(up.x, endTime);
  25660. listener.upY.linearRampToValueAtTime(up.y, endTime);
  25661. listener.upZ.linearRampToValueAtTime(up.z, endTime);
  25662. } else {
  25663. listener.setPosition(_position$2.x, _position$2.y, _position$2.z);
  25664. listener.setOrientation(_orientation.x, _orientation.y, _orientation.z, up.x, up.y, up.z);
  25665. }
  25666. }
  25667. }
  25668. exports.AudioListener = AudioListener;
  25669. class Audio extends Object3D {
  25670. constructor(listener) {
  25671. super();
  25672. this.type = 'Audio';
  25673. this.listener = listener;
  25674. this.context = listener.context;
  25675. this.gain = this.context.createGain();
  25676. this.gain.connect(listener.getInput());
  25677. this.autoplay = false;
  25678. this.buffer = null;
  25679. this.detune = 0;
  25680. this.loop = false;
  25681. this.loopStart = 0;
  25682. this.loopEnd = 0;
  25683. this.offset = 0;
  25684. this.duration = undefined;
  25685. this.playbackRate = 1;
  25686. this.isPlaying = false;
  25687. this.hasPlaybackControl = true;
  25688. this.source = null;
  25689. this.sourceType = 'empty';
  25690. this._startedAt = 0;
  25691. this._progress = 0;
  25692. this._connected = false;
  25693. this.filters = [];
  25694. }
  25695. getOutput() {
  25696. return this.gain;
  25697. }
  25698. setNodeSource(audioNode) {
  25699. this.hasPlaybackControl = false;
  25700. this.sourceType = 'audioNode';
  25701. this.source = audioNode;
  25702. this.connect();
  25703. return this;
  25704. }
  25705. setMediaElementSource(mediaElement) {
  25706. this.hasPlaybackControl = false;
  25707. this.sourceType = 'mediaNode';
  25708. this.source = this.context.createMediaElementSource(mediaElement);
  25709. this.connect();
  25710. return this;
  25711. }
  25712. setMediaStreamSource(mediaStream) {
  25713. this.hasPlaybackControl = false;
  25714. this.sourceType = 'mediaStreamNode';
  25715. this.source = this.context.createMediaStreamSource(mediaStream);
  25716. this.connect();
  25717. return this;
  25718. }
  25719. setBuffer(audioBuffer) {
  25720. this.buffer = audioBuffer;
  25721. this.sourceType = 'buffer';
  25722. if (this.autoplay) this.play();
  25723. return this;
  25724. }
  25725. play(delay = 0) {
  25726. if (this.isPlaying === true) {
  25727. console.warn('THREE.Audio: Audio is already playing.');
  25728. return;
  25729. }
  25730. if (this.hasPlaybackControl === false) {
  25731. console.warn('THREE.Audio: this Audio has no playback control.');
  25732. return;
  25733. }
  25734. this._startedAt = this.context.currentTime + delay;
  25735. const source = this.context.createBufferSource();
  25736. source.buffer = this.buffer;
  25737. source.loop = this.loop;
  25738. source.loopStart = this.loopStart;
  25739. source.loopEnd = this.loopEnd;
  25740. source.onended = this.onEnded.bind(this);
  25741. source.start(this._startedAt, this._progress + this.offset, this.duration);
  25742. this.isPlaying = true;
  25743. this.source = source;
  25744. this.setDetune(this.detune);
  25745. this.setPlaybackRate(this.playbackRate);
  25746. return this.connect();
  25747. }
  25748. pause() {
  25749. if (this.hasPlaybackControl === false) {
  25750. console.warn('THREE.Audio: this Audio has no playback control.');
  25751. return;
  25752. }
  25753. if (this.isPlaying === true) {
  25754. // update current progress
  25755. this._progress += Math.max(this.context.currentTime - this._startedAt, 0) * this.playbackRate;
  25756. if (this.loop === true) {
  25757. // ensure _progress does not exceed duration with looped audios
  25758. this._progress = this._progress % (this.duration || this.buffer.duration);
  25759. }
  25760. this.source.stop();
  25761. this.source.onended = null;
  25762. this.isPlaying = false;
  25763. }
  25764. return this;
  25765. }
  25766. stop() {
  25767. if (this.hasPlaybackControl === false) {
  25768. console.warn('THREE.Audio: this Audio has no playback control.');
  25769. return;
  25770. }
  25771. this._progress = 0;
  25772. this.source.stop();
  25773. this.source.onended = null;
  25774. this.isPlaying = false;
  25775. return this;
  25776. }
  25777. connect() {
  25778. if (this.filters.length > 0) {
  25779. this.source.connect(this.filters[0]);
  25780. for (let i = 1, l = this.filters.length; i < l; i++) {
  25781. this.filters[i - 1].connect(this.filters[i]);
  25782. }
  25783. this.filters[this.filters.length - 1].connect(this.getOutput());
  25784. } else {
  25785. this.source.connect(this.getOutput());
  25786. }
  25787. this._connected = true;
  25788. return this;
  25789. }
  25790. disconnect() {
  25791. if (this.filters.length > 0) {
  25792. this.source.disconnect(this.filters[0]);
  25793. for (let i = 1, l = this.filters.length; i < l; i++) {
  25794. this.filters[i - 1].disconnect(this.filters[i]);
  25795. }
  25796. this.filters[this.filters.length - 1].disconnect(this.getOutput());
  25797. } else {
  25798. this.source.disconnect(this.getOutput());
  25799. }
  25800. this._connected = false;
  25801. return this;
  25802. }
  25803. getFilters() {
  25804. return this.filters;
  25805. }
  25806. setFilters(value) {
  25807. if (!value) value = [];
  25808. if (this._connected === true) {
  25809. this.disconnect();
  25810. this.filters = value.slice();
  25811. this.connect();
  25812. } else {
  25813. this.filters = value.slice();
  25814. }
  25815. return this;
  25816. }
  25817. setDetune(value) {
  25818. this.detune = value;
  25819. if (this.source.detune === undefined) return; // only set detune when available
  25820. if (this.isPlaying === true) {
  25821. this.source.detune.setTargetAtTime(this.detune, this.context.currentTime, 0.01);
  25822. }
  25823. return this;
  25824. }
  25825. getDetune() {
  25826. return this.detune;
  25827. }
  25828. getFilter() {
  25829. return this.getFilters()[0];
  25830. }
  25831. setFilter(filter) {
  25832. return this.setFilters(filter ? [filter] : []);
  25833. }
  25834. setPlaybackRate(value) {
  25835. if (this.hasPlaybackControl === false) {
  25836. console.warn('THREE.Audio: this Audio has no playback control.');
  25837. return;
  25838. }
  25839. this.playbackRate = value;
  25840. if (this.isPlaying === true) {
  25841. this.source.playbackRate.setTargetAtTime(this.playbackRate, this.context.currentTime, 0.01);
  25842. }
  25843. return this;
  25844. }
  25845. getPlaybackRate() {
  25846. return this.playbackRate;
  25847. }
  25848. onEnded() {
  25849. this.isPlaying = false;
  25850. }
  25851. getLoop() {
  25852. if (this.hasPlaybackControl === false) {
  25853. console.warn('THREE.Audio: this Audio has no playback control.');
  25854. return false;
  25855. }
  25856. return this.loop;
  25857. }
  25858. setLoop(value) {
  25859. if (this.hasPlaybackControl === false) {
  25860. console.warn('THREE.Audio: this Audio has no playback control.');
  25861. return;
  25862. }
  25863. this.loop = value;
  25864. if (this.isPlaying === true) {
  25865. this.source.loop = this.loop;
  25866. }
  25867. return this;
  25868. }
  25869. setLoopStart(value) {
  25870. this.loopStart = value;
  25871. return this;
  25872. }
  25873. setLoopEnd(value) {
  25874. this.loopEnd = value;
  25875. return this;
  25876. }
  25877. getVolume() {
  25878. return this.gain.gain.value;
  25879. }
  25880. setVolume(value) {
  25881. this.gain.gain.setTargetAtTime(value, this.context.currentTime, 0.01);
  25882. return this;
  25883. }
  25884. }
  25885. exports.Audio = Audio;
  25886. const _position$3 =
  25887. /*@__PURE__*/
  25888. new Vector3();
  25889. const _quaternion$4 =
  25890. /*@__PURE__*/
  25891. new Quaternion();
  25892. const _scale$2 =
  25893. /*@__PURE__*/
  25894. new Vector3();
  25895. const _orientation$1 =
  25896. /*@__PURE__*/
  25897. new Vector3();
  25898. class PositionalAudio extends Audio {
  25899. constructor(listener) {
  25900. super(listener);
  25901. this.panner = this.context.createPanner();
  25902. this.panner.panningModel = 'HRTF';
  25903. this.panner.connect(this.gain);
  25904. }
  25905. getOutput() {
  25906. return this.panner;
  25907. }
  25908. getRefDistance() {
  25909. return this.panner.refDistance;
  25910. }
  25911. setRefDistance(value) {
  25912. this.panner.refDistance = value;
  25913. return this;
  25914. }
  25915. getRolloffFactor() {
  25916. return this.panner.rolloffFactor;
  25917. }
  25918. setRolloffFactor(value) {
  25919. this.panner.rolloffFactor = value;
  25920. return this;
  25921. }
  25922. getDistanceModel() {
  25923. return this.panner.distanceModel;
  25924. }
  25925. setDistanceModel(value) {
  25926. this.panner.distanceModel = value;
  25927. return this;
  25928. }
  25929. getMaxDistance() {
  25930. return this.panner.maxDistance;
  25931. }
  25932. setMaxDistance(value) {
  25933. this.panner.maxDistance = value;
  25934. return this;
  25935. }
  25936. setDirectionalCone(coneInnerAngle, coneOuterAngle, coneOuterGain) {
  25937. this.panner.coneInnerAngle = coneInnerAngle;
  25938. this.panner.coneOuterAngle = coneOuterAngle;
  25939. this.panner.coneOuterGain = coneOuterGain;
  25940. return this;
  25941. }
  25942. updateMatrixWorld(force) {
  25943. super.updateMatrixWorld(force);
  25944. if (this.hasPlaybackControl === true && this.isPlaying === false) return;
  25945. this.matrixWorld.decompose(_position$3, _quaternion$4, _scale$2);
  25946. _orientation$1.set(0, 0, 1).applyQuaternion(_quaternion$4);
  25947. const panner = this.panner;
  25948. if (panner.positionX) {
  25949. // code path for Chrome and Firefox (see #14393)
  25950. const endTime = this.context.currentTime + this.listener.timeDelta;
  25951. panner.positionX.linearRampToValueAtTime(_position$3.x, endTime);
  25952. panner.positionY.linearRampToValueAtTime(_position$3.y, endTime);
  25953. panner.positionZ.linearRampToValueAtTime(_position$3.z, endTime);
  25954. panner.orientationX.linearRampToValueAtTime(_orientation$1.x, endTime);
  25955. panner.orientationY.linearRampToValueAtTime(_orientation$1.y, endTime);
  25956. panner.orientationZ.linearRampToValueAtTime(_orientation$1.z, endTime);
  25957. } else {
  25958. panner.setPosition(_position$3.x, _position$3.y, _position$3.z);
  25959. panner.setOrientation(_orientation$1.x, _orientation$1.y, _orientation$1.z);
  25960. }
  25961. }
  25962. }
  25963. exports.PositionalAudio = PositionalAudio;
  25964. class AudioAnalyser {
  25965. constructor(audio, fftSize = 2048) {
  25966. this.analyser = audio.context.createAnalyser();
  25967. this.analyser.fftSize = fftSize;
  25968. this.data = new Uint8Array(this.analyser.frequencyBinCount);
  25969. audio.getOutput().connect(this.analyser);
  25970. }
  25971. getFrequencyData() {
  25972. this.analyser.getByteFrequencyData(this.data);
  25973. return this.data;
  25974. }
  25975. getAverageFrequency() {
  25976. let value = 0;
  25977. const data = this.getFrequencyData();
  25978. for (let i = 0; i < data.length; i++) {
  25979. value += data[i];
  25980. }
  25981. return value / data.length;
  25982. }
  25983. }
  25984. exports.AudioAnalyser = AudioAnalyser;
  25985. function PropertyMixer(binding, typeName, valueSize) {
  25986. this.binding = binding;
  25987. this.valueSize = valueSize;
  25988. let mixFunction, mixFunctionAdditive, setIdentity; // buffer layout: [ incoming | accu0 | accu1 | orig | addAccu | (optional work) ]
  25989. //
  25990. // interpolators can use .buffer as their .result
  25991. // the data then goes to 'incoming'
  25992. //
  25993. // 'accu0' and 'accu1' are used frame-interleaved for
  25994. // the cumulative result and are compared to detect
  25995. // changes
  25996. //
  25997. // 'orig' stores the original state of the property
  25998. //
  25999. // 'add' is used for additive cumulative results
  26000. //
  26001. // 'work' is optional and is only present for quaternion types. It is used
  26002. // to store intermediate quaternion multiplication results
  26003. switch (typeName) {
  26004. case 'quaternion':
  26005. mixFunction = this._slerp;
  26006. mixFunctionAdditive = this._slerpAdditive;
  26007. setIdentity = this._setAdditiveIdentityQuaternion;
  26008. this.buffer = new Float64Array(valueSize * 6);
  26009. this._workIndex = 5;
  26010. break;
  26011. case 'string':
  26012. case 'bool':
  26013. mixFunction = this._select; // Use the regular mix function and for additive on these types,
  26014. // additive is not relevant for non-numeric types
  26015. mixFunctionAdditive = this._select;
  26016. setIdentity = this._setAdditiveIdentityOther;
  26017. this.buffer = new Array(valueSize * 5);
  26018. break;
  26019. default:
  26020. mixFunction = this._lerp;
  26021. mixFunctionAdditive = this._lerpAdditive;
  26022. setIdentity = this._setAdditiveIdentityNumeric;
  26023. this.buffer = new Float64Array(valueSize * 5);
  26024. }
  26025. this._mixBufferRegion = mixFunction;
  26026. this._mixBufferRegionAdditive = mixFunctionAdditive;
  26027. this._setIdentity = setIdentity;
  26028. this._origIndex = 3;
  26029. this._addIndex = 4;
  26030. this.cumulativeWeight = 0;
  26031. this.cumulativeWeightAdditive = 0;
  26032. this.useCount = 0;
  26033. this.referenceCount = 0;
  26034. }
  26035. Object.assign(PropertyMixer.prototype, {
  26036. // accumulate data in the 'incoming' region into 'accu<i>'
  26037. accumulate: function (accuIndex, weight) {
  26038. // note: happily accumulating nothing when weight = 0, the caller knows
  26039. // the weight and shouldn't have made the call in the first place
  26040. const buffer = this.buffer,
  26041. stride = this.valueSize,
  26042. offset = accuIndex * stride + stride;
  26043. let currentWeight = this.cumulativeWeight;
  26044. if (currentWeight === 0) {
  26045. // accuN := incoming * weight
  26046. for (let i = 0; i !== stride; ++i) {
  26047. buffer[offset + i] = buffer[i];
  26048. }
  26049. currentWeight = weight;
  26050. } else {
  26051. // accuN := accuN + incoming * weight
  26052. currentWeight += weight;
  26053. const mix = weight / currentWeight;
  26054. this._mixBufferRegion(buffer, offset, 0, mix, stride);
  26055. }
  26056. this.cumulativeWeight = currentWeight;
  26057. },
  26058. // accumulate data in the 'incoming' region into 'add'
  26059. accumulateAdditive: function (weight) {
  26060. const buffer = this.buffer,
  26061. stride = this.valueSize,
  26062. offset = stride * this._addIndex;
  26063. if (this.cumulativeWeightAdditive === 0) {
  26064. // add = identity
  26065. this._setIdentity();
  26066. } // add := add + incoming * weight
  26067. this._mixBufferRegionAdditive(buffer, offset, 0, weight, stride);
  26068. this.cumulativeWeightAdditive += weight;
  26069. },
  26070. // apply the state of 'accu<i>' to the binding when accus differ
  26071. apply: function (accuIndex) {
  26072. const stride = this.valueSize,
  26073. buffer = this.buffer,
  26074. offset = accuIndex * stride + stride,
  26075. weight = this.cumulativeWeight,
  26076. weightAdditive = this.cumulativeWeightAdditive,
  26077. binding = this.binding;
  26078. this.cumulativeWeight = 0;
  26079. this.cumulativeWeightAdditive = 0;
  26080. if (weight < 1) {
  26081. // accuN := accuN + original * ( 1 - cumulativeWeight )
  26082. const originalValueOffset = stride * this._origIndex;
  26083. this._mixBufferRegion(buffer, offset, originalValueOffset, 1 - weight, stride);
  26084. }
  26085. if (weightAdditive > 0) {
  26086. // accuN := accuN + additive accuN
  26087. this._mixBufferRegionAdditive(buffer, offset, this._addIndex * stride, 1, stride);
  26088. }
  26089. for (let i = stride, e = stride + stride; i !== e; ++i) {
  26090. if (buffer[i] !== buffer[i + stride]) {
  26091. // value has changed -> update scene graph
  26092. binding.setValue(buffer, offset);
  26093. break;
  26094. }
  26095. }
  26096. },
  26097. // remember the state of the bound property and copy it to both accus
  26098. saveOriginalState: function () {
  26099. const binding = this.binding;
  26100. const buffer = this.buffer,
  26101. stride = this.valueSize,
  26102. originalValueOffset = stride * this._origIndex;
  26103. binding.getValue(buffer, originalValueOffset); // accu[0..1] := orig -- initially detect changes against the original
  26104. for (let i = stride, e = originalValueOffset; i !== e; ++i) {
  26105. buffer[i] = buffer[originalValueOffset + i % stride];
  26106. } // Add to identity for additive
  26107. this._setIdentity();
  26108. this.cumulativeWeight = 0;
  26109. this.cumulativeWeightAdditive = 0;
  26110. },
  26111. // apply the state previously taken via 'saveOriginalState' to the binding
  26112. restoreOriginalState: function () {
  26113. const originalValueOffset = this.valueSize * 3;
  26114. this.binding.setValue(this.buffer, originalValueOffset);
  26115. },
  26116. _setAdditiveIdentityNumeric: function () {
  26117. const startIndex = this._addIndex * this.valueSize;
  26118. const endIndex = startIndex + this.valueSize;
  26119. for (let i = startIndex; i < endIndex; i++) {
  26120. this.buffer[i] = 0;
  26121. }
  26122. },
  26123. _setAdditiveIdentityQuaternion: function () {
  26124. this._setAdditiveIdentityNumeric();
  26125. this.buffer[this._addIndex * this.valueSize + 3] = 1;
  26126. },
  26127. _setAdditiveIdentityOther: function () {
  26128. const startIndex = this._origIndex * this.valueSize;
  26129. const targetIndex = this._addIndex * this.valueSize;
  26130. for (let i = 0; i < this.valueSize; i++) {
  26131. this.buffer[targetIndex + i] = this.buffer[startIndex + i];
  26132. }
  26133. },
  26134. // mix functions
  26135. _select: function (buffer, dstOffset, srcOffset, t, stride) {
  26136. if (t >= 0.5) {
  26137. for (let i = 0; i !== stride; ++i) {
  26138. buffer[dstOffset + i] = buffer[srcOffset + i];
  26139. }
  26140. }
  26141. },
  26142. _slerp: function (buffer, dstOffset, srcOffset, t) {
  26143. Quaternion.slerpFlat(buffer, dstOffset, buffer, dstOffset, buffer, srcOffset, t);
  26144. },
  26145. _slerpAdditive: function (buffer, dstOffset, srcOffset, t, stride) {
  26146. const workOffset = this._workIndex * stride; // Store result in intermediate buffer offset
  26147. Quaternion.multiplyQuaternionsFlat(buffer, workOffset, buffer, dstOffset, buffer, srcOffset); // Slerp to the intermediate result
  26148. Quaternion.slerpFlat(buffer, dstOffset, buffer, dstOffset, buffer, workOffset, t);
  26149. },
  26150. _lerp: function (buffer, dstOffset, srcOffset, t, stride) {
  26151. const s = 1 - t;
  26152. for (let i = 0; i !== stride; ++i) {
  26153. const j = dstOffset + i;
  26154. buffer[j] = buffer[j] * s + buffer[srcOffset + i] * t;
  26155. }
  26156. },
  26157. _lerpAdditive: function (buffer, dstOffset, srcOffset, t, stride) {
  26158. for (let i = 0; i !== stride; ++i) {
  26159. const j = dstOffset + i;
  26160. buffer[j] = buffer[j] + buffer[srcOffset + i] * t;
  26161. }
  26162. }
  26163. }); // Characters [].:/ are reserved for track binding syntax.
  26164. const _RESERVED_CHARS_RE = '\\[\\]\\.:\\/';
  26165. const _reservedRe = new RegExp('[' + _RESERVED_CHARS_RE + ']', 'g'); // Attempts to allow node names from any language. ES5's `\w` regexp matches
  26166. // only latin characters, and the unicode \p{L} is not yet supported. So
  26167. // instead, we exclude reserved characters and match everything else.
  26168. const _wordChar = '[^' + _RESERVED_CHARS_RE + ']';
  26169. const _wordCharOrDot = '[^' + _RESERVED_CHARS_RE.replace('\\.', '') + ']'; // Parent directories, delimited by '/' or ':'. Currently unused, but must
  26170. // be matched to parse the rest of the track name.
  26171. const _directoryRe = /((?:WC+[\/:])*)/.source.replace('WC', _wordChar); // Target node. May contain word characters (a-zA-Z0-9_) and '.' or '-'.
  26172. const _nodeRe = /(WCOD+)?/.source.replace('WCOD', _wordCharOrDot); // Object on target node, and accessor. May not contain reserved
  26173. // characters. Accessor may contain any character except closing bracket.
  26174. const _objectRe = /(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace('WC', _wordChar); // Property and accessor. May not contain reserved characters. Accessor may
  26175. // contain any non-bracket characters.
  26176. const _propertyRe = /\.(WC+)(?:\[(.+)\])?/.source.replace('WC', _wordChar);
  26177. const _trackRe = new RegExp('' + '^' + _directoryRe + _nodeRe + _objectRe + _propertyRe + '$');
  26178. const _supportedObjectNames = ['material', 'materials', 'bones'];
  26179. function Composite(targetGroup, path, optionalParsedPath) {
  26180. const parsedPath = optionalParsedPath || PropertyBinding.parseTrackName(path);
  26181. this._targetGroup = targetGroup;
  26182. this._bindings = targetGroup.subscribe_(path, parsedPath);
  26183. }
  26184. Object.assign(Composite.prototype, {
  26185. getValue: function (array, offset) {
  26186. this.bind(); // bind all binding
  26187. const firstValidIndex = this._targetGroup.nCachedObjects_,
  26188. binding = this._bindings[firstValidIndex]; // and only call .getValue on the first
  26189. if (binding !== undefined) binding.getValue(array, offset);
  26190. },
  26191. setValue: function (array, offset) {
  26192. const bindings = this._bindings;
  26193. for (let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++i) {
  26194. bindings[i].setValue(array, offset);
  26195. }
  26196. },
  26197. bind: function () {
  26198. const bindings = this._bindings;
  26199. for (let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++i) {
  26200. bindings[i].bind();
  26201. }
  26202. },
  26203. unbind: function () {
  26204. const bindings = this._bindings;
  26205. for (let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++i) {
  26206. bindings[i].unbind();
  26207. }
  26208. }
  26209. });
  26210. function PropertyBinding(rootNode, path, parsedPath) {
  26211. this.path = path;
  26212. this.parsedPath = parsedPath || PropertyBinding.parseTrackName(path);
  26213. this.node = PropertyBinding.findNode(rootNode, this.parsedPath.nodeName) || rootNode;
  26214. this.rootNode = rootNode;
  26215. }
  26216. Object.assign(PropertyBinding, {
  26217. Composite: Composite,
  26218. create: function (root, path, parsedPath) {
  26219. if (!(root && root.isAnimationObjectGroup)) {
  26220. return new PropertyBinding(root, path, parsedPath);
  26221. } else {
  26222. return new PropertyBinding.Composite(root, path, parsedPath);
  26223. }
  26224. },
  26225. /**
  26226. * Replaces spaces with underscores and removes unsupported characters from
  26227. * node names, to ensure compatibility with parseTrackName().
  26228. *
  26229. * @param {string} name Node name to be sanitized.
  26230. * @return {string}
  26231. */
  26232. sanitizeNodeName: function (name) {
  26233. return name.replace(/\s/g, '_').replace(_reservedRe, '');
  26234. },
  26235. parseTrackName: function (trackName) {
  26236. const matches = _trackRe.exec(trackName);
  26237. if (!matches) {
  26238. throw new Error('PropertyBinding: Cannot parse trackName: ' + trackName);
  26239. }
  26240. const results = {
  26241. // directoryName: matches[ 1 ], // (tschw) currently unused
  26242. nodeName: matches[2],
  26243. objectName: matches[3],
  26244. objectIndex: matches[4],
  26245. propertyName: matches[5],
  26246. // required
  26247. propertyIndex: matches[6]
  26248. };
  26249. const lastDot = results.nodeName && results.nodeName.lastIndexOf('.');
  26250. if (lastDot !== undefined && lastDot !== -1) {
  26251. const objectName = results.nodeName.substring(lastDot + 1); // Object names must be checked against an allowlist. Otherwise, there
  26252. // is no way to parse 'foo.bar.baz': 'baz' must be a property, but
  26253. // 'bar' could be the objectName, or part of a nodeName (which can
  26254. // include '.' characters).
  26255. if (_supportedObjectNames.indexOf(objectName) !== -1) {
  26256. results.nodeName = results.nodeName.substring(0, lastDot);
  26257. results.objectName = objectName;
  26258. }
  26259. }
  26260. if (results.propertyName === null || results.propertyName.length === 0) {
  26261. throw new Error('PropertyBinding: can not parse propertyName from trackName: ' + trackName);
  26262. }
  26263. return results;
  26264. },
  26265. findNode: function (root, nodeName) {
  26266. if (!nodeName || nodeName === "" || nodeName === "." || nodeName === -1 || nodeName === root.name || nodeName === root.uuid) {
  26267. return root;
  26268. } // search into skeleton bones.
  26269. if (root.skeleton) {
  26270. const bone = root.skeleton.getBoneByName(nodeName);
  26271. if (bone !== undefined) {
  26272. return bone;
  26273. }
  26274. } // search into node subtree.
  26275. if (root.children) {
  26276. const searchNodeSubtree = function (children) {
  26277. for (let i = 0; i < children.length; i++) {
  26278. const childNode = children[i];
  26279. if (childNode.name === nodeName || childNode.uuid === nodeName) {
  26280. return childNode;
  26281. }
  26282. const result = searchNodeSubtree(childNode.children);
  26283. if (result) return result;
  26284. }
  26285. return null;
  26286. };
  26287. const subTreeNode = searchNodeSubtree(root.children);
  26288. if (subTreeNode) {
  26289. return subTreeNode;
  26290. }
  26291. }
  26292. return null;
  26293. }
  26294. });
  26295. Object.assign(PropertyBinding.prototype, {
  26296. // prototype, continued
  26297. // these are used to "bind" a nonexistent property
  26298. _getValue_unavailable: function () {},
  26299. _setValue_unavailable: function () {},
  26300. BindingType: {
  26301. Direct: 0,
  26302. EntireArray: 1,
  26303. ArrayElement: 2,
  26304. HasFromToArray: 3
  26305. },
  26306. Versioning: {
  26307. None: 0,
  26308. NeedsUpdate: 1,
  26309. MatrixWorldNeedsUpdate: 2
  26310. },
  26311. GetterByBindingType: [function getValue_direct(buffer, offset) {
  26312. buffer[offset] = this.node[this.propertyName];
  26313. }, function getValue_array(buffer, offset) {
  26314. const source = this.resolvedProperty;
  26315. for (let i = 0, n = source.length; i !== n; ++i) {
  26316. buffer[offset++] = source[i];
  26317. }
  26318. }, function getValue_arrayElement(buffer, offset) {
  26319. buffer[offset] = this.resolvedProperty[this.propertyIndex];
  26320. }, function getValue_toArray(buffer, offset) {
  26321. this.resolvedProperty.toArray(buffer, offset);
  26322. }],
  26323. SetterByBindingTypeAndVersioning: [[// Direct
  26324. function setValue_direct(buffer, offset) {
  26325. this.targetObject[this.propertyName] = buffer[offset];
  26326. }, function setValue_direct_setNeedsUpdate(buffer, offset) {
  26327. this.targetObject[this.propertyName] = buffer[offset];
  26328. this.targetObject.needsUpdate = true;
  26329. }, function setValue_direct_setMatrixWorldNeedsUpdate(buffer, offset) {
  26330. this.targetObject[this.propertyName] = buffer[offset];
  26331. this.targetObject.matrixWorldNeedsUpdate = true;
  26332. }], [// EntireArray
  26333. function setValue_array(buffer, offset) {
  26334. const dest = this.resolvedProperty;
  26335. for (let i = 0, n = dest.length; i !== n; ++i) {
  26336. dest[i] = buffer[offset++];
  26337. }
  26338. }, function setValue_array_setNeedsUpdate(buffer, offset) {
  26339. const dest = this.resolvedProperty;
  26340. for (let i = 0, n = dest.length; i !== n; ++i) {
  26341. dest[i] = buffer[offset++];
  26342. }
  26343. this.targetObject.needsUpdate = true;
  26344. }, function setValue_array_setMatrixWorldNeedsUpdate(buffer, offset) {
  26345. const dest = this.resolvedProperty;
  26346. for (let i = 0, n = dest.length; i !== n; ++i) {
  26347. dest[i] = buffer[offset++];
  26348. }
  26349. this.targetObject.matrixWorldNeedsUpdate = true;
  26350. }], [// ArrayElement
  26351. function setValue_arrayElement(buffer, offset) {
  26352. this.resolvedProperty[this.propertyIndex] = buffer[offset];
  26353. }, function setValue_arrayElement_setNeedsUpdate(buffer, offset) {
  26354. this.resolvedProperty[this.propertyIndex] = buffer[offset];
  26355. this.targetObject.needsUpdate = true;
  26356. }, function setValue_arrayElement_setMatrixWorldNeedsUpdate(buffer, offset) {
  26357. this.resolvedProperty[this.propertyIndex] = buffer[offset];
  26358. this.targetObject.matrixWorldNeedsUpdate = true;
  26359. }], [// HasToFromArray
  26360. function setValue_fromArray(buffer, offset) {
  26361. this.resolvedProperty.fromArray(buffer, offset);
  26362. }, function setValue_fromArray_setNeedsUpdate(buffer, offset) {
  26363. this.resolvedProperty.fromArray(buffer, offset);
  26364. this.targetObject.needsUpdate = true;
  26365. }, function setValue_fromArray_setMatrixWorldNeedsUpdate(buffer, offset) {
  26366. this.resolvedProperty.fromArray(buffer, offset);
  26367. this.targetObject.matrixWorldNeedsUpdate = true;
  26368. }]],
  26369. getValue: function getValue_unbound(targetArray, offset) {
  26370. this.bind();
  26371. this.getValue(targetArray, offset); // Note: This class uses a State pattern on a per-method basis:
  26372. // 'bind' sets 'this.getValue' / 'setValue' and shadows the
  26373. // prototype version of these methods with one that represents
  26374. // the bound state. When the property is not found, the methods
  26375. // become no-ops.
  26376. },
  26377. setValue: function getValue_unbound(sourceArray, offset) {
  26378. this.bind();
  26379. this.setValue(sourceArray, offset);
  26380. },
  26381. // create getter / setter pair for a property in the scene graph
  26382. bind: function () {
  26383. let targetObject = this.node;
  26384. const parsedPath = this.parsedPath;
  26385. const objectName = parsedPath.objectName;
  26386. const propertyName = parsedPath.propertyName;
  26387. let propertyIndex = parsedPath.propertyIndex;
  26388. if (!targetObject) {
  26389. targetObject = PropertyBinding.findNode(this.rootNode, parsedPath.nodeName) || this.rootNode;
  26390. this.node = targetObject;
  26391. } // set fail state so we can just 'return' on error
  26392. this.getValue = this._getValue_unavailable;
  26393. this.setValue = this._setValue_unavailable; // ensure there is a value node
  26394. if (!targetObject) {
  26395. console.error('THREE.PropertyBinding: Trying to update node for track: ' + this.path + ' but it wasn\'t found.');
  26396. return;
  26397. }
  26398. if (objectName) {
  26399. let objectIndex = parsedPath.objectIndex; // special cases were we need to reach deeper into the hierarchy to get the face materials....
  26400. switch (objectName) {
  26401. case 'materials':
  26402. if (!targetObject.material) {
  26403. console.error('THREE.PropertyBinding: Can not bind to material as node does not have a material.', this);
  26404. return;
  26405. }
  26406. if (!targetObject.material.materials) {
  26407. console.error('THREE.PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.', this);
  26408. return;
  26409. }
  26410. targetObject = targetObject.material.materials;
  26411. break;
  26412. case 'bones':
  26413. if (!targetObject.skeleton) {
  26414. console.error('THREE.PropertyBinding: Can not bind to bones as node does not have a skeleton.', this);
  26415. return;
  26416. } // potential future optimization: skip this if propertyIndex is already an integer
  26417. // and convert the integer string to a true integer.
  26418. targetObject = targetObject.skeleton.bones; // support resolving morphTarget names into indices.
  26419. for (let i = 0; i < targetObject.length; i++) {
  26420. if (targetObject[i].name === objectIndex) {
  26421. objectIndex = i;
  26422. break;
  26423. }
  26424. }
  26425. break;
  26426. default:
  26427. if (targetObject[objectName] === undefined) {
  26428. console.error('THREE.PropertyBinding: Can not bind to objectName of node undefined.', this);
  26429. return;
  26430. }
  26431. targetObject = targetObject[objectName];
  26432. }
  26433. if (objectIndex !== undefined) {
  26434. if (targetObject[objectIndex] === undefined) {
  26435. console.error('THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.', this, targetObject);
  26436. return;
  26437. }
  26438. targetObject = targetObject[objectIndex];
  26439. }
  26440. } // resolve property
  26441. const nodeProperty = targetObject[propertyName];
  26442. if (nodeProperty === undefined) {
  26443. const nodeName = parsedPath.nodeName;
  26444. console.error('THREE.PropertyBinding: Trying to update property for track: ' + nodeName + '.' + propertyName + ' but it wasn\'t found.', targetObject);
  26445. return;
  26446. } // determine versioning scheme
  26447. let versioning = this.Versioning.None;
  26448. this.targetObject = targetObject;
  26449. if (targetObject.needsUpdate !== undefined) {
  26450. // material
  26451. versioning = this.Versioning.NeedsUpdate;
  26452. } else if (targetObject.matrixWorldNeedsUpdate !== undefined) {
  26453. // node transform
  26454. versioning = this.Versioning.MatrixWorldNeedsUpdate;
  26455. } // determine how the property gets bound
  26456. let bindingType = this.BindingType.Direct;
  26457. if (propertyIndex !== undefined) {
  26458. // access a sub element of the property array (only primitives are supported right now)
  26459. if (propertyName === "morphTargetInfluences") {
  26460. // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer.
  26461. // support resolving morphTarget names into indices.
  26462. if (!targetObject.geometry) {
  26463. console.error('THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.', this);
  26464. return;
  26465. }
  26466. if (targetObject.geometry.isBufferGeometry) {
  26467. if (!targetObject.geometry.morphAttributes) {
  26468. console.error('THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.', this);
  26469. return;
  26470. }
  26471. if (targetObject.morphTargetDictionary[propertyIndex] !== undefined) {
  26472. propertyIndex = targetObject.morphTargetDictionary[propertyIndex];
  26473. }
  26474. } else {
  26475. console.error('THREE.PropertyBinding: Can not bind to morphTargetInfluences on THREE.Geometry. Use THREE.BufferGeometry instead.', this);
  26476. return;
  26477. }
  26478. }
  26479. bindingType = this.BindingType.ArrayElement;
  26480. this.resolvedProperty = nodeProperty;
  26481. this.propertyIndex = propertyIndex;
  26482. } else if (nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined) {
  26483. // must use copy for Object3D.Euler/Quaternion
  26484. bindingType = this.BindingType.HasFromToArray;
  26485. this.resolvedProperty = nodeProperty;
  26486. } else if (Array.isArray(nodeProperty)) {
  26487. bindingType = this.BindingType.EntireArray;
  26488. this.resolvedProperty = nodeProperty;
  26489. } else {
  26490. this.propertyName = propertyName;
  26491. } // select getter / setter
  26492. this.getValue = this.GetterByBindingType[bindingType];
  26493. this.setValue = this.SetterByBindingTypeAndVersioning[bindingType][versioning];
  26494. },
  26495. unbind: function () {
  26496. this.node = null; // back to the prototype version of getValue / setValue
  26497. // note: avoiding to mutate the shape of 'this' via 'delete'
  26498. this.getValue = this._getValue_unbound;
  26499. this.setValue = this._setValue_unbound;
  26500. }
  26501. }); // DECLARE ALIAS AFTER assign prototype
  26502. Object.assign(PropertyBinding.prototype, {
  26503. // initial state of these methods that calls 'bind'
  26504. _getValue_unbound: PropertyBinding.prototype.getValue,
  26505. _setValue_unbound: PropertyBinding.prototype.setValue
  26506. });
  26507. /**
  26508. *
  26509. * A group of objects that receives a shared animation state.
  26510. *
  26511. * Usage:
  26512. *
  26513. * - Add objects you would otherwise pass as 'root' to the
  26514. * constructor or the .clipAction method of AnimationMixer.
  26515. *
  26516. * - Instead pass this object as 'root'.
  26517. *
  26518. * - You can also add and remove objects later when the mixer
  26519. * is running.
  26520. *
  26521. * Note:
  26522. *
  26523. * Objects of this class appear as one object to the mixer,
  26524. * so cache control of the individual objects must be done
  26525. * on the group.
  26526. *
  26527. * Limitation:
  26528. *
  26529. * - The animated properties must be compatible among the
  26530. * all objects in the group.
  26531. *
  26532. * - A single property can either be controlled through a
  26533. * target group or directly, but not both.
  26534. */
  26535. function AnimationObjectGroup() {
  26536. this.uuid = MathUtils.generateUUID(); // cached objects followed by the active ones
  26537. this._objects = Array.prototype.slice.call(arguments);
  26538. this.nCachedObjects_ = 0; // threshold
  26539. // note: read by PropertyBinding.Composite
  26540. const indices = {};
  26541. this._indicesByUUID = indices; // for bookkeeping
  26542. for (let i = 0, n = arguments.length; i !== n; ++i) {
  26543. indices[arguments[i].uuid] = i;
  26544. }
  26545. this._paths = []; // inside: string
  26546. this._parsedPaths = []; // inside: { we don't care, here }
  26547. this._bindings = []; // inside: Array< PropertyBinding >
  26548. this._bindingsIndicesByPath = {}; // inside: indices in these arrays
  26549. const scope = this;
  26550. this.stats = {
  26551. objects: {
  26552. get total() {
  26553. return scope._objects.length;
  26554. },
  26555. get inUse() {
  26556. return this.total - scope.nCachedObjects_;
  26557. }
  26558. },
  26559. get bindingsPerObject() {
  26560. return scope._bindings.length;
  26561. }
  26562. };
  26563. }
  26564. Object.assign(AnimationObjectGroup.prototype, {
  26565. isAnimationObjectGroup: true,
  26566. add: function () {
  26567. const objects = this._objects,
  26568. indicesByUUID = this._indicesByUUID,
  26569. paths = this._paths,
  26570. parsedPaths = this._parsedPaths,
  26571. bindings = this._bindings,
  26572. nBindings = bindings.length;
  26573. let knownObject = undefined,
  26574. nObjects = objects.length,
  26575. nCachedObjects = this.nCachedObjects_;
  26576. for (let i = 0, n = arguments.length; i !== n; ++i) {
  26577. const object = arguments[i],
  26578. uuid = object.uuid;
  26579. let index = indicesByUUID[uuid];
  26580. if (index === undefined) {
  26581. // unknown object -> add it to the ACTIVE region
  26582. index = nObjects++;
  26583. indicesByUUID[uuid] = index;
  26584. objects.push(object); // accounting is done, now do the same for all bindings
  26585. for (let j = 0, m = nBindings; j !== m; ++j) {
  26586. bindings[j].push(new PropertyBinding(object, paths[j], parsedPaths[j]));
  26587. }
  26588. } else if (index < nCachedObjects) {
  26589. knownObject = objects[index]; // move existing object to the ACTIVE region
  26590. const firstActiveIndex = --nCachedObjects,
  26591. lastCachedObject = objects[firstActiveIndex];
  26592. indicesByUUID[lastCachedObject.uuid] = index;
  26593. objects[index] = lastCachedObject;
  26594. indicesByUUID[uuid] = firstActiveIndex;
  26595. objects[firstActiveIndex] = object; // accounting is done, now do the same for all bindings
  26596. for (let j = 0, m = nBindings; j !== m; ++j) {
  26597. const bindingsForPath = bindings[j],
  26598. lastCached = bindingsForPath[firstActiveIndex];
  26599. let binding = bindingsForPath[index];
  26600. bindingsForPath[index] = lastCached;
  26601. if (binding === undefined) {
  26602. // since we do not bother to create new bindings
  26603. // for objects that are cached, the binding may
  26604. // or may not exist
  26605. binding = new PropertyBinding(object, paths[j], parsedPaths[j]);
  26606. }
  26607. bindingsForPath[firstActiveIndex] = binding;
  26608. }
  26609. } else if (objects[index] !== knownObject) {
  26610. console.error('THREE.AnimationObjectGroup: Different objects with the same UUID ' + 'detected. Clean the caches or recreate your infrastructure when reloading scenes.');
  26611. } // else the object is already where we want it to be
  26612. } // for arguments
  26613. this.nCachedObjects_ = nCachedObjects;
  26614. },
  26615. remove: function () {
  26616. const objects = this._objects,
  26617. indicesByUUID = this._indicesByUUID,
  26618. bindings = this._bindings,
  26619. nBindings = bindings.length;
  26620. let nCachedObjects = this.nCachedObjects_;
  26621. for (let i = 0, n = arguments.length; i !== n; ++i) {
  26622. const object = arguments[i],
  26623. uuid = object.uuid,
  26624. index = indicesByUUID[uuid];
  26625. if (index !== undefined && index >= nCachedObjects) {
  26626. // move existing object into the CACHED region
  26627. const lastCachedIndex = nCachedObjects++,
  26628. firstActiveObject = objects[lastCachedIndex];
  26629. indicesByUUID[firstActiveObject.uuid] = index;
  26630. objects[index] = firstActiveObject;
  26631. indicesByUUID[uuid] = lastCachedIndex;
  26632. objects[lastCachedIndex] = object; // accounting is done, now do the same for all bindings
  26633. for (let j = 0, m = nBindings; j !== m; ++j) {
  26634. const bindingsForPath = bindings[j],
  26635. firstActive = bindingsForPath[lastCachedIndex],
  26636. binding = bindingsForPath[index];
  26637. bindingsForPath[index] = firstActive;
  26638. bindingsForPath[lastCachedIndex] = binding;
  26639. }
  26640. }
  26641. } // for arguments
  26642. this.nCachedObjects_ = nCachedObjects;
  26643. },
  26644. // remove & forget
  26645. uncache: function () {
  26646. const objects = this._objects,
  26647. indicesByUUID = this._indicesByUUID,
  26648. bindings = this._bindings,
  26649. nBindings = bindings.length;
  26650. let nCachedObjects = this.nCachedObjects_,
  26651. nObjects = objects.length;
  26652. for (let i = 0, n = arguments.length; i !== n; ++i) {
  26653. const object = arguments[i],
  26654. uuid = object.uuid,
  26655. index = indicesByUUID[uuid];
  26656. if (index !== undefined) {
  26657. delete indicesByUUID[uuid];
  26658. if (index < nCachedObjects) {
  26659. // object is cached, shrink the CACHED region
  26660. const firstActiveIndex = --nCachedObjects,
  26661. lastCachedObject = objects[firstActiveIndex],
  26662. lastIndex = --nObjects,
  26663. lastObject = objects[lastIndex]; // last cached object takes this object's place
  26664. indicesByUUID[lastCachedObject.uuid] = index;
  26665. objects[index] = lastCachedObject; // last object goes to the activated slot and pop
  26666. indicesByUUID[lastObject.uuid] = firstActiveIndex;
  26667. objects[firstActiveIndex] = lastObject;
  26668. objects.pop(); // accounting is done, now do the same for all bindings
  26669. for (let j = 0, m = nBindings; j !== m; ++j) {
  26670. const bindingsForPath = bindings[j],
  26671. lastCached = bindingsForPath[firstActiveIndex],
  26672. last = bindingsForPath[lastIndex];
  26673. bindingsForPath[index] = lastCached;
  26674. bindingsForPath[firstActiveIndex] = last;
  26675. bindingsForPath.pop();
  26676. }
  26677. } else {
  26678. // object is active, just swap with the last and pop
  26679. const lastIndex = --nObjects,
  26680. lastObject = objects[lastIndex];
  26681. if (lastIndex > 0) {
  26682. indicesByUUID[lastObject.uuid] = index;
  26683. }
  26684. objects[index] = lastObject;
  26685. objects.pop(); // accounting is done, now do the same for all bindings
  26686. for (let j = 0, m = nBindings; j !== m; ++j) {
  26687. const bindingsForPath = bindings[j];
  26688. bindingsForPath[index] = bindingsForPath[lastIndex];
  26689. bindingsForPath.pop();
  26690. }
  26691. } // cached or active
  26692. } // if object is known
  26693. } // for arguments
  26694. this.nCachedObjects_ = nCachedObjects;
  26695. },
  26696. // Internal interface used by befriended PropertyBinding.Composite:
  26697. subscribe_: function (path, parsedPath) {
  26698. // returns an array of bindings for the given path that is changed
  26699. // according to the contained objects in the group
  26700. const indicesByPath = this._bindingsIndicesByPath;
  26701. let index = indicesByPath[path];
  26702. const bindings = this._bindings;
  26703. if (index !== undefined) return bindings[index];
  26704. const paths = this._paths,
  26705. parsedPaths = this._parsedPaths,
  26706. objects = this._objects,
  26707. nObjects = objects.length,
  26708. nCachedObjects = this.nCachedObjects_,
  26709. bindingsForPath = new Array(nObjects);
  26710. index = bindings.length;
  26711. indicesByPath[path] = index;
  26712. paths.push(path);
  26713. parsedPaths.push(parsedPath);
  26714. bindings.push(bindingsForPath);
  26715. for (let i = nCachedObjects, n = objects.length; i !== n; ++i) {
  26716. const object = objects[i];
  26717. bindingsForPath[i] = new PropertyBinding(object, path, parsedPath);
  26718. }
  26719. return bindingsForPath;
  26720. },
  26721. unsubscribe_: function (path) {
  26722. // tells the group to forget about a property path and no longer
  26723. // update the array previously obtained with 'subscribe_'
  26724. const indicesByPath = this._bindingsIndicesByPath,
  26725. index = indicesByPath[path];
  26726. if (index !== undefined) {
  26727. const paths = this._paths,
  26728. parsedPaths = this._parsedPaths,
  26729. bindings = this._bindings,
  26730. lastBindingsIndex = bindings.length - 1,
  26731. lastBindings = bindings[lastBindingsIndex],
  26732. lastBindingsPath = path[lastBindingsIndex];
  26733. indicesByPath[lastBindingsPath] = index;
  26734. bindings[index] = lastBindings;
  26735. bindings.pop();
  26736. parsedPaths[index] = parsedPaths[lastBindingsIndex];
  26737. parsedPaths.pop();
  26738. paths[index] = paths[lastBindingsIndex];
  26739. paths.pop();
  26740. }
  26741. }
  26742. });
  26743. class AnimationAction {
  26744. constructor(mixer, clip, localRoot = null, blendMode = clip.blendMode) {
  26745. this._mixer = mixer;
  26746. this._clip = clip;
  26747. this._localRoot = localRoot;
  26748. this.blendMode = blendMode;
  26749. const tracks = clip.tracks,
  26750. nTracks = tracks.length,
  26751. interpolants = new Array(nTracks);
  26752. const interpolantSettings = {
  26753. endingStart: ZeroCurvatureEnding,
  26754. endingEnd: ZeroCurvatureEnding
  26755. };
  26756. for (let i = 0; i !== nTracks; ++i) {
  26757. const interpolant = tracks[i].createInterpolant(null);
  26758. interpolants[i] = interpolant;
  26759. interpolant.settings = interpolantSettings;
  26760. }
  26761. this._interpolantSettings = interpolantSettings;
  26762. this._interpolants = interpolants; // bound by the mixer
  26763. // inside: PropertyMixer (managed by the mixer)
  26764. this._propertyBindings = new Array(nTracks);
  26765. this._cacheIndex = null; // for the memory manager
  26766. this._byClipCacheIndex = null; // for the memory manager
  26767. this._timeScaleInterpolant = null;
  26768. this._weightInterpolant = null;
  26769. this.loop = LoopRepeat;
  26770. this._loopCount = -1; // global mixer time when the action is to be started
  26771. // it's set back to 'null' upon start of the action
  26772. this._startTime = null; // scaled local time of the action
  26773. // gets clamped or wrapped to 0..clip.duration according to loop
  26774. this.time = 0;
  26775. this.timeScale = 1;
  26776. this._effectiveTimeScale = 1;
  26777. this.weight = 1;
  26778. this._effectiveWeight = 1;
  26779. this.repetitions = Infinity; // no. of repetitions when looping
  26780. this.paused = false; // true -> zero effective time scale
  26781. this.enabled = true; // false -> zero effective weight
  26782. this.clampWhenFinished = false; // keep feeding the last frame?
  26783. this.zeroSlopeAtStart = true; // for smooth interpolation w/o separate
  26784. this.zeroSlopeAtEnd = true; // clips for start, loop and end
  26785. } // State & Scheduling
  26786. play() {
  26787. this._mixer._activateAction(this);
  26788. return this;
  26789. }
  26790. stop() {
  26791. this._mixer._deactivateAction(this);
  26792. return this.reset();
  26793. }
  26794. reset() {
  26795. this.paused = false;
  26796. this.enabled = true;
  26797. this.time = 0; // restart clip
  26798. this._loopCount = -1; // forget previous loops
  26799. this._startTime = null; // forget scheduling
  26800. return this.stopFading().stopWarping();
  26801. }
  26802. isRunning() {
  26803. return this.enabled && !this.paused && this.timeScale !== 0 && this._startTime === null && this._mixer._isActiveAction(this);
  26804. } // return true when play has been called
  26805. isScheduled() {
  26806. return this._mixer._isActiveAction(this);
  26807. }
  26808. startAt(time) {
  26809. this._startTime = time;
  26810. return this;
  26811. }
  26812. setLoop(mode, repetitions) {
  26813. this.loop = mode;
  26814. this.repetitions = repetitions;
  26815. return this;
  26816. } // Weight
  26817. // set the weight stopping any scheduled fading
  26818. // although .enabled = false yields an effective weight of zero, this
  26819. // method does *not* change .enabled, because it would be confusing
  26820. setEffectiveWeight(weight) {
  26821. this.weight = weight; // note: same logic as when updated at runtime
  26822. this._effectiveWeight = this.enabled ? weight : 0;
  26823. return this.stopFading();
  26824. } // return the weight considering fading and .enabled
  26825. getEffectiveWeight() {
  26826. return this._effectiveWeight;
  26827. }
  26828. fadeIn(duration) {
  26829. return this._scheduleFading(duration, 0, 1);
  26830. }
  26831. fadeOut(duration) {
  26832. return this._scheduleFading(duration, 1, 0);
  26833. }
  26834. crossFadeFrom(fadeOutAction, duration, warp) {
  26835. fadeOutAction.fadeOut(duration);
  26836. this.fadeIn(duration);
  26837. if (warp) {
  26838. const fadeInDuration = this._clip.duration,
  26839. fadeOutDuration = fadeOutAction._clip.duration,
  26840. startEndRatio = fadeOutDuration / fadeInDuration,
  26841. endStartRatio = fadeInDuration / fadeOutDuration;
  26842. fadeOutAction.warp(1.0, startEndRatio, duration);
  26843. this.warp(endStartRatio, 1.0, duration);
  26844. }
  26845. return this;
  26846. }
  26847. crossFadeTo(fadeInAction, duration, warp) {
  26848. return fadeInAction.crossFadeFrom(this, duration, warp);
  26849. }
  26850. stopFading() {
  26851. const weightInterpolant = this._weightInterpolant;
  26852. if (weightInterpolant !== null) {
  26853. this._weightInterpolant = null;
  26854. this._mixer._takeBackControlInterpolant(weightInterpolant);
  26855. }
  26856. return this;
  26857. } // Time Scale Control
  26858. // set the time scale stopping any scheduled warping
  26859. // although .paused = true yields an effective time scale of zero, this
  26860. // method does *not* change .paused, because it would be confusing
  26861. setEffectiveTimeScale(timeScale) {
  26862. this.timeScale = timeScale;
  26863. this._effectiveTimeScale = this.paused ? 0 : timeScale;
  26864. return this.stopWarping();
  26865. } // return the time scale considering warping and .paused
  26866. getEffectiveTimeScale() {
  26867. return this._effectiveTimeScale;
  26868. }
  26869. setDuration(duration) {
  26870. this.timeScale = this._clip.duration / duration;
  26871. return this.stopWarping();
  26872. }
  26873. syncWith(action) {
  26874. this.time = action.time;
  26875. this.timeScale = action.timeScale;
  26876. return this.stopWarping();
  26877. }
  26878. halt(duration) {
  26879. return this.warp(this._effectiveTimeScale, 0, duration);
  26880. }
  26881. warp(startTimeScale, endTimeScale, duration) {
  26882. const mixer = this._mixer,
  26883. now = mixer.time,
  26884. timeScale = this.timeScale;
  26885. let interpolant = this._timeScaleInterpolant;
  26886. if (interpolant === null) {
  26887. interpolant = mixer._lendControlInterpolant();
  26888. this._timeScaleInterpolant = interpolant;
  26889. }
  26890. const times = interpolant.parameterPositions,
  26891. values = interpolant.sampleValues;
  26892. times[0] = now;
  26893. times[1] = now + duration;
  26894. values[0] = startTimeScale / timeScale;
  26895. values[1] = endTimeScale / timeScale;
  26896. return this;
  26897. }
  26898. stopWarping() {
  26899. const timeScaleInterpolant = this._timeScaleInterpolant;
  26900. if (timeScaleInterpolant !== null) {
  26901. this._timeScaleInterpolant = null;
  26902. this._mixer._takeBackControlInterpolant(timeScaleInterpolant);
  26903. }
  26904. return this;
  26905. } // Object Accessors
  26906. getMixer() {
  26907. return this._mixer;
  26908. }
  26909. getClip() {
  26910. return this._clip;
  26911. }
  26912. getRoot() {
  26913. return this._localRoot || this._mixer._root;
  26914. } // Interna
  26915. _update(time, deltaTime, timeDirection, accuIndex) {
  26916. // called by the mixer
  26917. if (!this.enabled) {
  26918. // call ._updateWeight() to update ._effectiveWeight
  26919. this._updateWeight(time);
  26920. return;
  26921. }
  26922. const startTime = this._startTime;
  26923. if (startTime !== null) {
  26924. // check for scheduled start of action
  26925. const timeRunning = (time - startTime) * timeDirection;
  26926. if (timeRunning < 0 || timeDirection === 0) {
  26927. return; // yet to come / don't decide when delta = 0
  26928. } // start
  26929. this._startTime = null; // unschedule
  26930. deltaTime = timeDirection * timeRunning;
  26931. } // apply time scale and advance time
  26932. deltaTime *= this._updateTimeScale(time);
  26933. const clipTime = this._updateTime(deltaTime); // note: _updateTime may disable the action resulting in
  26934. // an effective weight of 0
  26935. const weight = this._updateWeight(time);
  26936. if (weight > 0) {
  26937. const interpolants = this._interpolants;
  26938. const propertyMixers = this._propertyBindings;
  26939. switch (this.blendMode) {
  26940. case AdditiveAnimationBlendMode:
  26941. for (let j = 0, m = interpolants.length; j !== m; ++j) {
  26942. interpolants[j].evaluate(clipTime);
  26943. propertyMixers[j].accumulateAdditive(weight);
  26944. }
  26945. break;
  26946. case NormalAnimationBlendMode:
  26947. default:
  26948. for (let j = 0, m = interpolants.length; j !== m; ++j) {
  26949. interpolants[j].evaluate(clipTime);
  26950. propertyMixers[j].accumulate(accuIndex, weight);
  26951. }
  26952. }
  26953. }
  26954. }
  26955. _updateWeight(time) {
  26956. let weight = 0;
  26957. if (this.enabled) {
  26958. weight = this.weight;
  26959. const interpolant = this._weightInterpolant;
  26960. if (interpolant !== null) {
  26961. const interpolantValue = interpolant.evaluate(time)[0];
  26962. weight *= interpolantValue;
  26963. if (time > interpolant.parameterPositions[1]) {
  26964. this.stopFading();
  26965. if (interpolantValue === 0) {
  26966. // faded out, disable
  26967. this.enabled = false;
  26968. }
  26969. }
  26970. }
  26971. }
  26972. this._effectiveWeight = weight;
  26973. return weight;
  26974. }
  26975. _updateTimeScale(time) {
  26976. let timeScale = 0;
  26977. if (!this.paused) {
  26978. timeScale = this.timeScale;
  26979. const interpolant = this._timeScaleInterpolant;
  26980. if (interpolant !== null) {
  26981. const interpolantValue = interpolant.evaluate(time)[0];
  26982. timeScale *= interpolantValue;
  26983. if (time > interpolant.parameterPositions[1]) {
  26984. this.stopWarping();
  26985. if (timeScale === 0) {
  26986. // motion has halted, pause
  26987. this.paused = true;
  26988. } else {
  26989. // warp done - apply final time scale
  26990. this.timeScale = timeScale;
  26991. }
  26992. }
  26993. }
  26994. }
  26995. this._effectiveTimeScale = timeScale;
  26996. return timeScale;
  26997. }
  26998. _updateTime(deltaTime) {
  26999. const duration = this._clip.duration;
  27000. const loop = this.loop;
  27001. let time = this.time + deltaTime;
  27002. let loopCount = this._loopCount;
  27003. const pingPong = loop === LoopPingPong;
  27004. if (deltaTime === 0) {
  27005. if (loopCount === -1) return time;
  27006. return pingPong && (loopCount & 1) === 1 ? duration - time : time;
  27007. }
  27008. if (loop === LoopOnce) {
  27009. if (loopCount === -1) {
  27010. // just started
  27011. this._loopCount = 0;
  27012. this._setEndings(true, true, false);
  27013. }
  27014. handle_stop: {
  27015. if (time >= duration) {
  27016. time = duration;
  27017. } else if (time < 0) {
  27018. time = 0;
  27019. } else {
  27020. this.time = time;
  27021. break handle_stop;
  27022. }
  27023. if (this.clampWhenFinished) this.paused = true;else this.enabled = false;
  27024. this.time = time;
  27025. this._mixer.dispatchEvent({
  27026. type: 'finished',
  27027. action: this,
  27028. direction: deltaTime < 0 ? -1 : 1
  27029. });
  27030. }
  27031. } else {
  27032. // repetitive Repeat or PingPong
  27033. if (loopCount === -1) {
  27034. // just started
  27035. if (deltaTime >= 0) {
  27036. loopCount = 0;
  27037. this._setEndings(true, this.repetitions === 0, pingPong);
  27038. } else {
  27039. // when looping in reverse direction, the initial
  27040. // transition through zero counts as a repetition,
  27041. // so leave loopCount at -1
  27042. this._setEndings(this.repetitions === 0, true, pingPong);
  27043. }
  27044. }
  27045. if (time >= duration || time < 0) {
  27046. // wrap around
  27047. const loopDelta = Math.floor(time / duration); // signed
  27048. time -= duration * loopDelta;
  27049. loopCount += Math.abs(loopDelta);
  27050. const pending = this.repetitions - loopCount;
  27051. if (pending <= 0) {
  27052. // have to stop (switch state, clamp time, fire event)
  27053. if (this.clampWhenFinished) this.paused = true;else this.enabled = false;
  27054. time = deltaTime > 0 ? duration : 0;
  27055. this.time = time;
  27056. this._mixer.dispatchEvent({
  27057. type: 'finished',
  27058. action: this,
  27059. direction: deltaTime > 0 ? 1 : -1
  27060. });
  27061. } else {
  27062. // keep running
  27063. if (pending === 1) {
  27064. // entering the last round
  27065. const atStart = deltaTime < 0;
  27066. this._setEndings(atStart, !atStart, pingPong);
  27067. } else {
  27068. this._setEndings(false, false, pingPong);
  27069. }
  27070. this._loopCount = loopCount;
  27071. this.time = time;
  27072. this._mixer.dispatchEvent({
  27073. type: 'loop',
  27074. action: this,
  27075. loopDelta: loopDelta
  27076. });
  27077. }
  27078. } else {
  27079. this.time = time;
  27080. }
  27081. if (pingPong && (loopCount & 1) === 1) {
  27082. // invert time for the "pong round"
  27083. return duration - time;
  27084. }
  27085. }
  27086. return time;
  27087. }
  27088. _setEndings(atStart, atEnd, pingPong) {
  27089. const settings = this._interpolantSettings;
  27090. if (pingPong) {
  27091. settings.endingStart = ZeroSlopeEnding;
  27092. settings.endingEnd = ZeroSlopeEnding;
  27093. } else {
  27094. // assuming for LoopOnce atStart == atEnd == true
  27095. if (atStart) {
  27096. settings.endingStart = this.zeroSlopeAtStart ? ZeroSlopeEnding : ZeroCurvatureEnding;
  27097. } else {
  27098. settings.endingStart = WrapAroundEnding;
  27099. }
  27100. if (atEnd) {
  27101. settings.endingEnd = this.zeroSlopeAtEnd ? ZeroSlopeEnding : ZeroCurvatureEnding;
  27102. } else {
  27103. settings.endingEnd = WrapAroundEnding;
  27104. }
  27105. }
  27106. }
  27107. _scheduleFading(duration, weightNow, weightThen) {
  27108. const mixer = this._mixer,
  27109. now = mixer.time;
  27110. let interpolant = this._weightInterpolant;
  27111. if (interpolant === null) {
  27112. interpolant = mixer._lendControlInterpolant();
  27113. this._weightInterpolant = interpolant;
  27114. }
  27115. const times = interpolant.parameterPositions,
  27116. values = interpolant.sampleValues;
  27117. times[0] = now;
  27118. values[0] = weightNow;
  27119. times[1] = now + duration;
  27120. values[1] = weightThen;
  27121. return this;
  27122. }
  27123. }
  27124. function AnimationMixer(root) {
  27125. this._root = root;
  27126. this._initMemoryManager();
  27127. this._accuIndex = 0;
  27128. this.time = 0;
  27129. this.timeScale = 1.0;
  27130. }
  27131. AnimationMixer.prototype = Object.assign(Object.create(EventDispatcher.prototype), {
  27132. constructor: AnimationMixer,
  27133. _bindAction: function (action, prototypeAction) {
  27134. const root = action._localRoot || this._root,
  27135. tracks = action._clip.tracks,
  27136. nTracks = tracks.length,
  27137. bindings = action._propertyBindings,
  27138. interpolants = action._interpolants,
  27139. rootUuid = root.uuid,
  27140. bindingsByRoot = this._bindingsByRootAndName;
  27141. let bindingsByName = bindingsByRoot[rootUuid];
  27142. if (bindingsByName === undefined) {
  27143. bindingsByName = {};
  27144. bindingsByRoot[rootUuid] = bindingsByName;
  27145. }
  27146. for (let i = 0; i !== nTracks; ++i) {
  27147. const track = tracks[i],
  27148. trackName = track.name;
  27149. let binding = bindingsByName[trackName];
  27150. if (binding !== undefined) {
  27151. bindings[i] = binding;
  27152. } else {
  27153. binding = bindings[i];
  27154. if (binding !== undefined) {
  27155. // existing binding, make sure the cache knows
  27156. if (binding._cacheIndex === null) {
  27157. ++binding.referenceCount;
  27158. this._addInactiveBinding(binding, rootUuid, trackName);
  27159. }
  27160. continue;
  27161. }
  27162. const path = prototypeAction && prototypeAction._propertyBindings[i].binding.parsedPath;
  27163. binding = new PropertyMixer(PropertyBinding.create(root, trackName, path), track.ValueTypeName, track.getValueSize());
  27164. ++binding.referenceCount;
  27165. this._addInactiveBinding(binding, rootUuid, trackName);
  27166. bindings[i] = binding;
  27167. }
  27168. interpolants[i].resultBuffer = binding.buffer;
  27169. }
  27170. },
  27171. _activateAction: function (action) {
  27172. if (!this._isActiveAction(action)) {
  27173. if (action._cacheIndex === null) {
  27174. // this action has been forgotten by the cache, but the user
  27175. // appears to be still using it -> rebind
  27176. const rootUuid = (action._localRoot || this._root).uuid,
  27177. clipUuid = action._clip.uuid,
  27178. actionsForClip = this._actionsByClip[clipUuid];
  27179. this._bindAction(action, actionsForClip && actionsForClip.knownActions[0]);
  27180. this._addInactiveAction(action, clipUuid, rootUuid);
  27181. }
  27182. const bindings = action._propertyBindings; // increment reference counts / sort out state
  27183. for (let i = 0, n = bindings.length; i !== n; ++i) {
  27184. const binding = bindings[i];
  27185. if (binding.useCount++ === 0) {
  27186. this._lendBinding(binding);
  27187. binding.saveOriginalState();
  27188. }
  27189. }
  27190. this._lendAction(action);
  27191. }
  27192. },
  27193. _deactivateAction: function (action) {
  27194. if (this._isActiveAction(action)) {
  27195. const bindings = action._propertyBindings; // decrement reference counts / sort out state
  27196. for (let i = 0, n = bindings.length; i !== n; ++i) {
  27197. const binding = bindings[i];
  27198. if (--binding.useCount === 0) {
  27199. binding.restoreOriginalState();
  27200. this._takeBackBinding(binding);
  27201. }
  27202. }
  27203. this._takeBackAction(action);
  27204. }
  27205. },
  27206. // Memory manager
  27207. _initMemoryManager: function () {
  27208. this._actions = []; // 'nActiveActions' followed by inactive ones
  27209. this._nActiveActions = 0;
  27210. this._actionsByClip = {}; // inside:
  27211. // {
  27212. // knownActions: Array< AnimationAction > - used as prototypes
  27213. // actionByRoot: AnimationAction - lookup
  27214. // }
  27215. this._bindings = []; // 'nActiveBindings' followed by inactive ones
  27216. this._nActiveBindings = 0;
  27217. this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer >
  27218. this._controlInterpolants = []; // same game as above
  27219. this._nActiveControlInterpolants = 0;
  27220. const scope = this;
  27221. this.stats = {
  27222. actions: {
  27223. get total() {
  27224. return scope._actions.length;
  27225. },
  27226. get inUse() {
  27227. return scope._nActiveActions;
  27228. }
  27229. },
  27230. bindings: {
  27231. get total() {
  27232. return scope._bindings.length;
  27233. },
  27234. get inUse() {
  27235. return scope._nActiveBindings;
  27236. }
  27237. },
  27238. controlInterpolants: {
  27239. get total() {
  27240. return scope._controlInterpolants.length;
  27241. },
  27242. get inUse() {
  27243. return scope._nActiveControlInterpolants;
  27244. }
  27245. }
  27246. };
  27247. },
  27248. // Memory management for AnimationAction objects
  27249. _isActiveAction: function (action) {
  27250. const index = action._cacheIndex;
  27251. return index !== null && index < this._nActiveActions;
  27252. },
  27253. _addInactiveAction: function (action, clipUuid, rootUuid) {
  27254. const actions = this._actions,
  27255. actionsByClip = this._actionsByClip;
  27256. let actionsForClip = actionsByClip[clipUuid];
  27257. if (actionsForClip === undefined) {
  27258. actionsForClip = {
  27259. knownActions: [action],
  27260. actionByRoot: {}
  27261. };
  27262. action._byClipCacheIndex = 0;
  27263. actionsByClip[clipUuid] = actionsForClip;
  27264. } else {
  27265. const knownActions = actionsForClip.knownActions;
  27266. action._byClipCacheIndex = knownActions.length;
  27267. knownActions.push(action);
  27268. }
  27269. action._cacheIndex = actions.length;
  27270. actions.push(action);
  27271. actionsForClip.actionByRoot[rootUuid] = action;
  27272. },
  27273. _removeInactiveAction: function (action) {
  27274. const actions = this._actions,
  27275. lastInactiveAction = actions[actions.length - 1],
  27276. cacheIndex = action._cacheIndex;
  27277. lastInactiveAction._cacheIndex = cacheIndex;
  27278. actions[cacheIndex] = lastInactiveAction;
  27279. actions.pop();
  27280. action._cacheIndex = null;
  27281. const clipUuid = action._clip.uuid,
  27282. actionsByClip = this._actionsByClip,
  27283. actionsForClip = actionsByClip[clipUuid],
  27284. knownActionsForClip = actionsForClip.knownActions,
  27285. lastKnownAction = knownActionsForClip[knownActionsForClip.length - 1],
  27286. byClipCacheIndex = action._byClipCacheIndex;
  27287. lastKnownAction._byClipCacheIndex = byClipCacheIndex;
  27288. knownActionsForClip[byClipCacheIndex] = lastKnownAction;
  27289. knownActionsForClip.pop();
  27290. action._byClipCacheIndex = null;
  27291. const actionByRoot = actionsForClip.actionByRoot,
  27292. rootUuid = (action._localRoot || this._root).uuid;
  27293. delete actionByRoot[rootUuid];
  27294. if (knownActionsForClip.length === 0) {
  27295. delete actionsByClip[clipUuid];
  27296. }
  27297. this._removeInactiveBindingsForAction(action);
  27298. },
  27299. _removeInactiveBindingsForAction: function (action) {
  27300. const bindings = action._propertyBindings;
  27301. for (let i = 0, n = bindings.length; i !== n; ++i) {
  27302. const binding = bindings[i];
  27303. if (--binding.referenceCount === 0) {
  27304. this._removeInactiveBinding(binding);
  27305. }
  27306. }
  27307. },
  27308. _lendAction: function (action) {
  27309. // [ active actions | inactive actions ]
  27310. // [ active actions >| inactive actions ]
  27311. // s a
  27312. // <-swap->
  27313. // a s
  27314. const actions = this._actions,
  27315. prevIndex = action._cacheIndex,
  27316. lastActiveIndex = this._nActiveActions++,
  27317. firstInactiveAction = actions[lastActiveIndex];
  27318. action._cacheIndex = lastActiveIndex;
  27319. actions[lastActiveIndex] = action;
  27320. firstInactiveAction._cacheIndex = prevIndex;
  27321. actions[prevIndex] = firstInactiveAction;
  27322. },
  27323. _takeBackAction: function (action) {
  27324. // [ active actions | inactive actions ]
  27325. // [ active actions |< inactive actions ]
  27326. // a s
  27327. // <-swap->
  27328. // s a
  27329. const actions = this._actions,
  27330. prevIndex = action._cacheIndex,
  27331. firstInactiveIndex = --this._nActiveActions,
  27332. lastActiveAction = actions[firstInactiveIndex];
  27333. action._cacheIndex = firstInactiveIndex;
  27334. actions[firstInactiveIndex] = action;
  27335. lastActiveAction._cacheIndex = prevIndex;
  27336. actions[prevIndex] = lastActiveAction;
  27337. },
  27338. // Memory management for PropertyMixer objects
  27339. _addInactiveBinding: function (binding, rootUuid, trackName) {
  27340. const bindingsByRoot = this._bindingsByRootAndName,
  27341. bindings = this._bindings;
  27342. let bindingByName = bindingsByRoot[rootUuid];
  27343. if (bindingByName === undefined) {
  27344. bindingByName = {};
  27345. bindingsByRoot[rootUuid] = bindingByName;
  27346. }
  27347. bindingByName[trackName] = binding;
  27348. binding._cacheIndex = bindings.length;
  27349. bindings.push(binding);
  27350. },
  27351. _removeInactiveBinding: function (binding) {
  27352. const bindings = this._bindings,
  27353. propBinding = binding.binding,
  27354. rootUuid = propBinding.rootNode.uuid,
  27355. trackName = propBinding.path,
  27356. bindingsByRoot = this._bindingsByRootAndName,
  27357. bindingByName = bindingsByRoot[rootUuid],
  27358. lastInactiveBinding = bindings[bindings.length - 1],
  27359. cacheIndex = binding._cacheIndex;
  27360. lastInactiveBinding._cacheIndex = cacheIndex;
  27361. bindings[cacheIndex] = lastInactiveBinding;
  27362. bindings.pop();
  27363. delete bindingByName[trackName];
  27364. if (Object.keys(bindingByName).length === 0) {
  27365. delete bindingsByRoot[rootUuid];
  27366. }
  27367. },
  27368. _lendBinding: function (binding) {
  27369. const bindings = this._bindings,
  27370. prevIndex = binding._cacheIndex,
  27371. lastActiveIndex = this._nActiveBindings++,
  27372. firstInactiveBinding = bindings[lastActiveIndex];
  27373. binding._cacheIndex = lastActiveIndex;
  27374. bindings[lastActiveIndex] = binding;
  27375. firstInactiveBinding._cacheIndex = prevIndex;
  27376. bindings[prevIndex] = firstInactiveBinding;
  27377. },
  27378. _takeBackBinding: function (binding) {
  27379. const bindings = this._bindings,
  27380. prevIndex = binding._cacheIndex,
  27381. firstInactiveIndex = --this._nActiveBindings,
  27382. lastActiveBinding = bindings[firstInactiveIndex];
  27383. binding._cacheIndex = firstInactiveIndex;
  27384. bindings[firstInactiveIndex] = binding;
  27385. lastActiveBinding._cacheIndex = prevIndex;
  27386. bindings[prevIndex] = lastActiveBinding;
  27387. },
  27388. // Memory management of Interpolants for weight and time scale
  27389. _lendControlInterpolant: function () {
  27390. const interpolants = this._controlInterpolants,
  27391. lastActiveIndex = this._nActiveControlInterpolants++;
  27392. let interpolant = interpolants[lastActiveIndex];
  27393. if (interpolant === undefined) {
  27394. interpolant = new LinearInterpolant(new Float32Array(2), new Float32Array(2), 1, this._controlInterpolantsResultBuffer);
  27395. interpolant.__cacheIndex = lastActiveIndex;
  27396. interpolants[lastActiveIndex] = interpolant;
  27397. }
  27398. return interpolant;
  27399. },
  27400. _takeBackControlInterpolant: function (interpolant) {
  27401. const interpolants = this._controlInterpolants,
  27402. prevIndex = interpolant.__cacheIndex,
  27403. firstInactiveIndex = --this._nActiveControlInterpolants,
  27404. lastActiveInterpolant = interpolants[firstInactiveIndex];
  27405. interpolant.__cacheIndex = firstInactiveIndex;
  27406. interpolants[firstInactiveIndex] = interpolant;
  27407. lastActiveInterpolant.__cacheIndex = prevIndex;
  27408. interpolants[prevIndex] = lastActiveInterpolant;
  27409. },
  27410. _controlInterpolantsResultBuffer: new Float32Array(1),
  27411. // return an action for a clip optionally using a custom root target
  27412. // object (this method allocates a lot of dynamic memory in case a
  27413. // previously unknown clip/root combination is specified)
  27414. clipAction: function (clip, optionalRoot, blendMode) {
  27415. const root = optionalRoot || this._root,
  27416. rootUuid = root.uuid;
  27417. let clipObject = typeof clip === 'string' ? AnimationClip.findByName(root, clip) : clip;
  27418. const clipUuid = clipObject !== null ? clipObject.uuid : clip;
  27419. const actionsForClip = this._actionsByClip[clipUuid];
  27420. let prototypeAction = null;
  27421. if (blendMode === undefined) {
  27422. if (clipObject !== null) {
  27423. blendMode = clipObject.blendMode;
  27424. } else {
  27425. blendMode = NormalAnimationBlendMode;
  27426. }
  27427. }
  27428. if (actionsForClip !== undefined) {
  27429. const existingAction = actionsForClip.actionByRoot[rootUuid];
  27430. if (existingAction !== undefined && existingAction.blendMode === blendMode) {
  27431. return existingAction;
  27432. } // we know the clip, so we don't have to parse all
  27433. // the bindings again but can just copy
  27434. prototypeAction = actionsForClip.knownActions[0]; // also, take the clip from the prototype action
  27435. if (clipObject === null) clipObject = prototypeAction._clip;
  27436. } // clip must be known when specified via string
  27437. if (clipObject === null) return null; // allocate all resources required to run it
  27438. const newAction = new AnimationAction(this, clipObject, optionalRoot, blendMode);
  27439. this._bindAction(newAction, prototypeAction); // and make the action known to the memory manager
  27440. this._addInactiveAction(newAction, clipUuid, rootUuid);
  27441. return newAction;
  27442. },
  27443. // get an existing action
  27444. existingAction: function (clip, optionalRoot) {
  27445. const root = optionalRoot || this._root,
  27446. rootUuid = root.uuid,
  27447. clipObject = typeof clip === 'string' ? AnimationClip.findByName(root, clip) : clip,
  27448. clipUuid = clipObject ? clipObject.uuid : clip,
  27449. actionsForClip = this._actionsByClip[clipUuid];
  27450. if (actionsForClip !== undefined) {
  27451. return actionsForClip.actionByRoot[rootUuid] || null;
  27452. }
  27453. return null;
  27454. },
  27455. // deactivates all previously scheduled actions
  27456. stopAllAction: function () {
  27457. const actions = this._actions,
  27458. nActions = this._nActiveActions;
  27459. for (let i = nActions - 1; i >= 0; --i) {
  27460. actions[i].stop();
  27461. }
  27462. return this;
  27463. },
  27464. // advance the time and update apply the animation
  27465. update: function (deltaTime) {
  27466. deltaTime *= this.timeScale;
  27467. const actions = this._actions,
  27468. nActions = this._nActiveActions,
  27469. time = this.time += deltaTime,
  27470. timeDirection = Math.sign(deltaTime),
  27471. accuIndex = this._accuIndex ^= 1; // run active actions
  27472. for (let i = 0; i !== nActions; ++i) {
  27473. const action = actions[i];
  27474. action._update(time, deltaTime, timeDirection, accuIndex);
  27475. } // update scene graph
  27476. const bindings = this._bindings,
  27477. nBindings = this._nActiveBindings;
  27478. for (let i = 0; i !== nBindings; ++i) {
  27479. bindings[i].apply(accuIndex);
  27480. }
  27481. return this;
  27482. },
  27483. // Allows you to seek to a specific time in an animation.
  27484. setTime: function (timeInSeconds) {
  27485. this.time = 0; // Zero out time attribute for AnimationMixer object;
  27486. for (let i = 0; i < this._actions.length; i++) {
  27487. this._actions[i].time = 0; // Zero out time attribute for all associated AnimationAction objects.
  27488. }
  27489. return this.update(timeInSeconds); // Update used to set exact time. Returns "this" AnimationMixer object.
  27490. },
  27491. // return this mixer's root target object
  27492. getRoot: function () {
  27493. return this._root;
  27494. },
  27495. // free all resources specific to a particular clip
  27496. uncacheClip: function (clip) {
  27497. const actions = this._actions,
  27498. clipUuid = clip.uuid,
  27499. actionsByClip = this._actionsByClip,
  27500. actionsForClip = actionsByClip[clipUuid];
  27501. if (actionsForClip !== undefined) {
  27502. // note: just calling _removeInactiveAction would mess up the
  27503. // iteration state and also require updating the state we can
  27504. // just throw away
  27505. const actionsToRemove = actionsForClip.knownActions;
  27506. for (let i = 0, n = actionsToRemove.length; i !== n; ++i) {
  27507. const action = actionsToRemove[i];
  27508. this._deactivateAction(action);
  27509. const cacheIndex = action._cacheIndex,
  27510. lastInactiveAction = actions[actions.length - 1];
  27511. action._cacheIndex = null;
  27512. action._byClipCacheIndex = null;
  27513. lastInactiveAction._cacheIndex = cacheIndex;
  27514. actions[cacheIndex] = lastInactiveAction;
  27515. actions.pop();
  27516. this._removeInactiveBindingsForAction(action);
  27517. }
  27518. delete actionsByClip[clipUuid];
  27519. }
  27520. },
  27521. // free all resources specific to a particular root target object
  27522. uncacheRoot: function (root) {
  27523. const rootUuid = root.uuid,
  27524. actionsByClip = this._actionsByClip;
  27525. for (const clipUuid in actionsByClip) {
  27526. const actionByRoot = actionsByClip[clipUuid].actionByRoot,
  27527. action = actionByRoot[rootUuid];
  27528. if (action !== undefined) {
  27529. this._deactivateAction(action);
  27530. this._removeInactiveAction(action);
  27531. }
  27532. }
  27533. const bindingsByRoot = this._bindingsByRootAndName,
  27534. bindingByName = bindingsByRoot[rootUuid];
  27535. if (bindingByName !== undefined) {
  27536. for (const trackName in bindingByName) {
  27537. const binding = bindingByName[trackName];
  27538. binding.restoreOriginalState();
  27539. this._removeInactiveBinding(binding);
  27540. }
  27541. }
  27542. },
  27543. // remove a targeted clip from the cache
  27544. uncacheAction: function (clip, optionalRoot) {
  27545. const action = this.existingAction(clip, optionalRoot);
  27546. if (action !== null) {
  27547. this._deactivateAction(action);
  27548. this._removeInactiveAction(action);
  27549. }
  27550. }
  27551. });
  27552. class Uniform {
  27553. constructor(value) {
  27554. if (typeof value === 'string') {
  27555. console.warn('THREE.Uniform: Type parameter is no longer needed.');
  27556. value = arguments[1];
  27557. }
  27558. this.value = value;
  27559. }
  27560. clone() {
  27561. return new Uniform(this.value.clone === undefined ? this.value : this.value.clone());
  27562. }
  27563. }
  27564. exports.Uniform = Uniform;
  27565. function InstancedInterleavedBuffer(array, stride, meshPerAttribute) {
  27566. InterleavedBuffer.call(this, array, stride);
  27567. this.meshPerAttribute = meshPerAttribute || 1;
  27568. }
  27569. InstancedInterleavedBuffer.prototype = Object.assign(Object.create(InterleavedBuffer.prototype), {
  27570. constructor: InstancedInterleavedBuffer,
  27571. isInstancedInterleavedBuffer: true,
  27572. copy: function (source) {
  27573. InterleavedBuffer.prototype.copy.call(this, source);
  27574. this.meshPerAttribute = source.meshPerAttribute;
  27575. return this;
  27576. },
  27577. clone: function (data) {
  27578. const ib = InterleavedBuffer.prototype.clone.call(this, data);
  27579. ib.meshPerAttribute = this.meshPerAttribute;
  27580. return ib;
  27581. },
  27582. toJSON: function (data) {
  27583. const json = InterleavedBuffer.prototype.toJSON.call(this, data);
  27584. json.isInstancedInterleavedBuffer = true;
  27585. json.meshPerAttribute = this.meshPerAttribute;
  27586. return json;
  27587. }
  27588. });
  27589. function GLBufferAttribute(buffer, type, itemSize, elementSize, count) {
  27590. this.buffer = buffer;
  27591. this.type = type;
  27592. this.itemSize = itemSize;
  27593. this.elementSize = elementSize;
  27594. this.count = count;
  27595. this.version = 0;
  27596. }
  27597. Object.defineProperty(GLBufferAttribute.prototype, 'needsUpdate', {
  27598. set: function (value) {
  27599. if (value === true) this.version++;
  27600. }
  27601. });
  27602. Object.assign(GLBufferAttribute.prototype, {
  27603. isGLBufferAttribute: true,
  27604. setBuffer: function (buffer) {
  27605. this.buffer = buffer;
  27606. return this;
  27607. },
  27608. setType: function (type, elementSize) {
  27609. this.type = type;
  27610. this.elementSize = elementSize;
  27611. return this;
  27612. },
  27613. setItemSize: function (itemSize) {
  27614. this.itemSize = itemSize;
  27615. return this;
  27616. },
  27617. setCount: function (count) {
  27618. this.count = count;
  27619. return this;
  27620. }
  27621. });
  27622. function Raycaster(origin, direction, near, far) {
  27623. this.ray = new Ray(origin, direction); // direction is assumed to be normalized (for accurate distance calculations)
  27624. this.near = near || 0;
  27625. this.far = far || Infinity;
  27626. this.camera = null;
  27627. this.layers = new Layers();
  27628. this.params = {
  27629. Mesh: {},
  27630. Line: {
  27631. threshold: 1
  27632. },
  27633. LOD: {},
  27634. Points: {
  27635. threshold: 1
  27636. },
  27637. Sprite: {}
  27638. };
  27639. Object.defineProperties(this.params, {
  27640. PointCloud: {
  27641. get: function () {
  27642. console.warn('THREE.Raycaster: params.PointCloud has been renamed to params.Points.');
  27643. return this.Points;
  27644. }
  27645. }
  27646. });
  27647. }
  27648. function ascSort(a, b) {
  27649. return a.distance - b.distance;
  27650. }
  27651. function intersectObject(object, raycaster, intersects, recursive) {
  27652. if (object.layers.test(raycaster.layers)) {
  27653. object.raycast(raycaster, intersects);
  27654. }
  27655. if (recursive === true) {
  27656. const children = object.children;
  27657. for (let i = 0, l = children.length; i < l; i++) {
  27658. intersectObject(children[i], raycaster, intersects, true);
  27659. }
  27660. }
  27661. }
  27662. Object.assign(Raycaster.prototype, {
  27663. set: function (origin, direction) {
  27664. // direction is assumed to be normalized (for accurate distance calculations)
  27665. this.ray.set(origin, direction);
  27666. },
  27667. setFromCamera: function (coords, camera) {
  27668. if (camera && camera.isPerspectiveCamera) {
  27669. this.ray.origin.setFromMatrixPosition(camera.matrixWorld);
  27670. this.ray.direction.set(coords.x, coords.y, 0.5).unproject(camera).sub(this.ray.origin).normalize();
  27671. this.camera = camera;
  27672. } else if (camera && camera.isOrthographicCamera) {
  27673. this.ray.origin.set(coords.x, coords.y, (camera.near + camera.far) / (camera.near - camera.far)).unproject(camera); // set origin in plane of camera
  27674. this.ray.direction.set(0, 0, -1).transformDirection(camera.matrixWorld);
  27675. this.camera = camera;
  27676. } else {
  27677. console.error('THREE.Raycaster: Unsupported camera type.');
  27678. }
  27679. },
  27680. intersectObject: function (object, recursive, optionalTarget) {
  27681. const intersects = optionalTarget || [];
  27682. intersectObject(object, this, intersects, recursive);
  27683. intersects.sort(ascSort);
  27684. return intersects;
  27685. },
  27686. intersectObjects: function (objects, recursive, optionalTarget) {
  27687. const intersects = optionalTarget || [];
  27688. if (Array.isArray(objects) === false) {
  27689. console.warn('THREE.Raycaster.intersectObjects: objects is not an Array.');
  27690. return intersects;
  27691. }
  27692. for (let i = 0, l = objects.length; i < l; i++) {
  27693. intersectObject(objects[i], this, intersects, recursive);
  27694. }
  27695. intersects.sort(ascSort);
  27696. return intersects;
  27697. }
  27698. });
  27699. /**
  27700. * Ref: https://en.wikipedia.org/wiki/Spherical_coordinate_system
  27701. *
  27702. * The polar angle (phi) is measured from the positive y-axis. The positive y-axis is up.
  27703. * The azimuthal angle (theta) is measured from the positive z-axis.
  27704. */
  27705. class Spherical {
  27706. constructor(radius = 1, phi = 0, theta = 0) {
  27707. this.radius = radius;
  27708. this.phi = phi; // polar angle
  27709. this.theta = theta; // azimuthal angle
  27710. return this;
  27711. }
  27712. set(radius, phi, theta) {
  27713. this.radius = radius;
  27714. this.phi = phi;
  27715. this.theta = theta;
  27716. return this;
  27717. }
  27718. clone() {
  27719. return new this.constructor().copy(this);
  27720. }
  27721. copy(other) {
  27722. this.radius = other.radius;
  27723. this.phi = other.phi;
  27724. this.theta = other.theta;
  27725. return this;
  27726. } // restrict phi to be betwee EPS and PI-EPS
  27727. makeSafe() {
  27728. const EPS = 0.000001;
  27729. this.phi = Math.max(EPS, Math.min(Math.PI - EPS, this.phi));
  27730. return this;
  27731. }
  27732. setFromVector3(v) {
  27733. return this.setFromCartesianCoords(v.x, v.y, v.z);
  27734. }
  27735. setFromCartesianCoords(x, y, z) {
  27736. this.radius = Math.sqrt(x * x + y * y + z * z);
  27737. if (this.radius === 0) {
  27738. this.theta = 0;
  27739. this.phi = 0;
  27740. } else {
  27741. this.theta = Math.atan2(x, z);
  27742. this.phi = Math.acos(MathUtils.clamp(y / this.radius, -1, 1));
  27743. }
  27744. return this;
  27745. }
  27746. }
  27747. /**
  27748. * Ref: https://en.wikipedia.org/wiki/Cylindrical_coordinate_system
  27749. */
  27750. exports.Spherical = Spherical;
  27751. class Cylindrical {
  27752. constructor(radius, theta, y) {
  27753. this.radius = radius !== undefined ? radius : 1.0; // distance from the origin to a point in the x-z plane
  27754. this.theta = theta !== undefined ? theta : 0; // counterclockwise angle in the x-z plane measured in radians from the positive z-axis
  27755. this.y = y !== undefined ? y : 0; // height above the x-z plane
  27756. return this;
  27757. }
  27758. set(radius, theta, y) {
  27759. this.radius = radius;
  27760. this.theta = theta;
  27761. this.y = y;
  27762. return this;
  27763. }
  27764. clone() {
  27765. return new this.constructor().copy(this);
  27766. }
  27767. copy(other) {
  27768. this.radius = other.radius;
  27769. this.theta = other.theta;
  27770. this.y = other.y;
  27771. return this;
  27772. }
  27773. setFromVector3(v) {
  27774. return this.setFromCartesianCoords(v.x, v.y, v.z);
  27775. }
  27776. setFromCartesianCoords(x, y, z) {
  27777. this.radius = Math.sqrt(x * x + z * z);
  27778. this.theta = Math.atan2(x, z);
  27779. this.y = y;
  27780. return this;
  27781. }
  27782. }
  27783. exports.Cylindrical = Cylindrical;
  27784. const _vector$7 =
  27785. /*@__PURE__*/
  27786. new Vector2();
  27787. class Box2 {
  27788. constructor(min, max) {
  27789. Object.defineProperty(this, 'isBox2', {
  27790. value: true
  27791. });
  27792. this.min = min !== undefined ? min : new Vector2(+Infinity, +Infinity);
  27793. this.max = max !== undefined ? max : new Vector2(-Infinity, -Infinity);
  27794. }
  27795. set(min, max) {
  27796. this.min.copy(min);
  27797. this.max.copy(max);
  27798. return this;
  27799. }
  27800. setFromPoints(points) {
  27801. this.makeEmpty();
  27802. for (let i = 0, il = points.length; i < il; i++) {
  27803. this.expandByPoint(points[i]);
  27804. }
  27805. return this;
  27806. }
  27807. setFromCenterAndSize(center, size) {
  27808. const halfSize = _vector$7.copy(size).multiplyScalar(0.5);
  27809. this.min.copy(center).sub(halfSize);
  27810. this.max.copy(center).add(halfSize);
  27811. return this;
  27812. }
  27813. clone() {
  27814. return new this.constructor().copy(this);
  27815. }
  27816. copy(box) {
  27817. this.min.copy(box.min);
  27818. this.max.copy(box.max);
  27819. return this;
  27820. }
  27821. makeEmpty() {
  27822. this.min.x = this.min.y = +Infinity;
  27823. this.max.x = this.max.y = -Infinity;
  27824. return this;
  27825. }
  27826. isEmpty() {
  27827. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  27828. return this.max.x < this.min.x || this.max.y < this.min.y;
  27829. }
  27830. getCenter(target) {
  27831. if (target === undefined) {
  27832. console.warn('THREE.Box2: .getCenter() target is now required');
  27833. target = new Vector2();
  27834. }
  27835. return this.isEmpty() ? target.set(0, 0) : target.addVectors(this.min, this.max).multiplyScalar(0.5);
  27836. }
  27837. getSize(target) {
  27838. if (target === undefined) {
  27839. console.warn('THREE.Box2: .getSize() target is now required');
  27840. target = new Vector2();
  27841. }
  27842. return this.isEmpty() ? target.set(0, 0) : target.subVectors(this.max, this.min);
  27843. }
  27844. expandByPoint(point) {
  27845. this.min.min(point);
  27846. this.max.max(point);
  27847. return this;
  27848. }
  27849. expandByVector(vector) {
  27850. this.min.sub(vector);
  27851. this.max.add(vector);
  27852. return this;
  27853. }
  27854. expandByScalar(scalar) {
  27855. this.min.addScalar(-scalar);
  27856. this.max.addScalar(scalar);
  27857. return this;
  27858. }
  27859. containsPoint(point) {
  27860. return point.x < this.min.x || point.x > this.max.x || point.y < this.min.y || point.y > this.max.y ? false : true;
  27861. }
  27862. containsBox(box) {
  27863. return this.min.x <= box.min.x && box.max.x <= this.max.x && this.min.y <= box.min.y && box.max.y <= this.max.y;
  27864. }
  27865. getParameter(point, target) {
  27866. // This can potentially have a divide by zero if the box
  27867. // has a size dimension of 0.
  27868. if (target === undefined) {
  27869. console.warn('THREE.Box2: .getParameter() target is now required');
  27870. target = new Vector2();
  27871. }
  27872. return target.set((point.x - this.min.x) / (this.max.x - this.min.x), (point.y - this.min.y) / (this.max.y - this.min.y));
  27873. }
  27874. intersectsBox(box) {
  27875. // using 4 splitting planes to rule out intersections
  27876. return box.max.x < this.min.x || box.min.x > this.max.x || box.max.y < this.min.y || box.min.y > this.max.y ? false : true;
  27877. }
  27878. clampPoint(point, target) {
  27879. if (target === undefined) {
  27880. console.warn('THREE.Box2: .clampPoint() target is now required');
  27881. target = new Vector2();
  27882. }
  27883. return target.copy(point).clamp(this.min, this.max);
  27884. }
  27885. distanceToPoint(point) {
  27886. const clampedPoint = _vector$7.copy(point).clamp(this.min, this.max);
  27887. return clampedPoint.sub(point).length();
  27888. }
  27889. intersect(box) {
  27890. this.min.max(box.min);
  27891. this.max.min(box.max);
  27892. return this;
  27893. }
  27894. union(box) {
  27895. this.min.min(box.min);
  27896. this.max.max(box.max);
  27897. return this;
  27898. }
  27899. translate(offset) {
  27900. this.min.add(offset);
  27901. this.max.add(offset);
  27902. return this;
  27903. }
  27904. equals(box) {
  27905. return box.min.equals(this.min) && box.max.equals(this.max);
  27906. }
  27907. }
  27908. exports.Box2 = Box2;
  27909. const _startP =
  27910. /*@__PURE__*/
  27911. new Vector3();
  27912. const _startEnd =
  27913. /*@__PURE__*/
  27914. new Vector3();
  27915. class Line3 {
  27916. constructor(start, end) {
  27917. this.start = start !== undefined ? start : new Vector3();
  27918. this.end = end !== undefined ? end : new Vector3();
  27919. }
  27920. set(start, end) {
  27921. this.start.copy(start);
  27922. this.end.copy(end);
  27923. return this;
  27924. }
  27925. clone() {
  27926. return new this.constructor().copy(this);
  27927. }
  27928. copy(line) {
  27929. this.start.copy(line.start);
  27930. this.end.copy(line.end);
  27931. return this;
  27932. }
  27933. getCenter(target) {
  27934. if (target === undefined) {
  27935. console.warn('THREE.Line3: .getCenter() target is now required');
  27936. target = new Vector3();
  27937. }
  27938. return target.addVectors(this.start, this.end).multiplyScalar(0.5);
  27939. }
  27940. delta(target) {
  27941. if (target === undefined) {
  27942. console.warn('THREE.Line3: .delta() target is now required');
  27943. target = new Vector3();
  27944. }
  27945. return target.subVectors(this.end, this.start);
  27946. }
  27947. distanceSq() {
  27948. return this.start.distanceToSquared(this.end);
  27949. }
  27950. distance() {
  27951. return this.start.distanceTo(this.end);
  27952. }
  27953. at(t, target) {
  27954. if (target === undefined) {
  27955. console.warn('THREE.Line3: .at() target is now required');
  27956. target = new Vector3();
  27957. }
  27958. return this.delta(target).multiplyScalar(t).add(this.start);
  27959. }
  27960. closestPointToPointParameter(point, clampToLine) {
  27961. _startP.subVectors(point, this.start);
  27962. _startEnd.subVectors(this.end, this.start);
  27963. const startEnd2 = _startEnd.dot(_startEnd);
  27964. const startEnd_startP = _startEnd.dot(_startP);
  27965. let t = startEnd_startP / startEnd2;
  27966. if (clampToLine) {
  27967. t = MathUtils.clamp(t, 0, 1);
  27968. }
  27969. return t;
  27970. }
  27971. closestPointToPoint(point, clampToLine, target) {
  27972. const t = this.closestPointToPointParameter(point, clampToLine);
  27973. if (target === undefined) {
  27974. console.warn('THREE.Line3: .closestPointToPoint() target is now required');
  27975. target = new Vector3();
  27976. }
  27977. return this.delta(target).multiplyScalar(t).add(this.start);
  27978. }
  27979. applyMatrix4(matrix) {
  27980. this.start.applyMatrix4(matrix);
  27981. this.end.applyMatrix4(matrix);
  27982. return this;
  27983. }
  27984. equals(line) {
  27985. return line.start.equals(this.start) && line.end.equals(this.end);
  27986. }
  27987. }
  27988. exports.Line3 = Line3;
  27989. function ImmediateRenderObject(material) {
  27990. Object3D.call(this);
  27991. this.material = material;
  27992. this.render = function ()
  27993. /* renderCallback */
  27994. {};
  27995. this.hasPositions = false;
  27996. this.hasNormals = false;
  27997. this.hasColors = false;
  27998. this.hasUvs = false;
  27999. this.positionArray = null;
  28000. this.normalArray = null;
  28001. this.colorArray = null;
  28002. this.uvArray = null;
  28003. this.count = 0;
  28004. }
  28005. ImmediateRenderObject.prototype = Object.create(Object3D.prototype);
  28006. ImmediateRenderObject.prototype.constructor = ImmediateRenderObject;
  28007. ImmediateRenderObject.prototype.isImmediateRenderObject = true;
  28008. const _vector$8 =
  28009. /*@__PURE__*/
  28010. new Vector3();
  28011. class SpotLightHelper extends Object3D {
  28012. constructor(light, color) {
  28013. super();
  28014. this.light = light;
  28015. this.light.updateMatrixWorld();
  28016. this.matrix = light.matrixWorld;
  28017. this.matrixAutoUpdate = false;
  28018. this.color = color;
  28019. const geometry = new BufferGeometry();
  28020. const positions = [0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, -1, 0, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, -1, 1];
  28021. for (let i = 0, j = 1, l = 32; i < l; i++, j++) {
  28022. const p1 = i / l * Math.PI * 2;
  28023. const p2 = j / l * Math.PI * 2;
  28024. positions.push(Math.cos(p1), Math.sin(p1), 1, Math.cos(p2), Math.sin(p2), 1);
  28025. }
  28026. geometry.setAttribute('position', new Float32BufferAttribute(positions, 3));
  28027. const material = new LineBasicMaterial({
  28028. fog: false,
  28029. toneMapped: false
  28030. });
  28031. this.cone = new LineSegments(geometry, material);
  28032. this.add(this.cone);
  28033. this.update();
  28034. }
  28035. dispose() {
  28036. this.cone.geometry.dispose();
  28037. this.cone.material.dispose();
  28038. }
  28039. update() {
  28040. this.light.updateMatrixWorld();
  28041. const coneLength = this.light.distance ? this.light.distance : 1000;
  28042. const coneWidth = coneLength * Math.tan(this.light.angle);
  28043. this.cone.scale.set(coneWidth, coneWidth, coneLength);
  28044. _vector$8.setFromMatrixPosition(this.light.target.matrixWorld);
  28045. this.cone.lookAt(_vector$8);
  28046. if (this.color !== undefined) {
  28047. this.cone.material.color.set(this.color);
  28048. } else {
  28049. this.cone.material.color.copy(this.light.color);
  28050. }
  28051. }
  28052. }
  28053. exports.SpotLightHelper = SpotLightHelper;
  28054. const _vector$9 =
  28055. /*@__PURE__*/
  28056. new Vector3();
  28057. const _boneMatrix =
  28058. /*@__PURE__*/
  28059. new Matrix4();
  28060. const _matrixWorldInv =
  28061. /*@__PURE__*/
  28062. new Matrix4();
  28063. class SkeletonHelper extends LineSegments {
  28064. constructor(object) {
  28065. const bones = getBoneList(object);
  28066. const geometry = new BufferGeometry();
  28067. const vertices = [];
  28068. const colors = [];
  28069. const color1 = new Color(0, 0, 1);
  28070. const color2 = new Color(0, 1, 0);
  28071. for (let i = 0; i < bones.length; i++) {
  28072. const bone = bones[i];
  28073. if (bone.parent && bone.parent.isBone) {
  28074. vertices.push(0, 0, 0);
  28075. vertices.push(0, 0, 0);
  28076. colors.push(color1.r, color1.g, color1.b);
  28077. colors.push(color2.r, color2.g, color2.b);
  28078. }
  28079. }
  28080. geometry.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  28081. geometry.setAttribute('color', new Float32BufferAttribute(colors, 3));
  28082. const material = new LineBasicMaterial({
  28083. vertexColors: true,
  28084. depthTest: false,
  28085. depthWrite: false,
  28086. toneMapped: false,
  28087. transparent: true
  28088. });
  28089. super(geometry, material);
  28090. this.type = 'SkeletonHelper';
  28091. this.isSkeletonHelper = true;
  28092. this.root = object;
  28093. this.bones = bones;
  28094. this.matrix = object.matrixWorld;
  28095. this.matrixAutoUpdate = false;
  28096. }
  28097. updateMatrixWorld(force) {
  28098. const bones = this.bones;
  28099. const geometry = this.geometry;
  28100. const position = geometry.getAttribute('position');
  28101. _matrixWorldInv.copy(this.root.matrixWorld).invert();
  28102. for (let i = 0, j = 0; i < bones.length; i++) {
  28103. const bone = bones[i];
  28104. if (bone.parent && bone.parent.isBone) {
  28105. _boneMatrix.multiplyMatrices(_matrixWorldInv, bone.matrixWorld);
  28106. _vector$9.setFromMatrixPosition(_boneMatrix);
  28107. position.setXYZ(j, _vector$9.x, _vector$9.y, _vector$9.z);
  28108. _boneMatrix.multiplyMatrices(_matrixWorldInv, bone.parent.matrixWorld);
  28109. _vector$9.setFromMatrixPosition(_boneMatrix);
  28110. position.setXYZ(j + 1, _vector$9.x, _vector$9.y, _vector$9.z);
  28111. j += 2;
  28112. }
  28113. }
  28114. geometry.getAttribute('position').needsUpdate = true;
  28115. super.updateMatrixWorld(force);
  28116. }
  28117. }
  28118. exports.SkeletonHelper = SkeletonHelper;
  28119. function getBoneList(object) {
  28120. const boneList = [];
  28121. if (object && object.isBone) {
  28122. boneList.push(object);
  28123. }
  28124. for (let i = 0; i < object.children.length; i++) {
  28125. boneList.push.apply(boneList, getBoneList(object.children[i]));
  28126. }
  28127. return boneList;
  28128. }
  28129. class PointLightHelper extends Mesh {
  28130. constructor(light, sphereSize, color) {
  28131. const geometry = new SphereBufferGeometry(sphereSize, 4, 2);
  28132. const material = new MeshBasicMaterial({
  28133. wireframe: true,
  28134. fog: false,
  28135. toneMapped: false
  28136. });
  28137. super(geometry, material);
  28138. this.light = light;
  28139. this.light.updateMatrixWorld();
  28140. this.color = color;
  28141. this.type = 'PointLightHelper';
  28142. this.matrix = this.light.matrixWorld;
  28143. this.matrixAutoUpdate = false;
  28144. this.update();
  28145. /*
  28146. // TODO: delete this comment?
  28147. const distanceGeometry = new THREE.IcosahedronBufferGeometry( 1, 2 );
  28148. const distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  28149. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  28150. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  28151. const d = light.distance;
  28152. if ( d === 0.0 ) {
  28153. this.lightDistance.visible = false;
  28154. } else {
  28155. this.lightDistance.scale.set( d, d, d );
  28156. }
  28157. this.add( this.lightDistance );
  28158. */
  28159. }
  28160. dispose() {
  28161. this.geometry.dispose();
  28162. this.material.dispose();
  28163. }
  28164. update() {
  28165. if (this.color !== undefined) {
  28166. this.material.color.set(this.color);
  28167. } else {
  28168. this.material.color.copy(this.light.color);
  28169. }
  28170. /*
  28171. const d = this.light.distance;
  28172. if ( d === 0.0 ) {
  28173. this.lightDistance.visible = false;
  28174. } else {
  28175. this.lightDistance.visible = true;
  28176. this.lightDistance.scale.set( d, d, d );
  28177. }
  28178. */
  28179. }
  28180. }
  28181. exports.PointLightHelper = PointLightHelper;
  28182. const _vector$a =
  28183. /*@__PURE__*/
  28184. new Vector3();
  28185. const _color1 =
  28186. /*@__PURE__*/
  28187. new Color();
  28188. const _color2 =
  28189. /*@__PURE__*/
  28190. new Color();
  28191. class HemisphereLightHelper extends Object3D {
  28192. constructor(light, size, color) {
  28193. super();
  28194. this.light = light;
  28195. this.light.updateMatrixWorld();
  28196. this.matrix = light.matrixWorld;
  28197. this.matrixAutoUpdate = false;
  28198. this.color = color;
  28199. const geometry = new OctahedronBufferGeometry(size);
  28200. geometry.rotateY(Math.PI * 0.5);
  28201. this.material = new MeshBasicMaterial({
  28202. wireframe: true,
  28203. fog: false,
  28204. toneMapped: false
  28205. });
  28206. if (this.color === undefined) this.material.vertexColors = true;
  28207. const position = geometry.getAttribute('position');
  28208. const colors = new Float32Array(position.count * 3);
  28209. geometry.setAttribute('color', new BufferAttribute(colors, 3));
  28210. this.add(new Mesh(geometry, this.material));
  28211. this.update();
  28212. }
  28213. dispose() {
  28214. this.children[0].geometry.dispose();
  28215. this.children[0].material.dispose();
  28216. }
  28217. update() {
  28218. const mesh = this.children[0];
  28219. if (this.color !== undefined) {
  28220. this.material.color.set(this.color);
  28221. } else {
  28222. const colors = mesh.geometry.getAttribute('color');
  28223. _color1.copy(this.light.color);
  28224. _color2.copy(this.light.groundColor);
  28225. for (let i = 0, l = colors.count; i < l; i++) {
  28226. const color = i < l / 2 ? _color1 : _color2;
  28227. colors.setXYZ(i, color.r, color.g, color.b);
  28228. }
  28229. colors.needsUpdate = true;
  28230. }
  28231. mesh.lookAt(_vector$a.setFromMatrixPosition(this.light.matrixWorld).negate());
  28232. }
  28233. }
  28234. exports.HemisphereLightHelper = HemisphereLightHelper;
  28235. class GridHelper extends LineSegments {
  28236. constructor(size = 10, divisions = 10, color1 = 0x444444, color2 = 0x888888) {
  28237. color1 = new Color(color1);
  28238. color2 = new Color(color2);
  28239. const center = divisions / 2;
  28240. const step = size / divisions;
  28241. const halfSize = size / 2;
  28242. const vertices = [],
  28243. colors = [];
  28244. for (let i = 0, j = 0, k = -halfSize; i <= divisions; i++, k += step) {
  28245. vertices.push(-halfSize, 0, k, halfSize, 0, k);
  28246. vertices.push(k, 0, -halfSize, k, 0, halfSize);
  28247. const color = i === center ? color1 : color2;
  28248. color.toArray(colors, j);
  28249. j += 3;
  28250. color.toArray(colors, j);
  28251. j += 3;
  28252. color.toArray(colors, j);
  28253. j += 3;
  28254. color.toArray(colors, j);
  28255. j += 3;
  28256. }
  28257. const geometry = new BufferGeometry();
  28258. geometry.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  28259. geometry.setAttribute('color', new Float32BufferAttribute(colors, 3));
  28260. const material = new LineBasicMaterial({
  28261. vertexColors: true,
  28262. toneMapped: false
  28263. });
  28264. super(geometry, material);
  28265. this.type = 'GridHelper';
  28266. }
  28267. }
  28268. exports.GridHelper = GridHelper;
  28269. class PolarGridHelper extends LineSegments {
  28270. constructor(radius = 10, radials = 16, circles = 8, divisions = 64, color1 = 0x444444, color2 = 0x888888) {
  28271. color1 = new Color(color1);
  28272. color2 = new Color(color2);
  28273. const vertices = [];
  28274. const colors = []; // create the radials
  28275. for (let i = 0; i <= radials; i++) {
  28276. const v = i / radials * (Math.PI * 2);
  28277. const x = Math.sin(v) * radius;
  28278. const z = Math.cos(v) * radius;
  28279. vertices.push(0, 0, 0);
  28280. vertices.push(x, 0, z);
  28281. const color = i & 1 ? color1 : color2;
  28282. colors.push(color.r, color.g, color.b);
  28283. colors.push(color.r, color.g, color.b);
  28284. } // create the circles
  28285. for (let i = 0; i <= circles; i++) {
  28286. const color = i & 1 ? color1 : color2;
  28287. const r = radius - radius / circles * i;
  28288. for (let j = 0; j < divisions; j++) {
  28289. // first vertex
  28290. let v = j / divisions * (Math.PI * 2);
  28291. let x = Math.sin(v) * r;
  28292. let z = Math.cos(v) * r;
  28293. vertices.push(x, 0, z);
  28294. colors.push(color.r, color.g, color.b); // second vertex
  28295. v = (j + 1) / divisions * (Math.PI * 2);
  28296. x = Math.sin(v) * r;
  28297. z = Math.cos(v) * r;
  28298. vertices.push(x, 0, z);
  28299. colors.push(color.r, color.g, color.b);
  28300. }
  28301. }
  28302. const geometry = new BufferGeometry();
  28303. geometry.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  28304. geometry.setAttribute('color', new Float32BufferAttribute(colors, 3));
  28305. const material = new LineBasicMaterial({
  28306. vertexColors: true,
  28307. toneMapped: false
  28308. });
  28309. super(geometry, material);
  28310. this.type = 'PolarGridHelper';
  28311. }
  28312. }
  28313. exports.PolarGridHelper = PolarGridHelper;
  28314. const _v1$6 =
  28315. /*@__PURE__*/
  28316. new Vector3();
  28317. const _v2$3 =
  28318. /*@__PURE__*/
  28319. new Vector3();
  28320. const _v3$1 =
  28321. /*@__PURE__*/
  28322. new Vector3();
  28323. class DirectionalLightHelper extends Object3D {
  28324. constructor(light, size, color) {
  28325. super();
  28326. this.light = light;
  28327. this.light.updateMatrixWorld();
  28328. this.matrix = light.matrixWorld;
  28329. this.matrixAutoUpdate = false;
  28330. this.color = color;
  28331. if (size === undefined) size = 1;
  28332. let geometry = new BufferGeometry();
  28333. geometry.setAttribute('position', new Float32BufferAttribute([-size, size, 0, size, size, 0, size, -size, 0, -size, -size, 0, -size, size, 0], 3));
  28334. const material = new LineBasicMaterial({
  28335. fog: false,
  28336. toneMapped: false
  28337. });
  28338. this.lightPlane = new Line(geometry, material);
  28339. this.add(this.lightPlane);
  28340. geometry = new BufferGeometry();
  28341. geometry.setAttribute('position', new Float32BufferAttribute([0, 0, 0, 0, 0, 1], 3));
  28342. this.targetLine = new Line(geometry, material);
  28343. this.add(this.targetLine);
  28344. this.update();
  28345. }
  28346. dispose() {
  28347. this.lightPlane.geometry.dispose();
  28348. this.lightPlane.material.dispose();
  28349. this.targetLine.geometry.dispose();
  28350. this.targetLine.material.dispose();
  28351. }
  28352. update() {
  28353. _v1$6.setFromMatrixPosition(this.light.matrixWorld);
  28354. _v2$3.setFromMatrixPosition(this.light.target.matrixWorld);
  28355. _v3$1.subVectors(_v2$3, _v1$6);
  28356. this.lightPlane.lookAt(_v2$3);
  28357. if (this.color !== undefined) {
  28358. this.lightPlane.material.color.set(this.color);
  28359. this.targetLine.material.color.set(this.color);
  28360. } else {
  28361. this.lightPlane.material.color.copy(this.light.color);
  28362. this.targetLine.material.color.copy(this.light.color);
  28363. }
  28364. this.targetLine.lookAt(_v2$3);
  28365. this.targetLine.scale.z = _v3$1.length();
  28366. }
  28367. }
  28368. exports.DirectionalLightHelper = DirectionalLightHelper;
  28369. const _vector$b =
  28370. /*@__PURE__*/
  28371. new Vector3();
  28372. const _camera =
  28373. /*@__PURE__*/
  28374. new Camera();
  28375. /**
  28376. * - shows frustum, line of sight and up of the camera
  28377. * - suitable for fast updates
  28378. * - based on frustum visualization in lightgl.js shadowmap example
  28379. * http://evanw.github.com/lightgl.js/tests/shadowmap.html
  28380. */
  28381. class CameraHelper extends LineSegments {
  28382. constructor(camera) {
  28383. const geometry = new BufferGeometry();
  28384. const material = new LineBasicMaterial({
  28385. color: 0xffffff,
  28386. vertexColors: true,
  28387. toneMapped: false
  28388. });
  28389. const vertices = [];
  28390. const colors = [];
  28391. const pointMap = {}; // colors
  28392. const colorFrustum = new Color(0xffaa00);
  28393. const colorCone = new Color(0xff0000);
  28394. const colorUp = new Color(0x00aaff);
  28395. const colorTarget = new Color(0xffffff);
  28396. const colorCross = new Color(0x333333); // near
  28397. addLine('n1', 'n2', colorFrustum);
  28398. addLine('n2', 'n4', colorFrustum);
  28399. addLine('n4', 'n3', colorFrustum);
  28400. addLine('n3', 'n1', colorFrustum); // far
  28401. addLine('f1', 'f2', colorFrustum);
  28402. addLine('f2', 'f4', colorFrustum);
  28403. addLine('f4', 'f3', colorFrustum);
  28404. addLine('f3', 'f1', colorFrustum); // sides
  28405. addLine('n1', 'f1', colorFrustum);
  28406. addLine('n2', 'f2', colorFrustum);
  28407. addLine('n3', 'f3', colorFrustum);
  28408. addLine('n4', 'f4', colorFrustum); // cone
  28409. addLine('p', 'n1', colorCone);
  28410. addLine('p', 'n2', colorCone);
  28411. addLine('p', 'n3', colorCone);
  28412. addLine('p', 'n4', colorCone); // up
  28413. addLine('u1', 'u2', colorUp);
  28414. addLine('u2', 'u3', colorUp);
  28415. addLine('u3', 'u1', colorUp); // target
  28416. addLine('c', 't', colorTarget);
  28417. addLine('p', 'c', colorCross); // cross
  28418. addLine('cn1', 'cn2', colorCross);
  28419. addLine('cn3', 'cn4', colorCross);
  28420. addLine('cf1', 'cf2', colorCross);
  28421. addLine('cf3', 'cf4', colorCross);
  28422. function addLine(a, b, color) {
  28423. addPoint(a, color);
  28424. addPoint(b, color);
  28425. }
  28426. function addPoint(id, color) {
  28427. vertices.push(0, 0, 0);
  28428. colors.push(color.r, color.g, color.b);
  28429. if (pointMap[id] === undefined) {
  28430. pointMap[id] = [];
  28431. }
  28432. pointMap[id].push(vertices.length / 3 - 1);
  28433. }
  28434. geometry.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  28435. geometry.setAttribute('color', new Float32BufferAttribute(colors, 3));
  28436. super(geometry, material);
  28437. this.type = 'CameraHelper';
  28438. this.camera = camera;
  28439. if (this.camera.updateProjectionMatrix) this.camera.updateProjectionMatrix();
  28440. this.matrix = camera.matrixWorld;
  28441. this.matrixAutoUpdate = false;
  28442. this.pointMap = pointMap;
  28443. this.update();
  28444. }
  28445. update() {
  28446. const geometry = this.geometry;
  28447. const pointMap = this.pointMap;
  28448. const w = 1,
  28449. h = 1; // we need just camera projection matrix inverse
  28450. // world matrix must be identity
  28451. _camera.projectionMatrixInverse.copy(this.camera.projectionMatrixInverse); // center / target
  28452. setPoint('c', pointMap, geometry, _camera, 0, 0, -1);
  28453. setPoint('t', pointMap, geometry, _camera, 0, 0, 1); // near
  28454. setPoint('n1', pointMap, geometry, _camera, -w, -h, -1);
  28455. setPoint('n2', pointMap, geometry, _camera, w, -h, -1);
  28456. setPoint('n3', pointMap, geometry, _camera, -w, h, -1);
  28457. setPoint('n4', pointMap, geometry, _camera, w, h, -1); // far
  28458. setPoint('f1', pointMap, geometry, _camera, -w, -h, 1);
  28459. setPoint('f2', pointMap, geometry, _camera, w, -h, 1);
  28460. setPoint('f3', pointMap, geometry, _camera, -w, h, 1);
  28461. setPoint('f4', pointMap, geometry, _camera, w, h, 1); // up
  28462. setPoint('u1', pointMap, geometry, _camera, w * 0.7, h * 1.1, -1);
  28463. setPoint('u2', pointMap, geometry, _camera, -w * 0.7, h * 1.1, -1);
  28464. setPoint('u3', pointMap, geometry, _camera, 0, h * 2, -1); // cross
  28465. setPoint('cf1', pointMap, geometry, _camera, -w, 0, 1);
  28466. setPoint('cf2', pointMap, geometry, _camera, w, 0, 1);
  28467. setPoint('cf3', pointMap, geometry, _camera, 0, -h, 1);
  28468. setPoint('cf4', pointMap, geometry, _camera, 0, h, 1);
  28469. setPoint('cn1', pointMap, geometry, _camera, -w, 0, -1);
  28470. setPoint('cn2', pointMap, geometry, _camera, w, 0, -1);
  28471. setPoint('cn3', pointMap, geometry, _camera, 0, -h, -1);
  28472. setPoint('cn4', pointMap, geometry, _camera, 0, h, -1);
  28473. geometry.getAttribute('position').needsUpdate = true;
  28474. }
  28475. }
  28476. exports.CameraHelper = CameraHelper;
  28477. function setPoint(point, pointMap, geometry, camera, x, y, z) {
  28478. _vector$b.set(x, y, z).unproject(camera);
  28479. const points = pointMap[point];
  28480. if (points !== undefined) {
  28481. const position = geometry.getAttribute('position');
  28482. for (let i = 0, l = points.length; i < l; i++) {
  28483. position.setXYZ(points[i], _vector$b.x, _vector$b.y, _vector$b.z);
  28484. }
  28485. }
  28486. }
  28487. const _box$3 =
  28488. /*@__PURE__*/
  28489. new Box3();
  28490. class BoxHelper extends LineSegments {
  28491. constructor(object, color = 0xffff00) {
  28492. const indices = new Uint16Array([0, 1, 1, 2, 2, 3, 3, 0, 4, 5, 5, 6, 6, 7, 7, 4, 0, 4, 1, 5, 2, 6, 3, 7]);
  28493. const positions = new Float32Array(8 * 3);
  28494. const geometry = new BufferGeometry();
  28495. geometry.setIndex(new BufferAttribute(indices, 1));
  28496. geometry.setAttribute('position', new BufferAttribute(positions, 3));
  28497. super(geometry, new LineBasicMaterial({
  28498. color: color,
  28499. toneMapped: false
  28500. }));
  28501. this.object = object;
  28502. this.type = 'BoxHelper';
  28503. this.matrixAutoUpdate = false;
  28504. this.update();
  28505. }
  28506. update(object) {
  28507. if (object !== undefined) {
  28508. console.warn('THREE.BoxHelper: .update() has no longer arguments.');
  28509. }
  28510. if (this.object !== undefined) {
  28511. _box$3.setFromObject(this.object);
  28512. }
  28513. if (_box$3.isEmpty()) return;
  28514. const min = _box$3.min;
  28515. const max = _box$3.max;
  28516. /*
  28517. 5____4
  28518. 1/___0/|
  28519. | 6__|_7
  28520. 2/___3/
  28521. 0: max.x, max.y, max.z
  28522. 1: min.x, max.y, max.z
  28523. 2: min.x, min.y, max.z
  28524. 3: max.x, min.y, max.z
  28525. 4: max.x, max.y, min.z
  28526. 5: min.x, max.y, min.z
  28527. 6: min.x, min.y, min.z
  28528. 7: max.x, min.y, min.z
  28529. */
  28530. const position = this.geometry.attributes.position;
  28531. const array = position.array;
  28532. array[0] = max.x;
  28533. array[1] = max.y;
  28534. array[2] = max.z;
  28535. array[3] = min.x;
  28536. array[4] = max.y;
  28537. array[5] = max.z;
  28538. array[6] = min.x;
  28539. array[7] = min.y;
  28540. array[8] = max.z;
  28541. array[9] = max.x;
  28542. array[10] = min.y;
  28543. array[11] = max.z;
  28544. array[12] = max.x;
  28545. array[13] = max.y;
  28546. array[14] = min.z;
  28547. array[15] = min.x;
  28548. array[16] = max.y;
  28549. array[17] = min.z;
  28550. array[18] = min.x;
  28551. array[19] = min.y;
  28552. array[20] = min.z;
  28553. array[21] = max.x;
  28554. array[22] = min.y;
  28555. array[23] = min.z;
  28556. position.needsUpdate = true;
  28557. this.geometry.computeBoundingSphere();
  28558. }
  28559. setFromObject(object) {
  28560. this.object = object;
  28561. this.update();
  28562. return this;
  28563. }
  28564. copy(source) {
  28565. LineSegments.prototype.copy.call(this, source);
  28566. this.object = source.object;
  28567. return this;
  28568. }
  28569. }
  28570. exports.BoxHelper = BoxHelper;
  28571. class Box3Helper extends LineSegments {
  28572. constructor(box, color = 0xffff00) {
  28573. const indices = new Uint16Array([0, 1, 1, 2, 2, 3, 3, 0, 4, 5, 5, 6, 6, 7, 7, 4, 0, 4, 1, 5, 2, 6, 3, 7]);
  28574. const positions = [1, 1, 1, -1, 1, 1, -1, -1, 1, 1, -1, 1, 1, 1, -1, -1, 1, -1, -1, -1, -1, 1, -1, -1];
  28575. const geometry = new BufferGeometry();
  28576. geometry.setIndex(new BufferAttribute(indices, 1));
  28577. geometry.setAttribute('position', new Float32BufferAttribute(positions, 3));
  28578. super(geometry, new LineBasicMaterial({
  28579. color: color,
  28580. toneMapped: false
  28581. }));
  28582. this.box = box;
  28583. this.type = 'Box3Helper';
  28584. this.geometry.computeBoundingSphere();
  28585. }
  28586. updateMatrixWorld(force) {
  28587. const box = this.box;
  28588. if (box.isEmpty()) return;
  28589. box.getCenter(this.position);
  28590. box.getSize(this.scale);
  28591. this.scale.multiplyScalar(0.5);
  28592. super.updateMatrixWorld(force);
  28593. }
  28594. }
  28595. exports.Box3Helper = Box3Helper;
  28596. class PlaneHelper extends Line {
  28597. constructor(plane, size = 1, hex = 0xffff00) {
  28598. const color = hex;
  28599. const positions = [1, -1, 1, -1, 1, 1, -1, -1, 1, 1, 1, 1, -1, 1, 1, -1, -1, 1, 1, -1, 1, 1, 1, 1, 0, 0, 1, 0, 0, 0];
  28600. const geometry = new BufferGeometry();
  28601. geometry.setAttribute('position', new Float32BufferAttribute(positions, 3));
  28602. geometry.computeBoundingSphere();
  28603. super(geometry, new LineBasicMaterial({
  28604. color: color,
  28605. toneMapped: false
  28606. }));
  28607. this.type = 'PlaneHelper';
  28608. this.plane = plane;
  28609. this.size = size;
  28610. const positions2 = [1, 1, 1, -1, 1, 1, -1, -1, 1, 1, 1, 1, -1, -1, 1, 1, -1, 1];
  28611. const geometry2 = new BufferGeometry();
  28612. geometry2.setAttribute('position', new Float32BufferAttribute(positions2, 3));
  28613. geometry2.computeBoundingSphere();
  28614. this.add(new Mesh(geometry2, new MeshBasicMaterial({
  28615. color: color,
  28616. opacity: 0.2,
  28617. transparent: true,
  28618. depthWrite: false,
  28619. toneMapped: false
  28620. })));
  28621. }
  28622. updateMatrixWorld(force) {
  28623. let scale = -this.plane.constant;
  28624. if (Math.abs(scale) < 1e-8) scale = 1e-8; // sign does not matter
  28625. this.scale.set(0.5 * this.size, 0.5 * this.size, scale);
  28626. this.children[0].material.side = scale < 0 ? BackSide : FrontSide; // renderer flips side when determinant < 0; flipping not wanted here
  28627. this.lookAt(this.plane.normal);
  28628. super.updateMatrixWorld(force);
  28629. }
  28630. }
  28631. exports.PlaneHelper = PlaneHelper;
  28632. const _axis =
  28633. /*@__PURE__*/
  28634. new Vector3();
  28635. let _lineGeometry, _coneGeometry;
  28636. class ArrowHelper extends Object3D {
  28637. constructor(dir, origin, length, color, headLength, headWidth) {
  28638. super(); // dir is assumed to be normalized
  28639. this.type = 'ArrowHelper';
  28640. if (dir === undefined) dir = new Vector3(0, 0, 1);
  28641. if (origin === undefined) origin = new Vector3(0, 0, 0);
  28642. if (length === undefined) length = 1;
  28643. if (color === undefined) color = 0xffff00;
  28644. if (headLength === undefined) headLength = 0.2 * length;
  28645. if (headWidth === undefined) headWidth = 0.2 * headLength;
  28646. if (_lineGeometry === undefined) {
  28647. _lineGeometry = new BufferGeometry();
  28648. _lineGeometry.setAttribute('position', new Float32BufferAttribute([0, 0, 0, 0, 1, 0], 3));
  28649. _coneGeometry = new CylinderBufferGeometry(0, 0.5, 1, 5, 1);
  28650. _coneGeometry.translate(0, -0.5, 0);
  28651. }
  28652. this.position.copy(origin);
  28653. this.line = new Line(_lineGeometry, new LineBasicMaterial({
  28654. color: color,
  28655. toneMapped: false
  28656. }));
  28657. this.line.matrixAutoUpdate = false;
  28658. this.add(this.line);
  28659. this.cone = new Mesh(_coneGeometry, new MeshBasicMaterial({
  28660. color: color,
  28661. toneMapped: false
  28662. }));
  28663. this.cone.matrixAutoUpdate = false;
  28664. this.add(this.cone);
  28665. this.setDirection(dir);
  28666. this.setLength(length, headLength, headWidth);
  28667. }
  28668. setDirection(dir) {
  28669. // dir is assumed to be normalized
  28670. if (dir.y > 0.99999) {
  28671. this.quaternion.set(0, 0, 0, 1);
  28672. } else if (dir.y < -0.99999) {
  28673. this.quaternion.set(1, 0, 0, 0);
  28674. } else {
  28675. _axis.set(dir.z, 0, -dir.x).normalize();
  28676. const radians = Math.acos(dir.y);
  28677. this.quaternion.setFromAxisAngle(_axis, radians);
  28678. }
  28679. }
  28680. setLength(length, headLength, headWidth) {
  28681. if (headLength === undefined) headLength = 0.2 * length;
  28682. if (headWidth === undefined) headWidth = 0.2 * headLength;
  28683. this.line.scale.set(1, Math.max(0.0001, length - headLength), 1); // see #17458
  28684. this.line.updateMatrix();
  28685. this.cone.scale.set(headWidth, headLength, headWidth);
  28686. this.cone.position.y = length;
  28687. this.cone.updateMatrix();
  28688. }
  28689. setColor(color) {
  28690. this.line.material.color.set(color);
  28691. this.cone.material.color.set(color);
  28692. }
  28693. copy(source) {
  28694. super.copy(source, false);
  28695. this.line.copy(source.line);
  28696. this.cone.copy(source.cone);
  28697. return this;
  28698. }
  28699. }
  28700. exports.ArrowHelper = ArrowHelper;
  28701. class AxesHelper extends LineSegments {
  28702. constructor(size = 1) {
  28703. const vertices = [0, 0, 0, size, 0, 0, 0, 0, 0, 0, size, 0, 0, 0, 0, 0, 0, size];
  28704. const colors = [1, 0, 0, 1, 0.6, 0, 0, 1, 0, 0.6, 1, 0, 0, 0, 1, 0, 0.6, 1];
  28705. const geometry = new BufferGeometry();
  28706. geometry.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  28707. geometry.setAttribute('color', new Float32BufferAttribute(colors, 3));
  28708. const material = new LineBasicMaterial({
  28709. vertexColors: true,
  28710. toneMapped: false
  28711. });
  28712. super(geometry, material);
  28713. this.type = 'AxesHelper';
  28714. }
  28715. }
  28716. exports.AxesHelper = AxesHelper;
  28717. const _floatView = new Float32Array(1);
  28718. const _int32View = new Int32Array(_floatView.buffer);
  28719. const DataUtils = {
  28720. // Converts float32 to float16 (stored as uint16 value).
  28721. toHalfFloat: function (val) {
  28722. // Source: http://gamedev.stackexchange.com/questions/17326/conversion-of-a-number-from-single-precision-floating-point-representation-to-a/17410#17410
  28723. /* This method is faster than the OpenEXR implementation (very often
  28724. * used, eg. in Ogre), with the additional benefit of rounding, inspired
  28725. * by James Tursa?s half-precision code. */
  28726. _floatView[0] = val;
  28727. const x = _int32View[0];
  28728. let bits = x >> 16 & 0x8000;
  28729. /* Get the sign */
  28730. let m = x >> 12 & 0x07ff;
  28731. /* Keep one extra bit for rounding */
  28732. const e = x >> 23 & 0xff;
  28733. /* Using int is faster here */
  28734. /* If zero, or denormal, or exponent underflows too much for a denormal
  28735. * half, return signed zero. */
  28736. if (e < 103) return bits;
  28737. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  28738. if (e > 142) {
  28739. bits |= 0x7c00;
  28740. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  28741. * not Inf, so make sure we set one mantissa bit too. */
  28742. bits |= (e == 255 ? 0 : 1) && x & 0x007fffff;
  28743. return bits;
  28744. }
  28745. /* If exponent underflows but not too much, return a denormal */
  28746. if (e < 113) {
  28747. m |= 0x0800;
  28748. /* Extra rounding may overflow and set mantissa to 0 and exponent
  28749. * to 1, which is OK. */
  28750. bits |= (m >> 114 - e) + (m >> 113 - e & 1);
  28751. return bits;
  28752. }
  28753. bits |= e - 112 << 10 | m >> 1;
  28754. /* Extra rounding. An overflow will set mantissa to 0 and increment
  28755. * the exponent, which is OK. */
  28756. bits += m & 1;
  28757. return bits;
  28758. }
  28759. };
  28760. exports.DataUtils = DataUtils;
  28761. const LOD_MIN = 4;
  28762. const LOD_MAX = 8;
  28763. const SIZE_MAX = Math.pow(2, LOD_MAX); // The standard deviations (radians) associated with the extra mips. These are
  28764. // chosen to approximate a Trowbridge-Reitz distribution function times the
  28765. // geometric shadowing function. These sigma values squared must match the
  28766. // variance #defines in cube_uv_reflection_fragment.glsl.js.
  28767. const EXTRA_LOD_SIGMA = [0.125, 0.215, 0.35, 0.446, 0.526, 0.582];
  28768. const TOTAL_LODS = LOD_MAX - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length; // The maximum length of the blur for loop. Smaller sigmas will use fewer
  28769. // samples and exit early, but not recompile the shader.
  28770. const MAX_SAMPLES = 20;
  28771. const ENCODINGS = {
  28772. [LinearEncoding]: 0,
  28773. [sRGBEncoding]: 1,
  28774. [RGBEEncoding]: 2,
  28775. [RGBM7Encoding]: 3,
  28776. [RGBM16Encoding]: 4,
  28777. [RGBDEncoding]: 5,
  28778. [GammaEncoding]: 6
  28779. };
  28780. const _flatCamera =
  28781. /*@__PURE__*/
  28782. new OrthographicCamera();
  28783. const {
  28784. _lodPlanes,
  28785. _sizeLods,
  28786. _sigmas
  28787. } =
  28788. /*@__PURE__*/
  28789. _createPlanes();
  28790. let _oldTarget = null; // Golden Ratio
  28791. const PHI = (1 + Math.sqrt(5)) / 2;
  28792. const INV_PHI = 1 / PHI; // Vertices of a dodecahedron (except the opposites, which represent the
  28793. // same axis), used as axis directions evenly spread on a sphere.
  28794. const _axisDirections = [
  28795. /*@__PURE__*/
  28796. new Vector3(1, 1, 1),
  28797. /*@__PURE__*/
  28798. new Vector3(-1, 1, 1),
  28799. /*@__PURE__*/
  28800. new Vector3(1, 1, -1),
  28801. /*@__PURE__*/
  28802. new Vector3(-1, 1, -1),
  28803. /*@__PURE__*/
  28804. new Vector3(0, PHI, INV_PHI),
  28805. /*@__PURE__*/
  28806. new Vector3(0, PHI, -INV_PHI),
  28807. /*@__PURE__*/
  28808. new Vector3(INV_PHI, 0, PHI),
  28809. /*@__PURE__*/
  28810. new Vector3(-INV_PHI, 0, PHI),
  28811. /*@__PURE__*/
  28812. new Vector3(PHI, INV_PHI, 0),
  28813. /*@__PURE__*/
  28814. new Vector3(-PHI, INV_PHI, 0)];
  28815. /**
  28816. * This class generates a Prefiltered, Mipmapped Radiance Environment Map
  28817. * (PMREM) from a cubeMap environment texture. This allows different levels of
  28818. * blur to be quickly accessed based on material roughness. It is packed into a
  28819. * special CubeUV format that allows us to perform custom interpolation so that
  28820. * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap
  28821. * chain, it only goes down to the LOD_MIN level (above), and then creates extra
  28822. * even more filtered 'mips' at the same LOD_MIN resolution, associated with
  28823. * higher roughness levels. In this way we maintain resolution to smoothly
  28824. * interpolate diffuse lighting while limiting sampling computation.
  28825. */
  28826. class PMREMGenerator {
  28827. constructor(renderer) {
  28828. this._renderer = renderer;
  28829. this._pingPongRenderTarget = null;
  28830. this._blurMaterial = _getBlurShader(MAX_SAMPLES);
  28831. this._equirectShader = null;
  28832. this._cubemapShader = null;
  28833. this._compileMaterial(this._blurMaterial);
  28834. }
  28835. /**
  28836. * Generates a PMREM from a supplied Scene, which can be faster than using an
  28837. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  28838. * in radians to be applied to the scene before PMREM generation. Optional near
  28839. * and far planes ensure the scene is rendered in its entirety (the cubeCamera
  28840. * is placed at the origin).
  28841. */
  28842. fromScene(scene, sigma = 0, near = 0.1, far = 100) {
  28843. _oldTarget = this._renderer.getRenderTarget();
  28844. const cubeUVRenderTarget = this._allocateTargets();
  28845. this._sceneToCubeUV(scene, near, far, cubeUVRenderTarget);
  28846. if (sigma > 0) {
  28847. this._blur(cubeUVRenderTarget, 0, 0, sigma);
  28848. }
  28849. this._applyPMREM(cubeUVRenderTarget);
  28850. this._cleanup(cubeUVRenderTarget);
  28851. return cubeUVRenderTarget;
  28852. }
  28853. /**
  28854. * Generates a PMREM from an equirectangular texture, which can be either LDR
  28855. * (RGBFormat) or HDR (RGBEFormat). The ideal input image size is 1k (1024 x 512),
  28856. * as this matches best with the 256 x 256 cubemap output.
  28857. */
  28858. fromEquirectangular(equirectangular) {
  28859. return this._fromTexture(equirectangular);
  28860. }
  28861. /**
  28862. * Generates a PMREM from an cubemap texture, which can be either LDR
  28863. * (RGBFormat) or HDR (RGBEFormat). The ideal input cube size is 256 x 256,
  28864. * as this matches best with the 256 x 256 cubemap output.
  28865. */
  28866. fromCubemap(cubemap) {
  28867. return this._fromTexture(cubemap);
  28868. }
  28869. /**
  28870. * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during
  28871. * your texture's network fetch for increased concurrency.
  28872. */
  28873. compileCubemapShader() {
  28874. if (this._cubemapShader === null) {
  28875. this._cubemapShader = _getCubemapShader();
  28876. this._compileMaterial(this._cubemapShader);
  28877. }
  28878. }
  28879. /**
  28880. * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during
  28881. * your texture's network fetch for increased concurrency.
  28882. */
  28883. compileEquirectangularShader() {
  28884. if (this._equirectShader === null) {
  28885. this._equirectShader = _getEquirectShader();
  28886. this._compileMaterial(this._equirectShader);
  28887. }
  28888. }
  28889. /**
  28890. * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class,
  28891. * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on
  28892. * one of them will cause any others to also become unusable.
  28893. */
  28894. dispose() {
  28895. this._blurMaterial.dispose();
  28896. if (this._cubemapShader !== null) this._cubemapShader.dispose();
  28897. if (this._equirectShader !== null) this._equirectShader.dispose();
  28898. for (let i = 0; i < _lodPlanes.length; i++) {
  28899. _lodPlanes[i].dispose();
  28900. }
  28901. } // private interface
  28902. _cleanup(outputTarget) {
  28903. this._pingPongRenderTarget.dispose();
  28904. this._renderer.setRenderTarget(_oldTarget);
  28905. outputTarget.scissorTest = false;
  28906. _setViewport(outputTarget, 0, 0, outputTarget.width, outputTarget.height);
  28907. }
  28908. _fromTexture(texture) {
  28909. _oldTarget = this._renderer.getRenderTarget();
  28910. const cubeUVRenderTarget = this._allocateTargets(texture);
  28911. this._textureToCubeUV(texture, cubeUVRenderTarget);
  28912. this._applyPMREM(cubeUVRenderTarget);
  28913. this._cleanup(cubeUVRenderTarget);
  28914. return cubeUVRenderTarget;
  28915. }
  28916. _allocateTargets(texture) {
  28917. // warning: null texture is valid
  28918. const params = {
  28919. magFilter: NearestFilter,
  28920. minFilter: NearestFilter,
  28921. generateMipmaps: false,
  28922. type: UnsignedByteType,
  28923. format: RGBEFormat,
  28924. encoding: _isLDR(texture) ? texture.encoding : RGBEEncoding,
  28925. depthBuffer: false
  28926. };
  28927. const cubeUVRenderTarget = _createRenderTarget(params);
  28928. cubeUVRenderTarget.depthBuffer = texture ? false : true;
  28929. this._pingPongRenderTarget = _createRenderTarget(params);
  28930. return cubeUVRenderTarget;
  28931. }
  28932. _compileMaterial(material) {
  28933. const tmpMesh = new Mesh(_lodPlanes[0], material);
  28934. this._renderer.compile(tmpMesh, _flatCamera);
  28935. }
  28936. _sceneToCubeUV(scene, near, far, cubeUVRenderTarget) {
  28937. const fov = 90;
  28938. const aspect = 1;
  28939. const cubeCamera = new PerspectiveCamera(fov, aspect, near, far);
  28940. const upSign = [1, -1, 1, 1, 1, 1];
  28941. const forwardSign = [1, 1, 1, -1, -1, -1];
  28942. const renderer = this._renderer;
  28943. const outputEncoding = renderer.outputEncoding;
  28944. const toneMapping = renderer.toneMapping;
  28945. const clearColor = renderer.getClearColor();
  28946. const clearAlpha = renderer.getClearAlpha();
  28947. renderer.toneMapping = NoToneMapping;
  28948. renderer.outputEncoding = LinearEncoding;
  28949. let background = scene.background;
  28950. if (background && background.isColor) {
  28951. background.convertSRGBToLinear(); // Convert linear to RGBE
  28952. const maxComponent = Math.max(background.r, background.g, background.b);
  28953. const fExp = Math.min(Math.max(Math.ceil(Math.log2(maxComponent)), -128.0), 127.0);
  28954. background = background.multiplyScalar(Math.pow(2.0, -fExp));
  28955. const alpha = (fExp + 128.0) / 255.0;
  28956. renderer.setClearColor(background, alpha);
  28957. scene.background = null;
  28958. }
  28959. for (let i = 0; i < 6; i++) {
  28960. const col = i % 3;
  28961. if (col == 0) {
  28962. cubeCamera.up.set(0, upSign[i], 0);
  28963. cubeCamera.lookAt(forwardSign[i], 0, 0);
  28964. } else if (col == 1) {
  28965. cubeCamera.up.set(0, 0, upSign[i]);
  28966. cubeCamera.lookAt(0, forwardSign[i], 0);
  28967. } else {
  28968. cubeCamera.up.set(0, upSign[i], 0);
  28969. cubeCamera.lookAt(0, 0, forwardSign[i]);
  28970. }
  28971. _setViewport(cubeUVRenderTarget, col * SIZE_MAX, i > 2 ? SIZE_MAX : 0, SIZE_MAX, SIZE_MAX);
  28972. renderer.setRenderTarget(cubeUVRenderTarget);
  28973. renderer.render(scene, cubeCamera);
  28974. }
  28975. renderer.toneMapping = toneMapping;
  28976. renderer.outputEncoding = outputEncoding;
  28977. renderer.setClearColor(clearColor, clearAlpha);
  28978. }
  28979. _textureToCubeUV(texture, cubeUVRenderTarget) {
  28980. const renderer = this._renderer;
  28981. if (texture.isCubeTexture) {
  28982. if (this._cubemapShader == null) {
  28983. this._cubemapShader = _getCubemapShader();
  28984. }
  28985. } else {
  28986. if (this._equirectShader == null) {
  28987. this._equirectShader = _getEquirectShader();
  28988. }
  28989. }
  28990. const material = texture.isCubeTexture ? this._cubemapShader : this._equirectShader;
  28991. const mesh = new Mesh(_lodPlanes[0], material);
  28992. const uniforms = material.uniforms;
  28993. uniforms['envMap'].value = texture;
  28994. if (!texture.isCubeTexture) {
  28995. uniforms['texelSize'].value.set(1.0 / texture.image.width, 1.0 / texture.image.height);
  28996. }
  28997. uniforms['inputEncoding'].value = ENCODINGS[texture.encoding];
  28998. uniforms['outputEncoding'].value = ENCODINGS[cubeUVRenderTarget.texture.encoding];
  28999. _setViewport(cubeUVRenderTarget, 0, 0, 3 * SIZE_MAX, 2 * SIZE_MAX);
  29000. renderer.setRenderTarget(cubeUVRenderTarget);
  29001. renderer.render(mesh, _flatCamera);
  29002. }
  29003. _applyPMREM(cubeUVRenderTarget) {
  29004. const renderer = this._renderer;
  29005. const autoClear = renderer.autoClear;
  29006. renderer.autoClear = false;
  29007. for (let i = 1; i < TOTAL_LODS; i++) {
  29008. const sigma = Math.sqrt(_sigmas[i] * _sigmas[i] - _sigmas[i - 1] * _sigmas[i - 1]);
  29009. const poleAxis = _axisDirections[(i - 1) % _axisDirections.length];
  29010. this._blur(cubeUVRenderTarget, i - 1, i, sigma, poleAxis);
  29011. }
  29012. renderer.autoClear = autoClear;
  29013. }
  29014. /**
  29015. * This is a two-pass Gaussian blur for a cubemap. Normally this is done
  29016. * vertically and horizontally, but this breaks down on a cube. Here we apply
  29017. * the blur latitudinally (around the poles), and then longitudinally (towards
  29018. * the poles) to approximate the orthogonally-separable blur. It is least
  29019. * accurate at the poles, but still does a decent job.
  29020. */
  29021. _blur(cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis) {
  29022. const pingPongRenderTarget = this._pingPongRenderTarget;
  29023. this._halfBlur(cubeUVRenderTarget, pingPongRenderTarget, lodIn, lodOut, sigma, 'latitudinal', poleAxis);
  29024. this._halfBlur(pingPongRenderTarget, cubeUVRenderTarget, lodOut, lodOut, sigma, 'longitudinal', poleAxis);
  29025. }
  29026. _halfBlur(targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis) {
  29027. const renderer = this._renderer;
  29028. const blurMaterial = this._blurMaterial;
  29029. if (direction !== 'latitudinal' && direction !== 'longitudinal') {
  29030. console.error('blur direction must be either latitudinal or longitudinal!');
  29031. } // Number of standard deviations at which to cut off the discrete approximation.
  29032. const STANDARD_DEVIATIONS = 3;
  29033. const blurMesh = new Mesh(_lodPlanes[lodOut], blurMaterial);
  29034. const blurUniforms = blurMaterial.uniforms;
  29035. const pixels = _sizeLods[lodIn] - 1;
  29036. const radiansPerPixel = isFinite(sigmaRadians) ? Math.PI / (2 * pixels) : 2 * Math.PI / (2 * MAX_SAMPLES - 1);
  29037. const sigmaPixels = sigmaRadians / radiansPerPixel;
  29038. const samples = isFinite(sigmaRadians) ? 1 + Math.floor(STANDARD_DEVIATIONS * sigmaPixels) : MAX_SAMPLES;
  29039. if (samples > MAX_SAMPLES) {
  29040. console.warn(`sigmaRadians, ${sigmaRadians}, is too large and will clip, as it requested ${samples} samples when the maximum is set to ${MAX_SAMPLES}`);
  29041. }
  29042. const weights = [];
  29043. let sum = 0;
  29044. for (let i = 0; i < MAX_SAMPLES; ++i) {
  29045. const x = i / sigmaPixels;
  29046. const weight = Math.exp(-x * x / 2);
  29047. weights.push(weight);
  29048. if (i == 0) {
  29049. sum += weight;
  29050. } else if (i < samples) {
  29051. sum += 2 * weight;
  29052. }
  29053. }
  29054. for (let i = 0; i < weights.length; i++) {
  29055. weights[i] = weights[i] / sum;
  29056. }
  29057. blurUniforms['envMap'].value = targetIn.texture;
  29058. blurUniforms['samples'].value = samples;
  29059. blurUniforms['weights'].value = weights;
  29060. blurUniforms['latitudinal'].value = direction === 'latitudinal';
  29061. if (poleAxis) {
  29062. blurUniforms['poleAxis'].value = poleAxis;
  29063. }
  29064. blurUniforms['dTheta'].value = radiansPerPixel;
  29065. blurUniforms['mipInt'].value = LOD_MAX - lodIn;
  29066. blurUniforms['inputEncoding'].value = ENCODINGS[targetIn.texture.encoding];
  29067. blurUniforms['outputEncoding'].value = ENCODINGS[targetIn.texture.encoding];
  29068. const outputSize = _sizeLods[lodOut];
  29069. const x = 3 * Math.max(0, SIZE_MAX - 2 * outputSize);
  29070. const y = (lodOut === 0 ? 0 : 2 * SIZE_MAX) + 2 * outputSize * (lodOut > LOD_MAX - LOD_MIN ? lodOut - LOD_MAX + LOD_MIN : 0);
  29071. _setViewport(targetOut, x, y, 3 * outputSize, 2 * outputSize);
  29072. renderer.setRenderTarget(targetOut);
  29073. renderer.render(blurMesh, _flatCamera);
  29074. }
  29075. }
  29076. exports.PMREMGenerator = PMREMGenerator;
  29077. function _isLDR(texture) {
  29078. if (texture === undefined || texture.type !== UnsignedByteType) return false;
  29079. return texture.encoding === LinearEncoding || texture.encoding === sRGBEncoding || texture.encoding === GammaEncoding;
  29080. }
  29081. function _createPlanes() {
  29082. const _lodPlanes = [];
  29083. const _sizeLods = [];
  29084. const _sigmas = [];
  29085. let lod = LOD_MAX;
  29086. for (let i = 0; i < TOTAL_LODS; i++) {
  29087. const sizeLod = Math.pow(2, lod);
  29088. _sizeLods.push(sizeLod);
  29089. let sigma = 1.0 / sizeLod;
  29090. if (i > LOD_MAX - LOD_MIN) {
  29091. sigma = EXTRA_LOD_SIGMA[i - LOD_MAX + LOD_MIN - 1];
  29092. } else if (i == 0) {
  29093. sigma = 0;
  29094. }
  29095. _sigmas.push(sigma);
  29096. const texelSize = 1.0 / (sizeLod - 1);
  29097. const min = -texelSize / 2;
  29098. const max = 1 + texelSize / 2;
  29099. const uv1 = [min, min, max, min, max, max, min, min, max, max, min, max];
  29100. const cubeFaces = 6;
  29101. const vertices = 6;
  29102. const positionSize = 3;
  29103. const uvSize = 2;
  29104. const faceIndexSize = 1;
  29105. const position = new Float32Array(positionSize * vertices * cubeFaces);
  29106. const uv = new Float32Array(uvSize * vertices * cubeFaces);
  29107. const faceIndex = new Float32Array(faceIndexSize * vertices * cubeFaces);
  29108. for (let face = 0; face < cubeFaces; face++) {
  29109. const x = face % 3 * 2 / 3 - 1;
  29110. const y = face > 2 ? 0 : -1;
  29111. const coordinates = [x, y, 0, x + 2 / 3, y, 0, x + 2 / 3, y + 1, 0, x, y, 0, x + 2 / 3, y + 1, 0, x, y + 1, 0];
  29112. position.set(coordinates, positionSize * vertices * face);
  29113. uv.set(uv1, uvSize * vertices * face);
  29114. const fill = [face, face, face, face, face, face];
  29115. faceIndex.set(fill, faceIndexSize * vertices * face);
  29116. }
  29117. const planes = new BufferGeometry();
  29118. planes.setAttribute('position', new BufferAttribute(position, positionSize));
  29119. planes.setAttribute('uv', new BufferAttribute(uv, uvSize));
  29120. planes.setAttribute('faceIndex', new BufferAttribute(faceIndex, faceIndexSize));
  29121. _lodPlanes.push(planes);
  29122. if (lod > LOD_MIN) {
  29123. lod--;
  29124. }
  29125. }
  29126. return {
  29127. _lodPlanes,
  29128. _sizeLods,
  29129. _sigmas
  29130. };
  29131. }
  29132. function _createRenderTarget(params) {
  29133. const cubeUVRenderTarget = new WebGLRenderTarget(3 * SIZE_MAX, 3 * SIZE_MAX, params);
  29134. cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping;
  29135. cubeUVRenderTarget.texture.name = 'PMREM.cubeUv';
  29136. cubeUVRenderTarget.scissorTest = true;
  29137. return cubeUVRenderTarget;
  29138. }
  29139. function _setViewport(target, x, y, width, height) {
  29140. target.viewport.set(x, y, width, height);
  29141. target.scissor.set(x, y, width, height);
  29142. }
  29143. function _getBlurShader(maxSamples) {
  29144. const weights = new Float32Array(maxSamples);
  29145. const poleAxis = new Vector3(0, 1, 0);
  29146. const shaderMaterial = new RawShaderMaterial({
  29147. name: 'SphericalGaussianBlur',
  29148. defines: {
  29149. 'n': maxSamples
  29150. },
  29151. uniforms: {
  29152. 'envMap': {
  29153. value: null
  29154. },
  29155. 'samples': {
  29156. value: 1
  29157. },
  29158. 'weights': {
  29159. value: weights
  29160. },
  29161. 'latitudinal': {
  29162. value: false
  29163. },
  29164. 'dTheta': {
  29165. value: 0
  29166. },
  29167. 'mipInt': {
  29168. value: 0
  29169. },
  29170. 'poleAxis': {
  29171. value: poleAxis
  29172. },
  29173. 'inputEncoding': {
  29174. value: ENCODINGS[LinearEncoding]
  29175. },
  29176. 'outputEncoding': {
  29177. value: ENCODINGS[LinearEncoding]
  29178. }
  29179. },
  29180. vertexShader: _getCommonVertexShader(),
  29181. fragmentShader:
  29182. /* glsl */
  29183. `
  29184. precision mediump float;
  29185. precision mediump int;
  29186. varying vec3 vOutputDirection;
  29187. uniform sampler2D envMap;
  29188. uniform int samples;
  29189. uniform float weights[ n ];
  29190. uniform bool latitudinal;
  29191. uniform float dTheta;
  29192. uniform float mipInt;
  29193. uniform vec3 poleAxis;
  29194. ${_getEncodings()}
  29195. #define ENVMAP_TYPE_CUBE_UV
  29196. #include <cube_uv_reflection_fragment>
  29197. vec3 getSample( float theta, vec3 axis ) {
  29198. float cosTheta = cos( theta );
  29199. // Rodrigues' axis-angle rotation
  29200. vec3 sampleDirection = vOutputDirection * cosTheta
  29201. + cross( axis, vOutputDirection ) * sin( theta )
  29202. + axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta );
  29203. return bilinearCubeUV( envMap, sampleDirection, mipInt );
  29204. }
  29205. void main() {
  29206. vec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection );
  29207. if ( all( equal( axis, vec3( 0.0 ) ) ) ) {
  29208. axis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x );
  29209. }
  29210. axis = normalize( axis );
  29211. gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );
  29212. gl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis );
  29213. for ( int i = 1; i < n; i++ ) {
  29214. if ( i >= samples ) {
  29215. break;
  29216. }
  29217. float theta = dTheta * float( i );
  29218. gl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis );
  29219. gl_FragColor.rgb += weights[ i ] * getSample( theta, axis );
  29220. }
  29221. gl_FragColor = linearToOutputTexel( gl_FragColor );
  29222. }
  29223. `,
  29224. blending: NoBlending,
  29225. depthTest: false,
  29226. depthWrite: false
  29227. });
  29228. return shaderMaterial;
  29229. }
  29230. function _getEquirectShader() {
  29231. const texelSize = new Vector2(1, 1);
  29232. const shaderMaterial = new RawShaderMaterial({
  29233. name: 'EquirectangularToCubeUV',
  29234. uniforms: {
  29235. 'envMap': {
  29236. value: null
  29237. },
  29238. 'texelSize': {
  29239. value: texelSize
  29240. },
  29241. 'inputEncoding': {
  29242. value: ENCODINGS[LinearEncoding]
  29243. },
  29244. 'outputEncoding': {
  29245. value: ENCODINGS[LinearEncoding]
  29246. }
  29247. },
  29248. vertexShader: _getCommonVertexShader(),
  29249. fragmentShader:
  29250. /* glsl */
  29251. `
  29252. precision mediump float;
  29253. precision mediump int;
  29254. varying vec3 vOutputDirection;
  29255. uniform sampler2D envMap;
  29256. uniform vec2 texelSize;
  29257. ${_getEncodings()}
  29258. #include <common>
  29259. void main() {
  29260. gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );
  29261. vec3 outputDirection = normalize( vOutputDirection );
  29262. vec2 uv = equirectUv( outputDirection );
  29263. vec2 f = fract( uv / texelSize - 0.5 );
  29264. uv -= f * texelSize;
  29265. vec3 tl = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb;
  29266. uv.x += texelSize.x;
  29267. vec3 tr = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb;
  29268. uv.y += texelSize.y;
  29269. vec3 br = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb;
  29270. uv.x -= texelSize.x;
  29271. vec3 bl = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb;
  29272. vec3 tm = mix( tl, tr, f.x );
  29273. vec3 bm = mix( bl, br, f.x );
  29274. gl_FragColor.rgb = mix( tm, bm, f.y );
  29275. gl_FragColor = linearToOutputTexel( gl_FragColor );
  29276. }
  29277. `,
  29278. blending: NoBlending,
  29279. depthTest: false,
  29280. depthWrite: false
  29281. });
  29282. return shaderMaterial;
  29283. }
  29284. function _getCubemapShader() {
  29285. const shaderMaterial = new RawShaderMaterial({
  29286. name: 'CubemapToCubeUV',
  29287. uniforms: {
  29288. 'envMap': {
  29289. value: null
  29290. },
  29291. 'inputEncoding': {
  29292. value: ENCODINGS[LinearEncoding]
  29293. },
  29294. 'outputEncoding': {
  29295. value: ENCODINGS[LinearEncoding]
  29296. }
  29297. },
  29298. vertexShader: _getCommonVertexShader(),
  29299. fragmentShader:
  29300. /* glsl */
  29301. `
  29302. precision mediump float;
  29303. precision mediump int;
  29304. varying vec3 vOutputDirection;
  29305. uniform samplerCube envMap;
  29306. ${_getEncodings()}
  29307. void main() {
  29308. gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );
  29309. gl_FragColor.rgb = envMapTexelToLinear( textureCube( envMap, vec3( - vOutputDirection.x, vOutputDirection.yz ) ) ).rgb;
  29310. gl_FragColor = linearToOutputTexel( gl_FragColor );
  29311. }
  29312. `,
  29313. blending: NoBlending,
  29314. depthTest: false,
  29315. depthWrite: false
  29316. });
  29317. return shaderMaterial;
  29318. }
  29319. function _getCommonVertexShader() {
  29320. return (
  29321. /* glsl */
  29322. `
  29323. precision mediump float;
  29324. precision mediump int;
  29325. attribute vec3 position;
  29326. attribute vec2 uv;
  29327. attribute float faceIndex;
  29328. varying vec3 vOutputDirection;
  29329. // RH coordinate system; PMREM face-indexing convention
  29330. vec3 getDirection( vec2 uv, float face ) {
  29331. uv = 2.0 * uv - 1.0;
  29332. vec3 direction = vec3( uv, 1.0 );
  29333. if ( face == 0.0 ) {
  29334. direction = direction.zyx; // ( 1, v, u ) pos x
  29335. } else if ( face == 1.0 ) {
  29336. direction = direction.xzy;
  29337. direction.xz *= -1.0; // ( -u, 1, -v ) pos y
  29338. } else if ( face == 2.0 ) {
  29339. direction.x *= -1.0; // ( -u, v, 1 ) pos z
  29340. } else if ( face == 3.0 ) {
  29341. direction = direction.zyx;
  29342. direction.xz *= -1.0; // ( -1, v, -u ) neg x
  29343. } else if ( face == 4.0 ) {
  29344. direction = direction.xzy;
  29345. direction.xy *= -1.0; // ( -u, -1, v ) neg y
  29346. } else if ( face == 5.0 ) {
  29347. direction.z *= -1.0; // ( u, v, -1 ) neg z
  29348. }
  29349. return direction;
  29350. }
  29351. void main() {
  29352. vOutputDirection = getDirection( uv, faceIndex );
  29353. gl_Position = vec4( position, 1.0 );
  29354. }
  29355. `
  29356. );
  29357. }
  29358. function _getEncodings() {
  29359. return (
  29360. /* glsl */
  29361. `
  29362. uniform int inputEncoding;
  29363. uniform int outputEncoding;
  29364. #include <encodings_pars_fragment>
  29365. vec4 inputTexelToLinear( vec4 value ) {
  29366. if ( inputEncoding == 0 ) {
  29367. return value;
  29368. } else if ( inputEncoding == 1 ) {
  29369. return sRGBToLinear( value );
  29370. } else if ( inputEncoding == 2 ) {
  29371. return RGBEToLinear( value );
  29372. } else if ( inputEncoding == 3 ) {
  29373. return RGBMToLinear( value, 7.0 );
  29374. } else if ( inputEncoding == 4 ) {
  29375. return RGBMToLinear( value, 16.0 );
  29376. } else if ( inputEncoding == 5 ) {
  29377. return RGBDToLinear( value, 256.0 );
  29378. } else {
  29379. return GammaToLinear( value, 2.2 );
  29380. }
  29381. }
  29382. vec4 linearToOutputTexel( vec4 value ) {
  29383. if ( outputEncoding == 0 ) {
  29384. return value;
  29385. } else if ( outputEncoding == 1 ) {
  29386. return LinearTosRGB( value );
  29387. } else if ( outputEncoding == 2 ) {
  29388. return LinearToRGBE( value );
  29389. } else if ( outputEncoding == 3 ) {
  29390. return LinearToRGBM( value, 7.0 );
  29391. } else if ( outputEncoding == 4 ) {
  29392. return LinearToRGBM( value, 16.0 );
  29393. } else if ( outputEncoding == 5 ) {
  29394. return LinearToRGBD( value, 256.0 );
  29395. } else {
  29396. return LinearToGamma( value, 2.2 );
  29397. }
  29398. }
  29399. vec4 envMapTexelToLinear( vec4 color ) {
  29400. return inputTexelToLinear( color );
  29401. }
  29402. `
  29403. );
  29404. }
  29405. function Face4(a, b, c, d, normal, color, materialIndex) {
  29406. console.warn('THREE.Face4 has been removed. A THREE.Face3 will be created instead.');
  29407. return new Face3(a, b, c, normal, color, materialIndex);
  29408. }
  29409. const LineStrip = 0;
  29410. exports.LineStrip = LineStrip;
  29411. const LinePieces = 1;
  29412. exports.LinePieces = LinePieces;
  29413. const NoColors = 0;
  29414. exports.NoColors = NoColors;
  29415. const FaceColors = 1;
  29416. exports.FaceColors = FaceColors;
  29417. const VertexColors = 2;
  29418. exports.VertexColors = VertexColors;
  29419. function MeshFaceMaterial(materials) {
  29420. console.warn('THREE.MeshFaceMaterial has been removed. Use an Array instead.');
  29421. return materials;
  29422. }
  29423. function MultiMaterial(materials = []) {
  29424. console.warn('THREE.MultiMaterial has been removed. Use an Array instead.');
  29425. materials.isMultiMaterial = true;
  29426. materials.materials = materials;
  29427. materials.clone = function () {
  29428. return materials.slice();
  29429. };
  29430. return materials;
  29431. }
  29432. function PointCloud(geometry, material) {
  29433. console.warn('THREE.PointCloud has been renamed to THREE.Points.');
  29434. return new Points(geometry, material);
  29435. }
  29436. function Particle(material) {
  29437. console.warn('THREE.Particle has been renamed to THREE.Sprite.');
  29438. return new Sprite(material);
  29439. }
  29440. function ParticleSystem(geometry, material) {
  29441. console.warn('THREE.ParticleSystem has been renamed to THREE.Points.');
  29442. return new Points(geometry, material);
  29443. }
  29444. function PointCloudMaterial(parameters) {
  29445. console.warn('THREE.PointCloudMaterial has been renamed to THREE.PointsMaterial.');
  29446. return new PointsMaterial(parameters);
  29447. }
  29448. function ParticleBasicMaterial(parameters) {
  29449. console.warn('THREE.ParticleBasicMaterial has been renamed to THREE.PointsMaterial.');
  29450. return new PointsMaterial(parameters);
  29451. }
  29452. function ParticleSystemMaterial(parameters) {
  29453. console.warn('THREE.ParticleSystemMaterial has been renamed to THREE.PointsMaterial.');
  29454. return new PointsMaterial(parameters);
  29455. }
  29456. function Vertex(x, y, z) {
  29457. console.warn('THREE.Vertex has been removed. Use THREE.Vector3 instead.');
  29458. return new Vector3(x, y, z);
  29459. } //
  29460. function DynamicBufferAttribute(array, itemSize) {
  29461. console.warn('THREE.DynamicBufferAttribute has been removed. Use new THREE.BufferAttribute().setUsage( THREE.DynamicDrawUsage ) instead.');
  29462. return new BufferAttribute(array, itemSize).setUsage(DynamicDrawUsage);
  29463. }
  29464. function Int8Attribute(array, itemSize) {
  29465. console.warn('THREE.Int8Attribute has been removed. Use new THREE.Int8BufferAttribute() instead.');
  29466. return new Int8BufferAttribute(array, itemSize);
  29467. }
  29468. function Uint8Attribute(array, itemSize) {
  29469. console.warn('THREE.Uint8Attribute has been removed. Use new THREE.Uint8BufferAttribute() instead.');
  29470. return new Uint8BufferAttribute(array, itemSize);
  29471. }
  29472. function Uint8ClampedAttribute(array, itemSize) {
  29473. console.warn('THREE.Uint8ClampedAttribute has been removed. Use new THREE.Uint8ClampedBufferAttribute() instead.');
  29474. return new Uint8ClampedBufferAttribute(array, itemSize);
  29475. }
  29476. function Int16Attribute(array, itemSize) {
  29477. console.warn('THREE.Int16Attribute has been removed. Use new THREE.Int16BufferAttribute() instead.');
  29478. return new Int16BufferAttribute(array, itemSize);
  29479. }
  29480. function Uint16Attribute(array, itemSize) {
  29481. console.warn('THREE.Uint16Attribute has been removed. Use new THREE.Uint16BufferAttribute() instead.');
  29482. return new Uint16BufferAttribute(array, itemSize);
  29483. }
  29484. function Int32Attribute(array, itemSize) {
  29485. console.warn('THREE.Int32Attribute has been removed. Use new THREE.Int32BufferAttribute() instead.');
  29486. return new Int32BufferAttribute(array, itemSize);
  29487. }
  29488. function Uint32Attribute(array, itemSize) {
  29489. console.warn('THREE.Uint32Attribute has been removed. Use new THREE.Uint32BufferAttribute() instead.');
  29490. return new Uint32BufferAttribute(array, itemSize);
  29491. }
  29492. function Float32Attribute(array, itemSize) {
  29493. console.warn('THREE.Float32Attribute has been removed. Use new THREE.Float32BufferAttribute() instead.');
  29494. return new Float32BufferAttribute(array, itemSize);
  29495. }
  29496. function Float64Attribute(array, itemSize) {
  29497. console.warn('THREE.Float64Attribute has been removed. Use new THREE.Float64BufferAttribute() instead.');
  29498. return new Float64BufferAttribute(array, itemSize);
  29499. } //
  29500. Curve.create = function (construct, getPoint) {
  29501. console.log('THREE.Curve.create() has been deprecated');
  29502. construct.prototype = Object.create(Curve.prototype);
  29503. construct.prototype.constructor = construct;
  29504. construct.prototype.getPoint = getPoint;
  29505. return construct;
  29506. }; //
  29507. Object.assign(CurvePath.prototype, {
  29508. createPointsGeometry: function (divisions) {
  29509. console.warn('THREE.CurvePath: .createPointsGeometry() has been removed. Use new THREE.Geometry().setFromPoints( points ) instead.'); // generate geometry from path points (for Line or Points objects)
  29510. const pts = this.getPoints(divisions);
  29511. return this.createGeometry(pts);
  29512. },
  29513. createSpacedPointsGeometry: function (divisions) {
  29514. console.warn('THREE.CurvePath: .createSpacedPointsGeometry() has been removed. Use new THREE.Geometry().setFromPoints( points ) instead.'); // generate geometry from equidistant sampling along the path
  29515. const pts = this.getSpacedPoints(divisions);
  29516. return this.createGeometry(pts);
  29517. },
  29518. createGeometry: function (points) {
  29519. console.warn('THREE.CurvePath: .createGeometry() has been removed. Use new THREE.Geometry().setFromPoints( points ) instead.');
  29520. const geometry = new Geometry();
  29521. for (let i = 0, l = points.length; i < l; i++) {
  29522. const point = points[i];
  29523. geometry.vertices.push(new Vector3(point.x, point.y, point.z || 0));
  29524. }
  29525. return geometry;
  29526. }
  29527. }); //
  29528. Object.assign(Path.prototype, {
  29529. fromPoints: function (points) {
  29530. console.warn('THREE.Path: .fromPoints() has been renamed to .setFromPoints().');
  29531. return this.setFromPoints(points);
  29532. }
  29533. }); //
  29534. function ClosedSplineCurve3(points) {
  29535. console.warn('THREE.ClosedSplineCurve3 has been deprecated. Use THREE.CatmullRomCurve3 instead.');
  29536. CatmullRomCurve3.call(this, points);
  29537. this.type = 'catmullrom';
  29538. this.closed = true;
  29539. }
  29540. ClosedSplineCurve3.prototype = Object.create(CatmullRomCurve3.prototype); //
  29541. function SplineCurve3(points) {
  29542. console.warn('THREE.SplineCurve3 has been deprecated. Use THREE.CatmullRomCurve3 instead.');
  29543. CatmullRomCurve3.call(this, points);
  29544. this.type = 'catmullrom';
  29545. }
  29546. SplineCurve3.prototype = Object.create(CatmullRomCurve3.prototype); //
  29547. function Spline(points) {
  29548. console.warn('THREE.Spline has been removed. Use THREE.CatmullRomCurve3 instead.');
  29549. CatmullRomCurve3.call(this, points);
  29550. this.type = 'catmullrom';
  29551. }
  29552. Spline.prototype = Object.create(CatmullRomCurve3.prototype);
  29553. Object.assign(Spline.prototype, {
  29554. initFromArray: function ()
  29555. /* a */
  29556. {
  29557. console.error('THREE.Spline: .initFromArray() has been removed.');
  29558. },
  29559. getControlPointsArray: function ()
  29560. /* optionalTarget */
  29561. {
  29562. console.error('THREE.Spline: .getControlPointsArray() has been removed.');
  29563. },
  29564. reparametrizeByArcLength: function ()
  29565. /* samplingCoef */
  29566. {
  29567. console.error('THREE.Spline: .reparametrizeByArcLength() has been removed.');
  29568. }
  29569. }); //
  29570. function AxisHelper(size) {
  29571. console.warn('THREE.AxisHelper has been renamed to THREE.AxesHelper.');
  29572. return new AxesHelper(size);
  29573. }
  29574. function BoundingBoxHelper(object, color) {
  29575. console.warn('THREE.BoundingBoxHelper has been deprecated. Creating a THREE.BoxHelper instead.');
  29576. return new BoxHelper(object, color);
  29577. }
  29578. function EdgesHelper(object, hex) {
  29579. console.warn('THREE.EdgesHelper has been removed. Use THREE.EdgesGeometry instead.');
  29580. return new LineSegments(new EdgesGeometry(object.geometry), new LineBasicMaterial({
  29581. color: hex !== undefined ? hex : 0xffffff
  29582. }));
  29583. }
  29584. GridHelper.prototype.setColors = function () {
  29585. console.error('THREE.GridHelper: setColors() has been deprecated, pass them in the constructor instead.');
  29586. };
  29587. SkeletonHelper.prototype.update = function () {
  29588. console.error('THREE.SkeletonHelper: update() no longer needs to be called.');
  29589. };
  29590. function WireframeHelper(object, hex) {
  29591. console.warn('THREE.WireframeHelper has been removed. Use THREE.WireframeGeometry instead.');
  29592. return new LineSegments(new WireframeGeometry(object.geometry), new LineBasicMaterial({
  29593. color: hex !== undefined ? hex : 0xffffff
  29594. }));
  29595. } //
  29596. Object.assign(Loader.prototype, {
  29597. extractUrlBase: function (url) {
  29598. console.warn('THREE.Loader: .extractUrlBase() has been deprecated. Use THREE.LoaderUtils.extractUrlBase() instead.');
  29599. return LoaderUtils.extractUrlBase(url);
  29600. }
  29601. });
  29602. Loader.Handlers = {
  29603. add: function ()
  29604. /* regex, loader */
  29605. {
  29606. console.error('THREE.Loader: Handlers.add() has been removed. Use LoadingManager.addHandler() instead.');
  29607. },
  29608. get: function ()
  29609. /* file */
  29610. {
  29611. console.error('THREE.Loader: Handlers.get() has been removed. Use LoadingManager.getHandler() instead.');
  29612. }
  29613. };
  29614. function XHRLoader(manager) {
  29615. console.warn('THREE.XHRLoader has been renamed to THREE.FileLoader.');
  29616. return new FileLoader(manager);
  29617. }
  29618. function BinaryTextureLoader(manager) {
  29619. console.warn('THREE.BinaryTextureLoader has been renamed to THREE.DataTextureLoader.');
  29620. return new DataTextureLoader(manager);
  29621. } //
  29622. Object.assign(Box2.prototype, {
  29623. center: function (optionalTarget) {
  29624. console.warn('THREE.Box2: .center() has been renamed to .getCenter().');
  29625. return this.getCenter(optionalTarget);
  29626. },
  29627. empty: function () {
  29628. console.warn('THREE.Box2: .empty() has been renamed to .isEmpty().');
  29629. return this.isEmpty();
  29630. },
  29631. isIntersectionBox: function (box) {
  29632. console.warn('THREE.Box2: .isIntersectionBox() has been renamed to .intersectsBox().');
  29633. return this.intersectsBox(box);
  29634. },
  29635. size: function (optionalTarget) {
  29636. console.warn('THREE.Box2: .size() has been renamed to .getSize().');
  29637. return this.getSize(optionalTarget);
  29638. }
  29639. });
  29640. Object.assign(Box3.prototype, {
  29641. center: function (optionalTarget) {
  29642. console.warn('THREE.Box3: .center() has been renamed to .getCenter().');
  29643. return this.getCenter(optionalTarget);
  29644. },
  29645. empty: function () {
  29646. console.warn('THREE.Box3: .empty() has been renamed to .isEmpty().');
  29647. return this.isEmpty();
  29648. },
  29649. isIntersectionBox: function (box) {
  29650. console.warn('THREE.Box3: .isIntersectionBox() has been renamed to .intersectsBox().');
  29651. return this.intersectsBox(box);
  29652. },
  29653. isIntersectionSphere: function (sphere) {
  29654. console.warn('THREE.Box3: .isIntersectionSphere() has been renamed to .intersectsSphere().');
  29655. return this.intersectsSphere(sphere);
  29656. },
  29657. size: function (optionalTarget) {
  29658. console.warn('THREE.Box3: .size() has been renamed to .getSize().');
  29659. return this.getSize(optionalTarget);
  29660. }
  29661. });
  29662. Object.assign(Sphere.prototype, {
  29663. empty: function () {
  29664. console.warn('THREE.Sphere: .empty() has been renamed to .isEmpty().');
  29665. return this.isEmpty();
  29666. }
  29667. });
  29668. Frustum.prototype.setFromMatrix = function (m) {
  29669. console.warn('THREE.Frustum: .setFromMatrix() has been renamed to .setFromProjectionMatrix().');
  29670. return this.setFromProjectionMatrix(m);
  29671. };
  29672. Line3.prototype.center = function (optionalTarget) {
  29673. console.warn('THREE.Line3: .center() has been renamed to .getCenter().');
  29674. return this.getCenter(optionalTarget);
  29675. };
  29676. Object.assign(MathUtils, {
  29677. random16: function () {
  29678. console.warn('THREE.Math: .random16() has been deprecated. Use Math.random() instead.');
  29679. return Math.random();
  29680. },
  29681. nearestPowerOfTwo: function (value) {
  29682. console.warn('THREE.Math: .nearestPowerOfTwo() has been renamed to .floorPowerOfTwo().');
  29683. return MathUtils.floorPowerOfTwo(value);
  29684. },
  29685. nextPowerOfTwo: function (value) {
  29686. console.warn('THREE.Math: .nextPowerOfTwo() has been renamed to .ceilPowerOfTwo().');
  29687. return MathUtils.ceilPowerOfTwo(value);
  29688. }
  29689. });
  29690. Object.assign(Matrix3.prototype, {
  29691. flattenToArrayOffset: function (array, offset) {
  29692. console.warn("THREE.Matrix3: .flattenToArrayOffset() has been deprecated. Use .toArray() instead.");
  29693. return this.toArray(array, offset);
  29694. },
  29695. multiplyVector3: function (vector) {
  29696. console.warn('THREE.Matrix3: .multiplyVector3() has been removed. Use vector.applyMatrix3( matrix ) instead.');
  29697. return vector.applyMatrix3(this);
  29698. },
  29699. multiplyVector3Array: function ()
  29700. /* a */
  29701. {
  29702. console.error('THREE.Matrix3: .multiplyVector3Array() has been removed.');
  29703. },
  29704. applyToBufferAttribute: function (attribute) {
  29705. console.warn('THREE.Matrix3: .applyToBufferAttribute() has been removed. Use attribute.applyMatrix3( matrix ) instead.');
  29706. return attribute.applyMatrix3(this);
  29707. },
  29708. applyToVector3Array: function ()
  29709. /* array, offset, length */
  29710. {
  29711. console.error('THREE.Matrix3: .applyToVector3Array() has been removed.');
  29712. },
  29713. getInverse: function (matrix) {
  29714. console.warn('THREE.Matrix3: .getInverse() has been removed. Use matrixInv.copy( matrix ).invert(); instead.');
  29715. return this.copy(matrix).invert();
  29716. }
  29717. });
  29718. Object.assign(Matrix4.prototype, {
  29719. extractPosition: function (m) {
  29720. console.warn('THREE.Matrix4: .extractPosition() has been renamed to .copyPosition().');
  29721. return this.copyPosition(m);
  29722. },
  29723. flattenToArrayOffset: function (array, offset) {
  29724. console.warn("THREE.Matrix4: .flattenToArrayOffset() has been deprecated. Use .toArray() instead.");
  29725. return this.toArray(array, offset);
  29726. },
  29727. getPosition: function () {
  29728. console.warn('THREE.Matrix4: .getPosition() has been removed. Use Vector3.setFromMatrixPosition( matrix ) instead.');
  29729. return new Vector3().setFromMatrixColumn(this, 3);
  29730. },
  29731. setRotationFromQuaternion: function (q) {
  29732. console.warn('THREE.Matrix4: .setRotationFromQuaternion() has been renamed to .makeRotationFromQuaternion().');
  29733. return this.makeRotationFromQuaternion(q);
  29734. },
  29735. multiplyToArray: function () {
  29736. console.warn('THREE.Matrix4: .multiplyToArray() has been removed.');
  29737. },
  29738. multiplyVector3: function (vector) {
  29739. console.warn('THREE.Matrix4: .multiplyVector3() has been removed. Use vector.applyMatrix4( matrix ) instead.');
  29740. return vector.applyMatrix4(this);
  29741. },
  29742. multiplyVector4: function (vector) {
  29743. console.warn('THREE.Matrix4: .multiplyVector4() has been removed. Use vector.applyMatrix4( matrix ) instead.');
  29744. return vector.applyMatrix4(this);
  29745. },
  29746. multiplyVector3Array: function ()
  29747. /* a */
  29748. {
  29749. console.error('THREE.Matrix4: .multiplyVector3Array() has been removed.');
  29750. },
  29751. rotateAxis: function (v) {
  29752. console.warn('THREE.Matrix4: .rotateAxis() has been removed. Use Vector3.transformDirection( matrix ) instead.');
  29753. v.transformDirection(this);
  29754. },
  29755. crossVector: function (vector) {
  29756. console.warn('THREE.Matrix4: .crossVector() has been removed. Use vector.applyMatrix4( matrix ) instead.');
  29757. return vector.applyMatrix4(this);
  29758. },
  29759. translate: function () {
  29760. console.error('THREE.Matrix4: .translate() has been removed.');
  29761. },
  29762. rotateX: function () {
  29763. console.error('THREE.Matrix4: .rotateX() has been removed.');
  29764. },
  29765. rotateY: function () {
  29766. console.error('THREE.Matrix4: .rotateY() has been removed.');
  29767. },
  29768. rotateZ: function () {
  29769. console.error('THREE.Matrix4: .rotateZ() has been removed.');
  29770. },
  29771. rotateByAxis: function () {
  29772. console.error('THREE.Matrix4: .rotateByAxis() has been removed.');
  29773. },
  29774. applyToBufferAttribute: function (attribute) {
  29775. console.warn('THREE.Matrix4: .applyToBufferAttribute() has been removed. Use attribute.applyMatrix4( matrix ) instead.');
  29776. return attribute.applyMatrix4(this);
  29777. },
  29778. applyToVector3Array: function ()
  29779. /* array, offset, length */
  29780. {
  29781. console.error('THREE.Matrix4: .applyToVector3Array() has been removed.');
  29782. },
  29783. makeFrustum: function (left, right, bottom, top, near, far) {
  29784. console.warn('THREE.Matrix4: .makeFrustum() has been removed. Use .makePerspective( left, right, top, bottom, near, far ) instead.');
  29785. return this.makePerspective(left, right, top, bottom, near, far);
  29786. },
  29787. getInverse: function (matrix) {
  29788. console.warn('THREE.Matrix4: .getInverse() has been removed. Use matrixInv.copy( matrix ).invert(); instead.');
  29789. return this.copy(matrix).invert();
  29790. }
  29791. });
  29792. Plane.prototype.isIntersectionLine = function (line) {
  29793. console.warn('THREE.Plane: .isIntersectionLine() has been renamed to .intersectsLine().');
  29794. return this.intersectsLine(line);
  29795. };
  29796. Object.assign(Quaternion.prototype, {
  29797. multiplyVector3: function (vector) {
  29798. console.warn('THREE.Quaternion: .multiplyVector3() has been removed. Use is now vector.applyQuaternion( quaternion ) instead.');
  29799. return vector.applyQuaternion(this);
  29800. },
  29801. inverse: function () {
  29802. console.warn('THREE.Quaternion: .inverse() has been renamed to invert().');
  29803. return this.invert();
  29804. }
  29805. });
  29806. Object.assign(Ray.prototype, {
  29807. isIntersectionBox: function (box) {
  29808. console.warn('THREE.Ray: .isIntersectionBox() has been renamed to .intersectsBox().');
  29809. return this.intersectsBox(box);
  29810. },
  29811. isIntersectionPlane: function (plane) {
  29812. console.warn('THREE.Ray: .isIntersectionPlane() has been renamed to .intersectsPlane().');
  29813. return this.intersectsPlane(plane);
  29814. },
  29815. isIntersectionSphere: function (sphere) {
  29816. console.warn('THREE.Ray: .isIntersectionSphere() has been renamed to .intersectsSphere().');
  29817. return this.intersectsSphere(sphere);
  29818. }
  29819. });
  29820. Object.assign(Triangle.prototype, {
  29821. area: function () {
  29822. console.warn('THREE.Triangle: .area() has been renamed to .getArea().');
  29823. return this.getArea();
  29824. },
  29825. barycoordFromPoint: function (point, target) {
  29826. console.warn('THREE.Triangle: .barycoordFromPoint() has been renamed to .getBarycoord().');
  29827. return this.getBarycoord(point, target);
  29828. },
  29829. midpoint: function (target) {
  29830. console.warn('THREE.Triangle: .midpoint() has been renamed to .getMidpoint().');
  29831. return this.getMidpoint(target);
  29832. },
  29833. normal: function (target) {
  29834. console.warn('THREE.Triangle: .normal() has been renamed to .getNormal().');
  29835. return this.getNormal(target);
  29836. },
  29837. plane: function (target) {
  29838. console.warn('THREE.Triangle: .plane() has been renamed to .getPlane().');
  29839. return this.getPlane(target);
  29840. }
  29841. });
  29842. Object.assign(Triangle, {
  29843. barycoordFromPoint: function (point, a, b, c, target) {
  29844. console.warn('THREE.Triangle: .barycoordFromPoint() has been renamed to .getBarycoord().');
  29845. return Triangle.getBarycoord(point, a, b, c, target);
  29846. },
  29847. normal: function (a, b, c, target) {
  29848. console.warn('THREE.Triangle: .normal() has been renamed to .getNormal().');
  29849. return Triangle.getNormal(a, b, c, target);
  29850. }
  29851. });
  29852. Object.assign(Shape.prototype, {
  29853. extractAllPoints: function (divisions) {
  29854. console.warn('THREE.Shape: .extractAllPoints() has been removed. Use .extractPoints() instead.');
  29855. return this.extractPoints(divisions);
  29856. },
  29857. extrude: function (options) {
  29858. console.warn('THREE.Shape: .extrude() has been removed. Use ExtrudeGeometry() instead.');
  29859. return new ExtrudeGeometry(this, options);
  29860. },
  29861. makeGeometry: function (options) {
  29862. console.warn('THREE.Shape: .makeGeometry() has been removed. Use ShapeGeometry() instead.');
  29863. return new ShapeGeometry(this, options);
  29864. }
  29865. });
  29866. Object.assign(Vector2.prototype, {
  29867. fromAttribute: function (attribute, index, offset) {
  29868. console.warn('THREE.Vector2: .fromAttribute() has been renamed to .fromBufferAttribute().');
  29869. return this.fromBufferAttribute(attribute, index, offset);
  29870. },
  29871. distanceToManhattan: function (v) {
  29872. console.warn('THREE.Vector2: .distanceToManhattan() has been renamed to .manhattanDistanceTo().');
  29873. return this.manhattanDistanceTo(v);
  29874. },
  29875. lengthManhattan: function () {
  29876. console.warn('THREE.Vector2: .lengthManhattan() has been renamed to .manhattanLength().');
  29877. return this.manhattanLength();
  29878. }
  29879. });
  29880. Object.assign(Vector3.prototype, {
  29881. setEulerFromRotationMatrix: function () {
  29882. console.error('THREE.Vector3: .setEulerFromRotationMatrix() has been removed. Use Euler.setFromRotationMatrix() instead.');
  29883. },
  29884. setEulerFromQuaternion: function () {
  29885. console.error('THREE.Vector3: .setEulerFromQuaternion() has been removed. Use Euler.setFromQuaternion() instead.');
  29886. },
  29887. getPositionFromMatrix: function (m) {
  29888. console.warn('THREE.Vector3: .getPositionFromMatrix() has been renamed to .setFromMatrixPosition().');
  29889. return this.setFromMatrixPosition(m);
  29890. },
  29891. getScaleFromMatrix: function (m) {
  29892. console.warn('THREE.Vector3: .getScaleFromMatrix() has been renamed to .setFromMatrixScale().');
  29893. return this.setFromMatrixScale(m);
  29894. },
  29895. getColumnFromMatrix: function (index, matrix) {
  29896. console.warn('THREE.Vector3: .getColumnFromMatrix() has been renamed to .setFromMatrixColumn().');
  29897. return this.setFromMatrixColumn(matrix, index);
  29898. },
  29899. applyProjection: function (m) {
  29900. console.warn('THREE.Vector3: .applyProjection() has been removed. Use .applyMatrix4( m ) instead.');
  29901. return this.applyMatrix4(m);
  29902. },
  29903. fromAttribute: function (attribute, index, offset) {
  29904. console.warn('THREE.Vector3: .fromAttribute() has been renamed to .fromBufferAttribute().');
  29905. return this.fromBufferAttribute(attribute, index, offset);
  29906. },
  29907. distanceToManhattan: function (v) {
  29908. console.warn('THREE.Vector3: .distanceToManhattan() has been renamed to .manhattanDistanceTo().');
  29909. return this.manhattanDistanceTo(v);
  29910. },
  29911. lengthManhattan: function () {
  29912. console.warn('THREE.Vector3: .lengthManhattan() has been renamed to .manhattanLength().');
  29913. return this.manhattanLength();
  29914. }
  29915. });
  29916. Object.assign(Vector4.prototype, {
  29917. fromAttribute: function (attribute, index, offset) {
  29918. console.warn('THREE.Vector4: .fromAttribute() has been renamed to .fromBufferAttribute().');
  29919. return this.fromBufferAttribute(attribute, index, offset);
  29920. },
  29921. lengthManhattan: function () {
  29922. console.warn('THREE.Vector4: .lengthManhattan() has been renamed to .manhattanLength().');
  29923. return this.manhattanLength();
  29924. }
  29925. }); //
  29926. Object.assign(Geometry.prototype, {
  29927. computeTangents: function () {
  29928. console.error('THREE.Geometry: .computeTangents() has been removed.');
  29929. },
  29930. computeLineDistances: function () {
  29931. console.error('THREE.Geometry: .computeLineDistances() has been removed. Use THREE.Line.computeLineDistances() instead.');
  29932. },
  29933. applyMatrix: function (matrix) {
  29934. console.warn('THREE.Geometry: .applyMatrix() has been renamed to .applyMatrix4().');
  29935. return this.applyMatrix4(matrix);
  29936. }
  29937. });
  29938. Object.assign(Object3D.prototype, {
  29939. getChildByName: function (name) {
  29940. console.warn('THREE.Object3D: .getChildByName() has been renamed to .getObjectByName().');
  29941. return this.getObjectByName(name);
  29942. },
  29943. renderDepth: function () {
  29944. console.warn('THREE.Object3D: .renderDepth has been removed. Use .renderOrder, instead.');
  29945. },
  29946. translate: function (distance, axis) {
  29947. console.warn('THREE.Object3D: .translate() has been removed. Use .translateOnAxis( axis, distance ) instead.');
  29948. return this.translateOnAxis(axis, distance);
  29949. },
  29950. getWorldRotation: function () {
  29951. console.error('THREE.Object3D: .getWorldRotation() has been removed. Use THREE.Object3D.getWorldQuaternion( target ) instead.');
  29952. },
  29953. applyMatrix: function (matrix) {
  29954. console.warn('THREE.Object3D: .applyMatrix() has been renamed to .applyMatrix4().');
  29955. return this.applyMatrix4(matrix);
  29956. }
  29957. });
  29958. Object.defineProperties(Object3D.prototype, {
  29959. eulerOrder: {
  29960. get: function () {
  29961. console.warn('THREE.Object3D: .eulerOrder is now .rotation.order.');
  29962. return this.rotation.order;
  29963. },
  29964. set: function (value) {
  29965. console.warn('THREE.Object3D: .eulerOrder is now .rotation.order.');
  29966. this.rotation.order = value;
  29967. }
  29968. },
  29969. useQuaternion: {
  29970. get: function () {
  29971. console.warn('THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.');
  29972. },
  29973. set: function () {
  29974. console.warn('THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.');
  29975. }
  29976. }
  29977. });
  29978. Object.assign(Mesh.prototype, {
  29979. setDrawMode: function () {
  29980. console.error('THREE.Mesh: .setDrawMode() has been removed. The renderer now always assumes THREE.TrianglesDrawMode. Transform your geometry via BufferGeometryUtils.toTrianglesDrawMode() if necessary.');
  29981. }
  29982. });
  29983. Object.defineProperties(Mesh.prototype, {
  29984. drawMode: {
  29985. get: function () {
  29986. console.error('THREE.Mesh: .drawMode has been removed. The renderer now always assumes THREE.TrianglesDrawMode.');
  29987. return TrianglesDrawMode;
  29988. },
  29989. set: function () {
  29990. console.error('THREE.Mesh: .drawMode has been removed. The renderer now always assumes THREE.TrianglesDrawMode. Transform your geometry via BufferGeometryUtils.toTrianglesDrawMode() if necessary.');
  29991. }
  29992. }
  29993. });
  29994. Object.defineProperties(LOD.prototype, {
  29995. objects: {
  29996. get: function () {
  29997. console.warn('THREE.LOD: .objects has been renamed to .levels.');
  29998. return this.levels;
  29999. }
  30000. }
  30001. });
  30002. Object.defineProperty(Skeleton.prototype, 'useVertexTexture', {
  30003. get: function () {
  30004. console.warn('THREE.Skeleton: useVertexTexture has been removed.');
  30005. },
  30006. set: function () {
  30007. console.warn('THREE.Skeleton: useVertexTexture has been removed.');
  30008. }
  30009. });
  30010. SkinnedMesh.prototype.initBones = function () {
  30011. console.error('THREE.SkinnedMesh: initBones() has been removed.');
  30012. };
  30013. Object.defineProperty(Curve.prototype, '__arcLengthDivisions', {
  30014. get: function () {
  30015. console.warn('THREE.Curve: .__arcLengthDivisions is now .arcLengthDivisions.');
  30016. return this.arcLengthDivisions;
  30017. },
  30018. set: function (value) {
  30019. console.warn('THREE.Curve: .__arcLengthDivisions is now .arcLengthDivisions.');
  30020. this.arcLengthDivisions = value;
  30021. }
  30022. }); //
  30023. PerspectiveCamera.prototype.setLens = function (focalLength, filmGauge) {
  30024. console.warn("THREE.PerspectiveCamera.setLens is deprecated. " + "Use .setFocalLength and .filmGauge for a photographic setup.");
  30025. if (filmGauge !== undefined) this.filmGauge = filmGauge;
  30026. this.setFocalLength(focalLength);
  30027. }; //
  30028. Object.defineProperties(Light.prototype, {
  30029. onlyShadow: {
  30030. set: function () {
  30031. console.warn('THREE.Light: .onlyShadow has been removed.');
  30032. }
  30033. },
  30034. shadowCameraFov: {
  30035. set: function (value) {
  30036. console.warn('THREE.Light: .shadowCameraFov is now .shadow.camera.fov.');
  30037. this.shadow.camera.fov = value;
  30038. }
  30039. },
  30040. shadowCameraLeft: {
  30041. set: function (value) {
  30042. console.warn('THREE.Light: .shadowCameraLeft is now .shadow.camera.left.');
  30043. this.shadow.camera.left = value;
  30044. }
  30045. },
  30046. shadowCameraRight: {
  30047. set: function (value) {
  30048. console.warn('THREE.Light: .shadowCameraRight is now .shadow.camera.right.');
  30049. this.shadow.camera.right = value;
  30050. }
  30051. },
  30052. shadowCameraTop: {
  30053. set: function (value) {
  30054. console.warn('THREE.Light: .shadowCameraTop is now .shadow.camera.top.');
  30055. this.shadow.camera.top = value;
  30056. }
  30057. },
  30058. shadowCameraBottom: {
  30059. set: function (value) {
  30060. console.warn('THREE.Light: .shadowCameraBottom is now .shadow.camera.bottom.');
  30061. this.shadow.camera.bottom = value;
  30062. }
  30063. },
  30064. shadowCameraNear: {
  30065. set: function (value) {
  30066. console.warn('THREE.Light: .shadowCameraNear is now .shadow.camera.near.');
  30067. this.shadow.camera.near = value;
  30068. }
  30069. },
  30070. shadowCameraFar: {
  30071. set: function (value) {
  30072. console.warn('THREE.Light: .shadowCameraFar is now .shadow.camera.far.');
  30073. this.shadow.camera.far = value;
  30074. }
  30075. },
  30076. shadowCameraVisible: {
  30077. set: function () {
  30078. console.warn('THREE.Light: .shadowCameraVisible has been removed. Use new THREE.CameraHelper( light.shadow.camera ) instead.');
  30079. }
  30080. },
  30081. shadowBias: {
  30082. set: function (value) {
  30083. console.warn('THREE.Light: .shadowBias is now .shadow.bias.');
  30084. this.shadow.bias = value;
  30085. }
  30086. },
  30087. shadowDarkness: {
  30088. set: function () {
  30089. console.warn('THREE.Light: .shadowDarkness has been removed.');
  30090. }
  30091. },
  30092. shadowMapWidth: {
  30093. set: function (value) {
  30094. console.warn('THREE.Light: .shadowMapWidth is now .shadow.mapSize.width.');
  30095. this.shadow.mapSize.width = value;
  30096. }
  30097. },
  30098. shadowMapHeight: {
  30099. set: function (value) {
  30100. console.warn('THREE.Light: .shadowMapHeight is now .shadow.mapSize.height.');
  30101. this.shadow.mapSize.height = value;
  30102. }
  30103. }
  30104. }); //
  30105. Object.defineProperties(BufferAttribute.prototype, {
  30106. length: {
  30107. get: function () {
  30108. console.warn('THREE.BufferAttribute: .length has been deprecated. Use .count instead.');
  30109. return this.array.length;
  30110. }
  30111. },
  30112. dynamic: {
  30113. get: function () {
  30114. console.warn('THREE.BufferAttribute: .dynamic has been deprecated. Use .usage instead.');
  30115. return this.usage === DynamicDrawUsage;
  30116. },
  30117. set: function ()
  30118. /* value */
  30119. {
  30120. console.warn('THREE.BufferAttribute: .dynamic has been deprecated. Use .usage instead.');
  30121. this.setUsage(DynamicDrawUsage);
  30122. }
  30123. }
  30124. });
  30125. Object.assign(BufferAttribute.prototype, {
  30126. setDynamic: function (value) {
  30127. console.warn('THREE.BufferAttribute: .setDynamic() has been deprecated. Use .setUsage() instead.');
  30128. this.setUsage(value === true ? DynamicDrawUsage : StaticDrawUsage);
  30129. return this;
  30130. },
  30131. copyIndicesArray: function ()
  30132. /* indices */
  30133. {
  30134. console.error('THREE.BufferAttribute: .copyIndicesArray() has been removed.');
  30135. },
  30136. setArray: function ()
  30137. /* array */
  30138. {
  30139. console.error('THREE.BufferAttribute: .setArray has been removed. Use BufferGeometry .setAttribute to replace/resize attribute buffers');
  30140. }
  30141. });
  30142. Object.assign(BufferGeometry.prototype, {
  30143. addIndex: function (index) {
  30144. console.warn('THREE.BufferGeometry: .addIndex() has been renamed to .setIndex().');
  30145. this.setIndex(index);
  30146. },
  30147. addAttribute: function (name, attribute) {
  30148. console.warn('THREE.BufferGeometry: .addAttribute() has been renamed to .setAttribute().');
  30149. if (!(attribute && attribute.isBufferAttribute) && !(attribute && attribute.isInterleavedBufferAttribute)) {
  30150. console.warn('THREE.BufferGeometry: .addAttribute() now expects ( name, attribute ).');
  30151. return this.setAttribute(name, new BufferAttribute(arguments[1], arguments[2]));
  30152. }
  30153. if (name === 'index') {
  30154. console.warn('THREE.BufferGeometry.addAttribute: Use .setIndex() for index attribute.');
  30155. this.setIndex(attribute);
  30156. return this;
  30157. }
  30158. return this.setAttribute(name, attribute);
  30159. },
  30160. addDrawCall: function (start, count, indexOffset) {
  30161. if (indexOffset !== undefined) {
  30162. console.warn('THREE.BufferGeometry: .addDrawCall() no longer supports indexOffset.');
  30163. }
  30164. console.warn('THREE.BufferGeometry: .addDrawCall() is now .addGroup().');
  30165. this.addGroup(start, count);
  30166. },
  30167. clearDrawCalls: function () {
  30168. console.warn('THREE.BufferGeometry: .clearDrawCalls() is now .clearGroups().');
  30169. this.clearGroups();
  30170. },
  30171. computeTangents: function () {
  30172. console.warn('THREE.BufferGeometry: .computeTangents() has been removed.');
  30173. },
  30174. computeOffsets: function () {
  30175. console.warn('THREE.BufferGeometry: .computeOffsets() has been removed.');
  30176. },
  30177. removeAttribute: function (name) {
  30178. console.warn('THREE.BufferGeometry: .removeAttribute() has been renamed to .deleteAttribute().');
  30179. return this.deleteAttribute(name);
  30180. },
  30181. applyMatrix: function (matrix) {
  30182. console.warn('THREE.BufferGeometry: .applyMatrix() has been renamed to .applyMatrix4().');
  30183. return this.applyMatrix4(matrix);
  30184. }
  30185. });
  30186. Object.defineProperties(BufferGeometry.prototype, {
  30187. drawcalls: {
  30188. get: function () {
  30189. console.error('THREE.BufferGeometry: .drawcalls has been renamed to .groups.');
  30190. return this.groups;
  30191. }
  30192. },
  30193. offsets: {
  30194. get: function () {
  30195. console.warn('THREE.BufferGeometry: .offsets has been renamed to .groups.');
  30196. return this.groups;
  30197. }
  30198. }
  30199. });
  30200. Object.defineProperties(InstancedBufferGeometry.prototype, {
  30201. maxInstancedCount: {
  30202. get: function () {
  30203. console.warn('THREE.InstancedBufferGeometry: .maxInstancedCount has been renamed to .instanceCount.');
  30204. return this.instanceCount;
  30205. },
  30206. set: function (value) {
  30207. console.warn('THREE.InstancedBufferGeometry: .maxInstancedCount has been renamed to .instanceCount.');
  30208. this.instanceCount = value;
  30209. }
  30210. }
  30211. });
  30212. Object.defineProperties(Raycaster.prototype, {
  30213. linePrecision: {
  30214. get: function () {
  30215. console.warn('THREE.Raycaster: .linePrecision has been deprecated. Use .params.Line.threshold instead.');
  30216. return this.params.Line.threshold;
  30217. },
  30218. set: function (value) {
  30219. console.warn('THREE.Raycaster: .linePrecision has been deprecated. Use .params.Line.threshold instead.');
  30220. this.params.Line.threshold = value;
  30221. }
  30222. }
  30223. });
  30224. Object.defineProperties(InterleavedBuffer.prototype, {
  30225. dynamic: {
  30226. get: function () {
  30227. console.warn('THREE.InterleavedBuffer: .length has been deprecated. Use .usage instead.');
  30228. return this.usage === DynamicDrawUsage;
  30229. },
  30230. set: function (value) {
  30231. console.warn('THREE.InterleavedBuffer: .length has been deprecated. Use .usage instead.');
  30232. this.setUsage(value);
  30233. }
  30234. }
  30235. });
  30236. Object.assign(InterleavedBuffer.prototype, {
  30237. setDynamic: function (value) {
  30238. console.warn('THREE.InterleavedBuffer: .setDynamic() has been deprecated. Use .setUsage() instead.');
  30239. this.setUsage(value === true ? DynamicDrawUsage : StaticDrawUsage);
  30240. return this;
  30241. },
  30242. setArray: function ()
  30243. /* array */
  30244. {
  30245. console.error('THREE.InterleavedBuffer: .setArray has been removed. Use BufferGeometry .setAttribute to replace/resize attribute buffers');
  30246. }
  30247. }); //
  30248. Object.assign(ExtrudeBufferGeometry.prototype, {
  30249. getArrays: function () {
  30250. console.error('THREE.ExtrudeBufferGeometry: .getArrays() has been removed.');
  30251. },
  30252. addShapeList: function () {
  30253. console.error('THREE.ExtrudeBufferGeometry: .addShapeList() has been removed.');
  30254. },
  30255. addShape: function () {
  30256. console.error('THREE.ExtrudeBufferGeometry: .addShape() has been removed.');
  30257. }
  30258. }); //
  30259. Object.assign(Scene.prototype, {
  30260. dispose: function () {
  30261. console.error('THREE.Scene: .dispose() has been removed.');
  30262. }
  30263. }); //
  30264. Object.defineProperties(Uniform.prototype, {
  30265. dynamic: {
  30266. set: function () {
  30267. console.warn('THREE.Uniform: .dynamic has been removed. Use object.onBeforeRender() instead.');
  30268. }
  30269. },
  30270. onUpdate: {
  30271. value: function () {
  30272. console.warn('THREE.Uniform: .onUpdate() has been removed. Use object.onBeforeRender() instead.');
  30273. return this;
  30274. }
  30275. }
  30276. }); //
  30277. Object.defineProperties(Material.prototype, {
  30278. wrapAround: {
  30279. get: function () {
  30280. console.warn('THREE.Material: .wrapAround has been removed.');
  30281. },
  30282. set: function () {
  30283. console.warn('THREE.Material: .wrapAround has been removed.');
  30284. }
  30285. },
  30286. overdraw: {
  30287. get: function () {
  30288. console.warn('THREE.Material: .overdraw has been removed.');
  30289. },
  30290. set: function () {
  30291. console.warn('THREE.Material: .overdraw has been removed.');
  30292. }
  30293. },
  30294. wrapRGB: {
  30295. get: function () {
  30296. console.warn('THREE.Material: .wrapRGB has been removed.');
  30297. return new Color();
  30298. }
  30299. },
  30300. shading: {
  30301. get: function () {
  30302. console.error('THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.');
  30303. },
  30304. set: function (value) {
  30305. console.warn('THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.');
  30306. this.flatShading = value === FlatShading;
  30307. }
  30308. },
  30309. stencilMask: {
  30310. get: function () {
  30311. console.warn('THREE.' + this.type + ': .stencilMask has been removed. Use .stencilFuncMask instead.');
  30312. return this.stencilFuncMask;
  30313. },
  30314. set: function (value) {
  30315. console.warn('THREE.' + this.type + ': .stencilMask has been removed. Use .stencilFuncMask instead.');
  30316. this.stencilFuncMask = value;
  30317. }
  30318. }
  30319. });
  30320. Object.defineProperties(MeshPhongMaterial.prototype, {
  30321. metal: {
  30322. get: function () {
  30323. console.warn('THREE.MeshPhongMaterial: .metal has been removed. Use THREE.MeshStandardMaterial instead.');
  30324. return false;
  30325. },
  30326. set: function () {
  30327. console.warn('THREE.MeshPhongMaterial: .metal has been removed. Use THREE.MeshStandardMaterial instead');
  30328. }
  30329. }
  30330. });
  30331. Object.defineProperties(MeshPhysicalMaterial.prototype, {
  30332. transparency: {
  30333. get: function () {
  30334. console.warn('THREE.MeshPhysicalMaterial: .transparency has been renamed to .transmission.');
  30335. return this.transmission;
  30336. },
  30337. set: function (value) {
  30338. console.warn('THREE.MeshPhysicalMaterial: .transparency has been renamed to .transmission.');
  30339. this.transmission = value;
  30340. }
  30341. }
  30342. });
  30343. Object.defineProperties(ShaderMaterial.prototype, {
  30344. derivatives: {
  30345. get: function () {
  30346. console.warn('THREE.ShaderMaterial: .derivatives has been moved to .extensions.derivatives.');
  30347. return this.extensions.derivatives;
  30348. },
  30349. set: function (value) {
  30350. console.warn('THREE. ShaderMaterial: .derivatives has been moved to .extensions.derivatives.');
  30351. this.extensions.derivatives = value;
  30352. }
  30353. }
  30354. }); //
  30355. Object.assign(WebGLRenderer.prototype, {
  30356. clearTarget: function (renderTarget, color, depth, stencil) {
  30357. console.warn('THREE.WebGLRenderer: .clearTarget() has been deprecated. Use .setRenderTarget() and .clear() instead.');
  30358. this.setRenderTarget(renderTarget);
  30359. this.clear(color, depth, stencil);
  30360. },
  30361. animate: function (callback) {
  30362. console.warn('THREE.WebGLRenderer: .animate() is now .setAnimationLoop().');
  30363. this.setAnimationLoop(callback);
  30364. },
  30365. getCurrentRenderTarget: function () {
  30366. console.warn('THREE.WebGLRenderer: .getCurrentRenderTarget() is now .getRenderTarget().');
  30367. return this.getRenderTarget();
  30368. },
  30369. getMaxAnisotropy: function () {
  30370. console.warn('THREE.WebGLRenderer: .getMaxAnisotropy() is now .capabilities.getMaxAnisotropy().');
  30371. return this.capabilities.getMaxAnisotropy();
  30372. },
  30373. getPrecision: function () {
  30374. console.warn('THREE.WebGLRenderer: .getPrecision() is now .capabilities.precision.');
  30375. return this.capabilities.precision;
  30376. },
  30377. resetGLState: function () {
  30378. console.warn('THREE.WebGLRenderer: .resetGLState() is now .state.reset().');
  30379. return this.state.reset();
  30380. },
  30381. supportsFloatTextures: function () {
  30382. console.warn('THREE.WebGLRenderer: .supportsFloatTextures() is now .extensions.get( \'OES_texture_float\' ).');
  30383. return this.extensions.get('OES_texture_float');
  30384. },
  30385. supportsHalfFloatTextures: function () {
  30386. console.warn('THREE.WebGLRenderer: .supportsHalfFloatTextures() is now .extensions.get( \'OES_texture_half_float\' ).');
  30387. return this.extensions.get('OES_texture_half_float');
  30388. },
  30389. supportsStandardDerivatives: function () {
  30390. console.warn('THREE.WebGLRenderer: .supportsStandardDerivatives() is now .extensions.get( \'OES_standard_derivatives\' ).');
  30391. return this.extensions.get('OES_standard_derivatives');
  30392. },
  30393. supportsCompressedTextureS3TC: function () {
  30394. console.warn('THREE.WebGLRenderer: .supportsCompressedTextureS3TC() is now .extensions.get( \'WEBGL_compressed_texture_s3tc\' ).');
  30395. return this.extensions.get('WEBGL_compressed_texture_s3tc');
  30396. },
  30397. supportsCompressedTexturePVRTC: function () {
  30398. console.warn('THREE.WebGLRenderer: .supportsCompressedTexturePVRTC() is now .extensions.get( \'WEBGL_compressed_texture_pvrtc\' ).');
  30399. return this.extensions.get('WEBGL_compressed_texture_pvrtc');
  30400. },
  30401. supportsBlendMinMax: function () {
  30402. console.warn('THREE.WebGLRenderer: .supportsBlendMinMax() is now .extensions.get( \'EXT_blend_minmax\' ).');
  30403. return this.extensions.get('EXT_blend_minmax');
  30404. },
  30405. supportsVertexTextures: function () {
  30406. console.warn('THREE.WebGLRenderer: .supportsVertexTextures() is now .capabilities.vertexTextures.');
  30407. return this.capabilities.vertexTextures;
  30408. },
  30409. supportsInstancedArrays: function () {
  30410. console.warn('THREE.WebGLRenderer: .supportsInstancedArrays() is now .extensions.get( \'ANGLE_instanced_arrays\' ).');
  30411. return this.extensions.get('ANGLE_instanced_arrays');
  30412. },
  30413. enableScissorTest: function (boolean) {
  30414. console.warn('THREE.WebGLRenderer: .enableScissorTest() is now .setScissorTest().');
  30415. this.setScissorTest(boolean);
  30416. },
  30417. initMaterial: function () {
  30418. console.warn('THREE.WebGLRenderer: .initMaterial() has been removed.');
  30419. },
  30420. addPrePlugin: function () {
  30421. console.warn('THREE.WebGLRenderer: .addPrePlugin() has been removed.');
  30422. },
  30423. addPostPlugin: function () {
  30424. console.warn('THREE.WebGLRenderer: .addPostPlugin() has been removed.');
  30425. },
  30426. updateShadowMap: function () {
  30427. console.warn('THREE.WebGLRenderer: .updateShadowMap() has been removed.');
  30428. },
  30429. setFaceCulling: function () {
  30430. console.warn('THREE.WebGLRenderer: .setFaceCulling() has been removed.');
  30431. },
  30432. allocTextureUnit: function () {
  30433. console.warn('THREE.WebGLRenderer: .allocTextureUnit() has been removed.');
  30434. },
  30435. setTexture: function () {
  30436. console.warn('THREE.WebGLRenderer: .setTexture() has been removed.');
  30437. },
  30438. setTexture2D: function () {
  30439. console.warn('THREE.WebGLRenderer: .setTexture2D() has been removed.');
  30440. },
  30441. setTextureCube: function () {
  30442. console.warn('THREE.WebGLRenderer: .setTextureCube() has been removed.');
  30443. },
  30444. getActiveMipMapLevel: function () {
  30445. console.warn('THREE.WebGLRenderer: .getActiveMipMapLevel() is now .getActiveMipmapLevel().');
  30446. return this.getActiveMipmapLevel();
  30447. }
  30448. });
  30449. Object.defineProperties(WebGLRenderer.prototype, {
  30450. shadowMapEnabled: {
  30451. get: function () {
  30452. return this.shadowMap.enabled;
  30453. },
  30454. set: function (value) {
  30455. console.warn('THREE.WebGLRenderer: .shadowMapEnabled is now .shadowMap.enabled.');
  30456. this.shadowMap.enabled = value;
  30457. }
  30458. },
  30459. shadowMapType: {
  30460. get: function () {
  30461. return this.shadowMap.type;
  30462. },
  30463. set: function (value) {
  30464. console.warn('THREE.WebGLRenderer: .shadowMapType is now .shadowMap.type.');
  30465. this.shadowMap.type = value;
  30466. }
  30467. },
  30468. shadowMapCullFace: {
  30469. get: function () {
  30470. console.warn('THREE.WebGLRenderer: .shadowMapCullFace has been removed. Set Material.shadowSide instead.');
  30471. return undefined;
  30472. },
  30473. set: function ()
  30474. /* value */
  30475. {
  30476. console.warn('THREE.WebGLRenderer: .shadowMapCullFace has been removed. Set Material.shadowSide instead.');
  30477. }
  30478. },
  30479. context: {
  30480. get: function () {
  30481. console.warn('THREE.WebGLRenderer: .context has been removed. Use .getContext() instead.');
  30482. return this.getContext();
  30483. }
  30484. },
  30485. vr: {
  30486. get: function () {
  30487. console.warn('THREE.WebGLRenderer: .vr has been renamed to .xr');
  30488. return this.xr;
  30489. }
  30490. },
  30491. gammaInput: {
  30492. get: function () {
  30493. console.warn('THREE.WebGLRenderer: .gammaInput has been removed. Set the encoding for textures via Texture.encoding instead.');
  30494. return false;
  30495. },
  30496. set: function () {
  30497. console.warn('THREE.WebGLRenderer: .gammaInput has been removed. Set the encoding for textures via Texture.encoding instead.');
  30498. }
  30499. },
  30500. gammaOutput: {
  30501. get: function () {
  30502. console.warn('THREE.WebGLRenderer: .gammaOutput has been removed. Set WebGLRenderer.outputEncoding instead.');
  30503. return false;
  30504. },
  30505. set: function (value) {
  30506. console.warn('THREE.WebGLRenderer: .gammaOutput has been removed. Set WebGLRenderer.outputEncoding instead.');
  30507. this.outputEncoding = value === true ? sRGBEncoding : LinearEncoding;
  30508. }
  30509. },
  30510. toneMappingWhitePoint: {
  30511. get: function () {
  30512. console.warn('THREE.WebGLRenderer: .toneMappingWhitePoint has been removed.');
  30513. return 1.0;
  30514. },
  30515. set: function () {
  30516. console.warn('THREE.WebGLRenderer: .toneMappingWhitePoint has been removed.');
  30517. }
  30518. }
  30519. });
  30520. Object.defineProperties(WebGLShadowMap.prototype, {
  30521. cullFace: {
  30522. get: function () {
  30523. console.warn('THREE.WebGLRenderer: .shadowMap.cullFace has been removed. Set Material.shadowSide instead.');
  30524. return undefined;
  30525. },
  30526. set: function ()
  30527. /* cullFace */
  30528. {
  30529. console.warn('THREE.WebGLRenderer: .shadowMap.cullFace has been removed. Set Material.shadowSide instead.');
  30530. }
  30531. },
  30532. renderReverseSided: {
  30533. get: function () {
  30534. console.warn('THREE.WebGLRenderer: .shadowMap.renderReverseSided has been removed. Set Material.shadowSide instead.');
  30535. return undefined;
  30536. },
  30537. set: function () {
  30538. console.warn('THREE.WebGLRenderer: .shadowMap.renderReverseSided has been removed. Set Material.shadowSide instead.');
  30539. }
  30540. },
  30541. renderSingleSided: {
  30542. get: function () {
  30543. console.warn('THREE.WebGLRenderer: .shadowMap.renderSingleSided has been removed. Set Material.shadowSide instead.');
  30544. return undefined;
  30545. },
  30546. set: function () {
  30547. console.warn('THREE.WebGLRenderer: .shadowMap.renderSingleSided has been removed. Set Material.shadowSide instead.');
  30548. }
  30549. }
  30550. });
  30551. function WebGLRenderTargetCube(width, height, options) {
  30552. console.warn('THREE.WebGLRenderTargetCube( width, height, options ) is now WebGLCubeRenderTarget( size, options ).');
  30553. return new WebGLCubeRenderTarget(width, options);
  30554. } //
  30555. Object.defineProperties(WebGLRenderTarget.prototype, {
  30556. wrapS: {
  30557. get: function () {
  30558. console.warn('THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.');
  30559. return this.texture.wrapS;
  30560. },
  30561. set: function (value) {
  30562. console.warn('THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.');
  30563. this.texture.wrapS = value;
  30564. }
  30565. },
  30566. wrapT: {
  30567. get: function () {
  30568. console.warn('THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.');
  30569. return this.texture.wrapT;
  30570. },
  30571. set: function (value) {
  30572. console.warn('THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.');
  30573. this.texture.wrapT = value;
  30574. }
  30575. },
  30576. magFilter: {
  30577. get: function () {
  30578. console.warn('THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.');
  30579. return this.texture.magFilter;
  30580. },
  30581. set: function (value) {
  30582. console.warn('THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.');
  30583. this.texture.magFilter = value;
  30584. }
  30585. },
  30586. minFilter: {
  30587. get: function () {
  30588. console.warn('THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.');
  30589. return this.texture.minFilter;
  30590. },
  30591. set: function (value) {
  30592. console.warn('THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.');
  30593. this.texture.minFilter = value;
  30594. }
  30595. },
  30596. anisotropy: {
  30597. get: function () {
  30598. console.warn('THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.');
  30599. return this.texture.anisotropy;
  30600. },
  30601. set: function (value) {
  30602. console.warn('THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.');
  30603. this.texture.anisotropy = value;
  30604. }
  30605. },
  30606. offset: {
  30607. get: function () {
  30608. console.warn('THREE.WebGLRenderTarget: .offset is now .texture.offset.');
  30609. return this.texture.offset;
  30610. },
  30611. set: function (value) {
  30612. console.warn('THREE.WebGLRenderTarget: .offset is now .texture.offset.');
  30613. this.texture.offset = value;
  30614. }
  30615. },
  30616. repeat: {
  30617. get: function () {
  30618. console.warn('THREE.WebGLRenderTarget: .repeat is now .texture.repeat.');
  30619. return this.texture.repeat;
  30620. },
  30621. set: function (value) {
  30622. console.warn('THREE.WebGLRenderTarget: .repeat is now .texture.repeat.');
  30623. this.texture.repeat = value;
  30624. }
  30625. },
  30626. format: {
  30627. get: function () {
  30628. console.warn('THREE.WebGLRenderTarget: .format is now .texture.format.');
  30629. return this.texture.format;
  30630. },
  30631. set: function (value) {
  30632. console.warn('THREE.WebGLRenderTarget: .format is now .texture.format.');
  30633. this.texture.format = value;
  30634. }
  30635. },
  30636. type: {
  30637. get: function () {
  30638. console.warn('THREE.WebGLRenderTarget: .type is now .texture.type.');
  30639. return this.texture.type;
  30640. },
  30641. set: function (value) {
  30642. console.warn('THREE.WebGLRenderTarget: .type is now .texture.type.');
  30643. this.texture.type = value;
  30644. }
  30645. },
  30646. generateMipmaps: {
  30647. get: function () {
  30648. console.warn('THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.');
  30649. return this.texture.generateMipmaps;
  30650. },
  30651. set: function (value) {
  30652. console.warn('THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.');
  30653. this.texture.generateMipmaps = value;
  30654. }
  30655. }
  30656. }); //
  30657. Object.defineProperties(Audio.prototype, {
  30658. load: {
  30659. value: function (file) {
  30660. console.warn('THREE.Audio: .load has been deprecated. Use THREE.AudioLoader instead.');
  30661. const scope = this;
  30662. const audioLoader = new AudioLoader();
  30663. audioLoader.load(file, function (buffer) {
  30664. scope.setBuffer(buffer);
  30665. });
  30666. return this;
  30667. }
  30668. },
  30669. startTime: {
  30670. set: function () {
  30671. console.warn('THREE.Audio: .startTime is now .play( delay ).');
  30672. }
  30673. }
  30674. });
  30675. AudioAnalyser.prototype.getData = function () {
  30676. console.warn('THREE.AudioAnalyser: .getData() is now .getFrequencyData().');
  30677. return this.getFrequencyData();
  30678. }; //
  30679. CubeCamera.prototype.updateCubeMap = function (renderer, scene) {
  30680. console.warn('THREE.CubeCamera: .updateCubeMap() is now .update().');
  30681. return this.update(renderer, scene);
  30682. };
  30683. CubeCamera.prototype.clear = function (renderer, color, depth, stencil) {
  30684. console.warn('THREE.CubeCamera: .clear() is now .renderTarget.clear().');
  30685. return this.renderTarget.clear(renderer, color, depth, stencil);
  30686. }; //
  30687. const GeometryUtils = {
  30688. merge: function (geometry1, geometry2, materialIndexOffset) {
  30689. console.warn('THREE.GeometryUtils: .merge() has been moved to Geometry. Use geometry.merge( geometry2, matrix, materialIndexOffset ) instead.');
  30690. let matrix;
  30691. if (geometry2.isMesh) {
  30692. geometry2.matrixAutoUpdate && geometry2.updateMatrix();
  30693. matrix = geometry2.matrix;
  30694. geometry2 = geometry2.geometry;
  30695. }
  30696. geometry1.merge(geometry2, matrix, materialIndexOffset);
  30697. },
  30698. center: function (geometry) {
  30699. console.warn('THREE.GeometryUtils: .center() has been moved to Geometry. Use geometry.center() instead.');
  30700. return geometry.center();
  30701. }
  30702. };
  30703. exports.GeometryUtils = GeometryUtils;
  30704. ImageUtils.crossOrigin = undefined;
  30705. ImageUtils.loadTexture = function (url, mapping, onLoad, onError) {
  30706. console.warn('THREE.ImageUtils.loadTexture has been deprecated. Use THREE.TextureLoader() instead.');
  30707. const loader = new TextureLoader();
  30708. loader.setCrossOrigin(this.crossOrigin);
  30709. const texture = loader.load(url, onLoad, undefined, onError);
  30710. if (mapping) texture.mapping = mapping;
  30711. return texture;
  30712. };
  30713. ImageUtils.loadTextureCube = function (urls, mapping, onLoad, onError) {
  30714. console.warn('THREE.ImageUtils.loadTextureCube has been deprecated. Use THREE.CubeTextureLoader() instead.');
  30715. const loader = new CubeTextureLoader();
  30716. loader.setCrossOrigin(this.crossOrigin);
  30717. const texture = loader.load(urls, onLoad, undefined, onError);
  30718. if (mapping) texture.mapping = mapping;
  30719. return texture;
  30720. };
  30721. ImageUtils.loadCompressedTexture = function () {
  30722. console.error('THREE.ImageUtils.loadCompressedTexture has been removed. Use THREE.DDSLoader instead.');
  30723. };
  30724. ImageUtils.loadCompressedTextureCube = function () {
  30725. console.error('THREE.ImageUtils.loadCompressedTextureCube has been removed. Use THREE.DDSLoader instead.');
  30726. }; //
  30727. function CanvasRenderer() {
  30728. console.error('THREE.CanvasRenderer has been removed');
  30729. } //
  30730. function JSONLoader() {
  30731. console.error('THREE.JSONLoader has been removed.');
  30732. } //
  30733. const SceneUtils = {
  30734. createMultiMaterialObject: function ()
  30735. /* geometry, materials */
  30736. {
  30737. console.error('THREE.SceneUtils has been moved to /examples/jsm/utils/SceneUtils.js');
  30738. },
  30739. detach: function ()
  30740. /* child, parent, scene */
  30741. {
  30742. console.error('THREE.SceneUtils has been moved to /examples/jsm/utils/SceneUtils.js');
  30743. },
  30744. attach: function ()
  30745. /* child, scene, parent */
  30746. {
  30747. console.error('THREE.SceneUtils has been moved to /examples/jsm/utils/SceneUtils.js');
  30748. }
  30749. }; //
  30750. exports.SceneUtils = SceneUtils;
  30751. function LensFlare() {
  30752. console.error('THREE.LensFlare has been moved to /examples/jsm/objects/Lensflare.js');
  30753. }
  30754. if (typeof __THREE_DEVTOOLS__ !== 'undefined') {
  30755. /* eslint-disable no-undef */
  30756. __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent('register', {
  30757. detail: {
  30758. revision: REVISION
  30759. }
  30760. }));
  30761. /* eslint-enable no-undef */
  30762. }
  30763. },{}],"../node_modules/process/browser.js":[function(require,module,exports) {
  30764. // shim for using process in browser
  30765. var process = module.exports = {}; // cached from whatever global is present so that test runners that stub it
  30766. // don't break things. But we need to wrap it in a try catch in case it is
  30767. // wrapped in strict mode code which doesn't define any globals. It's inside a
  30768. // function because try/catches deoptimize in certain engines.
  30769. var cachedSetTimeout;
  30770. var cachedClearTimeout;
  30771. function defaultSetTimout() {
  30772. throw new Error('setTimeout has not been defined');
  30773. }
  30774. function defaultClearTimeout() {
  30775. throw new Error('clearTimeout has not been defined');
  30776. }
  30777. (function () {
  30778. try {
  30779. if (typeof setTimeout === 'function') {
  30780. cachedSetTimeout = setTimeout;
  30781. } else {
  30782. cachedSetTimeout = defaultSetTimout;
  30783. }
  30784. } catch (e) {
  30785. cachedSetTimeout = defaultSetTimout;
  30786. }
  30787. try {
  30788. if (typeof clearTimeout === 'function') {
  30789. cachedClearTimeout = clearTimeout;
  30790. } else {
  30791. cachedClearTimeout = defaultClearTimeout;
  30792. }
  30793. } catch (e) {
  30794. cachedClearTimeout = defaultClearTimeout;
  30795. }
  30796. })();
  30797. function runTimeout(fun) {
  30798. if (cachedSetTimeout === setTimeout) {
  30799. //normal enviroments in sane situations
  30800. return setTimeout(fun, 0);
  30801. } // if setTimeout wasn't available but was latter defined
  30802. if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
  30803. cachedSetTimeout = setTimeout;
  30804. return setTimeout(fun, 0);
  30805. }
  30806. try {
  30807. // when when somebody has screwed with setTimeout but no I.E. maddness
  30808. return cachedSetTimeout(fun, 0);
  30809. } catch (e) {
  30810. try {
  30811. // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
  30812. return cachedSetTimeout.call(null, fun, 0);
  30813. } catch (e) {
  30814. // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
  30815. return cachedSetTimeout.call(this, fun, 0);
  30816. }
  30817. }
  30818. }
  30819. function runClearTimeout(marker) {
  30820. if (cachedClearTimeout === clearTimeout) {
  30821. //normal enviroments in sane situations
  30822. return clearTimeout(marker);
  30823. } // if clearTimeout wasn't available but was latter defined
  30824. if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
  30825. cachedClearTimeout = clearTimeout;
  30826. return clearTimeout(marker);
  30827. }
  30828. try {
  30829. // when when somebody has screwed with setTimeout but no I.E. maddness
  30830. return cachedClearTimeout(marker);
  30831. } catch (e) {
  30832. try {
  30833. // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
  30834. return cachedClearTimeout.call(null, marker);
  30835. } catch (e) {
  30836. // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
  30837. // Some versions of I.E. have different rules for clearTimeout vs setTimeout
  30838. return cachedClearTimeout.call(this, marker);
  30839. }
  30840. }
  30841. }
  30842. var queue = [];
  30843. var draining = false;
  30844. var currentQueue;
  30845. var queueIndex = -1;
  30846. function cleanUpNextTick() {
  30847. if (!draining || !currentQueue) {
  30848. return;
  30849. }
  30850. draining = false;
  30851. if (currentQueue.length) {
  30852. queue = currentQueue.concat(queue);
  30853. } else {
  30854. queueIndex = -1;
  30855. }
  30856. if (queue.length) {
  30857. drainQueue();
  30858. }
  30859. }
  30860. function drainQueue() {
  30861. if (draining) {
  30862. return;
  30863. }
  30864. var timeout = runTimeout(cleanUpNextTick);
  30865. draining = true;
  30866. var len = queue.length;
  30867. while (len) {
  30868. currentQueue = queue;
  30869. queue = [];
  30870. while (++queueIndex < len) {
  30871. if (currentQueue) {
  30872. currentQueue[queueIndex].run();
  30873. }
  30874. }
  30875. queueIndex = -1;
  30876. len = queue.length;
  30877. }
  30878. currentQueue = null;
  30879. draining = false;
  30880. runClearTimeout(timeout);
  30881. }
  30882. process.nextTick = function (fun) {
  30883. var args = new Array(arguments.length - 1);
  30884. if (arguments.length > 1) {
  30885. for (var i = 1; i < arguments.length; i++) {
  30886. args[i - 1] = arguments[i];
  30887. }
  30888. }
  30889. queue.push(new Item(fun, args));
  30890. if (queue.length === 1 && !draining) {
  30891. runTimeout(drainQueue);
  30892. }
  30893. }; // v8 likes predictible objects
  30894. function Item(fun, array) {
  30895. this.fun = fun;
  30896. this.array = array;
  30897. }
  30898. Item.prototype.run = function () {
  30899. this.fun.apply(null, this.array);
  30900. };
  30901. process.title = 'browser';
  30902. process.env = {};
  30903. process.argv = [];
  30904. process.version = ''; // empty string to avoid regexp issues
  30905. process.versions = {};
  30906. function noop() {}
  30907. process.on = noop;
  30908. process.addListener = noop;
  30909. process.once = noop;
  30910. process.off = noop;
  30911. process.removeListener = noop;
  30912. process.removeAllListeners = noop;
  30913. process.emit = noop;
  30914. process.prependListener = noop;
  30915. process.prependOnceListener = noop;
  30916. process.listeners = function (name) {
  30917. return [];
  30918. };
  30919. process.binding = function (name) {
  30920. throw new Error('process.binding is not supported');
  30921. };
  30922. process.cwd = function () {
  30923. return '/';
  30924. };
  30925. process.chdir = function (dir) {
  30926. throw new Error('process.chdir is not supported');
  30927. };
  30928. process.umask = function () {
  30929. return 0;
  30930. };
  30931. },{}],"../node_modules/path-browserify/index.js":[function(require,module,exports) {
  30932. var process = require("process");
  30933. // .dirname, .basename, and .extname methods are extracted from Node.js v8.11.1,
  30934. // backported and transplited with Babel, with backwards-compat fixes
  30935. // Copyright Joyent, Inc. and other Node contributors.
  30936. //
  30937. // Permission is hereby granted, free of charge, to any person obtaining a
  30938. // copy of this software and associated documentation files (the
  30939. // "Software"), to deal in the Software without restriction, including
  30940. // without limitation the rights to use, copy, modify, merge, publish,
  30941. // distribute, sublicense, and/or sell copies of the Software, and to permit
  30942. // persons to whom the Software is furnished to do so, subject to the
  30943. // following conditions:
  30944. //
  30945. // The above copyright notice and this permission notice shall be included
  30946. // in all copies or substantial portions of the Software.
  30947. //
  30948. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  30949. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  30950. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  30951. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  30952. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  30953. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  30954. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  30955. // resolves . and .. elements in a path array with directory names there
  30956. // must be no slashes, empty elements, or device names (c:\) in the array
  30957. // (so also no leading and trailing slashes - it does not distinguish
  30958. // relative and absolute paths)
  30959. function normalizeArray(parts, allowAboveRoot) {
  30960. // if the path tries to go above the root, `up` ends up > 0
  30961. var up = 0;
  30962. for (var i = parts.length - 1; i >= 0; i--) {
  30963. var last = parts[i];
  30964. if (last === '.') {
  30965. parts.splice(i, 1);
  30966. } else if (last === '..') {
  30967. parts.splice(i, 1);
  30968. up++;
  30969. } else if (up) {
  30970. parts.splice(i, 1);
  30971. up--;
  30972. }
  30973. }
  30974. // if the path is allowed to go above the root, restore leading ..s
  30975. if (allowAboveRoot) {
  30976. for (; up--; up) {
  30977. parts.unshift('..');
  30978. }
  30979. }
  30980. return parts;
  30981. }
  30982. // path.resolve([from ...], to)
  30983. // posix version
  30984. exports.resolve = function() {
  30985. var resolvedPath = '',
  30986. resolvedAbsolute = false;
  30987. for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) {
  30988. var path = (i >= 0) ? arguments[i] : process.cwd();
  30989. // Skip empty and invalid entries
  30990. if (typeof path !== 'string') {
  30991. throw new TypeError('Arguments to path.resolve must be strings');
  30992. } else if (!path) {
  30993. continue;
  30994. }
  30995. resolvedPath = path + '/' + resolvedPath;
  30996. resolvedAbsolute = path.charAt(0) === '/';
  30997. }
  30998. // At this point the path should be resolved to a full absolute path, but
  30999. // handle relative paths to be safe (might happen when process.cwd() fails)
  31000. // Normalize the path
  31001. resolvedPath = normalizeArray(filter(resolvedPath.split('/'), function(p) {
  31002. return !!p;
  31003. }), !resolvedAbsolute).join('/');
  31004. return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.';
  31005. };
  31006. // path.normalize(path)
  31007. // posix version
  31008. exports.normalize = function(path) {
  31009. var isAbsolute = exports.isAbsolute(path),
  31010. trailingSlash = substr(path, -1) === '/';
  31011. // Normalize the path
  31012. path = normalizeArray(filter(path.split('/'), function(p) {
  31013. return !!p;
  31014. }), !isAbsolute).join('/');
  31015. if (!path && !isAbsolute) {
  31016. path = '.';
  31017. }
  31018. if (path && trailingSlash) {
  31019. path += '/';
  31020. }
  31021. return (isAbsolute ? '/' : '') + path;
  31022. };
  31023. // posix version
  31024. exports.isAbsolute = function(path) {
  31025. return path.charAt(0) === '/';
  31026. };
  31027. // posix version
  31028. exports.join = function() {
  31029. var paths = Array.prototype.slice.call(arguments, 0);
  31030. return exports.normalize(filter(paths, function(p, index) {
  31031. if (typeof p !== 'string') {
  31032. throw new TypeError('Arguments to path.join must be strings');
  31033. }
  31034. return p;
  31035. }).join('/'));
  31036. };
  31037. // path.relative(from, to)
  31038. // posix version
  31039. exports.relative = function(from, to) {
  31040. from = exports.resolve(from).substr(1);
  31041. to = exports.resolve(to).substr(1);
  31042. function trim(arr) {
  31043. var start = 0;
  31044. for (; start < arr.length; start++) {
  31045. if (arr[start] !== '') break;
  31046. }
  31047. var end = arr.length - 1;
  31048. for (; end >= 0; end--) {
  31049. if (arr[end] !== '') break;
  31050. }
  31051. if (start > end) return [];
  31052. return arr.slice(start, end - start + 1);
  31053. }
  31054. var fromParts = trim(from.split('/'));
  31055. var toParts = trim(to.split('/'));
  31056. var length = Math.min(fromParts.length, toParts.length);
  31057. var samePartsLength = length;
  31058. for (var i = 0; i < length; i++) {
  31059. if (fromParts[i] !== toParts[i]) {
  31060. samePartsLength = i;
  31061. break;
  31062. }
  31063. }
  31064. var outputParts = [];
  31065. for (var i = samePartsLength; i < fromParts.length; i++) {
  31066. outputParts.push('..');
  31067. }
  31068. outputParts = outputParts.concat(toParts.slice(samePartsLength));
  31069. return outputParts.join('/');
  31070. };
  31071. exports.sep = '/';
  31072. exports.delimiter = ':';
  31073. exports.dirname = function (path) {
  31074. if (typeof path !== 'string') path = path + '';
  31075. if (path.length === 0) return '.';
  31076. var code = path.charCodeAt(0);
  31077. var hasRoot = code === 47 /*/*/;
  31078. var end = -1;
  31079. var matchedSlash = true;
  31080. for (var i = path.length - 1; i >= 1; --i) {
  31081. code = path.charCodeAt(i);
  31082. if (code === 47 /*/*/) {
  31083. if (!matchedSlash) {
  31084. end = i;
  31085. break;
  31086. }
  31087. } else {
  31088. // We saw the first non-path separator
  31089. matchedSlash = false;
  31090. }
  31091. }
  31092. if (end === -1) return hasRoot ? '/' : '.';
  31093. if (hasRoot && end === 1) {
  31094. // return '//';
  31095. // Backwards-compat fix:
  31096. return '/';
  31097. }
  31098. return path.slice(0, end);
  31099. };
  31100. function basename(path) {
  31101. if (typeof path !== 'string') path = path + '';
  31102. var start = 0;
  31103. var end = -1;
  31104. var matchedSlash = true;
  31105. var i;
  31106. for (i = path.length - 1; i >= 0; --i) {
  31107. if (path.charCodeAt(i) === 47 /*/*/) {
  31108. // If we reached a path separator that was not part of a set of path
  31109. // separators at the end of the string, stop now
  31110. if (!matchedSlash) {
  31111. start = i + 1;
  31112. break;
  31113. }
  31114. } else if (end === -1) {
  31115. // We saw the first non-path separator, mark this as the end of our
  31116. // path component
  31117. matchedSlash = false;
  31118. end = i + 1;
  31119. }
  31120. }
  31121. if (end === -1) return '';
  31122. return path.slice(start, end);
  31123. }
  31124. // Uses a mixed approach for backwards-compatibility, as ext behavior changed
  31125. // in new Node.js versions, so only basename() above is backported here
  31126. exports.basename = function (path, ext) {
  31127. var f = basename(path);
  31128. if (ext && f.substr(-1 * ext.length) === ext) {
  31129. f = f.substr(0, f.length - ext.length);
  31130. }
  31131. return f;
  31132. };
  31133. exports.extname = function (path) {
  31134. if (typeof path !== 'string') path = path + '';
  31135. var startDot = -1;
  31136. var startPart = 0;
  31137. var end = -1;
  31138. var matchedSlash = true;
  31139. // Track the state of characters (if any) we see before our first dot and
  31140. // after any path separator we find
  31141. var preDotState = 0;
  31142. for (var i = path.length - 1; i >= 0; --i) {
  31143. var code = path.charCodeAt(i);
  31144. if (code === 47 /*/*/) {
  31145. // If we reached a path separator that was not part of a set of path
  31146. // separators at the end of the string, stop now
  31147. if (!matchedSlash) {
  31148. startPart = i + 1;
  31149. break;
  31150. }
  31151. continue;
  31152. }
  31153. if (end === -1) {
  31154. // We saw the first non-path separator, mark this as the end of our
  31155. // extension
  31156. matchedSlash = false;
  31157. end = i + 1;
  31158. }
  31159. if (code === 46 /*.*/) {
  31160. // If this is our first dot, mark it as the start of our extension
  31161. if (startDot === -1)
  31162. startDot = i;
  31163. else if (preDotState !== 1)
  31164. preDotState = 1;
  31165. } else if (startDot !== -1) {
  31166. // We saw a non-dot and non-path separator before our dot, so we should
  31167. // have a good chance at having a non-empty extension
  31168. preDotState = -1;
  31169. }
  31170. }
  31171. if (startDot === -1 || end === -1 ||
  31172. // We saw a non-dot character immediately before the dot
  31173. preDotState === 0 ||
  31174. // The (right-most) trimmed path component is exactly '..'
  31175. preDotState === 1 && startDot === end - 1 && startDot === startPart + 1) {
  31176. return '';
  31177. }
  31178. return path.slice(startDot, end);
  31179. };
  31180. function filter (xs, f) {
  31181. if (xs.filter) return xs.filter(f);
  31182. var res = [];
  31183. for (var i = 0; i < xs.length; i++) {
  31184. if (f(xs[i], i, xs)) res.push(xs[i]);
  31185. }
  31186. return res;
  31187. }
  31188. // String.prototype.substr - negative index don't work in IE8
  31189. var substr = 'ab'.substr(-1) === 'b'
  31190. ? function (str, start, len) { return str.substr(start, len) }
  31191. : function (str, start, len) {
  31192. if (start < 0) start = str.length + start;
  31193. return str.substr(start, len);
  31194. }
  31195. ;
  31196. },{"process":"../node_modules/process/browser.js"}],"../src/utilities/urlJoin.js":[function(require,module,exports) {
  31197. "use strict";
  31198. Object.defineProperty(exports, "__esModule", {
  31199. value: true
  31200. });
  31201. exports.urlJoin = urlJoin;
  31202. var _path = _interopRequireDefault(require("path"));
  31203. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  31204. function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread(); }
  31205. function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance"); }
  31206. function _iterableToArray(iter) { if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter); }
  31207. function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } }
  31208. // Function that properly handles path resolution for parts that have
  31209. // a protocol component like "http://".
  31210. function urlJoin() {
  31211. var protocolRegex = /^[a-zA-Z]+:\/\//;
  31212. var lastRoot = -1;
  31213. for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
  31214. args[_key] = arguments[_key];
  31215. }
  31216. for (var i = 0, l = args.length; i < l; i++) {
  31217. if (protocolRegex.test(args[i])) {
  31218. lastRoot = i;
  31219. }
  31220. }
  31221. if (lastRoot === -1) {
  31222. return _path.default.join.apply(_path.default, args).replace(/\\/g, '/');
  31223. } else {
  31224. var parts = lastRoot <= 0 ? args : args.slice(lastRoot);
  31225. var protocol = parts[0].match(protocolRegex)[0];
  31226. parts[0] = parts[0].substring(protocol.length);
  31227. return (protocol + _path.default.join.apply(_path.default, _toConsumableArray(parts))).replace(/\\/g, '/');
  31228. }
  31229. }
  31230. },{"path":"../node_modules/path-browserify/index.js"}],"../src/utilities/LRUCache.js":[function(require,module,exports) {
  31231. "use strict";
  31232. Object.defineProperty(exports, "__esModule", {
  31233. value: true
  31234. });
  31235. exports.LRUCache = void 0;
  31236. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  31237. function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
  31238. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
  31239. // Fires at the end of the frame and before the next one
  31240. function enqueueMicrotask(callback) {
  31241. Promise.resolve().then(callback);
  31242. }
  31243. var LRUCache =
  31244. /*#__PURE__*/
  31245. function () {
  31246. function LRUCache() {
  31247. _classCallCheck(this, LRUCache);
  31248. // options
  31249. this.maxSize = 800;
  31250. this.minSize = 600;
  31251. this.unloadPercent = 0.05; // "itemSet" doubles as both the list of the full set of items currently
  31252. // stored in the cache (keys) as well as a map to the time the item was last
  31253. // used so it can be sorted appropriately.
  31254. this.itemSet = new Map();
  31255. this.itemList = [];
  31256. this.usedSet = new Set();
  31257. this.callbacks = new Map();
  31258. this.unloadPriorityCallback = null;
  31259. var itemSet = this.itemSet;
  31260. this.defaultPriorityCallback = function (item) {
  31261. return itemSet.get(item);
  31262. };
  31263. } // Returns whether or not the cache has reached the maximum size
  31264. _createClass(LRUCache, [{
  31265. key: "isFull",
  31266. value: function isFull() {
  31267. return this.itemSet.size >= this.maxSize;
  31268. }
  31269. }, {
  31270. key: "add",
  31271. value: function add(item, removeCb) {
  31272. var itemSet = this.itemSet;
  31273. if (itemSet.has(item)) {
  31274. return false;
  31275. }
  31276. if (this.isFull()) {
  31277. return false;
  31278. }
  31279. var usedSet = this.usedSet;
  31280. var itemList = this.itemList;
  31281. var callbacks = this.callbacks;
  31282. itemList.push(item);
  31283. usedSet.add(item);
  31284. itemSet.set(item, Date.now());
  31285. callbacks.set(item, removeCb);
  31286. return true;
  31287. }
  31288. }, {
  31289. key: "remove",
  31290. value: function remove(item) {
  31291. var usedSet = this.usedSet;
  31292. var itemSet = this.itemSet;
  31293. var itemList = this.itemList;
  31294. var callbacks = this.callbacks;
  31295. if (itemSet.has(item)) {
  31296. callbacks.get(item)(item);
  31297. var index = itemList.indexOf(item);
  31298. itemList.splice(index, 1);
  31299. usedSet.delete(item);
  31300. itemSet.delete(item);
  31301. callbacks.delete(item);
  31302. return true;
  31303. }
  31304. return false;
  31305. }
  31306. }, {
  31307. key: "markUsed",
  31308. value: function markUsed(item) {
  31309. var itemSet = this.itemSet;
  31310. var usedSet = this.usedSet;
  31311. if (itemSet.has(item) && !usedSet.has(item)) {
  31312. itemSet.set(item, Date.now());
  31313. usedSet.add(item);
  31314. }
  31315. }
  31316. }, {
  31317. key: "markAllUnused",
  31318. value: function markAllUnused() {
  31319. this.usedSet.clear();
  31320. } // TODO: this should be renamed because it's not necessarily unloading all unused content
  31321. // Maybe call it "cleanup" or "unloadToMinSize"
  31322. }, {
  31323. key: "unloadUnusedContent",
  31324. value: function unloadUnusedContent() {
  31325. var unloadPercent = this.unloadPercent;
  31326. var targetSize = this.minSize;
  31327. var itemList = this.itemList;
  31328. var itemSet = this.itemSet;
  31329. var usedSet = this.usedSet;
  31330. var callbacks = this.callbacks;
  31331. var unused = itemList.length - usedSet.size;
  31332. var excess = itemList.length - targetSize;
  31333. var unloadPriorityCallback = this.unloadPriorityCallback || this.defaultPriorityCallback;
  31334. if (excess > 0 && unused > 0) {
  31335. // used items should be at the end of the array
  31336. itemList.sort(function (a, b) {
  31337. var usedA = usedSet.has(a);
  31338. var usedB = usedSet.has(b);
  31339. if (usedA && usedB) {
  31340. // If they're both used then don't bother moving them
  31341. return 0;
  31342. } else if (!usedA && !usedB) {
  31343. // Use the sort function otherwise
  31344. // higher priority should be further to the left
  31345. return unloadPriorityCallback(b) - unloadPriorityCallback(a);
  31346. } else {
  31347. // If one is used and the other is not move the used one towards the end of the array
  31348. return usedA ? 1 : -1;
  31349. }
  31350. }); // address corner cases where the minSize might be zero or smaller than maxSize - minSize,
  31351. // which would result in a very small or no items being unloaded.
  31352. var unusedExcess = Math.min(excess, unused);
  31353. var maxUnload = Math.max(targetSize * unloadPercent, unusedExcess * unloadPercent);
  31354. var nodesToUnload = Math.min(maxUnload, unused);
  31355. nodesToUnload = Math.ceil(nodesToUnload);
  31356. var removedItems = itemList.splice(0, nodesToUnload);
  31357. for (var i = 0, l = removedItems.length; i < l; i++) {
  31358. var item = removedItems[i];
  31359. callbacks.get(item)(item);
  31360. itemSet.delete(item);
  31361. callbacks.delete(item);
  31362. }
  31363. }
  31364. }
  31365. }, {
  31366. key: "scheduleUnload",
  31367. value: function scheduleUnload() {
  31368. var _this = this;
  31369. var markAllUnused = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;
  31370. if (!this.scheduled) {
  31371. this.scheduled = true;
  31372. enqueueMicrotask(function () {
  31373. _this.scheduled = false;
  31374. _this.unloadUnusedContent();
  31375. if (markAllUnused) {
  31376. _this.markAllUnused();
  31377. }
  31378. });
  31379. }
  31380. }
  31381. }]);
  31382. return LRUCache;
  31383. }();
  31384. exports.LRUCache = LRUCache;
  31385. },{}],"../src/utilities/PriorityQueue.js":[function(require,module,exports) {
  31386. "use strict";
  31387. Object.defineProperty(exports, "__esModule", {
  31388. value: true
  31389. });
  31390. exports.PriorityQueue = void 0;
  31391. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  31392. function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
  31393. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
  31394. var PriorityQueue =
  31395. /*#__PURE__*/
  31396. function () {
  31397. function PriorityQueue() {
  31398. _classCallCheck(this, PriorityQueue);
  31399. // options
  31400. this.maxJobs = 6;
  31401. this.items = [];
  31402. this.callbacks = new Map();
  31403. this.currJobs = 0;
  31404. this.scheduled = false;
  31405. this.autoUpdate = true;
  31406. this.priorityCallback = function () {
  31407. throw new Error('PriorityQueue: PriorityCallback function not defined.');
  31408. };
  31409. }
  31410. _createClass(PriorityQueue, [{
  31411. key: "sort",
  31412. value: function sort() {
  31413. var priorityCallback = this.priorityCallback;
  31414. var items = this.items;
  31415. items.sort(function (a, b) {
  31416. return priorityCallback(a) - priorityCallback(b);
  31417. });
  31418. }
  31419. }, {
  31420. key: "add",
  31421. value: function add(item, callback) {
  31422. var _this = this;
  31423. return new Promise(function (resolve, reject) {
  31424. var prCallback = function prCallback() {
  31425. return callback.apply(void 0, arguments).then(resolve).catch(reject);
  31426. };
  31427. var items = _this.items;
  31428. var callbacks = _this.callbacks;
  31429. items.push(item);
  31430. callbacks.set(item, prCallback);
  31431. if (_this.autoUpdate) {
  31432. _this.scheduleJobRun();
  31433. }
  31434. });
  31435. }
  31436. }, {
  31437. key: "remove",
  31438. value: function remove(item) {
  31439. var items = this.items;
  31440. var callbacks = this.callbacks;
  31441. var index = items.indexOf(item);
  31442. if (index !== -1) {
  31443. items.splice(index, 1);
  31444. callbacks.delete(item);
  31445. }
  31446. }
  31447. }, {
  31448. key: "tryRunJobs",
  31449. value: function tryRunJobs() {
  31450. var _this2 = this;
  31451. this.sort();
  31452. var items = this.items;
  31453. var callbacks = this.callbacks;
  31454. var maxJobs = this.maxJobs;
  31455. var currJobs = this.currJobs;
  31456. while (maxJobs > currJobs && items.length > 0) {
  31457. currJobs++;
  31458. var item = items.pop();
  31459. var callback = callbacks.get(item);
  31460. callbacks.delete(item);
  31461. callback(item).then(function () {
  31462. _this2.currJobs--;
  31463. if (_this2.autoUpdate) {
  31464. _this2.scheduleJobRun();
  31465. }
  31466. }).catch(function () {
  31467. _this2.currJobs--;
  31468. if (_this2.autoUpdate) {
  31469. _this2.scheduleJobRun();
  31470. }
  31471. });
  31472. }
  31473. this.currJobs = currJobs;
  31474. }
  31475. }, {
  31476. key: "scheduleJobRun",
  31477. value: function scheduleJobRun() {
  31478. var _this3 = this;
  31479. if (!this.scheduled) {
  31480. requestAnimationFrame(function () {
  31481. _this3.tryRunJobs();
  31482. _this3.scheduled = false;
  31483. });
  31484. this.scheduled = true;
  31485. }
  31486. }
  31487. }]);
  31488. return PriorityQueue;
  31489. }();
  31490. exports.PriorityQueue = PriorityQueue;
  31491. },{}],"../src/base/constants.js":[function(require,module,exports) {
  31492. "use strict";
  31493. Object.defineProperty(exports, "__esModule", {
  31494. value: true
  31495. });
  31496. exports.FAILED = exports.LOADED = exports.PARSING = exports.LOADING = exports.UNLOADED = void 0;
  31497. var UNLOADED = 0;
  31498. exports.UNLOADED = UNLOADED;
  31499. var LOADING = 1;
  31500. exports.LOADING = LOADING;
  31501. var PARSING = 2;
  31502. exports.PARSING = PARSING;
  31503. var LOADED = 3;
  31504. exports.LOADED = LOADED;
  31505. var FAILED = 4;
  31506. exports.FAILED = FAILED;
  31507. },{}],"../src/base/traverseFunctions.js":[function(require,module,exports) {
  31508. "use strict";
  31509. Object.defineProperty(exports, "__esModule", {
  31510. value: true
  31511. });
  31512. exports.traverseSet = traverseSet;
  31513. exports.determineFrustumSet = determineFrustumSet;
  31514. exports.markUsedSetLeaves = markUsedSetLeaves;
  31515. exports.skipTraversal = skipTraversal;
  31516. exports.toggleTiles = toggleTiles;
  31517. var _constants = require("./constants.js");
  31518. function isDownloadFinished(value) {
  31519. return value === _constants.LOADED || value === _constants.FAILED;
  31520. } // Checks whether this tile was last used on the given frame.
  31521. function isUsedThisFrame(tile, frameCount) {
  31522. return tile.__lastFrameVisited === frameCount && tile.__used;
  31523. } // Resets the frame frame information for the given tile
  31524. function resetFrameState(tile, frameCount) {
  31525. if (tile.__lastFrameVisited !== frameCount) {
  31526. tile.__lastFrameVisited = frameCount;
  31527. tile.__used = false;
  31528. tile.__inFrustum = false;
  31529. tile.__isLeaf = false;
  31530. tile.__visible = false;
  31531. tile.__active = false;
  31532. tile.__error = 0;
  31533. tile.__childrenWereVisible = false;
  31534. tile.__allChildrenLoaded = false;
  31535. }
  31536. } // Recursively mark tiles used down to the next tile with content
  31537. function recursivelyMarkUsed(tile, frameCount, lruCache) {
  31538. resetFrameState(tile, frameCount);
  31539. tile.__used = true;
  31540. lruCache.markUsed(tile);
  31541. if (tile.__contentEmpty) {
  31542. var children = tile.children;
  31543. for (var i = 0, l = children.length; i < l; i++) {
  31544. recursivelyMarkUsed(children[i], frameCount, lruCache);
  31545. }
  31546. }
  31547. }
  31548. function recursivelyLoadTiles(tile, depthFromRenderedParent, renderer) {
  31549. // Try to load any external tile set children if the external tile set has loaded.
  31550. var doTraverse = tile.__contentEmpty && (!tile.__externalTileSet || isDownloadFinished(tile.__loadingState));
  31551. if (doTraverse) {
  31552. var children = tile.children;
  31553. for (var i = 0, l = children.length; i < l; i++) {
  31554. // don't increment depth to rendered parent here because we should treat
  31555. // the next layer of rendered children as just a single depth away for the
  31556. // sake of sorting.
  31557. var child = children[i];
  31558. child.__depthFromRenderedParent = depthFromRenderedParent;
  31559. recursivelyLoadTiles(child, depthFromRenderedParent, renderer);
  31560. }
  31561. } else {
  31562. renderer.requestTileContents(tile);
  31563. }
  31564. } // Helper function for recursively traversing a tile set. If `beforeCb` returns `true` then the
  31565. // traversal will end early.
  31566. function traverseSet(tile) {
  31567. var beforeCb = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
  31568. var afterCb = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
  31569. var parent = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null;
  31570. var depth = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 0;
  31571. if (beforeCb && beforeCb(tile, parent, depth)) {
  31572. if (afterCb) {
  31573. afterCb(tile, parent, depth);
  31574. }
  31575. return;
  31576. }
  31577. var children = tile.children;
  31578. for (var i = 0, l = children.length; i < l; i++) {
  31579. traverseSet(children[i], beforeCb, afterCb, tile, depth + 1);
  31580. }
  31581. if (afterCb) {
  31582. afterCb(tile, parent, depth);
  31583. }
  31584. } // Determine which tiles are within the camera frustum.
  31585. // TODO: this is marking items as used in the lrucache, which means some data is
  31586. // being kept around that isn't being used -- is that okay?
  31587. function determineFrustumSet(tile, renderer) {
  31588. var stats = renderer.stats;
  31589. var frameCount = renderer.frameCount;
  31590. var errorTarget = renderer.errorTarget;
  31591. var maxDepth = renderer.maxDepth;
  31592. var loadSiblings = renderer.loadSiblings;
  31593. var lruCache = renderer.lruCache;
  31594. var stopAtEmptyTiles = renderer.stopAtEmptyTiles;
  31595. resetFrameState(tile, frameCount); // Early out if this tile is not within view.
  31596. var inFrustum = renderer.tileInView(tile);
  31597. if (inFrustum === false) {
  31598. return false;
  31599. }
  31600. tile.__used = true;
  31601. lruCache.markUsed(tile);
  31602. tile.__inFrustum = true;
  31603. stats.inFrustum++; // Early out if this tile has less error than we're targeting but don't stop
  31604. // at an external tile set.
  31605. if ((stopAtEmptyTiles || !tile.__contentEmpty) && !tile.__externalTileSet) {
  31606. var error = renderer.calculateError(tile);
  31607. tile.__error = error;
  31608. if (error <= errorTarget) {
  31609. return true;
  31610. } // Early out if we've reached the maximum allowed depth.
  31611. if (renderer.maxDepth > 0 && tile.__depth + 1 >= maxDepth) {
  31612. return true;
  31613. }
  31614. } // Traverse children and see if any children are in view.
  31615. var anyChildrenUsed = false;
  31616. var children = tile.children;
  31617. for (var i = 0, l = children.length; i < l; i++) {
  31618. var c = children[i];
  31619. var r = determineFrustumSet(c, renderer);
  31620. anyChildrenUsed = anyChildrenUsed || r;
  31621. } // If there are children within view and we are loading siblings then mark
  31622. // all sibling tiles as used, as well.
  31623. if (anyChildrenUsed && loadSiblings) {
  31624. for (var _i = 0, _l = children.length; _i < _l; _i++) {
  31625. var _c = children[_i];
  31626. recursivelyMarkUsed(_c, frameCount, lruCache);
  31627. }
  31628. }
  31629. return true;
  31630. } // Traverse and mark the tiles that are at the leaf nodes of the "used" tree.
  31631. function markUsedSetLeaves(tile, renderer) {
  31632. var stats = renderer.stats;
  31633. var frameCount = renderer.frameCount;
  31634. if (!isUsedThisFrame(tile, frameCount)) {
  31635. return;
  31636. }
  31637. stats.used++; // This tile is a leaf if none of the children had been used.
  31638. var children = tile.children;
  31639. var anyChildrenUsed = false;
  31640. for (var i = 0, l = children.length; i < l; i++) {
  31641. var c = children[i];
  31642. anyChildrenUsed = anyChildrenUsed || isUsedThisFrame(c, frameCount);
  31643. }
  31644. if (!anyChildrenUsed) {
  31645. // TODO: This isn't necessarily right because it's possible that a parent tile is considered in the
  31646. // frustum while the child tiles are not, making them unused. If all children have loaded and were properly
  31647. // considered to be in the used set then we shouldn't set ourselves to a leaf here.
  31648. tile.__isLeaf = true;
  31649. } else {
  31650. var childrenWereVisible = false;
  31651. var allChildrenLoaded = true;
  31652. for (var _i2 = 0, _l2 = children.length; _i2 < _l2; _i2++) {
  31653. var _c2 = children[_i2];
  31654. markUsedSetLeaves(_c2, renderer);
  31655. childrenWereVisible = childrenWereVisible || _c2.__wasSetVisible || _c2.__childrenWereVisible;
  31656. if (isUsedThisFrame(_c2, frameCount)) {
  31657. var childLoaded = _c2.__allChildrenLoaded || !_c2.__contentEmpty && isDownloadFinished(_c2.__loadingState) || _c2.__externalTileSet && _c2.__loadingState === _constants.FAILED;
  31658. allChildrenLoaded = allChildrenLoaded && childLoaded;
  31659. }
  31660. }
  31661. tile.__childrenWereVisible = childrenWereVisible;
  31662. tile.__allChildrenLoaded = allChildrenLoaded;
  31663. }
  31664. } // Skip past tiles we consider unrenderable because they are outside the error threshold.
  31665. function skipTraversal(tile, renderer) {
  31666. var stats = renderer.stats;
  31667. var frameCount = renderer.frameCount;
  31668. if (!isUsedThisFrame(tile, frameCount)) {
  31669. return;
  31670. }
  31671. var parent = tile.parent;
  31672. var parentDepthToParent = parent ? parent.__depthFromRenderedParent : -1;
  31673. tile.__depthFromRenderedParent = parentDepthToParent; // Request the tile contents or mark it as visible if we've found a leaf.
  31674. var lruCache = renderer.lruCache;
  31675. if (tile.__isLeaf) {
  31676. tile.__depthFromRenderedParent++;
  31677. if (tile.__loadingState === _constants.LOADED) {
  31678. if (tile.__inFrustum) {
  31679. tile.__visible = true;
  31680. stats.visible++;
  31681. }
  31682. tile.__active = true;
  31683. stats.active++;
  31684. } else if (!lruCache.isFull() && (!tile.__contentEmpty || tile.__externalTileSet)) {
  31685. renderer.requestTileContents(tile);
  31686. }
  31687. return;
  31688. }
  31689. var errorRequirement = (renderer.errorTarget + 1) * renderer.errorThreshold;
  31690. var meetsSSE = tile.__error <= errorRequirement;
  31691. var includeTile = meetsSSE || tile.refine === 'ADD';
  31692. var hasModel = !tile.__contentEmpty;
  31693. var hasContent = hasModel || tile.__externalTileSet;
  31694. var loadedContent = isDownloadFinished(tile.__loadingState) && hasContent;
  31695. var childrenWereVisible = tile.__childrenWereVisible;
  31696. var children = tile.children;
  31697. var allChildrenHaveContent = tile.__allChildrenLoaded; // Increment the relative depth of the node to the nearest rendered parent if it has content
  31698. // and is being rendered.
  31699. if (includeTile && hasModel) {
  31700. tile.__depthFromRenderedParent++;
  31701. } // If we've met the SSE requirements and we can load content then fire a fetch.
  31702. if (includeTile && !loadedContent && !lruCache.isFull() && hasContent) {
  31703. renderer.requestTileContents(tile);
  31704. } // Only mark this tile as visible if it meets the screen space error requirements, has loaded content, not
  31705. // all children have loaded yet, and if no children were visible last frame. We want to keep children visible
  31706. // that _were_ visible to avoid a pop in level of detail as the camera moves around and parent / sibling tiles
  31707. // load in.
  31708. // Skip the tile entirely if there's no content to load
  31709. if (meetsSSE && !allChildrenHaveContent && !childrenWereVisible && loadedContent || tile.refine === 'ADD' && loadedContent) {
  31710. if (tile.__inFrustum) {
  31711. tile.__visible = true;
  31712. stats.visible++;
  31713. }
  31714. tile.__active = true;
  31715. stats.active++;
  31716. } // If we're additive then don't stop the traversal here because it doesn't matter whether the children load in
  31717. // at the same rate.
  31718. if (tile.refine !== 'ADD' && meetsSSE && !allChildrenHaveContent && loadedContent) {
  31719. // load the child content if we've found that we've been loaded so we can move down to the next tile
  31720. // layer when the data has loaded.
  31721. for (var i = 0, l = children.length; i < l; i++) {
  31722. var c = children[i];
  31723. if (isUsedThisFrame(c, frameCount) && !lruCache.isFull()) {
  31724. c.__depthFromRenderedParent = tile.__depthFromRenderedParent + 1;
  31725. recursivelyLoadTiles(c, c.__depthFromRenderedParent, renderer);
  31726. }
  31727. }
  31728. } else {
  31729. for (var _i3 = 0, _l3 = children.length; _i3 < _l3; _i3++) {
  31730. var _c3 = children[_i3];
  31731. if (isUsedThisFrame(_c3, frameCount)) {
  31732. skipTraversal(_c3, renderer);
  31733. }
  31734. }
  31735. }
  31736. } // Final traverse to toggle tile visibility.
  31737. function toggleTiles(tile, renderer) {
  31738. var frameCount = renderer.frameCount;
  31739. var isUsed = isUsedThisFrame(tile, frameCount);
  31740. if (isUsed || tile.__usedLastFrame) {
  31741. var setActive = false;
  31742. var setVisible = false;
  31743. if (isUsed) {
  31744. // enable visibility if active due to shadows
  31745. setActive = tile.__active;
  31746. if (renderer.displayActiveTiles) {
  31747. setVisible = tile.__active || tile.__visible;
  31748. } else {
  31749. setVisible = tile.__visible;
  31750. }
  31751. } // If the active or visible state changed then call the functions.
  31752. if (!tile.__contentEmpty && tile.__loadingState === _constants.LOADED) {
  31753. if (tile.__wasSetActive !== setActive) {
  31754. renderer.setTileActive(tile, setActive);
  31755. }
  31756. if (tile.__wasSetVisible !== setVisible) {
  31757. renderer.setTileVisible(tile, setVisible);
  31758. }
  31759. }
  31760. tile.__wasSetActive = setActive;
  31761. tile.__wasSetVisible = setVisible;
  31762. tile.__usedLastFrame = isUsed;
  31763. var children = tile.children;
  31764. for (var i = 0, l = children.length; i < l; i++) {
  31765. var c = children[i];
  31766. toggleTiles(c, renderer);
  31767. }
  31768. }
  31769. }
  31770. },{"./constants.js":"../src/base/constants.js"}],"../src/base/TilesRendererBase.js":[function(require,module,exports) {
  31771. "use strict";
  31772. Object.defineProperty(exports, "__esModule", {
  31773. value: true
  31774. });
  31775. exports.TilesRendererBase = void 0;
  31776. var _path = _interopRequireDefault(require("path"));
  31777. var _urlJoin = require("../utilities/urlJoin.js");
  31778. var _LRUCache = require("../utilities/LRUCache.js");
  31779. var _PriorityQueue = require("../utilities/PriorityQueue.js");
  31780. var _traverseFunctions = require("./traverseFunctions.js");
  31781. var _constants = require("./constants.js");
  31782. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  31783. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  31784. function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
  31785. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
  31786. // Function for sorting the evicted LRU items. We should evict the shallowest depth first.
  31787. var priorityCallback = function priorityCallback(tile) {
  31788. return 1 / (tile.__depthFromRenderedParent + 1);
  31789. };
  31790. var defaultIonToken = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiJlNzMyOGZjZC1jMWUzLTQxNDctOGQxYi03YTYyZDQ1OTIxMjkiLCJpZCI6MjU5LCJpYXQiOjE2MDE1Njk1NDN9.X1a0DCM6F539g9MDSs_ldZ0gwgruxLAZiBl60JwG1ck';
  31791. var TilesRendererBase =
  31792. /*#__PURE__*/
  31793. function () {
  31794. _createClass(TilesRendererBase, [{
  31795. key: "rootTileSet",
  31796. get: function get() {
  31797. var tileSet = this.tileSets[this.rootURL];
  31798. if (!tileSet || tileSet instanceof Promise) {
  31799. return null;
  31800. } else {
  31801. return tileSet;
  31802. }
  31803. }
  31804. }, {
  31805. key: "root",
  31806. get: function get() {
  31807. var tileSet = this.rootTileSet;
  31808. return tileSet ? tileSet.root : null;
  31809. } //The url can be:
  31810. //A plain url to the tileset json file
  31811. //A Cesium Ion asset number with access token
  31812. //A url to the Cesium Ion json file with bearer token as the ionAccessToken. This needs to be fetched from the Ion endpoint separately
  31813. }]);
  31814. function TilesRendererBase(url) {
  31815. var ionAccessToken = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : defaultIonToken;
  31816. _classCallCheck(this, TilesRendererBase);
  31817. // state
  31818. this.tileSets = {};
  31819. this.fetchOptions = {};
  31820. this.setupUrlTokens(url, ionAccessToken);
  31821. var lruCache = new _LRUCache.LRUCache();
  31822. lruCache.unloadPriorityCallback = priorityCallback;
  31823. var downloadQueue = new _PriorityQueue.PriorityQueue();
  31824. downloadQueue.maxJobs = 4;
  31825. downloadQueue.priorityCallback = priorityCallback;
  31826. var parseQueue = new _PriorityQueue.PriorityQueue();
  31827. parseQueue.maxJobs = 1;
  31828. parseQueue.priorityCallback = priorityCallback;
  31829. this.lruCache = lruCache;
  31830. this.downloadQueue = downloadQueue;
  31831. this.parseQueue = parseQueue;
  31832. this.stats = {
  31833. parsing: 0,
  31834. downloading: 0,
  31835. failed: 0,
  31836. inFrustum: 0,
  31837. used: 0,
  31838. active: 0,
  31839. visible: 0
  31840. };
  31841. this.frameCount = 0; // options
  31842. this.errorTarget = 6.0;
  31843. this.errorThreshold = Infinity;
  31844. this.loadSiblings = true;
  31845. this.displayActiveTiles = false;
  31846. this.maxDepth = Infinity;
  31847. this.stopAtEmptyTiles = true;
  31848. }
  31849. _createClass(TilesRendererBase, [{
  31850. key: "setupUrlTokens",
  31851. value: function setupUrlTokens(url, ionToken) {
  31852. this.ionAssetId = this.isInt(url) ? url : null;
  31853. this.ionAccessToken = ionToken;
  31854. this.fetchOptions.headers = {};
  31855. if (!this.ionAssetId) {
  31856. this.rootURL = url;
  31857. if (this.isIonJsonUrl(url)) {
  31858. this.ionAssetId = url.split("/")[3];
  31859. this.ionJsonUrl = new URL(url);
  31860. this.ionVersion = this.ionJsonUrl.searchParams.get('v');
  31861. this.fetchOptions.headers.Authorization = "Bearer ".concat(ionToken);
  31862. this.rootURL = this.ionJsonUrl;
  31863. }
  31864. return;
  31865. } else {
  31866. this.ionEndpointUrl = new URL("https://api.cesium.com/v1/assets/".concat(this.ionAssetId, "/endpoint"));
  31867. this.ionEndpointUrl.searchParams.append('access_token', ionToken);
  31868. }
  31869. }
  31870. }, {
  31871. key: "isInt",
  31872. value: function isInt(input) {
  31873. return typeof input === 'string' ? !isNaN(input) && !isNaN(parseFloat(input, 10)) && Number.isInteger(parseFloat(input, 10)) : Number.isInteger(input);
  31874. }
  31875. }, {
  31876. key: "isIonJsonUrl",
  31877. value: function isIonJsonUrl(input) {
  31878. return input.includes('://assets.cesium.com/') && input.includes('/tileset.json');
  31879. }
  31880. }, {
  31881. key: "getIonAssetJson",
  31882. value: function getIonAssetJson(url) {
  31883. var _this = this;
  31884. return fetch(url, this.fetchOptions).then(function (res) {
  31885. if (res.ok) {
  31886. return res.json();
  31887. } else {
  31888. return Promise.reject("".concat(res.status, " : ").concat(res.statusText));
  31889. }
  31890. }).then(function (json) {
  31891. _this.ionJsonUrl = new URL(json.url);
  31892. _this.ionVersion = _this.ionJsonUrl.searchParams.get('v');
  31893. _this.fetchOptions.headers.Authorization = "Bearer ".concat(json.accessToken);
  31894. _this.rootURL = _this.ionJsonUrl;
  31895. });
  31896. }
  31897. }, {
  31898. key: "traverse",
  31899. value: function traverse(beforecb, aftercb) {
  31900. var tileSets = this.tileSets;
  31901. var rootTileSet = tileSets[this.rootURL];
  31902. if (!rootTileSet || !rootTileSet.root) return;
  31903. (0, _traverseFunctions.traverseSet)(rootTileSet.root, beforecb, aftercb);
  31904. } // Public API
  31905. }, {
  31906. key: "update",
  31907. value: function update() {
  31908. var _this2 = this;
  31909. var stats = this.stats;
  31910. var lruCache = this.lruCache;
  31911. var tileSets = this.tileSets;
  31912. var rootTileSet = tileSets[this.rootURL];
  31913. if (!(this.rootURL in tileSets)) {
  31914. if (this.ionAssetId && !this.ionJsonUrl) {
  31915. if (this.ionJsonUrl == undefined) {
  31916. this.ionJsonUrl = false; // Can't use promise to block update loop, hence this hack
  31917. this.getIonAssetJson(this.ionEndpointUrl).catch(function (err) {
  31918. return console.error("TilesRenderer: Failed to load ION endpoint \"".concat(_this2.ionEndpointUrl, "\" with error: ").concat(err));
  31919. });
  31920. }
  31921. return;
  31922. }
  31923. this.loadRootTileSet(this.rootURL);
  31924. return;
  31925. } else if (!rootTileSet || !rootTileSet.root) {
  31926. return;
  31927. }
  31928. var root = rootTileSet.root;
  31929. stats.inFrustum = 0, stats.used = 0, stats.active = 0, stats.visible = 0, this.frameCount++;
  31930. (0, _traverseFunctions.determineFrustumSet)(root, this);
  31931. (0, _traverseFunctions.markUsedSetLeaves)(root, this);
  31932. (0, _traverseFunctions.skipTraversal)(root, this);
  31933. (0, _traverseFunctions.toggleTiles)(root, this);
  31934. lruCache.scheduleUnload();
  31935. } // Overrideable
  31936. }, {
  31937. key: "parseTile",
  31938. value: function parseTile(buffer, tile, extension) {
  31939. return null;
  31940. }
  31941. }, {
  31942. key: "disposeTile",
  31943. value: function disposeTile(tile) {}
  31944. }, {
  31945. key: "preprocessNode",
  31946. value: function preprocessNode(tile, parentTile, tileSetDir) {
  31947. if (tile.content) {
  31948. // Fix old file formats
  31949. if (!('uri' in tile.content) && 'url' in tile.content) {
  31950. tile.content.uri = tile.content.url;
  31951. delete tile.content.url;
  31952. }
  31953. if (tile.content.uri) {
  31954. tile.content.uri = (0, _urlJoin.urlJoin)(tileSetDir, tile.content.uri);
  31955. } // NOTE: fix for some cases where tilesets provide the bounding volume
  31956. // but volumes are not present.
  31957. if (tile.content.boundingVolume && !('box' in tile.content.boundingVolume || 'sphere' in tile.content.boundingVolume || 'region' in tile.content.boundingVolume)) {
  31958. delete tile.content.boundingVolume;
  31959. }
  31960. }
  31961. tile.parent = parentTile;
  31962. tile.children = tile.children || [];
  31963. var uri = tile.content && tile.content.uri;
  31964. if (uri) {
  31965. // "content" should only indicate loadable meshes, not external tile sets
  31966. var isExternalTileSet = /\.json$/i.test(tile.content.uri);
  31967. tile.__externalTileSet = isExternalTileSet;
  31968. tile.__contentEmpty = isExternalTileSet;
  31969. } else {
  31970. tile.__externalTileSet = false;
  31971. tile.__contentEmpty = true;
  31972. }
  31973. tile.__error = 0.0;
  31974. tile.__inFrustum = false;
  31975. tile.__isLeaf = false;
  31976. tile.__usedLastFrame = false;
  31977. tile.__used = false;
  31978. tile.__wasSetVisible = false;
  31979. tile.__visible = false;
  31980. tile.__childrenWereVisible = false;
  31981. tile.__allChildrenLoaded = false;
  31982. tile.__wasSetActive = false;
  31983. tile.__active = false;
  31984. tile.__loadingState = _constants.UNLOADED;
  31985. tile.__loadIndex = 0;
  31986. tile.__loadAbort = null;
  31987. tile.__depthFromRenderedParent = -1;
  31988. if (parentTile === null) {
  31989. tile.__depth = 0;
  31990. tile.refine = tile.refine || 'REPLACE';
  31991. } else {
  31992. tile.__depth = parentTile.__depth + 1;
  31993. tile.refine = tile.refine || parentTile.refine;
  31994. }
  31995. }
  31996. }, {
  31997. key: "setTileActive",
  31998. value: function setTileActive(tile, state) {}
  31999. }, {
  32000. key: "setTileVisible",
  32001. value: function setTileVisible(tile, state) {}
  32002. }, {
  32003. key: "calculateError",
  32004. value: function calculateError(tile) {
  32005. return 0;
  32006. }
  32007. }, {
  32008. key: "tileInView",
  32009. value: function tileInView(tile) {
  32010. return true;
  32011. } // Private Functions
  32012. }, {
  32013. key: "fetchTileSet",
  32014. value: function fetchTileSet(url, fetchOptions) {
  32015. var _this3 = this;
  32016. var parent = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
  32017. return fetch(url, fetchOptions).then(function (res) {
  32018. if (res.ok) {
  32019. return res.json();
  32020. } else {
  32021. throw new Error("TilesRenderer: Failed to load tileset \"".concat(url, "\" with status ").concat(res.status, " : ").concat(res.statusText));
  32022. }
  32023. }).then(function (json) {
  32024. var version = json.asset.version;
  32025. console.assert(version === '1.0' || version === '0.0', 'asset.version is expected to be a string of "1.0" or "0.0"');
  32026. var basePath = _path.default.dirname(url);
  32027. (0, _traverseFunctions.traverseSet)(json.root, function (node, parent) {
  32028. return _this3.preprocessNode(node, parent, basePath);
  32029. }, null, parent, parent ? parent.__depth : 0);
  32030. return json;
  32031. });
  32032. }
  32033. }, {
  32034. key: "loadRootTileSet",
  32035. value: function loadRootTileSet(url) {
  32036. var tileSets = this.tileSets;
  32037. if (!(url in tileSets)) {
  32038. var pr = this.fetchTileSet(url, this.fetchOptions).then(function (json) {
  32039. tileSets[url] = json;
  32040. });
  32041. pr.catch(function (err) {
  32042. console.error(err);
  32043. tileSets[url] = err;
  32044. });
  32045. tileSets[url] = pr;
  32046. return pr;
  32047. } else if (tileSets[url] instanceof Error) {
  32048. return Promise.reject(tileSets[url]);
  32049. } else {
  32050. return Promise.resolve(tileSets[url]);
  32051. }
  32052. }
  32053. }, {
  32054. key: "requestTileContents",
  32055. value: function requestTileContents(tile) {
  32056. var _this4 = this;
  32057. // If the tile is already being loaded then don't
  32058. // start it again.
  32059. if (tile.__loadingState !== _constants.UNLOADED) {
  32060. return;
  32061. }
  32062. var stats = this.stats;
  32063. var lruCache = this.lruCache;
  32064. var downloadQueue = this.downloadQueue;
  32065. var parseQueue = this.parseQueue;
  32066. var isExternalTileSet = tile.__externalTileSet;
  32067. lruCache.add(tile, function (t) {
  32068. // Stop the load if it's started
  32069. if (t.__loadingState === _constants.LOADING) {
  32070. t.__loadAbort.abort();
  32071. t.__loadAbort = null;
  32072. } else if (isExternalTileSet) {
  32073. t.children.length = 0;
  32074. } else {
  32075. _this4.disposeTile(t);
  32076. } // Decrement stats
  32077. if (t.__loadingState === _constants.LOADING) {
  32078. stats.downloading--;
  32079. } else if (t.__loadingState === _constants.PARSING) {
  32080. stats.parsing--;
  32081. }
  32082. t.__loadingState = _constants.UNLOADED;
  32083. t.__loadIndex++;
  32084. parseQueue.remove(t);
  32085. downloadQueue.remove(t);
  32086. }); // Track a new load index so we avoid the condition where this load is stopped and
  32087. // another begins soon after so we don't parse twice.
  32088. tile.__loadIndex++;
  32089. var loadIndex = tile.__loadIndex;
  32090. var controller = new AbortController();
  32091. var signal = controller.signal;
  32092. stats.downloading++;
  32093. tile.__loadAbort = controller;
  32094. tile.__loadingState = _constants.LOADING;
  32095. var errorCallback = function errorCallback(e) {
  32096. // if it has been unloaded then the tile has been disposed
  32097. if (tile.__loadIndex !== loadIndex) {
  32098. return;
  32099. }
  32100. if (e.name !== 'AbortError') {
  32101. parseQueue.remove(tile);
  32102. downloadQueue.remove(tile);
  32103. if (tile.__loadingState === _constants.PARSING) {
  32104. stats.parsing--;
  32105. } else if (tile.__loadingState === _constants.LOADING) {
  32106. stats.downloading--;
  32107. }
  32108. stats.failed++;
  32109. console.error("TilesRenderer : Failed to load tile at url \"".concat(tile.content.uri, "\"."));
  32110. console.error(e);
  32111. tile.__loadingState = _constants.FAILED;
  32112. } else {
  32113. lruCache.remove(tile);
  32114. }
  32115. };
  32116. if (isExternalTileSet) {
  32117. downloadQueue.add(tile, function (tile) {
  32118. // if it has been unloaded then the tile has been disposed
  32119. if (tile.__loadIndex !== loadIndex) {
  32120. return Promise.resolve();
  32121. }
  32122. var uri = tile.content.uri;
  32123. if (_this4.ionAssetId) {
  32124. uri = new URL(tile.content.uri);
  32125. uri.searchParams.append('v', _this4.ionVersion);
  32126. }
  32127. return _this4.fetchTileSet(uri, Object.assign({
  32128. signal: signal
  32129. }, _this4.fetchOptions), tile);
  32130. }).then(function (json) {
  32131. // if it has been unloaded then the tile has been disposed
  32132. if (tile.__loadIndex !== loadIndex) {
  32133. return;
  32134. }
  32135. stats.downloading--;
  32136. tile.__loadAbort = null;
  32137. tile.__loadingState = _constants.LOADED;
  32138. tile.children.push(json.root);
  32139. }).catch(errorCallback);
  32140. } else {
  32141. downloadQueue.add(tile, function (tile) {
  32142. if (tile.__loadIndex !== loadIndex) {
  32143. return Promise.resolve();
  32144. }
  32145. var uri = tile.content.uri;
  32146. if (_this4.ionAssetId) {
  32147. uri = new URL(tile.content.uri);
  32148. uri.searchParams.append('v', _this4.ionVersion);
  32149. }
  32150. return fetch(uri, Object.assign({
  32151. signal: signal
  32152. }, _this4.fetchOptions));
  32153. }).then(function (res) {
  32154. if (tile.__loadIndex !== loadIndex) {
  32155. return;
  32156. }
  32157. if (res.ok) {
  32158. return res.arrayBuffer();
  32159. } else {
  32160. throw new Error("Failed to load model with error code ".concat(res.status));
  32161. }
  32162. }).then(function (buffer) {
  32163. // if it has been unloaded then the tile has been disposed
  32164. if (tile.__loadIndex !== loadIndex) {
  32165. return;
  32166. }
  32167. stats.downloading--;
  32168. stats.parsing++;
  32169. tile.__loadAbort = null;
  32170. tile.__loadingState = _constants.PARSING;
  32171. return parseQueue.add(tile, function (tile) {
  32172. // if it has been unloaded then the tile has been disposed
  32173. if (tile.__loadIndex !== loadIndex) {
  32174. return Promise.resolve();
  32175. }
  32176. var uri = tile.content.uri;
  32177. var extension = uri.split(/\./g).pop();
  32178. return _this4.parseTile(buffer, tile, extension);
  32179. });
  32180. }).then(function () {
  32181. // if it has been unloaded then the tile has been disposed
  32182. if (tile.__loadIndex !== loadIndex) {
  32183. return;
  32184. }
  32185. stats.parsing--;
  32186. tile.__loadingState = _constants.LOADED;
  32187. if (tile.__wasSetVisible) {
  32188. _this4.setTileVisible(tile, true);
  32189. }
  32190. if (tile.__wasSetActive) {
  32191. _this4.setTileActive(tile, true);
  32192. }
  32193. }).catch(errorCallback);
  32194. }
  32195. }
  32196. }, {
  32197. key: "dispose",
  32198. value: function dispose() {
  32199. var lruCache = this.lruCache;
  32200. this.traverse(function (tile) {
  32201. lruCache.remove(tile);
  32202. });
  32203. }
  32204. }]);
  32205. return TilesRendererBase;
  32206. }();
  32207. exports.TilesRendererBase = TilesRendererBase;
  32208. },{"path":"../node_modules/path-browserify/index.js","../utilities/urlJoin.js":"../src/utilities/urlJoin.js","../utilities/LRUCache.js":"../src/utilities/LRUCache.js","../utilities/PriorityQueue.js":"../src/utilities/PriorityQueue.js","./traverseFunctions.js":"../src/base/traverseFunctions.js","./constants.js":"../src/base/constants.js"}],"../src/utilities/arrayToString.js":[function(require,module,exports) {
  32209. "use strict";
  32210. Object.defineProperty(exports, "__esModule", {
  32211. value: true
  32212. });
  32213. exports.arrayToString = arrayToString;
  32214. function arrayToString(array) {
  32215. var str = '';
  32216. for (var i = 0, l = array.length; i < l; i++) {
  32217. str += String.fromCharCode(array[i]);
  32218. }
  32219. return str;
  32220. }
  32221. },{}],"../src/utilities/FeatureTable.js":[function(require,module,exports) {
  32222. "use strict";
  32223. Object.defineProperty(exports, "__esModule", {
  32224. value: true
  32225. });
  32226. exports.BatchTable = exports.FeatureTable = void 0;
  32227. var _arrayToString = require("./arrayToString.js");
  32228. function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
  32229. function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }
  32230. function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
  32231. function _get(target, property, receiver) { if (typeof Reflect !== "undefined" && Reflect.get) { _get = Reflect.get; } else { _get = function _get(target, property, receiver) { var base = _superPropBase(target, property); if (!base) return; var desc = Object.getOwnPropertyDescriptor(base, property); if (desc.get) { return desc.get.call(receiver); } return desc.value; }; } return _get(target, property, receiver || target); }
  32232. function _superPropBase(object, property) { while (!Object.prototype.hasOwnProperty.call(object, property)) { object = _getPrototypeOf(object); if (object === null) break; } return object; }
  32233. function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
  32234. function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }
  32235. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  32236. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  32237. function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
  32238. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
  32239. var FeatureTable =
  32240. /*#__PURE__*/
  32241. function () {
  32242. function FeatureTable(buffer, start, headerLength, binLength) {
  32243. _classCallCheck(this, FeatureTable);
  32244. this.buffer = buffer;
  32245. this.binOffset = start + headerLength;
  32246. this.binLength = binLength;
  32247. var header = null;
  32248. if (headerLength !== 0) {
  32249. var headerData = new Uint8Array(buffer, start, headerLength);
  32250. header = JSON.parse((0, _arrayToString.arrayToString)(headerData));
  32251. } else {
  32252. header = {};
  32253. }
  32254. this.header = header;
  32255. }
  32256. _createClass(FeatureTable, [{
  32257. key: "getKeys",
  32258. value: function getKeys() {
  32259. return Object.keys(this.header);
  32260. }
  32261. }, {
  32262. key: "getData",
  32263. value: function getData(key, count) {
  32264. var defaultComponentType = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
  32265. var defaultType = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null;
  32266. var header = this.header;
  32267. if (!(key in header)) {
  32268. return null;
  32269. }
  32270. var feature = header[key];
  32271. if (!(feature instanceof Object)) {
  32272. return feature;
  32273. } else if (Array.isArray(feature)) {
  32274. return feature;
  32275. } else {
  32276. var buffer = this.buffer,
  32277. binOffset = this.binOffset,
  32278. binLength = this.binLength;
  32279. var byteOffset = feature.byteOffset || 0;
  32280. var featureType = feature.type || defaultType;
  32281. var featureComponentType = feature.componentType || defaultComponentType;
  32282. if ('type' in feature && defaultType && feature.type !== defaultType) {
  32283. throw new Error('FeatureTable: Specified type does not match expected type.');
  32284. }
  32285. var stride;
  32286. switch (featureType) {
  32287. case 'SCALAR':
  32288. stride = 1;
  32289. break;
  32290. case 'VEC2':
  32291. stride = 2;
  32292. break;
  32293. case 'VEC3':
  32294. stride = 3;
  32295. break;
  32296. case 'VEC4':
  32297. stride = 4;
  32298. break;
  32299. default:
  32300. throw new Error("FeatureTable : Feature type not provided for \"".concat(key, "\"."));
  32301. }
  32302. var data;
  32303. var arrayStart = binOffset + byteOffset;
  32304. var arrayLength = count * stride;
  32305. switch (featureComponentType) {
  32306. case 'BYTE':
  32307. data = new Int8Array(buffer, arrayStart, arrayLength);
  32308. break;
  32309. case 'UNSIGNED_BYTE':
  32310. data = new Uint8Array(buffer, arrayStart, arrayLength);
  32311. break;
  32312. case 'SHORT':
  32313. data = new Int16Array(buffer, arrayStart, arrayLength);
  32314. break;
  32315. case 'UNSIGNED_SHORT':
  32316. data = new Uint16Array(buffer, arrayStart, arrayLength);
  32317. break;
  32318. case 'INT':
  32319. data = new Int32Array(buffer, arrayStart, arrayLength);
  32320. break;
  32321. case 'UNSIGNED_INT':
  32322. data = new Uint32Array(buffer, arrayStart, arrayLength);
  32323. break;
  32324. case 'FLOAT':
  32325. data = new Float32Array(buffer, arrayStart, arrayLength);
  32326. break;
  32327. case 'DOUBLE':
  32328. data = new Float64Array(buffer, arrayStart, arrayLength);
  32329. break;
  32330. default:
  32331. throw new Error("FeatureTable : Feature component type not provided for \"".concat(key, "\"."));
  32332. }
  32333. var dataEnd = arrayStart + arrayLength * data.BYTES_PER_ELEMENT;
  32334. if (dataEnd > binOffset + binLength) {
  32335. throw new Error('FeatureTable: Feature data read outside binary body length.');
  32336. }
  32337. return data;
  32338. }
  32339. }
  32340. }]);
  32341. return FeatureTable;
  32342. }();
  32343. exports.FeatureTable = FeatureTable;
  32344. var BatchTable =
  32345. /*#__PURE__*/
  32346. function (_FeatureTable) {
  32347. _inherits(BatchTable, _FeatureTable);
  32348. function BatchTable(buffer, batchSize, start, headerLength, binLength) {
  32349. var _this;
  32350. _classCallCheck(this, BatchTable);
  32351. _this = _possibleConstructorReturn(this, _getPrototypeOf(BatchTable).call(this, buffer, start, headerLength, binLength));
  32352. _this.batchSize = batchSize;
  32353. return _this;
  32354. }
  32355. _createClass(BatchTable, [{
  32356. key: "getData",
  32357. value: function getData(key) {
  32358. var componentType = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
  32359. var type = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
  32360. return _get(_getPrototypeOf(BatchTable.prototype), "getData", this).call(this, key, this.batchSize, type, componentType);
  32361. }
  32362. }]);
  32363. return BatchTable;
  32364. }(FeatureTable);
  32365. exports.BatchTable = BatchTable;
  32366. },{"./arrayToString.js":"../src/utilities/arrayToString.js"}],"../src/base/B3DMLoaderBase.js":[function(require,module,exports) {
  32367. "use strict";
  32368. Object.defineProperty(exports, "__esModule", {
  32369. value: true
  32370. });
  32371. exports.B3DMLoaderBase = void 0;
  32372. var _FeatureTable = require("../utilities/FeatureTable.js");
  32373. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  32374. function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
  32375. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
  32376. var B3DMLoaderBase =
  32377. /*#__PURE__*/
  32378. function () {
  32379. function B3DMLoaderBase() {
  32380. _classCallCheck(this, B3DMLoaderBase);
  32381. this.fetchOptions = {};
  32382. }
  32383. _createClass(B3DMLoaderBase, [{
  32384. key: "load",
  32385. value: function load(url) {
  32386. var _this = this;
  32387. return fetch(url, this.fetchOptions).then(function (res) {
  32388. if (!res.ok) {
  32389. throw new Error("Failed to load file \"".concat(url, "\" with status ").concat(res.status, " : ").concat(res.statusText));
  32390. }
  32391. return res.arrayBuffer();
  32392. }).then(function (buffer) {
  32393. return _this.parse(buffer);
  32394. });
  32395. }
  32396. }, {
  32397. key: "parse",
  32398. value: function parse(buffer) {
  32399. // TODO: this should be able to take a uint8array with an offset and length
  32400. var dataView = new DataView(buffer); // 28-byte header
  32401. // 4 bytes
  32402. var magic = String.fromCharCode(dataView.getUint8(0)) + String.fromCharCode(dataView.getUint8(1)) + String.fromCharCode(dataView.getUint8(2)) + String.fromCharCode(dataView.getUint8(3));
  32403. console.assert(magic === 'b3dm'); // 4 bytes
  32404. var version = dataView.getUint32(4, true);
  32405. console.assert(version === 1); // 4 bytes
  32406. var byteLength = dataView.getUint32(8, true);
  32407. console.assert(byteLength === buffer.byteLength); // 4 bytes
  32408. var featureTableJSONByteLength = dataView.getUint32(12, true); // 4 bytes
  32409. var featureTableBinaryByteLength = dataView.getUint32(16, true); // 4 bytes
  32410. var batchTableJSONByteLength = dataView.getUint32(20, true); // 4 bytes
  32411. var batchTableBinaryByteLength = dataView.getUint32(24, true); // Feature Table
  32412. var featureTableStart = 28;
  32413. var featureTable = new _FeatureTable.FeatureTable(buffer, featureTableStart, featureTableJSONByteLength, featureTableBinaryByteLength); // Batch Table
  32414. var batchTableStart = featureTableStart + featureTableJSONByteLength + featureTableBinaryByteLength;
  32415. var batchTable = new _FeatureTable.BatchTable(buffer, featureTable.getData('BATCH_LENGTH'), batchTableStart, batchTableJSONByteLength, batchTableBinaryByteLength);
  32416. var glbStart = batchTableStart + batchTableJSONByteLength + batchTableBinaryByteLength;
  32417. var glbBytes = new Uint8Array(buffer, glbStart, byteLength - glbStart);
  32418. return {
  32419. version: version,
  32420. featureTable: featureTable,
  32421. batchTable: batchTable,
  32422. glbBytes: glbBytes
  32423. };
  32424. }
  32425. }]);
  32426. return B3DMLoaderBase;
  32427. }();
  32428. exports.B3DMLoaderBase = B3DMLoaderBase;
  32429. },{"../utilities/FeatureTable.js":"../src/utilities/FeatureTable.js"}],"../node_modules/three/examples/jsm/loaders/GLTFLoader.js":[function(require,module,exports) {
  32430. "use strict";
  32431. Object.defineProperty(exports, "__esModule", {
  32432. value: true
  32433. });
  32434. exports.GLTFLoader = void 0;
  32435. var _threeModule = require("../../../build/three.module.js");
  32436. var GLTFLoader = function () {
  32437. function GLTFLoader(manager) {
  32438. _threeModule.Loader.call(this, manager);
  32439. this.dracoLoader = null;
  32440. this.ddsLoader = null;
  32441. this.ktx2Loader = null;
  32442. this.meshoptDecoder = null;
  32443. this.pluginCallbacks = [];
  32444. this.register(function (parser) {
  32445. return new GLTFMaterialsClearcoatExtension(parser);
  32446. });
  32447. this.register(function (parser) {
  32448. return new GLTFTextureBasisUExtension(parser);
  32449. });
  32450. this.register(function (parser) {
  32451. return new GLTFTextureWebPExtension(parser);
  32452. });
  32453. this.register(function (parser) {
  32454. return new GLTFMaterialsTransmissionExtension(parser);
  32455. });
  32456. this.register(function (parser) {
  32457. return new GLTFLightsExtension(parser);
  32458. });
  32459. this.register(function (parser) {
  32460. return new GLTFMeshoptCompression(parser);
  32461. });
  32462. }
  32463. GLTFLoader.prototype = Object.assign(Object.create(_threeModule.Loader.prototype), {
  32464. constructor: GLTFLoader,
  32465. load: function (url, onLoad, onProgress, onError) {
  32466. var scope = this;
  32467. var resourcePath;
  32468. if (this.resourcePath !== '') {
  32469. resourcePath = this.resourcePath;
  32470. } else if (this.path !== '') {
  32471. resourcePath = this.path;
  32472. } else {
  32473. resourcePath = _threeModule.LoaderUtils.extractUrlBase(url);
  32474. } // Tells the LoadingManager to track an extra item, which resolves after
  32475. // the model is fully loaded. This means the count of items loaded will
  32476. // be incorrect, but ensures manager.onLoad() does not fire early.
  32477. this.manager.itemStart(url);
  32478. var _onError = function (e) {
  32479. if (onError) {
  32480. onError(e);
  32481. } else {
  32482. console.error(e);
  32483. }
  32484. scope.manager.itemError(url);
  32485. scope.manager.itemEnd(url);
  32486. };
  32487. var loader = new _threeModule.FileLoader(this.manager);
  32488. loader.setPath(this.path);
  32489. loader.setResponseType('arraybuffer');
  32490. loader.setRequestHeader(this.requestHeader);
  32491. loader.setWithCredentials(this.withCredentials);
  32492. loader.load(url, function (data) {
  32493. try {
  32494. scope.parse(data, resourcePath, function (gltf) {
  32495. onLoad(gltf);
  32496. scope.manager.itemEnd(url);
  32497. }, _onError);
  32498. } catch (e) {
  32499. _onError(e);
  32500. }
  32501. }, onProgress, _onError);
  32502. },
  32503. setDRACOLoader: function (dracoLoader) {
  32504. this.dracoLoader = dracoLoader;
  32505. return this;
  32506. },
  32507. setDDSLoader: function (ddsLoader) {
  32508. this.ddsLoader = ddsLoader;
  32509. return this;
  32510. },
  32511. setKTX2Loader: function (ktx2Loader) {
  32512. this.ktx2Loader = ktx2Loader;
  32513. return this;
  32514. },
  32515. setMeshoptDecoder: function (meshoptDecoder) {
  32516. this.meshoptDecoder = meshoptDecoder;
  32517. return this;
  32518. },
  32519. register: function (callback) {
  32520. if (this.pluginCallbacks.indexOf(callback) === -1) {
  32521. this.pluginCallbacks.push(callback);
  32522. }
  32523. return this;
  32524. },
  32525. unregister: function (callback) {
  32526. if (this.pluginCallbacks.indexOf(callback) !== -1) {
  32527. this.pluginCallbacks.splice(this.pluginCallbacks.indexOf(callback), 1);
  32528. }
  32529. return this;
  32530. },
  32531. parse: function (data, path, onLoad, onError) {
  32532. var content;
  32533. var extensions = {};
  32534. var plugins = {};
  32535. if (typeof data === 'string') {
  32536. content = data;
  32537. } else {
  32538. var magic = _threeModule.LoaderUtils.decodeText(new Uint8Array(data, 0, 4));
  32539. if (magic === BINARY_EXTENSION_HEADER_MAGIC) {
  32540. try {
  32541. extensions[EXTENSIONS.KHR_BINARY_GLTF] = new GLTFBinaryExtension(data);
  32542. } catch (error) {
  32543. if (onError) onError(error);
  32544. return;
  32545. }
  32546. content = extensions[EXTENSIONS.KHR_BINARY_GLTF].content;
  32547. } else {
  32548. content = _threeModule.LoaderUtils.decodeText(new Uint8Array(data));
  32549. }
  32550. }
  32551. var json = JSON.parse(content);
  32552. if (json.asset === undefined || json.asset.version[0] < 2) {
  32553. if (onError) onError(new Error('THREE.GLTFLoader: Unsupported asset. glTF versions >=2.0 are supported.'));
  32554. return;
  32555. }
  32556. var parser = new GLTFParser(json, {
  32557. path: path || this.resourcePath || '',
  32558. crossOrigin: this.crossOrigin,
  32559. manager: this.manager,
  32560. ktx2Loader: this.ktx2Loader,
  32561. meshoptDecoder: this.meshoptDecoder
  32562. });
  32563. parser.fileLoader.setRequestHeader(this.requestHeader);
  32564. for (var i = 0; i < this.pluginCallbacks.length; i++) {
  32565. var plugin = this.pluginCallbacks[i](parser);
  32566. plugins[plugin.name] = plugin; // Workaround to avoid determining as unknown extension
  32567. // in addUnknownExtensionsToUserData().
  32568. // Remove this workaround if we move all the existing
  32569. // extension handlers to plugin system
  32570. extensions[plugin.name] = true;
  32571. }
  32572. if (json.extensionsUsed) {
  32573. for (var i = 0; i < json.extensionsUsed.length; ++i) {
  32574. var extensionName = json.extensionsUsed[i];
  32575. var extensionsRequired = json.extensionsRequired || [];
  32576. switch (extensionName) {
  32577. case EXTENSIONS.KHR_MATERIALS_UNLIT:
  32578. extensions[extensionName] = new GLTFMaterialsUnlitExtension();
  32579. break;
  32580. case EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS:
  32581. extensions[extensionName] = new GLTFMaterialsPbrSpecularGlossinessExtension();
  32582. break;
  32583. case EXTENSIONS.KHR_DRACO_MESH_COMPRESSION:
  32584. extensions[extensionName] = new GLTFDracoMeshCompressionExtension(json, this.dracoLoader);
  32585. break;
  32586. case EXTENSIONS.MSFT_TEXTURE_DDS:
  32587. extensions[extensionName] = new GLTFTextureDDSExtension(this.ddsLoader);
  32588. break;
  32589. case EXTENSIONS.KHR_TEXTURE_TRANSFORM:
  32590. extensions[extensionName] = new GLTFTextureTransformExtension();
  32591. break;
  32592. case EXTENSIONS.KHR_MESH_QUANTIZATION:
  32593. extensions[extensionName] = new GLTFMeshQuantizationExtension();
  32594. break;
  32595. default:
  32596. if (extensionsRequired.indexOf(extensionName) >= 0 && plugins[extensionName] === undefined) {
  32597. console.warn('THREE.GLTFLoader: Unknown extension "' + extensionName + '".');
  32598. }
  32599. }
  32600. }
  32601. }
  32602. parser.setExtensions(extensions);
  32603. parser.setPlugins(plugins);
  32604. parser.parse(onLoad, onError);
  32605. }
  32606. });
  32607. /* GLTFREGISTRY */
  32608. function GLTFRegistry() {
  32609. var objects = {};
  32610. return {
  32611. get: function (key) {
  32612. return objects[key];
  32613. },
  32614. add: function (key, object) {
  32615. objects[key] = object;
  32616. },
  32617. remove: function (key) {
  32618. delete objects[key];
  32619. },
  32620. removeAll: function () {
  32621. objects = {};
  32622. }
  32623. };
  32624. }
  32625. /*********************************/
  32626. /********** EXTENSIONS ***********/
  32627. /*********************************/
  32628. var EXTENSIONS = {
  32629. KHR_BINARY_GLTF: 'KHR_binary_glTF',
  32630. KHR_DRACO_MESH_COMPRESSION: 'KHR_draco_mesh_compression',
  32631. KHR_LIGHTS_PUNCTUAL: 'KHR_lights_punctual',
  32632. KHR_MATERIALS_CLEARCOAT: 'KHR_materials_clearcoat',
  32633. KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS: 'KHR_materials_pbrSpecularGlossiness',
  32634. KHR_MATERIALS_TRANSMISSION: 'KHR_materials_transmission',
  32635. KHR_MATERIALS_UNLIT: 'KHR_materials_unlit',
  32636. KHR_TEXTURE_BASISU: 'KHR_texture_basisu',
  32637. KHR_TEXTURE_TRANSFORM: 'KHR_texture_transform',
  32638. KHR_MESH_QUANTIZATION: 'KHR_mesh_quantization',
  32639. EXT_TEXTURE_WEBP: 'EXT_texture_webp',
  32640. EXT_MESHOPT_COMPRESSION: 'EXT_meshopt_compression',
  32641. MSFT_TEXTURE_DDS: 'MSFT_texture_dds'
  32642. };
  32643. /**
  32644. * DDS Texture Extension
  32645. *
  32646. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/MSFT_texture_dds
  32647. *
  32648. */
  32649. function GLTFTextureDDSExtension(ddsLoader) {
  32650. if (!ddsLoader) {
  32651. throw new Error('THREE.GLTFLoader: Attempting to load .dds texture without importing DDSLoader');
  32652. }
  32653. this.name = EXTENSIONS.MSFT_TEXTURE_DDS;
  32654. this.ddsLoader = ddsLoader;
  32655. }
  32656. /**
  32657. * Punctual Lights Extension
  32658. *
  32659. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_lights_punctual
  32660. */
  32661. function GLTFLightsExtension(parser) {
  32662. this.parser = parser;
  32663. this.name = EXTENSIONS.KHR_LIGHTS_PUNCTUAL; // Object3D instance caches
  32664. this.cache = {
  32665. refs: {},
  32666. uses: {}
  32667. };
  32668. }
  32669. GLTFLightsExtension.prototype._markDefs = function () {
  32670. var parser = this.parser;
  32671. var nodeDefs = this.parser.json.nodes || [];
  32672. for (var nodeIndex = 0, nodeLength = nodeDefs.length; nodeIndex < nodeLength; nodeIndex++) {
  32673. var nodeDef = nodeDefs[nodeIndex];
  32674. if (nodeDef.extensions && nodeDef.extensions[this.name] && nodeDef.extensions[this.name].light !== undefined) {
  32675. parser._addNodeRef(this.cache, nodeDef.extensions[this.name].light);
  32676. }
  32677. }
  32678. };
  32679. GLTFLightsExtension.prototype._loadLight = function (lightIndex) {
  32680. var parser = this.parser;
  32681. var cacheKey = 'light:' + lightIndex;
  32682. var dependency = parser.cache.get(cacheKey);
  32683. if (dependency) return dependency;
  32684. var json = parser.json;
  32685. var extensions = json.extensions && json.extensions[this.name] || {};
  32686. var lightDefs = extensions.lights || [];
  32687. var lightDef = lightDefs[lightIndex];
  32688. var lightNode;
  32689. var color = new _threeModule.Color(0xffffff);
  32690. if (lightDef.color !== undefined) color.fromArray(lightDef.color);
  32691. var range = lightDef.range !== undefined ? lightDef.range : 0;
  32692. switch (lightDef.type) {
  32693. case 'directional':
  32694. lightNode = new _threeModule.DirectionalLight(color);
  32695. lightNode.target.position.set(0, 0, -1);
  32696. lightNode.add(lightNode.target);
  32697. break;
  32698. case 'point':
  32699. lightNode = new _threeModule.PointLight(color);
  32700. lightNode.distance = range;
  32701. break;
  32702. case 'spot':
  32703. lightNode = new _threeModule.SpotLight(color);
  32704. lightNode.distance = range; // Handle spotlight properties.
  32705. lightDef.spot = lightDef.spot || {};
  32706. lightDef.spot.innerConeAngle = lightDef.spot.innerConeAngle !== undefined ? lightDef.spot.innerConeAngle : 0;
  32707. lightDef.spot.outerConeAngle = lightDef.spot.outerConeAngle !== undefined ? lightDef.spot.outerConeAngle : Math.PI / 4.0;
  32708. lightNode.angle = lightDef.spot.outerConeAngle;
  32709. lightNode.penumbra = 1.0 - lightDef.spot.innerConeAngle / lightDef.spot.outerConeAngle;
  32710. lightNode.target.position.set(0, 0, -1);
  32711. lightNode.add(lightNode.target);
  32712. break;
  32713. default:
  32714. throw new Error('THREE.GLTFLoader: Unexpected light type, "' + lightDef.type + '".');
  32715. } // Some lights (e.g. spot) default to a position other than the origin. Reset the position
  32716. // here, because node-level parsing will only override position if explicitly specified.
  32717. lightNode.position.set(0, 0, 0);
  32718. lightNode.decay = 2;
  32719. if (lightDef.intensity !== undefined) lightNode.intensity = lightDef.intensity;
  32720. lightNode.name = parser.createUniqueName(lightDef.name || 'light_' + lightIndex);
  32721. dependency = Promise.resolve(lightNode);
  32722. parser.cache.add(cacheKey, dependency);
  32723. return dependency;
  32724. };
  32725. GLTFLightsExtension.prototype.createNodeAttachment = function (nodeIndex) {
  32726. var self = this;
  32727. var parser = this.parser;
  32728. var json = parser.json;
  32729. var nodeDef = json.nodes[nodeIndex];
  32730. var lightDef = nodeDef.extensions && nodeDef.extensions[this.name] || {};
  32731. var lightIndex = lightDef.light;
  32732. if (lightIndex === undefined) return null;
  32733. return this._loadLight(lightIndex).then(function (light) {
  32734. return parser._getNodeRef(self.cache, lightIndex, light);
  32735. });
  32736. };
  32737. /**
  32738. * Unlit Materials Extension
  32739. *
  32740. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_unlit
  32741. */
  32742. function GLTFMaterialsUnlitExtension() {
  32743. this.name = EXTENSIONS.KHR_MATERIALS_UNLIT;
  32744. }
  32745. GLTFMaterialsUnlitExtension.prototype.getMaterialType = function () {
  32746. return _threeModule.MeshBasicMaterial;
  32747. };
  32748. GLTFMaterialsUnlitExtension.prototype.extendParams = function (materialParams, materialDef, parser) {
  32749. var pending = [];
  32750. materialParams.color = new _threeModule.Color(1.0, 1.0, 1.0);
  32751. materialParams.opacity = 1.0;
  32752. var metallicRoughness = materialDef.pbrMetallicRoughness;
  32753. if (metallicRoughness) {
  32754. if (Array.isArray(metallicRoughness.baseColorFactor)) {
  32755. var array = metallicRoughness.baseColorFactor;
  32756. materialParams.color.fromArray(array);
  32757. materialParams.opacity = array[3];
  32758. }
  32759. if (metallicRoughness.baseColorTexture !== undefined) {
  32760. pending.push(parser.assignTexture(materialParams, 'map', metallicRoughness.baseColorTexture));
  32761. }
  32762. }
  32763. return Promise.all(pending);
  32764. };
  32765. /**
  32766. * Clearcoat Materials Extension
  32767. *
  32768. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_clearcoat
  32769. */
  32770. function GLTFMaterialsClearcoatExtension(parser) {
  32771. this.parser = parser;
  32772. this.name = EXTENSIONS.KHR_MATERIALS_CLEARCOAT;
  32773. }
  32774. GLTFMaterialsClearcoatExtension.prototype.getMaterialType = function (materialIndex) {
  32775. var parser = this.parser;
  32776. var materialDef = parser.json.materials[materialIndex];
  32777. if (!materialDef.extensions || !materialDef.extensions[this.name]) return null;
  32778. return _threeModule.MeshPhysicalMaterial;
  32779. };
  32780. GLTFMaterialsClearcoatExtension.prototype.extendMaterialParams = function (materialIndex, materialParams) {
  32781. var parser = this.parser;
  32782. var materialDef = parser.json.materials[materialIndex];
  32783. if (!materialDef.extensions || !materialDef.extensions[this.name]) {
  32784. return Promise.resolve();
  32785. }
  32786. var pending = [];
  32787. var extension = materialDef.extensions[this.name];
  32788. if (extension.clearcoatFactor !== undefined) {
  32789. materialParams.clearcoat = extension.clearcoatFactor;
  32790. }
  32791. if (extension.clearcoatTexture !== undefined) {
  32792. pending.push(parser.assignTexture(materialParams, 'clearcoatMap', extension.clearcoatTexture));
  32793. }
  32794. if (extension.clearcoatRoughnessFactor !== undefined) {
  32795. materialParams.clearcoatRoughness = extension.clearcoatRoughnessFactor;
  32796. }
  32797. if (extension.clearcoatRoughnessTexture !== undefined) {
  32798. pending.push(parser.assignTexture(materialParams, 'clearcoatRoughnessMap', extension.clearcoatRoughnessTexture));
  32799. }
  32800. if (extension.clearcoatNormalTexture !== undefined) {
  32801. pending.push(parser.assignTexture(materialParams, 'clearcoatNormalMap', extension.clearcoatNormalTexture));
  32802. if (extension.clearcoatNormalTexture.scale !== undefined) {
  32803. var scale = extension.clearcoatNormalTexture.scale;
  32804. materialParams.clearcoatNormalScale = new _threeModule.Vector2(scale, scale);
  32805. }
  32806. }
  32807. return Promise.all(pending);
  32808. };
  32809. /**
  32810. * Transmission Materials Extension
  32811. *
  32812. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_transmission
  32813. * Draft: https://github.com/KhronosGroup/glTF/pull/1698
  32814. */
  32815. function GLTFMaterialsTransmissionExtension(parser) {
  32816. this.parser = parser;
  32817. this.name = EXTENSIONS.KHR_MATERIALS_TRANSMISSION;
  32818. }
  32819. GLTFMaterialsTransmissionExtension.prototype.getMaterialType = function (materialIndex) {
  32820. var parser = this.parser;
  32821. var materialDef = parser.json.materials[materialIndex];
  32822. if (!materialDef.extensions || !materialDef.extensions[this.name]) return null;
  32823. return _threeModule.MeshPhysicalMaterial;
  32824. };
  32825. GLTFMaterialsTransmissionExtension.prototype.extendMaterialParams = function (materialIndex, materialParams) {
  32826. var parser = this.parser;
  32827. var materialDef = parser.json.materials[materialIndex];
  32828. if (!materialDef.extensions || !materialDef.extensions[this.name]) {
  32829. return Promise.resolve();
  32830. }
  32831. var pending = [];
  32832. var extension = materialDef.extensions[this.name];
  32833. if (extension.transmissionFactor !== undefined) {
  32834. materialParams.transmission = extension.transmissionFactor;
  32835. }
  32836. if (extension.transmissionTexture !== undefined) {
  32837. pending.push(parser.assignTexture(materialParams, 'transmissionMap', extension.transmissionTexture));
  32838. }
  32839. return Promise.all(pending);
  32840. };
  32841. /**
  32842. * BasisU Texture Extension
  32843. *
  32844. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_texture_basisu
  32845. */
  32846. function GLTFTextureBasisUExtension(parser) {
  32847. this.parser = parser;
  32848. this.name = EXTENSIONS.KHR_TEXTURE_BASISU;
  32849. }
  32850. GLTFTextureBasisUExtension.prototype.loadTexture = function (textureIndex) {
  32851. var parser = this.parser;
  32852. var json = parser.json;
  32853. var textureDef = json.textures[textureIndex];
  32854. if (!textureDef.extensions || !textureDef.extensions[this.name]) {
  32855. return null;
  32856. }
  32857. var extension = textureDef.extensions[this.name];
  32858. var source = json.images[extension.source];
  32859. var loader = parser.options.ktx2Loader;
  32860. if (!loader) {
  32861. if (json.extensionsRequired && json.extensionsRequired.indexOf(this.name) >= 0) {
  32862. throw new Error('THREE.GLTFLoader: setKTX2Loader must be called before loading KTX2 textures');
  32863. } else {
  32864. // Assumes that the extension is optional and that a fallback texture is present
  32865. return null;
  32866. }
  32867. }
  32868. return parser.loadTextureImage(textureIndex, source, loader);
  32869. };
  32870. /**
  32871. * WebP Texture Extension
  32872. *
  32873. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/EXT_texture_webp
  32874. */
  32875. function GLTFTextureWebPExtension(parser) {
  32876. this.parser = parser;
  32877. this.name = EXTENSIONS.EXT_TEXTURE_WEBP;
  32878. this.isSupported = null;
  32879. }
  32880. GLTFTextureWebPExtension.prototype.loadTexture = function (textureIndex) {
  32881. var name = this.name;
  32882. var parser = this.parser;
  32883. var json = parser.json;
  32884. var textureDef = json.textures[textureIndex];
  32885. if (!textureDef.extensions || !textureDef.extensions[name]) {
  32886. return null;
  32887. }
  32888. var extension = textureDef.extensions[name];
  32889. var source = json.images[extension.source];
  32890. var loader = source.uri ? parser.options.manager.getHandler(source.uri) : parser.textureLoader;
  32891. return this.detectSupport().then(function (isSupported) {
  32892. if (isSupported) return parser.loadTextureImage(textureIndex, source, loader);
  32893. if (json.extensionsRequired && json.extensionsRequired.indexOf(name) >= 0) {
  32894. throw new Error('THREE.GLTFLoader: WebP required by asset but unsupported.');
  32895. } // Fall back to PNG or JPEG.
  32896. return parser.loadTexture(textureIndex);
  32897. });
  32898. };
  32899. GLTFTextureWebPExtension.prototype.detectSupport = function () {
  32900. if (!this.isSupported) {
  32901. this.isSupported = new Promise(function (resolve) {
  32902. var image = new Image(); // Lossy test image. Support for lossy images doesn't guarantee support for all
  32903. // WebP images, unfortunately.
  32904. image.src = 'data:image/webp;base64,UklGRiIAAABXRUJQVlA4IBYAAAAwAQCdASoBAAEADsD+JaQAA3AAAAAA';
  32905. image.onload = image.onerror = function () {
  32906. resolve(image.height === 1);
  32907. };
  32908. });
  32909. }
  32910. return this.isSupported;
  32911. };
  32912. /**
  32913. * meshopt BufferView Compression Extension
  32914. *
  32915. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/EXT_meshopt_compression
  32916. */
  32917. function GLTFMeshoptCompression(parser) {
  32918. this.name = EXTENSIONS.EXT_MESHOPT_COMPRESSION;
  32919. this.parser = parser;
  32920. }
  32921. GLTFMeshoptCompression.prototype.loadBufferView = function (index) {
  32922. var json = this.parser.json;
  32923. var bufferView = json.bufferViews[index];
  32924. if (bufferView.extensions && bufferView.extensions[this.name]) {
  32925. var extensionDef = bufferView.extensions[this.name];
  32926. var buffer = this.parser.getDependency('buffer', extensionDef.buffer);
  32927. var decoder = this.parser.options.meshoptDecoder;
  32928. if (!decoder || !decoder.supported) {
  32929. if (json.extensionsRequired && json.extensionsRequired.indexOf(this.name) >= 0) {
  32930. throw new Error('THREE.GLTFLoader: setMeshoptDecoder must be called before loading compressed files');
  32931. } else {
  32932. // Assumes that the extension is optional and that fallback buffer data is present
  32933. return null;
  32934. }
  32935. }
  32936. return Promise.all([buffer, decoder.ready]).then(function (res) {
  32937. var byteOffset = extensionDef.byteOffset || 0;
  32938. var byteLength = extensionDef.byteLength || 0;
  32939. var count = extensionDef.count;
  32940. var stride = extensionDef.byteStride;
  32941. var result = new ArrayBuffer(count * stride);
  32942. var source = new Uint8Array(res[0], byteOffset, byteLength);
  32943. decoder.decodeGltfBuffer(new Uint8Array(result), count, stride, source, extensionDef.mode, extensionDef.filter);
  32944. return result;
  32945. });
  32946. } else {
  32947. return null;
  32948. }
  32949. };
  32950. /* BINARY EXTENSION */
  32951. var BINARY_EXTENSION_HEADER_MAGIC = 'glTF';
  32952. var BINARY_EXTENSION_HEADER_LENGTH = 12;
  32953. var BINARY_EXTENSION_CHUNK_TYPES = {
  32954. JSON: 0x4E4F534A,
  32955. BIN: 0x004E4942
  32956. };
  32957. function GLTFBinaryExtension(data) {
  32958. this.name = EXTENSIONS.KHR_BINARY_GLTF;
  32959. this.content = null;
  32960. this.body = null;
  32961. var headerView = new DataView(data, 0, BINARY_EXTENSION_HEADER_LENGTH);
  32962. this.header = {
  32963. magic: _threeModule.LoaderUtils.decodeText(new Uint8Array(data.slice(0, 4))),
  32964. version: headerView.getUint32(4, true),
  32965. length: headerView.getUint32(8, true)
  32966. };
  32967. if (this.header.magic !== BINARY_EXTENSION_HEADER_MAGIC) {
  32968. throw new Error('THREE.GLTFLoader: Unsupported glTF-Binary header.');
  32969. } else if (this.header.version < 2.0) {
  32970. throw new Error('THREE.GLTFLoader: Legacy binary file detected.');
  32971. }
  32972. var chunkView = new DataView(data, BINARY_EXTENSION_HEADER_LENGTH);
  32973. var chunkIndex = 0;
  32974. while (chunkIndex < chunkView.byteLength) {
  32975. var chunkLength = chunkView.getUint32(chunkIndex, true);
  32976. chunkIndex += 4;
  32977. var chunkType = chunkView.getUint32(chunkIndex, true);
  32978. chunkIndex += 4;
  32979. if (chunkType === BINARY_EXTENSION_CHUNK_TYPES.JSON) {
  32980. var contentArray = new Uint8Array(data, BINARY_EXTENSION_HEADER_LENGTH + chunkIndex, chunkLength);
  32981. this.content = _threeModule.LoaderUtils.decodeText(contentArray);
  32982. } else if (chunkType === BINARY_EXTENSION_CHUNK_TYPES.BIN) {
  32983. var byteOffset = BINARY_EXTENSION_HEADER_LENGTH + chunkIndex;
  32984. this.body = data.slice(byteOffset, byteOffset + chunkLength);
  32985. } // Clients must ignore chunks with unknown types.
  32986. chunkIndex += chunkLength;
  32987. }
  32988. if (this.content === null) {
  32989. throw new Error('THREE.GLTFLoader: JSON content not found.');
  32990. }
  32991. }
  32992. /**
  32993. * DRACO Mesh Compression Extension
  32994. *
  32995. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_draco_mesh_compression
  32996. */
  32997. function GLTFDracoMeshCompressionExtension(json, dracoLoader) {
  32998. if (!dracoLoader) {
  32999. throw new Error('THREE.GLTFLoader: No DRACOLoader instance provided.');
  33000. }
  33001. this.name = EXTENSIONS.KHR_DRACO_MESH_COMPRESSION;
  33002. this.json = json;
  33003. this.dracoLoader = dracoLoader;
  33004. this.dracoLoader.preload();
  33005. }
  33006. GLTFDracoMeshCompressionExtension.prototype.decodePrimitive = function (primitive, parser) {
  33007. var json = this.json;
  33008. var dracoLoader = this.dracoLoader;
  33009. var bufferViewIndex = primitive.extensions[this.name].bufferView;
  33010. var gltfAttributeMap = primitive.extensions[this.name].attributes;
  33011. var threeAttributeMap = {};
  33012. var attributeNormalizedMap = {};
  33013. var attributeTypeMap = {};
  33014. for (var attributeName in gltfAttributeMap) {
  33015. var threeAttributeName = ATTRIBUTES[attributeName] || attributeName.toLowerCase();
  33016. threeAttributeMap[threeAttributeName] = gltfAttributeMap[attributeName];
  33017. }
  33018. for (attributeName in primitive.attributes) {
  33019. var threeAttributeName = ATTRIBUTES[attributeName] || attributeName.toLowerCase();
  33020. if (gltfAttributeMap[attributeName] !== undefined) {
  33021. var accessorDef = json.accessors[primitive.attributes[attributeName]];
  33022. var componentType = WEBGL_COMPONENT_TYPES[accessorDef.componentType];
  33023. attributeTypeMap[threeAttributeName] = componentType;
  33024. attributeNormalizedMap[threeAttributeName] = accessorDef.normalized === true;
  33025. }
  33026. }
  33027. return parser.getDependency('bufferView', bufferViewIndex).then(function (bufferView) {
  33028. return new Promise(function (resolve) {
  33029. dracoLoader.decodeDracoFile(bufferView, function (geometry) {
  33030. for (var attributeName in geometry.attributes) {
  33031. var attribute = geometry.attributes[attributeName];
  33032. var normalized = attributeNormalizedMap[attributeName];
  33033. if (normalized !== undefined) attribute.normalized = normalized;
  33034. }
  33035. resolve(geometry);
  33036. }, threeAttributeMap, attributeTypeMap);
  33037. });
  33038. });
  33039. };
  33040. /**
  33041. * Texture Transform Extension
  33042. *
  33043. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_texture_transform
  33044. */
  33045. function GLTFTextureTransformExtension() {
  33046. this.name = EXTENSIONS.KHR_TEXTURE_TRANSFORM;
  33047. }
  33048. GLTFTextureTransformExtension.prototype.extendTexture = function (texture, transform) {
  33049. texture = texture.clone();
  33050. if (transform.offset !== undefined) {
  33051. texture.offset.fromArray(transform.offset);
  33052. }
  33053. if (transform.rotation !== undefined) {
  33054. texture.rotation = transform.rotation;
  33055. }
  33056. if (transform.scale !== undefined) {
  33057. texture.repeat.fromArray(transform.scale);
  33058. }
  33059. if (transform.texCoord !== undefined) {
  33060. console.warn('THREE.GLTFLoader: Custom UV sets in "' + this.name + '" extension not yet supported.');
  33061. }
  33062. texture.needsUpdate = true;
  33063. return texture;
  33064. };
  33065. /**
  33066. * Specular-Glossiness Extension
  33067. *
  33068. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_pbrSpecularGlossiness
  33069. */
  33070. /**
  33071. * A sub class of StandardMaterial with some of the functionality
  33072. * changed via the `onBeforeCompile` callback
  33073. * @pailhead
  33074. */
  33075. function GLTFMeshStandardSGMaterial(params) {
  33076. _threeModule.MeshStandardMaterial.call(this);
  33077. this.isGLTFSpecularGlossinessMaterial = true; //various chunks that need replacing
  33078. var specularMapParsFragmentChunk = ['#ifdef USE_SPECULARMAP', ' uniform sampler2D specularMap;', '#endif'].join('\n');
  33079. var glossinessMapParsFragmentChunk = ['#ifdef USE_GLOSSINESSMAP', ' uniform sampler2D glossinessMap;', '#endif'].join('\n');
  33080. var specularMapFragmentChunk = ['vec3 specularFactor = specular;', '#ifdef USE_SPECULARMAP', ' vec4 texelSpecular = texture2D( specularMap, vUv );', ' texelSpecular = sRGBToLinear( texelSpecular );', ' // reads channel RGB, compatible with a glTF Specular-Glossiness (RGBA) texture', ' specularFactor *= texelSpecular.rgb;', '#endif'].join('\n');
  33081. var glossinessMapFragmentChunk = ['float glossinessFactor = glossiness;', '#ifdef USE_GLOSSINESSMAP', ' vec4 texelGlossiness = texture2D( glossinessMap, vUv );', ' // reads channel A, compatible with a glTF Specular-Glossiness (RGBA) texture', ' glossinessFactor *= texelGlossiness.a;', '#endif'].join('\n');
  33082. var lightPhysicalFragmentChunk = ['PhysicalMaterial material;', 'material.diffuseColor = diffuseColor.rgb * ( 1. - max( specularFactor.r, max( specularFactor.g, specularFactor.b ) ) );', 'vec3 dxy = max( abs( dFdx( geometryNormal ) ), abs( dFdy( geometryNormal ) ) );', 'float geometryRoughness = max( max( dxy.x, dxy.y ), dxy.z );', 'material.specularRoughness = max( 1.0 - glossinessFactor, 0.0525 ); // 0.0525 corresponds to the base mip of a 256 cubemap.', 'material.specularRoughness += geometryRoughness;', 'material.specularRoughness = min( material.specularRoughness, 1.0 );', 'material.specularColor = specularFactor;'].join('\n');
  33083. var uniforms = {
  33084. specular: {
  33085. value: new _threeModule.Color().setHex(0xffffff)
  33086. },
  33087. glossiness: {
  33088. value: 1
  33089. },
  33090. specularMap: {
  33091. value: null
  33092. },
  33093. glossinessMap: {
  33094. value: null
  33095. }
  33096. };
  33097. this._extraUniforms = uniforms;
  33098. this.onBeforeCompile = function (shader) {
  33099. for (var uniformName in uniforms) {
  33100. shader.uniforms[uniformName] = uniforms[uniformName];
  33101. }
  33102. shader.fragmentShader = shader.fragmentShader.replace('uniform float roughness;', 'uniform vec3 specular;').replace('uniform float metalness;', 'uniform float glossiness;').replace('#include <roughnessmap_pars_fragment>', specularMapParsFragmentChunk).replace('#include <metalnessmap_pars_fragment>', glossinessMapParsFragmentChunk).replace('#include <roughnessmap_fragment>', specularMapFragmentChunk).replace('#include <metalnessmap_fragment>', glossinessMapFragmentChunk).replace('#include <lights_physical_fragment>', lightPhysicalFragmentChunk);
  33103. };
  33104. Object.defineProperties(this, {
  33105. specular: {
  33106. get: function () {
  33107. return uniforms.specular.value;
  33108. },
  33109. set: function (v) {
  33110. uniforms.specular.value = v;
  33111. }
  33112. },
  33113. specularMap: {
  33114. get: function () {
  33115. return uniforms.specularMap.value;
  33116. },
  33117. set: function (v) {
  33118. uniforms.specularMap.value = v;
  33119. if (v) {
  33120. this.defines.USE_SPECULARMAP = ''; // USE_UV is set by the renderer for specular maps
  33121. } else {
  33122. delete this.defines.USE_SPECULARMAP;
  33123. }
  33124. }
  33125. },
  33126. glossiness: {
  33127. get: function () {
  33128. return uniforms.glossiness.value;
  33129. },
  33130. set: function (v) {
  33131. uniforms.glossiness.value = v;
  33132. }
  33133. },
  33134. glossinessMap: {
  33135. get: function () {
  33136. return uniforms.glossinessMap.value;
  33137. },
  33138. set: function (v) {
  33139. uniforms.glossinessMap.value = v;
  33140. if (v) {
  33141. this.defines.USE_GLOSSINESSMAP = '';
  33142. this.defines.USE_UV = '';
  33143. } else {
  33144. delete this.defines.USE_GLOSSINESSMAP;
  33145. delete this.defines.USE_UV;
  33146. }
  33147. }
  33148. }
  33149. });
  33150. delete this.metalness;
  33151. delete this.roughness;
  33152. delete this.metalnessMap;
  33153. delete this.roughnessMap;
  33154. this.setValues(params);
  33155. }
  33156. GLTFMeshStandardSGMaterial.prototype = Object.create(_threeModule.MeshStandardMaterial.prototype);
  33157. GLTFMeshStandardSGMaterial.prototype.constructor = GLTFMeshStandardSGMaterial;
  33158. GLTFMeshStandardSGMaterial.prototype.copy = function (source) {
  33159. _threeModule.MeshStandardMaterial.prototype.copy.call(this, source);
  33160. this.specularMap = source.specularMap;
  33161. this.specular.copy(source.specular);
  33162. this.glossinessMap = source.glossinessMap;
  33163. this.glossiness = source.glossiness;
  33164. delete this.metalness;
  33165. delete this.roughness;
  33166. delete this.metalnessMap;
  33167. delete this.roughnessMap;
  33168. return this;
  33169. };
  33170. function GLTFMaterialsPbrSpecularGlossinessExtension() {
  33171. return {
  33172. name: EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS,
  33173. specularGlossinessParams: ['color', 'map', 'lightMap', 'lightMapIntensity', 'aoMap', 'aoMapIntensity', 'emissive', 'emissiveIntensity', 'emissiveMap', 'bumpMap', 'bumpScale', 'normalMap', 'normalMapType', 'displacementMap', 'displacementScale', 'displacementBias', 'specularMap', 'specular', 'glossinessMap', 'glossiness', 'alphaMap', 'envMap', 'envMapIntensity', 'refractionRatio'],
  33174. getMaterialType: function () {
  33175. return GLTFMeshStandardSGMaterial;
  33176. },
  33177. extendParams: function (materialParams, materialDef, parser) {
  33178. var pbrSpecularGlossiness = materialDef.extensions[this.name];
  33179. materialParams.color = new _threeModule.Color(1.0, 1.0, 1.0);
  33180. materialParams.opacity = 1.0;
  33181. var pending = [];
  33182. if (Array.isArray(pbrSpecularGlossiness.diffuseFactor)) {
  33183. var array = pbrSpecularGlossiness.diffuseFactor;
  33184. materialParams.color.fromArray(array);
  33185. materialParams.opacity = array[3];
  33186. }
  33187. if (pbrSpecularGlossiness.diffuseTexture !== undefined) {
  33188. pending.push(parser.assignTexture(materialParams, 'map', pbrSpecularGlossiness.diffuseTexture));
  33189. }
  33190. materialParams.emissive = new _threeModule.Color(0.0, 0.0, 0.0);
  33191. materialParams.glossiness = pbrSpecularGlossiness.glossinessFactor !== undefined ? pbrSpecularGlossiness.glossinessFactor : 1.0;
  33192. materialParams.specular = new _threeModule.Color(1.0, 1.0, 1.0);
  33193. if (Array.isArray(pbrSpecularGlossiness.specularFactor)) {
  33194. materialParams.specular.fromArray(pbrSpecularGlossiness.specularFactor);
  33195. }
  33196. if (pbrSpecularGlossiness.specularGlossinessTexture !== undefined) {
  33197. var specGlossMapDef = pbrSpecularGlossiness.specularGlossinessTexture;
  33198. pending.push(parser.assignTexture(materialParams, 'glossinessMap', specGlossMapDef));
  33199. pending.push(parser.assignTexture(materialParams, 'specularMap', specGlossMapDef));
  33200. }
  33201. return Promise.all(pending);
  33202. },
  33203. createMaterial: function (materialParams) {
  33204. var material = new GLTFMeshStandardSGMaterial(materialParams);
  33205. material.fog = true;
  33206. material.color = materialParams.color;
  33207. material.map = materialParams.map === undefined ? null : materialParams.map;
  33208. material.lightMap = null;
  33209. material.lightMapIntensity = 1.0;
  33210. material.aoMap = materialParams.aoMap === undefined ? null : materialParams.aoMap;
  33211. material.aoMapIntensity = 1.0;
  33212. material.emissive = materialParams.emissive;
  33213. material.emissiveIntensity = 1.0;
  33214. material.emissiveMap = materialParams.emissiveMap === undefined ? null : materialParams.emissiveMap;
  33215. material.bumpMap = materialParams.bumpMap === undefined ? null : materialParams.bumpMap;
  33216. material.bumpScale = 1;
  33217. material.normalMap = materialParams.normalMap === undefined ? null : materialParams.normalMap;
  33218. material.normalMapType = _threeModule.TangentSpaceNormalMap;
  33219. if (materialParams.normalScale) material.normalScale = materialParams.normalScale;
  33220. material.displacementMap = null;
  33221. material.displacementScale = 1;
  33222. material.displacementBias = 0;
  33223. material.specularMap = materialParams.specularMap === undefined ? null : materialParams.specularMap;
  33224. material.specular = materialParams.specular;
  33225. material.glossinessMap = materialParams.glossinessMap === undefined ? null : materialParams.glossinessMap;
  33226. material.glossiness = materialParams.glossiness;
  33227. material.alphaMap = null;
  33228. material.envMap = materialParams.envMap === undefined ? null : materialParams.envMap;
  33229. material.envMapIntensity = 1.0;
  33230. material.refractionRatio = 0.98;
  33231. return material;
  33232. }
  33233. };
  33234. }
  33235. /**
  33236. * Mesh Quantization Extension
  33237. *
  33238. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_mesh_quantization
  33239. */
  33240. function GLTFMeshQuantizationExtension() {
  33241. this.name = EXTENSIONS.KHR_MESH_QUANTIZATION;
  33242. }
  33243. /*********************************/
  33244. /********** INTERPOLATION ********/
  33245. /*********************************/
  33246. // Spline Interpolation
  33247. // Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#appendix-c-spline-interpolation
  33248. function GLTFCubicSplineInterpolant(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  33249. _threeModule.Interpolant.call(this, parameterPositions, sampleValues, sampleSize, resultBuffer);
  33250. }
  33251. GLTFCubicSplineInterpolant.prototype = Object.create(_threeModule.Interpolant.prototype);
  33252. GLTFCubicSplineInterpolant.prototype.constructor = GLTFCubicSplineInterpolant;
  33253. GLTFCubicSplineInterpolant.prototype.copySampleValue_ = function (index) {
  33254. // Copies a sample value to the result buffer. See description of glTF
  33255. // CUBICSPLINE values layout in interpolate_() function below.
  33256. var result = this.resultBuffer,
  33257. values = this.sampleValues,
  33258. valueSize = this.valueSize,
  33259. offset = index * valueSize * 3 + valueSize;
  33260. for (var i = 0; i !== valueSize; i++) {
  33261. result[i] = values[offset + i];
  33262. }
  33263. return result;
  33264. };
  33265. GLTFCubicSplineInterpolant.prototype.beforeStart_ = GLTFCubicSplineInterpolant.prototype.copySampleValue_;
  33266. GLTFCubicSplineInterpolant.prototype.afterEnd_ = GLTFCubicSplineInterpolant.prototype.copySampleValue_;
  33267. GLTFCubicSplineInterpolant.prototype.interpolate_ = function (i1, t0, t, t1) {
  33268. var result = this.resultBuffer;
  33269. var values = this.sampleValues;
  33270. var stride = this.valueSize;
  33271. var stride2 = stride * 2;
  33272. var stride3 = stride * 3;
  33273. var td = t1 - t0;
  33274. var p = (t - t0) / td;
  33275. var pp = p * p;
  33276. var ppp = pp * p;
  33277. var offset1 = i1 * stride3;
  33278. var offset0 = offset1 - stride3;
  33279. var s2 = -2 * ppp + 3 * pp;
  33280. var s3 = ppp - pp;
  33281. var s0 = 1 - s2;
  33282. var s1 = s3 - pp + p; // Layout of keyframe output values for CUBICSPLINE animations:
  33283. // [ inTangent_1, splineVertex_1, outTangent_1, inTangent_2, splineVertex_2, ... ]
  33284. for (var i = 0; i !== stride; i++) {
  33285. var p0 = values[offset0 + i + stride]; // splineVertex_k
  33286. var m0 = values[offset0 + i + stride2] * td; // outTangent_k * (t_k+1 - t_k)
  33287. var p1 = values[offset1 + i + stride]; // splineVertex_k+1
  33288. var m1 = values[offset1 + i] * td; // inTangent_k+1 * (t_k+1 - t_k)
  33289. result[i] = s0 * p0 + s1 * m0 + s2 * p1 + s3 * m1;
  33290. }
  33291. return result;
  33292. };
  33293. /*********************************/
  33294. /********** INTERNALS ************/
  33295. /*********************************/
  33296. /* CONSTANTS */
  33297. var WEBGL_CONSTANTS = {
  33298. FLOAT: 5126,
  33299. //FLOAT_MAT2: 35674,
  33300. FLOAT_MAT3: 35675,
  33301. FLOAT_MAT4: 35676,
  33302. FLOAT_VEC2: 35664,
  33303. FLOAT_VEC3: 35665,
  33304. FLOAT_VEC4: 35666,
  33305. LINEAR: 9729,
  33306. REPEAT: 10497,
  33307. SAMPLER_2D: 35678,
  33308. POINTS: 0,
  33309. LINES: 1,
  33310. LINE_LOOP: 2,
  33311. LINE_STRIP: 3,
  33312. TRIANGLES: 4,
  33313. TRIANGLE_STRIP: 5,
  33314. TRIANGLE_FAN: 6,
  33315. UNSIGNED_BYTE: 5121,
  33316. UNSIGNED_SHORT: 5123
  33317. };
  33318. var WEBGL_COMPONENT_TYPES = {
  33319. 5120: Int8Array,
  33320. 5121: Uint8Array,
  33321. 5122: Int16Array,
  33322. 5123: Uint16Array,
  33323. 5125: Uint32Array,
  33324. 5126: Float32Array
  33325. };
  33326. var WEBGL_FILTERS = {
  33327. 9728: _threeModule.NearestFilter,
  33328. 9729: _threeModule.LinearFilter,
  33329. 9984: _threeModule.NearestMipmapNearestFilter,
  33330. 9985: _threeModule.LinearMipmapNearestFilter,
  33331. 9986: _threeModule.NearestMipmapLinearFilter,
  33332. 9987: _threeModule.LinearMipmapLinearFilter
  33333. };
  33334. var WEBGL_WRAPPINGS = {
  33335. 33071: _threeModule.ClampToEdgeWrapping,
  33336. 33648: _threeModule.MirroredRepeatWrapping,
  33337. 10497: _threeModule.RepeatWrapping
  33338. };
  33339. var WEBGL_TYPE_SIZES = {
  33340. 'SCALAR': 1,
  33341. 'VEC2': 2,
  33342. 'VEC3': 3,
  33343. 'VEC4': 4,
  33344. 'MAT2': 4,
  33345. 'MAT3': 9,
  33346. 'MAT4': 16
  33347. };
  33348. var ATTRIBUTES = {
  33349. POSITION: 'position',
  33350. NORMAL: 'normal',
  33351. TANGENT: 'tangent',
  33352. TEXCOORD_0: 'uv',
  33353. TEXCOORD_1: 'uv2',
  33354. COLOR_0: 'color',
  33355. WEIGHTS_0: 'skinWeight',
  33356. JOINTS_0: 'skinIndex'
  33357. };
  33358. var PATH_PROPERTIES = {
  33359. scale: 'scale',
  33360. translation: 'position',
  33361. rotation: 'quaternion',
  33362. weights: 'morphTargetInfluences'
  33363. };
  33364. var INTERPOLATION = {
  33365. CUBICSPLINE: undefined,
  33366. // We use a custom interpolant (GLTFCubicSplineInterpolation) for CUBICSPLINE tracks. Each
  33367. // keyframe track will be initialized with a default interpolation type, then modified.
  33368. LINEAR: _threeModule.InterpolateLinear,
  33369. STEP: _threeModule.InterpolateDiscrete
  33370. };
  33371. var ALPHA_MODES = {
  33372. OPAQUE: 'OPAQUE',
  33373. MASK: 'MASK',
  33374. BLEND: 'BLEND'
  33375. };
  33376. /* UTILITY FUNCTIONS */
  33377. function resolveURL(url, path) {
  33378. // Invalid URL
  33379. if (typeof url !== 'string' || url === '') return ''; // Host Relative URL
  33380. if (/^https?:\/\//i.test(path) && /^\//.test(url)) {
  33381. path = path.replace(/(^https?:\/\/[^\/]+).*/i, '$1');
  33382. } // Absolute URL http://,https://,//
  33383. if (/^(https?:)?\/\//i.test(url)) return url; // Data URI
  33384. if (/^data:.*,.*$/i.test(url)) return url; // Blob URL
  33385. if (/^blob:.*$/i.test(url)) return url; // Relative URL
  33386. return path + url;
  33387. }
  33388. /**
  33389. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#default-material
  33390. */
  33391. function createDefaultMaterial(cache) {
  33392. if (cache['DefaultMaterial'] === undefined) {
  33393. cache['DefaultMaterial'] = new _threeModule.MeshStandardMaterial({
  33394. color: 0xFFFFFF,
  33395. emissive: 0x000000,
  33396. metalness: 1,
  33397. roughness: 1,
  33398. transparent: false,
  33399. depthTest: true,
  33400. side: _threeModule.FrontSide
  33401. });
  33402. }
  33403. return cache['DefaultMaterial'];
  33404. }
  33405. function addUnknownExtensionsToUserData(knownExtensions, object, objectDef) {
  33406. // Add unknown glTF extensions to an object's userData.
  33407. for (var name in objectDef.extensions) {
  33408. if (knownExtensions[name] === undefined) {
  33409. object.userData.gltfExtensions = object.userData.gltfExtensions || {};
  33410. object.userData.gltfExtensions[name] = objectDef.extensions[name];
  33411. }
  33412. }
  33413. }
  33414. /**
  33415. * @param {Object3D|Material|BufferGeometry} object
  33416. * @param {GLTF.definition} gltfDef
  33417. */
  33418. function assignExtrasToUserData(object, gltfDef) {
  33419. if (gltfDef.extras !== undefined) {
  33420. if (typeof gltfDef.extras === 'object') {
  33421. Object.assign(object.userData, gltfDef.extras);
  33422. } else {
  33423. console.warn('THREE.GLTFLoader: Ignoring primitive type .extras, ' + gltfDef.extras);
  33424. }
  33425. }
  33426. }
  33427. /**
  33428. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#morph-targets
  33429. *
  33430. * @param {BufferGeometry} geometry
  33431. * @param {Array<GLTF.Target>} targets
  33432. * @param {GLTFParser} parser
  33433. * @return {Promise<BufferGeometry>}
  33434. */
  33435. function addMorphTargets(geometry, targets, parser) {
  33436. var hasMorphPosition = false;
  33437. var hasMorphNormal = false;
  33438. for (var i = 0, il = targets.length; i < il; i++) {
  33439. var target = targets[i];
  33440. if (target.POSITION !== undefined) hasMorphPosition = true;
  33441. if (target.NORMAL !== undefined) hasMorphNormal = true;
  33442. if (hasMorphPosition && hasMorphNormal) break;
  33443. }
  33444. if (!hasMorphPosition && !hasMorphNormal) return Promise.resolve(geometry);
  33445. var pendingPositionAccessors = [];
  33446. var pendingNormalAccessors = [];
  33447. for (var i = 0, il = targets.length; i < il; i++) {
  33448. var target = targets[i];
  33449. if (hasMorphPosition) {
  33450. var pendingAccessor = target.POSITION !== undefined ? parser.getDependency('accessor', target.POSITION) : geometry.attributes.position;
  33451. pendingPositionAccessors.push(pendingAccessor);
  33452. }
  33453. if (hasMorphNormal) {
  33454. var pendingAccessor = target.NORMAL !== undefined ? parser.getDependency('accessor', target.NORMAL) : geometry.attributes.normal;
  33455. pendingNormalAccessors.push(pendingAccessor);
  33456. }
  33457. }
  33458. return Promise.all([Promise.all(pendingPositionAccessors), Promise.all(pendingNormalAccessors)]).then(function (accessors) {
  33459. var morphPositions = accessors[0];
  33460. var morphNormals = accessors[1];
  33461. if (hasMorphPosition) geometry.morphAttributes.position = morphPositions;
  33462. if (hasMorphNormal) geometry.morphAttributes.normal = morphNormals;
  33463. geometry.morphTargetsRelative = true;
  33464. return geometry;
  33465. });
  33466. }
  33467. /**
  33468. * @param {Mesh} mesh
  33469. * @param {GLTF.Mesh} meshDef
  33470. */
  33471. function updateMorphTargets(mesh, meshDef) {
  33472. mesh.updateMorphTargets();
  33473. if (meshDef.weights !== undefined) {
  33474. for (var i = 0, il = meshDef.weights.length; i < il; i++) {
  33475. mesh.morphTargetInfluences[i] = meshDef.weights[i];
  33476. }
  33477. } // .extras has user-defined data, so check that .extras.targetNames is an array.
  33478. if (meshDef.extras && Array.isArray(meshDef.extras.targetNames)) {
  33479. var targetNames = meshDef.extras.targetNames;
  33480. if (mesh.morphTargetInfluences.length === targetNames.length) {
  33481. mesh.morphTargetDictionary = {};
  33482. for (var i = 0, il = targetNames.length; i < il; i++) {
  33483. mesh.morphTargetDictionary[targetNames[i]] = i;
  33484. }
  33485. } else {
  33486. console.warn('THREE.GLTFLoader: Invalid extras.targetNames length. Ignoring names.');
  33487. }
  33488. }
  33489. }
  33490. function createPrimitiveKey(primitiveDef) {
  33491. var dracoExtension = primitiveDef.extensions && primitiveDef.extensions[EXTENSIONS.KHR_DRACO_MESH_COMPRESSION];
  33492. var geometryKey;
  33493. if (dracoExtension) {
  33494. geometryKey = 'draco:' + dracoExtension.bufferView + ':' + dracoExtension.indices + ':' + createAttributesKey(dracoExtension.attributes);
  33495. } else {
  33496. geometryKey = primitiveDef.indices + ':' + createAttributesKey(primitiveDef.attributes) + ':' + primitiveDef.mode;
  33497. }
  33498. return geometryKey;
  33499. }
  33500. function createAttributesKey(attributes) {
  33501. var attributesKey = '';
  33502. var keys = Object.keys(attributes).sort();
  33503. for (var i = 0, il = keys.length; i < il; i++) {
  33504. attributesKey += keys[i] + ':' + attributes[keys[i]] + ';';
  33505. }
  33506. return attributesKey;
  33507. }
  33508. /* GLTF PARSER */
  33509. function GLTFParser(json, options) {
  33510. this.json = json || {};
  33511. this.extensions = {};
  33512. this.plugins = {};
  33513. this.options = options || {}; // loader object cache
  33514. this.cache = new GLTFRegistry(); // associations between Three.js objects and glTF elements
  33515. this.associations = new Map(); // BufferGeometry caching
  33516. this.primitiveCache = {}; // Object3D instance caches
  33517. this.meshCache = {
  33518. refs: {},
  33519. uses: {}
  33520. };
  33521. this.cameraCache = {
  33522. refs: {},
  33523. uses: {}
  33524. };
  33525. this.lightCache = {
  33526. refs: {},
  33527. uses: {}
  33528. }; // Track node names, to ensure no duplicates
  33529. this.nodeNamesUsed = {}; // Use an ImageBitmapLoader if imageBitmaps are supported. Moves much of the
  33530. // expensive work of uploading a texture to the GPU off the main thread.
  33531. if (typeof createImageBitmap !== 'undefined' && /Firefox/.test(navigator.userAgent) === false) {
  33532. this.textureLoader = new _threeModule.ImageBitmapLoader(this.options.manager);
  33533. } else {
  33534. this.textureLoader = new _threeModule.TextureLoader(this.options.manager);
  33535. }
  33536. this.textureLoader.setCrossOrigin(this.options.crossOrigin);
  33537. this.fileLoader = new _threeModule.FileLoader(this.options.manager);
  33538. this.fileLoader.setResponseType('arraybuffer');
  33539. if (this.options.crossOrigin === 'use-credentials') {
  33540. this.fileLoader.setWithCredentials(true);
  33541. }
  33542. }
  33543. GLTFParser.prototype.setExtensions = function (extensions) {
  33544. this.extensions = extensions;
  33545. };
  33546. GLTFParser.prototype.setPlugins = function (plugins) {
  33547. this.plugins = plugins;
  33548. };
  33549. GLTFParser.prototype.parse = function (onLoad, onError) {
  33550. var parser = this;
  33551. var json = this.json;
  33552. var extensions = this.extensions; // Clear the loader cache
  33553. this.cache.removeAll(); // Mark the special nodes/meshes in json for efficient parse
  33554. this._invokeAll(function (ext) {
  33555. return ext._markDefs && ext._markDefs();
  33556. });
  33557. Promise.all([this.getDependencies('scene'), this.getDependencies('animation'), this.getDependencies('camera')]).then(function (dependencies) {
  33558. var result = {
  33559. scene: dependencies[0][json.scene || 0],
  33560. scenes: dependencies[0],
  33561. animations: dependencies[1],
  33562. cameras: dependencies[2],
  33563. asset: json.asset,
  33564. parser: parser,
  33565. userData: {}
  33566. };
  33567. addUnknownExtensionsToUserData(extensions, result, json);
  33568. assignExtrasToUserData(result, json);
  33569. onLoad(result);
  33570. }).catch(onError);
  33571. };
  33572. /**
  33573. * Marks the special nodes/meshes in json for efficient parse.
  33574. */
  33575. GLTFParser.prototype._markDefs = function () {
  33576. var nodeDefs = this.json.nodes || [];
  33577. var skinDefs = this.json.skins || [];
  33578. var meshDefs = this.json.meshes || []; // Nothing in the node definition indicates whether it is a Bone or an
  33579. // Object3D. Use the skins' joint references to mark bones.
  33580. for (var skinIndex = 0, skinLength = skinDefs.length; skinIndex < skinLength; skinIndex++) {
  33581. var joints = skinDefs[skinIndex].joints;
  33582. for (var i = 0, il = joints.length; i < il; i++) {
  33583. nodeDefs[joints[i]].isBone = true;
  33584. }
  33585. } // Iterate over all nodes, marking references to shared resources,
  33586. // as well as skeleton joints.
  33587. for (var nodeIndex = 0, nodeLength = nodeDefs.length; nodeIndex < nodeLength; nodeIndex++) {
  33588. var nodeDef = nodeDefs[nodeIndex];
  33589. if (nodeDef.mesh !== undefined) {
  33590. this._addNodeRef(this.meshCache, nodeDef.mesh); // Nothing in the mesh definition indicates whether it is
  33591. // a SkinnedMesh or Mesh. Use the node's mesh reference
  33592. // to mark SkinnedMesh if node has skin.
  33593. if (nodeDef.skin !== undefined) {
  33594. meshDefs[nodeDef.mesh].isSkinnedMesh = true;
  33595. }
  33596. }
  33597. if (nodeDef.camera !== undefined) {
  33598. this._addNodeRef(this.cameraCache, nodeDef.camera);
  33599. }
  33600. }
  33601. };
  33602. /**
  33603. * Counts references to shared node / Object3D resources. These resources
  33604. * can be reused, or "instantiated", at multiple nodes in the scene
  33605. * hierarchy. Mesh, Camera, and Light instances are instantiated and must
  33606. * be marked. Non-scenegraph resources (like Materials, Geometries, and
  33607. * Textures) can be reused directly and are not marked here.
  33608. *
  33609. * Example: CesiumMilkTruck sample model reuses "Wheel" meshes.
  33610. */
  33611. GLTFParser.prototype._addNodeRef = function (cache, index) {
  33612. if (index === undefined) return;
  33613. if (cache.refs[index] === undefined) {
  33614. cache.refs[index] = cache.uses[index] = 0;
  33615. }
  33616. cache.refs[index]++;
  33617. };
  33618. /** Returns a reference to a shared resource, cloning it if necessary. */
  33619. GLTFParser.prototype._getNodeRef = function (cache, index, object) {
  33620. if (cache.refs[index] <= 1) return object;
  33621. var ref = object.clone();
  33622. ref.name += '_instance_' + cache.uses[index]++;
  33623. return ref;
  33624. };
  33625. GLTFParser.prototype._invokeOne = function (func) {
  33626. var extensions = Object.values(this.plugins);
  33627. extensions.push(this);
  33628. for (var i = 0; i < extensions.length; i++) {
  33629. var result = func(extensions[i]);
  33630. if (result) return result;
  33631. }
  33632. };
  33633. GLTFParser.prototype._invokeAll = function (func) {
  33634. var extensions = Object.values(this.plugins);
  33635. extensions.unshift(this);
  33636. var pending = [];
  33637. for (var i = 0; i < extensions.length; i++) {
  33638. var result = func(extensions[i]);
  33639. if (result) pending.push(result);
  33640. }
  33641. return pending;
  33642. };
  33643. /**
  33644. * Requests the specified dependency asynchronously, with caching.
  33645. * @param {string} type
  33646. * @param {number} index
  33647. * @return {Promise<Object3D|Material|THREE.Texture|AnimationClip|ArrayBuffer|Object>}
  33648. */
  33649. GLTFParser.prototype.getDependency = function (type, index) {
  33650. var cacheKey = type + ':' + index;
  33651. var dependency = this.cache.get(cacheKey);
  33652. if (!dependency) {
  33653. switch (type) {
  33654. case 'scene':
  33655. dependency = this.loadScene(index);
  33656. break;
  33657. case 'node':
  33658. dependency = this.loadNode(index);
  33659. break;
  33660. case 'mesh':
  33661. dependency = this._invokeOne(function (ext) {
  33662. return ext.loadMesh && ext.loadMesh(index);
  33663. });
  33664. break;
  33665. case 'accessor':
  33666. dependency = this.loadAccessor(index);
  33667. break;
  33668. case 'bufferView':
  33669. dependency = this._invokeOne(function (ext) {
  33670. return ext.loadBufferView && ext.loadBufferView(index);
  33671. });
  33672. break;
  33673. case 'buffer':
  33674. dependency = this.loadBuffer(index);
  33675. break;
  33676. case 'material':
  33677. dependency = this._invokeOne(function (ext) {
  33678. return ext.loadMaterial && ext.loadMaterial(index);
  33679. });
  33680. break;
  33681. case 'texture':
  33682. dependency = this._invokeOne(function (ext) {
  33683. return ext.loadTexture && ext.loadTexture(index);
  33684. });
  33685. break;
  33686. case 'skin':
  33687. dependency = this.loadSkin(index);
  33688. break;
  33689. case 'animation':
  33690. dependency = this.loadAnimation(index);
  33691. break;
  33692. case 'camera':
  33693. dependency = this.loadCamera(index);
  33694. break;
  33695. default:
  33696. throw new Error('Unknown type: ' + type);
  33697. }
  33698. this.cache.add(cacheKey, dependency);
  33699. }
  33700. return dependency;
  33701. };
  33702. /**
  33703. * Requests all dependencies of the specified type asynchronously, with caching.
  33704. * @param {string} type
  33705. * @return {Promise<Array<Object>>}
  33706. */
  33707. GLTFParser.prototype.getDependencies = function (type) {
  33708. var dependencies = this.cache.get(type);
  33709. if (!dependencies) {
  33710. var parser = this;
  33711. var defs = this.json[type + (type === 'mesh' ? 'es' : 's')] || [];
  33712. dependencies = Promise.all(defs.map(function (def, index) {
  33713. return parser.getDependency(type, index);
  33714. }));
  33715. this.cache.add(type, dependencies);
  33716. }
  33717. return dependencies;
  33718. };
  33719. /**
  33720. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#buffers-and-buffer-views
  33721. * @param {number} bufferIndex
  33722. * @return {Promise<ArrayBuffer>}
  33723. */
  33724. GLTFParser.prototype.loadBuffer = function (bufferIndex) {
  33725. var bufferDef = this.json.buffers[bufferIndex];
  33726. var loader = this.fileLoader;
  33727. if (bufferDef.type && bufferDef.type !== 'arraybuffer') {
  33728. throw new Error('THREE.GLTFLoader: ' + bufferDef.type + ' buffer type is not supported.');
  33729. } // If present, GLB container is required to be the first buffer.
  33730. if (bufferDef.uri === undefined && bufferIndex === 0) {
  33731. return Promise.resolve(this.extensions[EXTENSIONS.KHR_BINARY_GLTF].body);
  33732. }
  33733. var options = this.options;
  33734. return new Promise(function (resolve, reject) {
  33735. loader.load(resolveURL(bufferDef.uri, options.path), resolve, undefined, function () {
  33736. reject(new Error('THREE.GLTFLoader: Failed to load buffer "' + bufferDef.uri + '".'));
  33737. });
  33738. });
  33739. };
  33740. /**
  33741. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#buffers-and-buffer-views
  33742. * @param {number} bufferViewIndex
  33743. * @return {Promise<ArrayBuffer>}
  33744. */
  33745. GLTFParser.prototype.loadBufferView = function (bufferViewIndex) {
  33746. var bufferViewDef = this.json.bufferViews[bufferViewIndex];
  33747. return this.getDependency('buffer', bufferViewDef.buffer).then(function (buffer) {
  33748. var byteLength = bufferViewDef.byteLength || 0;
  33749. var byteOffset = bufferViewDef.byteOffset || 0;
  33750. return buffer.slice(byteOffset, byteOffset + byteLength);
  33751. });
  33752. };
  33753. /**
  33754. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#accessors
  33755. * @param {number} accessorIndex
  33756. * @return {Promise<BufferAttribute|InterleavedBufferAttribute>}
  33757. */
  33758. GLTFParser.prototype.loadAccessor = function (accessorIndex) {
  33759. var parser = this;
  33760. var json = this.json;
  33761. var accessorDef = this.json.accessors[accessorIndex];
  33762. if (accessorDef.bufferView === undefined && accessorDef.sparse === undefined) {
  33763. // Ignore empty accessors, which may be used to declare runtime
  33764. // information about attributes coming from another source (e.g. Draco
  33765. // compression extension).
  33766. return Promise.resolve(null);
  33767. }
  33768. var pendingBufferViews = [];
  33769. if (accessorDef.bufferView !== undefined) {
  33770. pendingBufferViews.push(this.getDependency('bufferView', accessorDef.bufferView));
  33771. } else {
  33772. pendingBufferViews.push(null);
  33773. }
  33774. if (accessorDef.sparse !== undefined) {
  33775. pendingBufferViews.push(this.getDependency('bufferView', accessorDef.sparse.indices.bufferView));
  33776. pendingBufferViews.push(this.getDependency('bufferView', accessorDef.sparse.values.bufferView));
  33777. }
  33778. return Promise.all(pendingBufferViews).then(function (bufferViews) {
  33779. var bufferView = bufferViews[0];
  33780. var itemSize = WEBGL_TYPE_SIZES[accessorDef.type];
  33781. var TypedArray = WEBGL_COMPONENT_TYPES[accessorDef.componentType]; // For VEC3: itemSize is 3, elementBytes is 4, itemBytes is 12.
  33782. var elementBytes = TypedArray.BYTES_PER_ELEMENT;
  33783. var itemBytes = elementBytes * itemSize;
  33784. var byteOffset = accessorDef.byteOffset || 0;
  33785. var byteStride = accessorDef.bufferView !== undefined ? json.bufferViews[accessorDef.bufferView].byteStride : undefined;
  33786. var normalized = accessorDef.normalized === true;
  33787. var array, bufferAttribute; // The buffer is not interleaved if the stride is the item size in bytes.
  33788. if (byteStride && byteStride !== itemBytes) {
  33789. // Each "slice" of the buffer, as defined by 'count' elements of 'byteStride' bytes, gets its own InterleavedBuffer
  33790. // This makes sure that IBA.count reflects accessor.count properly
  33791. var ibSlice = Math.floor(byteOffset / byteStride);
  33792. var ibCacheKey = 'InterleavedBuffer:' + accessorDef.bufferView + ':' + accessorDef.componentType + ':' + ibSlice + ':' + accessorDef.count;
  33793. var ib = parser.cache.get(ibCacheKey);
  33794. if (!ib) {
  33795. array = new TypedArray(bufferView, ibSlice * byteStride, accessorDef.count * byteStride / elementBytes); // Integer parameters to IB/IBA are in array elements, not bytes.
  33796. ib = new _threeModule.InterleavedBuffer(array, byteStride / elementBytes);
  33797. parser.cache.add(ibCacheKey, ib);
  33798. }
  33799. bufferAttribute = new _threeModule.InterleavedBufferAttribute(ib, itemSize, byteOffset % byteStride / elementBytes, normalized);
  33800. } else {
  33801. if (bufferView === null) {
  33802. array = new TypedArray(accessorDef.count * itemSize);
  33803. } else {
  33804. array = new TypedArray(bufferView, byteOffset, accessorDef.count * itemSize);
  33805. }
  33806. bufferAttribute = new _threeModule.BufferAttribute(array, itemSize, normalized);
  33807. } // https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#sparse-accessors
  33808. if (accessorDef.sparse !== undefined) {
  33809. var itemSizeIndices = WEBGL_TYPE_SIZES.SCALAR;
  33810. var TypedArrayIndices = WEBGL_COMPONENT_TYPES[accessorDef.sparse.indices.componentType];
  33811. var byteOffsetIndices = accessorDef.sparse.indices.byteOffset || 0;
  33812. var byteOffsetValues = accessorDef.sparse.values.byteOffset || 0;
  33813. var sparseIndices = new TypedArrayIndices(bufferViews[1], byteOffsetIndices, accessorDef.sparse.count * itemSizeIndices);
  33814. var sparseValues = new TypedArray(bufferViews[2], byteOffsetValues, accessorDef.sparse.count * itemSize);
  33815. if (bufferView !== null) {
  33816. // Avoid modifying the original ArrayBuffer, if the bufferView wasn't initialized with zeroes.
  33817. bufferAttribute = new _threeModule.BufferAttribute(bufferAttribute.array.slice(), bufferAttribute.itemSize, bufferAttribute.normalized);
  33818. }
  33819. for (var i = 0, il = sparseIndices.length; i < il; i++) {
  33820. var index = sparseIndices[i];
  33821. bufferAttribute.setX(index, sparseValues[i * itemSize]);
  33822. if (itemSize >= 2) bufferAttribute.setY(index, sparseValues[i * itemSize + 1]);
  33823. if (itemSize >= 3) bufferAttribute.setZ(index, sparseValues[i * itemSize + 2]);
  33824. if (itemSize >= 4) bufferAttribute.setW(index, sparseValues[i * itemSize + 3]);
  33825. if (itemSize >= 5) throw new Error('THREE.GLTFLoader: Unsupported itemSize in sparse BufferAttribute.');
  33826. }
  33827. }
  33828. return bufferAttribute;
  33829. });
  33830. };
  33831. /**
  33832. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#textures
  33833. * @param {number} textureIndex
  33834. * @return {Promise<THREE.Texture>}
  33835. */
  33836. GLTFParser.prototype.loadTexture = function (textureIndex) {
  33837. var parser = this;
  33838. var json = this.json;
  33839. var options = this.options;
  33840. var textureDef = json.textures[textureIndex];
  33841. var textureExtensions = textureDef.extensions || {};
  33842. var source;
  33843. if (textureExtensions[EXTENSIONS.MSFT_TEXTURE_DDS]) {
  33844. source = json.images[textureExtensions[EXTENSIONS.MSFT_TEXTURE_DDS].source];
  33845. } else {
  33846. source = json.images[textureDef.source];
  33847. }
  33848. var loader;
  33849. if (source.uri) {
  33850. loader = options.manager.getHandler(source.uri);
  33851. }
  33852. if (!loader) {
  33853. loader = textureExtensions[EXTENSIONS.MSFT_TEXTURE_DDS] ? parser.extensions[EXTENSIONS.MSFT_TEXTURE_DDS].ddsLoader : this.textureLoader;
  33854. }
  33855. return this.loadTextureImage(textureIndex, source, loader);
  33856. };
  33857. GLTFParser.prototype.loadTextureImage = function (textureIndex, source, loader) {
  33858. var parser = this;
  33859. var json = this.json;
  33860. var options = this.options;
  33861. var textureDef = json.textures[textureIndex];
  33862. var URL = self.URL || self.webkitURL;
  33863. var sourceURI = source.uri;
  33864. var isObjectURL = false;
  33865. var hasAlpha = true;
  33866. if (source.mimeType === 'image/jpeg') hasAlpha = false;
  33867. if (source.bufferView !== undefined) {
  33868. // Load binary image data from bufferView, if provided.
  33869. sourceURI = parser.getDependency('bufferView', source.bufferView).then(function (bufferView) {
  33870. if (source.mimeType === 'image/png') {
  33871. // Inspect the PNG 'IHDR' chunk to determine whether the image could have an
  33872. // alpha channel. This check is conservative — the image could have an alpha
  33873. // channel with all values == 1, and the indexed type (colorType == 3) only
  33874. // sometimes contains alpha.
  33875. //
  33876. // https://en.wikipedia.org/wiki/Portable_Network_Graphics#File_header
  33877. var colorType = new DataView(bufferView, 25, 1).getUint8(0, false);
  33878. hasAlpha = colorType === 6 || colorType === 4 || colorType === 3;
  33879. }
  33880. isObjectURL = true;
  33881. var blob = new Blob([bufferView], {
  33882. type: source.mimeType
  33883. });
  33884. sourceURI = URL.createObjectURL(blob);
  33885. return sourceURI;
  33886. });
  33887. }
  33888. return Promise.resolve(sourceURI).then(function (sourceURI) {
  33889. return new Promise(function (resolve, reject) {
  33890. var onLoad = resolve;
  33891. if (loader.isImageBitmapLoader === true) {
  33892. onLoad = function (imageBitmap) {
  33893. resolve(new _threeModule.CanvasTexture(imageBitmap));
  33894. };
  33895. }
  33896. loader.load(resolveURL(sourceURI, options.path), onLoad, undefined, reject);
  33897. });
  33898. }).then(function (texture) {
  33899. // Clean up resources and configure Texture.
  33900. if (isObjectURL === true) {
  33901. URL.revokeObjectURL(sourceURI);
  33902. }
  33903. texture.flipY = false;
  33904. if (textureDef.name) texture.name = textureDef.name; // When there is definitely no alpha channel in the texture, set RGBFormat to save space.
  33905. if (!hasAlpha) texture.format = _threeModule.RGBFormat;
  33906. var samplers = json.samplers || {};
  33907. var sampler = samplers[textureDef.sampler] || {};
  33908. texture.magFilter = WEBGL_FILTERS[sampler.magFilter] || _threeModule.LinearFilter;
  33909. texture.minFilter = WEBGL_FILTERS[sampler.minFilter] || _threeModule.LinearMipmapLinearFilter;
  33910. texture.wrapS = WEBGL_WRAPPINGS[sampler.wrapS] || _threeModule.RepeatWrapping;
  33911. texture.wrapT = WEBGL_WRAPPINGS[sampler.wrapT] || _threeModule.RepeatWrapping;
  33912. parser.associations.set(texture, {
  33913. type: 'textures',
  33914. index: textureIndex
  33915. });
  33916. return texture;
  33917. });
  33918. };
  33919. /**
  33920. * Asynchronously assigns a texture to the given material parameters.
  33921. * @param {Object} materialParams
  33922. * @param {string} mapName
  33923. * @param {Object} mapDef
  33924. * @return {Promise}
  33925. */
  33926. GLTFParser.prototype.assignTexture = function (materialParams, mapName, mapDef) {
  33927. var parser = this;
  33928. return this.getDependency('texture', mapDef.index).then(function (texture) {
  33929. // Materials sample aoMap from UV set 1 and other maps from UV set 0 - this can't be configured
  33930. // However, we will copy UV set 0 to UV set 1 on demand for aoMap
  33931. if (mapDef.texCoord !== undefined && mapDef.texCoord != 0 && !(mapName === 'aoMap' && mapDef.texCoord == 1)) {
  33932. console.warn('THREE.GLTFLoader: Custom UV set ' + mapDef.texCoord + ' for texture ' + mapName + ' not yet supported.');
  33933. }
  33934. if (parser.extensions[EXTENSIONS.KHR_TEXTURE_TRANSFORM]) {
  33935. var transform = mapDef.extensions !== undefined ? mapDef.extensions[EXTENSIONS.KHR_TEXTURE_TRANSFORM] : undefined;
  33936. if (transform) {
  33937. var gltfReference = parser.associations.get(texture);
  33938. texture = parser.extensions[EXTENSIONS.KHR_TEXTURE_TRANSFORM].extendTexture(texture, transform);
  33939. parser.associations.set(texture, gltfReference);
  33940. }
  33941. }
  33942. materialParams[mapName] = texture;
  33943. });
  33944. };
  33945. /**
  33946. * Assigns final material to a Mesh, Line, or Points instance. The instance
  33947. * already has a material (generated from the glTF material options alone)
  33948. * but reuse of the same glTF material may require multiple threejs materials
  33949. * to accomodate different primitive types, defines, etc. New materials will
  33950. * be created if necessary, and reused from a cache.
  33951. * @param {Object3D} mesh Mesh, Line, or Points instance.
  33952. */
  33953. GLTFParser.prototype.assignFinalMaterial = function (mesh) {
  33954. var geometry = mesh.geometry;
  33955. var material = mesh.material;
  33956. var useVertexTangents = geometry.attributes.tangent !== undefined;
  33957. var useVertexColors = geometry.attributes.color !== undefined;
  33958. var useFlatShading = geometry.attributes.normal === undefined;
  33959. var useSkinning = mesh.isSkinnedMesh === true;
  33960. var useMorphTargets = Object.keys(geometry.morphAttributes).length > 0;
  33961. var useMorphNormals = useMorphTargets && geometry.morphAttributes.normal !== undefined;
  33962. if (mesh.isPoints) {
  33963. var cacheKey = 'PointsMaterial:' + material.uuid;
  33964. var pointsMaterial = this.cache.get(cacheKey);
  33965. if (!pointsMaterial) {
  33966. pointsMaterial = new _threeModule.PointsMaterial();
  33967. _threeModule.Material.prototype.copy.call(pointsMaterial, material);
  33968. pointsMaterial.color.copy(material.color);
  33969. pointsMaterial.map = material.map;
  33970. pointsMaterial.sizeAttenuation = false; // glTF spec says points should be 1px
  33971. this.cache.add(cacheKey, pointsMaterial);
  33972. }
  33973. material = pointsMaterial;
  33974. } else if (mesh.isLine) {
  33975. var cacheKey = 'LineBasicMaterial:' + material.uuid;
  33976. var lineMaterial = this.cache.get(cacheKey);
  33977. if (!lineMaterial) {
  33978. lineMaterial = new _threeModule.LineBasicMaterial();
  33979. _threeModule.Material.prototype.copy.call(lineMaterial, material);
  33980. lineMaterial.color.copy(material.color);
  33981. this.cache.add(cacheKey, lineMaterial);
  33982. }
  33983. material = lineMaterial;
  33984. } // Clone the material if it will be modified
  33985. if (useVertexTangents || useVertexColors || useFlatShading || useSkinning || useMorphTargets) {
  33986. var cacheKey = 'ClonedMaterial:' + material.uuid + ':';
  33987. if (material.isGLTFSpecularGlossinessMaterial) cacheKey += 'specular-glossiness:';
  33988. if (useSkinning) cacheKey += 'skinning:';
  33989. if (useVertexTangents) cacheKey += 'vertex-tangents:';
  33990. if (useVertexColors) cacheKey += 'vertex-colors:';
  33991. if (useFlatShading) cacheKey += 'flat-shading:';
  33992. if (useMorphTargets) cacheKey += 'morph-targets:';
  33993. if (useMorphNormals) cacheKey += 'morph-normals:';
  33994. var cachedMaterial = this.cache.get(cacheKey);
  33995. if (!cachedMaterial) {
  33996. cachedMaterial = material.clone();
  33997. if (useSkinning) cachedMaterial.skinning = true;
  33998. if (useVertexTangents) cachedMaterial.vertexTangents = true;
  33999. if (useVertexColors) cachedMaterial.vertexColors = true;
  34000. if (useFlatShading) cachedMaterial.flatShading = true;
  34001. if (useMorphTargets) cachedMaterial.morphTargets = true;
  34002. if (useMorphNormals) cachedMaterial.morphNormals = true;
  34003. this.cache.add(cacheKey, cachedMaterial);
  34004. this.associations.set(cachedMaterial, this.associations.get(material));
  34005. }
  34006. material = cachedMaterial;
  34007. } // workarounds for mesh and geometry
  34008. if (material.aoMap && geometry.attributes.uv2 === undefined && geometry.attributes.uv !== undefined) {
  34009. geometry.setAttribute('uv2', geometry.attributes.uv);
  34010. } // https://github.com/mrdoob/three.js/issues/11438#issuecomment-507003995
  34011. if (material.normalScale && !useVertexTangents) {
  34012. material.normalScale.y = -material.normalScale.y;
  34013. }
  34014. if (material.clearcoatNormalScale && !useVertexTangents) {
  34015. material.clearcoatNormalScale.y = -material.clearcoatNormalScale.y;
  34016. }
  34017. mesh.material = material;
  34018. };
  34019. GLTFParser.prototype.getMaterialType = function ()
  34020. /* materialIndex */
  34021. {
  34022. return _threeModule.MeshStandardMaterial;
  34023. };
  34024. /**
  34025. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#materials
  34026. * @param {number} materialIndex
  34027. * @return {Promise<Material>}
  34028. */
  34029. GLTFParser.prototype.loadMaterial = function (materialIndex) {
  34030. var parser = this;
  34031. var json = this.json;
  34032. var extensions = this.extensions;
  34033. var materialDef = json.materials[materialIndex];
  34034. var materialType;
  34035. var materialParams = {};
  34036. var materialExtensions = materialDef.extensions || {};
  34037. var pending = [];
  34038. if (materialExtensions[EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS]) {
  34039. var sgExtension = extensions[EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS];
  34040. materialType = sgExtension.getMaterialType();
  34041. pending.push(sgExtension.extendParams(materialParams, materialDef, parser));
  34042. } else if (materialExtensions[EXTENSIONS.KHR_MATERIALS_UNLIT]) {
  34043. var kmuExtension = extensions[EXTENSIONS.KHR_MATERIALS_UNLIT];
  34044. materialType = kmuExtension.getMaterialType();
  34045. pending.push(kmuExtension.extendParams(materialParams, materialDef, parser));
  34046. } else {
  34047. // Specification:
  34048. // https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#metallic-roughness-material
  34049. var metallicRoughness = materialDef.pbrMetallicRoughness || {};
  34050. materialParams.color = new _threeModule.Color(1.0, 1.0, 1.0);
  34051. materialParams.opacity = 1.0;
  34052. if (Array.isArray(metallicRoughness.baseColorFactor)) {
  34053. var array = metallicRoughness.baseColorFactor;
  34054. materialParams.color.fromArray(array);
  34055. materialParams.opacity = array[3];
  34056. }
  34057. if (metallicRoughness.baseColorTexture !== undefined) {
  34058. pending.push(parser.assignTexture(materialParams, 'map', metallicRoughness.baseColorTexture));
  34059. }
  34060. materialParams.metalness = metallicRoughness.metallicFactor !== undefined ? metallicRoughness.metallicFactor : 1.0;
  34061. materialParams.roughness = metallicRoughness.roughnessFactor !== undefined ? metallicRoughness.roughnessFactor : 1.0;
  34062. if (metallicRoughness.metallicRoughnessTexture !== undefined) {
  34063. pending.push(parser.assignTexture(materialParams, 'metalnessMap', metallicRoughness.metallicRoughnessTexture));
  34064. pending.push(parser.assignTexture(materialParams, 'roughnessMap', metallicRoughness.metallicRoughnessTexture));
  34065. }
  34066. materialType = this._invokeOne(function (ext) {
  34067. return ext.getMaterialType && ext.getMaterialType(materialIndex);
  34068. });
  34069. pending.push(Promise.all(this._invokeAll(function (ext) {
  34070. return ext.extendMaterialParams && ext.extendMaterialParams(materialIndex, materialParams);
  34071. })));
  34072. }
  34073. if (materialDef.doubleSided === true) {
  34074. materialParams.side = _threeModule.DoubleSide;
  34075. }
  34076. var alphaMode = materialDef.alphaMode || ALPHA_MODES.OPAQUE;
  34077. if (alphaMode === ALPHA_MODES.BLEND) {
  34078. materialParams.transparent = true; // See: https://github.com/mrdoob/three.js/issues/17706
  34079. materialParams.depthWrite = false;
  34080. } else {
  34081. materialParams.transparent = false;
  34082. if (alphaMode === ALPHA_MODES.MASK) {
  34083. materialParams.alphaTest = materialDef.alphaCutoff !== undefined ? materialDef.alphaCutoff : 0.5;
  34084. }
  34085. }
  34086. if (materialDef.normalTexture !== undefined && materialType !== _threeModule.MeshBasicMaterial) {
  34087. pending.push(parser.assignTexture(materialParams, 'normalMap', materialDef.normalTexture));
  34088. materialParams.normalScale = new _threeModule.Vector2(1, 1);
  34089. if (materialDef.normalTexture.scale !== undefined) {
  34090. materialParams.normalScale.set(materialDef.normalTexture.scale, materialDef.normalTexture.scale);
  34091. }
  34092. }
  34093. if (materialDef.occlusionTexture !== undefined && materialType !== _threeModule.MeshBasicMaterial) {
  34094. pending.push(parser.assignTexture(materialParams, 'aoMap', materialDef.occlusionTexture));
  34095. if (materialDef.occlusionTexture.strength !== undefined) {
  34096. materialParams.aoMapIntensity = materialDef.occlusionTexture.strength;
  34097. }
  34098. }
  34099. if (materialDef.emissiveFactor !== undefined && materialType !== _threeModule.MeshBasicMaterial) {
  34100. materialParams.emissive = new _threeModule.Color().fromArray(materialDef.emissiveFactor);
  34101. }
  34102. if (materialDef.emissiveTexture !== undefined && materialType !== _threeModule.MeshBasicMaterial) {
  34103. pending.push(parser.assignTexture(materialParams, 'emissiveMap', materialDef.emissiveTexture));
  34104. }
  34105. return Promise.all(pending).then(function () {
  34106. var material;
  34107. if (materialType === GLTFMeshStandardSGMaterial) {
  34108. material = extensions[EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS].createMaterial(materialParams);
  34109. } else {
  34110. material = new materialType(materialParams);
  34111. }
  34112. if (materialDef.name) material.name = materialDef.name; // baseColorTexture, emissiveTexture, and specularGlossinessTexture use sRGB encoding.
  34113. if (material.map) material.map.encoding = _threeModule.sRGBEncoding;
  34114. if (material.emissiveMap) material.emissiveMap.encoding = _threeModule.sRGBEncoding;
  34115. assignExtrasToUserData(material, materialDef);
  34116. parser.associations.set(material, {
  34117. type: 'materials',
  34118. index: materialIndex
  34119. });
  34120. if (materialDef.extensions) addUnknownExtensionsToUserData(extensions, material, materialDef);
  34121. return material;
  34122. });
  34123. };
  34124. /** When Object3D instances are targeted by animation, they need unique names. */
  34125. GLTFParser.prototype.createUniqueName = function (originalName) {
  34126. var name = _threeModule.PropertyBinding.sanitizeNodeName(originalName || '');
  34127. for (var i = 1; this.nodeNamesUsed[name]; ++i) {
  34128. name = originalName + '_' + i;
  34129. }
  34130. this.nodeNamesUsed[name] = true;
  34131. return name;
  34132. };
  34133. /**
  34134. * @param {BufferGeometry} geometry
  34135. * @param {GLTF.Primitive} primitiveDef
  34136. * @param {GLTFParser} parser
  34137. */
  34138. function computeBounds(geometry, primitiveDef, parser) {
  34139. var attributes = primitiveDef.attributes;
  34140. var box = new _threeModule.Box3();
  34141. if (attributes.POSITION !== undefined) {
  34142. var accessor = parser.json.accessors[attributes.POSITION];
  34143. var min = accessor.min;
  34144. var max = accessor.max; // glTF requires 'min' and 'max', but VRM (which extends glTF) currently ignores that requirement.
  34145. if (min !== undefined && max !== undefined) {
  34146. box.set(new _threeModule.Vector3(min[0], min[1], min[2]), new _threeModule.Vector3(max[0], max[1], max[2]));
  34147. } else {
  34148. console.warn('THREE.GLTFLoader: Missing min/max properties for accessor POSITION.');
  34149. return;
  34150. }
  34151. } else {
  34152. return;
  34153. }
  34154. var targets = primitiveDef.targets;
  34155. if (targets !== undefined) {
  34156. var maxDisplacement = new _threeModule.Vector3();
  34157. var vector = new _threeModule.Vector3();
  34158. for (var i = 0, il = targets.length; i < il; i++) {
  34159. var target = targets[i];
  34160. if (target.POSITION !== undefined) {
  34161. var accessor = parser.json.accessors[target.POSITION];
  34162. var min = accessor.min;
  34163. var max = accessor.max; // glTF requires 'min' and 'max', but VRM (which extends glTF) currently ignores that requirement.
  34164. if (min !== undefined && max !== undefined) {
  34165. // we need to get max of absolute components because target weight is [-1,1]
  34166. vector.setX(Math.max(Math.abs(min[0]), Math.abs(max[0])));
  34167. vector.setY(Math.max(Math.abs(min[1]), Math.abs(max[1])));
  34168. vector.setZ(Math.max(Math.abs(min[2]), Math.abs(max[2]))); // Note: this assumes that the sum of all weights is at most 1. This isn't quite correct - it's more conservative
  34169. // to assume that each target can have a max weight of 1. However, for some use cases - notably, when morph targets
  34170. // are used to implement key-frame animations and as such only two are active at a time - this results in very large
  34171. // boxes. So for now we make a box that's sometimes a touch too small but is hopefully mostly of reasonable size.
  34172. maxDisplacement.max(vector);
  34173. } else {
  34174. console.warn('THREE.GLTFLoader: Missing min/max properties for accessor POSITION.');
  34175. }
  34176. }
  34177. } // As per comment above this box isn't conservative, but has a reasonable size for a very large number of morph targets.
  34178. box.expandByVector(maxDisplacement);
  34179. }
  34180. geometry.boundingBox = box;
  34181. var sphere = new _threeModule.Sphere();
  34182. box.getCenter(sphere.center);
  34183. sphere.radius = box.min.distanceTo(box.max) / 2;
  34184. geometry.boundingSphere = sphere;
  34185. }
  34186. /**
  34187. * @param {BufferGeometry} geometry
  34188. * @param {GLTF.Primitive} primitiveDef
  34189. * @param {GLTFParser} parser
  34190. * @return {Promise<BufferGeometry>}
  34191. */
  34192. function addPrimitiveAttributes(geometry, primitiveDef, parser) {
  34193. var attributes = primitiveDef.attributes;
  34194. var pending = [];
  34195. function assignAttributeAccessor(accessorIndex, attributeName) {
  34196. return parser.getDependency('accessor', accessorIndex).then(function (accessor) {
  34197. geometry.setAttribute(attributeName, accessor);
  34198. });
  34199. }
  34200. for (var gltfAttributeName in attributes) {
  34201. var threeAttributeName = ATTRIBUTES[gltfAttributeName] || gltfAttributeName.toLowerCase(); // Skip attributes already provided by e.g. Draco extension.
  34202. if (threeAttributeName in geometry.attributes) continue;
  34203. pending.push(assignAttributeAccessor(attributes[gltfAttributeName], threeAttributeName));
  34204. }
  34205. if (primitiveDef.indices !== undefined && !geometry.index) {
  34206. var accessor = parser.getDependency('accessor', primitiveDef.indices).then(function (accessor) {
  34207. geometry.setIndex(accessor);
  34208. });
  34209. pending.push(accessor);
  34210. }
  34211. assignExtrasToUserData(geometry, primitiveDef);
  34212. computeBounds(geometry, primitiveDef, parser);
  34213. return Promise.all(pending).then(function () {
  34214. return primitiveDef.targets !== undefined ? addMorphTargets(geometry, primitiveDef.targets, parser) : geometry;
  34215. });
  34216. }
  34217. /**
  34218. * @param {BufferGeometry} geometry
  34219. * @param {Number} drawMode
  34220. * @return {BufferGeometry}
  34221. */
  34222. function toTrianglesDrawMode(geometry, drawMode) {
  34223. var index = geometry.getIndex(); // generate index if not present
  34224. if (index === null) {
  34225. var indices = [];
  34226. var position = geometry.getAttribute('position');
  34227. if (position !== undefined) {
  34228. for (var i = 0; i < position.count; i++) {
  34229. indices.push(i);
  34230. }
  34231. geometry.setIndex(indices);
  34232. index = geometry.getIndex();
  34233. } else {
  34234. console.error('THREE.GLTFLoader.toTrianglesDrawMode(): Undefined position attribute. Processing not possible.');
  34235. return geometry;
  34236. }
  34237. } //
  34238. var numberOfTriangles = index.count - 2;
  34239. var newIndices = [];
  34240. if (drawMode === _threeModule.TriangleFanDrawMode) {
  34241. // gl.TRIANGLE_FAN
  34242. for (var i = 1; i <= numberOfTriangles; i++) {
  34243. newIndices.push(index.getX(0));
  34244. newIndices.push(index.getX(i));
  34245. newIndices.push(index.getX(i + 1));
  34246. }
  34247. } else {
  34248. // gl.TRIANGLE_STRIP
  34249. for (var i = 0; i < numberOfTriangles; i++) {
  34250. if (i % 2 === 0) {
  34251. newIndices.push(index.getX(i));
  34252. newIndices.push(index.getX(i + 1));
  34253. newIndices.push(index.getX(i + 2));
  34254. } else {
  34255. newIndices.push(index.getX(i + 2));
  34256. newIndices.push(index.getX(i + 1));
  34257. newIndices.push(index.getX(i));
  34258. }
  34259. }
  34260. }
  34261. if (newIndices.length / 3 !== numberOfTriangles) {
  34262. console.error('THREE.GLTFLoader.toTrianglesDrawMode(): Unable to generate correct amount of triangles.');
  34263. } // build final geometry
  34264. var newGeometry = geometry.clone();
  34265. newGeometry.setIndex(newIndices);
  34266. return newGeometry;
  34267. }
  34268. /**
  34269. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#geometry
  34270. *
  34271. * Creates BufferGeometries from primitives.
  34272. *
  34273. * @param {Array<GLTF.Primitive>} primitives
  34274. * @return {Promise<Array<BufferGeometry>>}
  34275. */
  34276. GLTFParser.prototype.loadGeometries = function (primitives) {
  34277. var parser = this;
  34278. var extensions = this.extensions;
  34279. var cache = this.primitiveCache;
  34280. function createDracoPrimitive(primitive) {
  34281. return extensions[EXTENSIONS.KHR_DRACO_MESH_COMPRESSION].decodePrimitive(primitive, parser).then(function (geometry) {
  34282. return addPrimitiveAttributes(geometry, primitive, parser);
  34283. });
  34284. }
  34285. var pending = [];
  34286. for (var i = 0, il = primitives.length; i < il; i++) {
  34287. var primitive = primitives[i];
  34288. var cacheKey = createPrimitiveKey(primitive); // See if we've already created this geometry
  34289. var cached = cache[cacheKey];
  34290. if (cached) {
  34291. // Use the cached geometry if it exists
  34292. pending.push(cached.promise);
  34293. } else {
  34294. var geometryPromise;
  34295. if (primitive.extensions && primitive.extensions[EXTENSIONS.KHR_DRACO_MESH_COMPRESSION]) {
  34296. // Use DRACO geometry if available
  34297. geometryPromise = createDracoPrimitive(primitive);
  34298. } else {
  34299. // Otherwise create a new geometry
  34300. geometryPromise = addPrimitiveAttributes(new _threeModule.BufferGeometry(), primitive, parser);
  34301. } // Cache this geometry
  34302. cache[cacheKey] = {
  34303. primitive: primitive,
  34304. promise: geometryPromise
  34305. };
  34306. pending.push(geometryPromise);
  34307. }
  34308. }
  34309. return Promise.all(pending);
  34310. };
  34311. /**
  34312. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#meshes
  34313. * @param {number} meshIndex
  34314. * @return {Promise<Group|Mesh|SkinnedMesh>}
  34315. */
  34316. GLTFParser.prototype.loadMesh = function (meshIndex) {
  34317. var parser = this;
  34318. var json = this.json;
  34319. var extensions = this.extensions;
  34320. var meshDef = json.meshes[meshIndex];
  34321. var primitives = meshDef.primitives;
  34322. var pending = [];
  34323. for (var i = 0, il = primitives.length; i < il; i++) {
  34324. var material = primitives[i].material === undefined ? createDefaultMaterial(this.cache) : this.getDependency('material', primitives[i].material);
  34325. pending.push(material);
  34326. }
  34327. pending.push(parser.loadGeometries(primitives));
  34328. return Promise.all(pending).then(function (results) {
  34329. var materials = results.slice(0, results.length - 1);
  34330. var geometries = results[results.length - 1];
  34331. var meshes = [];
  34332. for (var i = 0, il = geometries.length; i < il; i++) {
  34333. var geometry = geometries[i];
  34334. var primitive = primitives[i]; // 1. create Mesh
  34335. var mesh;
  34336. var material = materials[i];
  34337. if (primitive.mode === WEBGL_CONSTANTS.TRIANGLES || primitive.mode === WEBGL_CONSTANTS.TRIANGLE_STRIP || primitive.mode === WEBGL_CONSTANTS.TRIANGLE_FAN || primitive.mode === undefined) {
  34338. // .isSkinnedMesh isn't in glTF spec. See ._markDefs()
  34339. mesh = meshDef.isSkinnedMesh === true ? new _threeModule.SkinnedMesh(geometry, material) : new _threeModule.Mesh(geometry, material);
  34340. if (mesh.isSkinnedMesh === true && !mesh.geometry.attributes.skinWeight.normalized) {
  34341. // we normalize floating point skin weight array to fix malformed assets (see #15319)
  34342. // it's important to skip this for non-float32 data since normalizeSkinWeights assumes non-normalized inputs
  34343. mesh.normalizeSkinWeights();
  34344. }
  34345. if (primitive.mode === WEBGL_CONSTANTS.TRIANGLE_STRIP) {
  34346. mesh.geometry = toTrianglesDrawMode(mesh.geometry, _threeModule.TriangleStripDrawMode);
  34347. } else if (primitive.mode === WEBGL_CONSTANTS.TRIANGLE_FAN) {
  34348. mesh.geometry = toTrianglesDrawMode(mesh.geometry, _threeModule.TriangleFanDrawMode);
  34349. }
  34350. } else if (primitive.mode === WEBGL_CONSTANTS.LINES) {
  34351. mesh = new _threeModule.LineSegments(geometry, material);
  34352. } else if (primitive.mode === WEBGL_CONSTANTS.LINE_STRIP) {
  34353. mesh = new _threeModule.Line(geometry, material);
  34354. } else if (primitive.mode === WEBGL_CONSTANTS.LINE_LOOP) {
  34355. mesh = new _threeModule.LineLoop(geometry, material);
  34356. } else if (primitive.mode === WEBGL_CONSTANTS.POINTS) {
  34357. mesh = new _threeModule.Points(geometry, material);
  34358. } else {
  34359. throw new Error('THREE.GLTFLoader: Primitive mode unsupported: ' + primitive.mode);
  34360. }
  34361. if (Object.keys(mesh.geometry.morphAttributes).length > 0) {
  34362. updateMorphTargets(mesh, meshDef);
  34363. }
  34364. mesh.name = parser.createUniqueName(meshDef.name || 'mesh_' + meshIndex);
  34365. assignExtrasToUserData(mesh, meshDef);
  34366. if (primitive.extensions) addUnknownExtensionsToUserData(extensions, mesh, primitive);
  34367. parser.assignFinalMaterial(mesh);
  34368. meshes.push(mesh);
  34369. }
  34370. if (meshes.length === 1) {
  34371. return meshes[0];
  34372. }
  34373. var group = new _threeModule.Group();
  34374. for (var i = 0, il = meshes.length; i < il; i++) {
  34375. group.add(meshes[i]);
  34376. }
  34377. return group;
  34378. });
  34379. };
  34380. /**
  34381. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#cameras
  34382. * @param {number} cameraIndex
  34383. * @return {Promise<THREE.Camera>}
  34384. */
  34385. GLTFParser.prototype.loadCamera = function (cameraIndex) {
  34386. var camera;
  34387. var cameraDef = this.json.cameras[cameraIndex];
  34388. var params = cameraDef[cameraDef.type];
  34389. if (!params) {
  34390. console.warn('THREE.GLTFLoader: Missing camera parameters.');
  34391. return;
  34392. }
  34393. if (cameraDef.type === 'perspective') {
  34394. camera = new _threeModule.PerspectiveCamera(_threeModule.MathUtils.radToDeg(params.yfov), params.aspectRatio || 1, params.znear || 1, params.zfar || 2e6);
  34395. } else if (cameraDef.type === 'orthographic') {
  34396. camera = new _threeModule.OrthographicCamera(-params.xmag, params.xmag, params.ymag, -params.ymag, params.znear, params.zfar);
  34397. }
  34398. if (cameraDef.name) camera.name = this.createUniqueName(cameraDef.name);
  34399. assignExtrasToUserData(camera, cameraDef);
  34400. return Promise.resolve(camera);
  34401. };
  34402. /**
  34403. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins
  34404. * @param {number} skinIndex
  34405. * @return {Promise<Object>}
  34406. */
  34407. GLTFParser.prototype.loadSkin = function (skinIndex) {
  34408. var skinDef = this.json.skins[skinIndex];
  34409. var skinEntry = {
  34410. joints: skinDef.joints
  34411. };
  34412. if (skinDef.inverseBindMatrices === undefined) {
  34413. return Promise.resolve(skinEntry);
  34414. }
  34415. return this.getDependency('accessor', skinDef.inverseBindMatrices).then(function (accessor) {
  34416. skinEntry.inverseBindMatrices = accessor;
  34417. return skinEntry;
  34418. });
  34419. };
  34420. /**
  34421. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#animations
  34422. * @param {number} animationIndex
  34423. * @return {Promise<AnimationClip>}
  34424. */
  34425. GLTFParser.prototype.loadAnimation = function (animationIndex) {
  34426. var json = this.json;
  34427. var animationDef = json.animations[animationIndex];
  34428. var pendingNodes = [];
  34429. var pendingInputAccessors = [];
  34430. var pendingOutputAccessors = [];
  34431. var pendingSamplers = [];
  34432. var pendingTargets = [];
  34433. for (var i = 0, il = animationDef.channels.length; i < il; i++) {
  34434. var channel = animationDef.channels[i];
  34435. var sampler = animationDef.samplers[channel.sampler];
  34436. var target = channel.target;
  34437. var name = target.node !== undefined ? target.node : target.id; // NOTE: target.id is deprecated.
  34438. var input = animationDef.parameters !== undefined ? animationDef.parameters[sampler.input] : sampler.input;
  34439. var output = animationDef.parameters !== undefined ? animationDef.parameters[sampler.output] : sampler.output;
  34440. pendingNodes.push(this.getDependency('node', name));
  34441. pendingInputAccessors.push(this.getDependency('accessor', input));
  34442. pendingOutputAccessors.push(this.getDependency('accessor', output));
  34443. pendingSamplers.push(sampler);
  34444. pendingTargets.push(target);
  34445. }
  34446. return Promise.all([Promise.all(pendingNodes), Promise.all(pendingInputAccessors), Promise.all(pendingOutputAccessors), Promise.all(pendingSamplers), Promise.all(pendingTargets)]).then(function (dependencies) {
  34447. var nodes = dependencies[0];
  34448. var inputAccessors = dependencies[1];
  34449. var outputAccessors = dependencies[2];
  34450. var samplers = dependencies[3];
  34451. var targets = dependencies[4];
  34452. var tracks = [];
  34453. for (var i = 0, il = nodes.length; i < il; i++) {
  34454. var node = nodes[i];
  34455. var inputAccessor = inputAccessors[i];
  34456. var outputAccessor = outputAccessors[i];
  34457. var sampler = samplers[i];
  34458. var target = targets[i];
  34459. if (node === undefined) continue;
  34460. node.updateMatrix();
  34461. node.matrixAutoUpdate = true;
  34462. var TypedKeyframeTrack;
  34463. switch (PATH_PROPERTIES[target.path]) {
  34464. case PATH_PROPERTIES.weights:
  34465. TypedKeyframeTrack = _threeModule.NumberKeyframeTrack;
  34466. break;
  34467. case PATH_PROPERTIES.rotation:
  34468. TypedKeyframeTrack = _threeModule.QuaternionKeyframeTrack;
  34469. break;
  34470. case PATH_PROPERTIES.position:
  34471. case PATH_PROPERTIES.scale:
  34472. default:
  34473. TypedKeyframeTrack = _threeModule.VectorKeyframeTrack;
  34474. break;
  34475. }
  34476. var targetName = node.name ? node.name : node.uuid;
  34477. var interpolation = sampler.interpolation !== undefined ? INTERPOLATION[sampler.interpolation] : _threeModule.InterpolateLinear;
  34478. var targetNames = [];
  34479. if (PATH_PROPERTIES[target.path] === PATH_PROPERTIES.weights) {
  34480. // Node may be a Group (glTF mesh with several primitives) or a Mesh.
  34481. node.traverse(function (object) {
  34482. if (object.isMesh === true && object.morphTargetInfluences) {
  34483. targetNames.push(object.name ? object.name : object.uuid);
  34484. }
  34485. });
  34486. } else {
  34487. targetNames.push(targetName);
  34488. }
  34489. var outputArray = outputAccessor.array;
  34490. if (outputAccessor.normalized) {
  34491. var scale;
  34492. if (outputArray.constructor === Int8Array) {
  34493. scale = 1 / 127;
  34494. } else if (outputArray.constructor === Uint8Array) {
  34495. scale = 1 / 255;
  34496. } else if (outputArray.constructor == Int16Array) {
  34497. scale = 1 / 32767;
  34498. } else if (outputArray.constructor === Uint16Array) {
  34499. scale = 1 / 65535;
  34500. } else {
  34501. throw new Error('THREE.GLTFLoader: Unsupported output accessor component type.');
  34502. }
  34503. var scaled = new Float32Array(outputArray.length);
  34504. for (var j = 0, jl = outputArray.length; j < jl; j++) {
  34505. scaled[j] = outputArray[j] * scale;
  34506. }
  34507. outputArray = scaled;
  34508. }
  34509. for (var j = 0, jl = targetNames.length; j < jl; j++) {
  34510. var track = new TypedKeyframeTrack(targetNames[j] + '.' + PATH_PROPERTIES[target.path], inputAccessor.array, outputArray, interpolation); // Override interpolation with custom factory method.
  34511. if (sampler.interpolation === 'CUBICSPLINE') {
  34512. track.createInterpolant = function InterpolantFactoryMethodGLTFCubicSpline(result) {
  34513. // A CUBICSPLINE keyframe in glTF has three output values for each input value,
  34514. // representing inTangent, splineVertex, and outTangent. As a result, track.getValueSize()
  34515. // must be divided by three to get the interpolant's sampleSize argument.
  34516. return new GLTFCubicSplineInterpolant(this.times, this.values, this.getValueSize() / 3, result);
  34517. }; // Mark as CUBICSPLINE. `track.getInterpolation()` doesn't support custom interpolants.
  34518. track.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline = true;
  34519. }
  34520. tracks.push(track);
  34521. }
  34522. }
  34523. var name = animationDef.name ? animationDef.name : 'animation_' + animationIndex;
  34524. return new _threeModule.AnimationClip(name, undefined, tracks);
  34525. });
  34526. };
  34527. /**
  34528. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#nodes-and-hierarchy
  34529. * @param {number} nodeIndex
  34530. * @return {Promise<Object3D>}
  34531. */
  34532. GLTFParser.prototype.loadNode = function (nodeIndex) {
  34533. var json = this.json;
  34534. var extensions = this.extensions;
  34535. var parser = this;
  34536. var nodeDef = json.nodes[nodeIndex]; // reserve node's name before its dependencies, so the root has the intended name.
  34537. var nodeName = nodeDef.name ? parser.createUniqueName(nodeDef.name) : '';
  34538. return function () {
  34539. var pending = [];
  34540. if (nodeDef.mesh !== undefined) {
  34541. pending.push(parser.getDependency('mesh', nodeDef.mesh).then(function (mesh) {
  34542. var node = parser._getNodeRef(parser.meshCache, nodeDef.mesh, mesh); // if weights are provided on the node, override weights on the mesh.
  34543. if (nodeDef.weights !== undefined) {
  34544. node.traverse(function (o) {
  34545. if (!o.isMesh) return;
  34546. for (var i = 0, il = nodeDef.weights.length; i < il; i++) {
  34547. o.morphTargetInfluences[i] = nodeDef.weights[i];
  34548. }
  34549. });
  34550. }
  34551. return node;
  34552. }));
  34553. }
  34554. if (nodeDef.camera !== undefined) {
  34555. pending.push(parser.getDependency('camera', nodeDef.camera).then(function (camera) {
  34556. return parser._getNodeRef(parser.cameraCache, nodeDef.camera, camera);
  34557. }));
  34558. }
  34559. parser._invokeAll(function (ext) {
  34560. return ext.createNodeAttachment && ext.createNodeAttachment(nodeIndex);
  34561. }).forEach(function (promise) {
  34562. pending.push(promise);
  34563. });
  34564. return Promise.all(pending);
  34565. }().then(function (objects) {
  34566. var node; // .isBone isn't in glTF spec. See ._markDefs
  34567. if (nodeDef.isBone === true) {
  34568. node = new _threeModule.Bone();
  34569. } else if (objects.length > 1) {
  34570. node = new _threeModule.Group();
  34571. } else if (objects.length === 1) {
  34572. node = objects[0];
  34573. } else {
  34574. node = new _threeModule.Object3D();
  34575. }
  34576. if (node !== objects[0]) {
  34577. for (var i = 0, il = objects.length; i < il; i++) {
  34578. node.add(objects[i]);
  34579. }
  34580. }
  34581. if (nodeDef.name) {
  34582. node.userData.name = nodeDef.name;
  34583. node.name = nodeName;
  34584. }
  34585. assignExtrasToUserData(node, nodeDef);
  34586. if (nodeDef.extensions) addUnknownExtensionsToUserData(extensions, node, nodeDef);
  34587. if (nodeDef.matrix !== undefined) {
  34588. var matrix = new _threeModule.Matrix4();
  34589. matrix.fromArray(nodeDef.matrix);
  34590. node.applyMatrix4(matrix);
  34591. } else {
  34592. if (nodeDef.translation !== undefined) {
  34593. node.position.fromArray(nodeDef.translation);
  34594. }
  34595. if (nodeDef.rotation !== undefined) {
  34596. node.quaternion.fromArray(nodeDef.rotation);
  34597. }
  34598. if (nodeDef.scale !== undefined) {
  34599. node.scale.fromArray(nodeDef.scale);
  34600. }
  34601. }
  34602. parser.associations.set(node, {
  34603. type: 'nodes',
  34604. index: nodeIndex
  34605. });
  34606. return node;
  34607. });
  34608. };
  34609. /**
  34610. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#scenes
  34611. * @param {number} sceneIndex
  34612. * @return {Promise<Group>}
  34613. */
  34614. GLTFParser.prototype.loadScene = function () {
  34615. // scene node hierachy builder
  34616. function buildNodeHierachy(nodeId, parentObject, json, parser) {
  34617. var nodeDef = json.nodes[nodeId];
  34618. return parser.getDependency('node', nodeId).then(function (node) {
  34619. if (nodeDef.skin === undefined) return node; // build skeleton here as well
  34620. var skinEntry;
  34621. return parser.getDependency('skin', nodeDef.skin).then(function (skin) {
  34622. skinEntry = skin;
  34623. var pendingJoints = [];
  34624. for (var i = 0, il = skinEntry.joints.length; i < il; i++) {
  34625. pendingJoints.push(parser.getDependency('node', skinEntry.joints[i]));
  34626. }
  34627. return Promise.all(pendingJoints);
  34628. }).then(function (jointNodes) {
  34629. node.traverse(function (mesh) {
  34630. if (!mesh.isMesh) return;
  34631. var bones = [];
  34632. var boneInverses = [];
  34633. for (var j = 0, jl = jointNodes.length; j < jl; j++) {
  34634. var jointNode = jointNodes[j];
  34635. if (jointNode) {
  34636. bones.push(jointNode);
  34637. var mat = new _threeModule.Matrix4();
  34638. if (skinEntry.inverseBindMatrices !== undefined) {
  34639. mat.fromArray(skinEntry.inverseBindMatrices.array, j * 16);
  34640. }
  34641. boneInverses.push(mat);
  34642. } else {
  34643. console.warn('THREE.GLTFLoader: Joint "%s" could not be found.', skinEntry.joints[j]);
  34644. }
  34645. }
  34646. mesh.bind(new _threeModule.Skeleton(bones, boneInverses), mesh.matrixWorld);
  34647. });
  34648. return node;
  34649. });
  34650. }).then(function (node) {
  34651. // build node hierachy
  34652. parentObject.add(node);
  34653. var pending = [];
  34654. if (nodeDef.children) {
  34655. var children = nodeDef.children;
  34656. for (var i = 0, il = children.length; i < il; i++) {
  34657. var child = children[i];
  34658. pending.push(buildNodeHierachy(child, node, json, parser));
  34659. }
  34660. }
  34661. return Promise.all(pending);
  34662. });
  34663. }
  34664. return function loadScene(sceneIndex) {
  34665. var json = this.json;
  34666. var extensions = this.extensions;
  34667. var sceneDef = this.json.scenes[sceneIndex];
  34668. var parser = this; // Loader returns Group, not Scene.
  34669. // See: https://github.com/mrdoob/three.js/issues/18342#issuecomment-578981172
  34670. var scene = new _threeModule.Group();
  34671. if (sceneDef.name) scene.name = parser.createUniqueName(sceneDef.name);
  34672. assignExtrasToUserData(scene, sceneDef);
  34673. if (sceneDef.extensions) addUnknownExtensionsToUserData(extensions, scene, sceneDef);
  34674. var nodeIds = sceneDef.nodes || [];
  34675. var pending = [];
  34676. for (var i = 0, il = nodeIds.length; i < il; i++) {
  34677. pending.push(buildNodeHierachy(nodeIds[i], scene, json, parser));
  34678. }
  34679. return Promise.all(pending).then(function () {
  34680. return scene;
  34681. });
  34682. };
  34683. }();
  34684. return GLTFLoader;
  34685. }();
  34686. exports.GLTFLoader = GLTFLoader;
  34687. },{"../../../build/three.module.js":"../node_modules/three/build/three.module.js"}],"../src/three/B3DMLoader.js":[function(require,module,exports) {
  34688. "use strict";
  34689. Object.defineProperty(exports, "__esModule", {
  34690. value: true
  34691. });
  34692. exports.B3DMLoader = void 0;
  34693. var _B3DMLoaderBase2 = require("../base/B3DMLoaderBase.js");
  34694. var _three = require("three");
  34695. var _GLTFLoader = require("three/examples/jsm/loaders/GLTFLoader.js");
  34696. function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
  34697. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  34698. function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
  34699. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
  34700. function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }
  34701. function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
  34702. function _get(target, property, receiver) { if (typeof Reflect !== "undefined" && Reflect.get) { _get = Reflect.get; } else { _get = function _get(target, property, receiver) { var base = _superPropBase(target, property); if (!base) return; var desc = Object.getOwnPropertyDescriptor(base, property); if (desc.get) { return desc.get.call(receiver); } return desc.value; }; } return _get(target, property, receiver || target); }
  34703. function _superPropBase(object, property) { while (!Object.prototype.hasOwnProperty.call(object, property)) { object = _getPrototypeOf(object); if (object === null) break; } return object; }
  34704. function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
  34705. function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }
  34706. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  34707. var B3DMLoader =
  34708. /*#__PURE__*/
  34709. function (_B3DMLoaderBase) {
  34710. _inherits(B3DMLoader, _B3DMLoaderBase);
  34711. function B3DMLoader() {
  34712. var _this;
  34713. var manager = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : _three.DefaultLoadingManager;
  34714. _classCallCheck(this, B3DMLoader);
  34715. _this = _possibleConstructorReturn(this, _getPrototypeOf(B3DMLoader).call(this));
  34716. _this.manager = manager;
  34717. return _this;
  34718. }
  34719. _createClass(B3DMLoader, [{
  34720. key: "parse",
  34721. value: function parse(buffer) {
  34722. var _this2 = this;
  34723. var b3dm = _get(_getPrototypeOf(B3DMLoader.prototype), "parse", this).call(this, buffer);
  34724. var gltfBuffer = b3dm.glbBytes.slice().buffer;
  34725. return new Promise(function (resolve, reject) {
  34726. var manager = _this2.manager;
  34727. var loader = manager.getHandler('path.gltf') || new _GLTFLoader.GLTFLoader(manager);
  34728. loader.parse(gltfBuffer, null, function (model) {
  34729. var batchTable = b3dm.batchTable,
  34730. featureTable = b3dm.featureTable;
  34731. var scene = model.scene;
  34732. var rtcCenter = featureTable.getData('RTC_CENTER');
  34733. if (rtcCenter) {
  34734. scene.position.x += rtcCenter[0];
  34735. scene.position.y += rtcCenter[1];
  34736. scene.position.z += rtcCenter[2];
  34737. }
  34738. model.batchTable = batchTable;
  34739. model.featureTable = featureTable;
  34740. scene.batchTable = batchTable;
  34741. scene.featureTable = featureTable;
  34742. resolve(model);
  34743. }, reject);
  34744. });
  34745. }
  34746. }]);
  34747. return B3DMLoader;
  34748. }(_B3DMLoaderBase2.B3DMLoaderBase);
  34749. exports.B3DMLoader = B3DMLoader;
  34750. },{"../base/B3DMLoaderBase.js":"../src/base/B3DMLoaderBase.js","three":"../node_modules/three/build/three.module.js","three/examples/jsm/loaders/GLTFLoader.js":"../node_modules/three/examples/jsm/loaders/GLTFLoader.js"}],"../src/base/PNTSLoaderBase.js":[function(require,module,exports) {
  34751. "use strict";
  34752. Object.defineProperty(exports, "__esModule", {
  34753. value: true
  34754. });
  34755. exports.PNTSLoaderBase = void 0;
  34756. var _FeatureTable = require("../utilities/FeatureTable.js");
  34757. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  34758. function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
  34759. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
  34760. var PNTSLoaderBase =
  34761. /*#__PURE__*/
  34762. function () {
  34763. function PNTSLoaderBase() {
  34764. _classCallCheck(this, PNTSLoaderBase);
  34765. this.fetchOptions = {};
  34766. }
  34767. _createClass(PNTSLoaderBase, [{
  34768. key: "load",
  34769. value: function load(url) {
  34770. var _this = this;
  34771. return fetch(url, this.fetchOptions).then(function (res) {
  34772. if (!res.ok) {
  34773. throw new Error("Failed to load file \"".concat(url, "\" with status ").concat(res.status, " : ").concat(res.statusText));
  34774. }
  34775. return res.arrayBuffer();
  34776. }).then(function (buffer) {
  34777. return _this.parse(buffer);
  34778. });
  34779. }
  34780. }, {
  34781. key: "parse",
  34782. value: function parse(buffer) {
  34783. var dataView = new DataView(buffer); // 28-byte header
  34784. // 4 bytes
  34785. var magic = String.fromCharCode(dataView.getUint8(0)) + String.fromCharCode(dataView.getUint8(1)) + String.fromCharCode(dataView.getUint8(2)) + String.fromCharCode(dataView.getUint8(3));
  34786. console.assert(magic === 'pnts'); // 4 bytes
  34787. var version = dataView.getUint32(4, true);
  34788. console.assert(version === 1); // 4 bytes
  34789. var byteLength = dataView.getUint32(8, true);
  34790. console.assert(byteLength === buffer.byteLength); // 4 bytes
  34791. var featureTableJSONByteLength = dataView.getUint32(12, true); // 4 bytes
  34792. var featureTableBinaryByteLength = dataView.getUint32(16, true); // 4 bytes
  34793. var batchTableJSONByteLength = dataView.getUint32(20, true); // 4 bytes
  34794. var batchTableBinaryByteLength = dataView.getUint32(24, true); // Feature Table
  34795. var featureTableStart = 28;
  34796. var featureTable = new _FeatureTable.FeatureTable(buffer, featureTableStart, featureTableJSONByteLength, featureTableBinaryByteLength); // Batch Table
  34797. var batchLength = featureTable.getData('BATCH_LENGTH') || featureTable.getData('POINTS_LENGTH');
  34798. var batchTableStart = featureTableStart + featureTableJSONByteLength + featureTableBinaryByteLength;
  34799. var batchTable = new _FeatureTable.BatchTable(buffer, batchLength, batchTableStart, batchTableJSONByteLength, batchTableBinaryByteLength);
  34800. return {
  34801. version: version,
  34802. featureTable: featureTable,
  34803. batchTable: batchTable
  34804. };
  34805. }
  34806. }]);
  34807. return PNTSLoaderBase;
  34808. }();
  34809. exports.PNTSLoaderBase = PNTSLoaderBase;
  34810. },{"../utilities/FeatureTable.js":"../src/utilities/FeatureTable.js"}],"../src/three/PNTSLoader.js":[function(require,module,exports) {
  34811. "use strict";
  34812. Object.defineProperty(exports, "__esModule", {
  34813. value: true
  34814. });
  34815. exports.PNTSLoader = void 0;
  34816. var _PNTSLoaderBase2 = require("../base/PNTSLoaderBase.js");
  34817. var _three = require("three");
  34818. function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
  34819. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  34820. function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
  34821. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
  34822. function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }
  34823. function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
  34824. function _get(target, property, receiver) { if (typeof Reflect !== "undefined" && Reflect.get) { _get = Reflect.get; } else { _get = function _get(target, property, receiver) { var base = _superPropBase(target, property); if (!base) return; var desc = Object.getOwnPropertyDescriptor(base, property); if (desc.get) { return desc.get.call(receiver); } return desc.value; }; } return _get(target, property, receiver || target); }
  34825. function _superPropBase(object, property) { while (!Object.prototype.hasOwnProperty.call(object, property)) { object = _getPrototypeOf(object); if (object === null) break; } return object; }
  34826. function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
  34827. function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }
  34828. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  34829. var PNTSLoader =
  34830. /*#__PURE__*/
  34831. function (_PNTSLoaderBase) {
  34832. _inherits(PNTSLoader, _PNTSLoaderBase);
  34833. function PNTSLoader() {
  34834. var _this;
  34835. var manager = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : _three.DefaultLoadingManager;
  34836. _classCallCheck(this, PNTSLoader);
  34837. _this = _possibleConstructorReturn(this, _getPrototypeOf(PNTSLoader).call(this));
  34838. _this.manager = manager;
  34839. return _this;
  34840. }
  34841. _createClass(PNTSLoader, [{
  34842. key: "parse",
  34843. value: function parse(buffer) {
  34844. var result = _get(_getPrototypeOf(PNTSLoader.prototype), "parse", this).call(this, buffer);
  34845. var featureTable = result.featureTable; // global semantics
  34846. var POINTS_LENGTH = featureTable.getData('POINTS_LENGTH'); // RTC_CENTER
  34847. // QUANTIZED_VOLUME_OFFSET
  34848. // QUANTIZED_VOLUME_SCALE
  34849. // CONSTANT_RGBA
  34850. // BATCH_LENGTH
  34851. var POSITION = featureTable.getData('POSITION', POINTS_LENGTH, 'FLOAT', 'VEC3');
  34852. var RGB = featureTable.getData('RGB', POINTS_LENGTH, 'UNSIGNED_BYTE', 'VEC3'); // POSITION_QUANTIZED
  34853. // RGBA
  34854. // RGB565
  34855. // NORMAL
  34856. // NORMAL_OCT16P
  34857. // BATCH_ID
  34858. if (POSITION === null) {
  34859. throw new Error('PNTSLoader : POSITION_QUANTIZED feature type is not supported.');
  34860. }
  34861. var geometry = new _three.BufferGeometry();
  34862. geometry.setAttribute('position', new _three.BufferAttribute(POSITION, 3, false));
  34863. var material = new _three.PointsMaterial();
  34864. material.size = 2;
  34865. material.sizeAttenuation = false;
  34866. if (RGB !== null) {
  34867. geometry.setAttribute('color', new _three.BufferAttribute(RGB, 3, true));
  34868. material.vertexColors = true;
  34869. }
  34870. var object = new _three.Points(geometry, material);
  34871. result.scene = object;
  34872. result.scene.featureTable = featureTable;
  34873. return result;
  34874. }
  34875. }]);
  34876. return PNTSLoader;
  34877. }(_PNTSLoaderBase2.PNTSLoaderBase);
  34878. exports.PNTSLoader = PNTSLoader;
  34879. },{"../base/PNTSLoaderBase.js":"../src/base/PNTSLoaderBase.js","three":"../node_modules/three/build/three.module.js"}],"../src/base/I3DMLoaderBase.js":[function(require,module,exports) {
  34880. "use strict";
  34881. Object.defineProperty(exports, "__esModule", {
  34882. value: true
  34883. });
  34884. exports.I3DMLoaderBase = void 0;
  34885. var _FeatureTable = require("../utilities/FeatureTable.js");
  34886. var _arrayToString = require("../utilities/arrayToString.js");
  34887. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  34888. function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
  34889. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
  34890. var I3DMLoaderBase =
  34891. /*#__PURE__*/
  34892. function () {
  34893. function I3DMLoaderBase() {
  34894. _classCallCheck(this, I3DMLoaderBase);
  34895. this.fetchOptions = {};
  34896. }
  34897. _createClass(I3DMLoaderBase, [{
  34898. key: "load",
  34899. value: function load(url) {
  34900. var _this = this;
  34901. return fetch(url, this.fetchOptions).then(function (res) {
  34902. if (!res.ok) {
  34903. throw new Error("Failed to load file \"".concat(url, "\" with status ").concat(res.status, " : ").concat(res.statusText));
  34904. }
  34905. return res.arrayBuffer();
  34906. }).then(function (buffer) {
  34907. return _this.parse(buffer);
  34908. });
  34909. }
  34910. }, {
  34911. key: "parse",
  34912. value: function parse(buffer) {
  34913. var dataView = new DataView(buffer); // 32-byte header
  34914. // 4 bytes
  34915. var magic = String.fromCharCode(dataView.getUint8(0)) + String.fromCharCode(dataView.getUint8(1)) + String.fromCharCode(dataView.getUint8(2)) + String.fromCharCode(dataView.getUint8(3));
  34916. console.assert(magic === 'i3dm'); // 4 bytes
  34917. var version = dataView.getUint32(4, true);
  34918. console.assert(version === 1); // 4 bytes
  34919. var byteLength = dataView.getUint32(8, true);
  34920. console.assert(byteLength === buffer.byteLength); // 4 bytes
  34921. var featureTableJSONByteLength = dataView.getUint32(12, true); // 4 bytes
  34922. var featureTableBinaryByteLength = dataView.getUint32(16, true); // 4 bytes
  34923. var batchTableJSONByteLength = dataView.getUint32(20, true); // 4 bytes
  34924. var batchTableBinaryByteLength = dataView.getUint32(24, true); // 4 bytes
  34925. var gltfFormat = dataView.getUint32(28, true); // Feature Table
  34926. var featureTableStart = 32;
  34927. var featureTable = new _FeatureTable.FeatureTable(buffer, featureTableStart, featureTableJSONByteLength, featureTableBinaryByteLength); // Batch Table
  34928. var batchLength = featureTable.getData('INSTANCES_LENGTH');
  34929. var batchTableStart = featureTableStart + featureTableJSONByteLength + featureTableBinaryByteLength;
  34930. var batchTable = new _FeatureTable.BatchTable(buffer, batchLength, batchTableStart, batchTableJSONByteLength, batchTableBinaryByteLength);
  34931. var glbStart = batchTableStart + batchTableJSONByteLength + batchTableBinaryByteLength;
  34932. var bodyBytes = new Uint8Array(buffer, glbStart, byteLength - glbStart);
  34933. var glbBytes = null;
  34934. var promise = null;
  34935. if (gltfFormat) {
  34936. glbBytes = bodyBytes;
  34937. promise = Promise.resolve();
  34938. } else {
  34939. var externalUri = (0, _arrayToString.arrayToString)(bodyBytes);
  34940. promise = fetch(externalUri, this.fetchOptions).then(function (res) {
  34941. return res.buffer;
  34942. }).then(function (buffer) {
  34943. glbBytes = new Uint8Array(buffer);
  34944. });
  34945. }
  34946. return promise.then(function () {
  34947. return {
  34948. version: version,
  34949. featureTable: featureTable,
  34950. batchTable: batchTable,
  34951. glbBytes: glbBytes
  34952. };
  34953. });
  34954. }
  34955. }]);
  34956. return I3DMLoaderBase;
  34957. }();
  34958. exports.I3DMLoaderBase = I3DMLoaderBase;
  34959. },{"../utilities/FeatureTable.js":"../src/utilities/FeatureTable.js","../utilities/arrayToString.js":"../src/utilities/arrayToString.js"}],"../src/three/I3DMLoader.js":[function(require,module,exports) {
  34960. "use strict";
  34961. Object.defineProperty(exports, "__esModule", {
  34962. value: true
  34963. });
  34964. exports.I3DMLoader = void 0;
  34965. var _I3DMLoaderBase2 = require("../base/I3DMLoaderBase.js");
  34966. var _three = require("three");
  34967. var _GLTFLoader = require("three/examples/jsm/loaders/GLTFLoader.js");
  34968. function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
  34969. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  34970. function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
  34971. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
  34972. function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }
  34973. function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
  34974. function _get(target, property, receiver) { if (typeof Reflect !== "undefined" && Reflect.get) { _get = Reflect.get; } else { _get = function _get(target, property, receiver) { var base = _superPropBase(target, property); if (!base) return; var desc = Object.getOwnPropertyDescriptor(base, property); if (desc.get) { return desc.get.call(receiver); } return desc.value; }; } return _get(target, property, receiver || target); }
  34975. function _superPropBase(object, property) { while (!Object.prototype.hasOwnProperty.call(object, property)) { object = _getPrototypeOf(object); if (object === null) break; } return object; }
  34976. function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
  34977. function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }
  34978. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  34979. var tempPos = new _three.Vector3();
  34980. var tempQuat = new _three.Quaternion();
  34981. var tempSca = new _three.Vector3();
  34982. var tempMat = new _three.Matrix4();
  34983. var I3DMLoader =
  34984. /*#__PURE__*/
  34985. function (_I3DMLoaderBase) {
  34986. _inherits(I3DMLoader, _I3DMLoaderBase);
  34987. function I3DMLoader() {
  34988. var _this;
  34989. var manager = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : _three.DefaultLoadingManager;
  34990. _classCallCheck(this, I3DMLoader);
  34991. _this = _possibleConstructorReturn(this, _getPrototypeOf(I3DMLoader).call(this));
  34992. _this.manager = manager;
  34993. return _this;
  34994. }
  34995. _createClass(I3DMLoader, [{
  34996. key: "parse",
  34997. value: function parse(buffer) {
  34998. var _this2 = this;
  34999. return _get(_getPrototypeOf(I3DMLoader.prototype), "parse", this).call(this, buffer).then(function (i3dm) {
  35000. var featureTable = i3dm.featureTable,
  35001. batchTable = i3dm.batchTable;
  35002. var gltfBuffer = i3dm.glbBytes.slice().buffer;
  35003. return new Promise(function (resolve, reject) {
  35004. var manager = _this2.manager;
  35005. var loader = manager.getHandler('path.gltf') || new _GLTFLoader.GLTFLoader(manager);
  35006. loader.parse(gltfBuffer, null, function (model) {
  35007. var INSTANCES_LENGTH = featureTable.getData('INSTANCES_LENGTH'); // RTC_CENTER
  35008. // QUANTIZED_VOLUME_OFFSET
  35009. // QUANTIZED_VOLUME_SCALE
  35010. // EAST_NORTH_UP
  35011. var POSITION = featureTable.getData('POSITION', INSTANCES_LENGTH, 'FLOAT', 'VEC3'); // POSITION_QUANTIZED
  35012. // NORMAL_UP
  35013. // NORMAL_RIGHT
  35014. // NORMAL_UP_OCT32P
  35015. // NORMAL_RIGHT_OCT32P
  35016. // SCALE
  35017. // SCALE_NON_UNIFORM
  35018. // BATCH_ID
  35019. var instanceMap = new Map();
  35020. var instances = [];
  35021. model.scene.traverse(function (child) {
  35022. if (child.isMesh) {
  35023. var geometry = child.geometry,
  35024. material = child.material;
  35025. var instancedMesh = new _three.InstancedMesh(geometry, material, INSTANCES_LENGTH);
  35026. instances.push(instancedMesh);
  35027. instanceMap.set(child, instancedMesh);
  35028. }
  35029. });
  35030. var averageVector = new _three.Vector3();
  35031. var transformedVector = new _three.Vector3();
  35032. for (var i = 0; i < INSTANCES_LENGTH; i++) {
  35033. // TODO: handle quantized position
  35034. averageVector.x += POSITION[i * 3 + 0] / INSTANCES_LENGTH;
  35035. averageVector.y += POSITION[i * 3 + 1] / INSTANCES_LENGTH;
  35036. averageVector.z += POSITION[i * 3 + 2] / INSTANCES_LENGTH;
  35037. } // replace the meshes with instanced meshes
  35038. instanceMap.forEach(function (instancedMesh, mesh) {
  35039. var parent = mesh.parent;
  35040. if (parent) {
  35041. // Mesh have no children
  35042. parent.remove(mesh);
  35043. parent.add(instancedMesh); // Center the instance around an average point to avoid jitter at large scales.
  35044. transformedVector.copy(averageVector).applyQuaternion(parent.quaternion).multiply(parent.scale);
  35045. instancedMesh.add(transformedVector);
  35046. }
  35047. });
  35048. for (var _i = 0; _i < INSTANCES_LENGTH; _i++) {
  35049. // TODO: handle quantized position
  35050. tempPos.set(POSITION[_i * 3 + 0] - averageVector.x, POSITION[_i * 3 + 1] - averageVector.y, POSITION[_i * 3 + 2] - averageVector.z); // TODO: handle normal orientation features
  35051. tempQuat.set(0, 0, 0, 1); // TODO: handle scale features
  35052. tempSca.set(1, 1, 1);
  35053. tempMat.compose(tempPos, tempQuat, tempSca);
  35054. for (var j = 0, l = instances.length; j < l; j++) {
  35055. var instance = instances[j];
  35056. instance.setMatrixAt(_i, tempMat);
  35057. }
  35058. }
  35059. model.batchTable = batchTable;
  35060. model.featureTable = featureTable;
  35061. model.scene.batchTable = batchTable;
  35062. model.scene.featureTable = featureTable;
  35063. resolve(model);
  35064. }, reject);
  35065. });
  35066. });
  35067. }
  35068. }]);
  35069. return I3DMLoader;
  35070. }(_I3DMLoaderBase2.I3DMLoaderBase);
  35071. exports.I3DMLoader = I3DMLoader;
  35072. },{"../base/I3DMLoaderBase.js":"../src/base/I3DMLoaderBase.js","three":"../node_modules/three/build/three.module.js","three/examples/jsm/loaders/GLTFLoader.js":"../node_modules/three/examples/jsm/loaders/GLTFLoader.js"}],"../src/base/CMPTLoaderBase.js":[function(require,module,exports) {
  35073. "use strict";
  35074. Object.defineProperty(exports, "__esModule", {
  35075. value: true
  35076. });
  35077. exports.CMPTLoaderBase = void 0;
  35078. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  35079. function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
  35080. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
  35081. // CMPT File Format
  35082. // https://github.com/CesiumGS/3d-tiles/blob/master/specification/TileFormats/Composite/README.md
  35083. var CMPTLoaderBase =
  35084. /*#__PURE__*/
  35085. function () {
  35086. function CMPTLoaderBase() {
  35087. _classCallCheck(this, CMPTLoaderBase);
  35088. this.fetchOptions = {};
  35089. }
  35090. _createClass(CMPTLoaderBase, [{
  35091. key: "load",
  35092. value: function load(url) {
  35093. var _this = this;
  35094. return fetch(url, this.fetchOptions).then(function (res) {
  35095. if (!res.ok) {
  35096. throw new Error("Failed to load file \"".concat(url, "\" with status ").concat(res.status, " : ").concat(res.statusText));
  35097. }
  35098. return res.arrayBuffer();
  35099. }).then(function (buffer) {
  35100. return _this.parse(buffer);
  35101. });
  35102. }
  35103. }, {
  35104. key: "parse",
  35105. value: function parse(buffer) {
  35106. var dataView = new DataView(buffer); // 16-byte header
  35107. // 4 bytes
  35108. var magic = String.fromCharCode(dataView.getUint8(0)) + String.fromCharCode(dataView.getUint8(1)) + String.fromCharCode(dataView.getUint8(2)) + String.fromCharCode(dataView.getUint8(3));
  35109. console.assert(magic === 'cmpt'); // 4 bytes
  35110. var version = dataView.getUint32(4, true);
  35111. console.assert(version === 1); // 4 bytes
  35112. var byteLength = dataView.getUint32(8, true);
  35113. console.assert(byteLength === buffer.byteLength); // 4 bytes
  35114. var tilesLength = dataView.getUint32(12, true);
  35115. var tiles = [];
  35116. var offset = 16;
  35117. for (var i = 0; i < tilesLength; i++) {
  35118. var tileView = new DataView(buffer, offset, 12);
  35119. var tileMagic = String.fromCharCode(tileView.getUint8(0)) + String.fromCharCode(tileView.getUint8(1)) + String.fromCharCode(tileView.getUint8(2)) + String.fromCharCode(tileView.getUint8(3));
  35120. var tileVersion = tileView.getUint32(4, true);
  35121. var _byteLength = tileView.getUint32(8, true);
  35122. var tileBuffer = new Uint8Array(buffer, offset, _byteLength);
  35123. tiles.push({
  35124. type: tileMagic,
  35125. buffer: tileBuffer,
  35126. version: tileVersion
  35127. });
  35128. offset += _byteLength;
  35129. }
  35130. return {
  35131. version: version,
  35132. tiles: tiles
  35133. };
  35134. }
  35135. }]);
  35136. return CMPTLoaderBase;
  35137. }();
  35138. exports.CMPTLoaderBase = CMPTLoaderBase;
  35139. },{}],"../src/three/CMPTLoader.js":[function(require,module,exports) {
  35140. "use strict";
  35141. Object.defineProperty(exports, "__esModule", {
  35142. value: true
  35143. });
  35144. exports.CMPTLoader = void 0;
  35145. var _three = require("three");
  35146. var _CMPTLoaderBase2 = require("../base/CMPTLoaderBase.js");
  35147. var _B3DMLoader = require("./B3DMLoader.js");
  35148. var _PNTSLoader = require("./PNTSLoader.js");
  35149. var _I3DMLoader = require("./I3DMLoader.js");
  35150. function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
  35151. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  35152. function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
  35153. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
  35154. function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }
  35155. function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
  35156. function _get(target, property, receiver) { if (typeof Reflect !== "undefined" && Reflect.get) { _get = Reflect.get; } else { _get = function _get(target, property, receiver) { var base = _superPropBase(target, property); if (!base) return; var desc = Object.getOwnPropertyDescriptor(base, property); if (desc.get) { return desc.get.call(receiver); } return desc.value; }; } return _get(target, property, receiver || target); }
  35157. function _superPropBase(object, property) { while (!Object.prototype.hasOwnProperty.call(object, property)) { object = _getPrototypeOf(object); if (object === null) break; } return object; }
  35158. function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
  35159. function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }
  35160. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  35161. var CMPTLoader =
  35162. /*#__PURE__*/
  35163. function (_CMPTLoaderBase) {
  35164. _inherits(CMPTLoader, _CMPTLoaderBase);
  35165. function CMPTLoader() {
  35166. var _this;
  35167. var manager = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : _three.DefaultLoadingManager;
  35168. _classCallCheck(this, CMPTLoader);
  35169. _this = _possibleConstructorReturn(this, _getPrototypeOf(CMPTLoader).call(this));
  35170. _this.manager = manager;
  35171. return _this;
  35172. }
  35173. _createClass(CMPTLoader, [{
  35174. key: "parse",
  35175. value: function parse(buffer) {
  35176. var result = _get(_getPrototypeOf(CMPTLoader.prototype), "parse", this).call(this, buffer);
  35177. var manager = this.manager;
  35178. var group = new _three.Group();
  35179. var results = [];
  35180. var promises = [];
  35181. for (var i in result.tiles) {
  35182. var _result$tiles$i = result.tiles[i],
  35183. type = _result$tiles$i.type,
  35184. _buffer = _result$tiles$i.buffer;
  35185. switch (type) {
  35186. case 'b3dm':
  35187. {
  35188. var slicedBuffer = _buffer.slice();
  35189. var promise = new _B3DMLoader.B3DMLoader(manager).parse(slicedBuffer.buffer).then(function (res) {
  35190. results.push(res);
  35191. group.add(res.scene);
  35192. });
  35193. promises.push(promise);
  35194. break;
  35195. }
  35196. case 'pnts':
  35197. {
  35198. var _slicedBuffer = _buffer.slice();
  35199. var pointsResult = new _PNTSLoader.PNTSLoader(manager).parse(_slicedBuffer.buffer);
  35200. results.push(pointsResult);
  35201. group.add(pointsResult.scene);
  35202. break;
  35203. }
  35204. case 'i3dm':
  35205. {
  35206. var _slicedBuffer2 = _buffer.slice();
  35207. var _promise = new _I3DMLoader.I3DMLoader(manager).parse(_slicedBuffer2.buffer).then(function (res) {
  35208. results.push(res);
  35209. group.add(res.scene);
  35210. });
  35211. promises.push(_promise);
  35212. break;
  35213. }
  35214. }
  35215. }
  35216. return Promise.all(promises).then(function () {
  35217. return {
  35218. tiles: results,
  35219. scene: group
  35220. };
  35221. });
  35222. }
  35223. }]);
  35224. return CMPTLoader;
  35225. }(_CMPTLoaderBase2.CMPTLoaderBase);
  35226. exports.CMPTLoader = CMPTLoader;
  35227. },{"three":"../node_modules/three/build/three.module.js","../base/CMPTLoaderBase.js":"../src/base/CMPTLoaderBase.js","./B3DMLoader.js":"../src/three/B3DMLoader.js","./PNTSLoader.js":"../src/three/PNTSLoader.js","./I3DMLoader.js":"../src/three/I3DMLoader.js"}],"../src/three/TilesGroup.js":[function(require,module,exports) {
  35228. "use strict";
  35229. Object.defineProperty(exports, "__esModule", {
  35230. value: true
  35231. });
  35232. exports.TilesGroup = void 0;
  35233. var _three = require("three");
  35234. function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
  35235. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  35236. function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
  35237. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
  35238. function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }
  35239. function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
  35240. function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
  35241. function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }
  35242. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  35243. // Specialization of "Group" that only updates world matrices of children if
  35244. // the transform has changed since the last update and ignores the "force"
  35245. // parameter under the assumption that the children tiles will not move.
  35246. var tempMat = new _three.Matrix4();
  35247. var TilesGroup =
  35248. /*#__PURE__*/
  35249. function (_Group) {
  35250. _inherits(TilesGroup, _Group);
  35251. function TilesGroup(tilesRenderer) {
  35252. var _this;
  35253. _classCallCheck(this, TilesGroup);
  35254. _this = _possibleConstructorReturn(this, _getPrototypeOf(TilesGroup).call(this));
  35255. _this.tilesRenderer = tilesRenderer;
  35256. return _this;
  35257. }
  35258. _createClass(TilesGroup, [{
  35259. key: "raycast",
  35260. value: function raycast(raycaster, intersects) {
  35261. this.tilesRenderer.raycast(raycaster, intersects);
  35262. }
  35263. }, {
  35264. key: "updateMatrixWorld",
  35265. value: function updateMatrixWorld(force) {
  35266. if (this.matrixAutoUpdate) {
  35267. this.updateMatrix();
  35268. }
  35269. if (this.matrixWorldNeedsUpdate || force) {
  35270. if (this.parent === null) {
  35271. tempMat.copy(this.matrix);
  35272. } else {
  35273. tempMat.multiplyMatrices(this.parent.matrixWorld, this.matrix);
  35274. }
  35275. this.matrixWorldNeedsUpdate = false; // check if the matrix changed relative to what it was.
  35276. var elA = tempMat.elements;
  35277. var elB = this.matrixWorld.elements;
  35278. var isDifferent = false;
  35279. for (var i = 0; i < 16; i++) {
  35280. var itemA = elA[i];
  35281. var itemB = elB[i];
  35282. var diff = Math.abs(itemA - itemB);
  35283. if (diff > Number.EPSILON) {
  35284. isDifferent = true;
  35285. break;
  35286. }
  35287. }
  35288. if (isDifferent) {
  35289. this.matrixWorld.copy(tempMat); // update children
  35290. // the children will not have to change unless the parent group has updated
  35291. var children = this.children;
  35292. for (var _i = 0, l = children.length; _i < l; _i++) {
  35293. children[_i].updateMatrixWorld();
  35294. }
  35295. }
  35296. }
  35297. }
  35298. }]);
  35299. return TilesGroup;
  35300. }(_three.Group);
  35301. exports.TilesGroup = TilesGroup;
  35302. },{"three":"../node_modules/three/build/three.module.js"}],"../src/three/raycastTraverse.js":[function(require,module,exports) {
  35303. "use strict";
  35304. Object.defineProperty(exports, "__esModule", {
  35305. value: true
  35306. });
  35307. exports.raycastTraverseFirstHit = raycastTraverseFirstHit;
  35308. exports.raycastTraverse = raycastTraverse;
  35309. var _three = require("three");
  35310. var _sphere = new _three.Sphere();
  35311. var _mat = new _three.Matrix4();
  35312. var _vec = new _three.Vector3();
  35313. var _vec2 = new _three.Vector3();
  35314. var _ray = new _three.Ray();
  35315. var _hitArray = [];
  35316. function distanceSort(a, b) {
  35317. return a.distance - b.distance;
  35318. }
  35319. function intersectTileScene(scene, raycaster, intersects) {
  35320. // Don't intersect the box3 helpers because those are used for debugging
  35321. scene.traverse(function (c) {
  35322. // We set the default raycast function to empty so three.js doesn't automatically cast against it
  35323. Object.getPrototypeOf(c).raycast.call(c, raycaster, intersects);
  35324. });
  35325. } // Returns the closest hit when traversing the tree
  35326. function raycastTraverseFirstHit(root, group, activeTiles, raycaster) {
  35327. // If the root is active make sure we've checked it
  35328. if (activeTiles.has(root)) {
  35329. intersectTileScene(root.cached.scene, raycaster, _hitArray);
  35330. if (_hitArray.length > 0) {
  35331. if (_hitArray.length > 1) {
  35332. _hitArray.sort(distanceSort);
  35333. }
  35334. var res = _hitArray[0];
  35335. _hitArray.length = 0;
  35336. return res;
  35337. } else {
  35338. return null;
  35339. }
  35340. } // TODO: can we avoid creating a new array here every time to save on memory?
  35341. var array = [];
  35342. var children = root.children;
  35343. for (var i = 0, l = children.length; i < l; i++) {
  35344. var tile = children[i];
  35345. var cached = tile.cached;
  35346. var groupMatrixWorld = group.matrixWorld;
  35347. _mat.copy(groupMatrixWorld); // if we don't hit the sphere then early out
  35348. var sphere = cached.sphere;
  35349. if (sphere) {
  35350. _sphere.copy(sphere);
  35351. _sphere.applyMatrix4(_mat);
  35352. if (!raycaster.ray.intersectsSphere(_sphere)) {
  35353. continue;
  35354. }
  35355. } // TODO: check region?
  35356. var boundingBox = cached.box;
  35357. var obbMat = cached.boxTransform;
  35358. if (boundingBox) {
  35359. _mat.multiply(obbMat).invert();
  35360. _ray.copy(raycaster.ray);
  35361. _ray.applyMatrix4(_mat);
  35362. if (_ray.intersectBox(boundingBox, _vec)) {
  35363. // account for tile scale
  35364. var invScale = void 0;
  35365. _vec2.setFromMatrixScale(_mat);
  35366. invScale = _vec2.x;
  35367. if (Math.abs(Math.max(_vec2.x - _vec2.y, _vec2.x - _vec2.z)) > 1e-6) {
  35368. console.warn('ThreeTilesRenderer : Non uniform scale used for tile which may cause issues when raycasting.');
  35369. } // if we intersect the box save the distance to the tile bounds
  35370. var data = {
  35371. distance: Infinity,
  35372. tile: null
  35373. };
  35374. array.push(data);
  35375. data.distance = _vec.distanceToSquared(_ray.origin) * invScale * invScale;
  35376. data.tile = tile;
  35377. } else {
  35378. continue;
  35379. }
  35380. }
  35381. } // sort them by ascending distance
  35382. array.sort(distanceSort); // traverse until we find the best hit and early out if a tile bounds
  35383. // couldn't possible include a best hit
  35384. var bestDistanceSquared = Infinity;
  35385. var bestHit = null;
  35386. for (var _i = 0, _l = array.length; _i < _l; _i++) {
  35387. var _data = array[_i];
  35388. var distanceSquared = _data.distance;
  35389. if (distanceSquared > bestDistanceSquared) {
  35390. break;
  35391. } else {
  35392. var _tile = _data.tile;
  35393. var scene = _tile.cached.scene;
  35394. var hit = null;
  35395. if (activeTiles.has(_tile)) {
  35396. // save the hit if it's closer
  35397. intersectTileScene(scene, raycaster, _hitArray);
  35398. if (_hitArray.length > 0) {
  35399. if (_hitArray.length > 1) {
  35400. _hitArray.sort(distanceSort);
  35401. }
  35402. hit = _hitArray[0];
  35403. }
  35404. } else {
  35405. hit = raycastTraverseFirstHit(_tile, group, activeTiles, raycaster);
  35406. }
  35407. if (hit) {
  35408. var hitDistanceSquared = hit.distance * hit.distance;
  35409. if (hitDistanceSquared < bestDistanceSquared) {
  35410. bestDistanceSquared = hitDistanceSquared;
  35411. bestHit = hit;
  35412. }
  35413. _hitArray.length = 0;
  35414. }
  35415. }
  35416. }
  35417. return bestHit;
  35418. }
  35419. function raycastTraverse(tile, group, activeTiles, raycaster, intersects) {
  35420. var cached = tile.cached;
  35421. var groupMatrixWorld = group.matrixWorld;
  35422. _mat.copy(groupMatrixWorld); // Early out if we don't hit this tile sphere
  35423. var sphere = cached.sphere;
  35424. if (sphere) {
  35425. _sphere.copy(sphere);
  35426. _sphere.applyMatrix4(_mat);
  35427. if (!raycaster.ray.intersectsSphere(_sphere)) {
  35428. return;
  35429. }
  35430. } // Early out if we don't this this tile box
  35431. var boundingBox = cached.box;
  35432. var obbMat = cached.boxTransform;
  35433. if (boundingBox) {
  35434. _mat.multiply(obbMat).invert();
  35435. _ray.copy(raycaster.ray).applyMatrix4(_mat);
  35436. if (!_ray.intersectsBox(boundingBox)) {
  35437. return;
  35438. }
  35439. } // TODO: check region
  35440. var scene = cached.scene;
  35441. if (activeTiles.has(tile)) {
  35442. intersectTileScene(scene, raycaster, intersects);
  35443. return;
  35444. }
  35445. var children = tile.children;
  35446. for (var i = 0, l = children.length; i < l; i++) {
  35447. raycastTraverse(children[i], group, activeTiles, raycaster, intersects);
  35448. }
  35449. }
  35450. },{"three":"../node_modules/three/build/three.module.js"}],"../src/three/TilesRenderer.js":[function(require,module,exports) {
  35451. "use strict";
  35452. Object.defineProperty(exports, "__esModule", {
  35453. value: true
  35454. });
  35455. exports.TilesRenderer = void 0;
  35456. var _TilesRendererBase2 = require("../base/TilesRendererBase.js");
  35457. var _B3DMLoader = require("./B3DMLoader.js");
  35458. var _PNTSLoader = require("./PNTSLoader.js");
  35459. var _I3DMLoader = require("./I3DMLoader.js");
  35460. var _CMPTLoader = require("./CMPTLoader.js");
  35461. var _TilesGroup = require("./TilesGroup.js");
  35462. var _three = require("three");
  35463. var _raycastTraverse = require("./raycastTraverse.js");
  35464. function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
  35465. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  35466. function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }
  35467. function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
  35468. function _get(target, property, receiver) { if (typeof Reflect !== "undefined" && Reflect.get) { _get = Reflect.get; } else { _get = function _get(target, property, receiver) { var base = _superPropBase(target, property); if (!base) return; var desc = Object.getOwnPropertyDescriptor(base, property); if (desc.get) { return desc.get.call(receiver); } return desc.value; }; } return _get(target, property, receiver || target); }
  35469. function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
  35470. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
  35471. function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }
  35472. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  35473. function set(target, property, value, receiver) { if (typeof Reflect !== "undefined" && Reflect.set) { set = Reflect.set; } else { set = function set(target, property, value, receiver) { var base = _superPropBase(target, property); var desc; if (base) { desc = Object.getOwnPropertyDescriptor(base, property); if (desc.set) { desc.set.call(receiver, value); return true; } else if (!desc.writable) { return false; } } desc = Object.getOwnPropertyDescriptor(receiver, property); if (desc) { if (!desc.writable) { return false; } desc.value = value; Object.defineProperty(receiver, property, desc); } else { _defineProperty(receiver, property, value); } return true; }; } return set(target, property, value, receiver); }
  35474. function _set(target, property, value, receiver, isStrict) { var s = set(target, property, value, receiver || target); if (!s && isStrict) { throw new Error('failed to set property'); } return value; }
  35475. function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
  35476. function _superPropBase(object, property) { while (!Object.prototype.hasOwnProperty.call(object, property)) { object = _getPrototypeOf(object); if (object === null) break; } return object; }
  35477. function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
  35478. var INITIAL_FRUSTUM_CULLED = Symbol('INITIAL_FRUSTUM_CULLED');
  35479. var DEG2RAD = _three.Math.DEG2RAD;
  35480. var tempMat = new _three.Matrix4();
  35481. var tempMat2 = new _three.Matrix4();
  35482. var tempVector = new _three.Vector3();
  35483. var vecX = new _three.Vector3();
  35484. var vecY = new _three.Vector3();
  35485. var vecZ = new _three.Vector3();
  35486. var X_AXIS = new _three.Vector3(1, 0, 0);
  35487. var Y_AXIS = new _three.Vector3(0, 1, 0);
  35488. function emptyRaycast() {}
  35489. function updateFrustumCulled(object, toInitialValue) {
  35490. object.traverse(function (c) {
  35491. c.frustumCulled = c[INITIAL_FRUSTUM_CULLED] && toInitialValue;
  35492. });
  35493. }
  35494. var TilesRenderer =
  35495. /*#__PURE__*/
  35496. function (_TilesRendererBase) {
  35497. _inherits(TilesRenderer, _TilesRendererBase);
  35498. _createClass(TilesRenderer, [{
  35499. key: "autoDisableRendererCulling",
  35500. get: function get() {
  35501. return this._autoDisableRendererCulling;
  35502. },
  35503. set: function set(value) {
  35504. if (this._autoDisableRendererCulling !== value) {
  35505. _set(_getPrototypeOf(TilesRenderer.prototype), "_autoDisableRendererCulling", value, this, true);
  35506. this.traverse(function (tile) {
  35507. if (tile.scene) {
  35508. updateFrustumCulled(tile.scene, value);
  35509. }
  35510. });
  35511. }
  35512. }
  35513. }]);
  35514. function TilesRenderer() {
  35515. var _getPrototypeOf2;
  35516. var _this;
  35517. _classCallCheck(this, TilesRenderer);
  35518. for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
  35519. args[_key] = arguments[_key];
  35520. }
  35521. _this = _possibleConstructorReturn(this, (_getPrototypeOf2 = _getPrototypeOf(TilesRenderer)).call.apply(_getPrototypeOf2, [this].concat(args)));
  35522. _this.group = new _TilesGroup.TilesGroup(_assertThisInitialized(_this));
  35523. _this.cameras = [];
  35524. _this.cameraMap = new Map();
  35525. _this.cameraInfo = [];
  35526. _this.activeTiles = new Set();
  35527. _this.visibleTiles = new Set();
  35528. _this._autoDisableRendererCulling = true;
  35529. _this.onLoadTileSet = null;
  35530. _this.onLoadModel = null;
  35531. _this.onDisposeModel = null;
  35532. _this.manager = new _three.LoadingManager();
  35533. return _this;
  35534. }
  35535. /* Public API */
  35536. _createClass(TilesRenderer, [{
  35537. key: "getBounds",
  35538. value: function getBounds(box) {
  35539. if (!this.root) {
  35540. return false;
  35541. }
  35542. var cached = this.root.cached;
  35543. var boundingBox = cached.box;
  35544. var obbMat = cached.boxTransform;
  35545. if (boundingBox) {
  35546. box.copy(boundingBox);
  35547. box.applyMatrix4(obbMat);
  35548. return true;
  35549. } else {
  35550. return false;
  35551. }
  35552. }
  35553. }, {
  35554. key: "forEachLoadedModel",
  35555. value: function forEachLoadedModel(callback) {
  35556. this.traverse(function (tile) {
  35557. var scene = tile.cached.scene;
  35558. if (scene) {
  35559. callback(scene, tile);
  35560. }
  35561. });
  35562. }
  35563. }, {
  35564. key: "raycast",
  35565. value: function raycast(raycaster, intersects) {
  35566. if (!this.root) {
  35567. return;
  35568. }
  35569. if (raycaster.firstHitOnly) {
  35570. var hit = (0, _raycastTraverse.raycastTraverseFirstHit)(this.root, this.group, this.activeTiles, raycaster);
  35571. if (hit) {
  35572. intersects.push(hit);
  35573. }
  35574. } else {
  35575. (0, _raycastTraverse.raycastTraverse)(this.root, this.group, this.activeTiles, raycaster, intersects);
  35576. }
  35577. }
  35578. }, {
  35579. key: "hasCamera",
  35580. value: function hasCamera(camera) {
  35581. return this.cameraMap.has(camera);
  35582. }
  35583. }, {
  35584. key: "setCamera",
  35585. value: function setCamera(camera) {
  35586. var cameras = this.cameras;
  35587. var cameraMap = this.cameraMap;
  35588. if (!cameraMap.has(camera)) {
  35589. cameraMap.set(camera, new _three.Vector2());
  35590. cameras.push(camera);
  35591. return true;
  35592. }
  35593. return false;
  35594. }
  35595. }, {
  35596. key: "setResolution",
  35597. value: function setResolution(camera, xOrVec, y) {
  35598. var cameraMap = this.cameraMap;
  35599. if (!cameraMap.has(camera)) {
  35600. return false;
  35601. }
  35602. if (xOrVec instanceof _three.Vector2) {
  35603. cameraMap.get(camera).copy(xOrVec);
  35604. } else {
  35605. cameraMap.get(camera).set(xOrVec, y);
  35606. }
  35607. return true;
  35608. }
  35609. }, {
  35610. key: "setResolutionFromRenderer",
  35611. value: function setResolutionFromRenderer(camera, renderer) {
  35612. var cameraMap = this.cameraMap;
  35613. if (!cameraMap.has(camera)) {
  35614. return false;
  35615. }
  35616. var resolution = cameraMap.get(camera);
  35617. renderer.getSize(resolution);
  35618. resolution.multiplyScalar(renderer.getPixelRatio());
  35619. return true;
  35620. }
  35621. }, {
  35622. key: "rotationBetweenDirections",
  35623. value: function rotationBetweenDirections(dir1, dir2) {
  35624. var rotation = new _three.Quaternion();
  35625. var a = new _three.Vector3().crossVectors(dir1, dir2);
  35626. rotation.x = a.x;
  35627. rotation.y = a.y;
  35628. rotation.z = a.z;
  35629. rotation.w = 1 + dir1.clone().dot(dir2);
  35630. rotation.normalize();
  35631. return rotation;
  35632. }
  35633. }, {
  35634. key: "deleteCamera",
  35635. value: function deleteCamera(camera) {
  35636. var cameras = this.cameras;
  35637. var cameraMap = this.cameraMap;
  35638. if (cameraMap.has(camera)) {
  35639. var index = cameras.indexOf(camera);
  35640. cameras.splice(index, 1);
  35641. cameraMap.delete(camera);
  35642. return true;
  35643. }
  35644. return false;
  35645. }
  35646. /* Overriden */
  35647. }, {
  35648. key: "fetchTileSet",
  35649. value: function fetchTileSet(url) {
  35650. var _get2,
  35651. _this2 = this;
  35652. for (var _len2 = arguments.length, rest = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
  35653. rest[_key2 - 1] = arguments[_key2];
  35654. }
  35655. var pr = (_get2 = _get(_getPrototypeOf(TilesRenderer.prototype), "fetchTileSet", this)).call.apply(_get2, [this, url].concat(rest));
  35656. pr.then(function (json) {
  35657. if (_this2.onLoadTileSet) {
  35658. // Push this onto the end of the event stack to ensure this runs
  35659. // after the base renderer has placed the provided json where it
  35660. // needs to be placed and is ready for an update.
  35661. Promise.resolve().then(function () {
  35662. _this2.onLoadTileSet(json, url);
  35663. });
  35664. }
  35665. Promise.resolve().then(function () {
  35666. if (_this2.ionAssetId) {
  35667. var transform = _this2.root.cached.boxTransform;
  35668. var position = new _three.Vector3().setFromMatrixPosition(transform);
  35669. var distance = position.length();
  35670. var surfaceDir = position.normalize();
  35671. var rotation = _this2.rotationBetweenDirections(surfaceDir, new _three.Vector3(0, 1, 0)); // Rotate tiles to the north pole around the Earth
  35672. _this2.group.quaternion.x = rotation.x;
  35673. _this2.group.quaternion.y = rotation.y;
  35674. _this2.group.quaternion.z = rotation.z;
  35675. _this2.group.quaternion.w = rotation.w; //Move tiles to the center of the Earth
  35676. _this2.group.position.y = -distance;
  35677. }
  35678. });
  35679. });
  35680. return pr;
  35681. }
  35682. /** set projection matrix to frustum for legacy versions of three.js */
  35683. }, {
  35684. key: "setFromProjectionMatrix",
  35685. value: function setFromProjectionMatrix(frustum, m) {
  35686. var planes = frustum.planes;
  35687. var me = m.elements;
  35688. var me0 = me[0],
  35689. me1 = me[1],
  35690. me2 = me[2],
  35691. me3 = me[3];
  35692. var me4 = me[4],
  35693. me5 = me[5],
  35694. me6 = me[6],
  35695. me7 = me[7];
  35696. var me8 = me[8],
  35697. me9 = me[9],
  35698. me10 = me[10],
  35699. me11 = me[11];
  35700. var me12 = me[12],
  35701. me13 = me[13],
  35702. me14 = me[14],
  35703. me15 = me[15];
  35704. planes[0].setComponents(me3 - me0, me7 - me4, me11 - me8, me15 - me12).normalize();
  35705. planes[1].setComponents(me3 + me0, me7 + me4, me11 + me8, me15 + me12).normalize();
  35706. planes[2].setComponents(me3 + me1, me7 + me5, me11 + me9, me15 + me13).normalize();
  35707. planes[3].setComponents(me3 - me1, me7 - me5, me11 - me9, me15 - me13).normalize();
  35708. planes[4].setComponents(me3 - me2, me7 - me6, me11 - me10, me15 - me14).normalize();
  35709. planes[5].setComponents(me3 + me2, me7 + me6, me11 + me10, me15 + me14).normalize();
  35710. }
  35711. }, {
  35712. key: "update",
  35713. value: function update() {
  35714. var group = this.group;
  35715. var cameras = this.cameras;
  35716. var cameraMap = this.cameraMap;
  35717. var cameraInfo = this.cameraInfo;
  35718. if (cameras.length === 0) {
  35719. console.warn('TilesRenderer: no cameras defined. Cannot update 3d tiles.');
  35720. return;
  35721. } // automatically scale the array of cameraInfo to match the cameras
  35722. while (cameraInfo.length > cameras.length) {
  35723. cameraInfo.pop();
  35724. }
  35725. while (cameraInfo.length < cameras.length) {
  35726. cameraInfo.push({
  35727. frustum: new _three.Frustum(),
  35728. sseDenominator: -1,
  35729. position: new _three.Vector3(),
  35730. invScale: -1,
  35731. pixelSize: 0
  35732. });
  35733. } // extract scale of group container
  35734. tempMat2.copy(group.matrixWorld).invert();
  35735. var invScale;
  35736. tempVector.setFromMatrixScale(tempMat2);
  35737. invScale = tempVector.x;
  35738. if (Math.abs(Math.max(tempVector.x - tempVector.y, tempVector.x - tempVector.z)) > 1e-6) {
  35739. console.warn('ThreeTilesRenderer : Non uniform scale used for tile which may cause issues when calculating screen space error.');
  35740. } // store the camera cameraInfo in the 3d tiles root frame
  35741. for (var i = 0, l = cameraInfo.length; i < l; i++) {
  35742. var camera = cameras[i];
  35743. var info = cameraInfo[i];
  35744. var frustum = info.frustum;
  35745. var position = info.position;
  35746. var resolution = cameraMap.get(camera);
  35747. if (resolution.width === 0 || resolution.height === 0) {
  35748. console.warn('TilesRenderer: resolution for camera error calculation is not set.');
  35749. }
  35750. if (camera.isPerspectiveCamera) {
  35751. info.sseDenominator = 2 * Math.tan(0.5 * camera.fov * DEG2RAD) / resolution.height;
  35752. }
  35753. if (camera.isOrthographicCamera) {
  35754. var w = camera.right - camera.left;
  35755. var h = camera.top - camera.bottom;
  35756. info.pixelSize = Math.max(h / resolution.height, w / resolution.width);
  35757. }
  35758. info.invScale = invScale; // get frustum in grop root frame
  35759. tempMat.copy(group.matrixWorld);
  35760. tempMat.premultiply(camera.matrixWorldInverse);
  35761. tempMat.premultiply(camera.projectionMatrix);
  35762. if (typeof frustum.setFromProjectionMatrix === 'function') {
  35763. frustum.setFromProjectionMatrix(tempMat);
  35764. } else {
  35765. this.setFromProjectionMatrix(frustum, tempMat);
  35766. } // get transform position in group root frame
  35767. position.set(0, 0, 0);
  35768. position.applyMatrix4(camera.matrixWorld);
  35769. position.applyMatrix4(tempMat2);
  35770. }
  35771. _get(_getPrototypeOf(TilesRenderer.prototype), "update", this).call(this);
  35772. }
  35773. }, {
  35774. key: "preprocessNode",
  35775. value: function preprocessNode(tile, parentTile, tileSetDir) {
  35776. _get(_getPrototypeOf(TilesRenderer.prototype), "preprocessNode", this).call(this, tile, parentTile, tileSetDir);
  35777. var transform = new _three.Matrix4();
  35778. if (tile.transform) {
  35779. var transformArr = tile.transform;
  35780. for (var i = 0; i < 16; i++) {
  35781. transform.elements[i] = transformArr[i];
  35782. }
  35783. } else {
  35784. transform.identity();
  35785. }
  35786. if (parentTile) {
  35787. transform.multiply(parentTile.cached.transform);
  35788. }
  35789. var box = null;
  35790. var boxTransform = null;
  35791. var boxTransformInverse = null;
  35792. if ('box' in tile.boundingVolume) {
  35793. var data = tile.boundingVolume.box;
  35794. box = new _three.Box3();
  35795. boxTransform = new _three.Matrix4();
  35796. boxTransformInverse = new _three.Matrix4(); // get the extents of the bounds in each axis
  35797. vecX.set(data[3], data[4], data[5]);
  35798. vecY.set(data[6], data[7], data[8]);
  35799. vecZ.set(data[9], data[10], data[11]);
  35800. var scaleX = vecX.length();
  35801. var scaleY = vecY.length();
  35802. var scaleZ = vecZ.length();
  35803. vecX.normalize();
  35804. vecY.normalize();
  35805. vecZ.normalize(); // create the oriented frame that the box exists in
  35806. boxTransform.set(vecX.x, vecY.x, vecZ.x, data[0], vecX.y, vecY.y, vecZ.y, data[1], vecX.z, vecY.z, vecZ.z, data[2], 0, 0, 0, 1);
  35807. boxTransform.premultiply(transform);
  35808. boxTransformInverse.copy(boxTransform).invert(); // scale the box by the extents
  35809. box.min.set(-scaleX, -scaleY, -scaleZ);
  35810. box.max.set(scaleX, scaleY, scaleZ);
  35811. }
  35812. var sphere = null;
  35813. if ('sphere' in tile.boundingVolume) {
  35814. var _data = tile.boundingVolume.sphere;
  35815. sphere = new _three.Sphere();
  35816. sphere.center.set(_data[0], _data[1], _data[2]);
  35817. sphere.radius = _data[3];
  35818. sphere.applyMatrix4(transform);
  35819. } else if ('box' in tile.boundingVolume) {
  35820. var _data2 = tile.boundingVolume.box;
  35821. sphere = new _three.Sphere();
  35822. box.getBoundingSphere(sphere);
  35823. sphere.center.set(_data2[0], _data2[1], _data2[2]);
  35824. sphere.applyMatrix4(transform);
  35825. }
  35826. var region = null;
  35827. if ('region' in tile.boundingVolume) {
  35828. console.warn('ThreeTilesRenderer: region bounding volume not supported.');
  35829. }
  35830. tile.cached = {
  35831. loadIndex: 0,
  35832. transform: transform,
  35833. active: false,
  35834. inFrustum: [],
  35835. box: box,
  35836. boxTransform: boxTransform,
  35837. boxTransformInverse: boxTransformInverse,
  35838. sphere: sphere,
  35839. region: region,
  35840. scene: null,
  35841. geometry: null,
  35842. material: null,
  35843. distance: Infinity
  35844. };
  35845. }
  35846. }, {
  35847. key: "parseTile",
  35848. value: function parseTile(buffer, tile, extension) {
  35849. var _this3 = this;
  35850. tile._loadIndex = tile._loadIndex || 0;
  35851. tile._loadIndex++;
  35852. var manager = this.manager;
  35853. var loadIndex = tile._loadIndex;
  35854. var promise = null;
  35855. switch (extension) {
  35856. case 'b3dm':
  35857. promise = new _B3DMLoader.B3DMLoader(manager).parse(buffer).then(function (res) {
  35858. return res.scene;
  35859. });
  35860. break;
  35861. case 'pnts':
  35862. promise = Promise.resolve(new _PNTSLoader.PNTSLoader(manager).parse(buffer).scene);
  35863. break;
  35864. case 'i3dm':
  35865. promise = new _I3DMLoader.I3DMLoader(manager).parse(buffer).then(function (res) {
  35866. return res.scene;
  35867. });
  35868. break;
  35869. case 'cmpt':
  35870. promise = new _CMPTLoader.CMPTLoader(manager).parse(buffer).then(function (res) {
  35871. return res.scene;
  35872. });
  35873. break;
  35874. default:
  35875. console.warn("TilesRenderer: Content type \"".concat(extension, "\" not supported."));
  35876. promise = Promise.resolve(null);
  35877. break;
  35878. }
  35879. return promise.then(function (scene) {
  35880. if (tile._loadIndex !== loadIndex) {
  35881. return;
  35882. }
  35883. var upAxis = _this3.rootTileSet.asset && _this3.rootTileSet.asset.gltfUpAxis || 'y';
  35884. var cached = tile.cached;
  35885. var cachedTransform = cached.transform;
  35886. switch (upAxis.toLowerCase()) {
  35887. case 'x':
  35888. scene.matrix.makeRotationAxis(Y_AXIS, -Math.PI / 2);
  35889. break;
  35890. case 'y':
  35891. scene.matrix.makeRotationAxis(X_AXIS, Math.PI / 2);
  35892. break;
  35893. case 'z':
  35894. break;
  35895. }
  35896. scene.matrix.premultiply(cachedTransform);
  35897. scene.matrix.decompose(scene.position, scene.quaternion, scene.scale);
  35898. scene.traverse(function (c) {
  35899. c[INITIAL_FRUSTUM_CULLED] = c.frustumCulled;
  35900. });
  35901. updateFrustumCulled(scene, _this3.autoDisableRendererCulling);
  35902. cached.scene = scene; // We handle raycasting in a custom way so remove it from here
  35903. scene.traverse(function (c) {
  35904. c.raycast = emptyRaycast;
  35905. });
  35906. var materials = [];
  35907. var geometry = [];
  35908. var textures = [];
  35909. scene.traverse(function (c) {
  35910. if (c.geometry) {
  35911. geometry.push(c.geometry);
  35912. }
  35913. if (c.material) {
  35914. var material = c.material;
  35915. materials.push(c.material);
  35916. for (var key in material) {
  35917. var value = material[key];
  35918. if (value && value.isTexture) {
  35919. textures.push(value);
  35920. }
  35921. }
  35922. }
  35923. });
  35924. cached.materials = materials;
  35925. cached.geometry = geometry;
  35926. cached.textures = textures;
  35927. if (_this3.onLoadModel) {
  35928. _this3.onLoadModel(scene, tile);
  35929. }
  35930. });
  35931. }
  35932. }, {
  35933. key: "disposeTile",
  35934. value: function disposeTile(tile) {
  35935. // This could get called before the tile has finished downloading
  35936. var cached = tile.cached;
  35937. if (cached.scene) {
  35938. var materials = cached.materials;
  35939. var geometry = cached.geometry;
  35940. var textures = cached.textures;
  35941. for (var i = 0, l = geometry.length; i < l; i++) {
  35942. geometry[i].dispose();
  35943. }
  35944. for (var _i = 0, _l = materials.length; _i < _l; _i++) {
  35945. materials[_i].dispose();
  35946. }
  35947. for (var _i2 = 0, _l2 = textures.length; _i2 < _l2; _i2++) {
  35948. var texture = textures[_i2];
  35949. texture.dispose();
  35950. }
  35951. if (this.onDisposeModel) {
  35952. this.onDisposeModel(cached.scene, tile);
  35953. }
  35954. cached.scene = null;
  35955. cached.materials = null;
  35956. cached.textures = null;
  35957. cached.geometry = null;
  35958. }
  35959. tile._loadIndex++;
  35960. }
  35961. }, {
  35962. key: "setTileVisible",
  35963. value: function setTileVisible(tile, visible) {
  35964. var scene = tile.cached.scene;
  35965. var visibleTiles = this.visibleTiles;
  35966. var group = this.group;
  35967. if (visible) {
  35968. group.add(scene);
  35969. visibleTiles.add(tile);
  35970. scene.updateMatrixWorld(true);
  35971. } else {
  35972. group.remove(scene);
  35973. visibleTiles.delete(tile);
  35974. }
  35975. }
  35976. }, {
  35977. key: "setTileActive",
  35978. value: function setTileActive(tile, active) {
  35979. var activeTiles = this.activeTiles;
  35980. if (active) {
  35981. activeTiles.add(tile);
  35982. } else {
  35983. activeTiles.delete(tile);
  35984. }
  35985. }
  35986. }, {
  35987. key: "calculateError",
  35988. value: function calculateError(tile) {
  35989. if (tile.geometricError === 0.0) {
  35990. return 0.0;
  35991. }
  35992. var cached = tile.cached;
  35993. var inFrustum = cached.inFrustum;
  35994. var cameras = this.cameras;
  35995. var cameraInfo = this.cameraInfo; // TODO: Use the content bounding volume here?
  35996. var boundingVolume = tile.boundingVolume;
  35997. if ('box' in boundingVolume) {
  35998. var boundingBox = cached.box;
  35999. var boxTransformInverse = cached.boxTransformInverse;
  36000. var maxError = -Infinity;
  36001. var minDistance = Infinity;
  36002. for (var i = 0, l = cameras.length; i < l; i++) {
  36003. if (!inFrustum[i]) {
  36004. continue;
  36005. } // transform camera position into local frame of the tile bounding box
  36006. var camera = cameras[i];
  36007. var info = cameraInfo[i];
  36008. var invScale = info.invScale;
  36009. tempVector.copy(info.position);
  36010. tempVector.applyMatrix4(boxTransformInverse);
  36011. var error = void 0;
  36012. if (camera.isOrthographicCamera) {
  36013. var pixelSize = info.pixelSize;
  36014. error = tile.geometricError / (pixelSize * invScale);
  36015. } else {
  36016. var distance = boundingBox.distanceToPoint(tempVector);
  36017. var scaledDistance = distance * invScale;
  36018. var sseDenominator = info.sseDenominator;
  36019. error = tile.geometricError / (scaledDistance * sseDenominator);
  36020. minDistance = Math.min(minDistance, scaledDistance);
  36021. }
  36022. maxError = Math.max(maxError, error);
  36023. }
  36024. tile.cached.distance = minDistance;
  36025. return maxError;
  36026. } else if ('sphere' in boundingVolume) {
  36027. // const sphere = cached.sphere;
  36028. console.warn('ThreeTilesRenderer : Sphere bounds not supported.');
  36029. } else if ('region' in boundingVolume) {
  36030. // unsupported
  36031. console.warn('ThreeTilesRenderer : Region bounds not supported.');
  36032. }
  36033. return Infinity;
  36034. }
  36035. }, {
  36036. key: "tileInView",
  36037. value: function tileInView(tile) {
  36038. // TODO: we should use the more precise bounding volumes here if possible
  36039. // cache the root-space planes
  36040. // Use separating axis theorem for frustum and obb
  36041. var cached = tile.cached;
  36042. var sphere = cached.sphere;
  36043. var inFrustum = cached.inFrustum;
  36044. if (sphere) {
  36045. var cameraInfo = this.cameraInfo;
  36046. var inView = false;
  36047. for (var i = 0, l = cameraInfo.length; i < l; i++) {
  36048. // Track which camera frustums this tile is in so we can use it
  36049. // to ignore the error calculations for cameras that can't see it
  36050. var frustum = cameraInfo[i].frustum;
  36051. if (frustum.intersectsSphere(sphere)) {
  36052. inView = true;
  36053. inFrustum[i] = true;
  36054. } else {
  36055. inFrustum[i] = false;
  36056. }
  36057. }
  36058. return inView;
  36059. }
  36060. return true;
  36061. }
  36062. }]);
  36063. return TilesRenderer;
  36064. }(_TilesRendererBase2.TilesRendererBase);
  36065. exports.TilesRenderer = TilesRenderer;
  36066. },{"../base/TilesRendererBase.js":"../src/base/TilesRendererBase.js","./B3DMLoader.js":"../src/three/B3DMLoader.js","./PNTSLoader.js":"../src/three/PNTSLoader.js","./I3DMLoader.js":"../src/three/I3DMLoader.js","./CMPTLoader.js":"../src/three/CMPTLoader.js","./TilesGroup.js":"../src/three/TilesGroup.js","three":"../node_modules/three/build/three.module.js","./raycastTraverse.js":"../src/three/raycastTraverse.js"}],"../src/three/SphereHelper.js":[function(require,module,exports) {
  36067. "use strict";
  36068. Object.defineProperty(exports, "__esModule", {
  36069. value: true
  36070. });
  36071. exports.SphereHelper = void 0;
  36072. var _three = require("three");
  36073. function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
  36074. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  36075. function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
  36076. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
  36077. function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }
  36078. function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
  36079. function _get(target, property, receiver) { if (typeof Reflect !== "undefined" && Reflect.get) { _get = Reflect.get; } else { _get = function _get(target, property, receiver) { var base = _superPropBase(target, property); if (!base) return; var desc = Object.getOwnPropertyDescriptor(base, property); if (desc.get) { return desc.get.call(receiver); } return desc.value; }; } return _get(target, property, receiver || target); }
  36080. function _superPropBase(object, property) { while (!Object.prototype.hasOwnProperty.call(object, property)) { object = _getPrototypeOf(object); if (object === null) break; } return object; }
  36081. function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
  36082. function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }
  36083. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  36084. var _vector = new _three.Vector3();
  36085. var axes = ['x', 'y', 'z'];
  36086. var SphereHelper =
  36087. /*#__PURE__*/
  36088. function (_LineSegments) {
  36089. _inherits(SphereHelper, _LineSegments);
  36090. function SphereHelper(sphere) {
  36091. var _this;
  36092. var color = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0xffff00;
  36093. var angleSteps = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 40;
  36094. _classCallCheck(this, SphereHelper);
  36095. var geometry = new _three.BufferGeometry();
  36096. var positions = [];
  36097. for (var i = 0; i < 3; i++) {
  36098. var axis1 = axes[i];
  36099. var axis2 = axes[(i + 1) % 3];
  36100. _vector.set(0, 0, 0);
  36101. for (var a = 0; a < angleSteps; a++) {
  36102. var angle = void 0;
  36103. angle = 2 * Math.PI * a / (angleSteps - 1);
  36104. _vector[axis1] = Math.sin(angle);
  36105. _vector[axis2] = Math.cos(angle);
  36106. positions.push(_vector.x, _vector.y, _vector.z);
  36107. angle = 2 * Math.PI * (a + 1) / (angleSteps - 1);
  36108. _vector[axis1] = Math.sin(angle);
  36109. _vector[axis2] = Math.cos(angle);
  36110. positions.push(_vector.x, _vector.y, _vector.z);
  36111. }
  36112. }
  36113. geometry.setAttribute('position', new _three.BufferAttribute(new Float32Array(positions), 3));
  36114. geometry.computeBoundingSphere();
  36115. _this = _possibleConstructorReturn(this, _getPrototypeOf(SphereHelper).call(this, geometry, new _three.LineBasicMaterial({
  36116. color: color,
  36117. toneMapped: false
  36118. })));
  36119. _this.sphere = sphere;
  36120. _this.type = 'SphereHelper';
  36121. return _this;
  36122. }
  36123. _createClass(SphereHelper, [{
  36124. key: "updateMatrixWorld",
  36125. value: function updateMatrixWorld(force) {
  36126. var sphere = this.sphere;
  36127. this.position.copy(sphere.center);
  36128. this.scale.setScalar(sphere.radius);
  36129. _get(_getPrototypeOf(SphereHelper.prototype), "updateMatrixWorld", this).call(this, force);
  36130. }
  36131. }]);
  36132. return SphereHelper;
  36133. }(_three.LineSegments);
  36134. exports.SphereHelper = SphereHelper;
  36135. },{"three":"../node_modules/three/build/three.module.js"}],"../src/three/DebugTilesRenderer.js":[function(require,module,exports) {
  36136. "use strict";
  36137. Object.defineProperty(exports, "__esModule", {
  36138. value: true
  36139. });
  36140. exports.DebugTilesRenderer = exports.RANDOM_COLOR = exports.IS_LEAF = exports.RELATIVE_DEPTH = exports.DEPTH = exports.DISTANCE = exports.GEOMETRIC_ERROR = exports.SCREEN_ERROR = exports.NONE = void 0;
  36141. var _three = require("three");
  36142. var _TilesRenderer2 = require("./TilesRenderer.js");
  36143. var _SphereHelper = require("./SphereHelper.js");
  36144. function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
  36145. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  36146. function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
  36147. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
  36148. function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }
  36149. function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
  36150. function _get(target, property, receiver) { if (typeof Reflect !== "undefined" && Reflect.get) { _get = Reflect.get; } else { _get = function _get(target, property, receiver) { var base = _superPropBase(target, property); if (!base) return; var desc = Object.getOwnPropertyDescriptor(base, property); if (desc.get) { return desc.get.call(receiver); } return desc.value; }; } return _get(target, property, receiver || target); }
  36151. function _superPropBase(object, property) { while (!Object.prototype.hasOwnProperty.call(object, property)) { object = _getPrototypeOf(object); if (object === null) break; } return object; }
  36152. function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
  36153. function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }
  36154. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  36155. var ORIGINAL_MATERIAL = Symbol('ORIGINAL_MATERIAL');
  36156. var HAS_RANDOM_COLOR = Symbol('HAS_RANDOM_COLOR');
  36157. function emptyRaycast() {}
  36158. var NONE = 0;
  36159. exports.NONE = NONE;
  36160. var SCREEN_ERROR = 1;
  36161. exports.SCREEN_ERROR = SCREEN_ERROR;
  36162. var GEOMETRIC_ERROR = 2;
  36163. exports.GEOMETRIC_ERROR = GEOMETRIC_ERROR;
  36164. var DISTANCE = 3;
  36165. exports.DISTANCE = DISTANCE;
  36166. var DEPTH = 4;
  36167. exports.DEPTH = DEPTH;
  36168. var RELATIVE_DEPTH = 5;
  36169. exports.RELATIVE_DEPTH = RELATIVE_DEPTH;
  36170. var IS_LEAF = 6;
  36171. exports.IS_LEAF = IS_LEAF;
  36172. var RANDOM_COLOR = 7;
  36173. exports.RANDOM_COLOR = RANDOM_COLOR;
  36174. var DebugTilesRenderer =
  36175. /*#__PURE__*/
  36176. function (_TilesRenderer) {
  36177. _inherits(DebugTilesRenderer, _TilesRenderer);
  36178. function DebugTilesRenderer() {
  36179. var _getPrototypeOf2;
  36180. var _this;
  36181. _classCallCheck(this, DebugTilesRenderer);
  36182. for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
  36183. args[_key] = arguments[_key];
  36184. }
  36185. _this = _possibleConstructorReturn(this, (_getPrototypeOf2 = _getPrototypeOf(DebugTilesRenderer)).call.apply(_getPrototypeOf2, [this].concat(args)));
  36186. var tilesGroup = _this.group;
  36187. var boxGroup = new _three.Group();
  36188. tilesGroup.add(boxGroup);
  36189. var sphereGroup = new _three.Group();
  36190. tilesGroup.add(sphereGroup);
  36191. _this.displayBoxBounds = false;
  36192. _this.displaySphereBounds = false;
  36193. _this.colorMode = NONE;
  36194. _this.boxGroup = boxGroup;
  36195. _this.sphereGroup = sphereGroup;
  36196. _this.maxDebugDepth = -1;
  36197. _this.maxDebugDistance = -1;
  36198. _this.maxDebugError = -1;
  36199. _this.extremeDebugDepth = -1;
  36200. _this.extremeDebugError = -1;
  36201. return _this;
  36202. }
  36203. _createClass(DebugTilesRenderer, [{
  36204. key: "initExtremes",
  36205. value: function initExtremes() {
  36206. // initialize the extreme values of the hierarchy
  36207. var maxDepth = -1;
  36208. this.traverse(function (tile) {
  36209. maxDepth = Math.max(maxDepth, tile.__depth);
  36210. });
  36211. var maxError = -1;
  36212. this.traverse(function (tile) {
  36213. maxError = Math.max(maxError, tile.geometricError);
  36214. });
  36215. this.extremeDebugDepth = maxDepth;
  36216. this.extremeDebugError = maxError;
  36217. }
  36218. }, {
  36219. key: "loadTileSet",
  36220. value: function loadTileSet() {
  36221. var _get2,
  36222. _this2 = this;
  36223. for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
  36224. args[_key2] = arguments[_key2];
  36225. }
  36226. var pr = (_get2 = _get(_getPrototypeOf(DebugTilesRenderer.prototype), "loadTileSet", this)).call.apply(_get2, [this].concat(args));
  36227. pr.then(function () {
  36228. return _this2.initExtremes();
  36229. }).catch(function () {// error is logged internally
  36230. });
  36231. return pr;
  36232. }
  36233. }, {
  36234. key: "getTileInformationFromActiveObject",
  36235. value: function getTileInformationFromActiveObject(object) {
  36236. // Find which tile this scene is associated with. This is slow and
  36237. // intended for debug purposes only.
  36238. var targetTile = null;
  36239. var activeTiles = this.activeTiles;
  36240. activeTiles.forEach(function (tile) {
  36241. if (targetTile) {
  36242. return true;
  36243. }
  36244. var scene = tile.cached.scene;
  36245. if (scene) {
  36246. scene.traverse(function (c) {
  36247. if (c === object) {
  36248. targetTile = tile;
  36249. }
  36250. });
  36251. }
  36252. });
  36253. if (targetTile) {
  36254. return {
  36255. distanceToCamera: targetTile.cached.distance,
  36256. geometricError: targetTile.geometricError,
  36257. screenSpaceError: targetTile.__error,
  36258. depth: targetTile.__depth,
  36259. isLeaf: targetTile.__isLeaf
  36260. };
  36261. } else {
  36262. return null;
  36263. }
  36264. }
  36265. }, {
  36266. key: "update",
  36267. value: function update() {
  36268. _get(_getPrototypeOf(DebugTilesRenderer.prototype), "update", this).call(this);
  36269. if (!this.root) {
  36270. return;
  36271. } // set box or sphere visibility
  36272. this.boxGroup.visible = this.displayBoxBounds;
  36273. this.sphereGroup.visible = this.displaySphereBounds; // get max values to use for materials
  36274. var maxDepth = -1;
  36275. if (this.maxDebugDepth === -1) {
  36276. maxDepth = this.extremeDebugDepth;
  36277. } else {
  36278. maxDepth = this.maxDebugDepth;
  36279. }
  36280. var maxError = -1;
  36281. if (this.maxDebugError === -1) {
  36282. maxError = this.extremeDebugError;
  36283. } else {
  36284. maxError = this.maxDebugError;
  36285. }
  36286. var maxDistance = -1;
  36287. if (this.maxDebugDistance === -1) {
  36288. maxDistance = this.root.cached.sphere.radius;
  36289. } else {
  36290. maxDistance = this.maxDebugDistance;
  36291. }
  36292. var errorTarget = this.errorTarget;
  36293. var colorMode = this.colorMode;
  36294. var visibleTiles = this.visibleTiles;
  36295. visibleTiles.forEach(function (tile) {
  36296. var scene = tile.cached.scene; // create a random color per-tile
  36297. var h, s, l;
  36298. if (colorMode === RANDOM_COLOR) {
  36299. h = Math.random();
  36300. s = 0.5 + Math.random() * 0.5;
  36301. l = 0.375 + Math.random() * 0.25;
  36302. }
  36303. scene.traverse(function (c) {
  36304. var currMaterial = c.material;
  36305. if (currMaterial) {
  36306. // Reset the material if needed
  36307. var originalMaterial = c[ORIGINAL_MATERIAL];
  36308. if (colorMode === NONE && currMaterial !== originalMaterial) {
  36309. c.material.dispose();
  36310. c.material = c[ORIGINAL_MATERIAL];
  36311. } else if (colorMode !== NONE && currMaterial === originalMaterial) {
  36312. if (c.isPoints) {
  36313. var pointsMaterial = new _three.PointsMaterial();
  36314. pointsMaterial.size = originalMaterial.size;
  36315. pointsMaterial.sizeAttenuation = originalMaterial.sizeAttenuation;
  36316. c.material = pointsMaterial;
  36317. } else {
  36318. c.material = new _three.MeshBasicMaterial();
  36319. }
  36320. }
  36321. if (colorMode !== RANDOM_COLOR) {
  36322. delete c.material[HAS_RANDOM_COLOR];
  36323. } // Set the color on the basic material
  36324. switch (colorMode) {
  36325. case DEPTH:
  36326. {
  36327. var val = tile.__depth / maxDepth;
  36328. c.material.color.setRGB(val, val, val);
  36329. break;
  36330. }
  36331. case RELATIVE_DEPTH:
  36332. {
  36333. var _val = tile.__depthFromRenderedParent / maxDepth;
  36334. c.material.color.setRGB(_val, _val, _val);
  36335. break;
  36336. }
  36337. case SCREEN_ERROR:
  36338. {
  36339. var _val2 = tile.__error / errorTarget;
  36340. if (_val2 > 1.0) {
  36341. c.material.color.setRGB(1.0, 0.0, 0.0);
  36342. } else {
  36343. c.material.color.setRGB(_val2, _val2, _val2);
  36344. }
  36345. break;
  36346. }
  36347. case GEOMETRIC_ERROR:
  36348. {
  36349. var _val3 = Math.min(tile.geometricError / maxError, 1);
  36350. c.material.color.setRGB(_val3, _val3, _val3);
  36351. break;
  36352. }
  36353. case DISTANCE:
  36354. {
  36355. // We don't update the distance if the geometric error is 0.0 so
  36356. // it will always be black.
  36357. var _val4 = Math.min(tile.cached.distance / maxDistance, 1);
  36358. c.material.color.setRGB(_val4, _val4, _val4);
  36359. break;
  36360. }
  36361. case IS_LEAF:
  36362. {
  36363. if (!tile.children || tile.children.length === 0) {
  36364. c.material.color.set(0xffffff);
  36365. } else {
  36366. c.material.color.set(0);
  36367. }
  36368. break;
  36369. }
  36370. case RANDOM_COLOR:
  36371. {
  36372. if (!c.material[HAS_RANDOM_COLOR]) {
  36373. c.material.color.setHSL(h, s, l);
  36374. c.material[HAS_RANDOM_COLOR] = true;
  36375. }
  36376. break;
  36377. }
  36378. }
  36379. }
  36380. });
  36381. });
  36382. }
  36383. }, {
  36384. key: "setTileVisible",
  36385. value: function setTileVisible(tile, visible) {
  36386. _get(_getPrototypeOf(DebugTilesRenderer.prototype), "setTileVisible", this).call(this, tile, visible);
  36387. var cached = tile.cached;
  36388. var sphereGroup = this.sphereGroup;
  36389. var boxGroup = this.boxGroup;
  36390. var boxHelperGroup = cached.boxHelperGroup;
  36391. var sphereHelper = cached.sphereHelper;
  36392. if (!visible) {
  36393. boxGroup.remove(boxHelperGroup);
  36394. sphereGroup.remove(sphereHelper);
  36395. } else {
  36396. boxGroup.add(boxHelperGroup);
  36397. boxHelperGroup.updateMatrixWorld(true);
  36398. sphereGroup.add(sphereHelper);
  36399. sphereHelper.updateMatrixWorld(true);
  36400. }
  36401. }
  36402. }, {
  36403. key: "parseTile",
  36404. value: function parseTile(buffer, tile, extension) {
  36405. var _this3 = this;
  36406. return _get(_getPrototypeOf(DebugTilesRenderer.prototype), "parseTile", this).call(this, buffer, tile, extension).then(function () {
  36407. var cached = tile.cached;
  36408. var scene = cached.scene;
  36409. if (scene) {
  36410. var cachedBox = cached.box;
  36411. var cachedBoxMat = cached.boxTransform; // Create debug bounding box
  36412. var boxHelperGroup = new _three.Group();
  36413. boxHelperGroup.matrix.copy(cachedBoxMat);
  36414. boxHelperGroup.matrix.decompose(boxHelperGroup.position, boxHelperGroup.quaternion, boxHelperGroup.scale);
  36415. var boxHelper = new _three.Box3Helper(cachedBox);
  36416. boxHelper.raycast = emptyRaycast;
  36417. boxHelperGroup.add(boxHelper);
  36418. cached.boxHelperGroup = boxHelperGroup;
  36419. if (_this3.visibleTiles.has(tile) && _this3.displayBoxBounds) {
  36420. _this3.boxGroup.add(boxHelperGroup);
  36421. boxHelperGroup.updateMatrixWorld(true);
  36422. } // Create debugbounding sphere
  36423. var cachedSphere = cached.sphere;
  36424. var sphereHelper = new _SphereHelper.SphereHelper(cachedSphere);
  36425. sphereHelper.raycast = emptyRaycast;
  36426. cached.sphereHelper = sphereHelper;
  36427. if (_this3.visibleTiles.has(tile) && _this3.displaySphereBounds) {
  36428. _this3.sphereGroup.add(sphereHelper);
  36429. sphereHelper.updateMatrixWorld(true);
  36430. } // Cache the original materials
  36431. scene.traverse(function (c) {
  36432. var material = c.material;
  36433. if (material) {
  36434. c[ORIGINAL_MATERIAL] = material;
  36435. }
  36436. });
  36437. }
  36438. });
  36439. }
  36440. }, {
  36441. key: "disposeTile",
  36442. value: function disposeTile(tile) {
  36443. _get(_getPrototypeOf(DebugTilesRenderer.prototype), "disposeTile", this).call(this, tile);
  36444. var cached = tile.cached;
  36445. if (cached.boxHelperGroup) {
  36446. cached.boxHelperGroup.children[0].geometry.dispose();
  36447. cached.sphereHelper.geometry.dispose();
  36448. delete cached.boxHelperGroup;
  36449. delete cached.sphereHelper;
  36450. }
  36451. }
  36452. }]);
  36453. return DebugTilesRenderer;
  36454. }(_TilesRenderer2.TilesRenderer);
  36455. exports.DebugTilesRenderer = DebugTilesRenderer;
  36456. },{"three":"../node_modules/three/build/three.module.js","./TilesRenderer.js":"../src/three/TilesRenderer.js","./SphereHelper.js":"../src/three/SphereHelper.js"}],"../src/index.js":[function(require,module,exports) {
  36457. "use strict";
  36458. Object.defineProperty(exports, "__esModule", {
  36459. value: true
  36460. });
  36461. Object.defineProperty(exports, "DebugTilesRenderer", {
  36462. enumerable: true,
  36463. get: function () {
  36464. return _DebugTilesRenderer.DebugTilesRenderer;
  36465. }
  36466. });
  36467. Object.defineProperty(exports, "NONE", {
  36468. enumerable: true,
  36469. get: function () {
  36470. return _DebugTilesRenderer.NONE;
  36471. }
  36472. });
  36473. Object.defineProperty(exports, "SCREEN_ERROR", {
  36474. enumerable: true,
  36475. get: function () {
  36476. return _DebugTilesRenderer.SCREEN_ERROR;
  36477. }
  36478. });
  36479. Object.defineProperty(exports, "GEOMETRIC_ERROR", {
  36480. enumerable: true,
  36481. get: function () {
  36482. return _DebugTilesRenderer.GEOMETRIC_ERROR;
  36483. }
  36484. });
  36485. Object.defineProperty(exports, "DISTANCE", {
  36486. enumerable: true,
  36487. get: function () {
  36488. return _DebugTilesRenderer.DISTANCE;
  36489. }
  36490. });
  36491. Object.defineProperty(exports, "DEPTH", {
  36492. enumerable: true,
  36493. get: function () {
  36494. return _DebugTilesRenderer.DEPTH;
  36495. }
  36496. });
  36497. Object.defineProperty(exports, "RELATIVE_DEPTH", {
  36498. enumerable: true,
  36499. get: function () {
  36500. return _DebugTilesRenderer.RELATIVE_DEPTH;
  36501. }
  36502. });
  36503. Object.defineProperty(exports, "IS_LEAF", {
  36504. enumerable: true,
  36505. get: function () {
  36506. return _DebugTilesRenderer.IS_LEAF;
  36507. }
  36508. });
  36509. Object.defineProperty(exports, "RANDOM_COLOR", {
  36510. enumerable: true,
  36511. get: function () {
  36512. return _DebugTilesRenderer.RANDOM_COLOR;
  36513. }
  36514. });
  36515. Object.defineProperty(exports, "TilesRenderer", {
  36516. enumerable: true,
  36517. get: function () {
  36518. return _TilesRenderer.TilesRenderer;
  36519. }
  36520. });
  36521. Object.defineProperty(exports, "B3DMLoader", {
  36522. enumerable: true,
  36523. get: function () {
  36524. return _B3DMLoader.B3DMLoader;
  36525. }
  36526. });
  36527. Object.defineProperty(exports, "PNTSLoader", {
  36528. enumerable: true,
  36529. get: function () {
  36530. return _PNTSLoader.PNTSLoader;
  36531. }
  36532. });
  36533. Object.defineProperty(exports, "I3DMLoader", {
  36534. enumerable: true,
  36535. get: function () {
  36536. return _I3DMLoader.I3DMLoader;
  36537. }
  36538. });
  36539. Object.defineProperty(exports, "CMPTLoader", {
  36540. enumerable: true,
  36541. get: function () {
  36542. return _CMPTLoader.CMPTLoader;
  36543. }
  36544. });
  36545. Object.defineProperty(exports, "TilesRendererBase", {
  36546. enumerable: true,
  36547. get: function () {
  36548. return _TilesRendererBase.TilesRendererBase;
  36549. }
  36550. });
  36551. Object.defineProperty(exports, "B3DMLoaderBase", {
  36552. enumerable: true,
  36553. get: function () {
  36554. return _B3DMLoaderBase.B3DMLoaderBase;
  36555. }
  36556. });
  36557. Object.defineProperty(exports, "I3DMLoaderBase", {
  36558. enumerable: true,
  36559. get: function () {
  36560. return _I3DMLoaderBase.I3DMLoaderBase;
  36561. }
  36562. });
  36563. Object.defineProperty(exports, "PNTSLoaderBase", {
  36564. enumerable: true,
  36565. get: function () {
  36566. return _PNTSLoaderBase.PNTSLoaderBase;
  36567. }
  36568. });
  36569. Object.defineProperty(exports, "CMPTLoaderBase", {
  36570. enumerable: true,
  36571. get: function () {
  36572. return _CMPTLoaderBase.CMPTLoaderBase;
  36573. }
  36574. });
  36575. Object.defineProperty(exports, "LRUCache", {
  36576. enumerable: true,
  36577. get: function () {
  36578. return _LRUCache.LRUCache;
  36579. }
  36580. });
  36581. Object.defineProperty(exports, "PriorityQueue", {
  36582. enumerable: true,
  36583. get: function () {
  36584. return _PriorityQueue.PriorityQueue;
  36585. }
  36586. });
  36587. var _DebugTilesRenderer = require("./three/DebugTilesRenderer.js");
  36588. var _TilesRenderer = require("./three/TilesRenderer.js");
  36589. var _B3DMLoader = require("./three/B3DMLoader.js");
  36590. var _PNTSLoader = require("./three/PNTSLoader.js");
  36591. var _I3DMLoader = require("./three/I3DMLoader.js");
  36592. var _CMPTLoader = require("./three/CMPTLoader.js");
  36593. var _TilesRendererBase = require("./base/TilesRendererBase.js");
  36594. var _B3DMLoaderBase = require("./base/B3DMLoaderBase.js");
  36595. var _I3DMLoaderBase = require("./base/I3DMLoaderBase.js");
  36596. var _PNTSLoaderBase = require("./base/PNTSLoaderBase.js");
  36597. var _CMPTLoaderBase = require("./base/CMPTLoaderBase.js");
  36598. var _LRUCache = require("./utilities/LRUCache.js");
  36599. var _PriorityQueue = require("./utilities/PriorityQueue.js");
  36600. },{"./three/DebugTilesRenderer.js":"../src/three/DebugTilesRenderer.js","./three/TilesRenderer.js":"../src/three/TilesRenderer.js","./three/B3DMLoader.js":"../src/three/B3DMLoader.js","./three/PNTSLoader.js":"../src/three/PNTSLoader.js","./three/I3DMLoader.js":"../src/three/I3DMLoader.js","./three/CMPTLoader.js":"../src/three/CMPTLoader.js","./base/TilesRendererBase.js":"../src/base/TilesRendererBase.js","./base/B3DMLoaderBase.js":"../src/base/B3DMLoaderBase.js","./base/I3DMLoaderBase.js":"../src/base/I3DMLoaderBase.js","./base/PNTSLoaderBase.js":"../src/base/PNTSLoaderBase.js","./base/CMPTLoaderBase.js":"../src/base/CMPTLoaderBase.js","./utilities/LRUCache.js":"../src/utilities/LRUCache.js","./utilities/PriorityQueue.js":"../src/utilities/PriorityQueue.js"}],"../node_modules/three/examples/jsm/controls/OrbitControls.js":[function(require,module,exports) {
  36601. "use strict";
  36602. Object.defineProperty(exports, "__esModule", {
  36603. value: true
  36604. });
  36605. exports.MapControls = exports.OrbitControls = void 0;
  36606. var _threeModule = require("../../../build/three.module.js");
  36607. // This set of controls performs orbiting, dollying (zooming), and panning.
  36608. // Unlike TrackballControls, it maintains the "up" direction object.up (+Y by default).
  36609. //
  36610. // Orbit - left mouse / touch: one-finger move
  36611. // Zoom - middle mouse, or mousewheel / touch: two-finger spread or squish
  36612. // Pan - right mouse, or left mouse + ctrl/meta/shiftKey, or arrow keys / touch: two-finger move
  36613. var OrbitControls = function (object, domElement) {
  36614. if (domElement === undefined) console.warn('THREE.OrbitControls: The second parameter "domElement" is now mandatory.');
  36615. if (domElement === document) console.error('THREE.OrbitControls: "document" should not be used as the target "domElement". Please use "renderer.domElement" instead.');
  36616. this.object = object;
  36617. this.domElement = domElement; // Set to false to disable this control
  36618. this.enabled = true; // "target" sets the location of focus, where the object orbits around
  36619. this.target = new _threeModule.Vector3(); // How far you can dolly in and out ( PerspectiveCamera only )
  36620. this.minDistance = 0;
  36621. this.maxDistance = Infinity; // How far you can zoom in and out ( OrthographicCamera only )
  36622. this.minZoom = 0;
  36623. this.maxZoom = Infinity; // How far you can orbit vertically, upper and lower limits.
  36624. // Range is 0 to Math.PI radians.
  36625. this.minPolarAngle = 0; // radians
  36626. this.maxPolarAngle = Math.PI; // radians
  36627. // How far you can orbit horizontally, upper and lower limits.
  36628. // If set, the interval [ min, max ] must be a sub-interval of [ - 2 PI, 2 PI ], with ( max - min < 2 PI )
  36629. this.minAzimuthAngle = -Infinity; // radians
  36630. this.maxAzimuthAngle = Infinity; // radians
  36631. // Set to true to enable damping (inertia)
  36632. // If damping is enabled, you must call controls.update() in your animation loop
  36633. this.enableDamping = false;
  36634. this.dampingFactor = 0.05; // This option actually enables dollying in and out; left as "zoom" for backwards compatibility.
  36635. // Set to false to disable zooming
  36636. this.enableZoom = true;
  36637. this.zoomSpeed = 1.0; // Set to false to disable rotating
  36638. this.enableRotate = true;
  36639. this.rotateSpeed = 1.0; // Set to false to disable panning
  36640. this.enablePan = true;
  36641. this.panSpeed = 1.0;
  36642. this.screenSpacePanning = true; // if false, pan orthogonal to world-space direction camera.up
  36643. this.keyPanSpeed = 7.0; // pixels moved per arrow key push
  36644. // Set to true to automatically rotate around the target
  36645. // If auto-rotate is enabled, you must call controls.update() in your animation loop
  36646. this.autoRotate = false;
  36647. this.autoRotateSpeed = 2.0; // 30 seconds per round when fps is 60
  36648. // Set to false to disable use of the keys
  36649. this.enableKeys = true; // The four arrow keys
  36650. this.keys = {
  36651. LEFT: 37,
  36652. UP: 38,
  36653. RIGHT: 39,
  36654. BOTTOM: 40
  36655. }; // Mouse buttons
  36656. this.mouseButtons = {
  36657. LEFT: _threeModule.MOUSE.ROTATE,
  36658. MIDDLE: _threeModule.MOUSE.DOLLY,
  36659. RIGHT: _threeModule.MOUSE.PAN
  36660. }; // Touch fingers
  36661. this.touches = {
  36662. ONE: _threeModule.TOUCH.ROTATE,
  36663. TWO: _threeModule.TOUCH.DOLLY_PAN
  36664. }; // for reset
  36665. this.target0 = this.target.clone();
  36666. this.position0 = this.object.position.clone();
  36667. this.zoom0 = this.object.zoom; //
  36668. // public methods
  36669. //
  36670. this.getPolarAngle = function () {
  36671. return spherical.phi;
  36672. };
  36673. this.getAzimuthalAngle = function () {
  36674. return spherical.theta;
  36675. };
  36676. this.saveState = function () {
  36677. scope.target0.copy(scope.target);
  36678. scope.position0.copy(scope.object.position);
  36679. scope.zoom0 = scope.object.zoom;
  36680. };
  36681. this.reset = function () {
  36682. scope.target.copy(scope.target0);
  36683. scope.object.position.copy(scope.position0);
  36684. scope.object.zoom = scope.zoom0;
  36685. scope.object.updateProjectionMatrix();
  36686. scope.dispatchEvent(changeEvent);
  36687. scope.update();
  36688. state = STATE.NONE;
  36689. }; // this method is exposed, but perhaps it would be better if we can make it private...
  36690. this.update = function () {
  36691. var offset = new _threeModule.Vector3(); // so camera.up is the orbit axis
  36692. var quat = new _threeModule.Quaternion().setFromUnitVectors(object.up, new _threeModule.Vector3(0, 1, 0));
  36693. var quatInverse = quat.clone().invert();
  36694. var lastPosition = new _threeModule.Vector3();
  36695. var lastQuaternion = new _threeModule.Quaternion();
  36696. var twoPI = 2 * Math.PI;
  36697. return function update() {
  36698. var position = scope.object.position;
  36699. offset.copy(position).sub(scope.target); // rotate offset to "y-axis-is-up" space
  36700. offset.applyQuaternion(quat); // angle from z-axis around y-axis
  36701. spherical.setFromVector3(offset);
  36702. if (scope.autoRotate && state === STATE.NONE) {
  36703. rotateLeft(getAutoRotationAngle());
  36704. }
  36705. if (scope.enableDamping) {
  36706. spherical.theta += sphericalDelta.theta * scope.dampingFactor;
  36707. spherical.phi += sphericalDelta.phi * scope.dampingFactor;
  36708. } else {
  36709. spherical.theta += sphericalDelta.theta;
  36710. spherical.phi += sphericalDelta.phi;
  36711. } // restrict theta to be between desired limits
  36712. var min = scope.minAzimuthAngle;
  36713. var max = scope.maxAzimuthAngle;
  36714. if (isFinite(min) && isFinite(max)) {
  36715. if (min < -Math.PI) min += twoPI;else if (min > Math.PI) min -= twoPI;
  36716. if (max < -Math.PI) max += twoPI;else if (max > Math.PI) max -= twoPI;
  36717. if (min <= max) {
  36718. spherical.theta = Math.max(min, Math.min(max, spherical.theta));
  36719. } else {
  36720. spherical.theta = spherical.theta > (min + max) / 2 ? Math.max(min, spherical.theta) : Math.min(max, spherical.theta);
  36721. }
  36722. } // restrict phi to be between desired limits
  36723. spherical.phi = Math.max(scope.minPolarAngle, Math.min(scope.maxPolarAngle, spherical.phi));
  36724. spherical.makeSafe();
  36725. spherical.radius *= scale; // restrict radius to be between desired limits
  36726. spherical.radius = Math.max(scope.minDistance, Math.min(scope.maxDistance, spherical.radius)); // move target to panned location
  36727. if (scope.enableDamping === true) {
  36728. scope.target.addScaledVector(panOffset, scope.dampingFactor);
  36729. } else {
  36730. scope.target.add(panOffset);
  36731. }
  36732. offset.setFromSpherical(spherical); // rotate offset back to "camera-up-vector-is-up" space
  36733. offset.applyQuaternion(quatInverse);
  36734. position.copy(scope.target).add(offset);
  36735. scope.object.lookAt(scope.target);
  36736. if (scope.enableDamping === true) {
  36737. sphericalDelta.theta *= 1 - scope.dampingFactor;
  36738. sphericalDelta.phi *= 1 - scope.dampingFactor;
  36739. panOffset.multiplyScalar(1 - scope.dampingFactor);
  36740. } else {
  36741. sphericalDelta.set(0, 0, 0);
  36742. panOffset.set(0, 0, 0);
  36743. }
  36744. scale = 1; // update condition is:
  36745. // min(camera displacement, camera rotation in radians)^2 > EPS
  36746. // using small-angle approximation cos(x/2) = 1 - x^2 / 8
  36747. if (zoomChanged || lastPosition.distanceToSquared(scope.object.position) > EPS || 8 * (1 - lastQuaternion.dot(scope.object.quaternion)) > EPS) {
  36748. scope.dispatchEvent(changeEvent);
  36749. lastPosition.copy(scope.object.position);
  36750. lastQuaternion.copy(scope.object.quaternion);
  36751. zoomChanged = false;
  36752. return true;
  36753. }
  36754. return false;
  36755. };
  36756. }();
  36757. this.dispose = function () {
  36758. scope.domElement.removeEventListener('contextmenu', onContextMenu, false);
  36759. scope.domElement.removeEventListener('pointerdown', onPointerDown, false);
  36760. scope.domElement.removeEventListener('wheel', onMouseWheel, false);
  36761. scope.domElement.removeEventListener('touchstart', onTouchStart, false);
  36762. scope.domElement.removeEventListener('touchend', onTouchEnd, false);
  36763. scope.domElement.removeEventListener('touchmove', onTouchMove, false);
  36764. scope.domElement.ownerDocument.removeEventListener('pointermove', onPointerMove, false);
  36765. scope.domElement.ownerDocument.removeEventListener('pointerup', onPointerUp, false);
  36766. scope.domElement.removeEventListener('keydown', onKeyDown, false); //scope.dispatchEvent( { type: 'dispose' } ); // should this be added here?
  36767. }; //
  36768. // internals
  36769. //
  36770. var scope = this;
  36771. var changeEvent = {
  36772. type: 'change'
  36773. };
  36774. var startEvent = {
  36775. type: 'start'
  36776. };
  36777. var endEvent = {
  36778. type: 'end'
  36779. };
  36780. var STATE = {
  36781. NONE: -1,
  36782. ROTATE: 0,
  36783. DOLLY: 1,
  36784. PAN: 2,
  36785. TOUCH_ROTATE: 3,
  36786. TOUCH_PAN: 4,
  36787. TOUCH_DOLLY_PAN: 5,
  36788. TOUCH_DOLLY_ROTATE: 6
  36789. };
  36790. var state = STATE.NONE;
  36791. var EPS = 0.000001; // current position in spherical coordinates
  36792. var spherical = new _threeModule.Spherical();
  36793. var sphericalDelta = new _threeModule.Spherical();
  36794. var scale = 1;
  36795. var panOffset = new _threeModule.Vector3();
  36796. var zoomChanged = false;
  36797. var rotateStart = new _threeModule.Vector2();
  36798. var rotateEnd = new _threeModule.Vector2();
  36799. var rotateDelta = new _threeModule.Vector2();
  36800. var panStart = new _threeModule.Vector2();
  36801. var panEnd = new _threeModule.Vector2();
  36802. var panDelta = new _threeModule.Vector2();
  36803. var dollyStart = new _threeModule.Vector2();
  36804. var dollyEnd = new _threeModule.Vector2();
  36805. var dollyDelta = new _threeModule.Vector2();
  36806. function getAutoRotationAngle() {
  36807. return 2 * Math.PI / 60 / 60 * scope.autoRotateSpeed;
  36808. }
  36809. function getZoomScale() {
  36810. return Math.pow(0.95, scope.zoomSpeed);
  36811. }
  36812. function rotateLeft(angle) {
  36813. sphericalDelta.theta -= angle;
  36814. }
  36815. function rotateUp(angle) {
  36816. sphericalDelta.phi -= angle;
  36817. }
  36818. var panLeft = function () {
  36819. var v = new _threeModule.Vector3();
  36820. return function panLeft(distance, objectMatrix) {
  36821. v.setFromMatrixColumn(objectMatrix, 0); // get X column of objectMatrix
  36822. v.multiplyScalar(-distance);
  36823. panOffset.add(v);
  36824. };
  36825. }();
  36826. var panUp = function () {
  36827. var v = new _threeModule.Vector3();
  36828. return function panUp(distance, objectMatrix) {
  36829. if (scope.screenSpacePanning === true) {
  36830. v.setFromMatrixColumn(objectMatrix, 1);
  36831. } else {
  36832. v.setFromMatrixColumn(objectMatrix, 0);
  36833. v.crossVectors(scope.object.up, v);
  36834. }
  36835. v.multiplyScalar(distance);
  36836. panOffset.add(v);
  36837. };
  36838. }(); // deltaX and deltaY are in pixels; right and down are positive
  36839. var pan = function () {
  36840. var offset = new _threeModule.Vector3();
  36841. return function pan(deltaX, deltaY) {
  36842. var element = scope.domElement;
  36843. if (scope.object.isPerspectiveCamera) {
  36844. // perspective
  36845. var position = scope.object.position;
  36846. offset.copy(position).sub(scope.target);
  36847. var targetDistance = offset.length(); // half of the fov is center to top of screen
  36848. targetDistance *= Math.tan(scope.object.fov / 2 * Math.PI / 180.0); // we use only clientHeight here so aspect ratio does not distort speed
  36849. panLeft(2 * deltaX * targetDistance / element.clientHeight, scope.object.matrix);
  36850. panUp(2 * deltaY * targetDistance / element.clientHeight, scope.object.matrix);
  36851. } else if (scope.object.isOrthographicCamera) {
  36852. // orthographic
  36853. panLeft(deltaX * (scope.object.right - scope.object.left) / scope.object.zoom / element.clientWidth, scope.object.matrix);
  36854. panUp(deltaY * (scope.object.top - scope.object.bottom) / scope.object.zoom / element.clientHeight, scope.object.matrix);
  36855. } else {
  36856. // camera neither orthographic nor perspective
  36857. console.warn('WARNING: OrbitControls.js encountered an unknown camera type - pan disabled.');
  36858. scope.enablePan = false;
  36859. }
  36860. };
  36861. }();
  36862. function dollyOut(dollyScale) {
  36863. if (scope.object.isPerspectiveCamera) {
  36864. scale /= dollyScale;
  36865. } else if (scope.object.isOrthographicCamera) {
  36866. scope.object.zoom = Math.max(scope.minZoom, Math.min(scope.maxZoom, scope.object.zoom * dollyScale));
  36867. scope.object.updateProjectionMatrix();
  36868. zoomChanged = true;
  36869. } else {
  36870. console.warn('WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled.');
  36871. scope.enableZoom = false;
  36872. }
  36873. }
  36874. function dollyIn(dollyScale) {
  36875. if (scope.object.isPerspectiveCamera) {
  36876. scale *= dollyScale;
  36877. } else if (scope.object.isOrthographicCamera) {
  36878. scope.object.zoom = Math.max(scope.minZoom, Math.min(scope.maxZoom, scope.object.zoom / dollyScale));
  36879. scope.object.updateProjectionMatrix();
  36880. zoomChanged = true;
  36881. } else {
  36882. console.warn('WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled.');
  36883. scope.enableZoom = false;
  36884. }
  36885. } //
  36886. // event callbacks - update the object state
  36887. //
  36888. function handleMouseDownRotate(event) {
  36889. rotateStart.set(event.clientX, event.clientY);
  36890. }
  36891. function handleMouseDownDolly(event) {
  36892. dollyStart.set(event.clientX, event.clientY);
  36893. }
  36894. function handleMouseDownPan(event) {
  36895. panStart.set(event.clientX, event.clientY);
  36896. }
  36897. function handleMouseMoveRotate(event) {
  36898. rotateEnd.set(event.clientX, event.clientY);
  36899. rotateDelta.subVectors(rotateEnd, rotateStart).multiplyScalar(scope.rotateSpeed);
  36900. var element = scope.domElement;
  36901. rotateLeft(2 * Math.PI * rotateDelta.x / element.clientHeight); // yes, height
  36902. rotateUp(2 * Math.PI * rotateDelta.y / element.clientHeight);
  36903. rotateStart.copy(rotateEnd);
  36904. scope.update();
  36905. }
  36906. function handleMouseMoveDolly(event) {
  36907. dollyEnd.set(event.clientX, event.clientY);
  36908. dollyDelta.subVectors(dollyEnd, dollyStart);
  36909. if (dollyDelta.y > 0) {
  36910. dollyOut(getZoomScale());
  36911. } else if (dollyDelta.y < 0) {
  36912. dollyIn(getZoomScale());
  36913. }
  36914. dollyStart.copy(dollyEnd);
  36915. scope.update();
  36916. }
  36917. function handleMouseMovePan(event) {
  36918. panEnd.set(event.clientX, event.clientY);
  36919. panDelta.subVectors(panEnd, panStart).multiplyScalar(scope.panSpeed);
  36920. pan(panDelta.x, panDelta.y);
  36921. panStart.copy(panEnd);
  36922. scope.update();
  36923. }
  36924. function handleMouseUp()
  36925. /*event*/
  36926. {// no-op
  36927. }
  36928. function handleMouseWheel(event) {
  36929. if (event.deltaY < 0) {
  36930. dollyIn(getZoomScale());
  36931. } else if (event.deltaY > 0) {
  36932. dollyOut(getZoomScale());
  36933. }
  36934. scope.update();
  36935. }
  36936. function handleKeyDown(event) {
  36937. var needsUpdate = false;
  36938. switch (event.keyCode) {
  36939. case scope.keys.UP:
  36940. pan(0, scope.keyPanSpeed);
  36941. needsUpdate = true;
  36942. break;
  36943. case scope.keys.BOTTOM:
  36944. pan(0, -scope.keyPanSpeed);
  36945. needsUpdate = true;
  36946. break;
  36947. case scope.keys.LEFT:
  36948. pan(scope.keyPanSpeed, 0);
  36949. needsUpdate = true;
  36950. break;
  36951. case scope.keys.RIGHT:
  36952. pan(-scope.keyPanSpeed, 0);
  36953. needsUpdate = true;
  36954. break;
  36955. }
  36956. if (needsUpdate) {
  36957. // prevent the browser from scrolling on cursor keys
  36958. event.preventDefault();
  36959. scope.update();
  36960. }
  36961. }
  36962. function handleTouchStartRotate(event) {
  36963. if (event.touches.length == 1) {
  36964. rotateStart.set(event.touches[0].pageX, event.touches[0].pageY);
  36965. } else {
  36966. var x = 0.5 * (event.touches[0].pageX + event.touches[1].pageX);
  36967. var y = 0.5 * (event.touches[0].pageY + event.touches[1].pageY);
  36968. rotateStart.set(x, y);
  36969. }
  36970. }
  36971. function handleTouchStartPan(event) {
  36972. if (event.touches.length == 1) {
  36973. panStart.set(event.touches[0].pageX, event.touches[0].pageY);
  36974. } else {
  36975. var x = 0.5 * (event.touches[0].pageX + event.touches[1].pageX);
  36976. var y = 0.5 * (event.touches[0].pageY + event.touches[1].pageY);
  36977. panStart.set(x, y);
  36978. }
  36979. }
  36980. function handleTouchStartDolly(event) {
  36981. var dx = event.touches[0].pageX - event.touches[1].pageX;
  36982. var dy = event.touches[0].pageY - event.touches[1].pageY;
  36983. var distance = Math.sqrt(dx * dx + dy * dy);
  36984. dollyStart.set(0, distance);
  36985. }
  36986. function handleTouchStartDollyPan(event) {
  36987. if (scope.enableZoom) handleTouchStartDolly(event);
  36988. if (scope.enablePan) handleTouchStartPan(event);
  36989. }
  36990. function handleTouchStartDollyRotate(event) {
  36991. if (scope.enableZoom) handleTouchStartDolly(event);
  36992. if (scope.enableRotate) handleTouchStartRotate(event);
  36993. }
  36994. function handleTouchMoveRotate(event) {
  36995. if (event.touches.length == 1) {
  36996. rotateEnd.set(event.touches[0].pageX, event.touches[0].pageY);
  36997. } else {
  36998. var x = 0.5 * (event.touches[0].pageX + event.touches[1].pageX);
  36999. var y = 0.5 * (event.touches[0].pageY + event.touches[1].pageY);
  37000. rotateEnd.set(x, y);
  37001. }
  37002. rotateDelta.subVectors(rotateEnd, rotateStart).multiplyScalar(scope.rotateSpeed);
  37003. var element = scope.domElement;
  37004. rotateLeft(2 * Math.PI * rotateDelta.x / element.clientHeight); // yes, height
  37005. rotateUp(2 * Math.PI * rotateDelta.y / element.clientHeight);
  37006. rotateStart.copy(rotateEnd);
  37007. }
  37008. function handleTouchMovePan(event) {
  37009. if (event.touches.length == 1) {
  37010. panEnd.set(event.touches[0].pageX, event.touches[0].pageY);
  37011. } else {
  37012. var x = 0.5 * (event.touches[0].pageX + event.touches[1].pageX);
  37013. var y = 0.5 * (event.touches[0].pageY + event.touches[1].pageY);
  37014. panEnd.set(x, y);
  37015. }
  37016. panDelta.subVectors(panEnd, panStart).multiplyScalar(scope.panSpeed);
  37017. pan(panDelta.x, panDelta.y);
  37018. panStart.copy(panEnd);
  37019. }
  37020. function handleTouchMoveDolly(event) {
  37021. var dx = event.touches[0].pageX - event.touches[1].pageX;
  37022. var dy = event.touches[0].pageY - event.touches[1].pageY;
  37023. var distance = Math.sqrt(dx * dx + dy * dy);
  37024. dollyEnd.set(0, distance);
  37025. dollyDelta.set(0, Math.pow(dollyEnd.y / dollyStart.y, scope.zoomSpeed));
  37026. dollyOut(dollyDelta.y);
  37027. dollyStart.copy(dollyEnd);
  37028. }
  37029. function handleTouchMoveDollyPan(event) {
  37030. if (scope.enableZoom) handleTouchMoveDolly(event);
  37031. if (scope.enablePan) handleTouchMovePan(event);
  37032. }
  37033. function handleTouchMoveDollyRotate(event) {
  37034. if (scope.enableZoom) handleTouchMoveDolly(event);
  37035. if (scope.enableRotate) handleTouchMoveRotate(event);
  37036. }
  37037. function handleTouchEnd()
  37038. /*event*/
  37039. {} // no-op
  37040. //
  37041. // event handlers - FSM: listen for events and reset state
  37042. //
  37043. function onPointerDown(event) {
  37044. if (scope.enabled === false) return;
  37045. switch (event.pointerType) {
  37046. case 'mouse':
  37047. case 'pen':
  37048. onMouseDown(event);
  37049. break;
  37050. // TODO touch
  37051. }
  37052. }
  37053. function onPointerMove(event) {
  37054. if (scope.enabled === false) return;
  37055. switch (event.pointerType) {
  37056. case 'mouse':
  37057. case 'pen':
  37058. onMouseMove(event);
  37059. break;
  37060. // TODO touch
  37061. }
  37062. }
  37063. function onPointerUp(event) {
  37064. switch (event.pointerType) {
  37065. case 'mouse':
  37066. case 'pen':
  37067. onMouseUp(event);
  37068. break;
  37069. // TODO touch
  37070. }
  37071. }
  37072. function onMouseDown(event) {
  37073. // Prevent the browser from scrolling.
  37074. event.preventDefault(); // Manually set the focus since calling preventDefault above
  37075. // prevents the browser from setting it automatically.
  37076. scope.domElement.focus ? scope.domElement.focus() : window.focus();
  37077. var mouseAction;
  37078. switch (event.button) {
  37079. case 0:
  37080. mouseAction = scope.mouseButtons.LEFT;
  37081. break;
  37082. case 1:
  37083. mouseAction = scope.mouseButtons.MIDDLE;
  37084. break;
  37085. case 2:
  37086. mouseAction = scope.mouseButtons.RIGHT;
  37087. break;
  37088. default:
  37089. mouseAction = -1;
  37090. }
  37091. switch (mouseAction) {
  37092. case _threeModule.MOUSE.DOLLY:
  37093. if (scope.enableZoom === false) return;
  37094. handleMouseDownDolly(event);
  37095. state = STATE.DOLLY;
  37096. break;
  37097. case _threeModule.MOUSE.ROTATE:
  37098. if (event.ctrlKey || event.metaKey || event.shiftKey) {
  37099. if (scope.enablePan === false) return;
  37100. handleMouseDownPan(event);
  37101. state = STATE.PAN;
  37102. } else {
  37103. if (scope.enableRotate === false) return;
  37104. handleMouseDownRotate(event);
  37105. state = STATE.ROTATE;
  37106. }
  37107. break;
  37108. case _threeModule.MOUSE.PAN:
  37109. if (event.ctrlKey || event.metaKey || event.shiftKey) {
  37110. if (scope.enableRotate === false) return;
  37111. handleMouseDownRotate(event);
  37112. state = STATE.ROTATE;
  37113. } else {
  37114. if (scope.enablePan === false) return;
  37115. handleMouseDownPan(event);
  37116. state = STATE.PAN;
  37117. }
  37118. break;
  37119. default:
  37120. state = STATE.NONE;
  37121. }
  37122. if (state !== STATE.NONE) {
  37123. scope.domElement.ownerDocument.addEventListener('pointermove', onPointerMove, false);
  37124. scope.domElement.ownerDocument.addEventListener('pointerup', onPointerUp, false);
  37125. scope.dispatchEvent(startEvent);
  37126. }
  37127. }
  37128. function onMouseMove(event) {
  37129. if (scope.enabled === false) return;
  37130. event.preventDefault();
  37131. switch (state) {
  37132. case STATE.ROTATE:
  37133. if (scope.enableRotate === false) return;
  37134. handleMouseMoveRotate(event);
  37135. break;
  37136. case STATE.DOLLY:
  37137. if (scope.enableZoom === false) return;
  37138. handleMouseMoveDolly(event);
  37139. break;
  37140. case STATE.PAN:
  37141. if (scope.enablePan === false) return;
  37142. handleMouseMovePan(event);
  37143. break;
  37144. }
  37145. }
  37146. function onMouseUp(event) {
  37147. scope.domElement.ownerDocument.removeEventListener('pointermove', onPointerMove, false);
  37148. scope.domElement.ownerDocument.removeEventListener('pointerup', onPointerUp, false);
  37149. if (scope.enabled === false) return;
  37150. handleMouseUp(event);
  37151. scope.dispatchEvent(endEvent);
  37152. state = STATE.NONE;
  37153. }
  37154. function onMouseWheel(event) {
  37155. if (scope.enabled === false || scope.enableZoom === false || state !== STATE.NONE && state !== STATE.ROTATE) return;
  37156. event.preventDefault();
  37157. event.stopPropagation();
  37158. scope.dispatchEvent(startEvent);
  37159. handleMouseWheel(event);
  37160. scope.dispatchEvent(endEvent);
  37161. }
  37162. function onKeyDown(event) {
  37163. if (scope.enabled === false || scope.enableKeys === false || scope.enablePan === false) return;
  37164. handleKeyDown(event);
  37165. }
  37166. function onTouchStart(event) {
  37167. if (scope.enabled === false) return;
  37168. event.preventDefault(); // prevent scrolling
  37169. switch (event.touches.length) {
  37170. case 1:
  37171. switch (scope.touches.ONE) {
  37172. case _threeModule.TOUCH.ROTATE:
  37173. if (scope.enableRotate === false) return;
  37174. handleTouchStartRotate(event);
  37175. state = STATE.TOUCH_ROTATE;
  37176. break;
  37177. case _threeModule.TOUCH.PAN:
  37178. if (scope.enablePan === false) return;
  37179. handleTouchStartPan(event);
  37180. state = STATE.TOUCH_PAN;
  37181. break;
  37182. default:
  37183. state = STATE.NONE;
  37184. }
  37185. break;
  37186. case 2:
  37187. switch (scope.touches.TWO) {
  37188. case _threeModule.TOUCH.DOLLY_PAN:
  37189. if (scope.enableZoom === false && scope.enablePan === false) return;
  37190. handleTouchStartDollyPan(event);
  37191. state = STATE.TOUCH_DOLLY_PAN;
  37192. break;
  37193. case _threeModule.TOUCH.DOLLY_ROTATE:
  37194. if (scope.enableZoom === false && scope.enableRotate === false) return;
  37195. handleTouchStartDollyRotate(event);
  37196. state = STATE.TOUCH_DOLLY_ROTATE;
  37197. break;
  37198. default:
  37199. state = STATE.NONE;
  37200. }
  37201. break;
  37202. default:
  37203. state = STATE.NONE;
  37204. }
  37205. if (state !== STATE.NONE) {
  37206. scope.dispatchEvent(startEvent);
  37207. }
  37208. }
  37209. function onTouchMove(event) {
  37210. if (scope.enabled === false) return;
  37211. event.preventDefault(); // prevent scrolling
  37212. event.stopPropagation();
  37213. switch (state) {
  37214. case STATE.TOUCH_ROTATE:
  37215. if (scope.enableRotate === false) return;
  37216. handleTouchMoveRotate(event);
  37217. scope.update();
  37218. break;
  37219. case STATE.TOUCH_PAN:
  37220. if (scope.enablePan === false) return;
  37221. handleTouchMovePan(event);
  37222. scope.update();
  37223. break;
  37224. case STATE.TOUCH_DOLLY_PAN:
  37225. if (scope.enableZoom === false && scope.enablePan === false) return;
  37226. handleTouchMoveDollyPan(event);
  37227. scope.update();
  37228. break;
  37229. case STATE.TOUCH_DOLLY_ROTATE:
  37230. if (scope.enableZoom === false && scope.enableRotate === false) return;
  37231. handleTouchMoveDollyRotate(event);
  37232. scope.update();
  37233. break;
  37234. default:
  37235. state = STATE.NONE;
  37236. }
  37237. }
  37238. function onTouchEnd(event) {
  37239. if (scope.enabled === false) return;
  37240. handleTouchEnd(event);
  37241. scope.dispatchEvent(endEvent);
  37242. state = STATE.NONE;
  37243. }
  37244. function onContextMenu(event) {
  37245. if (scope.enabled === false) return;
  37246. event.preventDefault();
  37247. } //
  37248. scope.domElement.addEventListener('contextmenu', onContextMenu, false);
  37249. scope.domElement.addEventListener('pointerdown', onPointerDown, false);
  37250. scope.domElement.addEventListener('wheel', onMouseWheel, false);
  37251. scope.domElement.addEventListener('touchstart', onTouchStart, false);
  37252. scope.domElement.addEventListener('touchend', onTouchEnd, false);
  37253. scope.domElement.addEventListener('touchmove', onTouchMove, false);
  37254. scope.domElement.addEventListener('keydown', onKeyDown, false); // force an update at start
  37255. this.update();
  37256. };
  37257. exports.OrbitControls = OrbitControls;
  37258. OrbitControls.prototype = Object.create(_threeModule.EventDispatcher.prototype);
  37259. OrbitControls.prototype.constructor = OrbitControls; // This set of controls performs orbiting, dollying (zooming), and panning.
  37260. // Unlike TrackballControls, it maintains the "up" direction object.up (+Y by default).
  37261. // This is very similar to OrbitControls, another set of touch behavior
  37262. //
  37263. // Orbit - right mouse, or left mouse + ctrl/meta/shiftKey / touch: two-finger rotate
  37264. // Zoom - middle mouse, or mousewheel / touch: two-finger spread or squish
  37265. // Pan - left mouse, or arrow keys / touch: one-finger move
  37266. var MapControls = function (object, domElement) {
  37267. OrbitControls.call(this, object, domElement);
  37268. this.screenSpacePanning = false; // pan orthogonal to world-space direction camera.up
  37269. this.mouseButtons.LEFT = _threeModule.MOUSE.PAN;
  37270. this.mouseButtons.RIGHT = _threeModule.MOUSE.ROTATE;
  37271. this.touches.ONE = _threeModule.TOUCH.PAN;
  37272. this.touches.TWO = _threeModule.TOUCH.DOLLY_ROTATE;
  37273. };
  37274. exports.MapControls = MapControls;
  37275. MapControls.prototype = Object.create(_threeModule.EventDispatcher.prototype);
  37276. MapControls.prototype.constructor = MapControls;
  37277. },{"../../../build/three.module.js":"../node_modules/three/build/three.module.js"}],"../node_modules/three/examples/jsm/utils/BufferGeometryUtils.js":[function(require,module,exports) {
  37278. "use strict";
  37279. Object.defineProperty(exports, "__esModule", {
  37280. value: true
  37281. });
  37282. exports.BufferGeometryUtils = void 0;
  37283. var _threeModule = require("../../../build/three.module.js");
  37284. var BufferGeometryUtils = {
  37285. computeTangents: function (geometry) {
  37286. var index = geometry.index;
  37287. var attributes = geometry.attributes; // based on http://www.terathon.com/code/tangent.html
  37288. // (per vertex tangents)
  37289. if (index === null || attributes.position === undefined || attributes.normal === undefined || attributes.uv === undefined) {
  37290. console.error('THREE.BufferGeometryUtils: .computeTangents() failed. Missing required attributes (index, position, normal or uv)');
  37291. return;
  37292. }
  37293. var indices = index.array;
  37294. var positions = attributes.position.array;
  37295. var normals = attributes.normal.array;
  37296. var uvs = attributes.uv.array;
  37297. var nVertices = positions.length / 3;
  37298. if (attributes.tangent === undefined) {
  37299. geometry.setAttribute('tangent', new _threeModule.BufferAttribute(new Float32Array(4 * nVertices), 4));
  37300. }
  37301. var tangents = attributes.tangent.array;
  37302. var tan1 = [],
  37303. tan2 = [];
  37304. for (var i = 0; i < nVertices; i++) {
  37305. tan1[i] = new _threeModule.Vector3();
  37306. tan2[i] = new _threeModule.Vector3();
  37307. }
  37308. var vA = new _threeModule.Vector3(),
  37309. vB = new _threeModule.Vector3(),
  37310. vC = new _threeModule.Vector3(),
  37311. uvA = new _threeModule.Vector2(),
  37312. uvB = new _threeModule.Vector2(),
  37313. uvC = new _threeModule.Vector2(),
  37314. sdir = new _threeModule.Vector3(),
  37315. tdir = new _threeModule.Vector3();
  37316. function handleTriangle(a, b, c) {
  37317. vA.fromArray(positions, a * 3);
  37318. vB.fromArray(positions, b * 3);
  37319. vC.fromArray(positions, c * 3);
  37320. uvA.fromArray(uvs, a * 2);
  37321. uvB.fromArray(uvs, b * 2);
  37322. uvC.fromArray(uvs, c * 2);
  37323. vB.sub(vA);
  37324. vC.sub(vA);
  37325. uvB.sub(uvA);
  37326. uvC.sub(uvA);
  37327. var r = 1.0 / (uvB.x * uvC.y - uvC.x * uvB.y); // silently ignore degenerate uv triangles having coincident or colinear vertices
  37328. if (!isFinite(r)) return;
  37329. sdir.copy(vB).multiplyScalar(uvC.y).addScaledVector(vC, -uvB.y).multiplyScalar(r);
  37330. tdir.copy(vC).multiplyScalar(uvB.x).addScaledVector(vB, -uvC.x).multiplyScalar(r);
  37331. tan1[a].add(sdir);
  37332. tan1[b].add(sdir);
  37333. tan1[c].add(sdir);
  37334. tan2[a].add(tdir);
  37335. tan2[b].add(tdir);
  37336. tan2[c].add(tdir);
  37337. }
  37338. var groups = geometry.groups;
  37339. if (groups.length === 0) {
  37340. groups = [{
  37341. start: 0,
  37342. count: indices.length
  37343. }];
  37344. }
  37345. for (var i = 0, il = groups.length; i < il; ++i) {
  37346. var group = groups[i];
  37347. var start = group.start;
  37348. var count = group.count;
  37349. for (var j = start, jl = start + count; j < jl; j += 3) {
  37350. handleTriangle(indices[j + 0], indices[j + 1], indices[j + 2]);
  37351. }
  37352. }
  37353. var tmp = new _threeModule.Vector3(),
  37354. tmp2 = new _threeModule.Vector3();
  37355. var n = new _threeModule.Vector3(),
  37356. n2 = new _threeModule.Vector3();
  37357. var w, t, test;
  37358. function handleVertex(v) {
  37359. n.fromArray(normals, v * 3);
  37360. n2.copy(n);
  37361. t = tan1[v]; // Gram-Schmidt orthogonalize
  37362. tmp.copy(t);
  37363. tmp.sub(n.multiplyScalar(n.dot(t))).normalize(); // Calculate handedness
  37364. tmp2.crossVectors(n2, t);
  37365. test = tmp2.dot(tan2[v]);
  37366. w = test < 0.0 ? -1.0 : 1.0;
  37367. tangents[v * 4] = tmp.x;
  37368. tangents[v * 4 + 1] = tmp.y;
  37369. tangents[v * 4 + 2] = tmp.z;
  37370. tangents[v * 4 + 3] = w;
  37371. }
  37372. for (var i = 0, il = groups.length; i < il; ++i) {
  37373. var group = groups[i];
  37374. var start = group.start;
  37375. var count = group.count;
  37376. for (var j = start, jl = start + count; j < jl; j += 3) {
  37377. handleVertex(indices[j + 0]);
  37378. handleVertex(indices[j + 1]);
  37379. handleVertex(indices[j + 2]);
  37380. }
  37381. }
  37382. },
  37383. /**
  37384. * @param {Array<BufferGeometry>} geometries
  37385. * @param {Boolean} useGroups
  37386. * @return {BufferGeometry}
  37387. */
  37388. mergeBufferGeometries: function (geometries, useGroups) {
  37389. var isIndexed = geometries[0].index !== null;
  37390. var attributesUsed = new Set(Object.keys(geometries[0].attributes));
  37391. var morphAttributesUsed = new Set(Object.keys(geometries[0].morphAttributes));
  37392. var attributes = {};
  37393. var morphAttributes = {};
  37394. var morphTargetsRelative = geometries[0].morphTargetsRelative;
  37395. var mergedGeometry = new _threeModule.BufferGeometry();
  37396. var offset = 0;
  37397. for (var i = 0; i < geometries.length; ++i) {
  37398. var geometry = geometries[i];
  37399. var attributesCount = 0; // ensure that all geometries are indexed, or none
  37400. if (isIndexed !== (geometry.index !== null)) {
  37401. console.error('THREE.BufferGeometryUtils: .mergeBufferGeometries() failed with geometry at index ' + i + '. All geometries must have compatible attributes; make sure index attribute exists among all geometries, or in none of them.');
  37402. return null;
  37403. } // gather attributes, exit early if they're different
  37404. for (var name in geometry.attributes) {
  37405. if (!attributesUsed.has(name)) {
  37406. console.error('THREE.BufferGeometryUtils: .mergeBufferGeometries() failed with geometry at index ' + i + '. All geometries must have compatible attributes; make sure "' + name + '" attribute exists among all geometries, or in none of them.');
  37407. return null;
  37408. }
  37409. if (attributes[name] === undefined) attributes[name] = [];
  37410. attributes[name].push(geometry.attributes[name]);
  37411. attributesCount++;
  37412. } // ensure geometries have the same number of attributes
  37413. if (attributesCount !== attributesUsed.size) {
  37414. console.error('THREE.BufferGeometryUtils: .mergeBufferGeometries() failed with geometry at index ' + i + '. Make sure all geometries have the same number of attributes.');
  37415. return null;
  37416. } // gather morph attributes, exit early if they're different
  37417. if (morphTargetsRelative !== geometry.morphTargetsRelative) {
  37418. console.error('THREE.BufferGeometryUtils: .mergeBufferGeometries() failed with geometry at index ' + i + '. .morphTargetsRelative must be consistent throughout all geometries.');
  37419. return null;
  37420. }
  37421. for (var name in geometry.morphAttributes) {
  37422. if (!morphAttributesUsed.has(name)) {
  37423. console.error('THREE.BufferGeometryUtils: .mergeBufferGeometries() failed with geometry at index ' + i + '. .morphAttributes must be consistent throughout all geometries.');
  37424. return null;
  37425. }
  37426. if (morphAttributes[name] === undefined) morphAttributes[name] = [];
  37427. morphAttributes[name].push(geometry.morphAttributes[name]);
  37428. } // gather .userData
  37429. mergedGeometry.userData.mergedUserData = mergedGeometry.userData.mergedUserData || [];
  37430. mergedGeometry.userData.mergedUserData.push(geometry.userData);
  37431. if (useGroups) {
  37432. var count;
  37433. if (isIndexed) {
  37434. count = geometry.index.count;
  37435. } else if (geometry.attributes.position !== undefined) {
  37436. count = geometry.attributes.position.count;
  37437. } else {
  37438. console.error('THREE.BufferGeometryUtils: .mergeBufferGeometries() failed with geometry at index ' + i + '. The geometry must have either an index or a position attribute');
  37439. return null;
  37440. }
  37441. mergedGeometry.addGroup(offset, count, i);
  37442. offset += count;
  37443. }
  37444. } // merge indices
  37445. if (isIndexed) {
  37446. var indexOffset = 0;
  37447. var mergedIndex = [];
  37448. for (var i = 0; i < geometries.length; ++i) {
  37449. var index = geometries[i].index;
  37450. for (var j = 0; j < index.count; ++j) {
  37451. mergedIndex.push(index.getX(j) + indexOffset);
  37452. }
  37453. indexOffset += geometries[i].attributes.position.count;
  37454. }
  37455. mergedGeometry.setIndex(mergedIndex);
  37456. } // merge attributes
  37457. for (var name in attributes) {
  37458. var mergedAttribute = this.mergeBufferAttributes(attributes[name]);
  37459. if (!mergedAttribute) {
  37460. console.error('THREE.BufferGeometryUtils: .mergeBufferGeometries() failed while trying to merge the ' + name + ' attribute.');
  37461. return null;
  37462. }
  37463. mergedGeometry.setAttribute(name, mergedAttribute);
  37464. } // merge morph attributes
  37465. for (var name in morphAttributes) {
  37466. var numMorphTargets = morphAttributes[name][0].length;
  37467. if (numMorphTargets === 0) break;
  37468. mergedGeometry.morphAttributes = mergedGeometry.morphAttributes || {};
  37469. mergedGeometry.morphAttributes[name] = [];
  37470. for (var i = 0; i < numMorphTargets; ++i) {
  37471. var morphAttributesToMerge = [];
  37472. for (var j = 0; j < morphAttributes[name].length; ++j) {
  37473. morphAttributesToMerge.push(morphAttributes[name][j][i]);
  37474. }
  37475. var mergedMorphAttribute = this.mergeBufferAttributes(morphAttributesToMerge);
  37476. if (!mergedMorphAttribute) {
  37477. console.error('THREE.BufferGeometryUtils: .mergeBufferGeometries() failed while trying to merge the ' + name + ' morphAttribute.');
  37478. return null;
  37479. }
  37480. mergedGeometry.morphAttributes[name].push(mergedMorphAttribute);
  37481. }
  37482. }
  37483. return mergedGeometry;
  37484. },
  37485. /**
  37486. * @param {Array<BufferAttribute>} attributes
  37487. * @return {BufferAttribute}
  37488. */
  37489. mergeBufferAttributes: function (attributes) {
  37490. var TypedArray;
  37491. var itemSize;
  37492. var normalized;
  37493. var arrayLength = 0;
  37494. for (var i = 0; i < attributes.length; ++i) {
  37495. var attribute = attributes[i];
  37496. if (attribute.isInterleavedBufferAttribute) {
  37497. console.error('THREE.BufferGeometryUtils: .mergeBufferAttributes() failed. InterleavedBufferAttributes are not supported.');
  37498. return null;
  37499. }
  37500. if (TypedArray === undefined) TypedArray = attribute.array.constructor;
  37501. if (TypedArray !== attribute.array.constructor) {
  37502. console.error('THREE.BufferGeometryUtils: .mergeBufferAttributes() failed. BufferAttribute.array must be of consistent array types across matching attributes.');
  37503. return null;
  37504. }
  37505. if (itemSize === undefined) itemSize = attribute.itemSize;
  37506. if (itemSize !== attribute.itemSize) {
  37507. console.error('THREE.BufferGeometryUtils: .mergeBufferAttributes() failed. BufferAttribute.itemSize must be consistent across matching attributes.');
  37508. return null;
  37509. }
  37510. if (normalized === undefined) normalized = attribute.normalized;
  37511. if (normalized !== attribute.normalized) {
  37512. console.error('THREE.BufferGeometryUtils: .mergeBufferAttributes() failed. BufferAttribute.normalized must be consistent across matching attributes.');
  37513. return null;
  37514. }
  37515. arrayLength += attribute.array.length;
  37516. }
  37517. var array = new TypedArray(arrayLength);
  37518. var offset = 0;
  37519. for (var i = 0; i < attributes.length; ++i) {
  37520. array.set(attributes[i].array, offset);
  37521. offset += attributes[i].array.length;
  37522. }
  37523. return new _threeModule.BufferAttribute(array, itemSize, normalized);
  37524. },
  37525. /**
  37526. * @param {Array<BufferAttribute>} attributes
  37527. * @return {Array<InterleavedBufferAttribute>}
  37528. */
  37529. interleaveAttributes: function (attributes) {
  37530. // Interleaves the provided attributes into an InterleavedBuffer and returns
  37531. // a set of InterleavedBufferAttributes for each attribute
  37532. var TypedArray;
  37533. var arrayLength = 0;
  37534. var stride = 0; // calculate the the length and type of the interleavedBuffer
  37535. for (var i = 0, l = attributes.length; i < l; ++i) {
  37536. var attribute = attributes[i];
  37537. if (TypedArray === undefined) TypedArray = attribute.array.constructor;
  37538. if (TypedArray !== attribute.array.constructor) {
  37539. console.error('AttributeBuffers of different types cannot be interleaved');
  37540. return null;
  37541. }
  37542. arrayLength += attribute.array.length;
  37543. stride += attribute.itemSize;
  37544. } // Create the set of buffer attributes
  37545. var interleavedBuffer = new _threeModule.InterleavedBuffer(new TypedArray(arrayLength), stride);
  37546. var offset = 0;
  37547. var res = [];
  37548. var getters = ['getX', 'getY', 'getZ', 'getW'];
  37549. var setters = ['setX', 'setY', 'setZ', 'setW'];
  37550. for (var j = 0, l = attributes.length; j < l; j++) {
  37551. var attribute = attributes[j];
  37552. var itemSize = attribute.itemSize;
  37553. var count = attribute.count;
  37554. var iba = new _threeModule.InterleavedBufferAttribute(interleavedBuffer, itemSize, offset, attribute.normalized);
  37555. res.push(iba);
  37556. offset += itemSize; // Move the data for each attribute into the new interleavedBuffer
  37557. // at the appropriate offset
  37558. for (var c = 0; c < count; c++) {
  37559. for (var k = 0; k < itemSize; k++) {
  37560. iba[setters[k]](c, attribute[getters[k]](c));
  37561. }
  37562. }
  37563. }
  37564. return res;
  37565. },
  37566. /**
  37567. * @param {Array<BufferGeometry>} geometry
  37568. * @return {number}
  37569. */
  37570. estimateBytesUsed: function (geometry) {
  37571. // Return the estimated memory used by this geometry in bytes
  37572. // Calculate using itemSize, count, and BYTES_PER_ELEMENT to account
  37573. // for InterleavedBufferAttributes.
  37574. var mem = 0;
  37575. for (var name in geometry.attributes) {
  37576. var attr = geometry.getAttribute(name);
  37577. mem += attr.count * attr.itemSize * attr.array.BYTES_PER_ELEMENT;
  37578. }
  37579. var indices = geometry.getIndex();
  37580. mem += indices ? indices.count * indices.itemSize * indices.array.BYTES_PER_ELEMENT : 0;
  37581. return mem;
  37582. },
  37583. /**
  37584. * @param {BufferGeometry} geometry
  37585. * @param {number} tolerance
  37586. * @return {BufferGeometry>}
  37587. */
  37588. mergeVertices: function (geometry, tolerance = 1e-4) {
  37589. tolerance = Math.max(tolerance, Number.EPSILON); // Generate an index buffer if the geometry doesn't have one, or optimize it
  37590. // if it's already available.
  37591. var hashToIndex = {};
  37592. var indices = geometry.getIndex();
  37593. var positions = geometry.getAttribute('position');
  37594. var vertexCount = indices ? indices.count : positions.count; // next value for triangle indices
  37595. var nextIndex = 0; // attributes and new attribute arrays
  37596. var attributeNames = Object.keys(geometry.attributes);
  37597. var attrArrays = {};
  37598. var morphAttrsArrays = {};
  37599. var newIndices = [];
  37600. var getters = ['getX', 'getY', 'getZ', 'getW']; // initialize the arrays
  37601. for (var i = 0, l = attributeNames.length; i < l; i++) {
  37602. var name = attributeNames[i];
  37603. attrArrays[name] = [];
  37604. var morphAttr = geometry.morphAttributes[name];
  37605. if (morphAttr) {
  37606. morphAttrsArrays[name] = new Array(morphAttr.length).fill().map(() => []);
  37607. }
  37608. } // convert the error tolerance to an amount of decimal places to truncate to
  37609. var decimalShift = Math.log10(1 / tolerance);
  37610. var shiftMultiplier = Math.pow(10, decimalShift);
  37611. for (var i = 0; i < vertexCount; i++) {
  37612. var index = indices ? indices.getX(i) : i; // Generate a hash for the vertex attributes at the current index 'i'
  37613. var hash = '';
  37614. for (var j = 0, l = attributeNames.length; j < l; j++) {
  37615. var name = attributeNames[j];
  37616. var attribute = geometry.getAttribute(name);
  37617. var itemSize = attribute.itemSize;
  37618. for (var k = 0; k < itemSize; k++) {
  37619. // double tilde truncates the decimal value
  37620. hash += `${~~(attribute[getters[k]](index) * shiftMultiplier)},`;
  37621. }
  37622. } // Add another reference to the vertex if it's already
  37623. // used by another index
  37624. if (hash in hashToIndex) {
  37625. newIndices.push(hashToIndex[hash]);
  37626. } else {
  37627. // copy data to the new index in the attribute arrays
  37628. for (var j = 0, l = attributeNames.length; j < l; j++) {
  37629. var name = attributeNames[j];
  37630. var attribute = geometry.getAttribute(name);
  37631. var morphAttr = geometry.morphAttributes[name];
  37632. var itemSize = attribute.itemSize;
  37633. var newarray = attrArrays[name];
  37634. var newMorphArrays = morphAttrsArrays[name];
  37635. for (var k = 0; k < itemSize; k++) {
  37636. var getterFunc = getters[k];
  37637. newarray.push(attribute[getterFunc](index));
  37638. if (morphAttr) {
  37639. for (var m = 0, ml = morphAttr.length; m < ml; m++) {
  37640. newMorphArrays[m].push(morphAttr[m][getterFunc](index));
  37641. }
  37642. }
  37643. }
  37644. }
  37645. hashToIndex[hash] = nextIndex;
  37646. newIndices.push(nextIndex);
  37647. nextIndex++;
  37648. }
  37649. } // Generate typed arrays from new attribute arrays and update
  37650. // the attributeBuffers
  37651. const result = geometry.clone();
  37652. for (var i = 0, l = attributeNames.length; i < l; i++) {
  37653. var name = attributeNames[i];
  37654. var oldAttribute = geometry.getAttribute(name);
  37655. var buffer = new oldAttribute.array.constructor(attrArrays[name]);
  37656. var attribute = new _threeModule.BufferAttribute(buffer, oldAttribute.itemSize, oldAttribute.normalized);
  37657. result.setAttribute(name, attribute); // Update the attribute arrays
  37658. if (name in morphAttrsArrays) {
  37659. for (var j = 0; j < morphAttrsArrays[name].length; j++) {
  37660. var oldMorphAttribute = geometry.morphAttributes[name][j];
  37661. var buffer = new oldMorphAttribute.array.constructor(morphAttrsArrays[name][j]);
  37662. var morphAttribute = new _threeModule.BufferAttribute(buffer, oldMorphAttribute.itemSize, oldMorphAttribute.normalized);
  37663. result.morphAttributes[name][j] = morphAttribute;
  37664. }
  37665. }
  37666. } // indices
  37667. result.setIndex(newIndices);
  37668. return result;
  37669. },
  37670. /**
  37671. * @param {BufferGeometry} geometry
  37672. * @param {number} drawMode
  37673. * @return {BufferGeometry>}
  37674. */
  37675. toTrianglesDrawMode: function (geometry, drawMode) {
  37676. if (drawMode === _threeModule.TrianglesDrawMode) {
  37677. console.warn('THREE.BufferGeometryUtils.toTrianglesDrawMode(): Geometry already defined as triangles.');
  37678. return geometry;
  37679. }
  37680. if (drawMode === _threeModule.TriangleFanDrawMode || drawMode === _threeModule.TriangleStripDrawMode) {
  37681. var index = geometry.getIndex(); // generate index if not present
  37682. if (index === null) {
  37683. var indices = [];
  37684. var position = geometry.getAttribute('position');
  37685. if (position !== undefined) {
  37686. for (var i = 0; i < position.count; i++) {
  37687. indices.push(i);
  37688. }
  37689. geometry.setIndex(indices);
  37690. index = geometry.getIndex();
  37691. } else {
  37692. console.error('THREE.BufferGeometryUtils.toTrianglesDrawMode(): Undefined position attribute. Processing not possible.');
  37693. return geometry;
  37694. }
  37695. } //
  37696. var numberOfTriangles = index.count - 2;
  37697. var newIndices = [];
  37698. if (drawMode === _threeModule.TriangleFanDrawMode) {
  37699. // gl.TRIANGLE_FAN
  37700. for (var i = 1; i <= numberOfTriangles; i++) {
  37701. newIndices.push(index.getX(0));
  37702. newIndices.push(index.getX(i));
  37703. newIndices.push(index.getX(i + 1));
  37704. }
  37705. } else {
  37706. // gl.TRIANGLE_STRIP
  37707. for (var i = 0; i < numberOfTriangles; i++) {
  37708. if (i % 2 === 0) {
  37709. newIndices.push(index.getX(i));
  37710. newIndices.push(index.getX(i + 1));
  37711. newIndices.push(index.getX(i + 2));
  37712. } else {
  37713. newIndices.push(index.getX(i + 2));
  37714. newIndices.push(index.getX(i + 1));
  37715. newIndices.push(index.getX(i));
  37716. }
  37717. }
  37718. }
  37719. if (newIndices.length / 3 !== numberOfTriangles) {
  37720. console.error('THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unable to generate correct amount of triangles.');
  37721. } // build final geometry
  37722. var newGeometry = geometry.clone();
  37723. newGeometry.setIndex(newIndices);
  37724. newGeometry.clearGroups();
  37725. return newGeometry;
  37726. } else {
  37727. console.error('THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unknown draw mode:', drawMode);
  37728. return geometry;
  37729. }
  37730. }
  37731. };
  37732. exports.BufferGeometryUtils = BufferGeometryUtils;
  37733. },{"../../../build/three.module.js":"../node_modules/three/build/three.module.js"}],"../node_modules/three/examples/jsm/loaders/DRACOLoader.js":[function(require,module,exports) {
  37734. "use strict";
  37735. Object.defineProperty(exports, "__esModule", {
  37736. value: true
  37737. });
  37738. exports.DRACOLoader = void 0;
  37739. var _threeModule = require("../../../build/three.module.js");
  37740. var DRACOLoader = function (manager) {
  37741. _threeModule.Loader.call(this, manager);
  37742. this.decoderPath = '';
  37743. this.decoderConfig = {};
  37744. this.decoderBinary = null;
  37745. this.decoderPending = null;
  37746. this.workerLimit = 4;
  37747. this.workerPool = [];
  37748. this.workerNextTaskID = 1;
  37749. this.workerSourceURL = '';
  37750. this.defaultAttributeIDs = {
  37751. position: 'POSITION',
  37752. normal: 'NORMAL',
  37753. color: 'COLOR',
  37754. uv: 'TEX_COORD'
  37755. };
  37756. this.defaultAttributeTypes = {
  37757. position: 'Float32Array',
  37758. normal: 'Float32Array',
  37759. color: 'Float32Array',
  37760. uv: 'Float32Array'
  37761. };
  37762. };
  37763. exports.DRACOLoader = DRACOLoader;
  37764. DRACOLoader.prototype = Object.assign(Object.create(_threeModule.Loader.prototype), {
  37765. constructor: DRACOLoader,
  37766. setDecoderPath: function (path) {
  37767. this.decoderPath = path;
  37768. return this;
  37769. },
  37770. setDecoderConfig: function (config) {
  37771. this.decoderConfig = config;
  37772. return this;
  37773. },
  37774. setWorkerLimit: function (workerLimit) {
  37775. this.workerLimit = workerLimit;
  37776. return this;
  37777. },
  37778. /** @deprecated */
  37779. setVerbosity: function () {
  37780. console.warn('THREE.DRACOLoader: The .setVerbosity() method has been removed.');
  37781. },
  37782. /** @deprecated */
  37783. setDrawMode: function () {
  37784. console.warn('THREE.DRACOLoader: The .setDrawMode() method has been removed.');
  37785. },
  37786. /** @deprecated */
  37787. setSkipDequantization: function () {
  37788. console.warn('THREE.DRACOLoader: The .setSkipDequantization() method has been removed.');
  37789. },
  37790. load: function (url, onLoad, onProgress, onError) {
  37791. var loader = new _threeModule.FileLoader(this.manager);
  37792. loader.setPath(this.path);
  37793. loader.setResponseType('arraybuffer');
  37794. loader.setRequestHeader(this.requestHeader);
  37795. loader.setWithCredentials(this.withCredentials);
  37796. loader.load(url, buffer => {
  37797. var taskConfig = {
  37798. attributeIDs: this.defaultAttributeIDs,
  37799. attributeTypes: this.defaultAttributeTypes,
  37800. useUniqueIDs: false
  37801. };
  37802. this.decodeGeometry(buffer, taskConfig).then(onLoad).catch(onError);
  37803. }, onProgress, onError);
  37804. },
  37805. /** @deprecated Kept for backward-compatibility with previous DRACOLoader versions. */
  37806. decodeDracoFile: function (buffer, callback, attributeIDs, attributeTypes) {
  37807. var taskConfig = {
  37808. attributeIDs: attributeIDs || this.defaultAttributeIDs,
  37809. attributeTypes: attributeTypes || this.defaultAttributeTypes,
  37810. useUniqueIDs: !!attributeIDs
  37811. };
  37812. this.decodeGeometry(buffer, taskConfig).then(callback);
  37813. },
  37814. decodeGeometry: function (buffer, taskConfig) {
  37815. // TODO: For backward-compatibility, support 'attributeTypes' objects containing
  37816. // references (rather than names) to typed array constructors. These must be
  37817. // serialized before sending them to the worker.
  37818. for (var attribute in taskConfig.attributeTypes) {
  37819. var type = taskConfig.attributeTypes[attribute];
  37820. if (type.BYTES_PER_ELEMENT !== undefined) {
  37821. taskConfig.attributeTypes[attribute] = type.name;
  37822. }
  37823. } //
  37824. var taskKey = JSON.stringify(taskConfig); // Check for an existing task using this buffer. A transferred buffer cannot be transferred
  37825. // again from this thread.
  37826. if (DRACOLoader.taskCache.has(buffer)) {
  37827. var cachedTask = DRACOLoader.taskCache.get(buffer);
  37828. if (cachedTask.key === taskKey) {
  37829. return cachedTask.promise;
  37830. } else if (buffer.byteLength === 0) {
  37831. // Technically, it would be possible to wait for the previous task to complete,
  37832. // transfer the buffer back, and decode again with the second configuration. That
  37833. // is complex, and I don't know of any reason to decode a Draco buffer twice in
  37834. // different ways, so this is left unimplemented.
  37835. throw new Error('THREE.DRACOLoader: Unable to re-decode a buffer with different ' + 'settings. Buffer has already been transferred.');
  37836. }
  37837. } //
  37838. var worker;
  37839. var taskID = this.workerNextTaskID++;
  37840. var taskCost = buffer.byteLength; // Obtain a worker and assign a task, and construct a geometry instance
  37841. // when the task completes.
  37842. var geometryPending = this._getWorker(taskID, taskCost).then(_worker => {
  37843. worker = _worker;
  37844. return new Promise((resolve, reject) => {
  37845. worker._callbacks[taskID] = {
  37846. resolve,
  37847. reject
  37848. };
  37849. worker.postMessage({
  37850. type: 'decode',
  37851. id: taskID,
  37852. taskConfig,
  37853. buffer
  37854. }, [buffer]); // this.debug();
  37855. });
  37856. }).then(message => this._createGeometry(message.geometry)); // Remove task from the task list.
  37857. // Note: replaced '.finally()' with '.catch().then()' block - iOS 11 support (#19416)
  37858. geometryPending.catch(() => true).then(() => {
  37859. if (worker && taskID) {
  37860. this._releaseTask(worker, taskID); // this.debug();
  37861. }
  37862. }); // Cache the task result.
  37863. DRACOLoader.taskCache.set(buffer, {
  37864. key: taskKey,
  37865. promise: geometryPending
  37866. });
  37867. return geometryPending;
  37868. },
  37869. _createGeometry: function (geometryData) {
  37870. var geometry = new _threeModule.BufferGeometry();
  37871. if (geometryData.index) {
  37872. geometry.setIndex(new _threeModule.BufferAttribute(geometryData.index.array, 1));
  37873. }
  37874. for (var i = 0; i < geometryData.attributes.length; i++) {
  37875. var attribute = geometryData.attributes[i];
  37876. var name = attribute.name;
  37877. var array = attribute.array;
  37878. var itemSize = attribute.itemSize;
  37879. geometry.setAttribute(name, new _threeModule.BufferAttribute(array, itemSize));
  37880. }
  37881. return geometry;
  37882. },
  37883. _loadLibrary: function (url, responseType) {
  37884. var loader = new _threeModule.FileLoader(this.manager);
  37885. loader.setPath(this.decoderPath);
  37886. loader.setResponseType(responseType);
  37887. loader.setWithCredentials(this.withCredentials);
  37888. return new Promise((resolve, reject) => {
  37889. loader.load(url, resolve, undefined, reject);
  37890. });
  37891. },
  37892. preload: function () {
  37893. this._initDecoder();
  37894. return this;
  37895. },
  37896. _initDecoder: function () {
  37897. if (this.decoderPending) return this.decoderPending;
  37898. var useJS = typeof WebAssembly !== 'object' || this.decoderConfig.type === 'js';
  37899. var librariesPending = [];
  37900. if (useJS) {
  37901. librariesPending.push(this._loadLibrary('draco_decoder.js', 'text'));
  37902. } else {
  37903. librariesPending.push(this._loadLibrary('draco_wasm_wrapper.js', 'text'));
  37904. librariesPending.push(this._loadLibrary('draco_decoder.wasm', 'arraybuffer'));
  37905. }
  37906. this.decoderPending = Promise.all(librariesPending).then(libraries => {
  37907. var jsContent = libraries[0];
  37908. if (!useJS) {
  37909. this.decoderConfig.wasmBinary = libraries[1];
  37910. }
  37911. var fn = DRACOLoader.DRACOWorker.toString();
  37912. var body = ['/* draco decoder */', jsContent, '', '/* worker */', fn.substring(fn.indexOf('{') + 1, fn.lastIndexOf('}'))].join('\n');
  37913. this.workerSourceURL = URL.createObjectURL(new Blob([body]));
  37914. });
  37915. return this.decoderPending;
  37916. },
  37917. _getWorker: function (taskID, taskCost) {
  37918. return this._initDecoder().then(() => {
  37919. if (this.workerPool.length < this.workerLimit) {
  37920. var worker = new Worker(this.workerSourceURL);
  37921. worker._callbacks = {};
  37922. worker._taskCosts = {};
  37923. worker._taskLoad = 0;
  37924. worker.postMessage({
  37925. type: 'init',
  37926. decoderConfig: this.decoderConfig
  37927. });
  37928. worker.onmessage = function (e) {
  37929. var message = e.data;
  37930. switch (message.type) {
  37931. case 'decode':
  37932. worker._callbacks[message.id].resolve(message);
  37933. break;
  37934. case 'error':
  37935. worker._callbacks[message.id].reject(message);
  37936. break;
  37937. default:
  37938. console.error('THREE.DRACOLoader: Unexpected message, "' + message.type + '"');
  37939. }
  37940. };
  37941. this.workerPool.push(worker);
  37942. } else {
  37943. this.workerPool.sort(function (a, b) {
  37944. return a._taskLoad > b._taskLoad ? -1 : 1;
  37945. });
  37946. }
  37947. var worker = this.workerPool[this.workerPool.length - 1];
  37948. worker._taskCosts[taskID] = taskCost;
  37949. worker._taskLoad += taskCost;
  37950. return worker;
  37951. });
  37952. },
  37953. _releaseTask: function (worker, taskID) {
  37954. worker._taskLoad -= worker._taskCosts[taskID];
  37955. delete worker._callbacks[taskID];
  37956. delete worker._taskCosts[taskID];
  37957. },
  37958. debug: function () {
  37959. console.log('Task load: ', this.workerPool.map(worker => worker._taskLoad));
  37960. },
  37961. dispose: function () {
  37962. for (var i = 0; i < this.workerPool.length; ++i) {
  37963. this.workerPool[i].terminate();
  37964. }
  37965. this.workerPool.length = 0;
  37966. return this;
  37967. }
  37968. });
  37969. /* WEB WORKER */
  37970. DRACOLoader.DRACOWorker = function () {
  37971. var decoderConfig;
  37972. var decoderPending;
  37973. onmessage = function (e) {
  37974. var message = e.data;
  37975. switch (message.type) {
  37976. case 'init':
  37977. decoderConfig = message.decoderConfig;
  37978. decoderPending = new Promise(function (resolve
  37979. /*, reject*/
  37980. ) {
  37981. decoderConfig.onModuleLoaded = function (draco) {
  37982. // Module is Promise-like. Wrap before resolving to avoid loop.
  37983. resolve({
  37984. draco: draco
  37985. });
  37986. };
  37987. DracoDecoderModule(decoderConfig); // eslint-disable-line no-undef
  37988. });
  37989. break;
  37990. case 'decode':
  37991. var buffer = message.buffer;
  37992. var taskConfig = message.taskConfig;
  37993. decoderPending.then(module => {
  37994. var draco = module.draco;
  37995. var decoder = new draco.Decoder();
  37996. var decoderBuffer = new draco.DecoderBuffer();
  37997. decoderBuffer.Init(new Int8Array(buffer), buffer.byteLength);
  37998. try {
  37999. var geometry = decodeGeometry(draco, decoder, decoderBuffer, taskConfig);
  38000. var buffers = geometry.attributes.map(attr => attr.array.buffer);
  38001. if (geometry.index) buffers.push(geometry.index.array.buffer);
  38002. self.postMessage({
  38003. type: 'decode',
  38004. id: message.id,
  38005. geometry
  38006. }, buffers);
  38007. } catch (error) {
  38008. console.error(error);
  38009. self.postMessage({
  38010. type: 'error',
  38011. id: message.id,
  38012. error: error.message
  38013. });
  38014. } finally {
  38015. draco.destroy(decoderBuffer);
  38016. draco.destroy(decoder);
  38017. }
  38018. });
  38019. break;
  38020. }
  38021. };
  38022. function decodeGeometry(draco, decoder, decoderBuffer, taskConfig) {
  38023. var attributeIDs = taskConfig.attributeIDs;
  38024. var attributeTypes = taskConfig.attributeTypes;
  38025. var dracoGeometry;
  38026. var decodingStatus;
  38027. var geometryType = decoder.GetEncodedGeometryType(decoderBuffer);
  38028. if (geometryType === draco.TRIANGULAR_MESH) {
  38029. dracoGeometry = new draco.Mesh();
  38030. decodingStatus = decoder.DecodeBufferToMesh(decoderBuffer, dracoGeometry);
  38031. } else if (geometryType === draco.POINT_CLOUD) {
  38032. dracoGeometry = new draco.PointCloud();
  38033. decodingStatus = decoder.DecodeBufferToPointCloud(decoderBuffer, dracoGeometry);
  38034. } else {
  38035. throw new Error('THREE.DRACOLoader: Unexpected geometry type.');
  38036. }
  38037. if (!decodingStatus.ok() || dracoGeometry.ptr === 0) {
  38038. throw new Error('THREE.DRACOLoader: Decoding failed: ' + decodingStatus.error_msg());
  38039. }
  38040. var geometry = {
  38041. index: null,
  38042. attributes: []
  38043. }; // Gather all vertex attributes.
  38044. for (var attributeName in attributeIDs) {
  38045. var attributeType = self[attributeTypes[attributeName]];
  38046. var attribute;
  38047. var attributeID; // A Draco file may be created with default vertex attributes, whose attribute IDs
  38048. // are mapped 1:1 from their semantic name (POSITION, NORMAL, ...). Alternatively,
  38049. // a Draco file may contain a custom set of attributes, identified by known unique
  38050. // IDs. glTF files always do the latter, and `.drc` files typically do the former.
  38051. if (taskConfig.useUniqueIDs) {
  38052. attributeID = attributeIDs[attributeName];
  38053. attribute = decoder.GetAttributeByUniqueId(dracoGeometry, attributeID);
  38054. } else {
  38055. attributeID = decoder.GetAttributeId(dracoGeometry, draco[attributeIDs[attributeName]]);
  38056. if (attributeID === -1) continue;
  38057. attribute = decoder.GetAttribute(dracoGeometry, attributeID);
  38058. }
  38059. geometry.attributes.push(decodeAttribute(draco, decoder, dracoGeometry, attributeName, attributeType, attribute));
  38060. } // Add index.
  38061. if (geometryType === draco.TRIANGULAR_MESH) {
  38062. geometry.index = decodeIndex(draco, decoder, dracoGeometry);
  38063. }
  38064. draco.destroy(dracoGeometry);
  38065. return geometry;
  38066. }
  38067. function decodeIndex(draco, decoder, dracoGeometry) {
  38068. var numFaces = dracoGeometry.num_faces();
  38069. var numIndices = numFaces * 3;
  38070. var byteLength = numIndices * 4;
  38071. var ptr = draco._malloc(byteLength);
  38072. decoder.GetTrianglesUInt32Array(dracoGeometry, byteLength, ptr);
  38073. var index = new Uint32Array(draco.HEAPF32.buffer, ptr, numIndices).slice();
  38074. draco._free(ptr);
  38075. return {
  38076. array: index,
  38077. itemSize: 1
  38078. };
  38079. }
  38080. function decodeAttribute(draco, decoder, dracoGeometry, attributeName, attributeType, attribute) {
  38081. var numComponents = attribute.num_components();
  38082. var numPoints = dracoGeometry.num_points();
  38083. var numValues = numPoints * numComponents;
  38084. var byteLength = numValues * attributeType.BYTES_PER_ELEMENT;
  38085. var dataType = getDracoDataType(draco, attributeType);
  38086. var ptr = draco._malloc(byteLength);
  38087. decoder.GetAttributeDataArrayForAllPoints(dracoGeometry, attribute, dataType, byteLength, ptr);
  38088. var array = new attributeType(draco.HEAPF32.buffer, ptr, numValues).slice();
  38089. draco._free(ptr);
  38090. return {
  38091. name: attributeName,
  38092. array: array,
  38093. itemSize: numComponents
  38094. };
  38095. }
  38096. function getDracoDataType(draco, attributeType) {
  38097. switch (attributeType) {
  38098. case Float32Array:
  38099. return draco.DT_FLOAT32;
  38100. case Int8Array:
  38101. return draco.DT_INT8;
  38102. case Int16Array:
  38103. return draco.DT_INT16;
  38104. case Int32Array:
  38105. return draco.DT_INT32;
  38106. case Uint8Array:
  38107. return draco.DT_UINT8;
  38108. case Uint16Array:
  38109. return draco.DT_UINT16;
  38110. case Uint32Array:
  38111. return draco.DT_UINT32;
  38112. }
  38113. }
  38114. };
  38115. DRACOLoader.taskCache = new WeakMap();
  38116. /** Deprecated static methods */
  38117. /** @deprecated */
  38118. DRACOLoader.setDecoderPath = function () {
  38119. console.warn('THREE.DRACOLoader: The .setDecoderPath() method has been removed. Use instance methods.');
  38120. };
  38121. /** @deprecated */
  38122. DRACOLoader.setDecoderConfig = function () {
  38123. console.warn('THREE.DRACOLoader: The .setDecoderConfig() method has been removed. Use instance methods.');
  38124. };
  38125. /** @deprecated */
  38126. DRACOLoader.releaseDecoderModule = function () {
  38127. console.warn('THREE.DRACOLoader: The .releaseDecoderModule() method has been removed. Use instance methods.');
  38128. };
  38129. /** @deprecated */
  38130. DRACOLoader.getDecoderModule = function () {
  38131. console.warn('THREE.DRACOLoader: The .getDecoderModule() method has been removed. Use instance methods.');
  38132. };
  38133. },{"../../../build/three.module.js":"../node_modules/three/build/three.module.js"}],"../node_modules/three/examples/jsm/libs/dat.gui.module.js":[function(require,module,exports) {
  38134. "use strict";
  38135. Object.defineProperty(exports, "__esModule", {
  38136. value: true
  38137. });
  38138. exports.default = exports.GUI = exports.gui = exports.dom = exports.controllers = exports.color = void 0;
  38139. /**
  38140. * dat-gui JavaScript Controller Library
  38141. * http://code.google.com/p/dat-gui
  38142. *
  38143. * Copyright 2011 Data Arts Team, Google Creative Lab
  38144. *
  38145. * Licensed under the Apache License, Version 2.0 (the "License");
  38146. * you may not use this file except in compliance with the License.
  38147. * You may obtain a copy of the License at
  38148. *
  38149. * http://www.apache.org/licenses/LICENSE-2.0
  38150. */
  38151. function ___$insertStyle(css) {
  38152. if (!css) {
  38153. return;
  38154. }
  38155. if (typeof window === 'undefined') {
  38156. return;
  38157. }
  38158. var style = document.createElement('style');
  38159. style.setAttribute('type', 'text/css');
  38160. style.innerHTML = css;
  38161. document.head.appendChild(style);
  38162. return css;
  38163. }
  38164. function colorToString(color, forceCSSHex) {
  38165. var colorFormat = color.__state.conversionName.toString();
  38166. var r = Math.round(color.r);
  38167. var g = Math.round(color.g);
  38168. var b = Math.round(color.b);
  38169. var a = color.a;
  38170. var h = Math.round(color.h);
  38171. var s = color.s.toFixed(1);
  38172. var v = color.v.toFixed(1);
  38173. if (forceCSSHex || colorFormat === 'THREE_CHAR_HEX' || colorFormat === 'SIX_CHAR_HEX') {
  38174. var str = color.hex.toString(16);
  38175. while (str.length < 6) {
  38176. str = '0' + str;
  38177. }
  38178. return '#' + str;
  38179. } else if (colorFormat === 'CSS_RGB') {
  38180. return 'rgb(' + r + ',' + g + ',' + b + ')';
  38181. } else if (colorFormat === 'CSS_RGBA') {
  38182. return 'rgba(' + r + ',' + g + ',' + b + ',' + a + ')';
  38183. } else if (colorFormat === 'HEX') {
  38184. return '0x' + color.hex.toString(16);
  38185. } else if (colorFormat === 'RGB_ARRAY') {
  38186. return '[' + r + ',' + g + ',' + b + ']';
  38187. } else if (colorFormat === 'RGBA_ARRAY') {
  38188. return '[' + r + ',' + g + ',' + b + ',' + a + ']';
  38189. } else if (colorFormat === 'RGB_OBJ') {
  38190. return '{r:' + r + ',g:' + g + ',b:' + b + '}';
  38191. } else if (colorFormat === 'RGBA_OBJ') {
  38192. return '{r:' + r + ',g:' + g + ',b:' + b + ',a:' + a + '}';
  38193. } else if (colorFormat === 'HSV_OBJ') {
  38194. return '{h:' + h + ',s:' + s + ',v:' + v + '}';
  38195. } else if (colorFormat === 'HSVA_OBJ') {
  38196. return '{h:' + h + ',s:' + s + ',v:' + v + ',a:' + a + '}';
  38197. }
  38198. return 'unknown format';
  38199. }
  38200. var ARR_EACH = Array.prototype.forEach;
  38201. var ARR_SLICE = Array.prototype.slice;
  38202. var Common = {
  38203. BREAK: {},
  38204. extend: function extend(target) {
  38205. this.each(ARR_SLICE.call(arguments, 1), function (obj) {
  38206. var keys = this.isObject(obj) ? Object.keys(obj) : [];
  38207. keys.forEach(function (key) {
  38208. if (!this.isUndefined(obj[key])) {
  38209. target[key] = obj[key];
  38210. }
  38211. }.bind(this));
  38212. }, this);
  38213. return target;
  38214. },
  38215. defaults: function defaults(target) {
  38216. this.each(ARR_SLICE.call(arguments, 1), function (obj) {
  38217. var keys = this.isObject(obj) ? Object.keys(obj) : [];
  38218. keys.forEach(function (key) {
  38219. if (this.isUndefined(target[key])) {
  38220. target[key] = obj[key];
  38221. }
  38222. }.bind(this));
  38223. }, this);
  38224. return target;
  38225. },
  38226. compose: function compose() {
  38227. var toCall = ARR_SLICE.call(arguments);
  38228. return function () {
  38229. var args = ARR_SLICE.call(arguments);
  38230. for (var i = toCall.length - 1; i >= 0; i--) {
  38231. args = [toCall[i].apply(this, args)];
  38232. }
  38233. return args[0];
  38234. };
  38235. },
  38236. each: function each(obj, itr, scope) {
  38237. if (!obj) {
  38238. return;
  38239. }
  38240. if (ARR_EACH && obj.forEach && obj.forEach === ARR_EACH) {
  38241. obj.forEach(itr, scope);
  38242. } else if (obj.length === obj.length + 0) {
  38243. var key = void 0;
  38244. var l = void 0;
  38245. for (key = 0, l = obj.length; key < l; key++) {
  38246. if (key in obj && itr.call(scope, obj[key], key) === this.BREAK) {
  38247. return;
  38248. }
  38249. }
  38250. } else {
  38251. for (var _key in obj) {
  38252. if (itr.call(scope, obj[_key], _key) === this.BREAK) {
  38253. return;
  38254. }
  38255. }
  38256. }
  38257. },
  38258. defer: function defer(fnc) {
  38259. setTimeout(fnc, 0);
  38260. },
  38261. debounce: function debounce(func, threshold, callImmediately) {
  38262. var timeout = void 0;
  38263. return function () {
  38264. var obj = this;
  38265. var args = arguments;
  38266. function delayed() {
  38267. timeout = null;
  38268. if (!callImmediately) func.apply(obj, args);
  38269. }
  38270. var callNow = callImmediately || !timeout;
  38271. clearTimeout(timeout);
  38272. timeout = setTimeout(delayed, threshold);
  38273. if (callNow) {
  38274. func.apply(obj, args);
  38275. }
  38276. };
  38277. },
  38278. toArray: function toArray(obj) {
  38279. if (obj.toArray) return obj.toArray();
  38280. return ARR_SLICE.call(obj);
  38281. },
  38282. isUndefined: function isUndefined(obj) {
  38283. return obj === undefined;
  38284. },
  38285. isNull: function isNull(obj) {
  38286. return obj === null;
  38287. },
  38288. isNaN: function (_isNaN) {
  38289. function isNaN() {
  38290. return _isNaN.apply(this, arguments);
  38291. }
  38292. isNaN.toString = function () {
  38293. return _isNaN.toString();
  38294. };
  38295. return isNaN;
  38296. }(function (obj) {
  38297. return isNaN(obj);
  38298. }),
  38299. isArray: Array.isArray || function (obj) {
  38300. return obj.constructor === Array;
  38301. },
  38302. isObject: function isObject(obj) {
  38303. return obj === Object(obj);
  38304. },
  38305. isNumber: function isNumber(obj) {
  38306. return obj === obj + 0;
  38307. },
  38308. isString: function isString(obj) {
  38309. return obj === obj + '';
  38310. },
  38311. isBoolean: function isBoolean(obj) {
  38312. return obj === false || obj === true;
  38313. },
  38314. isFunction: function isFunction(obj) {
  38315. return obj instanceof Function;
  38316. }
  38317. };
  38318. var INTERPRETATIONS = [{
  38319. litmus: Common.isString,
  38320. conversions: {
  38321. THREE_CHAR_HEX: {
  38322. read: function read(original) {
  38323. var test = original.match(/^#([A-F0-9])([A-F0-9])([A-F0-9])$/i);
  38324. if (test === null) {
  38325. return false;
  38326. }
  38327. return {
  38328. space: 'HEX',
  38329. hex: parseInt('0x' + test[1].toString() + test[1].toString() + test[2].toString() + test[2].toString() + test[3].toString() + test[3].toString(), 0)
  38330. };
  38331. },
  38332. write: colorToString
  38333. },
  38334. SIX_CHAR_HEX: {
  38335. read: function read(original) {
  38336. var test = original.match(/^#([A-F0-9]{6})$/i);
  38337. if (test === null) {
  38338. return false;
  38339. }
  38340. return {
  38341. space: 'HEX',
  38342. hex: parseInt('0x' + test[1].toString(), 0)
  38343. };
  38344. },
  38345. write: colorToString
  38346. },
  38347. CSS_RGB: {
  38348. read: function read(original) {
  38349. var test = original.match(/^rgb\(\s*(.+)\s*,\s*(.+)\s*,\s*(.+)\s*\)/);
  38350. if (test === null) {
  38351. return false;
  38352. }
  38353. return {
  38354. space: 'RGB',
  38355. r: parseFloat(test[1]),
  38356. g: parseFloat(test[2]),
  38357. b: parseFloat(test[3])
  38358. };
  38359. },
  38360. write: colorToString
  38361. },
  38362. CSS_RGBA: {
  38363. read: function read(original) {
  38364. var test = original.match(/^rgba\(\s*(.+)\s*,\s*(.+)\s*,\s*(.+)\s*,\s*(.+)\s*\)/);
  38365. if (test === null) {
  38366. return false;
  38367. }
  38368. return {
  38369. space: 'RGB',
  38370. r: parseFloat(test[1]),
  38371. g: parseFloat(test[2]),
  38372. b: parseFloat(test[3]),
  38373. a: parseFloat(test[4])
  38374. };
  38375. },
  38376. write: colorToString
  38377. }
  38378. }
  38379. }, {
  38380. litmus: Common.isNumber,
  38381. conversions: {
  38382. HEX: {
  38383. read: function read(original) {
  38384. return {
  38385. space: 'HEX',
  38386. hex: original,
  38387. conversionName: 'HEX'
  38388. };
  38389. },
  38390. write: function write(color) {
  38391. return color.hex;
  38392. }
  38393. }
  38394. }
  38395. }, {
  38396. litmus: Common.isArray,
  38397. conversions: {
  38398. RGB_ARRAY: {
  38399. read: function read(original) {
  38400. if (original.length !== 3) {
  38401. return false;
  38402. }
  38403. return {
  38404. space: 'RGB',
  38405. r: original[0],
  38406. g: original[1],
  38407. b: original[2]
  38408. };
  38409. },
  38410. write: function write(color) {
  38411. return [color.r, color.g, color.b];
  38412. }
  38413. },
  38414. RGBA_ARRAY: {
  38415. read: function read(original) {
  38416. if (original.length !== 4) return false;
  38417. return {
  38418. space: 'RGB',
  38419. r: original[0],
  38420. g: original[1],
  38421. b: original[2],
  38422. a: original[3]
  38423. };
  38424. },
  38425. write: function write(color) {
  38426. return [color.r, color.g, color.b, color.a];
  38427. }
  38428. }
  38429. }
  38430. }, {
  38431. litmus: Common.isObject,
  38432. conversions: {
  38433. RGBA_OBJ: {
  38434. read: function read(original) {
  38435. if (Common.isNumber(original.r) && Common.isNumber(original.g) && Common.isNumber(original.b) && Common.isNumber(original.a)) {
  38436. return {
  38437. space: 'RGB',
  38438. r: original.r,
  38439. g: original.g,
  38440. b: original.b,
  38441. a: original.a
  38442. };
  38443. }
  38444. return false;
  38445. },
  38446. write: function write(color) {
  38447. return {
  38448. r: color.r,
  38449. g: color.g,
  38450. b: color.b,
  38451. a: color.a
  38452. };
  38453. }
  38454. },
  38455. RGB_OBJ: {
  38456. read: function read(original) {
  38457. if (Common.isNumber(original.r) && Common.isNumber(original.g) && Common.isNumber(original.b)) {
  38458. return {
  38459. space: 'RGB',
  38460. r: original.r,
  38461. g: original.g,
  38462. b: original.b
  38463. };
  38464. }
  38465. return false;
  38466. },
  38467. write: function write(color) {
  38468. return {
  38469. r: color.r,
  38470. g: color.g,
  38471. b: color.b
  38472. };
  38473. }
  38474. },
  38475. HSVA_OBJ: {
  38476. read: function read(original) {
  38477. if (Common.isNumber(original.h) && Common.isNumber(original.s) && Common.isNumber(original.v) && Common.isNumber(original.a)) {
  38478. return {
  38479. space: 'HSV',
  38480. h: original.h,
  38481. s: original.s,
  38482. v: original.v,
  38483. a: original.a
  38484. };
  38485. }
  38486. return false;
  38487. },
  38488. write: function write(color) {
  38489. return {
  38490. h: color.h,
  38491. s: color.s,
  38492. v: color.v,
  38493. a: color.a
  38494. };
  38495. }
  38496. },
  38497. HSV_OBJ: {
  38498. read: function read(original) {
  38499. if (Common.isNumber(original.h) && Common.isNumber(original.s) && Common.isNumber(original.v)) {
  38500. return {
  38501. space: 'HSV',
  38502. h: original.h,
  38503. s: original.s,
  38504. v: original.v
  38505. };
  38506. }
  38507. return false;
  38508. },
  38509. write: function write(color) {
  38510. return {
  38511. h: color.h,
  38512. s: color.s,
  38513. v: color.v
  38514. };
  38515. }
  38516. }
  38517. }
  38518. }];
  38519. var result = void 0;
  38520. var toReturn = void 0;
  38521. var interpret = function interpret() {
  38522. toReturn = false;
  38523. var original = arguments.length > 1 ? Common.toArray(arguments) : arguments[0];
  38524. Common.each(INTERPRETATIONS, function (family) {
  38525. if (family.litmus(original)) {
  38526. Common.each(family.conversions, function (conversion, conversionName) {
  38527. result = conversion.read(original);
  38528. if (toReturn === false && result !== false) {
  38529. toReturn = result;
  38530. result.conversionName = conversionName;
  38531. result.conversion = conversion;
  38532. return Common.BREAK;
  38533. }
  38534. });
  38535. return Common.BREAK;
  38536. }
  38537. });
  38538. return toReturn;
  38539. };
  38540. var tmpComponent = void 0;
  38541. var ColorMath = {
  38542. hsv_to_rgb: function hsv_to_rgb(h, s, v) {
  38543. var hi = Math.floor(h / 60) % 6;
  38544. var f = h / 60 - Math.floor(h / 60);
  38545. var p = v * (1.0 - s);
  38546. var q = v * (1.0 - f * s);
  38547. var t = v * (1.0 - (1.0 - f) * s);
  38548. var c = [[v, t, p], [q, v, p], [p, v, t], [p, q, v], [t, p, v], [v, p, q]][hi];
  38549. return {
  38550. r: c[0] * 255,
  38551. g: c[1] * 255,
  38552. b: c[2] * 255
  38553. };
  38554. },
  38555. rgb_to_hsv: function rgb_to_hsv(r, g, b) {
  38556. var min = Math.min(r, g, b);
  38557. var max = Math.max(r, g, b);
  38558. var delta = max - min;
  38559. var h = void 0;
  38560. var s = void 0;
  38561. if (max !== 0) {
  38562. s = delta / max;
  38563. } else {
  38564. return {
  38565. h: NaN,
  38566. s: 0,
  38567. v: 0
  38568. };
  38569. }
  38570. if (r === max) {
  38571. h = (g - b) / delta;
  38572. } else if (g === max) {
  38573. h = 2 + (b - r) / delta;
  38574. } else {
  38575. h = 4 + (r - g) / delta;
  38576. }
  38577. h /= 6;
  38578. if (h < 0) {
  38579. h += 1;
  38580. }
  38581. return {
  38582. h: h * 360,
  38583. s: s,
  38584. v: max / 255
  38585. };
  38586. },
  38587. rgb_to_hex: function rgb_to_hex(r, g, b) {
  38588. var hex = this.hex_with_component(0, 2, r);
  38589. hex = this.hex_with_component(hex, 1, g);
  38590. hex = this.hex_with_component(hex, 0, b);
  38591. return hex;
  38592. },
  38593. component_from_hex: function component_from_hex(hex, componentIndex) {
  38594. return hex >> componentIndex * 8 & 0xFF;
  38595. },
  38596. hex_with_component: function hex_with_component(hex, componentIndex, value) {
  38597. return value << (tmpComponent = componentIndex * 8) | hex & ~(0xFF << tmpComponent);
  38598. }
  38599. };
  38600. var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) {
  38601. return typeof obj;
  38602. } : function (obj) {
  38603. return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
  38604. };
  38605. var classCallCheck = function (instance, Constructor) {
  38606. if (!(instance instanceof Constructor)) {
  38607. throw new TypeError("Cannot call a class as a function");
  38608. }
  38609. };
  38610. var createClass = function () {
  38611. function defineProperties(target, props) {
  38612. for (var i = 0; i < props.length; i++) {
  38613. var descriptor = props[i];
  38614. descriptor.enumerable = descriptor.enumerable || false;
  38615. descriptor.configurable = true;
  38616. if ("value" in descriptor) descriptor.writable = true;
  38617. Object.defineProperty(target, descriptor.key, descriptor);
  38618. }
  38619. }
  38620. return function (Constructor, protoProps, staticProps) {
  38621. if (protoProps) defineProperties(Constructor.prototype, protoProps);
  38622. if (staticProps) defineProperties(Constructor, staticProps);
  38623. return Constructor;
  38624. };
  38625. }();
  38626. var get = function get(object, property, receiver) {
  38627. if (object === null) object = Function.prototype;
  38628. var desc = Object.getOwnPropertyDescriptor(object, property);
  38629. if (desc === undefined) {
  38630. var parent = Object.getPrototypeOf(object);
  38631. if (parent === null) {
  38632. return undefined;
  38633. } else {
  38634. return get(parent, property, receiver);
  38635. }
  38636. } else if ("value" in desc) {
  38637. return desc.value;
  38638. } else {
  38639. var getter = desc.get;
  38640. if (getter === undefined) {
  38641. return undefined;
  38642. }
  38643. return getter.call(receiver);
  38644. }
  38645. };
  38646. var inherits = function (subClass, superClass) {
  38647. if (typeof superClass !== "function" && superClass !== null) {
  38648. throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);
  38649. }
  38650. subClass.prototype = Object.create(superClass && superClass.prototype, {
  38651. constructor: {
  38652. value: subClass,
  38653. enumerable: false,
  38654. writable: true,
  38655. configurable: true
  38656. }
  38657. });
  38658. if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
  38659. };
  38660. var possibleConstructorReturn = function (self, call) {
  38661. if (!self) {
  38662. throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  38663. }
  38664. return call && (typeof call === "object" || typeof call === "function") ? call : self;
  38665. };
  38666. var Color = function () {
  38667. function Color() {
  38668. classCallCheck(this, Color);
  38669. this.__state = interpret.apply(this, arguments);
  38670. if (this.__state === false) {
  38671. throw new Error('Failed to interpret color arguments');
  38672. }
  38673. this.__state.a = this.__state.a || 1;
  38674. }
  38675. createClass(Color, [{
  38676. key: 'toString',
  38677. value: function toString() {
  38678. return colorToString(this);
  38679. }
  38680. }, {
  38681. key: 'toHexString',
  38682. value: function toHexString() {
  38683. return colorToString(this, true);
  38684. }
  38685. }, {
  38686. key: 'toOriginal',
  38687. value: function toOriginal() {
  38688. return this.__state.conversion.write(this);
  38689. }
  38690. }]);
  38691. return Color;
  38692. }();
  38693. function defineRGBComponent(target, component, componentHexIndex) {
  38694. Object.defineProperty(target, component, {
  38695. get: function get$$1() {
  38696. if (this.__state.space === 'RGB') {
  38697. return this.__state[component];
  38698. }
  38699. Color.recalculateRGB(this, component, componentHexIndex);
  38700. return this.__state[component];
  38701. },
  38702. set: function set$$1(v) {
  38703. if (this.__state.space !== 'RGB') {
  38704. Color.recalculateRGB(this, component, componentHexIndex);
  38705. this.__state.space = 'RGB';
  38706. }
  38707. this.__state[component] = v;
  38708. }
  38709. });
  38710. }
  38711. function defineHSVComponent(target, component) {
  38712. Object.defineProperty(target, component, {
  38713. get: function get$$1() {
  38714. if (this.__state.space === 'HSV') {
  38715. return this.__state[component];
  38716. }
  38717. Color.recalculateHSV(this);
  38718. return this.__state[component];
  38719. },
  38720. set: function set$$1(v) {
  38721. if (this.__state.space !== 'HSV') {
  38722. Color.recalculateHSV(this);
  38723. this.__state.space = 'HSV';
  38724. }
  38725. this.__state[component] = v;
  38726. }
  38727. });
  38728. }
  38729. Color.recalculateRGB = function (color, component, componentHexIndex) {
  38730. if (color.__state.space === 'HEX') {
  38731. color.__state[component] = ColorMath.component_from_hex(color.__state.hex, componentHexIndex);
  38732. } else if (color.__state.space === 'HSV') {
  38733. Common.extend(color.__state, ColorMath.hsv_to_rgb(color.__state.h, color.__state.s, color.__state.v));
  38734. } else {
  38735. throw new Error('Corrupted color state');
  38736. }
  38737. };
  38738. Color.recalculateHSV = function (color) {
  38739. var result = ColorMath.rgb_to_hsv(color.r, color.g, color.b);
  38740. Common.extend(color.__state, {
  38741. s: result.s,
  38742. v: result.v
  38743. });
  38744. if (!Common.isNaN(result.h)) {
  38745. color.__state.h = result.h;
  38746. } else if (Common.isUndefined(color.__state.h)) {
  38747. color.__state.h = 0;
  38748. }
  38749. };
  38750. Color.COMPONENTS = ['r', 'g', 'b', 'h', 's', 'v', 'hex', 'a'];
  38751. defineRGBComponent(Color.prototype, 'r', 2);
  38752. defineRGBComponent(Color.prototype, 'g', 1);
  38753. defineRGBComponent(Color.prototype, 'b', 0);
  38754. defineHSVComponent(Color.prototype, 'h');
  38755. defineHSVComponent(Color.prototype, 's');
  38756. defineHSVComponent(Color.prototype, 'v');
  38757. Object.defineProperty(Color.prototype, 'a', {
  38758. get: function get$$1() {
  38759. return this.__state.a;
  38760. },
  38761. set: function set$$1(v) {
  38762. this.__state.a = v;
  38763. }
  38764. });
  38765. Object.defineProperty(Color.prototype, 'hex', {
  38766. get: function get$$1() {
  38767. if (this.__state.space !== 'HEX') {
  38768. this.__state.hex = ColorMath.rgb_to_hex(this.r, this.g, this.b);
  38769. this.__state.space = 'HEX';
  38770. }
  38771. return this.__state.hex;
  38772. },
  38773. set: function set$$1(v) {
  38774. this.__state.space = 'HEX';
  38775. this.__state.hex = v;
  38776. }
  38777. });
  38778. var Controller = function () {
  38779. function Controller(object, property) {
  38780. classCallCheck(this, Controller);
  38781. this.initialValue = object[property];
  38782. this.domElement = document.createElement('div');
  38783. this.object = object;
  38784. this.property = property;
  38785. this.__onChange = undefined;
  38786. this.__onFinishChange = undefined;
  38787. }
  38788. createClass(Controller, [{
  38789. key: 'onChange',
  38790. value: function onChange(fnc) {
  38791. this.__onChange = fnc;
  38792. return this;
  38793. }
  38794. }, {
  38795. key: 'onFinishChange',
  38796. value: function onFinishChange(fnc) {
  38797. this.__onFinishChange = fnc;
  38798. return this;
  38799. }
  38800. }, {
  38801. key: 'setValue',
  38802. value: function setValue(newValue) {
  38803. this.object[this.property] = newValue;
  38804. if (this.__onChange) {
  38805. this.__onChange.call(this, newValue);
  38806. }
  38807. this.updateDisplay();
  38808. return this;
  38809. }
  38810. }, {
  38811. key: 'getValue',
  38812. value: function getValue() {
  38813. return this.object[this.property];
  38814. }
  38815. }, {
  38816. key: 'updateDisplay',
  38817. value: function updateDisplay() {
  38818. return this;
  38819. }
  38820. }, {
  38821. key: 'isModified',
  38822. value: function isModified() {
  38823. return this.initialValue !== this.getValue();
  38824. }
  38825. }]);
  38826. return Controller;
  38827. }();
  38828. var EVENT_MAP = {
  38829. HTMLEvents: ['change'],
  38830. MouseEvents: ['click', 'mousemove', 'mousedown', 'mouseup', 'mouseover'],
  38831. KeyboardEvents: ['keydown']
  38832. };
  38833. var EVENT_MAP_INV = {};
  38834. Common.each(EVENT_MAP, function (v, k) {
  38835. Common.each(v, function (e) {
  38836. EVENT_MAP_INV[e] = k;
  38837. });
  38838. });
  38839. var CSS_VALUE_PIXELS = /(\d+(\.\d+)?)px/;
  38840. function cssValueToPixels(val) {
  38841. if (val === '0' || Common.isUndefined(val)) {
  38842. return 0;
  38843. }
  38844. var match = val.match(CSS_VALUE_PIXELS);
  38845. if (!Common.isNull(match)) {
  38846. return parseFloat(match[1]);
  38847. }
  38848. return 0;
  38849. }
  38850. var dom = {
  38851. makeSelectable: function makeSelectable(elem, selectable) {
  38852. if (elem === undefined || elem.style === undefined) return;
  38853. elem.onselectstart = selectable ? function () {
  38854. return false;
  38855. } : function () {};
  38856. elem.style.MozUserSelect = selectable ? 'auto' : 'none';
  38857. elem.style.KhtmlUserSelect = selectable ? 'auto' : 'none';
  38858. elem.unselectable = selectable ? 'on' : 'off';
  38859. },
  38860. makeFullscreen: function makeFullscreen(elem, hor, vert) {
  38861. var vertical = vert;
  38862. var horizontal = hor;
  38863. if (Common.isUndefined(horizontal)) {
  38864. horizontal = true;
  38865. }
  38866. if (Common.isUndefined(vertical)) {
  38867. vertical = true;
  38868. }
  38869. elem.style.position = 'absolute';
  38870. if (horizontal) {
  38871. elem.style.left = 0;
  38872. elem.style.right = 0;
  38873. }
  38874. if (vertical) {
  38875. elem.style.top = 0;
  38876. elem.style.bottom = 0;
  38877. }
  38878. },
  38879. fakeEvent: function fakeEvent(elem, eventType, pars, aux) {
  38880. var params = pars || {};
  38881. var className = EVENT_MAP_INV[eventType];
  38882. if (!className) {
  38883. throw new Error('Event type ' + eventType + ' not supported.');
  38884. }
  38885. var evt = document.createEvent(className);
  38886. switch (className) {
  38887. case 'MouseEvents':
  38888. {
  38889. var clientX = params.x || params.clientX || 0;
  38890. var clientY = params.y || params.clientY || 0;
  38891. evt.initMouseEvent(eventType, params.bubbles || false, params.cancelable || true, window, params.clickCount || 1, 0, 0, clientX, clientY, false, false, false, false, 0, null);
  38892. break;
  38893. }
  38894. case 'KeyboardEvents':
  38895. {
  38896. var init = evt.initKeyboardEvent || evt.initKeyEvent;
  38897. Common.defaults(params, {
  38898. cancelable: true,
  38899. ctrlKey: false,
  38900. altKey: false,
  38901. shiftKey: false,
  38902. metaKey: false,
  38903. keyCode: undefined,
  38904. charCode: undefined
  38905. });
  38906. init(eventType, params.bubbles || false, params.cancelable, window, params.ctrlKey, params.altKey, params.shiftKey, params.metaKey, params.keyCode, params.charCode);
  38907. break;
  38908. }
  38909. default:
  38910. {
  38911. evt.initEvent(eventType, params.bubbles || false, params.cancelable || true);
  38912. break;
  38913. }
  38914. }
  38915. Common.defaults(evt, aux);
  38916. elem.dispatchEvent(evt);
  38917. },
  38918. bind: function bind(elem, event, func, newBool) {
  38919. var bool = newBool || false;
  38920. if (elem.addEventListener) {
  38921. elem.addEventListener(event, func, bool);
  38922. } else if (elem.attachEvent) {
  38923. elem.attachEvent('on' + event, func);
  38924. }
  38925. return dom;
  38926. },
  38927. unbind: function unbind(elem, event, func, newBool) {
  38928. var bool = newBool || false;
  38929. if (elem.removeEventListener) {
  38930. elem.removeEventListener(event, func, bool);
  38931. } else if (elem.detachEvent) {
  38932. elem.detachEvent('on' + event, func);
  38933. }
  38934. return dom;
  38935. },
  38936. addClass: function addClass(elem, className) {
  38937. if (elem.className === undefined) {
  38938. elem.className = className;
  38939. } else if (elem.className !== className) {
  38940. var classes = elem.className.split(/ +/);
  38941. if (classes.indexOf(className) === -1) {
  38942. classes.push(className);
  38943. elem.className = classes.join(' ').replace(/^\s+/, '').replace(/\s+$/, '');
  38944. }
  38945. }
  38946. return dom;
  38947. },
  38948. removeClass: function removeClass(elem, className) {
  38949. if (className) {
  38950. if (elem.className === className) {
  38951. elem.removeAttribute('class');
  38952. } else {
  38953. var classes = elem.className.split(/ +/);
  38954. var index = classes.indexOf(className);
  38955. if (index !== -1) {
  38956. classes.splice(index, 1);
  38957. elem.className = classes.join(' ');
  38958. }
  38959. }
  38960. } else {
  38961. elem.className = undefined;
  38962. }
  38963. return dom;
  38964. },
  38965. hasClass: function hasClass(elem, className) {
  38966. return new RegExp('(?:^|\\s+)' + className + '(?:\\s+|$)').test(elem.className) || false;
  38967. },
  38968. getWidth: function getWidth(elem) {
  38969. var style = getComputedStyle(elem);
  38970. return cssValueToPixels(style['border-left-width']) + cssValueToPixels(style['border-right-width']) + cssValueToPixels(style['padding-left']) + cssValueToPixels(style['padding-right']) + cssValueToPixels(style.width);
  38971. },
  38972. getHeight: function getHeight(elem) {
  38973. var style = getComputedStyle(elem);
  38974. return cssValueToPixels(style['border-top-width']) + cssValueToPixels(style['border-bottom-width']) + cssValueToPixels(style['padding-top']) + cssValueToPixels(style['padding-bottom']) + cssValueToPixels(style.height);
  38975. },
  38976. getOffset: function getOffset(el) {
  38977. var elem = el;
  38978. var offset = {
  38979. left: 0,
  38980. top: 0
  38981. };
  38982. if (elem.offsetParent) {
  38983. do {
  38984. offset.left += elem.offsetLeft;
  38985. offset.top += elem.offsetTop;
  38986. elem = elem.offsetParent;
  38987. } while (elem);
  38988. }
  38989. return offset;
  38990. },
  38991. isActive: function isActive(elem) {
  38992. return elem === document.activeElement && (elem.type || elem.href);
  38993. }
  38994. };
  38995. var BooleanController = function (_Controller) {
  38996. inherits(BooleanController, _Controller);
  38997. function BooleanController(object, property) {
  38998. classCallCheck(this, BooleanController);
  38999. var _this2 = possibleConstructorReturn(this, (BooleanController.__proto__ || Object.getPrototypeOf(BooleanController)).call(this, object, property));
  39000. var _this = _this2;
  39001. _this2.__prev = _this2.getValue();
  39002. _this2.__checkbox = document.createElement('input');
  39003. _this2.__checkbox.setAttribute('type', 'checkbox');
  39004. function onChange() {
  39005. _this.setValue(!_this.__prev);
  39006. }
  39007. dom.bind(_this2.__checkbox, 'change', onChange, false);
  39008. _this2.domElement.appendChild(_this2.__checkbox);
  39009. _this2.updateDisplay();
  39010. return _this2;
  39011. }
  39012. createClass(BooleanController, [{
  39013. key: 'setValue',
  39014. value: function setValue(v) {
  39015. var toReturn = get(BooleanController.prototype.__proto__ || Object.getPrototypeOf(BooleanController.prototype), 'setValue', this).call(this, v);
  39016. if (this.__onFinishChange) {
  39017. this.__onFinishChange.call(this, this.getValue());
  39018. }
  39019. this.__prev = this.getValue();
  39020. return toReturn;
  39021. }
  39022. }, {
  39023. key: 'updateDisplay',
  39024. value: function updateDisplay() {
  39025. if (this.getValue() === true) {
  39026. this.__checkbox.setAttribute('checked', 'checked');
  39027. this.__checkbox.checked = true;
  39028. this.__prev = true;
  39029. } else {
  39030. this.__checkbox.checked = false;
  39031. this.__prev = false;
  39032. }
  39033. return get(BooleanController.prototype.__proto__ || Object.getPrototypeOf(BooleanController.prototype), 'updateDisplay', this).call(this);
  39034. }
  39035. }]);
  39036. return BooleanController;
  39037. }(Controller);
  39038. var OptionController = function (_Controller) {
  39039. inherits(OptionController, _Controller);
  39040. function OptionController(object, property, opts) {
  39041. classCallCheck(this, OptionController);
  39042. var _this2 = possibleConstructorReturn(this, (OptionController.__proto__ || Object.getPrototypeOf(OptionController)).call(this, object, property));
  39043. var options = opts;
  39044. var _this = _this2;
  39045. _this2.__select = document.createElement('select');
  39046. if (Common.isArray(options)) {
  39047. var map = {};
  39048. Common.each(options, function (element) {
  39049. map[element] = element;
  39050. });
  39051. options = map;
  39052. }
  39053. Common.each(options, function (value, key) {
  39054. var opt = document.createElement('option');
  39055. opt.innerHTML = key;
  39056. opt.setAttribute('value', value);
  39057. _this.__select.appendChild(opt);
  39058. });
  39059. _this2.updateDisplay();
  39060. dom.bind(_this2.__select, 'change', function () {
  39061. var desiredValue = this.options[this.selectedIndex].value;
  39062. _this.setValue(desiredValue);
  39063. });
  39064. _this2.domElement.appendChild(_this2.__select);
  39065. return _this2;
  39066. }
  39067. createClass(OptionController, [{
  39068. key: 'setValue',
  39069. value: function setValue(v) {
  39070. var toReturn = get(OptionController.prototype.__proto__ || Object.getPrototypeOf(OptionController.prototype), 'setValue', this).call(this, v);
  39071. if (this.__onFinishChange) {
  39072. this.__onFinishChange.call(this, this.getValue());
  39073. }
  39074. return toReturn;
  39075. }
  39076. }, {
  39077. key: 'updateDisplay',
  39078. value: function updateDisplay() {
  39079. if (dom.isActive(this.__select)) return this;
  39080. this.__select.value = this.getValue();
  39081. return get(OptionController.prototype.__proto__ || Object.getPrototypeOf(OptionController.prototype), 'updateDisplay', this).call(this);
  39082. }
  39083. }]);
  39084. return OptionController;
  39085. }(Controller);
  39086. var StringController = function (_Controller) {
  39087. inherits(StringController, _Controller);
  39088. function StringController(object, property) {
  39089. classCallCheck(this, StringController);
  39090. var _this2 = possibleConstructorReturn(this, (StringController.__proto__ || Object.getPrototypeOf(StringController)).call(this, object, property));
  39091. var _this = _this2;
  39092. function onChange() {
  39093. _this.setValue(_this.__input.value);
  39094. }
  39095. function onBlur() {
  39096. if (_this.__onFinishChange) {
  39097. _this.__onFinishChange.call(_this, _this.getValue());
  39098. }
  39099. }
  39100. _this2.__input = document.createElement('input');
  39101. _this2.__input.setAttribute('type', 'text');
  39102. dom.bind(_this2.__input, 'keyup', onChange);
  39103. dom.bind(_this2.__input, 'change', onChange);
  39104. dom.bind(_this2.__input, 'blur', onBlur);
  39105. dom.bind(_this2.__input, 'keydown', function (e) {
  39106. if (e.keyCode === 13) {
  39107. this.blur();
  39108. }
  39109. });
  39110. _this2.updateDisplay();
  39111. _this2.domElement.appendChild(_this2.__input);
  39112. return _this2;
  39113. }
  39114. createClass(StringController, [{
  39115. key: 'updateDisplay',
  39116. value: function updateDisplay() {
  39117. if (!dom.isActive(this.__input)) {
  39118. this.__input.value = this.getValue();
  39119. }
  39120. return get(StringController.prototype.__proto__ || Object.getPrototypeOf(StringController.prototype), 'updateDisplay', this).call(this);
  39121. }
  39122. }]);
  39123. return StringController;
  39124. }(Controller);
  39125. function numDecimals(x) {
  39126. var _x = x.toString();
  39127. if (_x.indexOf('.') > -1) {
  39128. return _x.length - _x.indexOf('.') - 1;
  39129. }
  39130. return 0;
  39131. }
  39132. var NumberController = function (_Controller) {
  39133. inherits(NumberController, _Controller);
  39134. function NumberController(object, property, params) {
  39135. classCallCheck(this, NumberController);
  39136. var _this = possibleConstructorReturn(this, (NumberController.__proto__ || Object.getPrototypeOf(NumberController)).call(this, object, property));
  39137. var _params = params || {};
  39138. _this.__min = _params.min;
  39139. _this.__max = _params.max;
  39140. _this.__step = _params.step;
  39141. if (Common.isUndefined(_this.__step)) {
  39142. if (_this.initialValue === 0) {
  39143. _this.__impliedStep = 1;
  39144. } else {
  39145. _this.__impliedStep = Math.pow(10, Math.floor(Math.log(Math.abs(_this.initialValue)) / Math.LN10)) / 10;
  39146. }
  39147. } else {
  39148. _this.__impliedStep = _this.__step;
  39149. }
  39150. _this.__precision = numDecimals(_this.__impliedStep);
  39151. return _this;
  39152. }
  39153. createClass(NumberController, [{
  39154. key: 'setValue',
  39155. value: function setValue(v) {
  39156. var _v = v;
  39157. if (this.__min !== undefined && _v < this.__min) {
  39158. _v = this.__min;
  39159. } else if (this.__max !== undefined && _v > this.__max) {
  39160. _v = this.__max;
  39161. }
  39162. if (this.__step !== undefined && _v % this.__step !== 0) {
  39163. _v = Math.round(_v / this.__step) * this.__step;
  39164. }
  39165. return get(NumberController.prototype.__proto__ || Object.getPrototypeOf(NumberController.prototype), 'setValue', this).call(this, _v);
  39166. }
  39167. }, {
  39168. key: 'min',
  39169. value: function min(minValue) {
  39170. this.__min = minValue;
  39171. return this;
  39172. }
  39173. }, {
  39174. key: 'max',
  39175. value: function max(maxValue) {
  39176. this.__max = maxValue;
  39177. return this;
  39178. }
  39179. }, {
  39180. key: 'step',
  39181. value: function step(stepValue) {
  39182. this.__step = stepValue;
  39183. this.__impliedStep = stepValue;
  39184. this.__precision = numDecimals(stepValue);
  39185. return this;
  39186. }
  39187. }]);
  39188. return NumberController;
  39189. }(Controller);
  39190. function roundToDecimal(value, decimals) {
  39191. var tenTo = Math.pow(10, decimals);
  39192. return Math.round(value * tenTo) / tenTo;
  39193. }
  39194. var NumberControllerBox = function (_NumberController) {
  39195. inherits(NumberControllerBox, _NumberController);
  39196. function NumberControllerBox(object, property, params) {
  39197. classCallCheck(this, NumberControllerBox);
  39198. var _this2 = possibleConstructorReturn(this, (NumberControllerBox.__proto__ || Object.getPrototypeOf(NumberControllerBox)).call(this, object, property, params));
  39199. _this2.__truncationSuspended = false;
  39200. var _this = _this2;
  39201. var prevY = void 0;
  39202. function onChange() {
  39203. var attempted = parseFloat(_this.__input.value);
  39204. if (!Common.isNaN(attempted)) {
  39205. _this.setValue(attempted);
  39206. }
  39207. }
  39208. function onFinish() {
  39209. if (_this.__onFinishChange) {
  39210. _this.__onFinishChange.call(_this, _this.getValue());
  39211. }
  39212. }
  39213. function onBlur() {
  39214. onFinish();
  39215. }
  39216. function onMouseDrag(e) {
  39217. var diff = prevY - e.clientY;
  39218. _this.setValue(_this.getValue() + diff * _this.__impliedStep);
  39219. prevY = e.clientY;
  39220. }
  39221. function onMouseUp() {
  39222. dom.unbind(window, 'mousemove', onMouseDrag);
  39223. dom.unbind(window, 'mouseup', onMouseUp);
  39224. onFinish();
  39225. }
  39226. function onMouseDown(e) {
  39227. dom.bind(window, 'mousemove', onMouseDrag);
  39228. dom.bind(window, 'mouseup', onMouseUp);
  39229. prevY = e.clientY;
  39230. }
  39231. _this2.__input = document.createElement('input');
  39232. _this2.__input.setAttribute('type', 'text');
  39233. dom.bind(_this2.__input, 'change', onChange);
  39234. dom.bind(_this2.__input, 'blur', onBlur);
  39235. dom.bind(_this2.__input, 'mousedown', onMouseDown);
  39236. dom.bind(_this2.__input, 'keydown', function (e) {
  39237. if (e.keyCode === 13) {
  39238. _this.__truncationSuspended = true;
  39239. this.blur();
  39240. _this.__truncationSuspended = false;
  39241. onFinish();
  39242. }
  39243. });
  39244. _this2.updateDisplay();
  39245. _this2.domElement.appendChild(_this2.__input);
  39246. return _this2;
  39247. }
  39248. createClass(NumberControllerBox, [{
  39249. key: 'updateDisplay',
  39250. value: function updateDisplay() {
  39251. this.__input.value = this.__truncationSuspended ? this.getValue() : roundToDecimal(this.getValue(), this.__precision);
  39252. return get(NumberControllerBox.prototype.__proto__ || Object.getPrototypeOf(NumberControllerBox.prototype), 'updateDisplay', this).call(this);
  39253. }
  39254. }]);
  39255. return NumberControllerBox;
  39256. }(NumberController);
  39257. function map(v, i1, i2, o1, o2) {
  39258. return o1 + (o2 - o1) * ((v - i1) / (i2 - i1));
  39259. }
  39260. var NumberControllerSlider = function (_NumberController) {
  39261. inherits(NumberControllerSlider, _NumberController);
  39262. function NumberControllerSlider(object, property, min, max, step) {
  39263. classCallCheck(this, NumberControllerSlider);
  39264. var _this2 = possibleConstructorReturn(this, (NumberControllerSlider.__proto__ || Object.getPrototypeOf(NumberControllerSlider)).call(this, object, property, {
  39265. min: min,
  39266. max: max,
  39267. step: step
  39268. }));
  39269. var _this = _this2;
  39270. _this2.__background = document.createElement('div');
  39271. _this2.__foreground = document.createElement('div');
  39272. dom.bind(_this2.__background, 'mousedown', onMouseDown);
  39273. dom.bind(_this2.__background, 'touchstart', onTouchStart);
  39274. dom.addClass(_this2.__background, 'slider');
  39275. dom.addClass(_this2.__foreground, 'slider-fg');
  39276. function onMouseDown(e) {
  39277. document.activeElement.blur();
  39278. dom.bind(window, 'mousemove', onMouseDrag);
  39279. dom.bind(window, 'mouseup', onMouseUp);
  39280. onMouseDrag(e);
  39281. }
  39282. function onMouseDrag(e) {
  39283. e.preventDefault();
  39284. var bgRect = _this.__background.getBoundingClientRect();
  39285. _this.setValue(map(e.clientX, bgRect.left, bgRect.right, _this.__min, _this.__max));
  39286. return false;
  39287. }
  39288. function onMouseUp() {
  39289. dom.unbind(window, 'mousemove', onMouseDrag);
  39290. dom.unbind(window, 'mouseup', onMouseUp);
  39291. if (_this.__onFinishChange) {
  39292. _this.__onFinishChange.call(_this, _this.getValue());
  39293. }
  39294. }
  39295. function onTouchStart(e) {
  39296. if (e.touches.length !== 1) {
  39297. return;
  39298. }
  39299. dom.bind(window, 'touchmove', onTouchMove);
  39300. dom.bind(window, 'touchend', onTouchEnd);
  39301. onTouchMove(e);
  39302. }
  39303. function onTouchMove(e) {
  39304. var clientX = e.touches[0].clientX;
  39305. var bgRect = _this.__background.getBoundingClientRect();
  39306. _this.setValue(map(clientX, bgRect.left, bgRect.right, _this.__min, _this.__max));
  39307. }
  39308. function onTouchEnd() {
  39309. dom.unbind(window, 'touchmove', onTouchMove);
  39310. dom.unbind(window, 'touchend', onTouchEnd);
  39311. if (_this.__onFinishChange) {
  39312. _this.__onFinishChange.call(_this, _this.getValue());
  39313. }
  39314. }
  39315. _this2.updateDisplay();
  39316. _this2.__background.appendChild(_this2.__foreground);
  39317. _this2.domElement.appendChild(_this2.__background);
  39318. return _this2;
  39319. }
  39320. createClass(NumberControllerSlider, [{
  39321. key: 'updateDisplay',
  39322. value: function updateDisplay() {
  39323. var pct = (this.getValue() - this.__min) / (this.__max - this.__min);
  39324. this.__foreground.style.width = pct * 100 + '%';
  39325. return get(NumberControllerSlider.prototype.__proto__ || Object.getPrototypeOf(NumberControllerSlider.prototype), 'updateDisplay', this).call(this);
  39326. }
  39327. }]);
  39328. return NumberControllerSlider;
  39329. }(NumberController);
  39330. var FunctionController = function (_Controller) {
  39331. inherits(FunctionController, _Controller);
  39332. function FunctionController(object, property, text) {
  39333. classCallCheck(this, FunctionController);
  39334. var _this2 = possibleConstructorReturn(this, (FunctionController.__proto__ || Object.getPrototypeOf(FunctionController)).call(this, object, property));
  39335. var _this = _this2;
  39336. _this2.__button = document.createElement('div');
  39337. _this2.__button.innerHTML = text === undefined ? 'Fire' : text;
  39338. dom.bind(_this2.__button, 'click', function (e) {
  39339. e.preventDefault();
  39340. _this.fire();
  39341. return false;
  39342. });
  39343. dom.addClass(_this2.__button, 'button');
  39344. _this2.domElement.appendChild(_this2.__button);
  39345. return _this2;
  39346. }
  39347. createClass(FunctionController, [{
  39348. key: 'fire',
  39349. value: function fire() {
  39350. if (this.__onChange) {
  39351. this.__onChange.call(this);
  39352. }
  39353. this.getValue().call(this.object);
  39354. if (this.__onFinishChange) {
  39355. this.__onFinishChange.call(this, this.getValue());
  39356. }
  39357. }
  39358. }]);
  39359. return FunctionController;
  39360. }(Controller);
  39361. var ColorController = function (_Controller) {
  39362. inherits(ColorController, _Controller);
  39363. function ColorController(object, property) {
  39364. classCallCheck(this, ColorController);
  39365. var _this2 = possibleConstructorReturn(this, (ColorController.__proto__ || Object.getPrototypeOf(ColorController)).call(this, object, property));
  39366. _this2.__color = new Color(_this2.getValue());
  39367. _this2.__temp = new Color(0);
  39368. var _this = _this2;
  39369. _this2.domElement = document.createElement('div');
  39370. dom.makeSelectable(_this2.domElement, false);
  39371. _this2.__selector = document.createElement('div');
  39372. _this2.__selector.className = 'selector';
  39373. _this2.__saturation_field = document.createElement('div');
  39374. _this2.__saturation_field.className = 'saturation-field';
  39375. _this2.__field_knob = document.createElement('div');
  39376. _this2.__field_knob.className = 'field-knob';
  39377. _this2.__field_knob_border = '2px solid ';
  39378. _this2.__hue_knob = document.createElement('div');
  39379. _this2.__hue_knob.className = 'hue-knob';
  39380. _this2.__hue_field = document.createElement('div');
  39381. _this2.__hue_field.className = 'hue-field';
  39382. _this2.__input = document.createElement('input');
  39383. _this2.__input.type = 'text';
  39384. _this2.__input_textShadow = '0 1px 1px ';
  39385. dom.bind(_this2.__input, 'keydown', function (e) {
  39386. if (e.keyCode === 13) {
  39387. onBlur.call(this);
  39388. }
  39389. });
  39390. dom.bind(_this2.__input, 'blur', onBlur);
  39391. dom.bind(_this2.__selector, 'mousedown', function () {
  39392. dom.addClass(this, 'drag').bind(window, 'mouseup', function () {
  39393. dom.removeClass(_this.__selector, 'drag');
  39394. });
  39395. });
  39396. dom.bind(_this2.__selector, 'touchstart', function () {
  39397. dom.addClass(this, 'drag').bind(window, 'touchend', function () {
  39398. dom.removeClass(_this.__selector, 'drag');
  39399. });
  39400. });
  39401. var valueField = document.createElement('div');
  39402. Common.extend(_this2.__selector.style, {
  39403. width: '122px',
  39404. height: '102px',
  39405. padding: '3px',
  39406. backgroundColor: '#222',
  39407. boxShadow: '0px 1px 3px rgba(0,0,0,0.3)'
  39408. });
  39409. Common.extend(_this2.__field_knob.style, {
  39410. position: 'absolute',
  39411. width: '12px',
  39412. height: '12px',
  39413. border: _this2.__field_knob_border + (_this2.__color.v < 0.5 ? '#fff' : '#000'),
  39414. boxShadow: '0px 1px 3px rgba(0,0,0,0.5)',
  39415. borderRadius: '12px',
  39416. zIndex: 1
  39417. });
  39418. Common.extend(_this2.__hue_knob.style, {
  39419. position: 'absolute',
  39420. width: '15px',
  39421. height: '2px',
  39422. borderRight: '4px solid #fff',
  39423. zIndex: 1
  39424. });
  39425. Common.extend(_this2.__saturation_field.style, {
  39426. width: '100px',
  39427. height: '100px',
  39428. border: '1px solid #555',
  39429. marginRight: '3px',
  39430. display: 'inline-block',
  39431. cursor: 'pointer'
  39432. });
  39433. Common.extend(valueField.style, {
  39434. width: '100%',
  39435. height: '100%',
  39436. background: 'none'
  39437. });
  39438. linearGradient(valueField, 'top', 'rgba(0,0,0,0)', '#000');
  39439. Common.extend(_this2.__hue_field.style, {
  39440. width: '15px',
  39441. height: '100px',
  39442. border: '1px solid #555',
  39443. cursor: 'ns-resize',
  39444. position: 'absolute',
  39445. top: '3px',
  39446. right: '3px'
  39447. });
  39448. hueGradient(_this2.__hue_field);
  39449. Common.extend(_this2.__input.style, {
  39450. outline: 'none',
  39451. textAlign: 'center',
  39452. color: '#fff',
  39453. border: 0,
  39454. fontWeight: 'bold',
  39455. textShadow: _this2.__input_textShadow + 'rgba(0,0,0,0.7)'
  39456. });
  39457. dom.bind(_this2.__saturation_field, 'mousedown', fieldDown);
  39458. dom.bind(_this2.__saturation_field, 'touchstart', fieldDown);
  39459. dom.bind(_this2.__field_knob, 'mousedown', fieldDown);
  39460. dom.bind(_this2.__field_knob, 'touchstart', fieldDown);
  39461. dom.bind(_this2.__hue_field, 'mousedown', fieldDownH);
  39462. dom.bind(_this2.__hue_field, 'touchstart', fieldDownH);
  39463. function fieldDown(e) {
  39464. setSV(e);
  39465. dom.bind(window, 'mousemove', setSV);
  39466. dom.bind(window, 'touchmove', setSV);
  39467. dom.bind(window, 'mouseup', fieldUpSV);
  39468. dom.bind(window, 'touchend', fieldUpSV);
  39469. }
  39470. function fieldDownH(e) {
  39471. setH(e);
  39472. dom.bind(window, 'mousemove', setH);
  39473. dom.bind(window, 'touchmove', setH);
  39474. dom.bind(window, 'mouseup', fieldUpH);
  39475. dom.bind(window, 'touchend', fieldUpH);
  39476. }
  39477. function fieldUpSV() {
  39478. dom.unbind(window, 'mousemove', setSV);
  39479. dom.unbind(window, 'touchmove', setSV);
  39480. dom.unbind(window, 'mouseup', fieldUpSV);
  39481. dom.unbind(window, 'touchend', fieldUpSV);
  39482. onFinish();
  39483. }
  39484. function fieldUpH() {
  39485. dom.unbind(window, 'mousemove', setH);
  39486. dom.unbind(window, 'touchmove', setH);
  39487. dom.unbind(window, 'mouseup', fieldUpH);
  39488. dom.unbind(window, 'touchend', fieldUpH);
  39489. onFinish();
  39490. }
  39491. function onBlur() {
  39492. var i = interpret(this.value);
  39493. if (i !== false) {
  39494. _this.__color.__state = i;
  39495. _this.setValue(_this.__color.toOriginal());
  39496. } else {
  39497. this.value = _this.__color.toString();
  39498. }
  39499. }
  39500. function onFinish() {
  39501. if (_this.__onFinishChange) {
  39502. _this.__onFinishChange.call(_this, _this.__color.toOriginal());
  39503. }
  39504. }
  39505. _this2.__saturation_field.appendChild(valueField);
  39506. _this2.__selector.appendChild(_this2.__field_knob);
  39507. _this2.__selector.appendChild(_this2.__saturation_field);
  39508. _this2.__selector.appendChild(_this2.__hue_field);
  39509. _this2.__hue_field.appendChild(_this2.__hue_knob);
  39510. _this2.domElement.appendChild(_this2.__input);
  39511. _this2.domElement.appendChild(_this2.__selector);
  39512. _this2.updateDisplay();
  39513. function setSV(e) {
  39514. if (e.type.indexOf('touch') === -1) {
  39515. e.preventDefault();
  39516. }
  39517. var fieldRect = _this.__saturation_field.getBoundingClientRect();
  39518. var _ref = e.touches && e.touches[0] || e,
  39519. clientX = _ref.clientX,
  39520. clientY = _ref.clientY;
  39521. var s = (clientX - fieldRect.left) / (fieldRect.right - fieldRect.left);
  39522. var v = 1 - (clientY - fieldRect.top) / (fieldRect.bottom - fieldRect.top);
  39523. if (v > 1) {
  39524. v = 1;
  39525. } else if (v < 0) {
  39526. v = 0;
  39527. }
  39528. if (s > 1) {
  39529. s = 1;
  39530. } else if (s < 0) {
  39531. s = 0;
  39532. }
  39533. _this.__color.v = v;
  39534. _this.__color.s = s;
  39535. _this.setValue(_this.__color.toOriginal());
  39536. return false;
  39537. }
  39538. function setH(e) {
  39539. if (e.type.indexOf('touch') === -1) {
  39540. e.preventDefault();
  39541. }
  39542. var fieldRect = _this.__hue_field.getBoundingClientRect();
  39543. var _ref2 = e.touches && e.touches[0] || e,
  39544. clientY = _ref2.clientY;
  39545. var h = 1 - (clientY - fieldRect.top) / (fieldRect.bottom - fieldRect.top);
  39546. if (h > 1) {
  39547. h = 1;
  39548. } else if (h < 0) {
  39549. h = 0;
  39550. }
  39551. _this.__color.h = h * 360;
  39552. _this.setValue(_this.__color.toOriginal());
  39553. return false;
  39554. }
  39555. return _this2;
  39556. }
  39557. createClass(ColorController, [{
  39558. key: 'updateDisplay',
  39559. value: function updateDisplay() {
  39560. var i = interpret(this.getValue());
  39561. if (i !== false) {
  39562. var mismatch = false;
  39563. Common.each(Color.COMPONENTS, function (component) {
  39564. if (!Common.isUndefined(i[component]) && !Common.isUndefined(this.__color.__state[component]) && i[component] !== this.__color.__state[component]) {
  39565. mismatch = true;
  39566. return {};
  39567. }
  39568. }, this);
  39569. if (mismatch) {
  39570. Common.extend(this.__color.__state, i);
  39571. }
  39572. }
  39573. Common.extend(this.__temp.__state, this.__color.__state);
  39574. this.__temp.a = 1;
  39575. var flip = this.__color.v < 0.5 || this.__color.s > 0.5 ? 255 : 0;
  39576. var _flip = 255 - flip;
  39577. Common.extend(this.__field_knob.style, {
  39578. marginLeft: 100 * this.__color.s - 7 + 'px',
  39579. marginTop: 100 * (1 - this.__color.v) - 7 + 'px',
  39580. backgroundColor: this.__temp.toHexString(),
  39581. border: this.__field_knob_border + 'rgb(' + flip + ',' + flip + ',' + flip + ')'
  39582. });
  39583. this.__hue_knob.style.marginTop = (1 - this.__color.h / 360) * 100 + 'px';
  39584. this.__temp.s = 1;
  39585. this.__temp.v = 1;
  39586. linearGradient(this.__saturation_field, 'left', '#fff', this.__temp.toHexString());
  39587. this.__input.value = this.__color.toString();
  39588. Common.extend(this.__input.style, {
  39589. backgroundColor: this.__color.toHexString(),
  39590. color: 'rgb(' + flip + ',' + flip + ',' + flip + ')',
  39591. textShadow: this.__input_textShadow + 'rgba(' + _flip + ',' + _flip + ',' + _flip + ',.7)'
  39592. });
  39593. }
  39594. }]);
  39595. return ColorController;
  39596. }(Controller);
  39597. var vendors = ['-moz-', '-o-', '-webkit-', '-ms-', ''];
  39598. function linearGradient(elem, x, a, b) {
  39599. elem.style.background = '';
  39600. Common.each(vendors, function (vendor) {
  39601. elem.style.cssText += 'background: ' + vendor + 'linear-gradient(' + x + ', ' + a + ' 0%, ' + b + ' 100%); ';
  39602. });
  39603. }
  39604. function hueGradient(elem) {
  39605. elem.style.background = '';
  39606. elem.style.cssText += 'background: -moz-linear-gradient(top, #ff0000 0%, #ff00ff 17%, #0000ff 34%, #00ffff 50%, #00ff00 67%, #ffff00 84%, #ff0000 100%);';
  39607. elem.style.cssText += 'background: -webkit-linear-gradient(top, #ff0000 0%,#ff00ff 17%,#0000ff 34%,#00ffff 50%,#00ff00 67%,#ffff00 84%,#ff0000 100%);';
  39608. elem.style.cssText += 'background: -o-linear-gradient(top, #ff0000 0%,#ff00ff 17%,#0000ff 34%,#00ffff 50%,#00ff00 67%,#ffff00 84%,#ff0000 100%);';
  39609. elem.style.cssText += 'background: -ms-linear-gradient(top, #ff0000 0%,#ff00ff 17%,#0000ff 34%,#00ffff 50%,#00ff00 67%,#ffff00 84%,#ff0000 100%);';
  39610. elem.style.cssText += 'background: linear-gradient(top, #ff0000 0%,#ff00ff 17%,#0000ff 34%,#00ffff 50%,#00ff00 67%,#ffff00 84%,#ff0000 100%);';
  39611. }
  39612. var css = {
  39613. load: function load(url, indoc) {
  39614. var doc = indoc || document;
  39615. var link = doc.createElement('link');
  39616. link.type = 'text/css';
  39617. link.rel = 'stylesheet';
  39618. link.href = url;
  39619. doc.getElementsByTagName('head')[0].appendChild(link);
  39620. },
  39621. inject: function inject(cssContent, indoc) {
  39622. var doc = indoc || document;
  39623. var injected = document.createElement('style');
  39624. injected.type = 'text/css';
  39625. injected.innerHTML = cssContent;
  39626. var head = doc.getElementsByTagName('head')[0];
  39627. try {
  39628. head.appendChild(injected);
  39629. } catch (e) {}
  39630. }
  39631. };
  39632. var saveDialogContents = "<div id=\"dg-save\" class=\"dg dialogue\">\n\n Here's the new load parameter for your <code>GUI</code>'s constructor:\n\n <textarea id=\"dg-new-constructor\"></textarea>\n\n <div id=\"dg-save-locally\">\n\n <input id=\"dg-local-storage\" type=\"checkbox\"/> Automatically save\n values to <code>localStorage</code> on exit.\n\n <div id=\"dg-local-explain\">The values saved to <code>localStorage</code> will\n override those passed to <code>dat.GUI</code>'s constructor. This makes it\n easier to work incrementally, but <code>localStorage</code> is fragile,\n and your friends may not see the same values you do.\n\n </div>\n\n </div>\n\n</div>";
  39633. var ControllerFactory = function ControllerFactory(object, property) {
  39634. var initialValue = object[property];
  39635. if (Common.isArray(arguments[2]) || Common.isObject(arguments[2])) {
  39636. return new OptionController(object, property, arguments[2]);
  39637. }
  39638. if (Common.isNumber(initialValue)) {
  39639. if (Common.isNumber(arguments[2]) && Common.isNumber(arguments[3])) {
  39640. if (Common.isNumber(arguments[4])) {
  39641. return new NumberControllerSlider(object, property, arguments[2], arguments[3], arguments[4]);
  39642. }
  39643. return new NumberControllerSlider(object, property, arguments[2], arguments[3]);
  39644. }
  39645. if (Common.isNumber(arguments[4])) {
  39646. return new NumberControllerBox(object, property, {
  39647. min: arguments[2],
  39648. max: arguments[3],
  39649. step: arguments[4]
  39650. });
  39651. }
  39652. return new NumberControllerBox(object, property, {
  39653. min: arguments[2],
  39654. max: arguments[3]
  39655. });
  39656. }
  39657. if (Common.isString(initialValue)) {
  39658. return new StringController(object, property);
  39659. }
  39660. if (Common.isFunction(initialValue)) {
  39661. return new FunctionController(object, property, '');
  39662. }
  39663. if (Common.isBoolean(initialValue)) {
  39664. return new BooleanController(object, property);
  39665. }
  39666. return null;
  39667. };
  39668. function requestAnimationFrame(callback) {
  39669. setTimeout(callback, 1000 / 60);
  39670. }
  39671. var requestAnimationFrame$1 = window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || requestAnimationFrame;
  39672. var CenteredDiv = function () {
  39673. function CenteredDiv() {
  39674. classCallCheck(this, CenteredDiv);
  39675. this.backgroundElement = document.createElement('div');
  39676. Common.extend(this.backgroundElement.style, {
  39677. backgroundColor: 'rgba(0,0,0,0.8)',
  39678. top: 0,
  39679. left: 0,
  39680. display: 'none',
  39681. zIndex: '1000',
  39682. opacity: 0,
  39683. WebkitTransition: 'opacity 0.2s linear',
  39684. transition: 'opacity 0.2s linear'
  39685. });
  39686. dom.makeFullscreen(this.backgroundElement);
  39687. this.backgroundElement.style.position = 'fixed';
  39688. this.domElement = document.createElement('div');
  39689. Common.extend(this.domElement.style, {
  39690. position: 'fixed',
  39691. display: 'none',
  39692. zIndex: '1001',
  39693. opacity: 0,
  39694. WebkitTransition: '-webkit-transform 0.2s ease-out, opacity 0.2s linear',
  39695. transition: 'transform 0.2s ease-out, opacity 0.2s linear'
  39696. });
  39697. document.body.appendChild(this.backgroundElement);
  39698. document.body.appendChild(this.domElement);
  39699. var _this = this;
  39700. dom.bind(this.backgroundElement, 'click', function () {
  39701. _this.hide();
  39702. });
  39703. }
  39704. createClass(CenteredDiv, [{
  39705. key: 'show',
  39706. value: function show() {
  39707. var _this = this;
  39708. this.backgroundElement.style.display = 'block';
  39709. this.domElement.style.display = 'block';
  39710. this.domElement.style.opacity = 0;
  39711. this.domElement.style.webkitTransform = 'scale(1.1)';
  39712. this.layout();
  39713. Common.defer(function () {
  39714. _this.backgroundElement.style.opacity = 1;
  39715. _this.domElement.style.opacity = 1;
  39716. _this.domElement.style.webkitTransform = 'scale(1)';
  39717. });
  39718. }
  39719. }, {
  39720. key: 'hide',
  39721. value: function hide() {
  39722. var _this = this;
  39723. var hide = function hide() {
  39724. _this.domElement.style.display = 'none';
  39725. _this.backgroundElement.style.display = 'none';
  39726. dom.unbind(_this.domElement, 'webkitTransitionEnd', hide);
  39727. dom.unbind(_this.domElement, 'transitionend', hide);
  39728. dom.unbind(_this.domElement, 'oTransitionEnd', hide);
  39729. };
  39730. dom.bind(this.domElement, 'webkitTransitionEnd', hide);
  39731. dom.bind(this.domElement, 'transitionend', hide);
  39732. dom.bind(this.domElement, 'oTransitionEnd', hide);
  39733. this.backgroundElement.style.opacity = 0;
  39734. this.domElement.style.opacity = 0;
  39735. this.domElement.style.webkitTransform = 'scale(1.1)';
  39736. }
  39737. }, {
  39738. key: 'layout',
  39739. value: function layout() {
  39740. this.domElement.style.left = window.innerWidth / 2 - dom.getWidth(this.domElement) / 2 + 'px';
  39741. this.domElement.style.top = window.innerHeight / 2 - dom.getHeight(this.domElement) / 2 + 'px';
  39742. }
  39743. }]);
  39744. return CenteredDiv;
  39745. }();
  39746. var styleSheet = ___$insertStyle(".dg ul{list-style:none;margin:0;padding:0;width:100%;clear:both}.dg.ac{position:fixed;top:0;left:0;right:0;height:0;z-index:0}.dg:not(.ac) .main{overflow:hidden}.dg.main{-webkit-transition:opacity .1s linear;-o-transition:opacity .1s linear;-moz-transition:opacity .1s linear;transition:opacity .1s linear}.dg.main.taller-than-window{overflow-y:auto}.dg.main.taller-than-window .close-button{opacity:1;margin-top:-1px;border-top:1px solid #2c2c2c}.dg.main ul.closed .close-button{opacity:1 !important}.dg.main:hover .close-button,.dg.main .close-button.drag{opacity:1}.dg.main .close-button{-webkit-transition:opacity .1s linear;-o-transition:opacity .1s linear;-moz-transition:opacity .1s linear;transition:opacity .1s linear;border:0;line-height:19px;height:20px;cursor:pointer;text-align:center;background-color:#000}.dg.main .close-button.close-top{position:relative}.dg.main .close-button.close-bottom{position:absolute}.dg.main .close-button:hover{background-color:#111}.dg.a{float:right;margin-right:15px;overflow-y:visible}.dg.a.has-save>ul.close-top{margin-top:0}.dg.a.has-save>ul.close-bottom{margin-top:27px}.dg.a.has-save>ul.closed{margin-top:0}.dg.a .save-row{top:0;z-index:1002}.dg.a .save-row.close-top{position:relative}.dg.a .save-row.close-bottom{position:fixed}.dg li{-webkit-transition:height .1s ease-out;-o-transition:height .1s ease-out;-moz-transition:height .1s ease-out;transition:height .1s ease-out;-webkit-transition:overflow .1s linear;-o-transition:overflow .1s linear;-moz-transition:overflow .1s linear;transition:overflow .1s linear}.dg li:not(.folder){cursor:auto;height:27px;line-height:27px;padding:0 4px 0 5px}.dg li.folder{padding:0;border-left:4px solid rgba(0,0,0,0)}.dg li.title{cursor:pointer;margin-left:-4px}.dg .closed li:not(.title),.dg .closed ul li,.dg .closed ul li>*{height:0;overflow:hidden;border:0}.dg .cr{clear:both;padding-left:3px;height:27px;overflow:hidden}.dg .property-name{cursor:default;float:left;clear:left;width:40%;overflow:hidden;text-overflow:ellipsis}.dg .c{float:left;width:60%;position:relative}.dg .c input[type=text]{border:0;margin-top:4px;padding:3px;width:100%;float:right}.dg .has-slider input[type=text]{width:30%;margin-left:0}.dg .slider{float:left;width:66%;margin-left:-5px;margin-right:0;height:19px;margin-top:4px}.dg .slider-fg{height:100%}.dg .c input[type=checkbox]{margin-top:7px}.dg .c select{margin-top:5px}.dg .cr.function,.dg .cr.function .property-name,.dg .cr.function *,.dg .cr.boolean,.dg .cr.boolean *{cursor:pointer}.dg .cr.color{overflow:visible}.dg .selector{display:none;position:absolute;margin-left:-9px;margin-top:23px;z-index:10}.dg .c:hover .selector,.dg .selector.drag{display:block}.dg li.save-row{padding:0}.dg li.save-row .button{display:inline-block;padding:0px 6px}.dg.dialogue{background-color:#222;width:460px;padding:15px;font-size:13px;line-height:15px}#dg-new-constructor{padding:10px;color:#222;font-family:Monaco, monospace;font-size:10px;border:0;resize:none;box-shadow:inset 1px 1px 1px #888;word-wrap:break-word;margin:12px 0;display:block;width:440px;overflow-y:scroll;height:100px;position:relative}#dg-local-explain{display:none;font-size:11px;line-height:17px;border-radius:3px;background-color:#333;padding:8px;margin-top:10px}#dg-local-explain code{font-size:10px}#dat-gui-save-locally{display:none}.dg{color:#eee;font:11px 'Lucida Grande', sans-serif;text-shadow:0 -1px 0 #111}.dg.main::-webkit-scrollbar{width:5px;background:#1a1a1a}.dg.main::-webkit-scrollbar-corner{height:0;display:none}.dg.main::-webkit-scrollbar-thumb{border-radius:5px;background:#676767}.dg li:not(.folder){background:#1a1a1a;border-bottom:1px solid #2c2c2c}.dg li.save-row{line-height:25px;background:#dad5cb;border:0}.dg li.save-row select{margin-left:5px;width:108px}.dg li.save-row .button{margin-left:5px;margin-top:1px;border-radius:2px;font-size:9px;line-height:7px;padding:4px 4px 5px 4px;background:#c5bdad;color:#fff;text-shadow:0 1px 0 #b0a58f;box-shadow:0 -1px 0 #b0a58f;cursor:pointer}.dg li.save-row .button.gears{background:#c5bdad url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAsAAAANCAYAAAB/9ZQ7AAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAQJJREFUeNpiYKAU/P//PwGIC/ApCABiBSAW+I8AClAcgKxQ4T9hoMAEUrxx2QSGN6+egDX+/vWT4e7N82AMYoPAx/evwWoYoSYbACX2s7KxCxzcsezDh3evFoDEBYTEEqycggWAzA9AuUSQQgeYPa9fPv6/YWm/Acx5IPb7ty/fw+QZblw67vDs8R0YHyQhgObx+yAJkBqmG5dPPDh1aPOGR/eugW0G4vlIoTIfyFcA+QekhhHJhPdQxbiAIguMBTQZrPD7108M6roWYDFQiIAAv6Aow/1bFwXgis+f2LUAynwoIaNcz8XNx3Dl7MEJUDGQpx9gtQ8YCueB+D26OECAAQDadt7e46D42QAAAABJRU5ErkJggg==) 2px 1px no-repeat;height:7px;width:8px}.dg li.save-row .button:hover{background-color:#bab19e;box-shadow:0 -1px 0 #b0a58f}.dg li.folder{border-bottom:0}.dg li.title{padding-left:16px;background:#000 url(data:image/gif;base64,R0lGODlhBQAFAJEAAP////Pz8////////yH5BAEAAAIALAAAAAAFAAUAAAIIlI+hKgFxoCgAOw==) 6px 10px no-repeat;cursor:pointer;border-bottom:1px solid rgba(255,255,255,0.2)}.dg .closed li.title{background-image:url(data:image/gif;base64,R0lGODlhBQAFAJEAAP////Pz8////////yH5BAEAAAIALAAAAAAFAAUAAAIIlGIWqMCbWAEAOw==)}.dg .cr.boolean{border-left:3px solid #806787}.dg .cr.color{border-left:3px solid}.dg .cr.function{border-left:3px solid #e61d5f}.dg .cr.number{border-left:3px solid #2FA1D6}.dg .cr.number input[type=text]{color:#2FA1D6}.dg .cr.string{border-left:3px solid #1ed36f}.dg .cr.string input[type=text]{color:#1ed36f}.dg .cr.function:hover,.dg .cr.boolean:hover{background:#111}.dg .c input[type=text]{background:#303030;outline:none}.dg .c input[type=text]:hover{background:#3c3c3c}.dg .c input[type=text]:focus{background:#494949;color:#fff}.dg .c .slider{background:#303030;cursor:ew-resize}.dg .c .slider-fg{background:#2FA1D6;max-width:100%}.dg .c .slider:hover{background:#3c3c3c}.dg .c .slider:hover .slider-fg{background:#44abda}\n");
  39747. css.inject(styleSheet);
  39748. var CSS_NAMESPACE = 'dg';
  39749. var HIDE_KEY_CODE = 72;
  39750. var CLOSE_BUTTON_HEIGHT = 20;
  39751. var DEFAULT_DEFAULT_PRESET_NAME = 'Default';
  39752. var SUPPORTS_LOCAL_STORAGE = function () {
  39753. try {
  39754. return !!window.localStorage;
  39755. } catch (e) {
  39756. return false;
  39757. }
  39758. }();
  39759. var SAVE_DIALOGUE = void 0;
  39760. var autoPlaceVirgin = true;
  39761. var autoPlaceContainer = void 0;
  39762. var hide = false;
  39763. var hideableGuis = [];
  39764. var GUI = function GUI(pars) {
  39765. var _this = this;
  39766. var params = pars || {};
  39767. this.domElement = document.createElement('div');
  39768. this.__ul = document.createElement('ul');
  39769. this.domElement.appendChild(this.__ul);
  39770. dom.addClass(this.domElement, CSS_NAMESPACE);
  39771. this.__folders = {};
  39772. this.__controllers = [];
  39773. this.__rememberedObjects = [];
  39774. this.__rememberedObjectIndecesToControllers = [];
  39775. this.__listening = [];
  39776. params = Common.defaults(params, {
  39777. closeOnTop: false,
  39778. autoPlace: true,
  39779. width: GUI.DEFAULT_WIDTH
  39780. });
  39781. params = Common.defaults(params, {
  39782. resizable: params.autoPlace,
  39783. hideable: params.autoPlace
  39784. });
  39785. if (!Common.isUndefined(params.load)) {
  39786. if (params.preset) {
  39787. params.load.preset = params.preset;
  39788. }
  39789. } else {
  39790. params.load = {
  39791. preset: DEFAULT_DEFAULT_PRESET_NAME
  39792. };
  39793. }
  39794. if (Common.isUndefined(params.parent) && params.hideable) {
  39795. hideableGuis.push(this);
  39796. }
  39797. params.resizable = Common.isUndefined(params.parent) && params.resizable;
  39798. if (params.autoPlace && Common.isUndefined(params.scrollable)) {
  39799. params.scrollable = true;
  39800. }
  39801. var useLocalStorage = SUPPORTS_LOCAL_STORAGE && localStorage.getItem(getLocalStorageHash(this, 'isLocal')) === 'true';
  39802. var saveToLocalStorage = void 0;
  39803. var titleRow = void 0;
  39804. Object.defineProperties(this, {
  39805. parent: {
  39806. get: function get$$1() {
  39807. return params.parent;
  39808. }
  39809. },
  39810. scrollable: {
  39811. get: function get$$1() {
  39812. return params.scrollable;
  39813. }
  39814. },
  39815. autoPlace: {
  39816. get: function get$$1() {
  39817. return params.autoPlace;
  39818. }
  39819. },
  39820. closeOnTop: {
  39821. get: function get$$1() {
  39822. return params.closeOnTop;
  39823. }
  39824. },
  39825. preset: {
  39826. get: function get$$1() {
  39827. if (_this.parent) {
  39828. return _this.getRoot().preset;
  39829. }
  39830. return params.load.preset;
  39831. },
  39832. set: function set$$1(v) {
  39833. if (_this.parent) {
  39834. _this.getRoot().preset = v;
  39835. } else {
  39836. params.load.preset = v;
  39837. }
  39838. setPresetSelectIndex(this);
  39839. _this.revert();
  39840. }
  39841. },
  39842. width: {
  39843. get: function get$$1() {
  39844. return params.width;
  39845. },
  39846. set: function set$$1(v) {
  39847. params.width = v;
  39848. setWidth(_this, v);
  39849. }
  39850. },
  39851. name: {
  39852. get: function get$$1() {
  39853. return params.name;
  39854. },
  39855. set: function set$$1(v) {
  39856. params.name = v;
  39857. if (titleRow) {
  39858. titleRow.innerHTML = params.name;
  39859. }
  39860. }
  39861. },
  39862. closed: {
  39863. get: function get$$1() {
  39864. return params.closed;
  39865. },
  39866. set: function set$$1(v) {
  39867. params.closed = v;
  39868. if (params.closed) {
  39869. dom.addClass(_this.__ul, GUI.CLASS_CLOSED);
  39870. } else {
  39871. dom.removeClass(_this.__ul, GUI.CLASS_CLOSED);
  39872. }
  39873. this.onResize();
  39874. if (_this.__closeButton) {
  39875. _this.__closeButton.innerHTML = v ? GUI.TEXT_OPEN : GUI.TEXT_CLOSED;
  39876. }
  39877. }
  39878. },
  39879. load: {
  39880. get: function get$$1() {
  39881. return params.load;
  39882. }
  39883. },
  39884. useLocalStorage: {
  39885. get: function get$$1() {
  39886. return useLocalStorage;
  39887. },
  39888. set: function set$$1(bool) {
  39889. if (SUPPORTS_LOCAL_STORAGE) {
  39890. useLocalStorage = bool;
  39891. if (bool) {
  39892. dom.bind(window, 'unload', saveToLocalStorage);
  39893. } else {
  39894. dom.unbind(window, 'unload', saveToLocalStorage);
  39895. }
  39896. localStorage.setItem(getLocalStorageHash(_this, 'isLocal'), bool);
  39897. }
  39898. }
  39899. }
  39900. });
  39901. if (Common.isUndefined(params.parent)) {
  39902. this.closed = params.closed || false;
  39903. dom.addClass(this.domElement, GUI.CLASS_MAIN);
  39904. dom.makeSelectable(this.domElement, false);
  39905. if (SUPPORTS_LOCAL_STORAGE) {
  39906. if (useLocalStorage) {
  39907. _this.useLocalStorage = true;
  39908. var savedGui = localStorage.getItem(getLocalStorageHash(this, 'gui'));
  39909. if (savedGui) {
  39910. params.load = JSON.parse(savedGui);
  39911. }
  39912. }
  39913. }
  39914. this.__closeButton = document.createElement('div');
  39915. this.__closeButton.innerHTML = GUI.TEXT_CLOSED;
  39916. dom.addClass(this.__closeButton, GUI.CLASS_CLOSE_BUTTON);
  39917. if (params.closeOnTop) {
  39918. dom.addClass(this.__closeButton, GUI.CLASS_CLOSE_TOP);
  39919. this.domElement.insertBefore(this.__closeButton, this.domElement.childNodes[0]);
  39920. } else {
  39921. dom.addClass(this.__closeButton, GUI.CLASS_CLOSE_BOTTOM);
  39922. this.domElement.appendChild(this.__closeButton);
  39923. }
  39924. dom.bind(this.__closeButton, 'click', function () {
  39925. _this.closed = !_this.closed;
  39926. });
  39927. } else {
  39928. if (params.closed === undefined) {
  39929. params.closed = true;
  39930. }
  39931. var titleRowName = document.createTextNode(params.name);
  39932. dom.addClass(titleRowName, 'controller-name');
  39933. titleRow = addRow(_this, titleRowName);
  39934. var onClickTitle = function onClickTitle(e) {
  39935. e.preventDefault();
  39936. _this.closed = !_this.closed;
  39937. return false;
  39938. };
  39939. dom.addClass(this.__ul, GUI.CLASS_CLOSED);
  39940. dom.addClass(titleRow, 'title');
  39941. dom.bind(titleRow, 'click', onClickTitle);
  39942. if (!params.closed) {
  39943. this.closed = false;
  39944. }
  39945. }
  39946. if (params.autoPlace) {
  39947. if (Common.isUndefined(params.parent)) {
  39948. if (autoPlaceVirgin) {
  39949. autoPlaceContainer = document.createElement('div');
  39950. dom.addClass(autoPlaceContainer, CSS_NAMESPACE);
  39951. dom.addClass(autoPlaceContainer, GUI.CLASS_AUTO_PLACE_CONTAINER);
  39952. document.body.appendChild(autoPlaceContainer);
  39953. autoPlaceVirgin = false;
  39954. }
  39955. autoPlaceContainer.appendChild(this.domElement);
  39956. dom.addClass(this.domElement, GUI.CLASS_AUTO_PLACE);
  39957. }
  39958. if (!this.parent) {
  39959. setWidth(_this, params.width);
  39960. }
  39961. }
  39962. this.__resizeHandler = function () {
  39963. _this.onResizeDebounced();
  39964. };
  39965. dom.bind(window, 'resize', this.__resizeHandler);
  39966. dom.bind(this.__ul, 'webkitTransitionEnd', this.__resizeHandler);
  39967. dom.bind(this.__ul, 'transitionend', this.__resizeHandler);
  39968. dom.bind(this.__ul, 'oTransitionEnd', this.__resizeHandler);
  39969. this.onResize();
  39970. if (params.resizable) {
  39971. addResizeHandle(this);
  39972. }
  39973. saveToLocalStorage = function saveToLocalStorage() {
  39974. if (SUPPORTS_LOCAL_STORAGE && localStorage.getItem(getLocalStorageHash(_this, 'isLocal')) === 'true') {
  39975. localStorage.setItem(getLocalStorageHash(_this, 'gui'), JSON.stringify(_this.getSaveObject()));
  39976. }
  39977. };
  39978. this.saveToLocalStorageIfPossible = saveToLocalStorage;
  39979. function resetWidth() {
  39980. var root = _this.getRoot();
  39981. root.width += 1;
  39982. Common.defer(function () {
  39983. root.width -= 1;
  39984. });
  39985. }
  39986. if (!params.parent) {
  39987. resetWidth();
  39988. }
  39989. };
  39990. GUI.toggleHide = function () {
  39991. hide = !hide;
  39992. Common.each(hideableGuis, function (gui) {
  39993. gui.domElement.style.display = hide ? 'none' : '';
  39994. });
  39995. };
  39996. GUI.CLASS_AUTO_PLACE = 'a';
  39997. GUI.CLASS_AUTO_PLACE_CONTAINER = 'ac';
  39998. GUI.CLASS_MAIN = 'main';
  39999. GUI.CLASS_CONTROLLER_ROW = 'cr';
  40000. GUI.CLASS_TOO_TALL = 'taller-than-window';
  40001. GUI.CLASS_CLOSED = 'closed';
  40002. GUI.CLASS_CLOSE_BUTTON = 'close-button';
  40003. GUI.CLASS_CLOSE_TOP = 'close-top';
  40004. GUI.CLASS_CLOSE_BOTTOM = 'close-bottom';
  40005. GUI.CLASS_DRAG = 'drag';
  40006. GUI.DEFAULT_WIDTH = 245;
  40007. GUI.TEXT_CLOSED = 'Close Controls';
  40008. GUI.TEXT_OPEN = 'Open Controls';
  40009. GUI._keydownHandler = function (e) {
  40010. if (document.activeElement.type !== 'text' && (e.which === HIDE_KEY_CODE || e.keyCode === HIDE_KEY_CODE)) {
  40011. GUI.toggleHide();
  40012. }
  40013. };
  40014. dom.bind(window, 'keydown', GUI._keydownHandler, false);
  40015. Common.extend(GUI.prototype, {
  40016. add: function add(object, property) {
  40017. return _add(this, object, property, {
  40018. factoryArgs: Array.prototype.slice.call(arguments, 2)
  40019. });
  40020. },
  40021. addColor: function addColor(object, property) {
  40022. return _add(this, object, property, {
  40023. color: true
  40024. });
  40025. },
  40026. remove: function remove(controller) {
  40027. this.__ul.removeChild(controller.__li);
  40028. this.__controllers.splice(this.__controllers.indexOf(controller), 1);
  40029. var _this = this;
  40030. Common.defer(function () {
  40031. _this.onResize();
  40032. });
  40033. },
  40034. destroy: function destroy() {
  40035. if (this.parent) {
  40036. throw new Error('Only the root GUI should be removed with .destroy(). ' + 'For subfolders, use gui.removeFolder(folder) instead.');
  40037. }
  40038. if (this.autoPlace) {
  40039. autoPlaceContainer.removeChild(this.domElement);
  40040. }
  40041. var _this = this;
  40042. Common.each(this.__folders, function (subfolder) {
  40043. _this.removeFolder(subfolder);
  40044. });
  40045. dom.unbind(window, 'keydown', GUI._keydownHandler, false);
  40046. removeListeners(this);
  40047. },
  40048. addFolder: function addFolder(name) {
  40049. if (this.__folders[name] !== undefined) {
  40050. throw new Error('You already have a folder in this GUI by the' + ' name "' + name + '"');
  40051. }
  40052. var newGuiParams = {
  40053. name: name,
  40054. parent: this
  40055. };
  40056. newGuiParams.autoPlace = this.autoPlace;
  40057. if (this.load && this.load.folders && this.load.folders[name]) {
  40058. newGuiParams.closed = this.load.folders[name].closed;
  40059. newGuiParams.load = this.load.folders[name];
  40060. }
  40061. var gui = new GUI(newGuiParams);
  40062. this.__folders[name] = gui;
  40063. var li = addRow(this, gui.domElement);
  40064. dom.addClass(li, 'folder');
  40065. return gui;
  40066. },
  40067. removeFolder: function removeFolder(folder) {
  40068. this.__ul.removeChild(folder.domElement.parentElement);
  40069. delete this.__folders[folder.name];
  40070. if (this.load && this.load.folders && this.load.folders[folder.name]) {
  40071. delete this.load.folders[folder.name];
  40072. }
  40073. removeListeners(folder);
  40074. var _this = this;
  40075. Common.each(folder.__folders, function (subfolder) {
  40076. folder.removeFolder(subfolder);
  40077. });
  40078. Common.defer(function () {
  40079. _this.onResize();
  40080. });
  40081. },
  40082. open: function open() {
  40083. this.closed = false;
  40084. },
  40085. close: function close() {
  40086. this.closed = true;
  40087. },
  40088. hide: function hide() {
  40089. this.domElement.style.display = 'none';
  40090. },
  40091. show: function show() {
  40092. this.domElement.style.display = '';
  40093. },
  40094. onResize: function onResize() {
  40095. var root = this.getRoot();
  40096. if (root.scrollable) {
  40097. var top = dom.getOffset(root.__ul).top;
  40098. var h = 0;
  40099. Common.each(root.__ul.childNodes, function (node) {
  40100. if (!(root.autoPlace && node === root.__save_row)) {
  40101. h += dom.getHeight(node);
  40102. }
  40103. });
  40104. if (window.innerHeight - top - CLOSE_BUTTON_HEIGHT < h) {
  40105. dom.addClass(root.domElement, GUI.CLASS_TOO_TALL);
  40106. root.__ul.style.height = window.innerHeight - top - CLOSE_BUTTON_HEIGHT + 'px';
  40107. } else {
  40108. dom.removeClass(root.domElement, GUI.CLASS_TOO_TALL);
  40109. root.__ul.style.height = 'auto';
  40110. }
  40111. }
  40112. if (root.__resize_handle) {
  40113. Common.defer(function () {
  40114. root.__resize_handle.style.height = root.__ul.offsetHeight + 'px';
  40115. });
  40116. }
  40117. if (root.__closeButton) {
  40118. root.__closeButton.style.width = root.width + 'px';
  40119. }
  40120. },
  40121. onResizeDebounced: Common.debounce(function () {
  40122. this.onResize();
  40123. }, 50),
  40124. remember: function remember() {
  40125. if (Common.isUndefined(SAVE_DIALOGUE)) {
  40126. SAVE_DIALOGUE = new CenteredDiv();
  40127. SAVE_DIALOGUE.domElement.innerHTML = saveDialogContents;
  40128. }
  40129. if (this.parent) {
  40130. throw new Error('You can only call remember on a top level GUI.');
  40131. }
  40132. var _this = this;
  40133. Common.each(Array.prototype.slice.call(arguments), function (object) {
  40134. if (_this.__rememberedObjects.length === 0) {
  40135. addSaveMenu(_this);
  40136. }
  40137. if (_this.__rememberedObjects.indexOf(object) === -1) {
  40138. _this.__rememberedObjects.push(object);
  40139. }
  40140. });
  40141. if (this.autoPlace) {
  40142. setWidth(this, this.width);
  40143. }
  40144. },
  40145. getRoot: function getRoot() {
  40146. var gui = this;
  40147. while (gui.parent) {
  40148. gui = gui.parent;
  40149. }
  40150. return gui;
  40151. },
  40152. getSaveObject: function getSaveObject() {
  40153. var toReturn = this.load;
  40154. toReturn.closed = this.closed;
  40155. if (this.__rememberedObjects.length > 0) {
  40156. toReturn.preset = this.preset;
  40157. if (!toReturn.remembered) {
  40158. toReturn.remembered = {};
  40159. }
  40160. toReturn.remembered[this.preset] = getCurrentPreset(this);
  40161. }
  40162. toReturn.folders = {};
  40163. Common.each(this.__folders, function (element, key) {
  40164. toReturn.folders[key] = element.getSaveObject();
  40165. });
  40166. return toReturn;
  40167. },
  40168. save: function save() {
  40169. if (!this.load.remembered) {
  40170. this.load.remembered = {};
  40171. }
  40172. this.load.remembered[this.preset] = getCurrentPreset(this);
  40173. markPresetModified(this, false);
  40174. this.saveToLocalStorageIfPossible();
  40175. },
  40176. saveAs: function saveAs(presetName) {
  40177. if (!this.load.remembered) {
  40178. this.load.remembered = {};
  40179. this.load.remembered[DEFAULT_DEFAULT_PRESET_NAME] = getCurrentPreset(this, true);
  40180. }
  40181. this.load.remembered[presetName] = getCurrentPreset(this);
  40182. this.preset = presetName;
  40183. addPresetOption(this, presetName, true);
  40184. this.saveToLocalStorageIfPossible();
  40185. },
  40186. revert: function revert(gui) {
  40187. Common.each(this.__controllers, function (controller) {
  40188. if (!this.getRoot().load.remembered) {
  40189. controller.setValue(controller.initialValue);
  40190. } else {
  40191. recallSavedValue(gui || this.getRoot(), controller);
  40192. }
  40193. if (controller.__onFinishChange) {
  40194. controller.__onFinishChange.call(controller, controller.getValue());
  40195. }
  40196. }, this);
  40197. Common.each(this.__folders, function (folder) {
  40198. folder.revert(folder);
  40199. });
  40200. if (!gui) {
  40201. markPresetModified(this.getRoot(), false);
  40202. }
  40203. },
  40204. listen: function listen(controller) {
  40205. var init = this.__listening.length === 0;
  40206. this.__listening.push(controller);
  40207. if (init) {
  40208. updateDisplays(this.__listening);
  40209. }
  40210. },
  40211. updateDisplay: function updateDisplay() {
  40212. Common.each(this.__controllers, function (controller) {
  40213. controller.updateDisplay();
  40214. });
  40215. Common.each(this.__folders, function (folder) {
  40216. folder.updateDisplay();
  40217. });
  40218. }
  40219. });
  40220. function addRow(gui, newDom, liBefore) {
  40221. var li = document.createElement('li');
  40222. if (newDom) {
  40223. li.appendChild(newDom);
  40224. }
  40225. if (liBefore) {
  40226. gui.__ul.insertBefore(li, liBefore);
  40227. } else {
  40228. gui.__ul.appendChild(li);
  40229. }
  40230. gui.onResize();
  40231. return li;
  40232. }
  40233. function removeListeners(gui) {
  40234. dom.unbind(window, 'resize', gui.__resizeHandler);
  40235. if (gui.saveToLocalStorageIfPossible) {
  40236. dom.unbind(window, 'unload', gui.saveToLocalStorageIfPossible);
  40237. }
  40238. }
  40239. function markPresetModified(gui, modified) {
  40240. var opt = gui.__preset_select[gui.__preset_select.selectedIndex];
  40241. if (modified) {
  40242. opt.innerHTML = opt.value + '*';
  40243. } else {
  40244. opt.innerHTML = opt.value;
  40245. }
  40246. }
  40247. function augmentController(gui, li, controller) {
  40248. controller.__li = li;
  40249. controller.__gui = gui;
  40250. Common.extend(controller, {
  40251. options: function options(_options) {
  40252. if (arguments.length > 1) {
  40253. var nextSibling = controller.__li.nextElementSibling;
  40254. controller.remove();
  40255. return _add(gui, controller.object, controller.property, {
  40256. before: nextSibling,
  40257. factoryArgs: [Common.toArray(arguments)]
  40258. });
  40259. }
  40260. if (Common.isArray(_options) || Common.isObject(_options)) {
  40261. var _nextSibling = controller.__li.nextElementSibling;
  40262. controller.remove();
  40263. return _add(gui, controller.object, controller.property, {
  40264. before: _nextSibling,
  40265. factoryArgs: [_options]
  40266. });
  40267. }
  40268. },
  40269. name: function name(_name) {
  40270. controller.__li.firstElementChild.firstElementChild.innerHTML = _name;
  40271. return controller;
  40272. },
  40273. listen: function listen() {
  40274. controller.__gui.listen(controller);
  40275. return controller;
  40276. },
  40277. remove: function remove() {
  40278. controller.__gui.remove(controller);
  40279. return controller;
  40280. }
  40281. });
  40282. if (controller instanceof NumberControllerSlider) {
  40283. var box = new NumberControllerBox(controller.object, controller.property, {
  40284. min: controller.__min,
  40285. max: controller.__max,
  40286. step: controller.__step
  40287. });
  40288. Common.each(['updateDisplay', 'onChange', 'onFinishChange', 'step', 'min', 'max'], function (method) {
  40289. var pc = controller[method];
  40290. var pb = box[method];
  40291. controller[method] = box[method] = function () {
  40292. var args = Array.prototype.slice.call(arguments);
  40293. pb.apply(box, args);
  40294. return pc.apply(controller, args);
  40295. };
  40296. });
  40297. dom.addClass(li, 'has-slider');
  40298. controller.domElement.insertBefore(box.domElement, controller.domElement.firstElementChild);
  40299. } else if (controller instanceof NumberControllerBox) {
  40300. var r = function r(returned) {
  40301. if (Common.isNumber(controller.__min) && Common.isNumber(controller.__max)) {
  40302. var oldName = controller.__li.firstElementChild.firstElementChild.innerHTML;
  40303. var wasListening = controller.__gui.__listening.indexOf(controller) > -1;
  40304. controller.remove();
  40305. var newController = _add(gui, controller.object, controller.property, {
  40306. before: controller.__li.nextElementSibling,
  40307. factoryArgs: [controller.__min, controller.__max, controller.__step]
  40308. });
  40309. newController.name(oldName);
  40310. if (wasListening) newController.listen();
  40311. return newController;
  40312. }
  40313. return returned;
  40314. };
  40315. controller.min = Common.compose(r, controller.min);
  40316. controller.max = Common.compose(r, controller.max);
  40317. } else if (controller instanceof BooleanController) {
  40318. dom.bind(li, 'click', function () {
  40319. dom.fakeEvent(controller.__checkbox, 'click');
  40320. });
  40321. dom.bind(controller.__checkbox, 'click', function (e) {
  40322. e.stopPropagation();
  40323. });
  40324. } else if (controller instanceof FunctionController) {
  40325. dom.bind(li, 'click', function () {
  40326. dom.fakeEvent(controller.__button, 'click');
  40327. });
  40328. dom.bind(li, 'mouseover', function () {
  40329. dom.addClass(controller.__button, 'hover');
  40330. });
  40331. dom.bind(li, 'mouseout', function () {
  40332. dom.removeClass(controller.__button, 'hover');
  40333. });
  40334. } else if (controller instanceof ColorController) {
  40335. dom.addClass(li, 'color');
  40336. controller.updateDisplay = Common.compose(function (val) {
  40337. li.style.borderLeftColor = controller.__color.toString();
  40338. return val;
  40339. }, controller.updateDisplay);
  40340. controller.updateDisplay();
  40341. }
  40342. controller.setValue = Common.compose(function (val) {
  40343. if (gui.getRoot().__preset_select && controller.isModified()) {
  40344. markPresetModified(gui.getRoot(), true);
  40345. }
  40346. return val;
  40347. }, controller.setValue);
  40348. }
  40349. function recallSavedValue(gui, controller) {
  40350. var root = gui.getRoot();
  40351. var matchedIndex = root.__rememberedObjects.indexOf(controller.object);
  40352. if (matchedIndex !== -1) {
  40353. var controllerMap = root.__rememberedObjectIndecesToControllers[matchedIndex];
  40354. if (controllerMap === undefined) {
  40355. controllerMap = {};
  40356. root.__rememberedObjectIndecesToControllers[matchedIndex] = controllerMap;
  40357. }
  40358. controllerMap[controller.property] = controller;
  40359. if (root.load && root.load.remembered) {
  40360. var presetMap = root.load.remembered;
  40361. var preset = void 0;
  40362. if (presetMap[gui.preset]) {
  40363. preset = presetMap[gui.preset];
  40364. } else if (presetMap[DEFAULT_DEFAULT_PRESET_NAME]) {
  40365. preset = presetMap[DEFAULT_DEFAULT_PRESET_NAME];
  40366. } else {
  40367. return;
  40368. }
  40369. if (preset[matchedIndex] && preset[matchedIndex][controller.property] !== undefined) {
  40370. var value = preset[matchedIndex][controller.property];
  40371. controller.initialValue = value;
  40372. controller.setValue(value);
  40373. }
  40374. }
  40375. }
  40376. }
  40377. function _add(gui, object, property, params) {
  40378. if (object[property] === undefined) {
  40379. throw new Error('Object "' + object + '" has no property "' + property + '"');
  40380. }
  40381. var controller = void 0;
  40382. if (params.color) {
  40383. controller = new ColorController(object, property);
  40384. } else {
  40385. var factoryArgs = [object, property].concat(params.factoryArgs);
  40386. controller = ControllerFactory.apply(gui, factoryArgs);
  40387. }
  40388. if (params.before instanceof Controller) {
  40389. params.before = params.before.__li;
  40390. }
  40391. recallSavedValue(gui, controller);
  40392. dom.addClass(controller.domElement, 'c');
  40393. var name = document.createElement('span');
  40394. dom.addClass(name, 'property-name');
  40395. name.innerHTML = controller.property;
  40396. var container = document.createElement('div');
  40397. container.appendChild(name);
  40398. container.appendChild(controller.domElement);
  40399. var li = addRow(gui, container, params.before);
  40400. dom.addClass(li, GUI.CLASS_CONTROLLER_ROW);
  40401. if (controller instanceof ColorController) {
  40402. dom.addClass(li, 'color');
  40403. } else {
  40404. dom.addClass(li, _typeof(controller.getValue()));
  40405. }
  40406. augmentController(gui, li, controller);
  40407. gui.__controllers.push(controller);
  40408. return controller;
  40409. }
  40410. function getLocalStorageHash(gui, key) {
  40411. return document.location.href + '.' + key;
  40412. }
  40413. function addPresetOption(gui, name, setSelected) {
  40414. var opt = document.createElement('option');
  40415. opt.innerHTML = name;
  40416. opt.value = name;
  40417. gui.__preset_select.appendChild(opt);
  40418. if (setSelected) {
  40419. gui.__preset_select.selectedIndex = gui.__preset_select.length - 1;
  40420. }
  40421. }
  40422. function showHideExplain(gui, explain) {
  40423. explain.style.display = gui.useLocalStorage ? 'block' : 'none';
  40424. }
  40425. function addSaveMenu(gui) {
  40426. var div = gui.__save_row = document.createElement('li');
  40427. dom.addClass(gui.domElement, 'has-save');
  40428. gui.__ul.insertBefore(div, gui.__ul.firstChild);
  40429. dom.addClass(div, 'save-row');
  40430. var gears = document.createElement('span');
  40431. gears.innerHTML = '&nbsp;';
  40432. dom.addClass(gears, 'button gears');
  40433. var button = document.createElement('span');
  40434. button.innerHTML = 'Save';
  40435. dom.addClass(button, 'button');
  40436. dom.addClass(button, 'save');
  40437. var button2 = document.createElement('span');
  40438. button2.innerHTML = 'New';
  40439. dom.addClass(button2, 'button');
  40440. dom.addClass(button2, 'save-as');
  40441. var button3 = document.createElement('span');
  40442. button3.innerHTML = 'Revert';
  40443. dom.addClass(button3, 'button');
  40444. dom.addClass(button3, 'revert');
  40445. var select = gui.__preset_select = document.createElement('select');
  40446. if (gui.load && gui.load.remembered) {
  40447. Common.each(gui.load.remembered, function (value, key) {
  40448. addPresetOption(gui, key, key === gui.preset);
  40449. });
  40450. } else {
  40451. addPresetOption(gui, DEFAULT_DEFAULT_PRESET_NAME, false);
  40452. }
  40453. dom.bind(select, 'change', function () {
  40454. for (var index = 0; index < gui.__preset_select.length; index++) {
  40455. gui.__preset_select[index].innerHTML = gui.__preset_select[index].value;
  40456. }
  40457. gui.preset = this.value;
  40458. });
  40459. div.appendChild(select);
  40460. div.appendChild(gears);
  40461. div.appendChild(button);
  40462. div.appendChild(button2);
  40463. div.appendChild(button3);
  40464. if (SUPPORTS_LOCAL_STORAGE) {
  40465. var explain = document.getElementById('dg-local-explain');
  40466. var localStorageCheckBox = document.getElementById('dg-local-storage');
  40467. var saveLocally = document.getElementById('dg-save-locally');
  40468. saveLocally.style.display = 'block';
  40469. if (localStorage.getItem(getLocalStorageHash(gui, 'isLocal')) === 'true') {
  40470. localStorageCheckBox.setAttribute('checked', 'checked');
  40471. }
  40472. showHideExplain(gui, explain);
  40473. dom.bind(localStorageCheckBox, 'change', function () {
  40474. gui.useLocalStorage = !gui.useLocalStorage;
  40475. showHideExplain(gui, explain);
  40476. });
  40477. }
  40478. var newConstructorTextArea = document.getElementById('dg-new-constructor');
  40479. dom.bind(newConstructorTextArea, 'keydown', function (e) {
  40480. if (e.metaKey && (e.which === 67 || e.keyCode === 67)) {
  40481. SAVE_DIALOGUE.hide();
  40482. }
  40483. });
  40484. dom.bind(gears, 'click', function () {
  40485. newConstructorTextArea.innerHTML = JSON.stringify(gui.getSaveObject(), undefined, 2);
  40486. SAVE_DIALOGUE.show();
  40487. newConstructorTextArea.focus();
  40488. newConstructorTextArea.select();
  40489. });
  40490. dom.bind(button, 'click', function () {
  40491. gui.save();
  40492. });
  40493. dom.bind(button2, 'click', function () {
  40494. var presetName = prompt('Enter a new preset name.');
  40495. if (presetName) {
  40496. gui.saveAs(presetName);
  40497. }
  40498. });
  40499. dom.bind(button3, 'click', function () {
  40500. gui.revert();
  40501. });
  40502. }
  40503. function addResizeHandle(gui) {
  40504. var pmouseX = void 0;
  40505. gui.__resize_handle = document.createElement('div');
  40506. Common.extend(gui.__resize_handle.style, {
  40507. width: '6px',
  40508. marginLeft: '-3px',
  40509. height: '200px',
  40510. cursor: 'ew-resize',
  40511. position: 'absolute'
  40512. });
  40513. function drag(e) {
  40514. e.preventDefault();
  40515. gui.width += pmouseX - e.clientX;
  40516. gui.onResize();
  40517. pmouseX = e.clientX;
  40518. return false;
  40519. }
  40520. function dragStop() {
  40521. dom.removeClass(gui.__closeButton, GUI.CLASS_DRAG);
  40522. dom.unbind(window, 'mousemove', drag);
  40523. dom.unbind(window, 'mouseup', dragStop);
  40524. }
  40525. function dragStart(e) {
  40526. e.preventDefault();
  40527. pmouseX = e.clientX;
  40528. dom.addClass(gui.__closeButton, GUI.CLASS_DRAG);
  40529. dom.bind(window, 'mousemove', drag);
  40530. dom.bind(window, 'mouseup', dragStop);
  40531. return false;
  40532. }
  40533. dom.bind(gui.__resize_handle, 'mousedown', dragStart);
  40534. dom.bind(gui.__closeButton, 'mousedown', dragStart);
  40535. gui.domElement.insertBefore(gui.__resize_handle, gui.domElement.firstElementChild);
  40536. }
  40537. function setWidth(gui, w) {
  40538. gui.domElement.style.width = w + 'px';
  40539. if (gui.__save_row && gui.autoPlace) {
  40540. gui.__save_row.style.width = w + 'px';
  40541. }
  40542. if (gui.__closeButton) {
  40543. gui.__closeButton.style.width = w + 'px';
  40544. }
  40545. }
  40546. function getCurrentPreset(gui, useInitialValues) {
  40547. var toReturn = {};
  40548. Common.each(gui.__rememberedObjects, function (val, index) {
  40549. var savedValues = {};
  40550. var controllerMap = gui.__rememberedObjectIndecesToControllers[index];
  40551. Common.each(controllerMap, function (controller, property) {
  40552. savedValues[property] = useInitialValues ? controller.initialValue : controller.getValue();
  40553. });
  40554. toReturn[index] = savedValues;
  40555. });
  40556. return toReturn;
  40557. }
  40558. function setPresetSelectIndex(gui) {
  40559. for (var index = 0; index < gui.__preset_select.length; index++) {
  40560. if (gui.__preset_select[index].value === gui.preset) {
  40561. gui.__preset_select.selectedIndex = index;
  40562. }
  40563. }
  40564. }
  40565. function updateDisplays(controllerArray) {
  40566. if (controllerArray.length !== 0) {
  40567. requestAnimationFrame$1.call(window, function () {
  40568. updateDisplays(controllerArray);
  40569. });
  40570. }
  40571. Common.each(controllerArray, function (c) {
  40572. c.updateDisplay();
  40573. });
  40574. }
  40575. var color = {
  40576. Color: Color,
  40577. math: ColorMath,
  40578. interpret: interpret
  40579. };
  40580. exports.color = color;
  40581. var controllers = {
  40582. Controller: Controller,
  40583. BooleanController: BooleanController,
  40584. OptionController: OptionController,
  40585. StringController: StringController,
  40586. NumberController: NumberController,
  40587. NumberControllerBox: NumberControllerBox,
  40588. NumberControllerSlider: NumberControllerSlider,
  40589. FunctionController: FunctionController,
  40590. ColorController: ColorController
  40591. };
  40592. exports.controllers = controllers;
  40593. var dom$1 = {
  40594. dom: dom
  40595. };
  40596. exports.dom = dom$1;
  40597. var gui = {
  40598. GUI: GUI
  40599. };
  40600. exports.gui = gui;
  40601. var GUI$1 = GUI;
  40602. exports.GUI = GUI$1;
  40603. var index = {
  40604. color: color,
  40605. controllers: controllers,
  40606. dom: dom$1,
  40607. gui: gui,
  40608. GUI: GUI$1
  40609. };
  40610. var _default = index;
  40611. exports.default = _default;
  40612. },{}],"../node_modules/three/examples/jsm/libs/stats.module.js":[function(require,module,exports) {
  40613. "use strict";
  40614. Object.defineProperty(exports, "__esModule", {
  40615. value: true
  40616. });
  40617. exports.default = void 0;
  40618. var Stats = function () {
  40619. var mode = 0;
  40620. var container = document.createElement('div');
  40621. container.style.cssText = 'position:fixed;top:0;left:0;cursor:pointer;opacity:0.9;z-index:10000';
  40622. container.addEventListener('click', function (event) {
  40623. event.preventDefault();
  40624. showPanel(++mode % container.children.length);
  40625. }, false); //
  40626. function addPanel(panel) {
  40627. container.appendChild(panel.dom);
  40628. return panel;
  40629. }
  40630. function showPanel(id) {
  40631. for (var i = 0; i < container.children.length; i++) {
  40632. container.children[i].style.display = i === id ? 'block' : 'none';
  40633. }
  40634. mode = id;
  40635. } //
  40636. var beginTime = (performance || Date).now(),
  40637. prevTime = beginTime,
  40638. frames = 0;
  40639. var fpsPanel = addPanel(new Stats.Panel('FPS', '#0ff', '#002'));
  40640. var msPanel = addPanel(new Stats.Panel('MS', '#0f0', '#020'));
  40641. if (self.performance && self.performance.memory) {
  40642. var memPanel = addPanel(new Stats.Panel('MB', '#f08', '#201'));
  40643. }
  40644. showPanel(0);
  40645. return {
  40646. REVISION: 16,
  40647. dom: container,
  40648. addPanel: addPanel,
  40649. showPanel: showPanel,
  40650. begin: function () {
  40651. beginTime = (performance || Date).now();
  40652. },
  40653. end: function () {
  40654. frames++;
  40655. var time = (performance || Date).now();
  40656. msPanel.update(time - beginTime, 200);
  40657. if (time >= prevTime + 1000) {
  40658. fpsPanel.update(frames * 1000 / (time - prevTime), 100);
  40659. prevTime = time;
  40660. frames = 0;
  40661. if (memPanel) {
  40662. var memory = performance.memory;
  40663. memPanel.update(memory.usedJSHeapSize / 1048576, memory.jsHeapSizeLimit / 1048576);
  40664. }
  40665. }
  40666. return time;
  40667. },
  40668. update: function () {
  40669. beginTime = this.end();
  40670. },
  40671. // Backwards Compatibility
  40672. domElement: container,
  40673. setMode: showPanel
  40674. };
  40675. };
  40676. Stats.Panel = function (name, fg, bg) {
  40677. var min = Infinity,
  40678. max = 0,
  40679. round = Math.round;
  40680. var PR = round(window.devicePixelRatio || 1);
  40681. var WIDTH = 80 * PR,
  40682. HEIGHT = 48 * PR,
  40683. TEXT_X = 3 * PR,
  40684. TEXT_Y = 2 * PR,
  40685. GRAPH_X = 3 * PR,
  40686. GRAPH_Y = 15 * PR,
  40687. GRAPH_WIDTH = 74 * PR,
  40688. GRAPH_HEIGHT = 30 * PR;
  40689. var canvas = document.createElement('canvas');
  40690. canvas.width = WIDTH;
  40691. canvas.height = HEIGHT;
  40692. canvas.style.cssText = 'width:80px;height:48px';
  40693. var context = canvas.getContext('2d');
  40694. context.font = 'bold ' + 9 * PR + 'px Helvetica,Arial,sans-serif';
  40695. context.textBaseline = 'top';
  40696. context.fillStyle = bg;
  40697. context.fillRect(0, 0, WIDTH, HEIGHT);
  40698. context.fillStyle = fg;
  40699. context.fillText(name, TEXT_X, TEXT_Y);
  40700. context.fillRect(GRAPH_X, GRAPH_Y, GRAPH_WIDTH, GRAPH_HEIGHT);
  40701. context.fillStyle = bg;
  40702. context.globalAlpha = 0.9;
  40703. context.fillRect(GRAPH_X, GRAPH_Y, GRAPH_WIDTH, GRAPH_HEIGHT);
  40704. return {
  40705. dom: canvas,
  40706. update: function (value, maxValue) {
  40707. min = Math.min(min, value);
  40708. max = Math.max(max, value);
  40709. context.fillStyle = bg;
  40710. context.globalAlpha = 1;
  40711. context.fillRect(0, 0, WIDTH, GRAPH_Y);
  40712. context.fillStyle = fg;
  40713. context.fillText(round(value) + ' ' + name + ' (' + round(min) + '-' + round(max) + ')', TEXT_X, TEXT_Y);
  40714. context.drawImage(canvas, GRAPH_X + PR, GRAPH_Y, GRAPH_WIDTH - PR, GRAPH_HEIGHT, GRAPH_X, GRAPH_Y, GRAPH_WIDTH - PR, GRAPH_HEIGHT);
  40715. context.fillRect(GRAPH_X + GRAPH_WIDTH - PR, GRAPH_Y, PR, GRAPH_HEIGHT);
  40716. context.fillStyle = bg;
  40717. context.globalAlpha = 0.9;
  40718. context.fillRect(GRAPH_X + GRAPH_WIDTH - PR, GRAPH_Y, PR, round((1 - value / maxValue) * GRAPH_HEIGHT));
  40719. }
  40720. };
  40721. };
  40722. var _default = Stats;
  40723. exports.default = _default;
  40724. },{}],"ionExample.js":[function(require,module,exports) {
  40725. "use strict";
  40726. var _index = require("../src/index.js");
  40727. var _three = require("three");
  40728. var _OrbitControls = require("three/examples/jsm/controls/OrbitControls.js");
  40729. var _BufferGeometryUtils = require("three/examples/jsm/utils/BufferGeometryUtils.js");
  40730. var _GLTFLoader = require("three/examples/jsm/loaders/GLTFLoader.js");
  40731. var _DRACOLoader = require("three/examples/jsm/loaders/DRACOLoader.js");
  40732. var dat = _interopRequireWildcard(require("three/examples/jsm/libs/dat.gui.module.js"));
  40733. var _statsModule = _interopRequireDefault(require("three/examples/jsm/libs/stats.module.js"));
  40734. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  40735. function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; }
  40736. function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
  40737. function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest(); }
  40738. function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance"); }
  40739. function _iterableToArrayLimit(arr, i) { if (!(Symbol.iterator in Object(arr) || Object.prototype.toString.call(arr) === "[object Arguments]")) { return; } var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }
  40740. function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
  40741. var ALL_HITS = 1;
  40742. var FIRST_HIT_ONLY = 2;
  40743. var hashUrl = window.location.hash.replace(/^#/, '');
  40744. var camera, controls, scene, renderer, tiles, cameraHelper;
  40745. var thirdPersonCamera, thirdPersonRenderer, thirdPersonControls;
  40746. var secondRenderer, secondCameraHelper, secondControls, secondCamera;
  40747. var orthoCamera, orthoCameraHelper;
  40748. var raycaster, mouse, rayIntersect, lastHoveredElement;
  40749. var offsetParent;
  40750. var statsContainer, stats;
  40751. var params = {
  40752. 'enableUpdate': true,
  40753. 'raycast': _index.NONE,
  40754. 'enableCacheDisplay': false,
  40755. 'enableRendererStats': false,
  40756. 'orthographic': false,
  40757. 'ionAssetId': '40866',
  40758. 'ionAccessToken': 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiIwY2Q2MzQ1OS1kNjI4LTRiZDEtOWVkZC1kMWI4YzAyODU3OGMiLCJpZCI6MjU5LCJpYXQiOjE2MDY4NzMyMTh9.8EwC6vilVHM2yizt8nG6VmbNu66QiCrk3O-1lEDPI9I',
  40759. 'preFetchToken': false,
  40760. 'errorTarget': 6,
  40761. 'errorThreshold': 60,
  40762. 'maxDepth': 15,
  40763. 'loadSiblings': true,
  40764. 'stopAtEmptyTiles': true,
  40765. 'displayActiveTiles': false,
  40766. 'resolutionScale': 1.0,
  40767. 'up': hashUrl ? '+Z' : '+Y',
  40768. 'displayBoxBounds': false,
  40769. 'colorMode': 0,
  40770. 'showThirdPerson': false,
  40771. 'showSecondView': false,
  40772. 'reload': reinstantiateTiles
  40773. };
  40774. init();
  40775. animate();
  40776. function loadIonJson(assetId, accessToken) {
  40777. var ionEndpointUrl = new URL("https://api.cesium.com/v1/assets/".concat(assetId, "/endpoint"));
  40778. ionEndpointUrl.searchParams.append("access_token", accessToken);
  40779. return fetch(ionEndpointUrl, {
  40780. mode: 'cors'
  40781. }).then(function (res) {
  40782. if (res.ok) {
  40783. return res.json();
  40784. } else {
  40785. return Promise.reject("".concat(res.status, " : ").concat(res.statusText));
  40786. }
  40787. }).then(function (json) {
  40788. return [json.url, json.accessToken];
  40789. });
  40790. }
  40791. function setupTiles() {
  40792. tiles.fetchOptions.mode = 'cors'; // Note the DRACO compression files need to be supplied via an explicit source.
  40793. // We use unpkg here but in practice should be provided by the application.
  40794. var dracoLoader = new _DRACOLoader.DRACOLoader();
  40795. dracoLoader.setDecoderPath('https://unpkg.com/three@0.123.0/examples/js/libs/draco/gltf/');
  40796. dracoLoader.setDecoderConfig({
  40797. type: "js"
  40798. });
  40799. var loader = new _GLTFLoader.GLTFLoader(tiles.manager);
  40800. loader.setDRACOLoader(dracoLoader);
  40801. tiles.manager.addHandler(/\.gltf$/, {
  40802. parse: function parse() {
  40803. return loader.parse.apply(loader, arguments);
  40804. }
  40805. });
  40806. offsetParent.add(tiles.group);
  40807. }
  40808. function reinstantiateTiles() {
  40809. var url = hashUrl || '../data/tileset.json';
  40810. if (tiles) {
  40811. offsetParent.remove(tiles.group);
  40812. tiles.dispose();
  40813. }
  40814. if (params.ionAssetId) {
  40815. if (params.preFetchToken) {
  40816. // If you don't want to share your ion access token on the client you can pre-fetch a temporary 1h bearer token on the server like so
  40817. loadIonJson(params.ionAssetId, params.ionAccessToken).then(function (_ref) {
  40818. var _ref2 = _slicedToArray(_ref, 2),
  40819. ionUrl = _ref2[0],
  40820. token = _ref2[1];
  40821. tiles = new _index.DebugTilesRenderer(ionUrl, token);
  40822. setupTiles();
  40823. });
  40824. } else {
  40825. // If no access token is given, the default ion token will be used.
  40826. tiles = new _index.DebugTilesRenderer(params.ionAssetId, params.ionAccessToken);
  40827. setupTiles();
  40828. }
  40829. } else {
  40830. tiles = new _index.DebugTilesRenderer(url);
  40831. setupTiles();
  40832. }
  40833. }
  40834. function init() {
  40835. scene = new _three.Scene(); // primary camera view
  40836. renderer = new _three.WebGLRenderer({
  40837. antialias: true
  40838. });
  40839. renderer.setPixelRatio(window.devicePixelRatio);
  40840. renderer.setSize(window.innerWidth, window.innerHeight);
  40841. renderer.setClearColor(0x151c1f);
  40842. renderer.outputEncoding = _three.sRGBEncoding;
  40843. document.body.appendChild(renderer.domElement);
  40844. camera = new _three.PerspectiveCamera(60, window.innerWidth / window.innerHeight, 1, 4000);
  40845. camera.position.set(400, 400, 400);
  40846. cameraHelper = new _three.CameraHelper(camera);
  40847. scene.add(cameraHelper);
  40848. orthoCamera = new _three.OrthographicCamera();
  40849. orthoCameraHelper = new _three.CameraHelper(orthoCamera);
  40850. scene.add(orthoCameraHelper); // secondary camera view
  40851. secondCamera = new _three.PerspectiveCamera(60, window.innerWidth / window.innerHeight, 1, 4000);
  40852. secondCamera.position.set(400, 400, -400);
  40853. secondCamera.lookAt(0, 0, 0);
  40854. secondRenderer = new _three.WebGLRenderer({
  40855. antialias: true
  40856. });
  40857. secondRenderer.setPixelRatio(window.devicePixelRatio);
  40858. secondRenderer.setSize(window.innerWidth, window.innerHeight);
  40859. secondRenderer.setClearColor(0x151c1f);
  40860. secondRenderer.outputEncoding = _three.sRGBEncoding;
  40861. document.body.appendChild(secondRenderer.domElement);
  40862. secondRenderer.domElement.style.position = 'absolute';
  40863. secondRenderer.domElement.style.right = '0';
  40864. secondRenderer.domElement.style.top = '0';
  40865. secondRenderer.domElement.style.outline = '#0f1416 solid 2px';
  40866. secondControls = new _OrbitControls.OrbitControls(secondCamera, secondRenderer.domElement);
  40867. secondControls.screenSpacePanning = false;
  40868. secondControls.minDistance = 1;
  40869. secondControls.maxDistance = 2000;
  40870. secondCameraHelper = new _three.CameraHelper(secondCamera);
  40871. scene.add(secondCameraHelper); // Third person camera view
  40872. thirdPersonCamera = new _three.PerspectiveCamera(60, window.innerWidth / window.innerHeight, 1, 4000);
  40873. thirdPersonCamera.position.set(50, 40, 40);
  40874. thirdPersonCamera.lookAt(0, 0, 0);
  40875. thirdPersonRenderer = new _three.WebGLRenderer({
  40876. antialias: true
  40877. });
  40878. thirdPersonRenderer.setPixelRatio(window.devicePixelRatio);
  40879. thirdPersonRenderer.setSize(window.innerWidth, window.innerHeight);
  40880. thirdPersonRenderer.setClearColor(0x0f1416);
  40881. thirdPersonRenderer.outputEncoding = _three.sRGBEncoding;
  40882. document.body.appendChild(thirdPersonRenderer.domElement);
  40883. thirdPersonRenderer.domElement.style.position = 'fixed';
  40884. thirdPersonRenderer.domElement.style.left = '5px';
  40885. thirdPersonRenderer.domElement.style.bottom = '5px';
  40886. thirdPersonControls = new _OrbitControls.OrbitControls(thirdPersonCamera, thirdPersonRenderer.domElement);
  40887. thirdPersonControls.screenSpacePanning = false;
  40888. thirdPersonControls.minDistance = 1;
  40889. thirdPersonControls.maxDistance = 2000; // controls
  40890. controls = new _OrbitControls.OrbitControls(camera, renderer.domElement);
  40891. controls.screenSpacePanning = false;
  40892. controls.minDistance = 1;
  40893. controls.maxDistance = 2000; // lights
  40894. var dirLight = new _three.DirectionalLight(0xffffff);
  40895. dirLight.position.set(1, 2, 3);
  40896. scene.add(dirLight);
  40897. var ambLight = new _three.AmbientLight(0xffffff, 0.2);
  40898. scene.add(ambLight);
  40899. offsetParent = new _three.Group();
  40900. scene.add(offsetParent); // Raycasting init
  40901. raycaster = new _three.Raycaster();
  40902. mouse = new _three.Vector2();
  40903. rayIntersect = new _three.Group();
  40904. var rayIntersectMat = new _three.MeshBasicMaterial({
  40905. color: 0xe91e63
  40906. });
  40907. var rayMesh = new _three.Mesh(new _three.CylinderBufferGeometry(0.25, 0.25, 6), rayIntersectMat);
  40908. rayMesh.rotation.x = Math.PI / 2;
  40909. rayMesh.position.z += 3;
  40910. rayIntersect.add(rayMesh);
  40911. var rayRing = new _three.Mesh(new _three.TorusBufferGeometry(1.5, 0.2, 16, 100), rayIntersectMat);
  40912. rayIntersect.add(rayRing);
  40913. scene.add(rayIntersect);
  40914. rayIntersect.visible = false;
  40915. reinstantiateTiles();
  40916. onWindowResize();
  40917. window.addEventListener('resize', onWindowResize, false);
  40918. renderer.domElement.addEventListener('mousemove', onMouseMove, false);
  40919. renderer.domElement.addEventListener('mousedown', onMouseDown, false);
  40920. renderer.domElement.addEventListener('mouseup', onMouseUp, false);
  40921. renderer.domElement.addEventListener('mouseleave', onMouseLeave, false);
  40922. secondRenderer.domElement.addEventListener('mousemove', onMouseMove, false);
  40923. secondRenderer.domElement.addEventListener('mousedown', onMouseDown, false);
  40924. secondRenderer.domElement.addEventListener('mouseup', onMouseUp, false);
  40925. secondRenderer.domElement.addEventListener('mouseleave', onMouseLeave, false); // GUI
  40926. var gui = new dat.GUI();
  40927. gui.width = 300;
  40928. var tileOptions = gui.addFolder('Tiles Options');
  40929. tileOptions.add(params, 'ionAssetId');
  40930. tileOptions.add(params, 'ionAccessToken');
  40931. tileOptions.add(params, 'preFetchToken');
  40932. tileOptions.add(params, 'loadSiblings');
  40933. tileOptions.add(params, 'stopAtEmptyTiles');
  40934. tileOptions.add(params, 'displayActiveTiles');
  40935. tileOptions.add(params, 'errorTarget').min(0).max(50);
  40936. tileOptions.add(params, 'errorThreshold').min(0).max(1000);
  40937. tileOptions.add(params, 'maxDepth').min(1).max(100);
  40938. tileOptions.add(params, 'up', ['+Y', '+Z', '-Z']);
  40939. tileOptions.open();
  40940. var debug = gui.addFolder('Debug Options');
  40941. debug.add(params, 'displayBoxBounds');
  40942. debug.add(params, 'colorMode', {
  40943. NONE: _index.NONE,
  40944. SCREEN_ERROR: _index.SCREEN_ERROR,
  40945. GEOMETRIC_ERROR: _index.GEOMETRIC_ERROR,
  40946. DISTANCE: _index.DISTANCE,
  40947. DEPTH: _index.DEPTH,
  40948. RELATIVE_DEPTH: _index.RELATIVE_DEPTH,
  40949. IS_LEAF: _index.IS_LEAF,
  40950. RANDOM_COLOR: _index.RANDOM_COLOR
  40951. });
  40952. debug.open();
  40953. var exampleOptions = gui.addFolder('Example Options');
  40954. exampleOptions.add(params, 'resolutionScale').min(0.01).max(2.0).step(0.01).onChange(onWindowResize);
  40955. exampleOptions.add(params, 'orthographic');
  40956. exampleOptions.add(params, 'showThirdPerson');
  40957. exampleOptions.add(params, 'showSecondView').onChange(onWindowResize);
  40958. exampleOptions.add(params, 'enableUpdate').onChange(function (v) {
  40959. tiles.parseQueue.autoUpdate = v;
  40960. tiles.downloadQueue.autoUpdate = v;
  40961. if (v) {
  40962. tiles.parseQueue.scheduleJobRun();
  40963. tiles.downloadQueue.scheduleJobRun();
  40964. }
  40965. });
  40966. exampleOptions.add(params, 'raycast', {
  40967. NONE: _index.NONE,
  40968. ALL_HITS: ALL_HITS,
  40969. FIRST_HIT_ONLY: FIRST_HIT_ONLY
  40970. });
  40971. exampleOptions.add(params, 'enableCacheDisplay');
  40972. exampleOptions.add(params, 'enableRendererStats');
  40973. exampleOptions.open();
  40974. gui.add(params, 'reload');
  40975. gui.open();
  40976. statsContainer = document.createElement('div');
  40977. statsContainer.style.position = 'absolute';
  40978. statsContainer.style.top = 0;
  40979. statsContainer.style.left = 0;
  40980. statsContainer.style.color = 'white';
  40981. statsContainer.style.width = '100%';
  40982. statsContainer.style.textAlign = 'center';
  40983. statsContainer.style.padding = '5px';
  40984. statsContainer.style.pointerEvents = 'none';
  40985. statsContainer.style.lineHeight = '1.5em';
  40986. document.body.appendChild(statsContainer); // Stats
  40987. stats = new _statsModule.default();
  40988. stats.showPanel(0);
  40989. document.body.appendChild(stats.dom);
  40990. }
  40991. function onWindowResize() {
  40992. thirdPersonCamera.aspect = window.innerWidth / window.innerHeight;
  40993. thirdPersonCamera.updateProjectionMatrix();
  40994. thirdPersonRenderer.setSize(Math.floor(window.innerWidth / 3), Math.floor(window.innerHeight / 3));
  40995. if (params.showSecondView) {
  40996. camera.aspect = 0.5 * window.innerWidth / window.innerHeight;
  40997. renderer.setSize(0.5 * window.innerWidth, window.innerHeight);
  40998. secondCamera.aspect = 0.5 * window.innerWidth / window.innerHeight;
  40999. secondRenderer.setSize(0.5 * window.innerWidth, window.innerHeight);
  41000. secondRenderer.domElement.style.display = 'block';
  41001. } else {
  41002. camera.aspect = window.innerWidth / window.innerHeight;
  41003. renderer.setSize(window.innerWidth, window.innerHeight);
  41004. secondRenderer.domElement.style.display = 'none';
  41005. }
  41006. camera.updateProjectionMatrix();
  41007. renderer.setPixelRatio(window.devicePixelRatio * params.resolutionScale);
  41008. secondCamera.updateProjectionMatrix();
  41009. secondRenderer.setPixelRatio(window.devicePixelRatio);
  41010. updateOrthoCamera();
  41011. }
  41012. function onMouseLeave(e) {
  41013. lastHoveredElement = null;
  41014. }
  41015. function onMouseMove(e) {
  41016. var bounds = this.getBoundingClientRect();
  41017. mouse.x = e.clientX - bounds.x;
  41018. mouse.y = e.clientY - bounds.y;
  41019. mouse.x = mouse.x / bounds.width * 2 - 1;
  41020. mouse.y = -(mouse.y / bounds.height) * 2 + 1;
  41021. lastHoveredElement = this;
  41022. }
  41023. var startPos = new _three.Vector2();
  41024. var endPos = new _three.Vector2();
  41025. function onMouseDown(e) {
  41026. var bounds = this.getBoundingClientRect();
  41027. startPos.set(e.clientX - bounds.x, e.clientY - bounds.y);
  41028. }
  41029. function onMouseUp(e) {
  41030. var bounds = this.getBoundingClientRect();
  41031. endPos.set(e.clientX - bounds.x, e.clientY - bounds.y);
  41032. if (startPos.distanceTo(endPos) > 2) {
  41033. return;
  41034. }
  41035. if (lastHoveredElement === secondRenderer.domElement) {
  41036. raycaster.setFromCamera(mouse, secondCamera);
  41037. } else {
  41038. raycaster.setFromCamera(mouse, params.orthographic ? orthoCamera : camera);
  41039. }
  41040. raycaster.firstHitOnly = true;
  41041. var results = raycaster.intersectObject(tiles.group, true);
  41042. if (results.length) {
  41043. var object = results[0].object;
  41044. var info = tiles.getTileInformationFromActiveObject(object);
  41045. var str = '';
  41046. for (var key in info) {
  41047. var val = info[key];
  41048. if (typeof val === 'number') {
  41049. val = Math.floor(val * 1e5) / 1e5;
  41050. }
  41051. var name = key;
  41052. while (name.length < 20) {
  41053. name += ' ';
  41054. }
  41055. str += "".concat(name, " : ").concat(val, "\n");
  41056. }
  41057. console.log(str);
  41058. }
  41059. }
  41060. function updateOrthoCamera() {
  41061. orthoCamera.position.copy(camera.position);
  41062. orthoCamera.rotation.copy(camera.rotation);
  41063. var scale = camera.position.distanceTo(controls.target) / 2.0;
  41064. var aspect = window.innerWidth / window.innerHeight;
  41065. if (params.showSecondView) {
  41066. aspect *= 0.5;
  41067. }
  41068. orthoCamera.left = -aspect * scale;
  41069. orthoCamera.right = aspect * scale;
  41070. orthoCamera.bottom = -scale;
  41071. orthoCamera.top = scale;
  41072. orthoCamera.near = camera.near;
  41073. orthoCamera.far = camera.far;
  41074. orthoCamera.updateProjectionMatrix();
  41075. }
  41076. function animate() {
  41077. requestAnimationFrame(animate);
  41078. if (!tiles) return; // update options
  41079. tiles.errorTarget = params.errorTarget;
  41080. tiles.errorThreshold = params.errorThreshold;
  41081. tiles.loadSiblings = params.loadSiblings;
  41082. tiles.stopAtEmptyTiles = params.stopAtEmptyTiles;
  41083. tiles.displayActiveTiles = params.displayActiveTiles;
  41084. tiles.maxDepth = params.maxDepth;
  41085. tiles.displayBoxBounds = params.displayBoxBounds;
  41086. tiles.colorMode = parseFloat(params.colorMode);
  41087. if (params.orthographic) {
  41088. tiles.deleteCamera(camera);
  41089. tiles.setCamera(orthoCamera);
  41090. tiles.setResolutionFromRenderer(orthoCamera, renderer);
  41091. } else {
  41092. tiles.deleteCamera(orthoCamera);
  41093. tiles.setCamera(camera);
  41094. tiles.setResolutionFromRenderer(camera, renderer);
  41095. }
  41096. if (params.showSecondView) {
  41097. tiles.setCamera(secondCamera);
  41098. tiles.setResolutionFromRenderer(secondCamera, secondRenderer);
  41099. } else {
  41100. tiles.deleteCamera(secondCamera);
  41101. }
  41102. offsetParent.rotation.set(0, 0, 0);
  41103. if (params.up === '-Z') {
  41104. offsetParent.rotation.x = Math.PI / 2;
  41105. } else if (params.up === '+Z') {
  41106. offsetParent.rotation.x = -Math.PI / 2;
  41107. }
  41108. offsetParent.updateMatrixWorld(true);
  41109. if (parseFloat(params.raycast) !== _index.NONE && lastHoveredElement !== null) {
  41110. if (lastHoveredElement === renderer.domElement) {
  41111. raycaster.setFromCamera(mouse, params.orthographic ? orthoCamera : camera);
  41112. } else {
  41113. raycaster.setFromCamera(mouse, secondCamera);
  41114. }
  41115. raycaster.firstHitOnly = parseFloat(params.raycast) === FIRST_HIT_ONLY;
  41116. var results = raycaster.intersectObject(tiles.group, true);
  41117. if (results.length) {
  41118. var closestHit = results[0];
  41119. var point = closestHit.point;
  41120. rayIntersect.position.copy(point); // If the display bounds are visible they get intersected
  41121. if (closestHit.face) {
  41122. var normal = closestHit.face.normal;
  41123. normal.transformDirection(closestHit.object.matrixWorld);
  41124. rayIntersect.lookAt(point.x + normal.x, point.y + normal.y, point.z + normal.z);
  41125. }
  41126. rayIntersect.visible = true;
  41127. } else {
  41128. rayIntersect.visible = false;
  41129. }
  41130. } else {
  41131. rayIntersect.visible = false;
  41132. } // update tiles
  41133. window.tiles = tiles;
  41134. if (params.enableUpdate) {
  41135. secondCamera.updateMatrixWorld();
  41136. camera.updateMatrixWorld();
  41137. orthoCamera.updateMatrixWorld();
  41138. tiles.update();
  41139. }
  41140. render();
  41141. stats.update();
  41142. }
  41143. function render() {
  41144. updateOrthoCamera();
  41145. cameraHelper.visible = false;
  41146. orthoCameraHelper.visible = false;
  41147. secondCameraHelper.visible = false; // render primary view
  41148. if (params.orthographic) {
  41149. var dist = orthoCamera.position.distanceTo(rayIntersect.position);
  41150. rayIntersect.scale.setScalar(dist / 150);
  41151. } else {
  41152. var _dist = camera.position.distanceTo(rayIntersect.position);
  41153. rayIntersect.scale.setScalar(_dist * camera.fov / 6000);
  41154. }
  41155. renderer.render(scene, params.orthographic ? orthoCamera : camera); // render secondary view
  41156. if (params.showSecondView) {
  41157. var _dist2 = secondCamera.position.distanceTo(rayIntersect.position);
  41158. rayIntersect.scale.setScalar(_dist2 * secondCamera.fov / 6000);
  41159. secondRenderer.render(scene, secondCamera);
  41160. } // render third person view
  41161. thirdPersonRenderer.domElement.style.visibility = params.showThirdPerson ? 'visible' : 'hidden';
  41162. if (params.showThirdPerson) {
  41163. cameraHelper.update();
  41164. cameraHelper.visible = !params.orthographic;
  41165. orthoCameraHelper.update();
  41166. orthoCameraHelper.visible = params.orthographic;
  41167. if (params.showSecondView) {
  41168. secondCameraHelper.update();
  41169. secondCameraHelper.visible = true;
  41170. }
  41171. var _dist3 = thirdPersonCamera.position.distanceTo(rayIntersect.position);
  41172. rayIntersect.scale.setScalar(_dist3 * thirdPersonCamera.fov / 6000);
  41173. thirdPersonRenderer.render(scene, thirdPersonCamera);
  41174. }
  41175. var cacheFullness = tiles.lruCache.itemList.length / tiles.lruCache.maxSize;
  41176. var str = "Downloading: ".concat(tiles.stats.downloading, " Parsing: ").concat(tiles.stats.parsing, " Visible: ").concat(tiles.group.children.length - 2);
  41177. if (params.enableCacheDisplay) {
  41178. var geomSet = new Set();
  41179. tiles.traverse(function (tile) {
  41180. var scene = tile.cached.scene;
  41181. if (scene) {
  41182. scene.traverse(function (c) {
  41183. if (c.geometry) {
  41184. geomSet.add(c.geometry);
  41185. }
  41186. });
  41187. }
  41188. });
  41189. var count = 0;
  41190. geomSet.forEach(function (g) {
  41191. count += _BufferGeometryUtils.BufferGeometryUtils.estimateBytesUsed(g);
  41192. });
  41193. str += "<br/>Cache: ".concat((100 * cacheFullness).toFixed(2), "% ~").concat((count / 1000 / 1000).toFixed(2), "mb");
  41194. }
  41195. if (params.enableRendererStats) {
  41196. var memory = renderer.info.memory;
  41197. var programCount = renderer.info.programs.length;
  41198. str += "<br/>Geometries: ".concat(memory.geometries, " Textures: ").concat(memory.textures, " Programs: ").concat(programCount);
  41199. }
  41200. if (statsContainer.innerHTML !== str) {
  41201. statsContainer.innerHTML = str;
  41202. }
  41203. }
  41204. },{"../src/index.js":"../src/index.js","three":"../node_modules/three/build/three.module.js","three/examples/jsm/controls/OrbitControls.js":"../node_modules/three/examples/jsm/controls/OrbitControls.js","three/examples/jsm/utils/BufferGeometryUtils.js":"../node_modules/three/examples/jsm/utils/BufferGeometryUtils.js","three/examples/jsm/loaders/GLTFLoader.js":"../node_modules/three/examples/jsm/loaders/GLTFLoader.js","three/examples/jsm/loaders/DRACOLoader.js":"../node_modules/three/examples/jsm/loaders/DRACOLoader.js","three/examples/jsm/libs/dat.gui.module.js":"../node_modules/three/examples/jsm/libs/dat.gui.module.js","three/examples/jsm/libs/stats.module.js":"../node_modules/three/examples/jsm/libs/stats.module.js"}],"../node_modules/parcel-bundler/src/builtins/hmr-runtime.js":[function(require,module,exports) {
  41205. var global = arguments[3];
  41206. var OVERLAY_ID = '__parcel__error__overlay__';
  41207. var OldModule = module.bundle.Module;
  41208. function Module(moduleName) {
  41209. OldModule.call(this, moduleName);
  41210. this.hot = {
  41211. data: module.bundle.hotData,
  41212. _acceptCallbacks: [],
  41213. _disposeCallbacks: [],
  41214. accept: function (fn) {
  41215. this._acceptCallbacks.push(fn || function () {});
  41216. },
  41217. dispose: function (fn) {
  41218. this._disposeCallbacks.push(fn);
  41219. }
  41220. };
  41221. module.bundle.hotData = null;
  41222. }
  41223. module.bundle.Module = Module;
  41224. var checkedAssets, assetsToAccept;
  41225. var parent = module.bundle.parent;
  41226. if ((!parent || !parent.isParcelRequire) && typeof WebSocket !== 'undefined') {
  41227. var hostname = "" || location.hostname;
  41228. var protocol = location.protocol === 'https:' ? 'wss' : 'ws';
  41229. var ws = new WebSocket(protocol + '://' + hostname + ':' + "56952" + '/');
  41230. ws.onmessage = function (event) {
  41231. checkedAssets = {};
  41232. assetsToAccept = [];
  41233. var data = JSON.parse(event.data);
  41234. if (data.type === 'update') {
  41235. var handled = false;
  41236. data.assets.forEach(function (asset) {
  41237. if (!asset.isNew) {
  41238. var didAccept = hmrAcceptCheck(global.parcelRequire, asset.id);
  41239. if (didAccept) {
  41240. handled = true;
  41241. }
  41242. }
  41243. }); // Enable HMR for CSS by default.
  41244. handled = handled || data.assets.every(function (asset) {
  41245. return asset.type === 'css' && asset.generated.js;
  41246. });
  41247. if (handled) {
  41248. console.clear();
  41249. data.assets.forEach(function (asset) {
  41250. hmrApply(global.parcelRequire, asset);
  41251. });
  41252. assetsToAccept.forEach(function (v) {
  41253. hmrAcceptRun(v[0], v[1]);
  41254. });
  41255. } else if (location.reload) {
  41256. // `location` global exists in a web worker context but lacks `.reload()` function.
  41257. location.reload();
  41258. }
  41259. }
  41260. if (data.type === 'reload') {
  41261. ws.close();
  41262. ws.onclose = function () {
  41263. location.reload();
  41264. };
  41265. }
  41266. if (data.type === 'error-resolved') {
  41267. console.log('[parcel] ✨ Error resolved');
  41268. removeErrorOverlay();
  41269. }
  41270. if (data.type === 'error') {
  41271. console.error('[parcel] 🚨 ' + data.error.message + '\n' + data.error.stack);
  41272. removeErrorOverlay();
  41273. var overlay = createErrorOverlay(data);
  41274. document.body.appendChild(overlay);
  41275. }
  41276. };
  41277. }
  41278. function removeErrorOverlay() {
  41279. var overlay = document.getElementById(OVERLAY_ID);
  41280. if (overlay) {
  41281. overlay.remove();
  41282. }
  41283. }
  41284. function createErrorOverlay(data) {
  41285. var overlay = document.createElement('div');
  41286. overlay.id = OVERLAY_ID; // html encode message and stack trace
  41287. var message = document.createElement('div');
  41288. var stackTrace = document.createElement('pre');
  41289. message.innerText = data.error.message;
  41290. stackTrace.innerText = data.error.stack;
  41291. overlay.innerHTML = '<div style="background: black; font-size: 16px; color: white; position: fixed; height: 100%; width: 100%; top: 0px; left: 0px; padding: 30px; opacity: 0.85; font-family: Menlo, Consolas, monospace; z-index: 9999;">' + '<span style="background: red; padding: 2px 4px; border-radius: 2px;">ERROR</span>' + '<span style="top: 2px; margin-left: 5px; position: relative;">🚨</span>' + '<div style="font-size: 18px; font-weight: bold; margin-top: 20px;">' + message.innerHTML + '</div>' + '<pre>' + stackTrace.innerHTML + '</pre>' + '</div>';
  41292. return overlay;
  41293. }
  41294. function getParents(bundle, id) {
  41295. var modules = bundle.modules;
  41296. if (!modules) {
  41297. return [];
  41298. }
  41299. var parents = [];
  41300. var k, d, dep;
  41301. for (k in modules) {
  41302. for (d in modules[k][1]) {
  41303. dep = modules[k][1][d];
  41304. if (dep === id || Array.isArray(dep) && dep[dep.length - 1] === id) {
  41305. parents.push(k);
  41306. }
  41307. }
  41308. }
  41309. if (bundle.parent) {
  41310. parents = parents.concat(getParents(bundle.parent, id));
  41311. }
  41312. return parents;
  41313. }
  41314. function hmrApply(bundle, asset) {
  41315. var modules = bundle.modules;
  41316. if (!modules) {
  41317. return;
  41318. }
  41319. if (modules[asset.id] || !bundle.parent) {
  41320. var fn = new Function('require', 'module', 'exports', asset.generated.js);
  41321. asset.isNew = !modules[asset.id];
  41322. modules[asset.id] = [fn, asset.deps];
  41323. } else if (bundle.parent) {
  41324. hmrApply(bundle.parent, asset);
  41325. }
  41326. }
  41327. function hmrAcceptCheck(bundle, id) {
  41328. var modules = bundle.modules;
  41329. if (!modules) {
  41330. return;
  41331. }
  41332. if (!modules[id] && bundle.parent) {
  41333. return hmrAcceptCheck(bundle.parent, id);
  41334. }
  41335. if (checkedAssets[id]) {
  41336. return;
  41337. }
  41338. checkedAssets[id] = true;
  41339. var cached = bundle.cache[id];
  41340. assetsToAccept.push([bundle, id]);
  41341. if (cached && cached.hot && cached.hot._acceptCallbacks.length) {
  41342. return true;
  41343. }
  41344. return getParents(global.parcelRequire, id).some(function (id) {
  41345. return hmrAcceptCheck(global.parcelRequire, id);
  41346. });
  41347. }
  41348. function hmrAcceptRun(bundle, id) {
  41349. var cached = bundle.cache[id];
  41350. bundle.hotData = {};
  41351. if (cached) {
  41352. cached.hot.data = bundle.hotData;
  41353. }
  41354. if (cached && cached.hot && cached.hot._disposeCallbacks.length) {
  41355. cached.hot._disposeCallbacks.forEach(function (cb) {
  41356. cb(bundle.hotData);
  41357. });
  41358. }
  41359. delete bundle.cache[id];
  41360. bundle(id);
  41361. cached = bundle.cache[id];
  41362. if (cached && cached.hot && cached.hot._acceptCallbacks.length) {
  41363. cached.hot._acceptCallbacks.forEach(function (cb) {
  41364. cb();
  41365. });
  41366. return true;
  41367. }
  41368. }
  41369. },{}]},{},["../node_modules/parcel-bundler/src/builtins/hmr-runtime.js","ionExample.js"], null)
  41370. //# sourceMappingURL=ionExample.4422c37a.js.map