three.js 1.1 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366
  1. /**
  2. * @license
  3. * Copyright 2010-2022 Three.js Authors
  4. * SPDX-License-Identifier: MIT
  5. */
  6. (function (global, factory) {
  7. typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
  8. typeof define === 'function' && define.amd ? define(['exports'], factory) :
  9. (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.THREE = {}));
  10. })(this, (function (exports) { 'use strict';
  11. const REVISION = '141dev';
  12. const MOUSE = {
  13. LEFT: 0,
  14. MIDDLE: 1,
  15. RIGHT: 2,
  16. ROTATE: 0,
  17. DOLLY: 1,
  18. PAN: 2
  19. };
  20. const TOUCH = {
  21. ROTATE: 0,
  22. PAN: 1,
  23. DOLLY_PAN: 2,
  24. DOLLY_ROTATE: 3
  25. };
  26. const CullFaceNone = 0;
  27. const CullFaceBack = 1;
  28. const CullFaceFront = 2;
  29. const CullFaceFrontBack = 3;
  30. const BasicShadowMap = 0;
  31. const PCFShadowMap = 1;
  32. const PCFSoftShadowMap = 2;
  33. const VSMShadowMap = 3;
  34. const FrontSide = 0;
  35. const BackSide = 1;
  36. const DoubleSide = 2;
  37. const FlatShading = 1;
  38. const SmoothShading = 2;
  39. const NoBlending = 0;
  40. const NormalBlending = 1;
  41. const AdditiveBlending = 2;
  42. const SubtractiveBlending = 3;
  43. const MultiplyBlending = 4;
  44. const CustomBlending = 5;
  45. const AddEquation = 100;
  46. const SubtractEquation = 101;
  47. const ReverseSubtractEquation = 102;
  48. const MinEquation = 103;
  49. const MaxEquation = 104;
  50. const ZeroFactor = 200;
  51. const OneFactor = 201;
  52. const SrcColorFactor = 202;
  53. const OneMinusSrcColorFactor = 203;
  54. const SrcAlphaFactor = 204;
  55. const OneMinusSrcAlphaFactor = 205;
  56. const DstAlphaFactor = 206;
  57. const OneMinusDstAlphaFactor = 207;
  58. const DstColorFactor = 208;
  59. const OneMinusDstColorFactor = 209;
  60. const SrcAlphaSaturateFactor = 210;
  61. const NeverDepth = 0;
  62. const AlwaysDepth = 1;
  63. const LessDepth = 2;
  64. const LessEqualDepth = 3;
  65. const EqualDepth = 4;
  66. const GreaterEqualDepth = 5;
  67. const GreaterDepth = 6;
  68. const NotEqualDepth = 7;
  69. const MultiplyOperation = 0;
  70. const MixOperation = 1;
  71. const AddOperation = 2;
  72. const NoToneMapping = 0;
  73. const LinearToneMapping = 1;
  74. const ReinhardToneMapping = 2;
  75. const CineonToneMapping = 3;
  76. const ACESFilmicToneMapping = 4;
  77. const CustomToneMapping = 5;
  78. const UVMapping = 300;
  79. const CubeReflectionMapping = 301;
  80. const CubeRefractionMapping = 302;
  81. const EquirectangularReflectionMapping = 303;
  82. const EquirectangularRefractionMapping = 304;
  83. const CubeUVReflectionMapping = 306;
  84. const RepeatWrapping = 1000;
  85. const ClampToEdgeWrapping = 1001;
  86. const MirroredRepeatWrapping = 1002;
  87. const NearestFilter = 1003;
  88. const NearestMipmapNearestFilter = 1004;
  89. const NearestMipMapNearestFilter = 1004;
  90. const NearestMipmapLinearFilter = 1005;
  91. const NearestMipMapLinearFilter = 1005;
  92. const LinearFilter = 1006;
  93. const LinearMipmapNearestFilter = 1007;
  94. const LinearMipMapNearestFilter = 1007;
  95. const LinearMipmapLinearFilter = 1008;
  96. const LinearMipMapLinearFilter = 1008;
  97. const UnsignedByteType = 1009;
  98. const ByteType = 1010;
  99. const ShortType = 1011;
  100. const UnsignedShortType = 1012;
  101. const IntType = 1013;
  102. const UnsignedIntType = 1014;
  103. const FloatType = 1015;
  104. const HalfFloatType = 1016;
  105. const UnsignedShort4444Type = 1017;
  106. const UnsignedShort5551Type = 1018;
  107. const UnsignedInt248Type = 1020;
  108. const AlphaFormat = 1021;
  109. const RGBFormat = 1022;
  110. const RGBAFormat = 1023;
  111. const LuminanceFormat = 1024;
  112. const LuminanceAlphaFormat = 1025;
  113. const DepthFormat = 1026;
  114. const DepthStencilFormat = 1027;
  115. const RedFormat = 1028;
  116. const RedIntegerFormat = 1029;
  117. const RGFormat = 1030;
  118. const RGIntegerFormat = 1031;
  119. const RGBAIntegerFormat = 1033;
  120. const RGB_S3TC_DXT1_Format = 33776;
  121. const RGBA_S3TC_DXT1_Format = 33777;
  122. const RGBA_S3TC_DXT3_Format = 33778;
  123. const RGBA_S3TC_DXT5_Format = 33779;
  124. const RGB_PVRTC_4BPPV1_Format = 35840;
  125. const RGB_PVRTC_2BPPV1_Format = 35841;
  126. const RGBA_PVRTC_4BPPV1_Format = 35842;
  127. const RGBA_PVRTC_2BPPV1_Format = 35843;
  128. const RGB_ETC1_Format = 36196;
  129. const RGB_ETC2_Format = 37492;
  130. const RGBA_ETC2_EAC_Format = 37496;
  131. const RGBA_ASTC_4x4_Format = 37808;
  132. const RGBA_ASTC_5x4_Format = 37809;
  133. const RGBA_ASTC_5x5_Format = 37810;
  134. const RGBA_ASTC_6x5_Format = 37811;
  135. const RGBA_ASTC_6x6_Format = 37812;
  136. const RGBA_ASTC_8x5_Format = 37813;
  137. const RGBA_ASTC_8x6_Format = 37814;
  138. const RGBA_ASTC_8x8_Format = 37815;
  139. const RGBA_ASTC_10x5_Format = 37816;
  140. const RGBA_ASTC_10x6_Format = 37817;
  141. const RGBA_ASTC_10x8_Format = 37818;
  142. const RGBA_ASTC_10x10_Format = 37819;
  143. const RGBA_ASTC_12x10_Format = 37820;
  144. const RGBA_ASTC_12x12_Format = 37821;
  145. const RGBA_BPTC_Format = 36492;
  146. const LoopOnce = 2200;
  147. const LoopRepeat = 2201;
  148. const LoopPingPong = 2202;
  149. const InterpolateDiscrete = 2300;
  150. const InterpolateLinear = 2301;
  151. const InterpolateSmooth = 2302;
  152. const ZeroCurvatureEnding = 2400;
  153. const ZeroSlopeEnding = 2401;
  154. const WrapAroundEnding = 2402;
  155. const NormalAnimationBlendMode = 2500;
  156. const AdditiveAnimationBlendMode = 2501;
  157. const TrianglesDrawMode = 0;
  158. const TriangleStripDrawMode = 1;
  159. const TriangleFanDrawMode = 2;
  160. const LinearEncoding = 3000;
  161. const sRGBEncoding = 3001;
  162. const BasicDepthPacking = 3200;
  163. const RGBADepthPacking = 3201;
  164. const TangentSpaceNormalMap = 0;
  165. const ObjectSpaceNormalMap = 1; // Color space string identifiers, matching CSS Color Module Level 4 and WebGPU names where available.
  166. const NoColorSpace = '';
  167. const SRGBColorSpace = 'srgb';
  168. const LinearSRGBColorSpace = 'srgb-linear';
  169. const ZeroStencilOp = 0;
  170. const KeepStencilOp = 7680;
  171. const ReplaceStencilOp = 7681;
  172. const IncrementStencilOp = 7682;
  173. const DecrementStencilOp = 7683;
  174. const IncrementWrapStencilOp = 34055;
  175. const DecrementWrapStencilOp = 34056;
  176. const InvertStencilOp = 5386;
  177. const NeverStencilFunc = 512;
  178. const LessStencilFunc = 513;
  179. const EqualStencilFunc = 514;
  180. const LessEqualStencilFunc = 515;
  181. const GreaterStencilFunc = 516;
  182. const NotEqualStencilFunc = 517;
  183. const GreaterEqualStencilFunc = 518;
  184. const AlwaysStencilFunc = 519;
  185. const StaticDrawUsage = 35044;
  186. const DynamicDrawUsage = 35048;
  187. const StreamDrawUsage = 35040;
  188. const StaticReadUsage = 35045;
  189. const DynamicReadUsage = 35049;
  190. const StreamReadUsage = 35041;
  191. const StaticCopyUsage = 35046;
  192. const DynamicCopyUsage = 35050;
  193. const StreamCopyUsage = 35042;
  194. const GLSL1 = '100';
  195. const GLSL3 = '300 es';
  196. const _SRGBAFormat = 1035; // fallback for WebGL 1
  197. /**
  198. * https://github.com/mrdoob/eventdispatcher.js/
  199. */
  200. class EventDispatcher {
  201. addEventListener(type, listener) {
  202. if (this._listeners === undefined) this._listeners = {};
  203. const listeners = this._listeners;
  204. if (listeners[type] === undefined) {
  205. listeners[type] = [];
  206. }
  207. if (listeners[type].indexOf(listener) === -1) {
  208. listeners[type].push(listener);
  209. }
  210. }
  211. hasEventListener(type, listener) {
  212. if (this._listeners === undefined) return false;
  213. const listeners = this._listeners;
  214. return listeners[type] !== undefined && listeners[type].indexOf(listener) !== -1;
  215. }
  216. removeEventListener(type, listener) {
  217. if (this._listeners === undefined) return;
  218. const listeners = this._listeners;
  219. const listenerArray = listeners[type];
  220. if (listenerArray !== undefined) {
  221. const index = listenerArray.indexOf(listener);
  222. if (index !== -1) {
  223. listenerArray.splice(index, 1);
  224. }
  225. }
  226. }
  227. dispatchEvent(event) {
  228. if (this._listeners === undefined) return;
  229. const listeners = this._listeners;
  230. const listenerArray = listeners[event.type];
  231. if (listenerArray !== undefined) {
  232. event.target = this; // Make a copy, in case listeners are removed while iterating.
  233. const array = listenerArray.slice(0);
  234. for (let i = 0, l = array.length; i < l; i++) {
  235. array[i].call(this, event);
  236. }
  237. event.target = null;
  238. }
  239. }
  240. }
  241. const _lut = [];
  242. for (let i = 0; i < 256; i++) {
  243. _lut[i] = (i < 16 ? '0' : '') + i.toString(16);
  244. }
  245. let _seed = 1234567;
  246. const DEG2RAD = Math.PI / 180;
  247. const RAD2DEG = 180 / Math.PI; // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/21963136#21963136
  248. function generateUUID() {
  249. const d0 = Math.random() * 0xffffffff | 0;
  250. const d1 = Math.random() * 0xffffffff | 0;
  251. const d2 = Math.random() * 0xffffffff | 0;
  252. const d3 = Math.random() * 0xffffffff | 0;
  253. 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]; // .toLowerCase() here flattens concatenated strings to save heap memory space.
  254. return uuid.toLowerCase();
  255. }
  256. function clamp(value, min, max) {
  257. return Math.max(min, Math.min(max, value));
  258. } // compute euclidean modulo of m % n
  259. // https://en.wikipedia.org/wiki/Modulo_operation
  260. function euclideanModulo(n, m) {
  261. return (n % m + m) % m;
  262. } // Linear mapping from range <a1, a2> to range <b1, b2>
  263. function mapLinear(x, a1, a2, b1, b2) {
  264. return b1 + (x - a1) * (b2 - b1) / (a2 - a1);
  265. } // https://www.gamedev.net/tutorials/programming/general-and-gameplay-programming/inverse-lerp-a-super-useful-yet-often-overlooked-function-r5230/
  266. function inverseLerp(x, y, value) {
  267. if (x !== y) {
  268. return (value - x) / (y - x);
  269. } else {
  270. return 0;
  271. }
  272. } // https://en.wikipedia.org/wiki/Linear_interpolation
  273. function lerp(x, y, t) {
  274. return (1 - t) * x + t * y;
  275. } // http://www.rorydriscoll.com/2016/03/07/frame-rate-independent-damping-using-lerp/
  276. function damp(x, y, lambda, dt) {
  277. return lerp(x, y, 1 - Math.exp(-lambda * dt));
  278. } // https://www.desmos.com/calculator/vcsjnyz7x4
  279. function pingpong(x, length = 1) {
  280. return length - Math.abs(euclideanModulo(x, length * 2) - length);
  281. } // http://en.wikipedia.org/wiki/Smoothstep
  282. function smoothstep(x, min, max) {
  283. if (x <= min) return 0;
  284. if (x >= max) return 1;
  285. x = (x - min) / (max - min);
  286. return x * x * (3 - 2 * x);
  287. }
  288. function smootherstep(x, min, max) {
  289. if (x <= min) return 0;
  290. if (x >= max) return 1;
  291. x = (x - min) / (max - min);
  292. return x * x * x * (x * (x * 6 - 15) + 10);
  293. } // Random integer from <low, high> interval
  294. function randInt(low, high) {
  295. return low + Math.floor(Math.random() * (high - low + 1));
  296. } // Random float from <low, high> interval
  297. function randFloat(low, high) {
  298. return low + Math.random() * (high - low);
  299. } // Random float from <-range/2, range/2> interval
  300. function randFloatSpread(range) {
  301. return range * (0.5 - Math.random());
  302. } // Deterministic pseudo-random float in the interval [ 0, 1 ]
  303. function seededRandom(s) {
  304. if (s !== undefined) _seed = s; // Mulberry32 generator
  305. let t = _seed += 0x6D2B79F5;
  306. t = Math.imul(t ^ t >>> 15, t | 1);
  307. t ^= t + Math.imul(t ^ t >>> 7, t | 61);
  308. return ((t ^ t >>> 14) >>> 0) / 4294967296;
  309. }
  310. function degToRad(degrees) {
  311. return degrees * DEG2RAD;
  312. }
  313. function radToDeg(radians) {
  314. return radians * RAD2DEG;
  315. }
  316. function isPowerOfTwo(value) {
  317. return (value & value - 1) === 0 && value !== 0;
  318. }
  319. function ceilPowerOfTwo(value) {
  320. return Math.pow(2, Math.ceil(Math.log(value) / Math.LN2));
  321. }
  322. function floorPowerOfTwo(value) {
  323. return Math.pow(2, Math.floor(Math.log(value) / Math.LN2));
  324. }
  325. function setQuaternionFromProperEuler(q, a, b, c, order) {
  326. // Intrinsic Proper Euler Angles - see https://en.wikipedia.org/wiki/Euler_angles
  327. // rotations are applied to the axes in the order specified by 'order'
  328. // rotation by angle 'a' is applied first, then by angle 'b', then by angle 'c'
  329. // angles are in radians
  330. const cos = Math.cos;
  331. const sin = Math.sin;
  332. const c2 = cos(b / 2);
  333. const s2 = sin(b / 2);
  334. const c13 = cos((a + c) / 2);
  335. const s13 = sin((a + c) / 2);
  336. const c1_3 = cos((a - c) / 2);
  337. const s1_3 = sin((a - c) / 2);
  338. const c3_1 = cos((c - a) / 2);
  339. const s3_1 = sin((c - a) / 2);
  340. switch (order) {
  341. case 'XYX':
  342. q.set(c2 * s13, s2 * c1_3, s2 * s1_3, c2 * c13);
  343. break;
  344. case 'YZY':
  345. q.set(s2 * s1_3, c2 * s13, s2 * c1_3, c2 * c13);
  346. break;
  347. case 'ZXZ':
  348. q.set(s2 * c1_3, s2 * s1_3, c2 * s13, c2 * c13);
  349. break;
  350. case 'XZX':
  351. q.set(c2 * s13, s2 * s3_1, s2 * c3_1, c2 * c13);
  352. break;
  353. case 'YXY':
  354. q.set(s2 * c3_1, c2 * s13, s2 * s3_1, c2 * c13);
  355. break;
  356. case 'ZYZ':
  357. q.set(s2 * s3_1, s2 * c3_1, c2 * s13, c2 * c13);
  358. break;
  359. default:
  360. console.warn('THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: ' + order);
  361. }
  362. }
  363. function denormalize$1(value, array) {
  364. switch (array.constructor) {
  365. case Float32Array:
  366. return value;
  367. case Uint16Array:
  368. return value / 65535.0;
  369. case Uint8Array:
  370. return value / 255.0;
  371. case Int16Array:
  372. return Math.max(value / 32767.0, -1.0);
  373. case Int8Array:
  374. return Math.max(value / 127.0, -1.0);
  375. default:
  376. throw new Error('Invalid component type.');
  377. }
  378. }
  379. function normalize(value, array) {
  380. switch (array.constructor) {
  381. case Float32Array:
  382. return value;
  383. case Uint16Array:
  384. return Math.round(value * 65535.0);
  385. case Uint8Array:
  386. return Math.round(value * 255.0);
  387. case Int16Array:
  388. return Math.round(value * 32767.0);
  389. case Int8Array:
  390. return Math.round(value * 127.0);
  391. default:
  392. throw new Error('Invalid component type.');
  393. }
  394. }
  395. var MathUtils = /*#__PURE__*/Object.freeze({
  396. __proto__: null,
  397. DEG2RAD: DEG2RAD,
  398. RAD2DEG: RAD2DEG,
  399. generateUUID: generateUUID,
  400. clamp: clamp,
  401. euclideanModulo: euclideanModulo,
  402. mapLinear: mapLinear,
  403. inverseLerp: inverseLerp,
  404. lerp: lerp,
  405. damp: damp,
  406. pingpong: pingpong,
  407. smoothstep: smoothstep,
  408. smootherstep: smootherstep,
  409. randInt: randInt,
  410. randFloat: randFloat,
  411. randFloatSpread: randFloatSpread,
  412. seededRandom: seededRandom,
  413. degToRad: degToRad,
  414. radToDeg: radToDeg,
  415. isPowerOfTwo: isPowerOfTwo,
  416. ceilPowerOfTwo: ceilPowerOfTwo,
  417. floorPowerOfTwo: floorPowerOfTwo,
  418. setQuaternionFromProperEuler: setQuaternionFromProperEuler,
  419. normalize: normalize,
  420. denormalize: denormalize$1
  421. });
  422. class Vector2 {
  423. constructor(x = 0, y = 0) {
  424. this.isVector2 = true;
  425. this.x = x;
  426. this.y = y;
  427. }
  428. get width() {
  429. return this.x;
  430. }
  431. set width(value) {
  432. this.x = value;
  433. }
  434. get height() {
  435. return this.y;
  436. }
  437. set height(value) {
  438. this.y = value;
  439. }
  440. set(x, y) {
  441. this.x = x;
  442. this.y = y;
  443. return this;
  444. }
  445. setScalar(scalar) {
  446. this.x = scalar;
  447. this.y = scalar;
  448. return this;
  449. }
  450. setX(x) {
  451. this.x = x;
  452. return this;
  453. }
  454. setY(y) {
  455. this.y = y;
  456. return this;
  457. }
  458. setComponent(index, value) {
  459. switch (index) {
  460. case 0:
  461. this.x = value;
  462. break;
  463. case 1:
  464. this.y = value;
  465. break;
  466. default:
  467. throw new Error('index is out of range: ' + index);
  468. }
  469. return this;
  470. }
  471. getComponent(index) {
  472. switch (index) {
  473. case 0:
  474. return this.x;
  475. case 1:
  476. return this.y;
  477. default:
  478. throw new Error('index is out of range: ' + index);
  479. }
  480. }
  481. clone() {
  482. return new this.constructor(this.x, this.y);
  483. }
  484. copy(v) {
  485. this.x = v.x;
  486. this.y = v.y;
  487. return this;
  488. }
  489. add(v, w) {
  490. if (w !== undefined) {
  491. console.warn('THREE.Vector2: .add() now only accepts one argument. Use .addVectors( a, b ) instead.');
  492. return this.addVectors(v, w);
  493. }
  494. this.x += v.x;
  495. this.y += v.y;
  496. return this;
  497. }
  498. addScalar(s) {
  499. this.x += s;
  500. this.y += s;
  501. return this;
  502. }
  503. addVectors(a, b) {
  504. this.x = a.x + b.x;
  505. this.y = a.y + b.y;
  506. return this;
  507. }
  508. addScaledVector(v, s) {
  509. this.x += v.x * s;
  510. this.y += v.y * s;
  511. return this;
  512. }
  513. sub(v, w) {
  514. if (w !== undefined) {
  515. console.warn('THREE.Vector2: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.');
  516. return this.subVectors(v, w);
  517. }
  518. this.x -= v.x;
  519. this.y -= v.y;
  520. return this;
  521. }
  522. subScalar(s) {
  523. this.x -= s;
  524. this.y -= s;
  525. return this;
  526. }
  527. subVectors(a, b) {
  528. this.x = a.x - b.x;
  529. this.y = a.y - b.y;
  530. return this;
  531. }
  532. multiply(v) {
  533. this.x *= v.x;
  534. this.y *= v.y;
  535. return this;
  536. }
  537. multiplyScalar(scalar) {
  538. this.x *= scalar;
  539. this.y *= scalar;
  540. return this;
  541. }
  542. divide(v) {
  543. this.x /= v.x;
  544. this.y /= v.y;
  545. return this;
  546. }
  547. divideScalar(scalar) {
  548. return this.multiplyScalar(1 / scalar);
  549. }
  550. applyMatrix3(m) {
  551. const x = this.x,
  552. y = this.y;
  553. const e = m.elements;
  554. this.x = e[0] * x + e[3] * y + e[6];
  555. this.y = e[1] * x + e[4] * y + e[7];
  556. return this;
  557. }
  558. min(v) {
  559. this.x = Math.min(this.x, v.x);
  560. this.y = Math.min(this.y, v.y);
  561. return this;
  562. }
  563. max(v) {
  564. this.x = Math.max(this.x, v.x);
  565. this.y = Math.max(this.y, v.y);
  566. return this;
  567. }
  568. clamp(min, max) {
  569. // assumes min < max, componentwise
  570. this.x = Math.max(min.x, Math.min(max.x, this.x));
  571. this.y = Math.max(min.y, Math.min(max.y, this.y));
  572. return this;
  573. }
  574. clampScalar(minVal, maxVal) {
  575. this.x = Math.max(minVal, Math.min(maxVal, this.x));
  576. this.y = Math.max(minVal, Math.min(maxVal, this.y));
  577. return this;
  578. }
  579. clampLength(min, max) {
  580. const length = this.length();
  581. return this.divideScalar(length || 1).multiplyScalar(Math.max(min, Math.min(max, length)));
  582. }
  583. floor() {
  584. this.x = Math.floor(this.x);
  585. this.y = Math.floor(this.y);
  586. return this;
  587. }
  588. ceil() {
  589. this.x = Math.ceil(this.x);
  590. this.y = Math.ceil(this.y);
  591. return this;
  592. }
  593. round() {
  594. this.x = Math.round(this.x);
  595. this.y = Math.round(this.y);
  596. return this;
  597. }
  598. roundToZero() {
  599. this.x = this.x < 0 ? Math.ceil(this.x) : Math.floor(this.x);
  600. this.y = this.y < 0 ? Math.ceil(this.y) : Math.floor(this.y);
  601. return this;
  602. }
  603. negate() {
  604. this.x = -this.x;
  605. this.y = -this.y;
  606. return this;
  607. }
  608. dot(v) {
  609. return this.x * v.x + this.y * v.y;
  610. }
  611. cross(v) {
  612. return this.x * v.y - this.y * v.x;
  613. }
  614. lengthSq() {
  615. return this.x * this.x + this.y * this.y;
  616. }
  617. length() {
  618. return Math.sqrt(this.x * this.x + this.y * this.y);
  619. }
  620. manhattanLength() {
  621. return Math.abs(this.x) + Math.abs(this.y);
  622. }
  623. normalize() {
  624. return this.divideScalar(this.length() || 1);
  625. }
  626. angle() {
  627. // computes the angle in radians with respect to the positive x-axis
  628. const angle = Math.atan2(-this.y, -this.x) + Math.PI;
  629. return angle;
  630. }
  631. distanceTo(v) {
  632. return Math.sqrt(this.distanceToSquared(v));
  633. }
  634. distanceToSquared(v) {
  635. const dx = this.x - v.x,
  636. dy = this.y - v.y;
  637. return dx * dx + dy * dy;
  638. }
  639. manhattanDistanceTo(v) {
  640. return Math.abs(this.x - v.x) + Math.abs(this.y - v.y);
  641. }
  642. setLength(length) {
  643. return this.normalize().multiplyScalar(length);
  644. }
  645. lerp(v, alpha) {
  646. this.x += (v.x - this.x) * alpha;
  647. this.y += (v.y - this.y) * alpha;
  648. return this;
  649. }
  650. lerpVectors(v1, v2, alpha) {
  651. this.x = v1.x + (v2.x - v1.x) * alpha;
  652. this.y = v1.y + (v2.y - v1.y) * alpha;
  653. return this;
  654. }
  655. equals(v) {
  656. return v.x === this.x && v.y === this.y;
  657. }
  658. fromArray(array, offset = 0) {
  659. this.x = array[offset];
  660. this.y = array[offset + 1];
  661. return this;
  662. }
  663. toArray(array = [], offset = 0) {
  664. array[offset] = this.x;
  665. array[offset + 1] = this.y;
  666. return array;
  667. }
  668. fromBufferAttribute(attribute, index, offset) {
  669. if (offset !== undefined) {
  670. console.warn('THREE.Vector2: offset has been removed from .fromBufferAttribute().');
  671. }
  672. this.x = attribute.getX(index);
  673. this.y = attribute.getY(index);
  674. return this;
  675. }
  676. rotateAround(center, angle) {
  677. const c = Math.cos(angle),
  678. s = Math.sin(angle);
  679. const x = this.x - center.x;
  680. const y = this.y - center.y;
  681. this.x = x * c - y * s + center.x;
  682. this.y = x * s + y * c + center.y;
  683. return this;
  684. }
  685. random() {
  686. this.x = Math.random();
  687. this.y = Math.random();
  688. return this;
  689. }
  690. *[Symbol.iterator]() {
  691. yield this.x;
  692. yield this.y;
  693. }
  694. }
  695. class Matrix3 {
  696. constructor() {
  697. this.isMatrix3 = true;
  698. this.elements = [1, 0, 0, 0, 1, 0, 0, 0, 1];
  699. if (arguments.length > 0) {
  700. console.error('THREE.Matrix3: the constructor no longer reads arguments. use .set() instead.');
  701. }
  702. }
  703. set(n11, n12, n13, n21, n22, n23, n31, n32, n33) {
  704. const te = this.elements;
  705. te[0] = n11;
  706. te[1] = n21;
  707. te[2] = n31;
  708. te[3] = n12;
  709. te[4] = n22;
  710. te[5] = n32;
  711. te[6] = n13;
  712. te[7] = n23;
  713. te[8] = n33;
  714. return this;
  715. }
  716. identity() {
  717. this.set(1, 0, 0, 0, 1, 0, 0, 0, 1);
  718. return this;
  719. }
  720. copy(m) {
  721. const te = this.elements;
  722. const me = m.elements;
  723. te[0] = me[0];
  724. te[1] = me[1];
  725. te[2] = me[2];
  726. te[3] = me[3];
  727. te[4] = me[4];
  728. te[5] = me[5];
  729. te[6] = me[6];
  730. te[7] = me[7];
  731. te[8] = me[8];
  732. return this;
  733. }
  734. extractBasis(xAxis, yAxis, zAxis) {
  735. xAxis.setFromMatrix3Column(this, 0);
  736. yAxis.setFromMatrix3Column(this, 1);
  737. zAxis.setFromMatrix3Column(this, 2);
  738. return this;
  739. }
  740. setFromMatrix4(m) {
  741. const me = m.elements;
  742. this.set(me[0], me[4], me[8], me[1], me[5], me[9], me[2], me[6], me[10]);
  743. return this;
  744. }
  745. multiply(m) {
  746. return this.multiplyMatrices(this, m);
  747. }
  748. premultiply(m) {
  749. return this.multiplyMatrices(m, this);
  750. }
  751. multiplyMatrices(a, b) {
  752. const ae = a.elements;
  753. const be = b.elements;
  754. const te = this.elements;
  755. const a11 = ae[0],
  756. a12 = ae[3],
  757. a13 = ae[6];
  758. const a21 = ae[1],
  759. a22 = ae[4],
  760. a23 = ae[7];
  761. const a31 = ae[2],
  762. a32 = ae[5],
  763. a33 = ae[8];
  764. const b11 = be[0],
  765. b12 = be[3],
  766. b13 = be[6];
  767. const b21 = be[1],
  768. b22 = be[4],
  769. b23 = be[7];
  770. const b31 = be[2],
  771. b32 = be[5],
  772. b33 = be[8];
  773. te[0] = a11 * b11 + a12 * b21 + a13 * b31;
  774. te[3] = a11 * b12 + a12 * b22 + a13 * b32;
  775. te[6] = a11 * b13 + a12 * b23 + a13 * b33;
  776. te[1] = a21 * b11 + a22 * b21 + a23 * b31;
  777. te[4] = a21 * b12 + a22 * b22 + a23 * b32;
  778. te[7] = a21 * b13 + a22 * b23 + a23 * b33;
  779. te[2] = a31 * b11 + a32 * b21 + a33 * b31;
  780. te[5] = a31 * b12 + a32 * b22 + a33 * b32;
  781. te[8] = a31 * b13 + a32 * b23 + a33 * b33;
  782. return this;
  783. }
  784. multiplyScalar(s) {
  785. const te = this.elements;
  786. te[0] *= s;
  787. te[3] *= s;
  788. te[6] *= s;
  789. te[1] *= s;
  790. te[4] *= s;
  791. te[7] *= s;
  792. te[2] *= s;
  793. te[5] *= s;
  794. te[8] *= s;
  795. return this;
  796. }
  797. determinant() {
  798. const te = this.elements;
  799. const a = te[0],
  800. b = te[1],
  801. c = te[2],
  802. d = te[3],
  803. e = te[4],
  804. f = te[5],
  805. g = te[6],
  806. h = te[7],
  807. i = te[8];
  808. return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g;
  809. }
  810. invert() {
  811. const te = this.elements,
  812. n11 = te[0],
  813. n21 = te[1],
  814. n31 = te[2],
  815. n12 = te[3],
  816. n22 = te[4],
  817. n32 = te[5],
  818. n13 = te[6],
  819. n23 = te[7],
  820. n33 = te[8],
  821. t11 = n33 * n22 - n32 * n23,
  822. t12 = n32 * n13 - n33 * n12,
  823. t13 = n23 * n12 - n22 * n13,
  824. det = n11 * t11 + n21 * t12 + n31 * t13;
  825. if (det === 0) return this.set(0, 0, 0, 0, 0, 0, 0, 0, 0);
  826. const detInv = 1 / det;
  827. te[0] = t11 * detInv;
  828. te[1] = (n31 * n23 - n33 * n21) * detInv;
  829. te[2] = (n32 * n21 - n31 * n22) * detInv;
  830. te[3] = t12 * detInv;
  831. te[4] = (n33 * n11 - n31 * n13) * detInv;
  832. te[5] = (n31 * n12 - n32 * n11) * detInv;
  833. te[6] = t13 * detInv;
  834. te[7] = (n21 * n13 - n23 * n11) * detInv;
  835. te[8] = (n22 * n11 - n21 * n12) * detInv;
  836. return this;
  837. }
  838. transpose() {
  839. let tmp;
  840. const m = this.elements;
  841. tmp = m[1];
  842. m[1] = m[3];
  843. m[3] = tmp;
  844. tmp = m[2];
  845. m[2] = m[6];
  846. m[6] = tmp;
  847. tmp = m[5];
  848. m[5] = m[7];
  849. m[7] = tmp;
  850. return this;
  851. }
  852. getNormalMatrix(matrix4) {
  853. return this.setFromMatrix4(matrix4).invert().transpose();
  854. }
  855. transposeIntoArray(r) {
  856. const m = this.elements;
  857. r[0] = m[0];
  858. r[1] = m[3];
  859. r[2] = m[6];
  860. r[3] = m[1];
  861. r[4] = m[4];
  862. r[5] = m[7];
  863. r[6] = m[2];
  864. r[7] = m[5];
  865. r[8] = m[8];
  866. return this;
  867. }
  868. setUvTransform(tx, ty, sx, sy, rotation, cx, cy) {
  869. const c = Math.cos(rotation);
  870. const s = Math.sin(rotation);
  871. 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);
  872. return this;
  873. }
  874. scale(sx, sy) {
  875. const te = this.elements;
  876. te[0] *= sx;
  877. te[3] *= sx;
  878. te[6] *= sx;
  879. te[1] *= sy;
  880. te[4] *= sy;
  881. te[7] *= sy;
  882. return this;
  883. }
  884. rotate(theta) {
  885. const c = Math.cos(theta);
  886. const s = Math.sin(theta);
  887. const te = this.elements;
  888. const a11 = te[0],
  889. a12 = te[3],
  890. a13 = te[6];
  891. const a21 = te[1],
  892. a22 = te[4],
  893. a23 = te[7];
  894. te[0] = c * a11 + s * a21;
  895. te[3] = c * a12 + s * a22;
  896. te[6] = c * a13 + s * a23;
  897. te[1] = -s * a11 + c * a21;
  898. te[4] = -s * a12 + c * a22;
  899. te[7] = -s * a13 + c * a23;
  900. return this;
  901. }
  902. translate(tx, ty) {
  903. const te = this.elements;
  904. te[0] += tx * te[2];
  905. te[3] += tx * te[5];
  906. te[6] += tx * te[8];
  907. te[1] += ty * te[2];
  908. te[4] += ty * te[5];
  909. te[7] += ty * te[8];
  910. return this;
  911. }
  912. equals(matrix) {
  913. const te = this.elements;
  914. const me = matrix.elements;
  915. for (let i = 0; i < 9; i++) {
  916. if (te[i] !== me[i]) return false;
  917. }
  918. return true;
  919. }
  920. fromArray(array, offset = 0) {
  921. for (let i = 0; i < 9; i++) {
  922. this.elements[i] = array[i + offset];
  923. }
  924. return this;
  925. }
  926. toArray(array = [], offset = 0) {
  927. const te = this.elements;
  928. array[offset] = te[0];
  929. array[offset + 1] = te[1];
  930. array[offset + 2] = te[2];
  931. array[offset + 3] = te[3];
  932. array[offset + 4] = te[4];
  933. array[offset + 5] = te[5];
  934. array[offset + 6] = te[6];
  935. array[offset + 7] = te[7];
  936. array[offset + 8] = te[8];
  937. return array;
  938. }
  939. clone() {
  940. return new this.constructor().fromArray(this.elements);
  941. }
  942. }
  943. function arrayNeedsUint32(array) {
  944. // assumes larger values usually on last
  945. for (let i = array.length - 1; i >= 0; --i) {
  946. if (array[i] > 65535) return true;
  947. }
  948. return false;
  949. }
  950. const TYPED_ARRAYS = {
  951. Int8Array: Int8Array,
  952. Uint8Array: Uint8Array,
  953. Uint8ClampedArray: Uint8ClampedArray,
  954. Int16Array: Int16Array,
  955. Uint16Array: Uint16Array,
  956. Int32Array: Int32Array,
  957. Uint32Array: Uint32Array,
  958. Float32Array: Float32Array,
  959. Float64Array: Float64Array
  960. };
  961. function getTypedArray(type, buffer) {
  962. return new TYPED_ARRAYS[type](buffer);
  963. }
  964. function createElementNS(name) {
  965. return document.createElementNS('http://www.w3.org/1999/xhtml', name);
  966. }
  967. function SRGBToLinear(c) {
  968. return c < 0.04045 ? c * 0.0773993808 : Math.pow(c * 0.9478672986 + 0.0521327014, 2.4);
  969. }
  970. function LinearToSRGB(c) {
  971. return c < 0.0031308 ? c * 12.92 : 1.055 * Math.pow(c, 0.41666) - 0.055;
  972. } // JavaScript RGB-to-RGB transforms, defined as
  973. // FN[InputColorSpace][OutputColorSpace] callback functions.
  974. const FN = {
  975. [SRGBColorSpace]: {
  976. [LinearSRGBColorSpace]: SRGBToLinear
  977. },
  978. [LinearSRGBColorSpace]: {
  979. [SRGBColorSpace]: LinearToSRGB
  980. }
  981. };
  982. const ColorManagement = {
  983. legacyMode: true,
  984. get workingColorSpace() {
  985. return LinearSRGBColorSpace;
  986. },
  987. set workingColorSpace(colorSpace) {
  988. console.warn('THREE.ColorManagement: .workingColorSpace is readonly.');
  989. },
  990. convert: function (color, sourceColorSpace, targetColorSpace) {
  991. if (this.legacyMode || sourceColorSpace === targetColorSpace || !sourceColorSpace || !targetColorSpace) {
  992. return color;
  993. }
  994. if (FN[sourceColorSpace] && FN[sourceColorSpace][targetColorSpace] !== undefined) {
  995. const fn = FN[sourceColorSpace][targetColorSpace];
  996. color.r = fn(color.r);
  997. color.g = fn(color.g);
  998. color.b = fn(color.b);
  999. return color;
  1000. }
  1001. throw new Error('Unsupported color space conversion.');
  1002. },
  1003. fromWorkingColorSpace: function (color, targetColorSpace) {
  1004. return this.convert(color, this.workingColorSpace, targetColorSpace);
  1005. },
  1006. toWorkingColorSpace: function (color, sourceColorSpace) {
  1007. return this.convert(color, sourceColorSpace, this.workingColorSpace);
  1008. }
  1009. };
  1010. const _colorKeywords = {
  1011. 'aliceblue': 0xF0F8FF,
  1012. 'antiquewhite': 0xFAEBD7,
  1013. 'aqua': 0x00FFFF,
  1014. 'aquamarine': 0x7FFFD4,
  1015. 'azure': 0xF0FFFF,
  1016. 'beige': 0xF5F5DC,
  1017. 'bisque': 0xFFE4C4,
  1018. 'black': 0x000000,
  1019. 'blanchedalmond': 0xFFEBCD,
  1020. 'blue': 0x0000FF,
  1021. 'blueviolet': 0x8A2BE2,
  1022. 'brown': 0xA52A2A,
  1023. 'burlywood': 0xDEB887,
  1024. 'cadetblue': 0x5F9EA0,
  1025. 'chartreuse': 0x7FFF00,
  1026. 'chocolate': 0xD2691E,
  1027. 'coral': 0xFF7F50,
  1028. 'cornflowerblue': 0x6495ED,
  1029. 'cornsilk': 0xFFF8DC,
  1030. 'crimson': 0xDC143C,
  1031. 'cyan': 0x00FFFF,
  1032. 'darkblue': 0x00008B,
  1033. 'darkcyan': 0x008B8B,
  1034. 'darkgoldenrod': 0xB8860B,
  1035. 'darkgray': 0xA9A9A9,
  1036. 'darkgreen': 0x006400,
  1037. 'darkgrey': 0xA9A9A9,
  1038. 'darkkhaki': 0xBDB76B,
  1039. 'darkmagenta': 0x8B008B,
  1040. 'darkolivegreen': 0x556B2F,
  1041. 'darkorange': 0xFF8C00,
  1042. 'darkorchid': 0x9932CC,
  1043. 'darkred': 0x8B0000,
  1044. 'darksalmon': 0xE9967A,
  1045. 'darkseagreen': 0x8FBC8F,
  1046. 'darkslateblue': 0x483D8B,
  1047. 'darkslategray': 0x2F4F4F,
  1048. 'darkslategrey': 0x2F4F4F,
  1049. 'darkturquoise': 0x00CED1,
  1050. 'darkviolet': 0x9400D3,
  1051. 'deeppink': 0xFF1493,
  1052. 'deepskyblue': 0x00BFFF,
  1053. 'dimgray': 0x696969,
  1054. 'dimgrey': 0x696969,
  1055. 'dodgerblue': 0x1E90FF,
  1056. 'firebrick': 0xB22222,
  1057. 'floralwhite': 0xFFFAF0,
  1058. 'forestgreen': 0x228B22,
  1059. 'fuchsia': 0xFF00FF,
  1060. 'gainsboro': 0xDCDCDC,
  1061. 'ghostwhite': 0xF8F8FF,
  1062. 'gold': 0xFFD700,
  1063. 'goldenrod': 0xDAA520,
  1064. 'gray': 0x808080,
  1065. 'green': 0x008000,
  1066. 'greenyellow': 0xADFF2F,
  1067. 'grey': 0x808080,
  1068. 'honeydew': 0xF0FFF0,
  1069. 'hotpink': 0xFF69B4,
  1070. 'indianred': 0xCD5C5C,
  1071. 'indigo': 0x4B0082,
  1072. 'ivory': 0xFFFFF0,
  1073. 'khaki': 0xF0E68C,
  1074. 'lavender': 0xE6E6FA,
  1075. 'lavenderblush': 0xFFF0F5,
  1076. 'lawngreen': 0x7CFC00,
  1077. 'lemonchiffon': 0xFFFACD,
  1078. 'lightblue': 0xADD8E6,
  1079. 'lightcoral': 0xF08080,
  1080. 'lightcyan': 0xE0FFFF,
  1081. 'lightgoldenrodyellow': 0xFAFAD2,
  1082. 'lightgray': 0xD3D3D3,
  1083. 'lightgreen': 0x90EE90,
  1084. 'lightgrey': 0xD3D3D3,
  1085. 'lightpink': 0xFFB6C1,
  1086. 'lightsalmon': 0xFFA07A,
  1087. 'lightseagreen': 0x20B2AA,
  1088. 'lightskyblue': 0x87CEFA,
  1089. 'lightslategray': 0x778899,
  1090. 'lightslategrey': 0x778899,
  1091. 'lightsteelblue': 0xB0C4DE,
  1092. 'lightyellow': 0xFFFFE0,
  1093. 'lime': 0x00FF00,
  1094. 'limegreen': 0x32CD32,
  1095. 'linen': 0xFAF0E6,
  1096. 'magenta': 0xFF00FF,
  1097. 'maroon': 0x800000,
  1098. 'mediumaquamarine': 0x66CDAA,
  1099. 'mediumblue': 0x0000CD,
  1100. 'mediumorchid': 0xBA55D3,
  1101. 'mediumpurple': 0x9370DB,
  1102. 'mediumseagreen': 0x3CB371,
  1103. 'mediumslateblue': 0x7B68EE,
  1104. 'mediumspringgreen': 0x00FA9A,
  1105. 'mediumturquoise': 0x48D1CC,
  1106. 'mediumvioletred': 0xC71585,
  1107. 'midnightblue': 0x191970,
  1108. 'mintcream': 0xF5FFFA,
  1109. 'mistyrose': 0xFFE4E1,
  1110. 'moccasin': 0xFFE4B5,
  1111. 'navajowhite': 0xFFDEAD,
  1112. 'navy': 0x000080,
  1113. 'oldlace': 0xFDF5E6,
  1114. 'olive': 0x808000,
  1115. 'olivedrab': 0x6B8E23,
  1116. 'orange': 0xFFA500,
  1117. 'orangered': 0xFF4500,
  1118. 'orchid': 0xDA70D6,
  1119. 'palegoldenrod': 0xEEE8AA,
  1120. 'palegreen': 0x98FB98,
  1121. 'paleturquoise': 0xAFEEEE,
  1122. 'palevioletred': 0xDB7093,
  1123. 'papayawhip': 0xFFEFD5,
  1124. 'peachpuff': 0xFFDAB9,
  1125. 'peru': 0xCD853F,
  1126. 'pink': 0xFFC0CB,
  1127. 'plum': 0xDDA0DD,
  1128. 'powderblue': 0xB0E0E6,
  1129. 'purple': 0x800080,
  1130. 'rebeccapurple': 0x663399,
  1131. 'red': 0xFF0000,
  1132. 'rosybrown': 0xBC8F8F,
  1133. 'royalblue': 0x4169E1,
  1134. 'saddlebrown': 0x8B4513,
  1135. 'salmon': 0xFA8072,
  1136. 'sandybrown': 0xF4A460,
  1137. 'seagreen': 0x2E8B57,
  1138. 'seashell': 0xFFF5EE,
  1139. 'sienna': 0xA0522D,
  1140. 'silver': 0xC0C0C0,
  1141. 'skyblue': 0x87CEEB,
  1142. 'slateblue': 0x6A5ACD,
  1143. 'slategray': 0x708090,
  1144. 'slategrey': 0x708090,
  1145. 'snow': 0xFFFAFA,
  1146. 'springgreen': 0x00FF7F,
  1147. 'steelblue': 0x4682B4,
  1148. 'tan': 0xD2B48C,
  1149. 'teal': 0x008080,
  1150. 'thistle': 0xD8BFD8,
  1151. 'tomato': 0xFF6347,
  1152. 'turquoise': 0x40E0D0,
  1153. 'violet': 0xEE82EE,
  1154. 'wheat': 0xF5DEB3,
  1155. 'white': 0xFFFFFF,
  1156. 'whitesmoke': 0xF5F5F5,
  1157. 'yellow': 0xFFFF00,
  1158. 'yellowgreen': 0x9ACD32
  1159. };
  1160. const _rgb = {
  1161. r: 0,
  1162. g: 0,
  1163. b: 0
  1164. };
  1165. const _hslA = {
  1166. h: 0,
  1167. s: 0,
  1168. l: 0
  1169. };
  1170. const _hslB = {
  1171. h: 0,
  1172. s: 0,
  1173. l: 0
  1174. };
  1175. function hue2rgb(p, q, t) {
  1176. if (t < 0) t += 1;
  1177. if (t > 1) t -= 1;
  1178. if (t < 1 / 6) return p + (q - p) * 6 * t;
  1179. if (t < 1 / 2) return q;
  1180. if (t < 2 / 3) return p + (q - p) * 6 * (2 / 3 - t);
  1181. return p;
  1182. }
  1183. function toComponents(source, target) {
  1184. target.r = source.r;
  1185. target.g = source.g;
  1186. target.b = source.b;
  1187. return target;
  1188. }
  1189. class Color {
  1190. constructor(r, g, b) {
  1191. this.isColor = true;
  1192. this.r = 1;
  1193. this.g = 1;
  1194. this.b = 1;
  1195. if (g === undefined && b === undefined) {
  1196. // r is THREE.Color, hex or string
  1197. return this.set(r);
  1198. }
  1199. return this.setRGB(r, g, b);
  1200. }
  1201. set(value) {
  1202. if (value && value.isColor) {
  1203. this.copy(value);
  1204. } else if (typeof value === 'number') {
  1205. this.setHex(value);
  1206. } else if (typeof value === 'string') {
  1207. this.setStyle(value);
  1208. }
  1209. return this;
  1210. }
  1211. setScalar(scalar) {
  1212. this.r = scalar;
  1213. this.g = scalar;
  1214. this.b = scalar;
  1215. return this;
  1216. }
  1217. setHex(hex, colorSpace = SRGBColorSpace) {
  1218. hex = Math.floor(hex);
  1219. this.r = (hex >> 16 & 255) / 255;
  1220. this.g = (hex >> 8 & 255) / 255;
  1221. this.b = (hex & 255) / 255;
  1222. ColorManagement.toWorkingColorSpace(this, colorSpace);
  1223. return this;
  1224. }
  1225. setRGB(r, g, b, colorSpace = LinearSRGBColorSpace) {
  1226. this.r = r;
  1227. this.g = g;
  1228. this.b = b;
  1229. ColorManagement.toWorkingColorSpace(this, colorSpace);
  1230. return this;
  1231. }
  1232. setHSL(h, s, l, colorSpace = LinearSRGBColorSpace) {
  1233. // h,s,l ranges are in 0.0 - 1.0
  1234. h = euclideanModulo(h, 1);
  1235. s = clamp(s, 0, 1);
  1236. l = clamp(l, 0, 1);
  1237. if (s === 0) {
  1238. this.r = this.g = this.b = l;
  1239. } else {
  1240. const p = l <= 0.5 ? l * (1 + s) : l + s - l * s;
  1241. const q = 2 * l - p;
  1242. this.r = hue2rgb(q, p, h + 1 / 3);
  1243. this.g = hue2rgb(q, p, h);
  1244. this.b = hue2rgb(q, p, h - 1 / 3);
  1245. }
  1246. ColorManagement.toWorkingColorSpace(this, colorSpace);
  1247. return this;
  1248. }
  1249. setStyle(style, colorSpace = SRGBColorSpace) {
  1250. function handleAlpha(string) {
  1251. if (string === undefined) return;
  1252. if (parseFloat(string) < 1) {
  1253. console.warn('THREE.Color: Alpha component of ' + style + ' will be ignored.');
  1254. }
  1255. }
  1256. let m;
  1257. if (m = /^((?:rgb|hsl)a?)\(([^\)]*)\)/.exec(style)) {
  1258. // rgb / hsl
  1259. let color;
  1260. const name = m[1];
  1261. const components = m[2];
  1262. switch (name) {
  1263. case 'rgb':
  1264. case 'rgba':
  1265. if (color = /^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(components)) {
  1266. // rgb(255,0,0) rgba(255,0,0,0.5)
  1267. this.r = Math.min(255, parseInt(color[1], 10)) / 255;
  1268. this.g = Math.min(255, parseInt(color[2], 10)) / 255;
  1269. this.b = Math.min(255, parseInt(color[3], 10)) / 255;
  1270. ColorManagement.toWorkingColorSpace(this, colorSpace);
  1271. handleAlpha(color[4]);
  1272. return this;
  1273. }
  1274. if (color = /^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(components)) {
  1275. // rgb(100%,0%,0%) rgba(100%,0%,0%,0.5)
  1276. this.r = Math.min(100, parseInt(color[1], 10)) / 100;
  1277. this.g = Math.min(100, parseInt(color[2], 10)) / 100;
  1278. this.b = Math.min(100, parseInt(color[3], 10)) / 100;
  1279. ColorManagement.toWorkingColorSpace(this, colorSpace);
  1280. handleAlpha(color[4]);
  1281. return this;
  1282. }
  1283. break;
  1284. case 'hsl':
  1285. case 'hsla':
  1286. if (color = /^\s*(\d*\.?\d+)\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(components)) {
  1287. // hsl(120,50%,50%) hsla(120,50%,50%,0.5)
  1288. const h = parseFloat(color[1]) / 360;
  1289. const s = parseInt(color[2], 10) / 100;
  1290. const l = parseInt(color[3], 10) / 100;
  1291. handleAlpha(color[4]);
  1292. return this.setHSL(h, s, l, colorSpace);
  1293. }
  1294. break;
  1295. }
  1296. } else if (m = /^\#([A-Fa-f\d]+)$/.exec(style)) {
  1297. // hex color
  1298. const hex = m[1];
  1299. const size = hex.length;
  1300. if (size === 3) {
  1301. // #ff0
  1302. this.r = parseInt(hex.charAt(0) + hex.charAt(0), 16) / 255;
  1303. this.g = parseInt(hex.charAt(1) + hex.charAt(1), 16) / 255;
  1304. this.b = parseInt(hex.charAt(2) + hex.charAt(2), 16) / 255;
  1305. ColorManagement.toWorkingColorSpace(this, colorSpace);
  1306. return this;
  1307. } else if (size === 6) {
  1308. // #ff0000
  1309. this.r = parseInt(hex.charAt(0) + hex.charAt(1), 16) / 255;
  1310. this.g = parseInt(hex.charAt(2) + hex.charAt(3), 16) / 255;
  1311. this.b = parseInt(hex.charAt(4) + hex.charAt(5), 16) / 255;
  1312. ColorManagement.toWorkingColorSpace(this, colorSpace);
  1313. return this;
  1314. }
  1315. }
  1316. if (style && style.length > 0) {
  1317. return this.setColorName(style, colorSpace);
  1318. }
  1319. return this;
  1320. }
  1321. setColorName(style, colorSpace = SRGBColorSpace) {
  1322. // color keywords
  1323. const hex = _colorKeywords[style.toLowerCase()];
  1324. if (hex !== undefined) {
  1325. // red
  1326. this.setHex(hex, colorSpace);
  1327. } else {
  1328. // unknown color
  1329. console.warn('THREE.Color: Unknown color ' + style);
  1330. }
  1331. return this;
  1332. }
  1333. clone() {
  1334. return new this.constructor(this.r, this.g, this.b);
  1335. }
  1336. copy(color) {
  1337. this.r = color.r;
  1338. this.g = color.g;
  1339. this.b = color.b;
  1340. return this;
  1341. }
  1342. copySRGBToLinear(color) {
  1343. this.r = SRGBToLinear(color.r);
  1344. this.g = SRGBToLinear(color.g);
  1345. this.b = SRGBToLinear(color.b);
  1346. return this;
  1347. }
  1348. copyLinearToSRGB(color) {
  1349. this.r = LinearToSRGB(color.r);
  1350. this.g = LinearToSRGB(color.g);
  1351. this.b = LinearToSRGB(color.b);
  1352. return this;
  1353. }
  1354. convertSRGBToLinear() {
  1355. this.copySRGBToLinear(this);
  1356. return this;
  1357. }
  1358. convertLinearToSRGB() {
  1359. this.copyLinearToSRGB(this);
  1360. return this;
  1361. }
  1362. getHex(colorSpace = SRGBColorSpace) {
  1363. ColorManagement.fromWorkingColorSpace(toComponents(this, _rgb), colorSpace);
  1364. return clamp(_rgb.r * 255, 0, 255) << 16 ^ clamp(_rgb.g * 255, 0, 255) << 8 ^ clamp(_rgb.b * 255, 0, 255) << 0;
  1365. }
  1366. getHexString(colorSpace = SRGBColorSpace) {
  1367. return ('000000' + this.getHex(colorSpace).toString(16)).slice(-6);
  1368. }
  1369. getHSL(target, colorSpace = LinearSRGBColorSpace) {
  1370. // h,s,l ranges are in 0.0 - 1.0
  1371. ColorManagement.fromWorkingColorSpace(toComponents(this, _rgb), colorSpace);
  1372. const r = _rgb.r,
  1373. g = _rgb.g,
  1374. b = _rgb.b;
  1375. const max = Math.max(r, g, b);
  1376. const min = Math.min(r, g, b);
  1377. let hue, saturation;
  1378. const lightness = (min + max) / 2.0;
  1379. if (min === max) {
  1380. hue = 0;
  1381. saturation = 0;
  1382. } else {
  1383. const delta = max - min;
  1384. saturation = lightness <= 0.5 ? delta / (max + min) : delta / (2 - max - min);
  1385. switch (max) {
  1386. case r:
  1387. hue = (g - b) / delta + (g < b ? 6 : 0);
  1388. break;
  1389. case g:
  1390. hue = (b - r) / delta + 2;
  1391. break;
  1392. case b:
  1393. hue = (r - g) / delta + 4;
  1394. break;
  1395. }
  1396. hue /= 6;
  1397. }
  1398. target.h = hue;
  1399. target.s = saturation;
  1400. target.l = lightness;
  1401. return target;
  1402. }
  1403. getRGB(target, colorSpace = LinearSRGBColorSpace) {
  1404. ColorManagement.fromWorkingColorSpace(toComponents(this, _rgb), colorSpace);
  1405. target.r = _rgb.r;
  1406. target.g = _rgb.g;
  1407. target.b = _rgb.b;
  1408. return target;
  1409. }
  1410. getStyle(colorSpace = SRGBColorSpace) {
  1411. ColorManagement.fromWorkingColorSpace(toComponents(this, _rgb), colorSpace);
  1412. if (colorSpace !== SRGBColorSpace) {
  1413. // Requires CSS Color Module Level 4 (https://www.w3.org/TR/css-color-4/).
  1414. return `color(${colorSpace} ${_rgb.r} ${_rgb.g} ${_rgb.b})`;
  1415. }
  1416. return `rgb(${_rgb.r * 255 | 0},${_rgb.g * 255 | 0},${_rgb.b * 255 | 0})`;
  1417. }
  1418. offsetHSL(h, s, l) {
  1419. this.getHSL(_hslA);
  1420. _hslA.h += h;
  1421. _hslA.s += s;
  1422. _hslA.l += l;
  1423. this.setHSL(_hslA.h, _hslA.s, _hslA.l);
  1424. return this;
  1425. }
  1426. add(color) {
  1427. this.r += color.r;
  1428. this.g += color.g;
  1429. this.b += color.b;
  1430. return this;
  1431. }
  1432. addColors(color1, color2) {
  1433. this.r = color1.r + color2.r;
  1434. this.g = color1.g + color2.g;
  1435. this.b = color1.b + color2.b;
  1436. return this;
  1437. }
  1438. addScalar(s) {
  1439. this.r += s;
  1440. this.g += s;
  1441. this.b += s;
  1442. return this;
  1443. }
  1444. sub(color) {
  1445. this.r = Math.max(0, this.r - color.r);
  1446. this.g = Math.max(0, this.g - color.g);
  1447. this.b = Math.max(0, this.b - color.b);
  1448. return this;
  1449. }
  1450. multiply(color) {
  1451. this.r *= color.r;
  1452. this.g *= color.g;
  1453. this.b *= color.b;
  1454. return this;
  1455. }
  1456. multiplyScalar(s) {
  1457. this.r *= s;
  1458. this.g *= s;
  1459. this.b *= s;
  1460. return this;
  1461. }
  1462. lerp(color, alpha) {
  1463. this.r += (color.r - this.r) * alpha;
  1464. this.g += (color.g - this.g) * alpha;
  1465. this.b += (color.b - this.b) * alpha;
  1466. return this;
  1467. }
  1468. lerpColors(color1, color2, alpha) {
  1469. this.r = color1.r + (color2.r - color1.r) * alpha;
  1470. this.g = color1.g + (color2.g - color1.g) * alpha;
  1471. this.b = color1.b + (color2.b - color1.b) * alpha;
  1472. return this;
  1473. }
  1474. lerpHSL(color, alpha) {
  1475. this.getHSL(_hslA);
  1476. color.getHSL(_hslB);
  1477. const h = lerp(_hslA.h, _hslB.h, alpha);
  1478. const s = lerp(_hslA.s, _hslB.s, alpha);
  1479. const l = lerp(_hslA.l, _hslB.l, alpha);
  1480. this.setHSL(h, s, l);
  1481. return this;
  1482. }
  1483. equals(c) {
  1484. return c.r === this.r && c.g === this.g && c.b === this.b;
  1485. }
  1486. fromArray(array, offset = 0) {
  1487. this.r = array[offset];
  1488. this.g = array[offset + 1];
  1489. this.b = array[offset + 2];
  1490. return this;
  1491. }
  1492. toArray(array = [], offset = 0) {
  1493. array[offset] = this.r;
  1494. array[offset + 1] = this.g;
  1495. array[offset + 2] = this.b;
  1496. return array;
  1497. }
  1498. fromBufferAttribute(attribute, index) {
  1499. this.r = attribute.getX(index);
  1500. this.g = attribute.getY(index);
  1501. this.b = attribute.getZ(index);
  1502. if (attribute.normalized === true) {
  1503. // assuming Uint8Array
  1504. this.r /= 255;
  1505. this.g /= 255;
  1506. this.b /= 255;
  1507. }
  1508. return this;
  1509. }
  1510. toJSON() {
  1511. return this.getHex();
  1512. }
  1513. *[Symbol.iterator]() {
  1514. yield this.r;
  1515. yield this.g;
  1516. yield this.b;
  1517. }
  1518. }
  1519. Color.NAMES = _colorKeywords;
  1520. let _canvas;
  1521. class ImageUtils {
  1522. static getDataURL(image) {
  1523. if (/^data:/i.test(image.src)) {
  1524. return image.src;
  1525. }
  1526. if (typeof HTMLCanvasElement == 'undefined') {
  1527. return image.src;
  1528. }
  1529. let canvas;
  1530. if (image instanceof HTMLCanvasElement) {
  1531. canvas = image;
  1532. } else {
  1533. if (_canvas === undefined) _canvas = createElementNS('canvas');
  1534. _canvas.width = image.width;
  1535. _canvas.height = image.height;
  1536. const context = _canvas.getContext('2d');
  1537. if (image instanceof ImageData) {
  1538. context.putImageData(image, 0, 0);
  1539. } else {
  1540. context.drawImage(image, 0, 0, image.width, image.height);
  1541. }
  1542. canvas = _canvas;
  1543. }
  1544. if (canvas.width > 2048 || canvas.height > 2048) {
  1545. console.warn('THREE.ImageUtils.getDataURL: Image converted to jpg for performance reasons', image);
  1546. return canvas.toDataURL('image/jpeg', 0.6);
  1547. } else {
  1548. return canvas.toDataURL('image/png');
  1549. }
  1550. }
  1551. static sRGBToLinear(image) {
  1552. if (typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement || typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement || typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap) {
  1553. const canvas = createElementNS('canvas');
  1554. canvas.width = image.width;
  1555. canvas.height = image.height;
  1556. const context = canvas.getContext('2d');
  1557. context.drawImage(image, 0, 0, image.width, image.height);
  1558. const imageData = context.getImageData(0, 0, image.width, image.height);
  1559. const data = imageData.data;
  1560. for (let i = 0; i < data.length; i++) {
  1561. data[i] = SRGBToLinear(data[i] / 255) * 255;
  1562. }
  1563. context.putImageData(imageData, 0, 0);
  1564. return canvas;
  1565. } else if (image.data) {
  1566. const data = image.data.slice(0);
  1567. for (let i = 0; i < data.length; i++) {
  1568. if (data instanceof Uint8Array || data instanceof Uint8ClampedArray) {
  1569. data[i] = Math.floor(SRGBToLinear(data[i] / 255) * 255);
  1570. } else {
  1571. // assuming float
  1572. data[i] = SRGBToLinear(data[i]);
  1573. }
  1574. }
  1575. return {
  1576. data: data,
  1577. width: image.width,
  1578. height: image.height
  1579. };
  1580. } else {
  1581. console.warn('THREE.ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied.');
  1582. return image;
  1583. }
  1584. }
  1585. }
  1586. class Source {
  1587. constructor(data = null) {
  1588. this.isSource = true;
  1589. this.uuid = generateUUID();
  1590. this.data = data;
  1591. this.version = 0;
  1592. }
  1593. set needsUpdate(value) {
  1594. if (value === true) this.version++;
  1595. }
  1596. toJSON(meta) {
  1597. const isRootObject = meta === undefined || typeof meta === 'string';
  1598. if (!isRootObject && meta.images[this.uuid] !== undefined) {
  1599. return meta.images[this.uuid];
  1600. }
  1601. const output = {
  1602. uuid: this.uuid,
  1603. url: ''
  1604. };
  1605. const data = this.data;
  1606. if (data !== null) {
  1607. let url;
  1608. if (Array.isArray(data)) {
  1609. // cube texture
  1610. url = [];
  1611. for (let i = 0, l = data.length; i < l; i++) {
  1612. if (data[i].isDataTexture) {
  1613. url.push(serializeImage(data[i].image));
  1614. } else {
  1615. url.push(serializeImage(data[i]));
  1616. }
  1617. }
  1618. } else {
  1619. // texture
  1620. url = serializeImage(data);
  1621. }
  1622. output.url = url;
  1623. }
  1624. if (!isRootObject) {
  1625. meta.images[this.uuid] = output;
  1626. }
  1627. return output;
  1628. }
  1629. }
  1630. function serializeImage(image) {
  1631. if (typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement || typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement || typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap) {
  1632. // default images
  1633. return ImageUtils.getDataURL(image);
  1634. } else {
  1635. if (image.data) {
  1636. // images of DataTexture
  1637. return {
  1638. data: Array.prototype.slice.call(image.data),
  1639. width: image.width,
  1640. height: image.height,
  1641. type: image.data.constructor.name
  1642. };
  1643. } else {
  1644. console.warn('THREE.Texture: Unable to serialize Texture.');
  1645. return {};
  1646. }
  1647. }
  1648. }
  1649. let textureId = 0;
  1650. class Texture extends EventDispatcher {
  1651. constructor(image = Texture.DEFAULT_IMAGE, mapping = Texture.DEFAULT_MAPPING, wrapS = ClampToEdgeWrapping, wrapT = ClampToEdgeWrapping, magFilter = LinearFilter, minFilter = LinearMipmapLinearFilter, format = RGBAFormat, type = UnsignedByteType, anisotropy = 1, encoding = LinearEncoding) {
  1652. super();
  1653. this.isTexture = true;
  1654. Object.defineProperty(this, 'id', {
  1655. value: textureId++
  1656. });
  1657. this.uuid = generateUUID();
  1658. this.name = '';
  1659. this.source = new Source(image);
  1660. this.mipmaps = [];
  1661. this.mapping = mapping;
  1662. this.wrapS = wrapS;
  1663. this.wrapT = wrapT;
  1664. this.magFilter = magFilter;
  1665. this.minFilter = minFilter;
  1666. this.anisotropy = anisotropy;
  1667. this.format = format;
  1668. this.internalFormat = null;
  1669. this.type = type;
  1670. this.offset = new Vector2(0, 0);
  1671. this.repeat = new Vector2(1, 1);
  1672. this.center = new Vector2(0, 0);
  1673. this.rotation = 0;
  1674. this.matrixAutoUpdate = true;
  1675. this.matrix = new Matrix3();
  1676. this.generateMipmaps = true;
  1677. this.premultiplyAlpha = false;
  1678. this.flipY = true;
  1679. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  1680. // Values of encoding !== THREE.LinearEncoding only supported on map, envMap and emissiveMap.
  1681. //
  1682. // Also changing the encoding after already used by a Material will not automatically make the Material
  1683. // update. You need to explicitly call Material.needsUpdate to trigger it to recompile.
  1684. this.encoding = encoding;
  1685. this.userData = {};
  1686. this.version = 0;
  1687. this.onUpdate = null;
  1688. this.isRenderTargetTexture = false; // indicates whether a texture belongs to a render target or not
  1689. this.needsPMREMUpdate = false; // indicates whether this texture should be processed by PMREMGenerator or not (only relevant for render target textures)
  1690. }
  1691. get image() {
  1692. return this.source.data;
  1693. }
  1694. set image(value) {
  1695. this.source.data = value;
  1696. }
  1697. updateMatrix() {
  1698. this.matrix.setUvTransform(this.offset.x, this.offset.y, this.repeat.x, this.repeat.y, this.rotation, this.center.x, this.center.y);
  1699. }
  1700. clone() {
  1701. return new this.constructor().copy(this);
  1702. }
  1703. copy(source) {
  1704. this.name = source.name;
  1705. this.source = source.source;
  1706. this.mipmaps = source.mipmaps.slice(0);
  1707. this.mapping = source.mapping;
  1708. this.wrapS = source.wrapS;
  1709. this.wrapT = source.wrapT;
  1710. this.magFilter = source.magFilter;
  1711. this.minFilter = source.minFilter;
  1712. this.anisotropy = source.anisotropy;
  1713. this.format = source.format;
  1714. this.internalFormat = source.internalFormat;
  1715. this.type = source.type;
  1716. this.offset.copy(source.offset);
  1717. this.repeat.copy(source.repeat);
  1718. this.center.copy(source.center);
  1719. this.rotation = source.rotation;
  1720. this.matrixAutoUpdate = source.matrixAutoUpdate;
  1721. this.matrix.copy(source.matrix);
  1722. this.generateMipmaps = source.generateMipmaps;
  1723. this.premultiplyAlpha = source.premultiplyAlpha;
  1724. this.flipY = source.flipY;
  1725. this.unpackAlignment = source.unpackAlignment;
  1726. this.encoding = source.encoding;
  1727. this.userData = JSON.parse(JSON.stringify(source.userData));
  1728. this.needsUpdate = true;
  1729. return this;
  1730. }
  1731. toJSON(meta) {
  1732. const isRootObject = meta === undefined || typeof meta === 'string';
  1733. if (!isRootObject && meta.textures[this.uuid] !== undefined) {
  1734. return meta.textures[this.uuid];
  1735. }
  1736. const output = {
  1737. metadata: {
  1738. version: 4.5,
  1739. type: 'Texture',
  1740. generator: 'Texture.toJSON'
  1741. },
  1742. uuid: this.uuid,
  1743. name: this.name,
  1744. image: this.source.toJSON(meta).uuid,
  1745. mapping: this.mapping,
  1746. repeat: [this.repeat.x, this.repeat.y],
  1747. offset: [this.offset.x, this.offset.y],
  1748. center: [this.center.x, this.center.y],
  1749. rotation: this.rotation,
  1750. wrap: [this.wrapS, this.wrapT],
  1751. format: this.format,
  1752. type: this.type,
  1753. encoding: this.encoding,
  1754. minFilter: this.minFilter,
  1755. magFilter: this.magFilter,
  1756. anisotropy: this.anisotropy,
  1757. flipY: this.flipY,
  1758. premultiplyAlpha: this.premultiplyAlpha,
  1759. unpackAlignment: this.unpackAlignment
  1760. };
  1761. if (JSON.stringify(this.userData) !== '{}') output.userData = this.userData;
  1762. if (!isRootObject) {
  1763. meta.textures[this.uuid] = output;
  1764. }
  1765. return output;
  1766. }
  1767. dispose() {
  1768. this.dispatchEvent({
  1769. type: 'dispose'
  1770. });
  1771. }
  1772. transformUv(uv) {
  1773. if (this.mapping !== UVMapping) return uv;
  1774. uv.applyMatrix3(this.matrix);
  1775. if (uv.x < 0 || uv.x > 1) {
  1776. switch (this.wrapS) {
  1777. case RepeatWrapping:
  1778. uv.x = uv.x - Math.floor(uv.x);
  1779. break;
  1780. case ClampToEdgeWrapping:
  1781. uv.x = uv.x < 0 ? 0 : 1;
  1782. break;
  1783. case MirroredRepeatWrapping:
  1784. if (Math.abs(Math.floor(uv.x) % 2) === 1) {
  1785. uv.x = Math.ceil(uv.x) - uv.x;
  1786. } else {
  1787. uv.x = uv.x - Math.floor(uv.x);
  1788. }
  1789. break;
  1790. }
  1791. }
  1792. if (uv.y < 0 || uv.y > 1) {
  1793. switch (this.wrapT) {
  1794. case RepeatWrapping:
  1795. uv.y = uv.y - Math.floor(uv.y);
  1796. break;
  1797. case ClampToEdgeWrapping:
  1798. uv.y = uv.y < 0 ? 0 : 1;
  1799. break;
  1800. case MirroredRepeatWrapping:
  1801. if (Math.abs(Math.floor(uv.y) % 2) === 1) {
  1802. uv.y = Math.ceil(uv.y) - uv.y;
  1803. } else {
  1804. uv.y = uv.y - Math.floor(uv.y);
  1805. }
  1806. break;
  1807. }
  1808. }
  1809. if (this.flipY) {
  1810. uv.y = 1 - uv.y;
  1811. }
  1812. return uv;
  1813. }
  1814. set needsUpdate(value) {
  1815. if (value === true) {
  1816. this.version++;
  1817. this.source.needsUpdate = true;
  1818. }
  1819. }
  1820. }
  1821. Texture.DEFAULT_IMAGE = null;
  1822. Texture.DEFAULT_MAPPING = UVMapping;
  1823. class Vector4 {
  1824. constructor(x = 0, y = 0, z = 0, w = 1) {
  1825. this.isVector4 = true;
  1826. this.x = x;
  1827. this.y = y;
  1828. this.z = z;
  1829. this.w = w;
  1830. }
  1831. get width() {
  1832. return this.z;
  1833. }
  1834. set width(value) {
  1835. this.z = value;
  1836. }
  1837. get height() {
  1838. return this.w;
  1839. }
  1840. set height(value) {
  1841. this.w = value;
  1842. }
  1843. set(x, y, z, w) {
  1844. this.x = x;
  1845. this.y = y;
  1846. this.z = z;
  1847. this.w = w;
  1848. return this;
  1849. }
  1850. setScalar(scalar) {
  1851. this.x = scalar;
  1852. this.y = scalar;
  1853. this.z = scalar;
  1854. this.w = scalar;
  1855. return this;
  1856. }
  1857. setX(x) {
  1858. this.x = x;
  1859. return this;
  1860. }
  1861. setY(y) {
  1862. this.y = y;
  1863. return this;
  1864. }
  1865. setZ(z) {
  1866. this.z = z;
  1867. return this;
  1868. }
  1869. setW(w) {
  1870. this.w = w;
  1871. return this;
  1872. }
  1873. setComponent(index, value) {
  1874. switch (index) {
  1875. case 0:
  1876. this.x = value;
  1877. break;
  1878. case 1:
  1879. this.y = value;
  1880. break;
  1881. case 2:
  1882. this.z = value;
  1883. break;
  1884. case 3:
  1885. this.w = value;
  1886. break;
  1887. default:
  1888. throw new Error('index is out of range: ' + index);
  1889. }
  1890. return this;
  1891. }
  1892. getComponent(index) {
  1893. switch (index) {
  1894. case 0:
  1895. return this.x;
  1896. case 1:
  1897. return this.y;
  1898. case 2:
  1899. return this.z;
  1900. case 3:
  1901. return this.w;
  1902. default:
  1903. throw new Error('index is out of range: ' + index);
  1904. }
  1905. }
  1906. clone() {
  1907. return new this.constructor(this.x, this.y, this.z, this.w);
  1908. }
  1909. copy(v) {
  1910. this.x = v.x;
  1911. this.y = v.y;
  1912. this.z = v.z;
  1913. this.w = v.w !== undefined ? v.w : 1;
  1914. return this;
  1915. }
  1916. add(v, w) {
  1917. if (w !== undefined) {
  1918. console.warn('THREE.Vector4: .add() now only accepts one argument. Use .addVectors( a, b ) instead.');
  1919. return this.addVectors(v, w);
  1920. }
  1921. this.x += v.x;
  1922. this.y += v.y;
  1923. this.z += v.z;
  1924. this.w += v.w;
  1925. return this;
  1926. }
  1927. addScalar(s) {
  1928. this.x += s;
  1929. this.y += s;
  1930. this.z += s;
  1931. this.w += s;
  1932. return this;
  1933. }
  1934. addVectors(a, b) {
  1935. this.x = a.x + b.x;
  1936. this.y = a.y + b.y;
  1937. this.z = a.z + b.z;
  1938. this.w = a.w + b.w;
  1939. return this;
  1940. }
  1941. addScaledVector(v, s) {
  1942. this.x += v.x * s;
  1943. this.y += v.y * s;
  1944. this.z += v.z * s;
  1945. this.w += v.w * s;
  1946. return this;
  1947. }
  1948. sub(v, w) {
  1949. if (w !== undefined) {
  1950. console.warn('THREE.Vector4: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.');
  1951. return this.subVectors(v, w);
  1952. }
  1953. this.x -= v.x;
  1954. this.y -= v.y;
  1955. this.z -= v.z;
  1956. this.w -= v.w;
  1957. return this;
  1958. }
  1959. subScalar(s) {
  1960. this.x -= s;
  1961. this.y -= s;
  1962. this.z -= s;
  1963. this.w -= s;
  1964. return this;
  1965. }
  1966. subVectors(a, b) {
  1967. this.x = a.x - b.x;
  1968. this.y = a.y - b.y;
  1969. this.z = a.z - b.z;
  1970. this.w = a.w - b.w;
  1971. return this;
  1972. }
  1973. multiply(v) {
  1974. this.x *= v.x;
  1975. this.y *= v.y;
  1976. this.z *= v.z;
  1977. this.w *= v.w;
  1978. return this;
  1979. }
  1980. multiplyScalar(scalar) {
  1981. this.x *= scalar;
  1982. this.y *= scalar;
  1983. this.z *= scalar;
  1984. this.w *= scalar;
  1985. return this;
  1986. }
  1987. applyMatrix4(m) {
  1988. const x = this.x,
  1989. y = this.y,
  1990. z = this.z,
  1991. w = this.w;
  1992. const e = m.elements;
  1993. this.x = e[0] * x + e[4] * y + e[8] * z + e[12] * w;
  1994. this.y = e[1] * x + e[5] * y + e[9] * z + e[13] * w;
  1995. this.z = e[2] * x + e[6] * y + e[10] * z + e[14] * w;
  1996. this.w = e[3] * x + e[7] * y + e[11] * z + e[15] * w;
  1997. return this;
  1998. }
  1999. divideScalar(scalar) {
  2000. return this.multiplyScalar(1 / scalar);
  2001. }
  2002. setAxisAngleFromQuaternion(q) {
  2003. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  2004. // q is assumed to be normalized
  2005. this.w = 2 * Math.acos(q.w);
  2006. const s = Math.sqrt(1 - q.w * q.w);
  2007. if (s < 0.0001) {
  2008. this.x = 1;
  2009. this.y = 0;
  2010. this.z = 0;
  2011. } else {
  2012. this.x = q.x / s;
  2013. this.y = q.y / s;
  2014. this.z = q.z / s;
  2015. }
  2016. return this;
  2017. }
  2018. setAxisAngleFromRotationMatrix(m) {
  2019. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  2020. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  2021. let angle, x, y, z; // variables for result
  2022. const epsilon = 0.01,
  2023. // margin to allow for rounding errors
  2024. epsilon2 = 0.1,
  2025. // margin to distinguish between 0 and 180 degrees
  2026. te = m.elements,
  2027. m11 = te[0],
  2028. m12 = te[4],
  2029. m13 = te[8],
  2030. m21 = te[1],
  2031. m22 = te[5],
  2032. m23 = te[9],
  2033. m31 = te[2],
  2034. m32 = te[6],
  2035. m33 = te[10];
  2036. if (Math.abs(m12 - m21) < epsilon && Math.abs(m13 - m31) < epsilon && Math.abs(m23 - m32) < epsilon) {
  2037. // singularity found
  2038. // first check for identity matrix which must have +1 for all terms
  2039. // in leading diagonal and zero in other terms
  2040. if (Math.abs(m12 + m21) < epsilon2 && Math.abs(m13 + m31) < epsilon2 && Math.abs(m23 + m32) < epsilon2 && Math.abs(m11 + m22 + m33 - 3) < epsilon2) {
  2041. // this singularity is identity matrix so angle = 0
  2042. this.set(1, 0, 0, 0);
  2043. return this; // zero angle, arbitrary axis
  2044. } // otherwise this singularity is angle = 180
  2045. angle = Math.PI;
  2046. const xx = (m11 + 1) / 2;
  2047. const yy = (m22 + 1) / 2;
  2048. const zz = (m33 + 1) / 2;
  2049. const xy = (m12 + m21) / 4;
  2050. const xz = (m13 + m31) / 4;
  2051. const yz = (m23 + m32) / 4;
  2052. if (xx > yy && xx > zz) {
  2053. // m11 is the largest diagonal term
  2054. if (xx < epsilon) {
  2055. x = 0;
  2056. y = 0.707106781;
  2057. z = 0.707106781;
  2058. } else {
  2059. x = Math.sqrt(xx);
  2060. y = xy / x;
  2061. z = xz / x;
  2062. }
  2063. } else if (yy > zz) {
  2064. // m22 is the largest diagonal term
  2065. if (yy < epsilon) {
  2066. x = 0.707106781;
  2067. y = 0;
  2068. z = 0.707106781;
  2069. } else {
  2070. y = Math.sqrt(yy);
  2071. x = xy / y;
  2072. z = yz / y;
  2073. }
  2074. } else {
  2075. // m33 is the largest diagonal term so base result on this
  2076. if (zz < epsilon) {
  2077. x = 0.707106781;
  2078. y = 0.707106781;
  2079. z = 0;
  2080. } else {
  2081. z = Math.sqrt(zz);
  2082. x = xz / z;
  2083. y = yz / z;
  2084. }
  2085. }
  2086. this.set(x, y, z, angle);
  2087. return this; // return 180 deg rotation
  2088. } // as we have reached here there are no singularities so we can handle normally
  2089. let s = Math.sqrt((m32 - m23) * (m32 - m23) + (m13 - m31) * (m13 - m31) + (m21 - m12) * (m21 - m12)); // used to normalize
  2090. if (Math.abs(s) < 0.001) s = 1; // prevent divide by zero, should not happen if matrix is orthogonal and should be
  2091. // caught by singularity test above, but I've left it in just in case
  2092. this.x = (m32 - m23) / s;
  2093. this.y = (m13 - m31) / s;
  2094. this.z = (m21 - m12) / s;
  2095. this.w = Math.acos((m11 + m22 + m33 - 1) / 2);
  2096. return this;
  2097. }
  2098. min(v) {
  2099. this.x = Math.min(this.x, v.x);
  2100. this.y = Math.min(this.y, v.y);
  2101. this.z = Math.min(this.z, v.z);
  2102. this.w = Math.min(this.w, v.w);
  2103. return this;
  2104. }
  2105. max(v) {
  2106. this.x = Math.max(this.x, v.x);
  2107. this.y = Math.max(this.y, v.y);
  2108. this.z = Math.max(this.z, v.z);
  2109. this.w = Math.max(this.w, v.w);
  2110. return this;
  2111. }
  2112. clamp(min, max) {
  2113. // assumes min < max, componentwise
  2114. this.x = Math.max(min.x, Math.min(max.x, this.x));
  2115. this.y = Math.max(min.y, Math.min(max.y, this.y));
  2116. this.z = Math.max(min.z, Math.min(max.z, this.z));
  2117. this.w = Math.max(min.w, Math.min(max.w, this.w));
  2118. return this;
  2119. }
  2120. clampScalar(minVal, maxVal) {
  2121. this.x = Math.max(minVal, Math.min(maxVal, this.x));
  2122. this.y = Math.max(minVal, Math.min(maxVal, this.y));
  2123. this.z = Math.max(minVal, Math.min(maxVal, this.z));
  2124. this.w = Math.max(minVal, Math.min(maxVal, this.w));
  2125. return this;
  2126. }
  2127. clampLength(min, max) {
  2128. const length = this.length();
  2129. return this.divideScalar(length || 1).multiplyScalar(Math.max(min, Math.min(max, length)));
  2130. }
  2131. floor() {
  2132. this.x = Math.floor(this.x);
  2133. this.y = Math.floor(this.y);
  2134. this.z = Math.floor(this.z);
  2135. this.w = Math.floor(this.w);
  2136. return this;
  2137. }
  2138. ceil() {
  2139. this.x = Math.ceil(this.x);
  2140. this.y = Math.ceil(this.y);
  2141. this.z = Math.ceil(this.z);
  2142. this.w = Math.ceil(this.w);
  2143. return this;
  2144. }
  2145. round() {
  2146. this.x = Math.round(this.x);
  2147. this.y = Math.round(this.y);
  2148. this.z = Math.round(this.z);
  2149. this.w = Math.round(this.w);
  2150. return this;
  2151. }
  2152. roundToZero() {
  2153. this.x = this.x < 0 ? Math.ceil(this.x) : Math.floor(this.x);
  2154. this.y = this.y < 0 ? Math.ceil(this.y) : Math.floor(this.y);
  2155. this.z = this.z < 0 ? Math.ceil(this.z) : Math.floor(this.z);
  2156. this.w = this.w < 0 ? Math.ceil(this.w) : Math.floor(this.w);
  2157. return this;
  2158. }
  2159. negate() {
  2160. this.x = -this.x;
  2161. this.y = -this.y;
  2162. this.z = -this.z;
  2163. this.w = -this.w;
  2164. return this;
  2165. }
  2166. dot(v) {
  2167. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  2168. }
  2169. lengthSq() {
  2170. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  2171. }
  2172. length() {
  2173. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  2174. }
  2175. manhattanLength() {
  2176. return Math.abs(this.x) + Math.abs(this.y) + Math.abs(this.z) + Math.abs(this.w);
  2177. }
  2178. normalize() {
  2179. return this.divideScalar(this.length() || 1);
  2180. }
  2181. setLength(length) {
  2182. return this.normalize().multiplyScalar(length);
  2183. }
  2184. lerp(v, alpha) {
  2185. this.x += (v.x - this.x) * alpha;
  2186. this.y += (v.y - this.y) * alpha;
  2187. this.z += (v.z - this.z) * alpha;
  2188. this.w += (v.w - this.w) * alpha;
  2189. return this;
  2190. }
  2191. lerpVectors(v1, v2, alpha) {
  2192. this.x = v1.x + (v2.x - v1.x) * alpha;
  2193. this.y = v1.y + (v2.y - v1.y) * alpha;
  2194. this.z = v1.z + (v2.z - v1.z) * alpha;
  2195. this.w = v1.w + (v2.w - v1.w) * alpha;
  2196. return this;
  2197. }
  2198. equals(v) {
  2199. return v.x === this.x && v.y === this.y && v.z === this.z && v.w === this.w;
  2200. }
  2201. fromArray(array, offset = 0) {
  2202. this.x = array[offset];
  2203. this.y = array[offset + 1];
  2204. this.z = array[offset + 2];
  2205. this.w = array[offset + 3];
  2206. return this;
  2207. }
  2208. toArray(array = [], offset = 0) {
  2209. array[offset] = this.x;
  2210. array[offset + 1] = this.y;
  2211. array[offset + 2] = this.z;
  2212. array[offset + 3] = this.w;
  2213. return array;
  2214. }
  2215. fromBufferAttribute(attribute, index, offset) {
  2216. if (offset !== undefined) {
  2217. console.warn('THREE.Vector4: offset has been removed from .fromBufferAttribute().');
  2218. }
  2219. this.x = attribute.getX(index);
  2220. this.y = attribute.getY(index);
  2221. this.z = attribute.getZ(index);
  2222. this.w = attribute.getW(index);
  2223. return this;
  2224. }
  2225. random() {
  2226. this.x = Math.random();
  2227. this.y = Math.random();
  2228. this.z = Math.random();
  2229. this.w = Math.random();
  2230. return this;
  2231. }
  2232. *[Symbol.iterator]() {
  2233. yield this.x;
  2234. yield this.y;
  2235. yield this.z;
  2236. yield this.w;
  2237. }
  2238. }
  2239. /*
  2240. In options, we can specify:
  2241. * Texture parameters for an auto-generated target texture
  2242. * depthBuffer/stencilBuffer: Booleans to indicate if we should generate these buffers
  2243. */
  2244. class WebGLRenderTarget extends EventDispatcher {
  2245. constructor(width, height, options = {}) {
  2246. super();
  2247. this.isWebGLRenderTarget = true;
  2248. this.width = width;
  2249. this.height = height;
  2250. this.depth = 1;
  2251. this.scissor = new Vector4(0, 0, width, height);
  2252. this.scissorTest = false;
  2253. this.viewport = new Vector4(0, 0, width, height);
  2254. const image = {
  2255. width: width,
  2256. height: height,
  2257. depth: 1
  2258. };
  2259. this.texture = new Texture(image, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding);
  2260. this.texture.isRenderTargetTexture = true;
  2261. this.texture.flipY = false;
  2262. this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false;
  2263. this.texture.internalFormat = options.internalFormat !== undefined ? options.internalFormat : null;
  2264. this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter;
  2265. this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
  2266. this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : false;
  2267. this.depthTexture = options.depthTexture !== undefined ? options.depthTexture : null;
  2268. this.samples = options.samples !== undefined ? options.samples : 0;
  2269. }
  2270. setSize(width, height, depth = 1) {
  2271. if (this.width !== width || this.height !== height || this.depth !== depth) {
  2272. this.width = width;
  2273. this.height = height;
  2274. this.depth = depth;
  2275. this.texture.image.width = width;
  2276. this.texture.image.height = height;
  2277. this.texture.image.depth = depth;
  2278. this.dispose();
  2279. }
  2280. this.viewport.set(0, 0, width, height);
  2281. this.scissor.set(0, 0, width, height);
  2282. }
  2283. clone() {
  2284. return new this.constructor().copy(this);
  2285. }
  2286. copy(source) {
  2287. this.width = source.width;
  2288. this.height = source.height;
  2289. this.depth = source.depth;
  2290. this.viewport.copy(source.viewport);
  2291. this.texture = source.texture.clone();
  2292. this.texture.isRenderTargetTexture = true; // ensure image object is not shared, see #20328
  2293. const image = Object.assign({}, source.texture.image);
  2294. this.texture.source = new Source(image);
  2295. this.depthBuffer = source.depthBuffer;
  2296. this.stencilBuffer = source.stencilBuffer;
  2297. if (source.depthTexture !== null) this.depthTexture = source.depthTexture.clone();
  2298. this.samples = source.samples;
  2299. return this;
  2300. }
  2301. dispose() {
  2302. this.dispatchEvent({
  2303. type: 'dispose'
  2304. });
  2305. }
  2306. }
  2307. class DataArrayTexture extends Texture {
  2308. constructor(data = null, width = 1, height = 1, depth = 1) {
  2309. super(null);
  2310. this.isDataArrayTexture = true;
  2311. this.image = {
  2312. data,
  2313. width,
  2314. height,
  2315. depth
  2316. };
  2317. this.magFilter = NearestFilter;
  2318. this.minFilter = NearestFilter;
  2319. this.wrapR = ClampToEdgeWrapping;
  2320. this.generateMipmaps = false;
  2321. this.flipY = false;
  2322. this.unpackAlignment = 1;
  2323. }
  2324. }
  2325. class WebGLArrayRenderTarget extends WebGLRenderTarget {
  2326. constructor(width, height, depth) {
  2327. super(width, height);
  2328. this.isWebGLArrayRenderTarget = true;
  2329. this.depth = depth;
  2330. this.texture = new DataArrayTexture(null, width, height, depth);
  2331. this.texture.isRenderTargetTexture = true;
  2332. }
  2333. }
  2334. class Data3DTexture extends Texture {
  2335. constructor(data = null, width = 1, height = 1, depth = 1) {
  2336. // We're going to add .setXXX() methods for setting properties later.
  2337. // Users can still set in DataTexture3D directly.
  2338. //
  2339. // const texture = new THREE.DataTexture3D( data, width, height, depth );
  2340. // texture.anisotropy = 16;
  2341. //
  2342. // See #14839
  2343. super(null);
  2344. this.isData3DTexture = true;
  2345. this.image = {
  2346. data,
  2347. width,
  2348. height,
  2349. depth
  2350. };
  2351. this.magFilter = NearestFilter;
  2352. this.minFilter = NearestFilter;
  2353. this.wrapR = ClampToEdgeWrapping;
  2354. this.generateMipmaps = false;
  2355. this.flipY = false;
  2356. this.unpackAlignment = 1;
  2357. }
  2358. }
  2359. class WebGL3DRenderTarget extends WebGLRenderTarget {
  2360. constructor(width, height, depth) {
  2361. super(width, height);
  2362. this.isWebGL3DRenderTarget = true;
  2363. this.depth = depth;
  2364. this.texture = new Data3DTexture(null, width, height, depth);
  2365. this.texture.isRenderTargetTexture = true;
  2366. }
  2367. }
  2368. class WebGLMultipleRenderTargets extends WebGLRenderTarget {
  2369. constructor(width, height, count, options = {}) {
  2370. super(width, height, options);
  2371. this.isWebGLMultipleRenderTargets = true;
  2372. const texture = this.texture;
  2373. this.texture = [];
  2374. for (let i = 0; i < count; i++) {
  2375. this.texture[i] = texture.clone();
  2376. this.texture[i].isRenderTargetTexture = true;
  2377. }
  2378. }
  2379. setSize(width, height, depth = 1) {
  2380. if (this.width !== width || this.height !== height || this.depth !== depth) {
  2381. this.width = width;
  2382. this.height = height;
  2383. this.depth = depth;
  2384. for (let i = 0, il = this.texture.length; i < il; i++) {
  2385. this.texture[i].image.width = width;
  2386. this.texture[i].image.height = height;
  2387. this.texture[i].image.depth = depth;
  2388. }
  2389. this.dispose();
  2390. }
  2391. this.viewport.set(0, 0, width, height);
  2392. this.scissor.set(0, 0, width, height);
  2393. return this;
  2394. }
  2395. copy(source) {
  2396. this.dispose();
  2397. this.width = source.width;
  2398. this.height = source.height;
  2399. this.depth = source.depth;
  2400. this.viewport.set(0, 0, this.width, this.height);
  2401. this.scissor.set(0, 0, this.width, this.height);
  2402. this.depthBuffer = source.depthBuffer;
  2403. this.stencilBuffer = source.stencilBuffer;
  2404. if (source.depthTexture !== null) this.depthTexture = source.depthTexture.clone();
  2405. this.texture.length = 0;
  2406. for (let i = 0, il = source.texture.length; i < il; i++) {
  2407. this.texture[i] = source.texture[i].clone();
  2408. this.texture[i].isRenderTargetTexture = true;
  2409. }
  2410. return this;
  2411. }
  2412. }
  2413. class Quaternion {
  2414. constructor(x = 0, y = 0, z = 0, w = 1) {
  2415. this.isQuaternion = true;
  2416. this._x = x;
  2417. this._y = y;
  2418. this._z = z;
  2419. this._w = w;
  2420. }
  2421. static slerp(qa, qb, qm, t) {
  2422. console.warn('THREE.Quaternion: Static .slerp() has been deprecated. Use qm.slerpQuaternions( qa, qb, t ) instead.');
  2423. return qm.slerpQuaternions(qa, qb, t);
  2424. }
  2425. static slerpFlat(dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t) {
  2426. // fuzz-free, array-based Quaternion SLERP operation
  2427. let x0 = src0[srcOffset0 + 0],
  2428. y0 = src0[srcOffset0 + 1],
  2429. z0 = src0[srcOffset0 + 2],
  2430. w0 = src0[srcOffset0 + 3];
  2431. const x1 = src1[srcOffset1 + 0],
  2432. y1 = src1[srcOffset1 + 1],
  2433. z1 = src1[srcOffset1 + 2],
  2434. w1 = src1[srcOffset1 + 3];
  2435. if (t === 0) {
  2436. dst[dstOffset + 0] = x0;
  2437. dst[dstOffset + 1] = y0;
  2438. dst[dstOffset + 2] = z0;
  2439. dst[dstOffset + 3] = w0;
  2440. return;
  2441. }
  2442. if (t === 1) {
  2443. dst[dstOffset + 0] = x1;
  2444. dst[dstOffset + 1] = y1;
  2445. dst[dstOffset + 2] = z1;
  2446. dst[dstOffset + 3] = w1;
  2447. return;
  2448. }
  2449. if (w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1) {
  2450. let s = 1 - t;
  2451. const cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1,
  2452. dir = cos >= 0 ? 1 : -1,
  2453. sqrSin = 1 - cos * cos; // Skip the Slerp for tiny steps to avoid numeric problems:
  2454. if (sqrSin > Number.EPSILON) {
  2455. const sin = Math.sqrt(sqrSin),
  2456. len = Math.atan2(sin, cos * dir);
  2457. s = Math.sin(s * len) / sin;
  2458. t = Math.sin(t * len) / sin;
  2459. }
  2460. const tDir = t * dir;
  2461. x0 = x0 * s + x1 * tDir;
  2462. y0 = y0 * s + y1 * tDir;
  2463. z0 = z0 * s + z1 * tDir;
  2464. w0 = w0 * s + w1 * tDir; // Normalize in case we just did a lerp:
  2465. if (s === 1 - t) {
  2466. const f = 1 / Math.sqrt(x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0);
  2467. x0 *= f;
  2468. y0 *= f;
  2469. z0 *= f;
  2470. w0 *= f;
  2471. }
  2472. }
  2473. dst[dstOffset] = x0;
  2474. dst[dstOffset + 1] = y0;
  2475. dst[dstOffset + 2] = z0;
  2476. dst[dstOffset + 3] = w0;
  2477. }
  2478. static multiplyQuaternionsFlat(dst, dstOffset, src0, srcOffset0, src1, srcOffset1) {
  2479. const x0 = src0[srcOffset0];
  2480. const y0 = src0[srcOffset0 + 1];
  2481. const z0 = src0[srcOffset0 + 2];
  2482. const w0 = src0[srcOffset0 + 3];
  2483. const x1 = src1[srcOffset1];
  2484. const y1 = src1[srcOffset1 + 1];
  2485. const z1 = src1[srcOffset1 + 2];
  2486. const w1 = src1[srcOffset1 + 3];
  2487. dst[dstOffset] = x0 * w1 + w0 * x1 + y0 * z1 - z0 * y1;
  2488. dst[dstOffset + 1] = y0 * w1 + w0 * y1 + z0 * x1 - x0 * z1;
  2489. dst[dstOffset + 2] = z0 * w1 + w0 * z1 + x0 * y1 - y0 * x1;
  2490. dst[dstOffset + 3] = w0 * w1 - x0 * x1 - y0 * y1 - z0 * z1;
  2491. return dst;
  2492. }
  2493. get x() {
  2494. return this._x;
  2495. }
  2496. set x(value) {
  2497. this._x = value;
  2498. this._onChangeCallback();
  2499. }
  2500. get y() {
  2501. return this._y;
  2502. }
  2503. set y(value) {
  2504. this._y = value;
  2505. this._onChangeCallback();
  2506. }
  2507. get z() {
  2508. return this._z;
  2509. }
  2510. set z(value) {
  2511. this._z = value;
  2512. this._onChangeCallback();
  2513. }
  2514. get w() {
  2515. return this._w;
  2516. }
  2517. set w(value) {
  2518. this._w = value;
  2519. this._onChangeCallback();
  2520. }
  2521. set(x, y, z, w) {
  2522. this._x = x;
  2523. this._y = y;
  2524. this._z = z;
  2525. this._w = w;
  2526. this._onChangeCallback();
  2527. return this;
  2528. }
  2529. clone() {
  2530. return new this.constructor(this._x, this._y, this._z, this._w);
  2531. }
  2532. copy(quaternion) {
  2533. this._x = quaternion.x;
  2534. this._y = quaternion.y;
  2535. this._z = quaternion.z;
  2536. this._w = quaternion.w;
  2537. this._onChangeCallback();
  2538. return this;
  2539. }
  2540. setFromEuler(euler, update) {
  2541. if (!(euler && euler.isEuler)) {
  2542. throw new Error('THREE.Quaternion: .setFromEuler() now expects an Euler rotation rather than a Vector3 and order.');
  2543. }
  2544. const x = euler._x,
  2545. y = euler._y,
  2546. z = euler._z,
  2547. order = euler._order; // http://www.mathworks.com/matlabcentral/fileexchange/
  2548. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  2549. // content/SpinCalc.m
  2550. const cos = Math.cos;
  2551. const sin = Math.sin;
  2552. const c1 = cos(x / 2);
  2553. const c2 = cos(y / 2);
  2554. const c3 = cos(z / 2);
  2555. const s1 = sin(x / 2);
  2556. const s2 = sin(y / 2);
  2557. const s3 = sin(z / 2);
  2558. switch (order) {
  2559. case 'XYZ':
  2560. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  2561. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  2562. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  2563. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  2564. break;
  2565. case 'YXZ':
  2566. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  2567. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  2568. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  2569. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  2570. break;
  2571. case 'ZXY':
  2572. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  2573. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  2574. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  2575. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  2576. break;
  2577. case 'ZYX':
  2578. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  2579. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  2580. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  2581. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  2582. break;
  2583. case 'YZX':
  2584. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  2585. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  2586. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  2587. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  2588. break;
  2589. case 'XZY':
  2590. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  2591. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  2592. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  2593. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  2594. break;
  2595. default:
  2596. console.warn('THREE.Quaternion: .setFromEuler() encountered an unknown order: ' + order);
  2597. }
  2598. if (update !== false) this._onChangeCallback();
  2599. return this;
  2600. }
  2601. setFromAxisAngle(axis, angle) {
  2602. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  2603. // assumes axis is normalized
  2604. const halfAngle = angle / 2,
  2605. s = Math.sin(halfAngle);
  2606. this._x = axis.x * s;
  2607. this._y = axis.y * s;
  2608. this._z = axis.z * s;
  2609. this._w = Math.cos(halfAngle);
  2610. this._onChangeCallback();
  2611. return this;
  2612. }
  2613. setFromRotationMatrix(m) {
  2614. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  2615. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  2616. const te = m.elements,
  2617. m11 = te[0],
  2618. m12 = te[4],
  2619. m13 = te[8],
  2620. m21 = te[1],
  2621. m22 = te[5],
  2622. m23 = te[9],
  2623. m31 = te[2],
  2624. m32 = te[6],
  2625. m33 = te[10],
  2626. trace = m11 + m22 + m33;
  2627. if (trace > 0) {
  2628. const s = 0.5 / Math.sqrt(trace + 1.0);
  2629. this._w = 0.25 / s;
  2630. this._x = (m32 - m23) * s;
  2631. this._y = (m13 - m31) * s;
  2632. this._z = (m21 - m12) * s;
  2633. } else if (m11 > m22 && m11 > m33) {
  2634. const s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  2635. this._w = (m32 - m23) / s;
  2636. this._x = 0.25 * s;
  2637. this._y = (m12 + m21) / s;
  2638. this._z = (m13 + m31) / s;
  2639. } else if (m22 > m33) {
  2640. const s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  2641. this._w = (m13 - m31) / s;
  2642. this._x = (m12 + m21) / s;
  2643. this._y = 0.25 * s;
  2644. this._z = (m23 + m32) / s;
  2645. } else {
  2646. const s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  2647. this._w = (m21 - m12) / s;
  2648. this._x = (m13 + m31) / s;
  2649. this._y = (m23 + m32) / s;
  2650. this._z = 0.25 * s;
  2651. }
  2652. this._onChangeCallback();
  2653. return this;
  2654. }
  2655. setFromUnitVectors(vFrom, vTo) {
  2656. // assumes direction vectors vFrom and vTo are normalized
  2657. let r = vFrom.dot(vTo) + 1;
  2658. if (r < Number.EPSILON) {
  2659. // vFrom and vTo point in opposite directions
  2660. r = 0;
  2661. if (Math.abs(vFrom.x) > Math.abs(vFrom.z)) {
  2662. this._x = -vFrom.y;
  2663. this._y = vFrom.x;
  2664. this._z = 0;
  2665. this._w = r;
  2666. } else {
  2667. this._x = 0;
  2668. this._y = -vFrom.z;
  2669. this._z = vFrom.y;
  2670. this._w = r;
  2671. }
  2672. } else {
  2673. // crossVectors( vFrom, vTo ); // inlined to avoid cyclic dependency on Vector3
  2674. this._x = vFrom.y * vTo.z - vFrom.z * vTo.y;
  2675. this._y = vFrom.z * vTo.x - vFrom.x * vTo.z;
  2676. this._z = vFrom.x * vTo.y - vFrom.y * vTo.x;
  2677. this._w = r;
  2678. }
  2679. return this.normalize();
  2680. }
  2681. angleTo(q) {
  2682. return 2 * Math.acos(Math.abs(clamp(this.dot(q), -1, 1)));
  2683. }
  2684. rotateTowards(q, step) {
  2685. const angle = this.angleTo(q);
  2686. if (angle === 0) return this;
  2687. const t = Math.min(1, step / angle);
  2688. this.slerp(q, t);
  2689. return this;
  2690. }
  2691. identity() {
  2692. return this.set(0, 0, 0, 1);
  2693. }
  2694. invert() {
  2695. // quaternion is assumed to have unit length
  2696. return this.conjugate();
  2697. }
  2698. conjugate() {
  2699. this._x *= -1;
  2700. this._y *= -1;
  2701. this._z *= -1;
  2702. this._onChangeCallback();
  2703. return this;
  2704. }
  2705. dot(v) {
  2706. return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w;
  2707. }
  2708. lengthSq() {
  2709. return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  2710. }
  2711. length() {
  2712. return Math.sqrt(this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w);
  2713. }
  2714. normalize() {
  2715. let l = this.length();
  2716. if (l === 0) {
  2717. this._x = 0;
  2718. this._y = 0;
  2719. this._z = 0;
  2720. this._w = 1;
  2721. } else {
  2722. l = 1 / l;
  2723. this._x = this._x * l;
  2724. this._y = this._y * l;
  2725. this._z = this._z * l;
  2726. this._w = this._w * l;
  2727. }
  2728. this._onChangeCallback();
  2729. return this;
  2730. }
  2731. multiply(q, p) {
  2732. if (p !== undefined) {
  2733. console.warn('THREE.Quaternion: .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead.');
  2734. return this.multiplyQuaternions(q, p);
  2735. }
  2736. return this.multiplyQuaternions(this, q);
  2737. }
  2738. premultiply(q) {
  2739. return this.multiplyQuaternions(q, this);
  2740. }
  2741. multiplyQuaternions(a, b) {
  2742. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  2743. const qax = a._x,
  2744. qay = a._y,
  2745. qaz = a._z,
  2746. qaw = a._w;
  2747. const qbx = b._x,
  2748. qby = b._y,
  2749. qbz = b._z,
  2750. qbw = b._w;
  2751. this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  2752. this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  2753. this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  2754. this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  2755. this._onChangeCallback();
  2756. return this;
  2757. }
  2758. slerp(qb, t) {
  2759. if (t === 0) return this;
  2760. if (t === 1) return this.copy(qb);
  2761. const x = this._x,
  2762. y = this._y,
  2763. z = this._z,
  2764. w = this._w; // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  2765. let cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z;
  2766. if (cosHalfTheta < 0) {
  2767. this._w = -qb._w;
  2768. this._x = -qb._x;
  2769. this._y = -qb._y;
  2770. this._z = -qb._z;
  2771. cosHalfTheta = -cosHalfTheta;
  2772. } else {
  2773. this.copy(qb);
  2774. }
  2775. if (cosHalfTheta >= 1.0) {
  2776. this._w = w;
  2777. this._x = x;
  2778. this._y = y;
  2779. this._z = z;
  2780. return this;
  2781. }
  2782. const sqrSinHalfTheta = 1.0 - cosHalfTheta * cosHalfTheta;
  2783. if (sqrSinHalfTheta <= Number.EPSILON) {
  2784. const s = 1 - t;
  2785. this._w = s * w + t * this._w;
  2786. this._x = s * x + t * this._x;
  2787. this._y = s * y + t * this._y;
  2788. this._z = s * z + t * this._z;
  2789. this.normalize();
  2790. this._onChangeCallback();
  2791. return this;
  2792. }
  2793. const sinHalfTheta = Math.sqrt(sqrSinHalfTheta);
  2794. const halfTheta = Math.atan2(sinHalfTheta, cosHalfTheta);
  2795. const ratioA = Math.sin((1 - t) * halfTheta) / sinHalfTheta,
  2796. ratioB = Math.sin(t * halfTheta) / sinHalfTheta;
  2797. this._w = w * ratioA + this._w * ratioB;
  2798. this._x = x * ratioA + this._x * ratioB;
  2799. this._y = y * ratioA + this._y * ratioB;
  2800. this._z = z * ratioA + this._z * ratioB;
  2801. this._onChangeCallback();
  2802. return this;
  2803. }
  2804. slerpQuaternions(qa, qb, t) {
  2805. return this.copy(qa).slerp(qb, t);
  2806. }
  2807. random() {
  2808. // Derived from http://planning.cs.uiuc.edu/node198.html
  2809. // Note, this source uses w, x, y, z ordering,
  2810. // so we swap the order below.
  2811. const u1 = Math.random();
  2812. const sqrt1u1 = Math.sqrt(1 - u1);
  2813. const sqrtu1 = Math.sqrt(u1);
  2814. const u2 = 2 * Math.PI * Math.random();
  2815. const u3 = 2 * Math.PI * Math.random();
  2816. return this.set(sqrt1u1 * Math.cos(u2), sqrtu1 * Math.sin(u3), sqrtu1 * Math.cos(u3), sqrt1u1 * Math.sin(u2));
  2817. }
  2818. equals(quaternion) {
  2819. return quaternion._x === this._x && quaternion._y === this._y && quaternion._z === this._z && quaternion._w === this._w;
  2820. }
  2821. fromArray(array, offset = 0) {
  2822. this._x = array[offset];
  2823. this._y = array[offset + 1];
  2824. this._z = array[offset + 2];
  2825. this._w = array[offset + 3];
  2826. this._onChangeCallback();
  2827. return this;
  2828. }
  2829. toArray(array = [], offset = 0) {
  2830. array[offset] = this._x;
  2831. array[offset + 1] = this._y;
  2832. array[offset + 2] = this._z;
  2833. array[offset + 3] = this._w;
  2834. return array;
  2835. }
  2836. fromBufferAttribute(attribute, index) {
  2837. this._x = attribute.getX(index);
  2838. this._y = attribute.getY(index);
  2839. this._z = attribute.getZ(index);
  2840. this._w = attribute.getW(index);
  2841. return this;
  2842. }
  2843. _onChange(callback) {
  2844. this._onChangeCallback = callback;
  2845. return this;
  2846. }
  2847. _onChangeCallback() {}
  2848. *[Symbol.iterator]() {
  2849. yield this._x;
  2850. yield this._y;
  2851. yield this._z;
  2852. yield this._w;
  2853. }
  2854. }
  2855. class Vector3 {
  2856. constructor(x = 0, y = 0, z = 0) {
  2857. this.isVector3 = true;
  2858. this.x = x;
  2859. this.y = y;
  2860. this.z = z;
  2861. }
  2862. set(x, y, z) {
  2863. if (z === undefined) z = this.z; // sprite.scale.set(x,y)
  2864. this.x = x;
  2865. this.y = y;
  2866. this.z = z;
  2867. return this;
  2868. }
  2869. setScalar(scalar) {
  2870. this.x = scalar;
  2871. this.y = scalar;
  2872. this.z = scalar;
  2873. return this;
  2874. }
  2875. setX(x) {
  2876. this.x = x;
  2877. return this;
  2878. }
  2879. setY(y) {
  2880. this.y = y;
  2881. return this;
  2882. }
  2883. setZ(z) {
  2884. this.z = z;
  2885. return this;
  2886. }
  2887. setComponent(index, value) {
  2888. switch (index) {
  2889. case 0:
  2890. this.x = value;
  2891. break;
  2892. case 1:
  2893. this.y = value;
  2894. break;
  2895. case 2:
  2896. this.z = value;
  2897. break;
  2898. default:
  2899. throw new Error('index is out of range: ' + index);
  2900. }
  2901. return this;
  2902. }
  2903. getComponent(index) {
  2904. switch (index) {
  2905. case 0:
  2906. return this.x;
  2907. case 1:
  2908. return this.y;
  2909. case 2:
  2910. return this.z;
  2911. default:
  2912. throw new Error('index is out of range: ' + index);
  2913. }
  2914. }
  2915. clone() {
  2916. return new this.constructor(this.x, this.y, this.z);
  2917. }
  2918. copy(v) {
  2919. this.x = v.x;
  2920. this.y = v.y;
  2921. this.z = v.z;
  2922. return this;
  2923. }
  2924. add(v, w) {
  2925. if (w !== undefined) {
  2926. console.warn('THREE.Vector3: .add() now only accepts one argument. Use .addVectors( a, b ) instead.');
  2927. return this.addVectors(v, w);
  2928. }
  2929. this.x += v.x;
  2930. this.y += v.y;
  2931. this.z += v.z;
  2932. return this;
  2933. }
  2934. addScalar(s) {
  2935. this.x += s;
  2936. this.y += s;
  2937. this.z += s;
  2938. return this;
  2939. }
  2940. addVectors(a, b) {
  2941. this.x = a.x + b.x;
  2942. this.y = a.y + b.y;
  2943. this.z = a.z + b.z;
  2944. return this;
  2945. }
  2946. addScaledVector(v, s) {
  2947. this.x += v.x * s;
  2948. this.y += v.y * s;
  2949. this.z += v.z * s;
  2950. return this;
  2951. }
  2952. sub(v, w) {
  2953. if (w !== undefined) {
  2954. console.warn('THREE.Vector3: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.');
  2955. return this.subVectors(v, w);
  2956. }
  2957. this.x -= v.x;
  2958. this.y -= v.y;
  2959. this.z -= v.z;
  2960. return this;
  2961. }
  2962. subScalar(s) {
  2963. this.x -= s;
  2964. this.y -= s;
  2965. this.z -= s;
  2966. return this;
  2967. }
  2968. subVectors(a, b) {
  2969. this.x = a.x - b.x;
  2970. this.y = a.y - b.y;
  2971. this.z = a.z - b.z;
  2972. return this;
  2973. }
  2974. multiply(v, w) {
  2975. if (w !== undefined) {
  2976. console.warn('THREE.Vector3: .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead.');
  2977. return this.multiplyVectors(v, w);
  2978. }
  2979. this.x *= v.x;
  2980. this.y *= v.y;
  2981. this.z *= v.z;
  2982. return this;
  2983. }
  2984. multiplyScalar(scalar) {
  2985. this.x *= scalar;
  2986. this.y *= scalar;
  2987. this.z *= scalar;
  2988. return this;
  2989. }
  2990. multiplyVectors(a, b) {
  2991. this.x = a.x * b.x;
  2992. this.y = a.y * b.y;
  2993. this.z = a.z * b.z;
  2994. return this;
  2995. }
  2996. applyEuler(euler) {
  2997. if (!(euler && euler.isEuler)) {
  2998. console.error('THREE.Vector3: .applyEuler() now expects an Euler rotation rather than a Vector3 and order.');
  2999. }
  3000. return this.applyQuaternion(_quaternion$4.setFromEuler(euler));
  3001. }
  3002. applyAxisAngle(axis, angle) {
  3003. return this.applyQuaternion(_quaternion$4.setFromAxisAngle(axis, angle));
  3004. }
  3005. applyMatrix3(m) {
  3006. const x = this.x,
  3007. y = this.y,
  3008. z = this.z;
  3009. const e = m.elements;
  3010. this.x = e[0] * x + e[3] * y + e[6] * z;
  3011. this.y = e[1] * x + e[4] * y + e[7] * z;
  3012. this.z = e[2] * x + e[5] * y + e[8] * z;
  3013. return this;
  3014. }
  3015. applyNormalMatrix(m) {
  3016. return this.applyMatrix3(m).normalize();
  3017. }
  3018. applyMatrix4(m) {
  3019. const x = this.x,
  3020. y = this.y,
  3021. z = this.z;
  3022. const e = m.elements;
  3023. const w = 1 / (e[3] * x + e[7] * y + e[11] * z + e[15]);
  3024. this.x = (e[0] * x + e[4] * y + e[8] * z + e[12]) * w;
  3025. this.y = (e[1] * x + e[5] * y + e[9] * z + e[13]) * w;
  3026. this.z = (e[2] * x + e[6] * y + e[10] * z + e[14]) * w;
  3027. return this;
  3028. }
  3029. applyQuaternion(q) {
  3030. const x = this.x,
  3031. y = this.y,
  3032. z = this.z;
  3033. const qx = q.x,
  3034. qy = q.y,
  3035. qz = q.z,
  3036. qw = q.w; // calculate quat * vector
  3037. const ix = qw * x + qy * z - qz * y;
  3038. const iy = qw * y + qz * x - qx * z;
  3039. const iz = qw * z + qx * y - qy * x;
  3040. const iw = -qx * x - qy * y - qz * z; // calculate result * inverse quat
  3041. this.x = ix * qw + iw * -qx + iy * -qz - iz * -qy;
  3042. this.y = iy * qw + iw * -qy + iz * -qx - ix * -qz;
  3043. this.z = iz * qw + iw * -qz + ix * -qy - iy * -qx;
  3044. return this;
  3045. }
  3046. project(camera) {
  3047. return this.applyMatrix4(camera.matrixWorldInverse).applyMatrix4(camera.projectionMatrix);
  3048. }
  3049. unproject(camera) {
  3050. return this.applyMatrix4(camera.projectionMatrixInverse).applyMatrix4(camera.matrixWorld);
  3051. }
  3052. transformDirection(m) {
  3053. // input: THREE.Matrix4 affine matrix
  3054. // vector interpreted as a direction
  3055. const x = this.x,
  3056. y = this.y,
  3057. z = this.z;
  3058. const e = m.elements;
  3059. this.x = e[0] * x + e[4] * y + e[8] * z;
  3060. this.y = e[1] * x + e[5] * y + e[9] * z;
  3061. this.z = e[2] * x + e[6] * y + e[10] * z;
  3062. return this.normalize();
  3063. }
  3064. divide(v) {
  3065. this.x /= v.x;
  3066. this.y /= v.y;
  3067. this.z /= v.z;
  3068. return this;
  3069. }
  3070. divideScalar(scalar) {
  3071. return this.multiplyScalar(1 / scalar);
  3072. }
  3073. min(v) {
  3074. this.x = Math.min(this.x, v.x);
  3075. this.y = Math.min(this.y, v.y);
  3076. this.z = Math.min(this.z, v.z);
  3077. return this;
  3078. }
  3079. max(v) {
  3080. this.x = Math.max(this.x, v.x);
  3081. this.y = Math.max(this.y, v.y);
  3082. this.z = Math.max(this.z, v.z);
  3083. return this;
  3084. }
  3085. clamp(min, max) {
  3086. // assumes min < max, componentwise
  3087. this.x = Math.max(min.x, Math.min(max.x, this.x));
  3088. this.y = Math.max(min.y, Math.min(max.y, this.y));
  3089. this.z = Math.max(min.z, Math.min(max.z, this.z));
  3090. return this;
  3091. }
  3092. clampScalar(minVal, maxVal) {
  3093. this.x = Math.max(minVal, Math.min(maxVal, this.x));
  3094. this.y = Math.max(minVal, Math.min(maxVal, this.y));
  3095. this.z = Math.max(minVal, Math.min(maxVal, this.z));
  3096. return this;
  3097. }
  3098. clampLength(min, max) {
  3099. const length = this.length();
  3100. return this.divideScalar(length || 1).multiplyScalar(Math.max(min, Math.min(max, length)));
  3101. }
  3102. floor() {
  3103. this.x = Math.floor(this.x);
  3104. this.y = Math.floor(this.y);
  3105. this.z = Math.floor(this.z);
  3106. return this;
  3107. }
  3108. ceil() {
  3109. this.x = Math.ceil(this.x);
  3110. this.y = Math.ceil(this.y);
  3111. this.z = Math.ceil(this.z);
  3112. return this;
  3113. }
  3114. round() {
  3115. this.x = Math.round(this.x);
  3116. this.y = Math.round(this.y);
  3117. this.z = Math.round(this.z);
  3118. return this;
  3119. }
  3120. roundToZero() {
  3121. this.x = this.x < 0 ? Math.ceil(this.x) : Math.floor(this.x);
  3122. this.y = this.y < 0 ? Math.ceil(this.y) : Math.floor(this.y);
  3123. this.z = this.z < 0 ? Math.ceil(this.z) : Math.floor(this.z);
  3124. return this;
  3125. }
  3126. negate() {
  3127. this.x = -this.x;
  3128. this.y = -this.y;
  3129. this.z = -this.z;
  3130. return this;
  3131. }
  3132. dot(v) {
  3133. return this.x * v.x + this.y * v.y + this.z * v.z;
  3134. } // TODO lengthSquared?
  3135. lengthSq() {
  3136. return this.x * this.x + this.y * this.y + this.z * this.z;
  3137. }
  3138. length() {
  3139. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  3140. }
  3141. manhattanLength() {
  3142. return Math.abs(this.x) + Math.abs(this.y) + Math.abs(this.z);
  3143. }
  3144. normalize() {
  3145. return this.divideScalar(this.length() || 1);
  3146. }
  3147. setLength(length) {
  3148. return this.normalize().multiplyScalar(length);
  3149. }
  3150. lerp(v, alpha) {
  3151. this.x += (v.x - this.x) * alpha;
  3152. this.y += (v.y - this.y) * alpha;
  3153. this.z += (v.z - this.z) * alpha;
  3154. return this;
  3155. }
  3156. lerpVectors(v1, v2, alpha) {
  3157. this.x = v1.x + (v2.x - v1.x) * alpha;
  3158. this.y = v1.y + (v2.y - v1.y) * alpha;
  3159. this.z = v1.z + (v2.z - v1.z) * alpha;
  3160. return this;
  3161. }
  3162. cross(v, w) {
  3163. if (w !== undefined) {
  3164. console.warn('THREE.Vector3: .cross() now only accepts one argument. Use .crossVectors( a, b ) instead.');
  3165. return this.crossVectors(v, w);
  3166. }
  3167. return this.crossVectors(this, v);
  3168. }
  3169. crossVectors(a, b) {
  3170. const ax = a.x,
  3171. ay = a.y,
  3172. az = a.z;
  3173. const bx = b.x,
  3174. by = b.y,
  3175. bz = b.z;
  3176. this.x = ay * bz - az * by;
  3177. this.y = az * bx - ax * bz;
  3178. this.z = ax * by - ay * bx;
  3179. return this;
  3180. }
  3181. projectOnVector(v) {
  3182. const denominator = v.lengthSq();
  3183. if (denominator === 0) return this.set(0, 0, 0);
  3184. const scalar = v.dot(this) / denominator;
  3185. return this.copy(v).multiplyScalar(scalar);
  3186. }
  3187. projectOnPlane(planeNormal) {
  3188. _vector$c.copy(this).projectOnVector(planeNormal);
  3189. return this.sub(_vector$c);
  3190. }
  3191. reflect(normal) {
  3192. // reflect incident vector off plane orthogonal to normal
  3193. // normal is assumed to have unit length
  3194. return this.sub(_vector$c.copy(normal).multiplyScalar(2 * this.dot(normal)));
  3195. }
  3196. angleTo(v) {
  3197. const denominator = Math.sqrt(this.lengthSq() * v.lengthSq());
  3198. if (denominator === 0) return Math.PI / 2;
  3199. const theta = this.dot(v) / denominator; // clamp, to handle numerical problems
  3200. return Math.acos(clamp(theta, -1, 1));
  3201. }
  3202. distanceTo(v) {
  3203. return Math.sqrt(this.distanceToSquared(v));
  3204. }
  3205. distanceToSquared(v) {
  3206. const dx = this.x - v.x,
  3207. dy = this.y - v.y,
  3208. dz = this.z - v.z;
  3209. return dx * dx + dy * dy + dz * dz;
  3210. }
  3211. manhattanDistanceTo(v) {
  3212. return Math.abs(this.x - v.x) + Math.abs(this.y - v.y) + Math.abs(this.z - v.z);
  3213. }
  3214. setFromSpherical(s) {
  3215. return this.setFromSphericalCoords(s.radius, s.phi, s.theta);
  3216. }
  3217. setFromSphericalCoords(radius, phi, theta) {
  3218. const sinPhiRadius = Math.sin(phi) * radius;
  3219. this.x = sinPhiRadius * Math.sin(theta);
  3220. this.y = Math.cos(phi) * radius;
  3221. this.z = sinPhiRadius * Math.cos(theta);
  3222. return this;
  3223. }
  3224. setFromCylindrical(c) {
  3225. return this.setFromCylindricalCoords(c.radius, c.theta, c.y);
  3226. }
  3227. setFromCylindricalCoords(radius, theta, y) {
  3228. this.x = radius * Math.sin(theta);
  3229. this.y = y;
  3230. this.z = radius * Math.cos(theta);
  3231. return this;
  3232. }
  3233. setFromMatrixPosition(m) {
  3234. const e = m.elements;
  3235. this.x = e[12];
  3236. this.y = e[13];
  3237. this.z = e[14];
  3238. return this;
  3239. }
  3240. setFromMatrixScale(m) {
  3241. const sx = this.setFromMatrixColumn(m, 0).length();
  3242. const sy = this.setFromMatrixColumn(m, 1).length();
  3243. const sz = this.setFromMatrixColumn(m, 2).length();
  3244. this.x = sx;
  3245. this.y = sy;
  3246. this.z = sz;
  3247. return this;
  3248. }
  3249. setFromMatrixColumn(m, index) {
  3250. return this.fromArray(m.elements, index * 4);
  3251. }
  3252. setFromMatrix3Column(m, index) {
  3253. return this.fromArray(m.elements, index * 3);
  3254. }
  3255. setFromEuler(e) {
  3256. this.x = e._x;
  3257. this.y = e._y;
  3258. this.z = e._z;
  3259. return this;
  3260. }
  3261. equals(v) {
  3262. return v.x === this.x && v.y === this.y && v.z === this.z;
  3263. }
  3264. fromArray(array, offset = 0) {
  3265. this.x = array[offset];
  3266. this.y = array[offset + 1];
  3267. this.z = array[offset + 2];
  3268. return this;
  3269. }
  3270. toArray(array = [], offset = 0) {
  3271. array[offset] = this.x;
  3272. array[offset + 1] = this.y;
  3273. array[offset + 2] = this.z;
  3274. return array;
  3275. }
  3276. fromBufferAttribute(attribute, index, offset) {
  3277. if (offset !== undefined) {
  3278. console.warn('THREE.Vector3: offset has been removed from .fromBufferAttribute().');
  3279. }
  3280. this.x = attribute.getX(index);
  3281. this.y = attribute.getY(index);
  3282. this.z = attribute.getZ(index);
  3283. return this;
  3284. }
  3285. random() {
  3286. this.x = Math.random();
  3287. this.y = Math.random();
  3288. this.z = Math.random();
  3289. return this;
  3290. }
  3291. randomDirection() {
  3292. // Derived from https://mathworld.wolfram.com/SpherePointPicking.html
  3293. const u = (Math.random() - 0.5) * 2;
  3294. const t = Math.random() * Math.PI * 2;
  3295. const f = Math.sqrt(1 - u ** 2);
  3296. this.x = f * Math.cos(t);
  3297. this.y = f * Math.sin(t);
  3298. this.z = u;
  3299. return this;
  3300. }
  3301. *[Symbol.iterator]() {
  3302. yield this.x;
  3303. yield this.y;
  3304. yield this.z;
  3305. }
  3306. }
  3307. const _vector$c = /*@__PURE__*/new Vector3();
  3308. const _quaternion$4 = /*@__PURE__*/new Quaternion();
  3309. class Box3 {
  3310. constructor(min = new Vector3(+Infinity, +Infinity, +Infinity), max = new Vector3(-Infinity, -Infinity, -Infinity)) {
  3311. this.isBox3 = true;
  3312. this.min = min;
  3313. this.max = max;
  3314. }
  3315. set(min, max) {
  3316. this.min.copy(min);
  3317. this.max.copy(max);
  3318. return this;
  3319. }
  3320. setFromArray(array) {
  3321. let minX = +Infinity;
  3322. let minY = +Infinity;
  3323. let minZ = +Infinity;
  3324. let maxX = -Infinity;
  3325. let maxY = -Infinity;
  3326. let maxZ = -Infinity;
  3327. for (let i = 0, l = array.length; i < l; i += 3) {
  3328. const x = array[i];
  3329. const y = array[i + 1];
  3330. const z = array[i + 2];
  3331. if (x < minX) minX = x;
  3332. if (y < minY) minY = y;
  3333. if (z < minZ) minZ = z;
  3334. if (x > maxX) maxX = x;
  3335. if (y > maxY) maxY = y;
  3336. if (z > maxZ) maxZ = z;
  3337. }
  3338. this.min.set(minX, minY, minZ);
  3339. this.max.set(maxX, maxY, maxZ);
  3340. return this;
  3341. }
  3342. setFromBufferAttribute(attribute) {
  3343. let minX = +Infinity;
  3344. let minY = +Infinity;
  3345. let minZ = +Infinity;
  3346. let maxX = -Infinity;
  3347. let maxY = -Infinity;
  3348. let maxZ = -Infinity;
  3349. for (let i = 0, l = attribute.count; i < l; i++) {
  3350. const x = attribute.getX(i);
  3351. const y = attribute.getY(i);
  3352. const z = attribute.getZ(i);
  3353. if (x < minX) minX = x;
  3354. if (y < minY) minY = y;
  3355. if (z < minZ) minZ = z;
  3356. if (x > maxX) maxX = x;
  3357. if (y > maxY) maxY = y;
  3358. if (z > maxZ) maxZ = z;
  3359. }
  3360. this.min.set(minX, minY, minZ);
  3361. this.max.set(maxX, maxY, maxZ);
  3362. return this;
  3363. }
  3364. setFromPoints(points) {
  3365. this.makeEmpty();
  3366. for (let i = 0, il = points.length; i < il; i++) {
  3367. this.expandByPoint(points[i]);
  3368. }
  3369. return this;
  3370. }
  3371. setFromCenterAndSize(center, size) {
  3372. const halfSize = _vector$b.copy(size).multiplyScalar(0.5);
  3373. this.min.copy(center).sub(halfSize);
  3374. this.max.copy(center).add(halfSize);
  3375. return this;
  3376. }
  3377. setFromObject(object, precise = false) {
  3378. this.makeEmpty();
  3379. return this.expandByObject(object, precise);
  3380. }
  3381. clone() {
  3382. return new this.constructor().copy(this);
  3383. }
  3384. copy(box) {
  3385. this.min.copy(box.min);
  3386. this.max.copy(box.max);
  3387. return this;
  3388. }
  3389. makeEmpty() {
  3390. this.min.x = this.min.y = this.min.z = +Infinity;
  3391. this.max.x = this.max.y = this.max.z = -Infinity;
  3392. return this;
  3393. }
  3394. isEmpty() {
  3395. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  3396. return this.max.x < this.min.x || this.max.y < this.min.y || this.max.z < this.min.z;
  3397. }
  3398. getCenter(target) {
  3399. return this.isEmpty() ? target.set(0, 0, 0) : target.addVectors(this.min, this.max).multiplyScalar(0.5);
  3400. }
  3401. getSize(target) {
  3402. return this.isEmpty() ? target.set(0, 0, 0) : target.subVectors(this.max, this.min);
  3403. }
  3404. expandByPoint(point) {
  3405. this.min.min(point);
  3406. this.max.max(point);
  3407. return this;
  3408. }
  3409. expandByVector(vector) {
  3410. this.min.sub(vector);
  3411. this.max.add(vector);
  3412. return this;
  3413. }
  3414. expandByScalar(scalar) {
  3415. this.min.addScalar(-scalar);
  3416. this.max.addScalar(scalar);
  3417. return this;
  3418. }
  3419. expandByObject(object, precise = false) {
  3420. // Computes the world-axis-aligned bounding box of an object (including its children),
  3421. // accounting for both the object's, and children's, world transforms
  3422. object.updateWorldMatrix(false, false);
  3423. const geometry = object.geometry;
  3424. if (geometry !== undefined) {
  3425. if (precise && geometry.attributes != undefined && geometry.attributes.position !== undefined) {
  3426. const position = geometry.attributes.position;
  3427. for (let i = 0, l = position.count; i < l; i++) {
  3428. _vector$b.fromBufferAttribute(position, i).applyMatrix4(object.matrixWorld);
  3429. this.expandByPoint(_vector$b);
  3430. }
  3431. } else {
  3432. if (geometry.boundingBox === null) {
  3433. geometry.computeBoundingBox();
  3434. }
  3435. _box$3.copy(geometry.boundingBox);
  3436. _box$3.applyMatrix4(object.matrixWorld);
  3437. this.union(_box$3);
  3438. }
  3439. }
  3440. const children = object.children;
  3441. for (let i = 0, l = children.length; i < l; i++) {
  3442. this.expandByObject(children[i], precise);
  3443. }
  3444. return this;
  3445. }
  3446. containsPoint(point) {
  3447. 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;
  3448. }
  3449. containsBox(box) {
  3450. 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;
  3451. }
  3452. getParameter(point, target) {
  3453. // This can potentially have a divide by zero if the box
  3454. // has a size dimension of 0.
  3455. 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));
  3456. }
  3457. intersectsBox(box) {
  3458. // using 6 splitting planes to rule out intersections.
  3459. 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;
  3460. }
  3461. intersectsSphere(sphere) {
  3462. // Find the point on the AABB closest to the sphere center.
  3463. this.clampPoint(sphere.center, _vector$b); // If that point is inside the sphere, the AABB and sphere intersect.
  3464. return _vector$b.distanceToSquared(sphere.center) <= sphere.radius * sphere.radius;
  3465. }
  3466. intersectsPlane(plane) {
  3467. // We compute the minimum and maximum dot product values. If those values
  3468. // are on the same side (back or front) of the plane, then there is no intersection.
  3469. let min, max;
  3470. if (plane.normal.x > 0) {
  3471. min = plane.normal.x * this.min.x;
  3472. max = plane.normal.x * this.max.x;
  3473. } else {
  3474. min = plane.normal.x * this.max.x;
  3475. max = plane.normal.x * this.min.x;
  3476. }
  3477. if (plane.normal.y > 0) {
  3478. min += plane.normal.y * this.min.y;
  3479. max += plane.normal.y * this.max.y;
  3480. } else {
  3481. min += plane.normal.y * this.max.y;
  3482. max += plane.normal.y * this.min.y;
  3483. }
  3484. if (plane.normal.z > 0) {
  3485. min += plane.normal.z * this.min.z;
  3486. max += plane.normal.z * this.max.z;
  3487. } else {
  3488. min += plane.normal.z * this.max.z;
  3489. max += plane.normal.z * this.min.z;
  3490. }
  3491. return min <= -plane.constant && max >= -plane.constant;
  3492. }
  3493. intersectsTriangle(triangle) {
  3494. if (this.isEmpty()) {
  3495. return false;
  3496. } // compute box center and extents
  3497. this.getCenter(_center);
  3498. _extents.subVectors(this.max, _center); // translate triangle to aabb origin
  3499. _v0$2.subVectors(triangle.a, _center);
  3500. _v1$7.subVectors(triangle.b, _center);
  3501. _v2$3.subVectors(triangle.c, _center); // compute edge vectors for triangle
  3502. _f0.subVectors(_v1$7, _v0$2);
  3503. _f1.subVectors(_v2$3, _v1$7);
  3504. _f2.subVectors(_v0$2, _v2$3); // test against axes that are given by cross product combinations of the edges of the triangle and the edges of the aabb
  3505. // 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
  3506. // axis_ij = u_i x f_j (u0, u1, u2 = face normals of aabb = x,y,z axes vectors since aabb is axis aligned)
  3507. 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];
  3508. if (!satForAxes(axes, _v0$2, _v1$7, _v2$3, _extents)) {
  3509. return false;
  3510. } // test 3 face normals from the aabb
  3511. axes = [1, 0, 0, 0, 1, 0, 0, 0, 1];
  3512. if (!satForAxes(axes, _v0$2, _v1$7, _v2$3, _extents)) {
  3513. return false;
  3514. } // finally testing the face normal of the triangle
  3515. // use already existing triangle edge vectors here
  3516. _triangleNormal.crossVectors(_f0, _f1);
  3517. axes = [_triangleNormal.x, _triangleNormal.y, _triangleNormal.z];
  3518. return satForAxes(axes, _v0$2, _v1$7, _v2$3, _extents);
  3519. }
  3520. clampPoint(point, target) {
  3521. return target.copy(point).clamp(this.min, this.max);
  3522. }
  3523. distanceToPoint(point) {
  3524. const clampedPoint = _vector$b.copy(point).clamp(this.min, this.max);
  3525. return clampedPoint.sub(point).length();
  3526. }
  3527. getBoundingSphere(target) {
  3528. this.getCenter(target.center);
  3529. target.radius = this.getSize(_vector$b).length() * 0.5;
  3530. return target;
  3531. }
  3532. intersect(box) {
  3533. this.min.max(box.min);
  3534. 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.
  3535. if (this.isEmpty()) this.makeEmpty();
  3536. return this;
  3537. }
  3538. union(box) {
  3539. this.min.min(box.min);
  3540. this.max.max(box.max);
  3541. return this;
  3542. }
  3543. applyMatrix4(matrix) {
  3544. // transform of empty box is an empty box.
  3545. if (this.isEmpty()) return this; // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  3546. _points[0].set(this.min.x, this.min.y, this.min.z).applyMatrix4(matrix); // 000
  3547. _points[1].set(this.min.x, this.min.y, this.max.z).applyMatrix4(matrix); // 001
  3548. _points[2].set(this.min.x, this.max.y, this.min.z).applyMatrix4(matrix); // 010
  3549. _points[3].set(this.min.x, this.max.y, this.max.z).applyMatrix4(matrix); // 011
  3550. _points[4].set(this.max.x, this.min.y, this.min.z).applyMatrix4(matrix); // 100
  3551. _points[5].set(this.max.x, this.min.y, this.max.z).applyMatrix4(matrix); // 101
  3552. _points[6].set(this.max.x, this.max.y, this.min.z).applyMatrix4(matrix); // 110
  3553. _points[7].set(this.max.x, this.max.y, this.max.z).applyMatrix4(matrix); // 111
  3554. this.setFromPoints(_points);
  3555. return this;
  3556. }
  3557. translate(offset) {
  3558. this.min.add(offset);
  3559. this.max.add(offset);
  3560. return this;
  3561. }
  3562. equals(box) {
  3563. return box.min.equals(this.min) && box.max.equals(this.max);
  3564. }
  3565. }
  3566. const _points = [/*@__PURE__*/new Vector3(), /*@__PURE__*/new Vector3(), /*@__PURE__*/new Vector3(), /*@__PURE__*/new Vector3(), /*@__PURE__*/new Vector3(), /*@__PURE__*/new Vector3(), /*@__PURE__*/new Vector3(), /*@__PURE__*/new Vector3()];
  3567. const _vector$b = /*@__PURE__*/new Vector3();
  3568. const _box$3 = /*@__PURE__*/new Box3(); // triangle centered vertices
  3569. const _v0$2 = /*@__PURE__*/new Vector3();
  3570. const _v1$7 = /*@__PURE__*/new Vector3();
  3571. const _v2$3 = /*@__PURE__*/new Vector3(); // triangle edge vectors
  3572. const _f0 = /*@__PURE__*/new Vector3();
  3573. const _f1 = /*@__PURE__*/new Vector3();
  3574. const _f2 = /*@__PURE__*/new Vector3();
  3575. const _center = /*@__PURE__*/new Vector3();
  3576. const _extents = /*@__PURE__*/new Vector3();
  3577. const _triangleNormal = /*@__PURE__*/new Vector3();
  3578. const _testAxis = /*@__PURE__*/new Vector3();
  3579. function satForAxes(axes, v0, v1, v2, extents) {
  3580. for (let i = 0, j = axes.length - 3; i <= j; i += 3) {
  3581. _testAxis.fromArray(axes, i); // project the aabb onto the separating axis
  3582. 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 separating axis
  3583. const p0 = v0.dot(_testAxis);
  3584. const p1 = v1.dot(_testAxis);
  3585. const p2 = v2.dot(_testAxis); // actual test, basically see if either of the most extreme of the triangle points intersects r
  3586. if (Math.max(-Math.max(p0, p1, p2), Math.min(p0, p1, p2)) > r) {
  3587. // points of the projected triangle are outside the projected half-length of the aabb
  3588. // the axis is separating and we can exit
  3589. return false;
  3590. }
  3591. }
  3592. return true;
  3593. }
  3594. const _box$2 = /*@__PURE__*/new Box3();
  3595. const _v1$6 = /*@__PURE__*/new Vector3();
  3596. const _toFarthestPoint = /*@__PURE__*/new Vector3();
  3597. const _toPoint = /*@__PURE__*/new Vector3();
  3598. class Sphere {
  3599. constructor(center = new Vector3(), radius = -1) {
  3600. this.center = center;
  3601. this.radius = radius;
  3602. }
  3603. set(center, radius) {
  3604. this.center.copy(center);
  3605. this.radius = radius;
  3606. return this;
  3607. }
  3608. setFromPoints(points, optionalCenter) {
  3609. const center = this.center;
  3610. if (optionalCenter !== undefined) {
  3611. center.copy(optionalCenter);
  3612. } else {
  3613. _box$2.setFromPoints(points).getCenter(center);
  3614. }
  3615. let maxRadiusSq = 0;
  3616. for (let i = 0, il = points.length; i < il; i++) {
  3617. maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(points[i]));
  3618. }
  3619. this.radius = Math.sqrt(maxRadiusSq);
  3620. return this;
  3621. }
  3622. copy(sphere) {
  3623. this.center.copy(sphere.center);
  3624. this.radius = sphere.radius;
  3625. return this;
  3626. }
  3627. isEmpty() {
  3628. return this.radius < 0;
  3629. }
  3630. makeEmpty() {
  3631. this.center.set(0, 0, 0);
  3632. this.radius = -1;
  3633. return this;
  3634. }
  3635. containsPoint(point) {
  3636. return point.distanceToSquared(this.center) <= this.radius * this.radius;
  3637. }
  3638. distanceToPoint(point) {
  3639. return point.distanceTo(this.center) - this.radius;
  3640. }
  3641. intersectsSphere(sphere) {
  3642. const radiusSum = this.radius + sphere.radius;
  3643. return sphere.center.distanceToSquared(this.center) <= radiusSum * radiusSum;
  3644. }
  3645. intersectsBox(box) {
  3646. return box.intersectsSphere(this);
  3647. }
  3648. intersectsPlane(plane) {
  3649. return Math.abs(plane.distanceToPoint(this.center)) <= this.radius;
  3650. }
  3651. clampPoint(point, target) {
  3652. const deltaLengthSq = this.center.distanceToSquared(point);
  3653. target.copy(point);
  3654. if (deltaLengthSq > this.radius * this.radius) {
  3655. target.sub(this.center).normalize();
  3656. target.multiplyScalar(this.radius).add(this.center);
  3657. }
  3658. return target;
  3659. }
  3660. getBoundingBox(target) {
  3661. if (this.isEmpty()) {
  3662. // Empty sphere produces empty bounding box
  3663. target.makeEmpty();
  3664. return target;
  3665. }
  3666. target.set(this.center, this.center);
  3667. target.expandByScalar(this.radius);
  3668. return target;
  3669. }
  3670. applyMatrix4(matrix) {
  3671. this.center.applyMatrix4(matrix);
  3672. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  3673. return this;
  3674. }
  3675. translate(offset) {
  3676. this.center.add(offset);
  3677. return this;
  3678. }
  3679. expandByPoint(point) {
  3680. // from https://github.com/juj/MathGeoLib/blob/2940b99b99cfe575dd45103ef20f4019dee15b54/src/Geometry/Sphere.cpp#L649-L671
  3681. _toPoint.subVectors(point, this.center);
  3682. const lengthSq = _toPoint.lengthSq();
  3683. if (lengthSq > this.radius * this.radius) {
  3684. const length = Math.sqrt(lengthSq);
  3685. const missingRadiusHalf = (length - this.radius) * 0.5; // Nudge this sphere towards the target point. Add half the missing distance to radius,
  3686. // and the other half to position. This gives a tighter enclosure, instead of if
  3687. // the whole missing distance were just added to radius.
  3688. this.center.add(_toPoint.multiplyScalar(missingRadiusHalf / length));
  3689. this.radius += missingRadiusHalf;
  3690. }
  3691. return this;
  3692. }
  3693. union(sphere) {
  3694. // from https://github.com/juj/MathGeoLib/blob/2940b99b99cfe575dd45103ef20f4019dee15b54/src/Geometry/Sphere.cpp#L759-L769
  3695. // To enclose another sphere into this sphere, we only need to enclose two points:
  3696. // 1) Enclose the farthest point on the other sphere into this sphere.
  3697. // 2) Enclose the opposite point of the farthest point into this sphere.
  3698. if (this.center.equals(sphere.center) === true) {
  3699. _toFarthestPoint.set(0, 0, 1).multiplyScalar(sphere.radius);
  3700. } else {
  3701. _toFarthestPoint.subVectors(sphere.center, this.center).normalize().multiplyScalar(sphere.radius);
  3702. }
  3703. this.expandByPoint(_v1$6.copy(sphere.center).add(_toFarthestPoint));
  3704. this.expandByPoint(_v1$6.copy(sphere.center).sub(_toFarthestPoint));
  3705. return this;
  3706. }
  3707. equals(sphere) {
  3708. return sphere.center.equals(this.center) && sphere.radius === this.radius;
  3709. }
  3710. clone() {
  3711. return new this.constructor().copy(this);
  3712. }
  3713. }
  3714. const _vector$a = /*@__PURE__*/new Vector3();
  3715. const _segCenter = /*@__PURE__*/new Vector3();
  3716. const _segDir = /*@__PURE__*/new Vector3();
  3717. const _diff = /*@__PURE__*/new Vector3();
  3718. const _edge1 = /*@__PURE__*/new Vector3();
  3719. const _edge2 = /*@__PURE__*/new Vector3();
  3720. const _normal$1 = /*@__PURE__*/new Vector3();
  3721. class Ray {
  3722. constructor(origin = new Vector3(), direction = new Vector3(0, 0, -1)) {
  3723. this.origin = origin;
  3724. this.direction = direction;
  3725. }
  3726. set(origin, direction) {
  3727. this.origin.copy(origin);
  3728. this.direction.copy(direction);
  3729. return this;
  3730. }
  3731. copy(ray) {
  3732. this.origin.copy(ray.origin);
  3733. this.direction.copy(ray.direction);
  3734. return this;
  3735. }
  3736. at(t, target) {
  3737. return target.copy(this.direction).multiplyScalar(t).add(this.origin);
  3738. }
  3739. lookAt(v) {
  3740. this.direction.copy(v).sub(this.origin).normalize();
  3741. return this;
  3742. }
  3743. recast(t) {
  3744. this.origin.copy(this.at(t, _vector$a));
  3745. return this;
  3746. }
  3747. closestPointToPoint(point, target) {
  3748. target.subVectors(point, this.origin);
  3749. const directionDistance = target.dot(this.direction);
  3750. if (directionDistance < 0) {
  3751. return target.copy(this.origin);
  3752. }
  3753. return target.copy(this.direction).multiplyScalar(directionDistance).add(this.origin);
  3754. }
  3755. distanceToPoint(point) {
  3756. return Math.sqrt(this.distanceSqToPoint(point));
  3757. }
  3758. distanceSqToPoint(point) {
  3759. const directionDistance = _vector$a.subVectors(point, this.origin).dot(this.direction); // point behind the ray
  3760. if (directionDistance < 0) {
  3761. return this.origin.distanceToSquared(point);
  3762. }
  3763. _vector$a.copy(this.direction).multiplyScalar(directionDistance).add(this.origin);
  3764. return _vector$a.distanceToSquared(point);
  3765. }
  3766. distanceSqToSegment(v0, v1, optionalPointOnRay, optionalPointOnSegment) {
  3767. // from https://github.com/pmjoniak/GeometricTools/blob/master/GTEngine/Include/Mathematics/GteDistRaySegment.h
  3768. // It returns the min distance between the ray and the segment
  3769. // defined by v0 and v1
  3770. // It can also set two optional targets :
  3771. // - The closest point on the ray
  3772. // - The closest point on the segment
  3773. _segCenter.copy(v0).add(v1).multiplyScalar(0.5);
  3774. _segDir.copy(v1).sub(v0).normalize();
  3775. _diff.copy(this.origin).sub(_segCenter);
  3776. const segExtent = v0.distanceTo(v1) * 0.5;
  3777. const a01 = -this.direction.dot(_segDir);
  3778. const b0 = _diff.dot(this.direction);
  3779. const b1 = -_diff.dot(_segDir);
  3780. const c = _diff.lengthSq();
  3781. const det = Math.abs(1 - a01 * a01);
  3782. let s0, s1, sqrDist, extDet;
  3783. if (det > 0) {
  3784. // The ray and segment are not parallel.
  3785. s0 = a01 * b1 - b0;
  3786. s1 = a01 * b0 - b1;
  3787. extDet = segExtent * det;
  3788. if (s0 >= 0) {
  3789. if (s1 >= -extDet) {
  3790. if (s1 <= extDet) {
  3791. // region 0
  3792. // Minimum at interior points of ray and segment.
  3793. const invDet = 1 / det;
  3794. s0 *= invDet;
  3795. s1 *= invDet;
  3796. sqrDist = s0 * (s0 + a01 * s1 + 2 * b0) + s1 * (a01 * s0 + s1 + 2 * b1) + c;
  3797. } else {
  3798. // region 1
  3799. s1 = segExtent;
  3800. s0 = Math.max(0, -(a01 * s1 + b0));
  3801. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  3802. }
  3803. } else {
  3804. // region 5
  3805. s1 = -segExtent;
  3806. s0 = Math.max(0, -(a01 * s1 + b0));
  3807. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  3808. }
  3809. } else {
  3810. if (s1 <= -extDet) {
  3811. // region 4
  3812. s0 = Math.max(0, -(-a01 * segExtent + b0));
  3813. s1 = s0 > 0 ? -segExtent : Math.min(Math.max(-segExtent, -b1), segExtent);
  3814. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  3815. } else if (s1 <= extDet) {
  3816. // region 3
  3817. s0 = 0;
  3818. s1 = Math.min(Math.max(-segExtent, -b1), segExtent);
  3819. sqrDist = s1 * (s1 + 2 * b1) + c;
  3820. } else {
  3821. // region 2
  3822. s0 = Math.max(0, -(a01 * segExtent + b0));
  3823. s1 = s0 > 0 ? segExtent : Math.min(Math.max(-segExtent, -b1), segExtent);
  3824. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  3825. }
  3826. }
  3827. } else {
  3828. // Ray and segment are parallel.
  3829. s1 = a01 > 0 ? -segExtent : segExtent;
  3830. s0 = Math.max(0, -(a01 * s1 + b0));
  3831. sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c;
  3832. }
  3833. if (optionalPointOnRay) {
  3834. optionalPointOnRay.copy(this.direction).multiplyScalar(s0).add(this.origin);
  3835. }
  3836. if (optionalPointOnSegment) {
  3837. optionalPointOnSegment.copy(_segDir).multiplyScalar(s1).add(_segCenter);
  3838. }
  3839. return sqrDist;
  3840. }
  3841. intersectSphere(sphere, target) {
  3842. _vector$a.subVectors(sphere.center, this.origin);
  3843. const tca = _vector$a.dot(this.direction);
  3844. const d2 = _vector$a.dot(_vector$a) - tca * tca;
  3845. const radius2 = sphere.radius * sphere.radius;
  3846. if (d2 > radius2) return null;
  3847. const thc = Math.sqrt(radius2 - d2); // t0 = first intersect point - entrance on front of sphere
  3848. const t0 = tca - thc; // t1 = second intersect point - exit point on back of sphere
  3849. const t1 = tca + thc; // test to see if both t0 and t1 are behind the ray - if so, return null
  3850. if (t0 < 0 && t1 < 0) return null; // test to see if t0 is behind the ray:
  3851. // if it is, the ray is inside the sphere, so return the second exit point scaled by t1,
  3852. // in order to always return an intersect point that is in front of the ray.
  3853. 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
  3854. return this.at(t0, target);
  3855. }
  3856. intersectsSphere(sphere) {
  3857. return this.distanceSqToPoint(sphere.center) <= sphere.radius * sphere.radius;
  3858. }
  3859. distanceToPlane(plane) {
  3860. const denominator = plane.normal.dot(this.direction);
  3861. if (denominator === 0) {
  3862. // line is coplanar, return origin
  3863. if (plane.distanceToPoint(this.origin) === 0) {
  3864. return 0;
  3865. } // Null is preferable to undefined since undefined means.... it is undefined
  3866. return null;
  3867. }
  3868. const t = -(this.origin.dot(plane.normal) + plane.constant) / denominator; // Return if the ray never intersects the plane
  3869. return t >= 0 ? t : null;
  3870. }
  3871. intersectPlane(plane, target) {
  3872. const t = this.distanceToPlane(plane);
  3873. if (t === null) {
  3874. return null;
  3875. }
  3876. return this.at(t, target);
  3877. }
  3878. intersectsPlane(plane) {
  3879. // check if the ray lies on the plane first
  3880. const distToPoint = plane.distanceToPoint(this.origin);
  3881. if (distToPoint === 0) {
  3882. return true;
  3883. }
  3884. const denominator = plane.normal.dot(this.direction);
  3885. if (denominator * distToPoint < 0) {
  3886. return true;
  3887. } // ray origin is behind the plane (and is pointing behind it)
  3888. return false;
  3889. }
  3890. intersectBox(box, target) {
  3891. let tmin, tmax, tymin, tymax, tzmin, tzmax;
  3892. const invdirx = 1 / this.direction.x,
  3893. invdiry = 1 / this.direction.y,
  3894. invdirz = 1 / this.direction.z;
  3895. const origin = this.origin;
  3896. if (invdirx >= 0) {
  3897. tmin = (box.min.x - origin.x) * invdirx;
  3898. tmax = (box.max.x - origin.x) * invdirx;
  3899. } else {
  3900. tmin = (box.max.x - origin.x) * invdirx;
  3901. tmax = (box.min.x - origin.x) * invdirx;
  3902. }
  3903. if (invdiry >= 0) {
  3904. tymin = (box.min.y - origin.y) * invdiry;
  3905. tymax = (box.max.y - origin.y) * invdiry;
  3906. } else {
  3907. tymin = (box.max.y - origin.y) * invdiry;
  3908. tymax = (box.min.y - origin.y) * invdiry;
  3909. }
  3910. if (tmin > tymax || tymin > tmax) return null; // These lines also handle the case where tmin or tmax is NaN
  3911. // (result of 0 * Infinity). x !== x returns true if x is NaN
  3912. if (tymin > tmin || tmin !== tmin) tmin = tymin;
  3913. if (tymax < tmax || tmax !== tmax) tmax = tymax;
  3914. if (invdirz >= 0) {
  3915. tzmin = (box.min.z - origin.z) * invdirz;
  3916. tzmax = (box.max.z - origin.z) * invdirz;
  3917. } else {
  3918. tzmin = (box.max.z - origin.z) * invdirz;
  3919. tzmax = (box.min.z - origin.z) * invdirz;
  3920. }
  3921. if (tmin > tzmax || tzmin > tmax) return null;
  3922. if (tzmin > tmin || tmin !== tmin) tmin = tzmin;
  3923. if (tzmax < tmax || tmax !== tmax) tmax = tzmax; //return point closest to the ray (positive side)
  3924. if (tmax < 0) return null;
  3925. return this.at(tmin >= 0 ? tmin : tmax, target);
  3926. }
  3927. intersectsBox(box) {
  3928. return this.intersectBox(box, _vector$a) !== null;
  3929. }
  3930. intersectTriangle(a, b, c, backfaceCulling, target) {
  3931. // Compute the offset origin, edges, and normal.
  3932. // from https://github.com/pmjoniak/GeometricTools/blob/master/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h
  3933. _edge1.subVectors(b, a);
  3934. _edge2.subVectors(c, a);
  3935. _normal$1.crossVectors(_edge1, _edge2); // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  3936. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  3937. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  3938. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  3939. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  3940. let DdN = this.direction.dot(_normal$1);
  3941. let sign;
  3942. if (DdN > 0) {
  3943. if (backfaceCulling) return null;
  3944. sign = 1;
  3945. } else if (DdN < 0) {
  3946. sign = -1;
  3947. DdN = -DdN;
  3948. } else {
  3949. return null;
  3950. }
  3951. _diff.subVectors(this.origin, a);
  3952. const DdQxE2 = sign * this.direction.dot(_edge2.crossVectors(_diff, _edge2)); // b1 < 0, no intersection
  3953. if (DdQxE2 < 0) {
  3954. return null;
  3955. }
  3956. const DdE1xQ = sign * this.direction.dot(_edge1.cross(_diff)); // b2 < 0, no intersection
  3957. if (DdE1xQ < 0) {
  3958. return null;
  3959. } // b1+b2 > 1, no intersection
  3960. if (DdQxE2 + DdE1xQ > DdN) {
  3961. return null;
  3962. } // Line intersects triangle, check if ray does.
  3963. const QdN = -sign * _diff.dot(_normal$1); // t < 0, no intersection
  3964. if (QdN < 0) {
  3965. return null;
  3966. } // Ray intersects triangle.
  3967. return this.at(QdN / DdN, target);
  3968. }
  3969. applyMatrix4(matrix4) {
  3970. this.origin.applyMatrix4(matrix4);
  3971. this.direction.transformDirection(matrix4);
  3972. return this;
  3973. }
  3974. equals(ray) {
  3975. return ray.origin.equals(this.origin) && ray.direction.equals(this.direction);
  3976. }
  3977. clone() {
  3978. return new this.constructor().copy(this);
  3979. }
  3980. }
  3981. class Matrix4 {
  3982. constructor() {
  3983. this.isMatrix4 = true;
  3984. this.elements = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];
  3985. if (arguments.length > 0) {
  3986. console.error('THREE.Matrix4: the constructor no longer reads arguments. use .set() instead.');
  3987. }
  3988. }
  3989. set(n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44) {
  3990. const te = this.elements;
  3991. te[0] = n11;
  3992. te[4] = n12;
  3993. te[8] = n13;
  3994. te[12] = n14;
  3995. te[1] = n21;
  3996. te[5] = n22;
  3997. te[9] = n23;
  3998. te[13] = n24;
  3999. te[2] = n31;
  4000. te[6] = n32;
  4001. te[10] = n33;
  4002. te[14] = n34;
  4003. te[3] = n41;
  4004. te[7] = n42;
  4005. te[11] = n43;
  4006. te[15] = n44;
  4007. return this;
  4008. }
  4009. identity() {
  4010. this.set(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1);
  4011. return this;
  4012. }
  4013. clone() {
  4014. return new Matrix4().fromArray(this.elements);
  4015. }
  4016. copy(m) {
  4017. const te = this.elements;
  4018. const me = m.elements;
  4019. te[0] = me[0];
  4020. te[1] = me[1];
  4021. te[2] = me[2];
  4022. te[3] = me[3];
  4023. te[4] = me[4];
  4024. te[5] = me[5];
  4025. te[6] = me[6];
  4026. te[7] = me[7];
  4027. te[8] = me[8];
  4028. te[9] = me[9];
  4029. te[10] = me[10];
  4030. te[11] = me[11];
  4031. te[12] = me[12];
  4032. te[13] = me[13];
  4033. te[14] = me[14];
  4034. te[15] = me[15];
  4035. return this;
  4036. }
  4037. copyPosition(m) {
  4038. const te = this.elements,
  4039. me = m.elements;
  4040. te[12] = me[12];
  4041. te[13] = me[13];
  4042. te[14] = me[14];
  4043. return this;
  4044. }
  4045. setFromMatrix3(m) {
  4046. const me = m.elements;
  4047. this.set(me[0], me[3], me[6], 0, me[1], me[4], me[7], 0, me[2], me[5], me[8], 0, 0, 0, 0, 1);
  4048. return this;
  4049. }
  4050. extractBasis(xAxis, yAxis, zAxis) {
  4051. xAxis.setFromMatrixColumn(this, 0);
  4052. yAxis.setFromMatrixColumn(this, 1);
  4053. zAxis.setFromMatrixColumn(this, 2);
  4054. return this;
  4055. }
  4056. makeBasis(xAxis, yAxis, zAxis) {
  4057. 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);
  4058. return this;
  4059. }
  4060. extractRotation(m) {
  4061. // this method does not support reflection matrices
  4062. const te = this.elements;
  4063. const me = m.elements;
  4064. const scaleX = 1 / _v1$5.setFromMatrixColumn(m, 0).length();
  4065. const scaleY = 1 / _v1$5.setFromMatrixColumn(m, 1).length();
  4066. const scaleZ = 1 / _v1$5.setFromMatrixColumn(m, 2).length();
  4067. te[0] = me[0] * scaleX;
  4068. te[1] = me[1] * scaleX;
  4069. te[2] = me[2] * scaleX;
  4070. te[3] = 0;
  4071. te[4] = me[4] * scaleY;
  4072. te[5] = me[5] * scaleY;
  4073. te[6] = me[6] * scaleY;
  4074. te[7] = 0;
  4075. te[8] = me[8] * scaleZ;
  4076. te[9] = me[9] * scaleZ;
  4077. te[10] = me[10] * scaleZ;
  4078. te[11] = 0;
  4079. te[12] = 0;
  4080. te[13] = 0;
  4081. te[14] = 0;
  4082. te[15] = 1;
  4083. return this;
  4084. }
  4085. makeRotationFromEuler(euler) {
  4086. if (!(euler && euler.isEuler)) {
  4087. console.error('THREE.Matrix4: .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order.');
  4088. }
  4089. const te = this.elements;
  4090. const x = euler.x,
  4091. y = euler.y,
  4092. z = euler.z;
  4093. const a = Math.cos(x),
  4094. b = Math.sin(x);
  4095. const c = Math.cos(y),
  4096. d = Math.sin(y);
  4097. const e = Math.cos(z),
  4098. f = Math.sin(z);
  4099. if (euler.order === 'XYZ') {
  4100. const ae = a * e,
  4101. af = a * f,
  4102. be = b * e,
  4103. bf = b * f;
  4104. te[0] = c * e;
  4105. te[4] = -c * f;
  4106. te[8] = d;
  4107. te[1] = af + be * d;
  4108. te[5] = ae - bf * d;
  4109. te[9] = -b * c;
  4110. te[2] = bf - ae * d;
  4111. te[6] = be + af * d;
  4112. te[10] = a * c;
  4113. } else if (euler.order === 'YXZ') {
  4114. const ce = c * e,
  4115. cf = c * f,
  4116. de = d * e,
  4117. df = d * f;
  4118. te[0] = ce + df * b;
  4119. te[4] = de * b - cf;
  4120. te[8] = a * d;
  4121. te[1] = a * f;
  4122. te[5] = a * e;
  4123. te[9] = -b;
  4124. te[2] = cf * b - de;
  4125. te[6] = df + ce * b;
  4126. te[10] = a * c;
  4127. } else if (euler.order === 'ZXY') {
  4128. const ce = c * e,
  4129. cf = c * f,
  4130. de = d * e,
  4131. df = d * f;
  4132. te[0] = ce - df * b;
  4133. te[4] = -a * f;
  4134. te[8] = de + cf * b;
  4135. te[1] = cf + de * b;
  4136. te[5] = a * e;
  4137. te[9] = df - ce * b;
  4138. te[2] = -a * d;
  4139. te[6] = b;
  4140. te[10] = a * c;
  4141. } else if (euler.order === 'ZYX') {
  4142. const ae = a * e,
  4143. af = a * f,
  4144. be = b * e,
  4145. bf = b * f;
  4146. te[0] = c * e;
  4147. te[4] = be * d - af;
  4148. te[8] = ae * d + bf;
  4149. te[1] = c * f;
  4150. te[5] = bf * d + ae;
  4151. te[9] = af * d - be;
  4152. te[2] = -d;
  4153. te[6] = b * c;
  4154. te[10] = a * c;
  4155. } else if (euler.order === 'YZX') {
  4156. const ac = a * c,
  4157. ad = a * d,
  4158. bc = b * c,
  4159. bd = b * d;
  4160. te[0] = c * e;
  4161. te[4] = bd - ac * f;
  4162. te[8] = bc * f + ad;
  4163. te[1] = f;
  4164. te[5] = a * e;
  4165. te[9] = -b * e;
  4166. te[2] = -d * e;
  4167. te[6] = ad * f + bc;
  4168. te[10] = ac - bd * f;
  4169. } else if (euler.order === 'XZY') {
  4170. const ac = a * c,
  4171. ad = a * d,
  4172. bc = b * c,
  4173. bd = b * d;
  4174. te[0] = c * e;
  4175. te[4] = -f;
  4176. te[8] = d * e;
  4177. te[1] = ac * f + bd;
  4178. te[5] = a * e;
  4179. te[9] = ad * f - bc;
  4180. te[2] = bc * f - ad;
  4181. te[6] = b * e;
  4182. te[10] = bd * f + ac;
  4183. } // bottom row
  4184. te[3] = 0;
  4185. te[7] = 0;
  4186. te[11] = 0; // last column
  4187. te[12] = 0;
  4188. te[13] = 0;
  4189. te[14] = 0;
  4190. te[15] = 1;
  4191. return this;
  4192. }
  4193. makeRotationFromQuaternion(q) {
  4194. return this.compose(_zero, q, _one);
  4195. }
  4196. lookAt(eye, target, up) {
  4197. const te = this.elements;
  4198. _z.subVectors(eye, target);
  4199. if (_z.lengthSq() === 0) {
  4200. // eye and target are in the same position
  4201. _z.z = 1;
  4202. }
  4203. _z.normalize();
  4204. _x.crossVectors(up, _z);
  4205. if (_x.lengthSq() === 0) {
  4206. // up and z are parallel
  4207. if (Math.abs(up.z) === 1) {
  4208. _z.x += 0.0001;
  4209. } else {
  4210. _z.z += 0.0001;
  4211. }
  4212. _z.normalize();
  4213. _x.crossVectors(up, _z);
  4214. }
  4215. _x.normalize();
  4216. _y.crossVectors(_z, _x);
  4217. te[0] = _x.x;
  4218. te[4] = _y.x;
  4219. te[8] = _z.x;
  4220. te[1] = _x.y;
  4221. te[5] = _y.y;
  4222. te[9] = _z.y;
  4223. te[2] = _x.z;
  4224. te[6] = _y.z;
  4225. te[10] = _z.z;
  4226. return this;
  4227. }
  4228. multiply(m, n) {
  4229. if (n !== undefined) {
  4230. console.warn('THREE.Matrix4: .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead.');
  4231. return this.multiplyMatrices(m, n);
  4232. }
  4233. return this.multiplyMatrices(this, m);
  4234. }
  4235. premultiply(m) {
  4236. return this.multiplyMatrices(m, this);
  4237. }
  4238. multiplyMatrices(a, b) {
  4239. const ae = a.elements;
  4240. const be = b.elements;
  4241. const te = this.elements;
  4242. const a11 = ae[0],
  4243. a12 = ae[4],
  4244. a13 = ae[8],
  4245. a14 = ae[12];
  4246. const a21 = ae[1],
  4247. a22 = ae[5],
  4248. a23 = ae[9],
  4249. a24 = ae[13];
  4250. const a31 = ae[2],
  4251. a32 = ae[6],
  4252. a33 = ae[10],
  4253. a34 = ae[14];
  4254. const a41 = ae[3],
  4255. a42 = ae[7],
  4256. a43 = ae[11],
  4257. a44 = ae[15];
  4258. const b11 = be[0],
  4259. b12 = be[4],
  4260. b13 = be[8],
  4261. b14 = be[12];
  4262. const b21 = be[1],
  4263. b22 = be[5],
  4264. b23 = be[9],
  4265. b24 = be[13];
  4266. const b31 = be[2],
  4267. b32 = be[6],
  4268. b33 = be[10],
  4269. b34 = be[14];
  4270. const b41 = be[3],
  4271. b42 = be[7],
  4272. b43 = be[11],
  4273. b44 = be[15];
  4274. te[0] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  4275. te[4] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  4276. te[8] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  4277. te[12] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  4278. te[1] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  4279. te[5] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  4280. te[9] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  4281. te[13] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  4282. te[2] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  4283. te[6] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  4284. te[10] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  4285. te[14] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  4286. te[3] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  4287. te[7] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  4288. te[11] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  4289. te[15] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  4290. return this;
  4291. }
  4292. multiplyScalar(s) {
  4293. const te = this.elements;
  4294. te[0] *= s;
  4295. te[4] *= s;
  4296. te[8] *= s;
  4297. te[12] *= s;
  4298. te[1] *= s;
  4299. te[5] *= s;
  4300. te[9] *= s;
  4301. te[13] *= s;
  4302. te[2] *= s;
  4303. te[6] *= s;
  4304. te[10] *= s;
  4305. te[14] *= s;
  4306. te[3] *= s;
  4307. te[7] *= s;
  4308. te[11] *= s;
  4309. te[15] *= s;
  4310. return this;
  4311. }
  4312. determinant() {
  4313. const te = this.elements;
  4314. const n11 = te[0],
  4315. n12 = te[4],
  4316. n13 = te[8],
  4317. n14 = te[12];
  4318. const n21 = te[1],
  4319. n22 = te[5],
  4320. n23 = te[9],
  4321. n24 = te[13];
  4322. const n31 = te[2],
  4323. n32 = te[6],
  4324. n33 = te[10],
  4325. n34 = te[14];
  4326. const n41 = te[3],
  4327. n42 = te[7],
  4328. n43 = te[11],
  4329. n44 = te[15]; //TODO: make this more efficient
  4330. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  4331. 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);
  4332. }
  4333. transpose() {
  4334. const te = this.elements;
  4335. let tmp;
  4336. tmp = te[1];
  4337. te[1] = te[4];
  4338. te[4] = tmp;
  4339. tmp = te[2];
  4340. te[2] = te[8];
  4341. te[8] = tmp;
  4342. tmp = te[6];
  4343. te[6] = te[9];
  4344. te[9] = tmp;
  4345. tmp = te[3];
  4346. te[3] = te[12];
  4347. te[12] = tmp;
  4348. tmp = te[7];
  4349. te[7] = te[13];
  4350. te[13] = tmp;
  4351. tmp = te[11];
  4352. te[11] = te[14];
  4353. te[14] = tmp;
  4354. return this;
  4355. }
  4356. setPosition(x, y, z) {
  4357. const te = this.elements;
  4358. if (x.isVector3) {
  4359. te[12] = x.x;
  4360. te[13] = x.y;
  4361. te[14] = x.z;
  4362. } else {
  4363. te[12] = x;
  4364. te[13] = y;
  4365. te[14] = z;
  4366. }
  4367. return this;
  4368. }
  4369. invert() {
  4370. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  4371. const te = this.elements,
  4372. n11 = te[0],
  4373. n21 = te[1],
  4374. n31 = te[2],
  4375. n41 = te[3],
  4376. n12 = te[4],
  4377. n22 = te[5],
  4378. n32 = te[6],
  4379. n42 = te[7],
  4380. n13 = te[8],
  4381. n23 = te[9],
  4382. n33 = te[10],
  4383. n43 = te[11],
  4384. n14 = te[12],
  4385. n24 = te[13],
  4386. n34 = te[14],
  4387. n44 = te[15],
  4388. t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44,
  4389. t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44,
  4390. t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44,
  4391. t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34;
  4392. const det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14;
  4393. if (det === 0) return this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  4394. const detInv = 1 / det;
  4395. te[0] = t11 * detInv;
  4396. te[1] = (n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44) * detInv;
  4397. te[2] = (n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44) * detInv;
  4398. te[3] = (n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43) * detInv;
  4399. te[4] = t12 * detInv;
  4400. te[5] = (n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44) * detInv;
  4401. te[6] = (n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44) * detInv;
  4402. te[7] = (n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43) * detInv;
  4403. te[8] = t13 * detInv;
  4404. te[9] = (n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44) * detInv;
  4405. te[10] = (n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44) * detInv;
  4406. te[11] = (n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43) * detInv;
  4407. te[12] = t14 * detInv;
  4408. te[13] = (n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34) * detInv;
  4409. te[14] = (n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34) * detInv;
  4410. te[15] = (n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33) * detInv;
  4411. return this;
  4412. }
  4413. scale(v) {
  4414. const te = this.elements;
  4415. const x = v.x,
  4416. y = v.y,
  4417. z = v.z;
  4418. te[0] *= x;
  4419. te[4] *= y;
  4420. te[8] *= z;
  4421. te[1] *= x;
  4422. te[5] *= y;
  4423. te[9] *= z;
  4424. te[2] *= x;
  4425. te[6] *= y;
  4426. te[10] *= z;
  4427. te[3] *= x;
  4428. te[7] *= y;
  4429. te[11] *= z;
  4430. return this;
  4431. }
  4432. getMaxScaleOnAxis() {
  4433. const te = this.elements;
  4434. const scaleXSq = te[0] * te[0] + te[1] * te[1] + te[2] * te[2];
  4435. const scaleYSq = te[4] * te[4] + te[5] * te[5] + te[6] * te[6];
  4436. const scaleZSq = te[8] * te[8] + te[9] * te[9] + te[10] * te[10];
  4437. return Math.sqrt(Math.max(scaleXSq, scaleYSq, scaleZSq));
  4438. }
  4439. makeTranslation(x, y, z) {
  4440. this.set(1, 0, 0, x, 0, 1, 0, y, 0, 0, 1, z, 0, 0, 0, 1);
  4441. return this;
  4442. }
  4443. makeRotationX(theta) {
  4444. const c = Math.cos(theta),
  4445. s = Math.sin(theta);
  4446. this.set(1, 0, 0, 0, 0, c, -s, 0, 0, s, c, 0, 0, 0, 0, 1);
  4447. return this;
  4448. }
  4449. makeRotationY(theta) {
  4450. const c = Math.cos(theta),
  4451. s = Math.sin(theta);
  4452. this.set(c, 0, s, 0, 0, 1, 0, 0, -s, 0, c, 0, 0, 0, 0, 1);
  4453. return this;
  4454. }
  4455. makeRotationZ(theta) {
  4456. const c = Math.cos(theta),
  4457. s = Math.sin(theta);
  4458. this.set(c, -s, 0, 0, s, c, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1);
  4459. return this;
  4460. }
  4461. makeRotationAxis(axis, angle) {
  4462. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  4463. const c = Math.cos(angle);
  4464. const s = Math.sin(angle);
  4465. const t = 1 - c;
  4466. const x = axis.x,
  4467. y = axis.y,
  4468. z = axis.z;
  4469. const tx = t * x,
  4470. ty = t * y;
  4471. 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);
  4472. return this;
  4473. }
  4474. makeScale(x, y, z) {
  4475. this.set(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1);
  4476. return this;
  4477. }
  4478. makeShear(xy, xz, yx, yz, zx, zy) {
  4479. this.set(1, yx, zx, 0, xy, 1, zy, 0, xz, yz, 1, 0, 0, 0, 0, 1);
  4480. return this;
  4481. }
  4482. compose(position, quaternion, scale) {
  4483. const te = this.elements;
  4484. const x = quaternion._x,
  4485. y = quaternion._y,
  4486. z = quaternion._z,
  4487. w = quaternion._w;
  4488. const x2 = x + x,
  4489. y2 = y + y,
  4490. z2 = z + z;
  4491. const xx = x * x2,
  4492. xy = x * y2,
  4493. xz = x * z2;
  4494. const yy = y * y2,
  4495. yz = y * z2,
  4496. zz = z * z2;
  4497. const wx = w * x2,
  4498. wy = w * y2,
  4499. wz = w * z2;
  4500. const sx = scale.x,
  4501. sy = scale.y,
  4502. sz = scale.z;
  4503. te[0] = (1 - (yy + zz)) * sx;
  4504. te[1] = (xy + wz) * sx;
  4505. te[2] = (xz - wy) * sx;
  4506. te[3] = 0;
  4507. te[4] = (xy - wz) * sy;
  4508. te[5] = (1 - (xx + zz)) * sy;
  4509. te[6] = (yz + wx) * sy;
  4510. te[7] = 0;
  4511. te[8] = (xz + wy) * sz;
  4512. te[9] = (yz - wx) * sz;
  4513. te[10] = (1 - (xx + yy)) * sz;
  4514. te[11] = 0;
  4515. te[12] = position.x;
  4516. te[13] = position.y;
  4517. te[14] = position.z;
  4518. te[15] = 1;
  4519. return this;
  4520. }
  4521. decompose(position, quaternion, scale) {
  4522. const te = this.elements;
  4523. let sx = _v1$5.set(te[0], te[1], te[2]).length();
  4524. const sy = _v1$5.set(te[4], te[5], te[6]).length();
  4525. const sz = _v1$5.set(te[8], te[9], te[10]).length(); // if determine is negative, we need to invert one scale
  4526. const det = this.determinant();
  4527. if (det < 0) sx = -sx;
  4528. position.x = te[12];
  4529. position.y = te[13];
  4530. position.z = te[14]; // scale the rotation part
  4531. _m1$2.copy(this);
  4532. const invSX = 1 / sx;
  4533. const invSY = 1 / sy;
  4534. const invSZ = 1 / sz;
  4535. _m1$2.elements[0] *= invSX;
  4536. _m1$2.elements[1] *= invSX;
  4537. _m1$2.elements[2] *= invSX;
  4538. _m1$2.elements[4] *= invSY;
  4539. _m1$2.elements[5] *= invSY;
  4540. _m1$2.elements[6] *= invSY;
  4541. _m1$2.elements[8] *= invSZ;
  4542. _m1$2.elements[9] *= invSZ;
  4543. _m1$2.elements[10] *= invSZ;
  4544. quaternion.setFromRotationMatrix(_m1$2);
  4545. scale.x = sx;
  4546. scale.y = sy;
  4547. scale.z = sz;
  4548. return this;
  4549. }
  4550. makePerspective(left, right, top, bottom, near, far) {
  4551. if (far === undefined) {
  4552. console.warn('THREE.Matrix4: .makePerspective() has been redefined and has a new signature. Please check the docs.');
  4553. }
  4554. const te = this.elements;
  4555. const x = 2 * near / (right - left);
  4556. const y = 2 * near / (top - bottom);
  4557. const a = (right + left) / (right - left);
  4558. const b = (top + bottom) / (top - bottom);
  4559. const c = -(far + near) / (far - near);
  4560. const d = -2 * far * near / (far - near);
  4561. te[0] = x;
  4562. te[4] = 0;
  4563. te[8] = a;
  4564. te[12] = 0;
  4565. te[1] = 0;
  4566. te[5] = y;
  4567. te[9] = b;
  4568. te[13] = 0;
  4569. te[2] = 0;
  4570. te[6] = 0;
  4571. te[10] = c;
  4572. te[14] = d;
  4573. te[3] = 0;
  4574. te[7] = 0;
  4575. te[11] = -1;
  4576. te[15] = 0;
  4577. return this;
  4578. }
  4579. makeOrthographic(left, right, top, bottom, near, far) {
  4580. const te = this.elements;
  4581. const w = 1.0 / (right - left);
  4582. const h = 1.0 / (top - bottom);
  4583. const p = 1.0 / (far - near);
  4584. const x = (right + left) * w;
  4585. const y = (top + bottom) * h;
  4586. const z = (far + near) * p;
  4587. te[0] = 2 * w;
  4588. te[4] = 0;
  4589. te[8] = 0;
  4590. te[12] = -x;
  4591. te[1] = 0;
  4592. te[5] = 2 * h;
  4593. te[9] = 0;
  4594. te[13] = -y;
  4595. te[2] = 0;
  4596. te[6] = 0;
  4597. te[10] = -2 * p;
  4598. te[14] = -z;
  4599. te[3] = 0;
  4600. te[7] = 0;
  4601. te[11] = 0;
  4602. te[15] = 1;
  4603. return this;
  4604. }
  4605. equals(matrix) {
  4606. const te = this.elements;
  4607. const me = matrix.elements;
  4608. for (let i = 0; i < 16; i++) {
  4609. if (te[i] !== me[i]) return false;
  4610. }
  4611. return true;
  4612. }
  4613. fromArray(array, offset = 0) {
  4614. for (let i = 0; i < 16; i++) {
  4615. this.elements[i] = array[i + offset];
  4616. }
  4617. return this;
  4618. }
  4619. toArray(array = [], offset = 0) {
  4620. const te = this.elements;
  4621. array[offset] = te[0];
  4622. array[offset + 1] = te[1];
  4623. array[offset + 2] = te[2];
  4624. array[offset + 3] = te[3];
  4625. array[offset + 4] = te[4];
  4626. array[offset + 5] = te[5];
  4627. array[offset + 6] = te[6];
  4628. array[offset + 7] = te[7];
  4629. array[offset + 8] = te[8];
  4630. array[offset + 9] = te[9];
  4631. array[offset + 10] = te[10];
  4632. array[offset + 11] = te[11];
  4633. array[offset + 12] = te[12];
  4634. array[offset + 13] = te[13];
  4635. array[offset + 14] = te[14];
  4636. array[offset + 15] = te[15];
  4637. return array;
  4638. }
  4639. }
  4640. const _v1$5 = /*@__PURE__*/new Vector3();
  4641. const _m1$2 = /*@__PURE__*/new Matrix4();
  4642. const _zero = /*@__PURE__*/new Vector3(0, 0, 0);
  4643. const _one = /*@__PURE__*/new Vector3(1, 1, 1);
  4644. const _x = /*@__PURE__*/new Vector3();
  4645. const _y = /*@__PURE__*/new Vector3();
  4646. const _z = /*@__PURE__*/new Vector3();
  4647. const _matrix$1 = /*@__PURE__*/new Matrix4();
  4648. const _quaternion$3 = /*@__PURE__*/new Quaternion();
  4649. class Euler {
  4650. constructor(x = 0, y = 0, z = 0, order = Euler.DefaultOrder) {
  4651. this.isEuler = true;
  4652. this._x = x;
  4653. this._y = y;
  4654. this._z = z;
  4655. this._order = order;
  4656. }
  4657. get x() {
  4658. return this._x;
  4659. }
  4660. set x(value) {
  4661. this._x = value;
  4662. this._onChangeCallback();
  4663. }
  4664. get y() {
  4665. return this._y;
  4666. }
  4667. set y(value) {
  4668. this._y = value;
  4669. this._onChangeCallback();
  4670. }
  4671. get z() {
  4672. return this._z;
  4673. }
  4674. set z(value) {
  4675. this._z = value;
  4676. this._onChangeCallback();
  4677. }
  4678. get order() {
  4679. return this._order;
  4680. }
  4681. set order(value) {
  4682. this._order = value;
  4683. this._onChangeCallback();
  4684. }
  4685. set(x, y, z, order = this._order) {
  4686. this._x = x;
  4687. this._y = y;
  4688. this._z = z;
  4689. this._order = order;
  4690. this._onChangeCallback();
  4691. return this;
  4692. }
  4693. clone() {
  4694. return new this.constructor(this._x, this._y, this._z, this._order);
  4695. }
  4696. copy(euler) {
  4697. this._x = euler._x;
  4698. this._y = euler._y;
  4699. this._z = euler._z;
  4700. this._order = euler._order;
  4701. this._onChangeCallback();
  4702. return this;
  4703. }
  4704. setFromRotationMatrix(m, order = this._order, update = true) {
  4705. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  4706. const te = m.elements;
  4707. const m11 = te[0],
  4708. m12 = te[4],
  4709. m13 = te[8];
  4710. const m21 = te[1],
  4711. m22 = te[5],
  4712. m23 = te[9];
  4713. const m31 = te[2],
  4714. m32 = te[6],
  4715. m33 = te[10];
  4716. switch (order) {
  4717. case 'XYZ':
  4718. this._y = Math.asin(clamp(m13, -1, 1));
  4719. if (Math.abs(m13) < 0.9999999) {
  4720. this._x = Math.atan2(-m23, m33);
  4721. this._z = Math.atan2(-m12, m11);
  4722. } else {
  4723. this._x = Math.atan2(m32, m22);
  4724. this._z = 0;
  4725. }
  4726. break;
  4727. case 'YXZ':
  4728. this._x = Math.asin(-clamp(m23, -1, 1));
  4729. if (Math.abs(m23) < 0.9999999) {
  4730. this._y = Math.atan2(m13, m33);
  4731. this._z = Math.atan2(m21, m22);
  4732. } else {
  4733. this._y = Math.atan2(-m31, m11);
  4734. this._z = 0;
  4735. }
  4736. break;
  4737. case 'ZXY':
  4738. this._x = Math.asin(clamp(m32, -1, 1));
  4739. if (Math.abs(m32) < 0.9999999) {
  4740. this._y = Math.atan2(-m31, m33);
  4741. this._z = Math.atan2(-m12, m22);
  4742. } else {
  4743. this._y = 0;
  4744. this._z = Math.atan2(m21, m11);
  4745. }
  4746. break;
  4747. case 'ZYX':
  4748. this._y = Math.asin(-clamp(m31, -1, 1));
  4749. if (Math.abs(m31) < 0.9999999) {
  4750. this._x = Math.atan2(m32, m33);
  4751. this._z = Math.atan2(m21, m11);
  4752. } else {
  4753. this._x = 0;
  4754. this._z = Math.atan2(-m12, m22);
  4755. }
  4756. break;
  4757. case 'YZX':
  4758. this._z = Math.asin(clamp(m21, -1, 1));
  4759. if (Math.abs(m21) < 0.9999999) {
  4760. this._x = Math.atan2(-m23, m22);
  4761. this._y = Math.atan2(-m31, m11);
  4762. } else {
  4763. this._x = 0;
  4764. this._y = Math.atan2(m13, m33);
  4765. }
  4766. break;
  4767. case 'XZY':
  4768. this._z = Math.asin(-clamp(m12, -1, 1));
  4769. if (Math.abs(m12) < 0.9999999) {
  4770. this._x = Math.atan2(m32, m22);
  4771. this._y = Math.atan2(m13, m11);
  4772. } else {
  4773. this._x = Math.atan2(-m23, m33);
  4774. this._y = 0;
  4775. }
  4776. break;
  4777. default:
  4778. console.warn('THREE.Euler: .setFromRotationMatrix() encountered an unknown order: ' + order);
  4779. }
  4780. this._order = order;
  4781. if (update === true) this._onChangeCallback();
  4782. return this;
  4783. }
  4784. setFromQuaternion(q, order, update) {
  4785. _matrix$1.makeRotationFromQuaternion(q);
  4786. return this.setFromRotationMatrix(_matrix$1, order, update);
  4787. }
  4788. setFromVector3(v, order = this._order) {
  4789. return this.set(v.x, v.y, v.z, order);
  4790. }
  4791. reorder(newOrder) {
  4792. // WARNING: this discards revolution information -bhouston
  4793. _quaternion$3.setFromEuler(this);
  4794. return this.setFromQuaternion(_quaternion$3, newOrder);
  4795. }
  4796. equals(euler) {
  4797. return euler._x === this._x && euler._y === this._y && euler._z === this._z && euler._order === this._order;
  4798. }
  4799. fromArray(array) {
  4800. this._x = array[0];
  4801. this._y = array[1];
  4802. this._z = array[2];
  4803. if (array[3] !== undefined) this._order = array[3];
  4804. this._onChangeCallback();
  4805. return this;
  4806. }
  4807. toArray(array = [], offset = 0) {
  4808. array[offset] = this._x;
  4809. array[offset + 1] = this._y;
  4810. array[offset + 2] = this._z;
  4811. array[offset + 3] = this._order;
  4812. return array;
  4813. }
  4814. _onChange(callback) {
  4815. this._onChangeCallback = callback;
  4816. return this;
  4817. }
  4818. _onChangeCallback() {}
  4819. *[Symbol.iterator]() {
  4820. yield this._x;
  4821. yield this._y;
  4822. yield this._z;
  4823. yield this._order;
  4824. } // @deprecated since r138, 02cf0df1cb4575d5842fef9c85bb5a89fe020d53
  4825. toVector3() {
  4826. console.error('THREE.Euler: .toVector3() has been removed. Use Vector3.setFromEuler() instead');
  4827. }
  4828. }
  4829. Euler.DefaultOrder = 'XYZ';
  4830. Euler.RotationOrders = ['XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX'];
  4831. class Layers {
  4832. constructor() {
  4833. this.mask = 1 | 0;
  4834. }
  4835. set(channel) {
  4836. this.mask = (1 << channel | 0) >>> 0;
  4837. }
  4838. enable(channel) {
  4839. this.mask |= 1 << channel | 0;
  4840. }
  4841. enableAll() {
  4842. this.mask = 0xffffffff | 0;
  4843. }
  4844. toggle(channel) {
  4845. this.mask ^= 1 << channel | 0;
  4846. }
  4847. disable(channel) {
  4848. this.mask &= ~(1 << channel | 0);
  4849. }
  4850. disableAll() {
  4851. this.mask = 0;
  4852. }
  4853. test(layers) {
  4854. return (this.mask & layers.mask) !== 0;
  4855. }
  4856. isEnabled(channel) {
  4857. return (this.mask & (1 << channel | 0)) !== 0;
  4858. }
  4859. }
  4860. let _object3DId = 0;
  4861. const _v1$4 = /*@__PURE__*/new Vector3();
  4862. const _q1 = /*@__PURE__*/new Quaternion();
  4863. const _m1$1 = /*@__PURE__*/new Matrix4();
  4864. const _target = /*@__PURE__*/new Vector3();
  4865. const _position$3 = /*@__PURE__*/new Vector3();
  4866. const _scale$2 = /*@__PURE__*/new Vector3();
  4867. const _quaternion$2 = /*@__PURE__*/new Quaternion();
  4868. const _xAxis = /*@__PURE__*/new Vector3(1, 0, 0);
  4869. const _yAxis = /*@__PURE__*/new Vector3(0, 1, 0);
  4870. const _zAxis = /*@__PURE__*/new Vector3(0, 0, 1);
  4871. const _addedEvent = {
  4872. type: 'added'
  4873. };
  4874. const _removedEvent = {
  4875. type: 'removed'
  4876. };
  4877. class Object3D extends EventDispatcher {
  4878. constructor() {
  4879. super();
  4880. this.isObject3D = true;
  4881. Object.defineProperty(this, 'id', {
  4882. value: _object3DId++
  4883. });
  4884. this.uuid = generateUUID();
  4885. this.name = '';
  4886. this.type = 'Object3D';
  4887. this.parent = null;
  4888. this.children = [];
  4889. this.up = Object3D.DefaultUp.clone();
  4890. const position = new Vector3();
  4891. const rotation = new Euler();
  4892. const quaternion = new Quaternion();
  4893. const scale = new Vector3(1, 1, 1);
  4894. function onRotationChange() {
  4895. quaternion.setFromEuler(rotation, false);
  4896. }
  4897. function onQuaternionChange() {
  4898. rotation.setFromQuaternion(quaternion, undefined, false);
  4899. }
  4900. rotation._onChange(onRotationChange);
  4901. quaternion._onChange(onQuaternionChange);
  4902. Object.defineProperties(this, {
  4903. position: {
  4904. configurable: true,
  4905. enumerable: true,
  4906. value: position
  4907. },
  4908. rotation: {
  4909. configurable: true,
  4910. enumerable: true,
  4911. value: rotation
  4912. },
  4913. quaternion: {
  4914. configurable: true,
  4915. enumerable: true,
  4916. value: quaternion
  4917. },
  4918. scale: {
  4919. configurable: true,
  4920. enumerable: true,
  4921. value: scale
  4922. },
  4923. modelViewMatrix: {
  4924. value: new Matrix4()
  4925. },
  4926. normalMatrix: {
  4927. value: new Matrix3()
  4928. }
  4929. });
  4930. this.matrix = new Matrix4();
  4931. this.matrixWorld = new Matrix4();
  4932. this.matrixAutoUpdate = Object3D.DefaultMatrixAutoUpdate;
  4933. this.matrixWorldNeedsUpdate = false;
  4934. this.layers = new Layers();
  4935. this.visible = true;
  4936. this.castShadow = false;
  4937. this.receiveShadow = false;
  4938. this.frustumCulled = true;
  4939. this.renderOrder = 0;
  4940. this.animations = [];
  4941. this.userData = {};
  4942. }
  4943. onBeforeRender() {}
  4944. onAfterRender() {}
  4945. applyMatrix4(matrix) {
  4946. if (this.matrixAutoUpdate) this.updateMatrix();
  4947. this.matrix.premultiply(matrix);
  4948. this.matrix.decompose(this.position, this.quaternion, this.scale);
  4949. }
  4950. applyQuaternion(q) {
  4951. this.quaternion.premultiply(q);
  4952. return this;
  4953. }
  4954. setRotationFromAxisAngle(axis, angle) {
  4955. // assumes axis is normalized
  4956. this.quaternion.setFromAxisAngle(axis, angle);
  4957. }
  4958. setRotationFromEuler(euler) {
  4959. this.quaternion.setFromEuler(euler, true);
  4960. }
  4961. setRotationFromMatrix(m) {
  4962. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  4963. this.quaternion.setFromRotationMatrix(m);
  4964. }
  4965. setRotationFromQuaternion(q) {
  4966. // assumes q is normalized
  4967. this.quaternion.copy(q);
  4968. }
  4969. rotateOnAxis(axis, angle) {
  4970. // rotate object on axis in object space
  4971. // axis is assumed to be normalized
  4972. _q1.setFromAxisAngle(axis, angle);
  4973. this.quaternion.multiply(_q1);
  4974. return this;
  4975. }
  4976. rotateOnWorldAxis(axis, angle) {
  4977. // rotate object on axis in world space
  4978. // axis is assumed to be normalized
  4979. // method assumes no rotated parent
  4980. _q1.setFromAxisAngle(axis, angle);
  4981. this.quaternion.premultiply(_q1);
  4982. return this;
  4983. }
  4984. rotateX(angle) {
  4985. return this.rotateOnAxis(_xAxis, angle);
  4986. }
  4987. rotateY(angle) {
  4988. return this.rotateOnAxis(_yAxis, angle);
  4989. }
  4990. rotateZ(angle) {
  4991. return this.rotateOnAxis(_zAxis, angle);
  4992. }
  4993. translateOnAxis(axis, distance) {
  4994. // translate object by distance along axis in object space
  4995. // axis is assumed to be normalized
  4996. _v1$4.copy(axis).applyQuaternion(this.quaternion);
  4997. this.position.add(_v1$4.multiplyScalar(distance));
  4998. return this;
  4999. }
  5000. translateX(distance) {
  5001. return this.translateOnAxis(_xAxis, distance);
  5002. }
  5003. translateY(distance) {
  5004. return this.translateOnAxis(_yAxis, distance);
  5005. }
  5006. translateZ(distance) {
  5007. return this.translateOnAxis(_zAxis, distance);
  5008. }
  5009. localToWorld(vector) {
  5010. return vector.applyMatrix4(this.matrixWorld);
  5011. }
  5012. worldToLocal(vector) {
  5013. return vector.applyMatrix4(_m1$1.copy(this.matrixWorld).invert());
  5014. }
  5015. lookAt(x, y, z) {
  5016. // This method does not support objects having non-uniformly-scaled parent(s)
  5017. if (x.isVector3) {
  5018. _target.copy(x);
  5019. } else {
  5020. _target.set(x, y, z);
  5021. }
  5022. const parent = this.parent;
  5023. this.updateWorldMatrix(true, false);
  5024. _position$3.setFromMatrixPosition(this.matrixWorld);
  5025. if (this.isCamera || this.isLight) {
  5026. _m1$1.lookAt(_position$3, _target, this.up);
  5027. } else {
  5028. _m1$1.lookAt(_target, _position$3, this.up);
  5029. }
  5030. this.quaternion.setFromRotationMatrix(_m1$1);
  5031. if (parent) {
  5032. _m1$1.extractRotation(parent.matrixWorld);
  5033. _q1.setFromRotationMatrix(_m1$1);
  5034. this.quaternion.premultiply(_q1.invert());
  5035. }
  5036. }
  5037. add(object) {
  5038. if (arguments.length > 1) {
  5039. for (let i = 0; i < arguments.length; i++) {
  5040. this.add(arguments[i]);
  5041. }
  5042. return this;
  5043. }
  5044. if (object === this) {
  5045. console.error('THREE.Object3D.add: object can\'t be added as a child of itself.', object);
  5046. return this;
  5047. }
  5048. if (object && object.isObject3D) {
  5049. if (object.parent !== null) {
  5050. object.parent.remove(object);
  5051. }
  5052. object.parent = this;
  5053. this.children.push(object);
  5054. object.dispatchEvent(_addedEvent);
  5055. } else {
  5056. console.error('THREE.Object3D.add: object not an instance of THREE.Object3D.', object);
  5057. }
  5058. return this;
  5059. }
  5060. remove(object) {
  5061. if (arguments.length > 1) {
  5062. for (let i = 0; i < arguments.length; i++) {
  5063. this.remove(arguments[i]);
  5064. }
  5065. return this;
  5066. }
  5067. const index = this.children.indexOf(object);
  5068. if (index !== -1) {
  5069. object.parent = null;
  5070. this.children.splice(index, 1);
  5071. object.dispatchEvent(_removedEvent);
  5072. }
  5073. return this;
  5074. }
  5075. removeFromParent() {
  5076. const parent = this.parent;
  5077. if (parent !== null) {
  5078. parent.remove(this);
  5079. }
  5080. return this;
  5081. }
  5082. clear() {
  5083. for (let i = 0; i < this.children.length; i++) {
  5084. const object = this.children[i];
  5085. object.parent = null;
  5086. object.dispatchEvent(_removedEvent);
  5087. }
  5088. this.children.length = 0;
  5089. return this;
  5090. }
  5091. attach(object) {
  5092. // adds object as a child of this, while maintaining the object's world transform
  5093. // Note: This method does not support scene graphs having non-uniformly-scaled nodes(s)
  5094. this.updateWorldMatrix(true, false);
  5095. _m1$1.copy(this.matrixWorld).invert();
  5096. if (object.parent !== null) {
  5097. object.parent.updateWorldMatrix(true, false);
  5098. _m1$1.multiply(object.parent.matrixWorld);
  5099. }
  5100. object.applyMatrix4(_m1$1);
  5101. this.add(object);
  5102. object.updateWorldMatrix(false, true);
  5103. return this;
  5104. }
  5105. getObjectById(id) {
  5106. return this.getObjectByProperty('id', id);
  5107. }
  5108. getObjectByName(name) {
  5109. return this.getObjectByProperty('name', name);
  5110. }
  5111. getObjectByProperty(name, value) {
  5112. if (this[name] === value) return this;
  5113. for (let i = 0, l = this.children.length; i < l; i++) {
  5114. const child = this.children[i];
  5115. const object = child.getObjectByProperty(name, value);
  5116. if (object !== undefined) {
  5117. return object;
  5118. }
  5119. }
  5120. return undefined;
  5121. }
  5122. getWorldPosition(target) {
  5123. this.updateWorldMatrix(true, false);
  5124. return target.setFromMatrixPosition(this.matrixWorld);
  5125. }
  5126. getWorldQuaternion(target) {
  5127. this.updateWorldMatrix(true, false);
  5128. this.matrixWorld.decompose(_position$3, target, _scale$2);
  5129. return target;
  5130. }
  5131. getWorldScale(target) {
  5132. this.updateWorldMatrix(true, false);
  5133. this.matrixWorld.decompose(_position$3, _quaternion$2, target);
  5134. return target;
  5135. }
  5136. getWorldDirection(target) {
  5137. this.updateWorldMatrix(true, false);
  5138. const e = this.matrixWorld.elements;
  5139. return target.set(e[8], e[9], e[10]).normalize();
  5140. }
  5141. raycast() {}
  5142. traverse(callback) {
  5143. callback(this);
  5144. const children = this.children;
  5145. for (let i = 0, l = children.length; i < l; i++) {
  5146. children[i].traverse(callback);
  5147. }
  5148. }
  5149. traverseVisible(callback) {
  5150. if (this.visible === false) return;
  5151. callback(this);
  5152. const children = this.children;
  5153. for (let i = 0, l = children.length; i < l; i++) {
  5154. children[i].traverseVisible(callback);
  5155. }
  5156. }
  5157. traverseAncestors(callback) {
  5158. const parent = this.parent;
  5159. if (parent !== null) {
  5160. callback(parent);
  5161. parent.traverseAncestors(callback);
  5162. }
  5163. }
  5164. updateMatrix() {
  5165. this.matrix.compose(this.position, this.quaternion, this.scale);
  5166. this.matrixWorldNeedsUpdate = true;
  5167. }
  5168. updateMatrixWorld(force) {
  5169. if (this.matrixAutoUpdate) this.updateMatrix();
  5170. if (this.matrixWorldNeedsUpdate || force) {
  5171. if (this.parent === null) {
  5172. this.matrixWorld.copy(this.matrix);
  5173. } else {
  5174. this.matrixWorld.multiplyMatrices(this.parent.matrixWorld, this.matrix);
  5175. }
  5176. this.matrixWorldNeedsUpdate = false;
  5177. force = true;
  5178. } // update children
  5179. const children = this.children;
  5180. for (let i = 0, l = children.length; i < l; i++) {
  5181. children[i].updateMatrixWorld(force);
  5182. }
  5183. }
  5184. updateWorldMatrix(updateParents, updateChildren) {
  5185. const parent = this.parent;
  5186. if (updateParents === true && parent !== null) {
  5187. parent.updateWorldMatrix(true, false);
  5188. }
  5189. if (this.matrixAutoUpdate) this.updateMatrix();
  5190. if (this.parent === null) {
  5191. this.matrixWorld.copy(this.matrix);
  5192. } else {
  5193. this.matrixWorld.multiplyMatrices(this.parent.matrixWorld, this.matrix);
  5194. } // update children
  5195. if (updateChildren === true) {
  5196. const children = this.children;
  5197. for (let i = 0, l = children.length; i < l; i++) {
  5198. children[i].updateWorldMatrix(false, true);
  5199. }
  5200. }
  5201. }
  5202. toJSON(meta) {
  5203. // meta is a string when called from JSON.stringify
  5204. const isRootObject = meta === undefined || typeof meta === 'string';
  5205. const output = {}; // meta is a hash used to collect geometries, materials.
  5206. // not providing it implies that this is the root object
  5207. // being serialized.
  5208. if (isRootObject) {
  5209. // initialize meta obj
  5210. meta = {
  5211. geometries: {},
  5212. materials: {},
  5213. textures: {},
  5214. images: {},
  5215. shapes: {},
  5216. skeletons: {},
  5217. animations: {},
  5218. nodes: {}
  5219. };
  5220. output.metadata = {
  5221. version: 4.5,
  5222. type: 'Object',
  5223. generator: 'Object3D.toJSON'
  5224. };
  5225. } // standard Object3D serialization
  5226. const object = {};
  5227. object.uuid = this.uuid;
  5228. object.type = this.type;
  5229. if (this.name !== '') object.name = this.name;
  5230. if (this.castShadow === true) object.castShadow = true;
  5231. if (this.receiveShadow === true) object.receiveShadow = true;
  5232. if (this.visible === false) object.visible = false;
  5233. if (this.frustumCulled === false) object.frustumCulled = false;
  5234. if (this.renderOrder !== 0) object.renderOrder = this.renderOrder;
  5235. if (JSON.stringify(this.userData) !== '{}') object.userData = this.userData;
  5236. object.layers = this.layers.mask;
  5237. object.matrix = this.matrix.toArray();
  5238. if (this.matrixAutoUpdate === false) object.matrixAutoUpdate = false; // object specific properties
  5239. if (this.isInstancedMesh) {
  5240. object.type = 'InstancedMesh';
  5241. object.count = this.count;
  5242. object.instanceMatrix = this.instanceMatrix.toJSON();
  5243. if (this.instanceColor !== null) object.instanceColor = this.instanceColor.toJSON();
  5244. } //
  5245. function serialize(library, element) {
  5246. if (library[element.uuid] === undefined) {
  5247. library[element.uuid] = element.toJSON(meta);
  5248. }
  5249. return element.uuid;
  5250. }
  5251. if (this.isScene) {
  5252. if (this.background) {
  5253. if (this.background.isColor) {
  5254. object.background = this.background.toJSON();
  5255. } else if (this.background.isTexture) {
  5256. object.background = this.background.toJSON(meta).uuid;
  5257. }
  5258. }
  5259. if (this.environment && this.environment.isTexture) {
  5260. object.environment = this.environment.toJSON(meta).uuid;
  5261. }
  5262. } else if (this.isMesh || this.isLine || this.isPoints) {
  5263. object.geometry = serialize(meta.geometries, this.geometry);
  5264. const parameters = this.geometry.parameters;
  5265. if (parameters !== undefined && parameters.shapes !== undefined) {
  5266. const shapes = parameters.shapes;
  5267. if (Array.isArray(shapes)) {
  5268. for (let i = 0, l = shapes.length; i < l; i++) {
  5269. const shape = shapes[i];
  5270. serialize(meta.shapes, shape);
  5271. }
  5272. } else {
  5273. serialize(meta.shapes, shapes);
  5274. }
  5275. }
  5276. }
  5277. if (this.isSkinnedMesh) {
  5278. object.bindMode = this.bindMode;
  5279. object.bindMatrix = this.bindMatrix.toArray();
  5280. if (this.skeleton !== undefined) {
  5281. serialize(meta.skeletons, this.skeleton);
  5282. object.skeleton = this.skeleton.uuid;
  5283. }
  5284. }
  5285. if (this.material !== undefined) {
  5286. if (Array.isArray(this.material)) {
  5287. const uuids = [];
  5288. for (let i = 0, l = this.material.length; i < l; i++) {
  5289. uuids.push(serialize(meta.materials, this.material[i]));
  5290. }
  5291. object.material = uuids;
  5292. } else {
  5293. object.material = serialize(meta.materials, this.material);
  5294. }
  5295. } //
  5296. if (this.children.length > 0) {
  5297. object.children = [];
  5298. for (let i = 0; i < this.children.length; i++) {
  5299. object.children.push(this.children[i].toJSON(meta).object);
  5300. }
  5301. } //
  5302. if (this.animations.length > 0) {
  5303. object.animations = [];
  5304. for (let i = 0; i < this.animations.length; i++) {
  5305. const animation = this.animations[i];
  5306. object.animations.push(serialize(meta.animations, animation));
  5307. }
  5308. }
  5309. if (isRootObject) {
  5310. const geometries = extractFromCache(meta.geometries);
  5311. const materials = extractFromCache(meta.materials);
  5312. const textures = extractFromCache(meta.textures);
  5313. const images = extractFromCache(meta.images);
  5314. const shapes = extractFromCache(meta.shapes);
  5315. const skeletons = extractFromCache(meta.skeletons);
  5316. const animations = extractFromCache(meta.animations);
  5317. const nodes = extractFromCache(meta.nodes);
  5318. if (geometries.length > 0) output.geometries = geometries;
  5319. if (materials.length > 0) output.materials = materials;
  5320. if (textures.length > 0) output.textures = textures;
  5321. if (images.length > 0) output.images = images;
  5322. if (shapes.length > 0) output.shapes = shapes;
  5323. if (skeletons.length > 0) output.skeletons = skeletons;
  5324. if (animations.length > 0) output.animations = animations;
  5325. if (nodes.length > 0) output.nodes = nodes;
  5326. }
  5327. output.object = object;
  5328. return output; // extract data from the cache hash
  5329. // remove metadata on each item
  5330. // and return as array
  5331. function extractFromCache(cache) {
  5332. const values = [];
  5333. for (const key in cache) {
  5334. const data = cache[key];
  5335. delete data.metadata;
  5336. values.push(data);
  5337. }
  5338. return values;
  5339. }
  5340. }
  5341. clone(recursive) {
  5342. return new this.constructor().copy(this, recursive);
  5343. }
  5344. copy(source, recursive = true) {
  5345. this.name = source.name;
  5346. this.up.copy(source.up);
  5347. this.position.copy(source.position);
  5348. this.rotation.order = source.rotation.order;
  5349. this.quaternion.copy(source.quaternion);
  5350. this.scale.copy(source.scale);
  5351. this.matrix.copy(source.matrix);
  5352. this.matrixWorld.copy(source.matrixWorld);
  5353. this.matrixAutoUpdate = source.matrixAutoUpdate;
  5354. this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;
  5355. this.layers.mask = source.layers.mask;
  5356. this.visible = source.visible;
  5357. this.castShadow = source.castShadow;
  5358. this.receiveShadow = source.receiveShadow;
  5359. this.frustumCulled = source.frustumCulled;
  5360. this.renderOrder = source.renderOrder;
  5361. this.userData = JSON.parse(JSON.stringify(source.userData));
  5362. if (recursive === true) {
  5363. for (let i = 0; i < source.children.length; i++) {
  5364. const child = source.children[i];
  5365. this.add(child.clone());
  5366. }
  5367. }
  5368. return this;
  5369. }
  5370. }
  5371. Object3D.DefaultUp = new Vector3(0, 1, 0);
  5372. Object3D.DefaultMatrixAutoUpdate = true;
  5373. const _v0$1 = /*@__PURE__*/new Vector3();
  5374. const _v1$3 = /*@__PURE__*/new Vector3();
  5375. const _v2$2 = /*@__PURE__*/new Vector3();
  5376. const _v3$1 = /*@__PURE__*/new Vector3();
  5377. const _vab = /*@__PURE__*/new Vector3();
  5378. const _vac = /*@__PURE__*/new Vector3();
  5379. const _vbc = /*@__PURE__*/new Vector3();
  5380. const _vap = /*@__PURE__*/new Vector3();
  5381. const _vbp = /*@__PURE__*/new Vector3();
  5382. const _vcp = /*@__PURE__*/new Vector3();
  5383. class Triangle {
  5384. constructor(a = new Vector3(), b = new Vector3(), c = new Vector3()) {
  5385. this.a = a;
  5386. this.b = b;
  5387. this.c = c;
  5388. }
  5389. static getNormal(a, b, c, target) {
  5390. target.subVectors(c, b);
  5391. _v0$1.subVectors(a, b);
  5392. target.cross(_v0$1);
  5393. const targetLengthSq = target.lengthSq();
  5394. if (targetLengthSq > 0) {
  5395. return target.multiplyScalar(1 / Math.sqrt(targetLengthSq));
  5396. }
  5397. return target.set(0, 0, 0);
  5398. } // static/instance method to calculate barycentric coordinates
  5399. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  5400. static getBarycoord(point, a, b, c, target) {
  5401. _v0$1.subVectors(c, a);
  5402. _v1$3.subVectors(b, a);
  5403. _v2$2.subVectors(point, a);
  5404. const dot00 = _v0$1.dot(_v0$1);
  5405. const dot01 = _v0$1.dot(_v1$3);
  5406. const dot02 = _v0$1.dot(_v2$2);
  5407. const dot11 = _v1$3.dot(_v1$3);
  5408. const dot12 = _v1$3.dot(_v2$2);
  5409. const denom = dot00 * dot11 - dot01 * dot01; // collinear or singular triangle
  5410. if (denom === 0) {
  5411. // arbitrary location outside of triangle?
  5412. // not sure if this is the best idea, maybe should be returning undefined
  5413. return target.set(-2, -1, -1);
  5414. }
  5415. const invDenom = 1 / denom;
  5416. const u = (dot11 * dot02 - dot01 * dot12) * invDenom;
  5417. const v = (dot00 * dot12 - dot01 * dot02) * invDenom; // barycentric coordinates must always sum to 1
  5418. return target.set(1 - u - v, v, u);
  5419. }
  5420. static containsPoint(point, a, b, c) {
  5421. this.getBarycoord(point, a, b, c, _v3$1);
  5422. return _v3$1.x >= 0 && _v3$1.y >= 0 && _v3$1.x + _v3$1.y <= 1;
  5423. }
  5424. static getUV(point, p1, p2, p3, uv1, uv2, uv3, target) {
  5425. this.getBarycoord(point, p1, p2, p3, _v3$1);
  5426. target.set(0, 0);
  5427. target.addScaledVector(uv1, _v3$1.x);
  5428. target.addScaledVector(uv2, _v3$1.y);
  5429. target.addScaledVector(uv3, _v3$1.z);
  5430. return target;
  5431. }
  5432. static isFrontFacing(a, b, c, direction) {
  5433. _v0$1.subVectors(c, b);
  5434. _v1$3.subVectors(a, b); // strictly front facing
  5435. return _v0$1.cross(_v1$3).dot(direction) < 0 ? true : false;
  5436. }
  5437. set(a, b, c) {
  5438. this.a.copy(a);
  5439. this.b.copy(b);
  5440. this.c.copy(c);
  5441. return this;
  5442. }
  5443. setFromPointsAndIndices(points, i0, i1, i2) {
  5444. this.a.copy(points[i0]);
  5445. this.b.copy(points[i1]);
  5446. this.c.copy(points[i2]);
  5447. return this;
  5448. }
  5449. setFromAttributeAndIndices(attribute, i0, i1, i2) {
  5450. this.a.fromBufferAttribute(attribute, i0);
  5451. this.b.fromBufferAttribute(attribute, i1);
  5452. this.c.fromBufferAttribute(attribute, i2);
  5453. return this;
  5454. }
  5455. clone() {
  5456. return new this.constructor().copy(this);
  5457. }
  5458. copy(triangle) {
  5459. this.a.copy(triangle.a);
  5460. this.b.copy(triangle.b);
  5461. this.c.copy(triangle.c);
  5462. return this;
  5463. }
  5464. getArea() {
  5465. _v0$1.subVectors(this.c, this.b);
  5466. _v1$3.subVectors(this.a, this.b);
  5467. return _v0$1.cross(_v1$3).length() * 0.5;
  5468. }
  5469. getMidpoint(target) {
  5470. return target.addVectors(this.a, this.b).add(this.c).multiplyScalar(1 / 3);
  5471. }
  5472. getNormal(target) {
  5473. return Triangle.getNormal(this.a, this.b, this.c, target);
  5474. }
  5475. getPlane(target) {
  5476. return target.setFromCoplanarPoints(this.a, this.b, this.c);
  5477. }
  5478. getBarycoord(point, target) {
  5479. return Triangle.getBarycoord(point, this.a, this.b, this.c, target);
  5480. }
  5481. getUV(point, uv1, uv2, uv3, target) {
  5482. return Triangle.getUV(point, this.a, this.b, this.c, uv1, uv2, uv3, target);
  5483. }
  5484. containsPoint(point) {
  5485. return Triangle.containsPoint(point, this.a, this.b, this.c);
  5486. }
  5487. isFrontFacing(direction) {
  5488. return Triangle.isFrontFacing(this.a, this.b, this.c, direction);
  5489. }
  5490. intersectsBox(box) {
  5491. return box.intersectsTriangle(this);
  5492. }
  5493. closestPointToPoint(p, target) {
  5494. const a = this.a,
  5495. b = this.b,
  5496. c = this.c;
  5497. let v, w; // algorithm thanks to Real-Time Collision Detection by Christer Ericson,
  5498. // published by Morgan Kaufmann Publishers, (c) 2005 Elsevier Inc.,
  5499. // under the accompanying license; see chapter 5.1.5 for detailed explanation.
  5500. // basically, we're distinguishing which of the voronoi regions of the triangle
  5501. // the point lies in with the minimum amount of redundant computation.
  5502. _vab.subVectors(b, a);
  5503. _vac.subVectors(c, a);
  5504. _vap.subVectors(p, a);
  5505. const d1 = _vab.dot(_vap);
  5506. const d2 = _vac.dot(_vap);
  5507. if (d1 <= 0 && d2 <= 0) {
  5508. // vertex region of A; barycentric coords (1, 0, 0)
  5509. return target.copy(a);
  5510. }
  5511. _vbp.subVectors(p, b);
  5512. const d3 = _vab.dot(_vbp);
  5513. const d4 = _vac.dot(_vbp);
  5514. if (d3 >= 0 && d4 <= d3) {
  5515. // vertex region of B; barycentric coords (0, 1, 0)
  5516. return target.copy(b);
  5517. }
  5518. const vc = d1 * d4 - d3 * d2;
  5519. if (vc <= 0 && d1 >= 0 && d3 <= 0) {
  5520. v = d1 / (d1 - d3); // edge region of AB; barycentric coords (1-v, v, 0)
  5521. return target.copy(a).addScaledVector(_vab, v);
  5522. }
  5523. _vcp.subVectors(p, c);
  5524. const d5 = _vab.dot(_vcp);
  5525. const d6 = _vac.dot(_vcp);
  5526. if (d6 >= 0 && d5 <= d6) {
  5527. // vertex region of C; barycentric coords (0, 0, 1)
  5528. return target.copy(c);
  5529. }
  5530. const vb = d5 * d2 - d1 * d6;
  5531. if (vb <= 0 && d2 >= 0 && d6 <= 0) {
  5532. w = d2 / (d2 - d6); // edge region of AC; barycentric coords (1-w, 0, w)
  5533. return target.copy(a).addScaledVector(_vac, w);
  5534. }
  5535. const va = d3 * d6 - d5 * d4;
  5536. if (va <= 0 && d4 - d3 >= 0 && d5 - d6 >= 0) {
  5537. _vbc.subVectors(c, b);
  5538. w = (d4 - d3) / (d4 - d3 + (d5 - d6)); // edge region of BC; barycentric coords (0, 1-w, w)
  5539. return target.copy(b).addScaledVector(_vbc, w); // edge region of BC
  5540. } // face region
  5541. const denom = 1 / (va + vb + vc); // u = va * denom
  5542. v = vb * denom;
  5543. w = vc * denom;
  5544. return target.copy(a).addScaledVector(_vab, v).addScaledVector(_vac, w);
  5545. }
  5546. equals(triangle) {
  5547. return triangle.a.equals(this.a) && triangle.b.equals(this.b) && triangle.c.equals(this.c);
  5548. }
  5549. }
  5550. let materialId = 0;
  5551. class Material extends EventDispatcher {
  5552. constructor() {
  5553. super();
  5554. this.isMaterial = true;
  5555. Object.defineProperty(this, 'id', {
  5556. value: materialId++
  5557. });
  5558. this.uuid = generateUUID();
  5559. this.name = '';
  5560. this.type = 'Material';
  5561. this.blending = NormalBlending;
  5562. this.side = FrontSide;
  5563. this.vertexColors = false;
  5564. this.opacity = 1;
  5565. this.transparent = false;
  5566. this.blendSrc = SrcAlphaFactor;
  5567. this.blendDst = OneMinusSrcAlphaFactor;
  5568. this.blendEquation = AddEquation;
  5569. this.blendSrcAlpha = null;
  5570. this.blendDstAlpha = null;
  5571. this.blendEquationAlpha = null;
  5572. this.depthFunc = LessEqualDepth;
  5573. this.depthTest = true;
  5574. this.depthWrite = true;
  5575. this.stencilWriteMask = 0xff;
  5576. this.stencilFunc = AlwaysStencilFunc;
  5577. this.stencilRef = 0;
  5578. this.stencilFuncMask = 0xff;
  5579. this.stencilFail = KeepStencilOp;
  5580. this.stencilZFail = KeepStencilOp;
  5581. this.stencilZPass = KeepStencilOp;
  5582. this.stencilWrite = false;
  5583. this.clippingPlanes = null;
  5584. this.clipIntersection = false;
  5585. this.clipShadows = false;
  5586. this.shadowSide = null;
  5587. this.colorWrite = true;
  5588. this.precision = null; // override the renderer's default precision for this material
  5589. this.polygonOffset = false;
  5590. this.polygonOffsetFactor = 0;
  5591. this.polygonOffsetUnits = 0;
  5592. this.dithering = false;
  5593. this.alphaToCoverage = false;
  5594. this.premultipliedAlpha = false;
  5595. this.visible = true;
  5596. this.toneMapped = true;
  5597. this.userData = {};
  5598. this.version = 0;
  5599. this._alphaTest = 0;
  5600. }
  5601. get alphaTest() {
  5602. return this._alphaTest;
  5603. }
  5604. set alphaTest(value) {
  5605. if (this._alphaTest > 0 !== value > 0) {
  5606. this.version++;
  5607. }
  5608. this._alphaTest = value;
  5609. }
  5610. onBuild() {}
  5611. onBeforeRender() {}
  5612. onBeforeCompile() {}
  5613. customProgramCacheKey() {
  5614. return this.onBeforeCompile.toString();
  5615. }
  5616. setValues(values) {
  5617. if (values === undefined) return;
  5618. for (const key in values) {
  5619. const newValue = values[key];
  5620. if (newValue === undefined) {
  5621. console.warn('THREE.Material: \'' + key + '\' parameter is undefined.');
  5622. continue;
  5623. } // for backward compatibility if shading is set in the constructor
  5624. if (key === 'shading') {
  5625. console.warn('THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.');
  5626. this.flatShading = newValue === FlatShading ? true : false;
  5627. continue;
  5628. }
  5629. const currentValue = this[key];
  5630. if (currentValue === undefined) {
  5631. console.warn('THREE.' + this.type + ': \'' + key + '\' is not a property of this material.');
  5632. continue;
  5633. }
  5634. if (currentValue && currentValue.isColor) {
  5635. currentValue.set(newValue);
  5636. } else if (currentValue && currentValue.isVector3 && newValue && newValue.isVector3) {
  5637. currentValue.copy(newValue);
  5638. } else {
  5639. this[key] = newValue;
  5640. }
  5641. }
  5642. }
  5643. toJSON(meta) {
  5644. const isRootObject = meta === undefined || typeof meta === 'string';
  5645. if (isRootObject) {
  5646. meta = {
  5647. textures: {},
  5648. images: {}
  5649. };
  5650. }
  5651. const data = {
  5652. metadata: {
  5653. version: 4.5,
  5654. type: 'Material',
  5655. generator: 'Material.toJSON'
  5656. }
  5657. }; // standard Material serialization
  5658. data.uuid = this.uuid;
  5659. data.type = this.type;
  5660. if (this.name !== '') data.name = this.name;
  5661. if (this.color && this.color.isColor) data.color = this.color.getHex();
  5662. if (this.roughness !== undefined) data.roughness = this.roughness;
  5663. if (this.metalness !== undefined) data.metalness = this.metalness;
  5664. if (this.sheen !== undefined) data.sheen = this.sheen;
  5665. if (this.sheenColor && this.sheenColor.isColor) data.sheenColor = this.sheenColor.getHex();
  5666. if (this.sheenRoughness !== undefined) data.sheenRoughness = this.sheenRoughness;
  5667. if (this.emissive && this.emissive.isColor) data.emissive = this.emissive.getHex();
  5668. if (this.emissiveIntensity && this.emissiveIntensity !== 1) data.emissiveIntensity = this.emissiveIntensity;
  5669. if (this.specular && this.specular.isColor) data.specular = this.specular.getHex();
  5670. if (this.specularIntensity !== undefined) data.specularIntensity = this.specularIntensity;
  5671. if (this.specularColor && this.specularColor.isColor) data.specularColor = this.specularColor.getHex();
  5672. if (this.shininess !== undefined) data.shininess = this.shininess;
  5673. if (this.clearcoat !== undefined) data.clearcoat = this.clearcoat;
  5674. if (this.clearcoatRoughness !== undefined) data.clearcoatRoughness = this.clearcoatRoughness;
  5675. if (this.clearcoatMap && this.clearcoatMap.isTexture) {
  5676. data.clearcoatMap = this.clearcoatMap.toJSON(meta).uuid;
  5677. }
  5678. if (this.clearcoatRoughnessMap && this.clearcoatRoughnessMap.isTexture) {
  5679. data.clearcoatRoughnessMap = this.clearcoatRoughnessMap.toJSON(meta).uuid;
  5680. }
  5681. if (this.clearcoatNormalMap && this.clearcoatNormalMap.isTexture) {
  5682. data.clearcoatNormalMap = this.clearcoatNormalMap.toJSON(meta).uuid;
  5683. data.clearcoatNormalScale = this.clearcoatNormalScale.toArray();
  5684. }
  5685. if (this.map && this.map.isTexture) data.map = this.map.toJSON(meta).uuid;
  5686. if (this.matcap && this.matcap.isTexture) data.matcap = this.matcap.toJSON(meta).uuid;
  5687. if (this.alphaMap && this.alphaMap.isTexture) data.alphaMap = this.alphaMap.toJSON(meta).uuid;
  5688. if (this.lightMap && this.lightMap.isTexture) {
  5689. data.lightMap = this.lightMap.toJSON(meta).uuid;
  5690. data.lightMapIntensity = this.lightMapIntensity;
  5691. }
  5692. if (this.aoMap && this.aoMap.isTexture) {
  5693. data.aoMap = this.aoMap.toJSON(meta).uuid;
  5694. data.aoMapIntensity = this.aoMapIntensity;
  5695. }
  5696. if (this.bumpMap && this.bumpMap.isTexture) {
  5697. data.bumpMap = this.bumpMap.toJSON(meta).uuid;
  5698. data.bumpScale = this.bumpScale;
  5699. }
  5700. if (this.normalMap && this.normalMap.isTexture) {
  5701. data.normalMap = this.normalMap.toJSON(meta).uuid;
  5702. data.normalMapType = this.normalMapType;
  5703. data.normalScale = this.normalScale.toArray();
  5704. }
  5705. if (this.displacementMap && this.displacementMap.isTexture) {
  5706. data.displacementMap = this.displacementMap.toJSON(meta).uuid;
  5707. data.displacementScale = this.displacementScale;
  5708. data.displacementBias = this.displacementBias;
  5709. }
  5710. if (this.roughnessMap && this.roughnessMap.isTexture) data.roughnessMap = this.roughnessMap.toJSON(meta).uuid;
  5711. if (this.metalnessMap && this.metalnessMap.isTexture) data.metalnessMap = this.metalnessMap.toJSON(meta).uuid;
  5712. if (this.emissiveMap && this.emissiveMap.isTexture) data.emissiveMap = this.emissiveMap.toJSON(meta).uuid;
  5713. if (this.specularMap && this.specularMap.isTexture) data.specularMap = this.specularMap.toJSON(meta).uuid;
  5714. if (this.specularIntensityMap && this.specularIntensityMap.isTexture) data.specularIntensityMap = this.specularIntensityMap.toJSON(meta).uuid;
  5715. if (this.specularColorMap && this.specularColorMap.isTexture) data.specularColorMap = this.specularColorMap.toJSON(meta).uuid;
  5716. if (this.envMap && this.envMap.isTexture) {
  5717. data.envMap = this.envMap.toJSON(meta).uuid;
  5718. if (this.combine !== undefined) data.combine = this.combine;
  5719. }
  5720. if (this.envMapIntensity !== undefined) data.envMapIntensity = this.envMapIntensity;
  5721. if (this.reflectivity !== undefined) data.reflectivity = this.reflectivity;
  5722. if (this.refractionRatio !== undefined) data.refractionRatio = this.refractionRatio;
  5723. if (this.gradientMap && this.gradientMap.isTexture) {
  5724. data.gradientMap = this.gradientMap.toJSON(meta).uuid;
  5725. }
  5726. if (this.transmission !== undefined) data.transmission = this.transmission;
  5727. if (this.transmissionMap && this.transmissionMap.isTexture) data.transmissionMap = this.transmissionMap.toJSON(meta).uuid;
  5728. if (this.thickness !== undefined) data.thickness = this.thickness;
  5729. if (this.thicknessMap && this.thicknessMap.isTexture) data.thicknessMap = this.thicknessMap.toJSON(meta).uuid;
  5730. if (this.attenuationDistance !== undefined) data.attenuationDistance = this.attenuationDistance;
  5731. if (this.attenuationColor !== undefined) data.attenuationColor = this.attenuationColor.getHex();
  5732. if (this.size !== undefined) data.size = this.size;
  5733. if (this.shadowSide !== null) data.shadowSide = this.shadowSide;
  5734. if (this.sizeAttenuation !== undefined) data.sizeAttenuation = this.sizeAttenuation;
  5735. if (this.blending !== NormalBlending) data.blending = this.blending;
  5736. if (this.side !== FrontSide) data.side = this.side;
  5737. if (this.vertexColors) data.vertexColors = true;
  5738. if (this.opacity < 1) data.opacity = this.opacity;
  5739. if (this.transparent === true) data.transparent = this.transparent;
  5740. data.depthFunc = this.depthFunc;
  5741. data.depthTest = this.depthTest;
  5742. data.depthWrite = this.depthWrite;
  5743. data.colorWrite = this.colorWrite;
  5744. data.stencilWrite = this.stencilWrite;
  5745. data.stencilWriteMask = this.stencilWriteMask;
  5746. data.stencilFunc = this.stencilFunc;
  5747. data.stencilRef = this.stencilRef;
  5748. data.stencilFuncMask = this.stencilFuncMask;
  5749. data.stencilFail = this.stencilFail;
  5750. data.stencilZFail = this.stencilZFail;
  5751. data.stencilZPass = this.stencilZPass; // rotation (SpriteMaterial)
  5752. if (this.rotation !== undefined && this.rotation !== 0) data.rotation = this.rotation;
  5753. if (this.polygonOffset === true) data.polygonOffset = true;
  5754. if (this.polygonOffsetFactor !== 0) data.polygonOffsetFactor = this.polygonOffsetFactor;
  5755. if (this.polygonOffsetUnits !== 0) data.polygonOffsetUnits = this.polygonOffsetUnits;
  5756. if (this.linewidth !== undefined && this.linewidth !== 1) data.linewidth = this.linewidth;
  5757. if (this.dashSize !== undefined) data.dashSize = this.dashSize;
  5758. if (this.gapSize !== undefined) data.gapSize = this.gapSize;
  5759. if (this.scale !== undefined) data.scale = this.scale;
  5760. if (this.dithering === true) data.dithering = true;
  5761. if (this.alphaTest > 0) data.alphaTest = this.alphaTest;
  5762. if (this.alphaToCoverage === true) data.alphaToCoverage = this.alphaToCoverage;
  5763. if (this.premultipliedAlpha === true) data.premultipliedAlpha = this.premultipliedAlpha;
  5764. if (this.wireframe === true) data.wireframe = this.wireframe;
  5765. if (this.wireframeLinewidth > 1) data.wireframeLinewidth = this.wireframeLinewidth;
  5766. if (this.wireframeLinecap !== 'round') data.wireframeLinecap = this.wireframeLinecap;
  5767. if (this.wireframeLinejoin !== 'round') data.wireframeLinejoin = this.wireframeLinejoin;
  5768. if (this.flatShading === true) data.flatShading = this.flatShading;
  5769. if (this.visible === false) data.visible = false;
  5770. if (this.toneMapped === false) data.toneMapped = false;
  5771. if (this.fog === false) data.fog = false;
  5772. if (JSON.stringify(this.userData) !== '{}') data.userData = this.userData; // TODO: Copied from Object3D.toJSON
  5773. function extractFromCache(cache) {
  5774. const values = [];
  5775. for (const key in cache) {
  5776. const data = cache[key];
  5777. delete data.metadata;
  5778. values.push(data);
  5779. }
  5780. return values;
  5781. }
  5782. if (isRootObject) {
  5783. const textures = extractFromCache(meta.textures);
  5784. const images = extractFromCache(meta.images);
  5785. if (textures.length > 0) data.textures = textures;
  5786. if (images.length > 0) data.images = images;
  5787. }
  5788. return data;
  5789. }
  5790. clone() {
  5791. return new this.constructor().copy(this);
  5792. }
  5793. copy(source) {
  5794. this.name = source.name;
  5795. this.blending = source.blending;
  5796. this.side = source.side;
  5797. this.vertexColors = source.vertexColors;
  5798. this.opacity = source.opacity;
  5799. this.transparent = source.transparent;
  5800. this.blendSrc = source.blendSrc;
  5801. this.blendDst = source.blendDst;
  5802. this.blendEquation = source.blendEquation;
  5803. this.blendSrcAlpha = source.blendSrcAlpha;
  5804. this.blendDstAlpha = source.blendDstAlpha;
  5805. this.blendEquationAlpha = source.blendEquationAlpha;
  5806. this.depthFunc = source.depthFunc;
  5807. this.depthTest = source.depthTest;
  5808. this.depthWrite = source.depthWrite;
  5809. this.stencilWriteMask = source.stencilWriteMask;
  5810. this.stencilFunc = source.stencilFunc;
  5811. this.stencilRef = source.stencilRef;
  5812. this.stencilFuncMask = source.stencilFuncMask;
  5813. this.stencilFail = source.stencilFail;
  5814. this.stencilZFail = source.stencilZFail;
  5815. this.stencilZPass = source.stencilZPass;
  5816. this.stencilWrite = source.stencilWrite;
  5817. const srcPlanes = source.clippingPlanes;
  5818. let dstPlanes = null;
  5819. if (srcPlanes !== null) {
  5820. const n = srcPlanes.length;
  5821. dstPlanes = new Array(n);
  5822. for (let i = 0; i !== n; ++i) {
  5823. dstPlanes[i] = srcPlanes[i].clone();
  5824. }
  5825. }
  5826. this.clippingPlanes = dstPlanes;
  5827. this.clipIntersection = source.clipIntersection;
  5828. this.clipShadows = source.clipShadows;
  5829. this.shadowSide = source.shadowSide;
  5830. this.colorWrite = source.colorWrite;
  5831. this.precision = source.precision;
  5832. this.polygonOffset = source.polygonOffset;
  5833. this.polygonOffsetFactor = source.polygonOffsetFactor;
  5834. this.polygonOffsetUnits = source.polygonOffsetUnits;
  5835. this.dithering = source.dithering;
  5836. this.alphaTest = source.alphaTest;
  5837. this.alphaToCoverage = source.alphaToCoverage;
  5838. this.premultipliedAlpha = source.premultipliedAlpha;
  5839. this.visible = source.visible;
  5840. this.toneMapped = source.toneMapped;
  5841. this.userData = JSON.parse(JSON.stringify(source.userData));
  5842. return this;
  5843. }
  5844. dispose() {
  5845. this.dispatchEvent({
  5846. type: 'dispose'
  5847. });
  5848. }
  5849. set needsUpdate(value) {
  5850. if (value === true) this.version++;
  5851. } // @deprecated since r131, f5803c62cc4a29d90744e9dc7811d086e354c1d8
  5852. get vertexTangents() {
  5853. console.warn('THREE.' + this.type + ': .vertexTangents has been removed.');
  5854. return false;
  5855. }
  5856. set vertexTangents(value) {
  5857. console.warn('THREE.' + this.type + ': .vertexTangents has been removed.');
  5858. }
  5859. }
  5860. Material.fromType = function
  5861. /*type*/
  5862. () {
  5863. // TODO: Behavior added in Materials.js
  5864. return null;
  5865. };
  5866. class MeshBasicMaterial extends Material {
  5867. constructor(parameters) {
  5868. super();
  5869. this.isMeshBasicMaterial = true;
  5870. this.type = 'MeshBasicMaterial';
  5871. this.color = new Color(0xffffff); // emissive
  5872. this.map = null;
  5873. this.lightMap = null;
  5874. this.lightMapIntensity = 1.0;
  5875. this.aoMap = null;
  5876. this.aoMapIntensity = 1.0;
  5877. this.specularMap = null;
  5878. this.alphaMap = null;
  5879. this.envMap = null;
  5880. this.combine = MultiplyOperation;
  5881. this.reflectivity = 1;
  5882. this.refractionRatio = 0.98;
  5883. this.wireframe = false;
  5884. this.wireframeLinewidth = 1;
  5885. this.wireframeLinecap = 'round';
  5886. this.wireframeLinejoin = 'round';
  5887. this.fog = true;
  5888. this.setValues(parameters);
  5889. }
  5890. copy(source) {
  5891. super.copy(source);
  5892. this.color.copy(source.color);
  5893. this.map = source.map;
  5894. this.lightMap = source.lightMap;
  5895. this.lightMapIntensity = source.lightMapIntensity;
  5896. this.aoMap = source.aoMap;
  5897. this.aoMapIntensity = source.aoMapIntensity;
  5898. this.specularMap = source.specularMap;
  5899. this.alphaMap = source.alphaMap;
  5900. this.envMap = source.envMap;
  5901. this.combine = source.combine;
  5902. this.reflectivity = source.reflectivity;
  5903. this.refractionRatio = source.refractionRatio;
  5904. this.wireframe = source.wireframe;
  5905. this.wireframeLinewidth = source.wireframeLinewidth;
  5906. this.wireframeLinecap = source.wireframeLinecap;
  5907. this.wireframeLinejoin = source.wireframeLinejoin;
  5908. this.fog = source.fog;
  5909. return this;
  5910. }
  5911. }
  5912. const _vector$9 = /*@__PURE__*/new Vector3();
  5913. const _vector2$1 = /*@__PURE__*/new Vector2();
  5914. class BufferAttribute {
  5915. constructor(array, itemSize, normalized) {
  5916. if (Array.isArray(array)) {
  5917. throw new TypeError('THREE.BufferAttribute: array should be a Typed Array.');
  5918. }
  5919. this.isBufferAttribute = true;
  5920. this.name = '';
  5921. this.array = array;
  5922. this.itemSize = itemSize;
  5923. this.count = array !== undefined ? array.length / itemSize : 0;
  5924. this.normalized = normalized === true;
  5925. this.usage = StaticDrawUsage;
  5926. this.updateRange = {
  5927. offset: 0,
  5928. count: -1
  5929. };
  5930. this.version = 0;
  5931. }
  5932. onUploadCallback() {}
  5933. set needsUpdate(value) {
  5934. if (value === true) this.version++;
  5935. }
  5936. setUsage(value) {
  5937. this.usage = value;
  5938. return this;
  5939. }
  5940. copy(source) {
  5941. this.name = source.name;
  5942. this.array = new source.array.constructor(source.array);
  5943. this.itemSize = source.itemSize;
  5944. this.count = source.count;
  5945. this.normalized = source.normalized;
  5946. this.usage = source.usage;
  5947. return this;
  5948. }
  5949. copyAt(index1, attribute, index2) {
  5950. index1 *= this.itemSize;
  5951. index2 *= attribute.itemSize;
  5952. for (let i = 0, l = this.itemSize; i < l; i++) {
  5953. this.array[index1 + i] = attribute.array[index2 + i];
  5954. }
  5955. return this;
  5956. }
  5957. copyArray(array) {
  5958. this.array.set(array);
  5959. return this;
  5960. }
  5961. copyColorsArray(colors) {
  5962. const array = this.array;
  5963. let offset = 0;
  5964. for (let i = 0, l = colors.length; i < l; i++) {
  5965. let color = colors[i];
  5966. if (color === undefined) {
  5967. console.warn('THREE.BufferAttribute.copyColorsArray(): color is undefined', i);
  5968. color = new Color();
  5969. }
  5970. array[offset++] = color.r;
  5971. array[offset++] = color.g;
  5972. array[offset++] = color.b;
  5973. }
  5974. return this;
  5975. }
  5976. copyVector2sArray(vectors) {
  5977. const array = this.array;
  5978. let offset = 0;
  5979. for (let i = 0, l = vectors.length; i < l; i++) {
  5980. let vector = vectors[i];
  5981. if (vector === undefined) {
  5982. console.warn('THREE.BufferAttribute.copyVector2sArray(): vector is undefined', i);
  5983. vector = new Vector2();
  5984. }
  5985. array[offset++] = vector.x;
  5986. array[offset++] = vector.y;
  5987. }
  5988. return this;
  5989. }
  5990. copyVector3sArray(vectors) {
  5991. const array = this.array;
  5992. let offset = 0;
  5993. for (let i = 0, l = vectors.length; i < l; i++) {
  5994. let vector = vectors[i];
  5995. if (vector === undefined) {
  5996. console.warn('THREE.BufferAttribute.copyVector3sArray(): vector is undefined', i);
  5997. vector = new Vector3();
  5998. }
  5999. array[offset++] = vector.x;
  6000. array[offset++] = vector.y;
  6001. array[offset++] = vector.z;
  6002. }
  6003. return this;
  6004. }
  6005. copyVector4sArray(vectors) {
  6006. const array = this.array;
  6007. let offset = 0;
  6008. for (let i = 0, l = vectors.length; i < l; i++) {
  6009. let vector = vectors[i];
  6010. if (vector === undefined) {
  6011. console.warn('THREE.BufferAttribute.copyVector4sArray(): vector is undefined', i);
  6012. vector = new Vector4();
  6013. }
  6014. array[offset++] = vector.x;
  6015. array[offset++] = vector.y;
  6016. array[offset++] = vector.z;
  6017. array[offset++] = vector.w;
  6018. }
  6019. return this;
  6020. }
  6021. applyMatrix3(m) {
  6022. if (this.itemSize === 2) {
  6023. for (let i = 0, l = this.count; i < l; i++) {
  6024. _vector2$1.fromBufferAttribute(this, i);
  6025. _vector2$1.applyMatrix3(m);
  6026. this.setXY(i, _vector2$1.x, _vector2$1.y);
  6027. }
  6028. } else if (this.itemSize === 3) {
  6029. for (let i = 0, l = this.count; i < l; i++) {
  6030. _vector$9.fromBufferAttribute(this, i);
  6031. _vector$9.applyMatrix3(m);
  6032. this.setXYZ(i, _vector$9.x, _vector$9.y, _vector$9.z);
  6033. }
  6034. }
  6035. return this;
  6036. }
  6037. applyMatrix4(m) {
  6038. for (let i = 0, l = this.count; i < l; i++) {
  6039. _vector$9.fromBufferAttribute(this, i);
  6040. _vector$9.applyMatrix4(m);
  6041. this.setXYZ(i, _vector$9.x, _vector$9.y, _vector$9.z);
  6042. }
  6043. return this;
  6044. }
  6045. applyNormalMatrix(m) {
  6046. for (let i = 0, l = this.count; i < l; i++) {
  6047. _vector$9.fromBufferAttribute(this, i);
  6048. _vector$9.applyNormalMatrix(m);
  6049. this.setXYZ(i, _vector$9.x, _vector$9.y, _vector$9.z);
  6050. }
  6051. return this;
  6052. }
  6053. transformDirection(m) {
  6054. for (let i = 0, l = this.count; i < l; i++) {
  6055. _vector$9.fromBufferAttribute(this, i);
  6056. _vector$9.transformDirection(m);
  6057. this.setXYZ(i, _vector$9.x, _vector$9.y, _vector$9.z);
  6058. }
  6059. return this;
  6060. }
  6061. set(value, offset = 0) {
  6062. this.array.set(value, offset);
  6063. return this;
  6064. }
  6065. getX(index) {
  6066. return this.array[index * this.itemSize];
  6067. }
  6068. setX(index, x) {
  6069. this.array[index * this.itemSize] = x;
  6070. return this;
  6071. }
  6072. getY(index) {
  6073. return this.array[index * this.itemSize + 1];
  6074. }
  6075. setY(index, y) {
  6076. this.array[index * this.itemSize + 1] = y;
  6077. return this;
  6078. }
  6079. getZ(index) {
  6080. return this.array[index * this.itemSize + 2];
  6081. }
  6082. setZ(index, z) {
  6083. this.array[index * this.itemSize + 2] = z;
  6084. return this;
  6085. }
  6086. getW(index) {
  6087. return this.array[index * this.itemSize + 3];
  6088. }
  6089. setW(index, w) {
  6090. this.array[index * this.itemSize + 3] = w;
  6091. return this;
  6092. }
  6093. setXY(index, x, y) {
  6094. index *= this.itemSize;
  6095. this.array[index + 0] = x;
  6096. this.array[index + 1] = y;
  6097. return this;
  6098. }
  6099. setXYZ(index, x, y, z) {
  6100. index *= this.itemSize;
  6101. this.array[index + 0] = x;
  6102. this.array[index + 1] = y;
  6103. this.array[index + 2] = z;
  6104. return this;
  6105. }
  6106. setXYZW(index, x, y, z, w) {
  6107. index *= this.itemSize;
  6108. this.array[index + 0] = x;
  6109. this.array[index + 1] = y;
  6110. this.array[index + 2] = z;
  6111. this.array[index + 3] = w;
  6112. return this;
  6113. }
  6114. onUpload(callback) {
  6115. this.onUploadCallback = callback;
  6116. return this;
  6117. }
  6118. clone() {
  6119. return new this.constructor(this.array, this.itemSize).copy(this);
  6120. }
  6121. toJSON() {
  6122. const data = {
  6123. itemSize: this.itemSize,
  6124. type: this.array.constructor.name,
  6125. array: Array.prototype.slice.call(this.array),
  6126. normalized: this.normalized
  6127. };
  6128. if (this.name !== '') data.name = this.name;
  6129. if (this.usage !== StaticDrawUsage) data.usage = this.usage;
  6130. if (this.updateRange.offset !== 0 || this.updateRange.count !== -1) data.updateRange = this.updateRange;
  6131. return data;
  6132. }
  6133. } //
  6134. class Int8BufferAttribute extends BufferAttribute {
  6135. constructor(array, itemSize, normalized) {
  6136. super(new Int8Array(array), itemSize, normalized);
  6137. }
  6138. }
  6139. class Uint8BufferAttribute extends BufferAttribute {
  6140. constructor(array, itemSize, normalized) {
  6141. super(new Uint8Array(array), itemSize, normalized);
  6142. }
  6143. }
  6144. class Uint8ClampedBufferAttribute extends BufferAttribute {
  6145. constructor(array, itemSize, normalized) {
  6146. super(new Uint8ClampedArray(array), itemSize, normalized);
  6147. }
  6148. }
  6149. class Int16BufferAttribute extends BufferAttribute {
  6150. constructor(array, itemSize, normalized) {
  6151. super(new Int16Array(array), itemSize, normalized);
  6152. }
  6153. }
  6154. class Uint16BufferAttribute extends BufferAttribute {
  6155. constructor(array, itemSize, normalized) {
  6156. super(new Uint16Array(array), itemSize, normalized);
  6157. }
  6158. }
  6159. class Int32BufferAttribute extends BufferAttribute {
  6160. constructor(array, itemSize, normalized) {
  6161. super(new Int32Array(array), itemSize, normalized);
  6162. }
  6163. }
  6164. class Uint32BufferAttribute extends BufferAttribute {
  6165. constructor(array, itemSize, normalized) {
  6166. super(new Uint32Array(array), itemSize, normalized);
  6167. }
  6168. }
  6169. class Float16BufferAttribute extends BufferAttribute {
  6170. constructor(array, itemSize, normalized) {
  6171. super(new Uint16Array(array), itemSize, normalized);
  6172. this.isFloat16BufferAttribute = true;
  6173. }
  6174. }
  6175. class Float32BufferAttribute extends BufferAttribute {
  6176. constructor(array, itemSize, normalized) {
  6177. super(new Float32Array(array), itemSize, normalized);
  6178. }
  6179. }
  6180. class Float64BufferAttribute extends BufferAttribute {
  6181. constructor(array, itemSize, normalized) {
  6182. super(new Float64Array(array), itemSize, normalized);
  6183. }
  6184. } //
  6185. let _id$1 = 0;
  6186. const _m1 = /*@__PURE__*/new Matrix4();
  6187. const _obj = /*@__PURE__*/new Object3D();
  6188. const _offset = /*@__PURE__*/new Vector3();
  6189. const _box$1 = /*@__PURE__*/new Box3();
  6190. const _boxMorphTargets = /*@__PURE__*/new Box3();
  6191. const _vector$8 = /*@__PURE__*/new Vector3();
  6192. class BufferGeometry extends EventDispatcher {
  6193. constructor() {
  6194. super();
  6195. this.isBufferGeometry = true;
  6196. Object.defineProperty(this, 'id', {
  6197. value: _id$1++
  6198. });
  6199. this.uuid = generateUUID();
  6200. this.name = '';
  6201. this.type = 'BufferGeometry';
  6202. this.index = null;
  6203. this.attributes = {};
  6204. this.morphAttributes = {};
  6205. this.morphTargetsRelative = false;
  6206. this.groups = [];
  6207. this.boundingBox = null;
  6208. this.boundingSphere = null;
  6209. this.drawRange = {
  6210. start: 0,
  6211. count: Infinity
  6212. };
  6213. this.userData = {};
  6214. }
  6215. getIndex() {
  6216. return this.index;
  6217. }
  6218. setIndex(index) {
  6219. if (Array.isArray(index)) {
  6220. this.index = new (arrayNeedsUint32(index) ? Uint32BufferAttribute : Uint16BufferAttribute)(index, 1);
  6221. } else {
  6222. this.index = index;
  6223. }
  6224. return this;
  6225. }
  6226. getAttribute(name) {
  6227. return this.attributes[name];
  6228. }
  6229. setAttribute(name, attribute) {
  6230. this.attributes[name] = attribute;
  6231. return this;
  6232. }
  6233. deleteAttribute(name) {
  6234. delete this.attributes[name];
  6235. return this;
  6236. }
  6237. hasAttribute(name) {
  6238. return this.attributes[name] !== undefined;
  6239. }
  6240. addGroup(start, count, materialIndex = 0) {
  6241. this.groups.push({
  6242. start: start,
  6243. count: count,
  6244. materialIndex: materialIndex
  6245. });
  6246. }
  6247. clearGroups() {
  6248. this.groups = [];
  6249. }
  6250. setDrawRange(start, count) {
  6251. this.drawRange.start = start;
  6252. this.drawRange.count = count;
  6253. }
  6254. applyMatrix4(matrix) {
  6255. const position = this.attributes.position;
  6256. if (position !== undefined) {
  6257. position.applyMatrix4(matrix);
  6258. position.needsUpdate = true;
  6259. }
  6260. const normal = this.attributes.normal;
  6261. if (normal !== undefined) {
  6262. const normalMatrix = new Matrix3().getNormalMatrix(matrix);
  6263. normal.applyNormalMatrix(normalMatrix);
  6264. normal.needsUpdate = true;
  6265. }
  6266. const tangent = this.attributes.tangent;
  6267. if (tangent !== undefined) {
  6268. tangent.transformDirection(matrix);
  6269. tangent.needsUpdate = true;
  6270. }
  6271. if (this.boundingBox !== null) {
  6272. this.computeBoundingBox();
  6273. }
  6274. if (this.boundingSphere !== null) {
  6275. this.computeBoundingSphere();
  6276. }
  6277. return this;
  6278. }
  6279. applyQuaternion(q) {
  6280. _m1.makeRotationFromQuaternion(q);
  6281. this.applyMatrix4(_m1);
  6282. return this;
  6283. }
  6284. rotateX(angle) {
  6285. // rotate geometry around world x-axis
  6286. _m1.makeRotationX(angle);
  6287. this.applyMatrix4(_m1);
  6288. return this;
  6289. }
  6290. rotateY(angle) {
  6291. // rotate geometry around world y-axis
  6292. _m1.makeRotationY(angle);
  6293. this.applyMatrix4(_m1);
  6294. return this;
  6295. }
  6296. rotateZ(angle) {
  6297. // rotate geometry around world z-axis
  6298. _m1.makeRotationZ(angle);
  6299. this.applyMatrix4(_m1);
  6300. return this;
  6301. }
  6302. translate(x, y, z) {
  6303. // translate geometry
  6304. _m1.makeTranslation(x, y, z);
  6305. this.applyMatrix4(_m1);
  6306. return this;
  6307. }
  6308. scale(x, y, z) {
  6309. // scale geometry
  6310. _m1.makeScale(x, y, z);
  6311. this.applyMatrix4(_m1);
  6312. return this;
  6313. }
  6314. lookAt(vector) {
  6315. _obj.lookAt(vector);
  6316. _obj.updateMatrix();
  6317. this.applyMatrix4(_obj.matrix);
  6318. return this;
  6319. }
  6320. center() {
  6321. this.computeBoundingBox();
  6322. this.boundingBox.getCenter(_offset).negate();
  6323. this.translate(_offset.x, _offset.y, _offset.z);
  6324. return this;
  6325. }
  6326. setFromPoints(points) {
  6327. const position = [];
  6328. for (let i = 0, l = points.length; i < l; i++) {
  6329. const point = points[i];
  6330. position.push(point.x, point.y, point.z || 0);
  6331. }
  6332. this.setAttribute('position', new Float32BufferAttribute(position, 3));
  6333. return this;
  6334. }
  6335. computeBoundingBox() {
  6336. if (this.boundingBox === null) {
  6337. this.boundingBox = new Box3();
  6338. }
  6339. const position = this.attributes.position;
  6340. const morphAttributesPosition = this.morphAttributes.position;
  6341. if (position && position.isGLBufferAttribute) {
  6342. console.error('THREE.BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box. Alternatively set "mesh.frustumCulled" to "false".', this);
  6343. this.boundingBox.set(new Vector3(-Infinity, -Infinity, -Infinity), new Vector3(+Infinity, +Infinity, +Infinity));
  6344. return;
  6345. }
  6346. if (position !== undefined) {
  6347. this.boundingBox.setFromBufferAttribute(position); // process morph attributes if present
  6348. if (morphAttributesPosition) {
  6349. for (let i = 0, il = morphAttributesPosition.length; i < il; i++) {
  6350. const morphAttribute = morphAttributesPosition[i];
  6351. _box$1.setFromBufferAttribute(morphAttribute);
  6352. if (this.morphTargetsRelative) {
  6353. _vector$8.addVectors(this.boundingBox.min, _box$1.min);
  6354. this.boundingBox.expandByPoint(_vector$8);
  6355. _vector$8.addVectors(this.boundingBox.max, _box$1.max);
  6356. this.boundingBox.expandByPoint(_vector$8);
  6357. } else {
  6358. this.boundingBox.expandByPoint(_box$1.min);
  6359. this.boundingBox.expandByPoint(_box$1.max);
  6360. }
  6361. }
  6362. }
  6363. } else {
  6364. this.boundingBox.makeEmpty();
  6365. }
  6366. if (isNaN(this.boundingBox.min.x) || isNaN(this.boundingBox.min.y) || isNaN(this.boundingBox.min.z)) {
  6367. console.error('THREE.BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this);
  6368. }
  6369. }
  6370. computeBoundingSphere() {
  6371. if (this.boundingSphere === null) {
  6372. this.boundingSphere = new Sphere();
  6373. }
  6374. const position = this.attributes.position;
  6375. const morphAttributesPosition = this.morphAttributes.position;
  6376. if (position && position.isGLBufferAttribute) {
  6377. console.error('THREE.BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere. Alternatively set "mesh.frustumCulled" to "false".', this);
  6378. this.boundingSphere.set(new Vector3(), Infinity);
  6379. return;
  6380. }
  6381. if (position) {
  6382. // first, find the center of the bounding sphere
  6383. const center = this.boundingSphere.center;
  6384. _box$1.setFromBufferAttribute(position); // process morph attributes if present
  6385. if (morphAttributesPosition) {
  6386. for (let i = 0, il = morphAttributesPosition.length; i < il; i++) {
  6387. const morphAttribute = morphAttributesPosition[i];
  6388. _boxMorphTargets.setFromBufferAttribute(morphAttribute);
  6389. if (this.morphTargetsRelative) {
  6390. _vector$8.addVectors(_box$1.min, _boxMorphTargets.min);
  6391. _box$1.expandByPoint(_vector$8);
  6392. _vector$8.addVectors(_box$1.max, _boxMorphTargets.max);
  6393. _box$1.expandByPoint(_vector$8);
  6394. } else {
  6395. _box$1.expandByPoint(_boxMorphTargets.min);
  6396. _box$1.expandByPoint(_boxMorphTargets.max);
  6397. }
  6398. }
  6399. }
  6400. _box$1.getCenter(center); // second, try to find a boundingSphere with a radius smaller than the
  6401. // boundingSphere of the boundingBox: sqrt(3) smaller in the best case
  6402. let maxRadiusSq = 0;
  6403. for (let i = 0, il = position.count; i < il; i++) {
  6404. _vector$8.fromBufferAttribute(position, i);
  6405. maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(_vector$8));
  6406. } // process morph attributes if present
  6407. if (morphAttributesPosition) {
  6408. for (let i = 0, il = morphAttributesPosition.length; i < il; i++) {
  6409. const morphAttribute = morphAttributesPosition[i];
  6410. const morphTargetsRelative = this.morphTargetsRelative;
  6411. for (let j = 0, jl = morphAttribute.count; j < jl; j++) {
  6412. _vector$8.fromBufferAttribute(morphAttribute, j);
  6413. if (morphTargetsRelative) {
  6414. _offset.fromBufferAttribute(position, j);
  6415. _vector$8.add(_offset);
  6416. }
  6417. maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(_vector$8));
  6418. }
  6419. }
  6420. }
  6421. this.boundingSphere.radius = Math.sqrt(maxRadiusSq);
  6422. if (isNaN(this.boundingSphere.radius)) {
  6423. console.error('THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this);
  6424. }
  6425. }
  6426. }
  6427. computeTangents() {
  6428. const index = this.index;
  6429. const attributes = this.attributes; // based on http://www.terathon.com/code/tangent.html
  6430. // (per vertex tangents)
  6431. if (index === null || attributes.position === undefined || attributes.normal === undefined || attributes.uv === undefined) {
  6432. console.error('THREE.BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)');
  6433. return;
  6434. }
  6435. const indices = index.array;
  6436. const positions = attributes.position.array;
  6437. const normals = attributes.normal.array;
  6438. const uvs = attributes.uv.array;
  6439. const nVertices = positions.length / 3;
  6440. if (this.hasAttribute('tangent') === false) {
  6441. this.setAttribute('tangent', new BufferAttribute(new Float32Array(4 * nVertices), 4));
  6442. }
  6443. const tangents = this.getAttribute('tangent').array;
  6444. const tan1 = [],
  6445. tan2 = [];
  6446. for (let i = 0; i < nVertices; i++) {
  6447. tan1[i] = new Vector3();
  6448. tan2[i] = new Vector3();
  6449. }
  6450. const vA = new Vector3(),
  6451. vB = new Vector3(),
  6452. vC = new Vector3(),
  6453. uvA = new Vector2(),
  6454. uvB = new Vector2(),
  6455. uvC = new Vector2(),
  6456. sdir = new Vector3(),
  6457. tdir = new Vector3();
  6458. function handleTriangle(a, b, c) {
  6459. vA.fromArray(positions, a * 3);
  6460. vB.fromArray(positions, b * 3);
  6461. vC.fromArray(positions, c * 3);
  6462. uvA.fromArray(uvs, a * 2);
  6463. uvB.fromArray(uvs, b * 2);
  6464. uvC.fromArray(uvs, c * 2);
  6465. vB.sub(vA);
  6466. vC.sub(vA);
  6467. uvB.sub(uvA);
  6468. uvC.sub(uvA);
  6469. const r = 1.0 / (uvB.x * uvC.y - uvC.x * uvB.y); // silently ignore degenerate uv triangles having coincident or colinear vertices
  6470. if (!isFinite(r)) return;
  6471. sdir.copy(vB).multiplyScalar(uvC.y).addScaledVector(vC, -uvB.y).multiplyScalar(r);
  6472. tdir.copy(vC).multiplyScalar(uvB.x).addScaledVector(vB, -uvC.x).multiplyScalar(r);
  6473. tan1[a].add(sdir);
  6474. tan1[b].add(sdir);
  6475. tan1[c].add(sdir);
  6476. tan2[a].add(tdir);
  6477. tan2[b].add(tdir);
  6478. tan2[c].add(tdir);
  6479. }
  6480. let groups = this.groups;
  6481. if (groups.length === 0) {
  6482. groups = [{
  6483. start: 0,
  6484. count: indices.length
  6485. }];
  6486. }
  6487. for (let i = 0, il = groups.length; i < il; ++i) {
  6488. const group = groups[i];
  6489. const start = group.start;
  6490. const count = group.count;
  6491. for (let j = start, jl = start + count; j < jl; j += 3) {
  6492. handleTriangle(indices[j + 0], indices[j + 1], indices[j + 2]);
  6493. }
  6494. }
  6495. const tmp = new Vector3(),
  6496. tmp2 = new Vector3();
  6497. const n = new Vector3(),
  6498. n2 = new Vector3();
  6499. function handleVertex(v) {
  6500. n.fromArray(normals, v * 3);
  6501. n2.copy(n);
  6502. const t = tan1[v]; // Gram-Schmidt orthogonalize
  6503. tmp.copy(t);
  6504. tmp.sub(n.multiplyScalar(n.dot(t))).normalize(); // Calculate handedness
  6505. tmp2.crossVectors(n2, t);
  6506. const test = tmp2.dot(tan2[v]);
  6507. const w = test < 0.0 ? -1.0 : 1.0;
  6508. tangents[v * 4] = tmp.x;
  6509. tangents[v * 4 + 1] = tmp.y;
  6510. tangents[v * 4 + 2] = tmp.z;
  6511. tangents[v * 4 + 3] = w;
  6512. }
  6513. for (let i = 0, il = groups.length; i < il; ++i) {
  6514. const group = groups[i];
  6515. const start = group.start;
  6516. const count = group.count;
  6517. for (let j = start, jl = start + count; j < jl; j += 3) {
  6518. handleVertex(indices[j + 0]);
  6519. handleVertex(indices[j + 1]);
  6520. handleVertex(indices[j + 2]);
  6521. }
  6522. }
  6523. }
  6524. computeVertexNormals() {
  6525. const index = this.index;
  6526. const positionAttribute = this.getAttribute('position');
  6527. if (positionAttribute !== undefined) {
  6528. let normalAttribute = this.getAttribute('normal');
  6529. if (normalAttribute === undefined) {
  6530. normalAttribute = new BufferAttribute(new Float32Array(positionAttribute.count * 3), 3);
  6531. this.setAttribute('normal', normalAttribute);
  6532. } else {
  6533. // reset existing normals to zero
  6534. for (let i = 0, il = normalAttribute.count; i < il; i++) {
  6535. normalAttribute.setXYZ(i, 0, 0, 0);
  6536. }
  6537. }
  6538. const pA = new Vector3(),
  6539. pB = new Vector3(),
  6540. pC = new Vector3();
  6541. const nA = new Vector3(),
  6542. nB = new Vector3(),
  6543. nC = new Vector3();
  6544. const cb = new Vector3(),
  6545. ab = new Vector3(); // indexed elements
  6546. if (index) {
  6547. for (let i = 0, il = index.count; i < il; i += 3) {
  6548. const vA = index.getX(i + 0);
  6549. const vB = index.getX(i + 1);
  6550. const vC = index.getX(i + 2);
  6551. pA.fromBufferAttribute(positionAttribute, vA);
  6552. pB.fromBufferAttribute(positionAttribute, vB);
  6553. pC.fromBufferAttribute(positionAttribute, vC);
  6554. cb.subVectors(pC, pB);
  6555. ab.subVectors(pA, pB);
  6556. cb.cross(ab);
  6557. nA.fromBufferAttribute(normalAttribute, vA);
  6558. nB.fromBufferAttribute(normalAttribute, vB);
  6559. nC.fromBufferAttribute(normalAttribute, vC);
  6560. nA.add(cb);
  6561. nB.add(cb);
  6562. nC.add(cb);
  6563. normalAttribute.setXYZ(vA, nA.x, nA.y, nA.z);
  6564. normalAttribute.setXYZ(vB, nB.x, nB.y, nB.z);
  6565. normalAttribute.setXYZ(vC, nC.x, nC.y, nC.z);
  6566. }
  6567. } else {
  6568. // non-indexed elements (unconnected triangle soup)
  6569. for (let i = 0, il = positionAttribute.count; i < il; i += 3) {
  6570. pA.fromBufferAttribute(positionAttribute, i + 0);
  6571. pB.fromBufferAttribute(positionAttribute, i + 1);
  6572. pC.fromBufferAttribute(positionAttribute, i + 2);
  6573. cb.subVectors(pC, pB);
  6574. ab.subVectors(pA, pB);
  6575. cb.cross(ab);
  6576. normalAttribute.setXYZ(i + 0, cb.x, cb.y, cb.z);
  6577. normalAttribute.setXYZ(i + 1, cb.x, cb.y, cb.z);
  6578. normalAttribute.setXYZ(i + 2, cb.x, cb.y, cb.z);
  6579. }
  6580. }
  6581. this.normalizeNormals();
  6582. normalAttribute.needsUpdate = true;
  6583. }
  6584. }
  6585. merge(geometry, offset) {
  6586. if (!(geometry && geometry.isBufferGeometry)) {
  6587. console.error('THREE.BufferGeometry.merge(): geometry not an instance of THREE.BufferGeometry.', geometry);
  6588. return;
  6589. }
  6590. if (offset === undefined) {
  6591. offset = 0;
  6592. console.warn('THREE.BufferGeometry.merge(): Overwriting original geometry, starting at offset=0. ' + 'Use BufferGeometryUtils.mergeBufferGeometries() for lossless merge.');
  6593. }
  6594. const attributes = this.attributes;
  6595. for (const key in attributes) {
  6596. if (geometry.attributes[key] === undefined) continue;
  6597. const attribute1 = attributes[key];
  6598. const attributeArray1 = attribute1.array;
  6599. const attribute2 = geometry.attributes[key];
  6600. const attributeArray2 = attribute2.array;
  6601. const attributeOffset = attribute2.itemSize * offset;
  6602. const length = Math.min(attributeArray2.length, attributeArray1.length - attributeOffset);
  6603. for (let i = 0, j = attributeOffset; i < length; i++, j++) {
  6604. attributeArray1[j] = attributeArray2[i];
  6605. }
  6606. }
  6607. return this;
  6608. }
  6609. normalizeNormals() {
  6610. const normals = this.attributes.normal;
  6611. for (let i = 0, il = normals.count; i < il; i++) {
  6612. _vector$8.fromBufferAttribute(normals, i);
  6613. _vector$8.normalize();
  6614. normals.setXYZ(i, _vector$8.x, _vector$8.y, _vector$8.z);
  6615. }
  6616. }
  6617. toNonIndexed() {
  6618. function convertBufferAttribute(attribute, indices) {
  6619. const array = attribute.array;
  6620. const itemSize = attribute.itemSize;
  6621. const normalized = attribute.normalized;
  6622. const array2 = new array.constructor(indices.length * itemSize);
  6623. let index = 0,
  6624. index2 = 0;
  6625. for (let i = 0, l = indices.length; i < l; i++) {
  6626. if (attribute.isInterleavedBufferAttribute) {
  6627. index = indices[i] * attribute.data.stride + attribute.offset;
  6628. } else {
  6629. index = indices[i] * itemSize;
  6630. }
  6631. for (let j = 0; j < itemSize; j++) {
  6632. array2[index2++] = array[index++];
  6633. }
  6634. }
  6635. return new BufferAttribute(array2, itemSize, normalized);
  6636. } //
  6637. if (this.index === null) {
  6638. console.warn('THREE.BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed.');
  6639. return this;
  6640. }
  6641. const geometry2 = new BufferGeometry();
  6642. const indices = this.index.array;
  6643. const attributes = this.attributes; // attributes
  6644. for (const name in attributes) {
  6645. const attribute = attributes[name];
  6646. const newAttribute = convertBufferAttribute(attribute, indices);
  6647. geometry2.setAttribute(name, newAttribute);
  6648. } // morph attributes
  6649. const morphAttributes = this.morphAttributes;
  6650. for (const name in morphAttributes) {
  6651. const morphArray = [];
  6652. const morphAttribute = morphAttributes[name]; // morphAttribute: array of Float32BufferAttributes
  6653. for (let i = 0, il = morphAttribute.length; i < il; i++) {
  6654. const attribute = morphAttribute[i];
  6655. const newAttribute = convertBufferAttribute(attribute, indices);
  6656. morphArray.push(newAttribute);
  6657. }
  6658. geometry2.morphAttributes[name] = morphArray;
  6659. }
  6660. geometry2.morphTargetsRelative = this.morphTargetsRelative; // groups
  6661. const groups = this.groups;
  6662. for (let i = 0, l = groups.length; i < l; i++) {
  6663. const group = groups[i];
  6664. geometry2.addGroup(group.start, group.count, group.materialIndex);
  6665. }
  6666. return geometry2;
  6667. }
  6668. toJSON() {
  6669. const data = {
  6670. metadata: {
  6671. version: 4.5,
  6672. type: 'BufferGeometry',
  6673. generator: 'BufferGeometry.toJSON'
  6674. }
  6675. }; // standard BufferGeometry serialization
  6676. data.uuid = this.uuid;
  6677. data.type = this.type;
  6678. if (this.name !== '') data.name = this.name;
  6679. if (Object.keys(this.userData).length > 0) data.userData = this.userData;
  6680. if (this.parameters !== undefined) {
  6681. const parameters = this.parameters;
  6682. for (const key in parameters) {
  6683. if (parameters[key] !== undefined) data[key] = parameters[key];
  6684. }
  6685. return data;
  6686. } // for simplicity the code assumes attributes are not shared across geometries, see #15811
  6687. data.data = {
  6688. attributes: {}
  6689. };
  6690. const index = this.index;
  6691. if (index !== null) {
  6692. data.data.index = {
  6693. type: index.array.constructor.name,
  6694. array: Array.prototype.slice.call(index.array)
  6695. };
  6696. }
  6697. const attributes = this.attributes;
  6698. for (const key in attributes) {
  6699. const attribute = attributes[key];
  6700. data.data.attributes[key] = attribute.toJSON(data.data);
  6701. }
  6702. const morphAttributes = {};
  6703. let hasMorphAttributes = false;
  6704. for (const key in this.morphAttributes) {
  6705. const attributeArray = this.morphAttributes[key];
  6706. const array = [];
  6707. for (let i = 0, il = attributeArray.length; i < il; i++) {
  6708. const attribute = attributeArray[i];
  6709. array.push(attribute.toJSON(data.data));
  6710. }
  6711. if (array.length > 0) {
  6712. morphAttributes[key] = array;
  6713. hasMorphAttributes = true;
  6714. }
  6715. }
  6716. if (hasMorphAttributes) {
  6717. data.data.morphAttributes = morphAttributes;
  6718. data.data.morphTargetsRelative = this.morphTargetsRelative;
  6719. }
  6720. const groups = this.groups;
  6721. if (groups.length > 0) {
  6722. data.data.groups = JSON.parse(JSON.stringify(groups));
  6723. }
  6724. const boundingSphere = this.boundingSphere;
  6725. if (boundingSphere !== null) {
  6726. data.data.boundingSphere = {
  6727. center: boundingSphere.center.toArray(),
  6728. radius: boundingSphere.radius
  6729. };
  6730. }
  6731. return data;
  6732. }
  6733. clone() {
  6734. return new this.constructor().copy(this);
  6735. }
  6736. copy(source) {
  6737. // reset
  6738. this.index = null;
  6739. this.attributes = {};
  6740. this.morphAttributes = {};
  6741. this.groups = [];
  6742. this.boundingBox = null;
  6743. this.boundingSphere = null; // used for storing cloned, shared data
  6744. const data = {}; // name
  6745. this.name = source.name; // index
  6746. const index = source.index;
  6747. if (index !== null) {
  6748. this.setIndex(index.clone(data));
  6749. } // attributes
  6750. const attributes = source.attributes;
  6751. for (const name in attributes) {
  6752. const attribute = attributes[name];
  6753. this.setAttribute(name, attribute.clone(data));
  6754. } // morph attributes
  6755. const morphAttributes = source.morphAttributes;
  6756. for (const name in morphAttributes) {
  6757. const array = [];
  6758. const morphAttribute = morphAttributes[name]; // morphAttribute: array of Float32BufferAttributes
  6759. for (let i = 0, l = morphAttribute.length; i < l; i++) {
  6760. array.push(morphAttribute[i].clone(data));
  6761. }
  6762. this.morphAttributes[name] = array;
  6763. }
  6764. this.morphTargetsRelative = source.morphTargetsRelative; // groups
  6765. const groups = source.groups;
  6766. for (let i = 0, l = groups.length; i < l; i++) {
  6767. const group = groups[i];
  6768. this.addGroup(group.start, group.count, group.materialIndex);
  6769. } // bounding box
  6770. const boundingBox = source.boundingBox;
  6771. if (boundingBox !== null) {
  6772. this.boundingBox = boundingBox.clone();
  6773. } // bounding sphere
  6774. const boundingSphere = source.boundingSphere;
  6775. if (boundingSphere !== null) {
  6776. this.boundingSphere = boundingSphere.clone();
  6777. } // draw range
  6778. this.drawRange.start = source.drawRange.start;
  6779. this.drawRange.count = source.drawRange.count; // user data
  6780. this.userData = source.userData; // geometry generator parameters
  6781. if (source.parameters !== undefined) this.parameters = Object.assign({}, source.parameters);
  6782. return this;
  6783. }
  6784. dispose() {
  6785. this.dispatchEvent({
  6786. type: 'dispose'
  6787. });
  6788. }
  6789. }
  6790. const _inverseMatrix$2 = /*@__PURE__*/new Matrix4();
  6791. const _ray$2 = /*@__PURE__*/new Ray();
  6792. const _sphere$3 = /*@__PURE__*/new Sphere();
  6793. const _vA$1 = /*@__PURE__*/new Vector3();
  6794. const _vB$1 = /*@__PURE__*/new Vector3();
  6795. const _vC$1 = /*@__PURE__*/new Vector3();
  6796. const _tempA = /*@__PURE__*/new Vector3();
  6797. const _tempB = /*@__PURE__*/new Vector3();
  6798. const _tempC = /*@__PURE__*/new Vector3();
  6799. const _morphA = /*@__PURE__*/new Vector3();
  6800. const _morphB = /*@__PURE__*/new Vector3();
  6801. const _morphC = /*@__PURE__*/new Vector3();
  6802. const _uvA$1 = /*@__PURE__*/new Vector2();
  6803. const _uvB$1 = /*@__PURE__*/new Vector2();
  6804. const _uvC$1 = /*@__PURE__*/new Vector2();
  6805. const _intersectionPoint = /*@__PURE__*/new Vector3();
  6806. const _intersectionPointWorld = /*@__PURE__*/new Vector3();
  6807. class Mesh extends Object3D {
  6808. constructor(geometry = new BufferGeometry(), material = new MeshBasicMaterial()) {
  6809. super();
  6810. this.isMesh = true;
  6811. this.type = 'Mesh';
  6812. this.geometry = geometry;
  6813. this.material = material;
  6814. this.updateMorphTargets();
  6815. }
  6816. copy(source) {
  6817. super.copy(source);
  6818. if (source.morphTargetInfluences !== undefined) {
  6819. this.morphTargetInfluences = source.morphTargetInfluences.slice();
  6820. }
  6821. if (source.morphTargetDictionary !== undefined) {
  6822. this.morphTargetDictionary = Object.assign({}, source.morphTargetDictionary);
  6823. }
  6824. this.material = source.material;
  6825. this.geometry = source.geometry;
  6826. return this;
  6827. }
  6828. updateMorphTargets() {
  6829. const geometry = this.geometry;
  6830. if (geometry.isBufferGeometry) {
  6831. const morphAttributes = geometry.morphAttributes;
  6832. const keys = Object.keys(morphAttributes);
  6833. if (keys.length > 0) {
  6834. const morphAttribute = morphAttributes[keys[0]];
  6835. if (morphAttribute !== undefined) {
  6836. this.morphTargetInfluences = [];
  6837. this.morphTargetDictionary = {};
  6838. for (let m = 0, ml = morphAttribute.length; m < ml; m++) {
  6839. const name = morphAttribute[m].name || String(m);
  6840. this.morphTargetInfluences.push(0);
  6841. this.morphTargetDictionary[name] = m;
  6842. }
  6843. }
  6844. }
  6845. } else {
  6846. const morphTargets = geometry.morphTargets;
  6847. if (morphTargets !== undefined && morphTargets.length > 0) {
  6848. console.error('THREE.Mesh.updateMorphTargets() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');
  6849. }
  6850. }
  6851. }
  6852. raycast(raycaster, intersects) {
  6853. const geometry = this.geometry;
  6854. const material = this.material;
  6855. const matrixWorld = this.matrixWorld;
  6856. if (material === undefined) return; // Checking boundingSphere distance to ray
  6857. if (geometry.boundingSphere === null) geometry.computeBoundingSphere();
  6858. _sphere$3.copy(geometry.boundingSphere);
  6859. _sphere$3.applyMatrix4(matrixWorld);
  6860. if (raycaster.ray.intersectsSphere(_sphere$3) === false) return; //
  6861. _inverseMatrix$2.copy(matrixWorld).invert();
  6862. _ray$2.copy(raycaster.ray).applyMatrix4(_inverseMatrix$2); // Check boundingBox before continuing
  6863. if (geometry.boundingBox !== null) {
  6864. if (_ray$2.intersectsBox(geometry.boundingBox) === false) return;
  6865. }
  6866. let intersection;
  6867. if (geometry.isBufferGeometry) {
  6868. const index = geometry.index;
  6869. const position = geometry.attributes.position;
  6870. const morphPosition = geometry.morphAttributes.position;
  6871. const morphTargetsRelative = geometry.morphTargetsRelative;
  6872. const uv = geometry.attributes.uv;
  6873. const uv2 = geometry.attributes.uv2;
  6874. const groups = geometry.groups;
  6875. const drawRange = geometry.drawRange;
  6876. if (index !== null) {
  6877. // indexed buffer geometry
  6878. if (Array.isArray(material)) {
  6879. for (let i = 0, il = groups.length; i < il; i++) {
  6880. const group = groups[i];
  6881. const groupMaterial = material[group.materialIndex];
  6882. const start = Math.max(group.start, drawRange.start);
  6883. const end = Math.min(index.count, Math.min(group.start + group.count, drawRange.start + drawRange.count));
  6884. for (let j = start, jl = end; j < jl; j += 3) {
  6885. const a = index.getX(j);
  6886. const b = index.getX(j + 1);
  6887. const c = index.getX(j + 2);
  6888. intersection = checkBufferGeometryIntersection(this, groupMaterial, raycaster, _ray$2, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c);
  6889. if (intersection) {
  6890. intersection.faceIndex = Math.floor(j / 3); // triangle number in indexed buffer semantics
  6891. intersection.face.materialIndex = group.materialIndex;
  6892. intersects.push(intersection);
  6893. }
  6894. }
  6895. }
  6896. } else {
  6897. const start = Math.max(0, drawRange.start);
  6898. const end = Math.min(index.count, drawRange.start + drawRange.count);
  6899. for (let i = start, il = end; i < il; i += 3) {
  6900. const a = index.getX(i);
  6901. const b = index.getX(i + 1);
  6902. const c = index.getX(i + 2);
  6903. intersection = checkBufferGeometryIntersection(this, material, raycaster, _ray$2, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c);
  6904. if (intersection) {
  6905. intersection.faceIndex = Math.floor(i / 3); // triangle number in indexed buffer semantics
  6906. intersects.push(intersection);
  6907. }
  6908. }
  6909. }
  6910. } else if (position !== undefined) {
  6911. // non-indexed buffer geometry
  6912. if (Array.isArray(material)) {
  6913. for (let i = 0, il = groups.length; i < il; i++) {
  6914. const group = groups[i];
  6915. const groupMaterial = material[group.materialIndex];
  6916. const start = Math.max(group.start, drawRange.start);
  6917. const end = Math.min(position.count, Math.min(group.start + group.count, drawRange.start + drawRange.count));
  6918. for (let j = start, jl = end; j < jl; j += 3) {
  6919. const a = j;
  6920. const b = j + 1;
  6921. const c = j + 2;
  6922. intersection = checkBufferGeometryIntersection(this, groupMaterial, raycaster, _ray$2, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c);
  6923. if (intersection) {
  6924. intersection.faceIndex = Math.floor(j / 3); // triangle number in non-indexed buffer semantics
  6925. intersection.face.materialIndex = group.materialIndex;
  6926. intersects.push(intersection);
  6927. }
  6928. }
  6929. }
  6930. } else {
  6931. const start = Math.max(0, drawRange.start);
  6932. const end = Math.min(position.count, drawRange.start + drawRange.count);
  6933. for (let i = start, il = end; i < il; i += 3) {
  6934. const a = i;
  6935. const b = i + 1;
  6936. const c = i + 2;
  6937. intersection = checkBufferGeometryIntersection(this, material, raycaster, _ray$2, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c);
  6938. if (intersection) {
  6939. intersection.faceIndex = Math.floor(i / 3); // triangle number in non-indexed buffer semantics
  6940. intersects.push(intersection);
  6941. }
  6942. }
  6943. }
  6944. }
  6945. } else if (geometry.isGeometry) {
  6946. console.error('THREE.Mesh.raycast() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');
  6947. }
  6948. }
  6949. }
  6950. function checkIntersection(object, material, raycaster, ray, pA, pB, pC, point) {
  6951. let intersect;
  6952. if (material.side === BackSide) {
  6953. intersect = ray.intersectTriangle(pC, pB, pA, true, point);
  6954. } else {
  6955. intersect = ray.intersectTriangle(pA, pB, pC, material.side !== DoubleSide, point);
  6956. }
  6957. if (intersect === null) return null;
  6958. _intersectionPointWorld.copy(point);
  6959. _intersectionPointWorld.applyMatrix4(object.matrixWorld);
  6960. const distance = raycaster.ray.origin.distanceTo(_intersectionPointWorld);
  6961. if (distance < raycaster.near || distance > raycaster.far) return null;
  6962. return {
  6963. distance: distance,
  6964. point: _intersectionPointWorld.clone(),
  6965. object: object
  6966. };
  6967. }
  6968. function checkBufferGeometryIntersection(object, material, raycaster, ray, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c) {
  6969. _vA$1.fromBufferAttribute(position, a);
  6970. _vB$1.fromBufferAttribute(position, b);
  6971. _vC$1.fromBufferAttribute(position, c);
  6972. const morphInfluences = object.morphTargetInfluences;
  6973. if (morphPosition && morphInfluences) {
  6974. _morphA.set(0, 0, 0);
  6975. _morphB.set(0, 0, 0);
  6976. _morphC.set(0, 0, 0);
  6977. for (let i = 0, il = morphPosition.length; i < il; i++) {
  6978. const influence = morphInfluences[i];
  6979. const morphAttribute = morphPosition[i];
  6980. if (influence === 0) continue;
  6981. _tempA.fromBufferAttribute(morphAttribute, a);
  6982. _tempB.fromBufferAttribute(morphAttribute, b);
  6983. _tempC.fromBufferAttribute(morphAttribute, c);
  6984. if (morphTargetsRelative) {
  6985. _morphA.addScaledVector(_tempA, influence);
  6986. _morphB.addScaledVector(_tempB, influence);
  6987. _morphC.addScaledVector(_tempC, influence);
  6988. } else {
  6989. _morphA.addScaledVector(_tempA.sub(_vA$1), influence);
  6990. _morphB.addScaledVector(_tempB.sub(_vB$1), influence);
  6991. _morphC.addScaledVector(_tempC.sub(_vC$1), influence);
  6992. }
  6993. }
  6994. _vA$1.add(_morphA);
  6995. _vB$1.add(_morphB);
  6996. _vC$1.add(_morphC);
  6997. }
  6998. if (object.isSkinnedMesh) {
  6999. object.boneTransform(a, _vA$1);
  7000. object.boneTransform(b, _vB$1);
  7001. object.boneTransform(c, _vC$1);
  7002. }
  7003. const intersection = checkIntersection(object, material, raycaster, ray, _vA$1, _vB$1, _vC$1, _intersectionPoint);
  7004. if (intersection) {
  7005. if (uv) {
  7006. _uvA$1.fromBufferAttribute(uv, a);
  7007. _uvB$1.fromBufferAttribute(uv, b);
  7008. _uvC$1.fromBufferAttribute(uv, c);
  7009. intersection.uv = Triangle.getUV(_intersectionPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2());
  7010. }
  7011. if (uv2) {
  7012. _uvA$1.fromBufferAttribute(uv2, a);
  7013. _uvB$1.fromBufferAttribute(uv2, b);
  7014. _uvC$1.fromBufferAttribute(uv2, c);
  7015. intersection.uv2 = Triangle.getUV(_intersectionPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2());
  7016. }
  7017. const face = {
  7018. a: a,
  7019. b: b,
  7020. c: c,
  7021. normal: new Vector3(),
  7022. materialIndex: 0
  7023. };
  7024. Triangle.getNormal(_vA$1, _vB$1, _vC$1, face.normal);
  7025. intersection.face = face;
  7026. }
  7027. return intersection;
  7028. }
  7029. class BoxGeometry extends BufferGeometry {
  7030. constructor(width = 1, height = 1, depth = 1, widthSegments = 1, heightSegments = 1, depthSegments = 1) {
  7031. super();
  7032. this.type = 'BoxGeometry';
  7033. this.parameters = {
  7034. width: width,
  7035. height: height,
  7036. depth: depth,
  7037. widthSegments: widthSegments,
  7038. heightSegments: heightSegments,
  7039. depthSegments: depthSegments
  7040. };
  7041. const scope = this; // segments
  7042. widthSegments = Math.floor(widthSegments);
  7043. heightSegments = Math.floor(heightSegments);
  7044. depthSegments = Math.floor(depthSegments); // buffers
  7045. const indices = [];
  7046. const vertices = [];
  7047. const normals = [];
  7048. const uvs = []; // helper variables
  7049. let numberOfVertices = 0;
  7050. let groupStart = 0; // build each side of the box geometry
  7051. buildPlane('z', 'y', 'x', -1, -1, depth, height, width, depthSegments, heightSegments, 0); // px
  7052. buildPlane('z', 'y', 'x', 1, -1, depth, height, -width, depthSegments, heightSegments, 1); // nx
  7053. buildPlane('x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2); // py
  7054. buildPlane('x', 'z', 'y', 1, -1, width, depth, -height, widthSegments, depthSegments, 3); // ny
  7055. buildPlane('x', 'y', 'z', 1, -1, width, height, depth, widthSegments, heightSegments, 4); // pz
  7056. buildPlane('x', 'y', 'z', -1, -1, width, height, -depth, widthSegments, heightSegments, 5); // nz
  7057. // build geometry
  7058. this.setIndex(indices);
  7059. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  7060. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  7061. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  7062. function buildPlane(u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex) {
  7063. const segmentWidth = width / gridX;
  7064. const segmentHeight = height / gridY;
  7065. const widthHalf = width / 2;
  7066. const heightHalf = height / 2;
  7067. const depthHalf = depth / 2;
  7068. const gridX1 = gridX + 1;
  7069. const gridY1 = gridY + 1;
  7070. let vertexCounter = 0;
  7071. let groupCount = 0;
  7072. const vector = new Vector3(); // generate vertices, normals and uvs
  7073. for (let iy = 0; iy < gridY1; iy++) {
  7074. const y = iy * segmentHeight - heightHalf;
  7075. for (let ix = 0; ix < gridX1; ix++) {
  7076. const x = ix * segmentWidth - widthHalf; // set values to correct vector component
  7077. vector[u] = x * udir;
  7078. vector[v] = y * vdir;
  7079. vector[w] = depthHalf; // now apply vector to vertex buffer
  7080. vertices.push(vector.x, vector.y, vector.z); // set values to correct vector component
  7081. vector[u] = 0;
  7082. vector[v] = 0;
  7083. vector[w] = depth > 0 ? 1 : -1; // now apply vector to normal buffer
  7084. normals.push(vector.x, vector.y, vector.z); // uvs
  7085. uvs.push(ix / gridX);
  7086. uvs.push(1 - iy / gridY); // counters
  7087. vertexCounter += 1;
  7088. }
  7089. } // indices
  7090. // 1. you need three indices to draw a single face
  7091. // 2. a single segment consists of two faces
  7092. // 3. so we need to generate six (2*3) indices per segment
  7093. for (let iy = 0; iy < gridY; iy++) {
  7094. for (let ix = 0; ix < gridX; ix++) {
  7095. const a = numberOfVertices + ix + gridX1 * iy;
  7096. const b = numberOfVertices + ix + gridX1 * (iy + 1);
  7097. const c = numberOfVertices + (ix + 1) + gridX1 * (iy + 1);
  7098. const d = numberOfVertices + (ix + 1) + gridX1 * iy; // faces
  7099. indices.push(a, b, d);
  7100. indices.push(b, c, d); // increase counter
  7101. groupCount += 6;
  7102. }
  7103. } // add a group to the geometry. this will ensure multi material support
  7104. scope.addGroup(groupStart, groupCount, materialIndex); // calculate new start value for groups
  7105. groupStart += groupCount; // update total number of vertices
  7106. numberOfVertices += vertexCounter;
  7107. }
  7108. }
  7109. static fromJSON(data) {
  7110. return new BoxGeometry(data.width, data.height, data.depth, data.widthSegments, data.heightSegments, data.depthSegments);
  7111. }
  7112. }
  7113. /**
  7114. * Uniform Utilities
  7115. */
  7116. function cloneUniforms(src) {
  7117. const dst = {};
  7118. for (const u in src) {
  7119. dst[u] = {};
  7120. for (const p in src[u]) {
  7121. const property = src[u][p];
  7122. if (property && (property.isColor || property.isMatrix3 || property.isMatrix4 || property.isVector2 || property.isVector3 || property.isVector4 || property.isTexture || property.isQuaternion)) {
  7123. dst[u][p] = property.clone();
  7124. } else if (Array.isArray(property)) {
  7125. dst[u][p] = property.slice();
  7126. } else {
  7127. dst[u][p] = property;
  7128. }
  7129. }
  7130. }
  7131. return dst;
  7132. }
  7133. function mergeUniforms(uniforms) {
  7134. const merged = {};
  7135. for (let u = 0; u < uniforms.length; u++) {
  7136. const tmp = cloneUniforms(uniforms[u]);
  7137. for (const p in tmp) {
  7138. merged[p] = tmp[p];
  7139. }
  7140. }
  7141. return merged;
  7142. } // Legacy
  7143. const UniformsUtils = {
  7144. clone: cloneUniforms,
  7145. merge: mergeUniforms
  7146. };
  7147. var default_vertex = "void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}";
  7148. var default_fragment = "void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}";
  7149. class ShaderMaterial extends Material {
  7150. constructor(parameters) {
  7151. super();
  7152. this.isShaderMaterial = true;
  7153. this.type = 'ShaderMaterial';
  7154. this.defines = {};
  7155. this.uniforms = {};
  7156. this.vertexShader = default_vertex;
  7157. this.fragmentShader = default_fragment;
  7158. this.linewidth = 1;
  7159. this.wireframe = false;
  7160. this.wireframeLinewidth = 1;
  7161. this.fog = false; // set to use scene fog
  7162. this.lights = false; // set to use scene lights
  7163. this.clipping = false; // set to use user-defined clipping planes
  7164. this.extensions = {
  7165. derivatives: false,
  7166. // set to use derivatives
  7167. fragDepth: false,
  7168. // set to use fragment depth values
  7169. drawBuffers: false,
  7170. // set to use draw buffers
  7171. shaderTextureLOD: false // set to use shader texture LOD
  7172. }; // When rendered geometry doesn't include these attributes but the material does,
  7173. // use these default values in WebGL. This avoids errors when buffer data is missing.
  7174. this.defaultAttributeValues = {
  7175. 'color': [1, 1, 1],
  7176. 'uv': [0, 0],
  7177. 'uv2': [0, 0]
  7178. };
  7179. this.index0AttributeName = undefined;
  7180. this.uniformsNeedUpdate = false;
  7181. this.glslVersion = null;
  7182. if (parameters !== undefined) {
  7183. if (parameters.attributes !== undefined) {
  7184. console.error('THREE.ShaderMaterial: attributes should now be defined in THREE.BufferGeometry instead.');
  7185. }
  7186. this.setValues(parameters);
  7187. }
  7188. }
  7189. copy(source) {
  7190. super.copy(source);
  7191. this.fragmentShader = source.fragmentShader;
  7192. this.vertexShader = source.vertexShader;
  7193. this.uniforms = cloneUniforms(source.uniforms);
  7194. this.defines = Object.assign({}, source.defines);
  7195. this.wireframe = source.wireframe;
  7196. this.wireframeLinewidth = source.wireframeLinewidth;
  7197. this.fog = source.fog;
  7198. this.lights = source.lights;
  7199. this.clipping = source.clipping;
  7200. this.extensions = Object.assign({}, source.extensions);
  7201. this.glslVersion = source.glslVersion;
  7202. return this;
  7203. }
  7204. toJSON(meta) {
  7205. const data = super.toJSON(meta);
  7206. data.glslVersion = this.glslVersion;
  7207. data.uniforms = {};
  7208. for (const name in this.uniforms) {
  7209. const uniform = this.uniforms[name];
  7210. const value = uniform.value;
  7211. if (value && value.isTexture) {
  7212. data.uniforms[name] = {
  7213. type: 't',
  7214. value: value.toJSON(meta).uuid
  7215. };
  7216. } else if (value && value.isColor) {
  7217. data.uniforms[name] = {
  7218. type: 'c',
  7219. value: value.getHex()
  7220. };
  7221. } else if (value && value.isVector2) {
  7222. data.uniforms[name] = {
  7223. type: 'v2',
  7224. value: value.toArray()
  7225. };
  7226. } else if (value && value.isVector3) {
  7227. data.uniforms[name] = {
  7228. type: 'v3',
  7229. value: value.toArray()
  7230. };
  7231. } else if (value && value.isVector4) {
  7232. data.uniforms[name] = {
  7233. type: 'v4',
  7234. value: value.toArray()
  7235. };
  7236. } else if (value && value.isMatrix3) {
  7237. data.uniforms[name] = {
  7238. type: 'm3',
  7239. value: value.toArray()
  7240. };
  7241. } else if (value && value.isMatrix4) {
  7242. data.uniforms[name] = {
  7243. type: 'm4',
  7244. value: value.toArray()
  7245. };
  7246. } else {
  7247. data.uniforms[name] = {
  7248. value: value
  7249. }; // note: the array variants v2v, v3v, v4v, m4v and tv are not supported so far
  7250. }
  7251. }
  7252. if (Object.keys(this.defines).length > 0) data.defines = this.defines;
  7253. data.vertexShader = this.vertexShader;
  7254. data.fragmentShader = this.fragmentShader;
  7255. const extensions = {};
  7256. for (const key in this.extensions) {
  7257. if (this.extensions[key] === true) extensions[key] = true;
  7258. }
  7259. if (Object.keys(extensions).length > 0) data.extensions = extensions;
  7260. return data;
  7261. }
  7262. }
  7263. class Camera extends Object3D {
  7264. constructor() {
  7265. super();
  7266. this.isCamera = true;
  7267. this.type = 'Camera';
  7268. this.matrixWorldInverse = new Matrix4();
  7269. this.projectionMatrix = new Matrix4();
  7270. this.projectionMatrixInverse = new Matrix4();
  7271. }
  7272. copy(source, recursive) {
  7273. super.copy(source, recursive);
  7274. this.matrixWorldInverse.copy(source.matrixWorldInverse);
  7275. this.projectionMatrix.copy(source.projectionMatrix);
  7276. this.projectionMatrixInverse.copy(source.projectionMatrixInverse);
  7277. return this;
  7278. }
  7279. getWorldDirection(target) {
  7280. this.updateWorldMatrix(true, false);
  7281. const e = this.matrixWorld.elements;
  7282. return target.set(-e[8], -e[9], -e[10]).normalize();
  7283. }
  7284. updateMatrixWorld(force) {
  7285. super.updateMatrixWorld(force);
  7286. this.matrixWorldInverse.copy(this.matrixWorld).invert();
  7287. }
  7288. updateWorldMatrix(updateParents, updateChildren) {
  7289. super.updateWorldMatrix(updateParents, updateChildren);
  7290. this.matrixWorldInverse.copy(this.matrixWorld).invert();
  7291. }
  7292. clone() {
  7293. return new this.constructor().copy(this);
  7294. }
  7295. }
  7296. class PerspectiveCamera extends Camera {
  7297. constructor(fov = 50, aspect = 1, near = 0.1, far = 2000) {
  7298. super();
  7299. this.isPerspectiveCamera = true;
  7300. this.type = 'PerspectiveCamera';
  7301. this.fov = fov;
  7302. this.zoom = 1;
  7303. this.near = near;
  7304. this.far = far;
  7305. this.focus = 10;
  7306. this.aspect = aspect;
  7307. this.view = null;
  7308. this.filmGauge = 35; // width of the film (default in millimeters)
  7309. this.filmOffset = 0; // horizontal film offset (same unit as gauge)
  7310. this.updateProjectionMatrix();
  7311. }
  7312. copy(source, recursive) {
  7313. super.copy(source, recursive);
  7314. this.fov = source.fov;
  7315. this.zoom = source.zoom;
  7316. this.near = source.near;
  7317. this.far = source.far;
  7318. this.focus = source.focus;
  7319. this.aspect = source.aspect;
  7320. this.view = source.view === null ? null : Object.assign({}, source.view);
  7321. this.filmGauge = source.filmGauge;
  7322. this.filmOffset = source.filmOffset;
  7323. return this;
  7324. }
  7325. /**
  7326. * Sets the FOV by focal length in respect to the current .filmGauge.
  7327. *
  7328. * The default film gauge is 35, so that the focal length can be specified for
  7329. * a 35mm (full frame) camera.
  7330. *
  7331. * Values for focal length and film gauge must have the same unit.
  7332. */
  7333. setFocalLength(focalLength) {
  7334. /** see {@link http://www.bobatkins.com/photography/technical/field_of_view.html} */
  7335. const vExtentSlope = 0.5 * this.getFilmHeight() / focalLength;
  7336. this.fov = RAD2DEG * 2 * Math.atan(vExtentSlope);
  7337. this.updateProjectionMatrix();
  7338. }
  7339. /**
  7340. * Calculates the focal length from the current .fov and .filmGauge.
  7341. */
  7342. getFocalLength() {
  7343. const vExtentSlope = Math.tan(DEG2RAD * 0.5 * this.fov);
  7344. return 0.5 * this.getFilmHeight() / vExtentSlope;
  7345. }
  7346. getEffectiveFOV() {
  7347. return RAD2DEG * 2 * Math.atan(Math.tan(DEG2RAD * 0.5 * this.fov) / this.zoom);
  7348. }
  7349. getFilmWidth() {
  7350. // film not completely covered in portrait format (aspect < 1)
  7351. return this.filmGauge * Math.min(this.aspect, 1);
  7352. }
  7353. getFilmHeight() {
  7354. // film not completely covered in landscape format (aspect > 1)
  7355. return this.filmGauge / Math.max(this.aspect, 1);
  7356. }
  7357. /**
  7358. * Sets an offset in a larger frustum. This is useful for multi-window or
  7359. * multi-monitor/multi-machine setups.
  7360. *
  7361. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  7362. * the monitors are in grid like this
  7363. *
  7364. * +---+---+---+
  7365. * | A | B | C |
  7366. * +---+---+---+
  7367. * | D | E | F |
  7368. * +---+---+---+
  7369. *
  7370. * then for each monitor you would call it like this
  7371. *
  7372. * const w = 1920;
  7373. * const h = 1080;
  7374. * const fullWidth = w * 3;
  7375. * const fullHeight = h * 2;
  7376. *
  7377. * --A--
  7378. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  7379. * --B--
  7380. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  7381. * --C--
  7382. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  7383. * --D--
  7384. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  7385. * --E--
  7386. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  7387. * --F--
  7388. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  7389. *
  7390. * Note there is no reason monitors have to be the same size or in a grid.
  7391. */
  7392. setViewOffset(fullWidth, fullHeight, x, y, width, height) {
  7393. this.aspect = fullWidth / fullHeight;
  7394. if (this.view === null) {
  7395. this.view = {
  7396. enabled: true,
  7397. fullWidth: 1,
  7398. fullHeight: 1,
  7399. offsetX: 0,
  7400. offsetY: 0,
  7401. width: 1,
  7402. height: 1
  7403. };
  7404. }
  7405. this.view.enabled = true;
  7406. this.view.fullWidth = fullWidth;
  7407. this.view.fullHeight = fullHeight;
  7408. this.view.offsetX = x;
  7409. this.view.offsetY = y;
  7410. this.view.width = width;
  7411. this.view.height = height;
  7412. this.updateProjectionMatrix();
  7413. }
  7414. clearViewOffset() {
  7415. if (this.view !== null) {
  7416. this.view.enabled = false;
  7417. }
  7418. this.updateProjectionMatrix();
  7419. }
  7420. updateProjectionMatrix() {
  7421. const near = this.near;
  7422. let top = near * Math.tan(DEG2RAD * 0.5 * this.fov) / this.zoom;
  7423. let height = 2 * top;
  7424. let width = this.aspect * height;
  7425. let left = -0.5 * width;
  7426. const view = this.view;
  7427. if (this.view !== null && this.view.enabled) {
  7428. const fullWidth = view.fullWidth,
  7429. fullHeight = view.fullHeight;
  7430. left += view.offsetX * width / fullWidth;
  7431. top -= view.offsetY * height / fullHeight;
  7432. width *= view.width / fullWidth;
  7433. height *= view.height / fullHeight;
  7434. }
  7435. const skew = this.filmOffset;
  7436. if (skew !== 0) left += near * skew / this.getFilmWidth();
  7437. this.projectionMatrix.makePerspective(left, left + width, top, top - height, near, this.far);
  7438. this.projectionMatrixInverse.copy(this.projectionMatrix).invert();
  7439. }
  7440. toJSON(meta) {
  7441. const data = super.toJSON(meta);
  7442. data.object.fov = this.fov;
  7443. data.object.zoom = this.zoom;
  7444. data.object.near = this.near;
  7445. data.object.far = this.far;
  7446. data.object.focus = this.focus;
  7447. data.object.aspect = this.aspect;
  7448. if (this.view !== null) data.object.view = Object.assign({}, this.view);
  7449. data.object.filmGauge = this.filmGauge;
  7450. data.object.filmOffset = this.filmOffset;
  7451. return data;
  7452. }
  7453. }
  7454. const fov = 90,
  7455. aspect = 1;
  7456. class CubeCamera extends Object3D {
  7457. constructor(near, far, renderTarget) {
  7458. super();
  7459. this.type = 'CubeCamera';
  7460. if (renderTarget.isWebGLCubeRenderTarget !== true) {
  7461. console.error('THREE.CubeCamera: The constructor now expects an instance of WebGLCubeRenderTarget as third parameter.');
  7462. return;
  7463. }
  7464. this.renderTarget = renderTarget;
  7465. const cameraPX = new PerspectiveCamera(fov, aspect, near, far);
  7466. cameraPX.layers = this.layers;
  7467. cameraPX.up.set(0, -1, 0);
  7468. cameraPX.lookAt(new Vector3(1, 0, 0));
  7469. this.add(cameraPX);
  7470. const cameraNX = new PerspectiveCamera(fov, aspect, near, far);
  7471. cameraNX.layers = this.layers;
  7472. cameraNX.up.set(0, -1, 0);
  7473. cameraNX.lookAt(new Vector3(-1, 0, 0));
  7474. this.add(cameraNX);
  7475. const cameraPY = new PerspectiveCamera(fov, aspect, near, far);
  7476. cameraPY.layers = this.layers;
  7477. cameraPY.up.set(0, 0, 1);
  7478. cameraPY.lookAt(new Vector3(0, 1, 0));
  7479. this.add(cameraPY);
  7480. const cameraNY = new PerspectiveCamera(fov, aspect, near, far);
  7481. cameraNY.layers = this.layers;
  7482. cameraNY.up.set(0, 0, -1);
  7483. cameraNY.lookAt(new Vector3(0, -1, 0));
  7484. this.add(cameraNY);
  7485. const cameraPZ = new PerspectiveCamera(fov, aspect, near, far);
  7486. cameraPZ.layers = this.layers;
  7487. cameraPZ.up.set(0, -1, 0);
  7488. cameraPZ.lookAt(new Vector3(0, 0, 1));
  7489. this.add(cameraPZ);
  7490. const cameraNZ = new PerspectiveCamera(fov, aspect, near, far);
  7491. cameraNZ.layers = this.layers;
  7492. cameraNZ.up.set(0, -1, 0);
  7493. cameraNZ.lookAt(new Vector3(0, 0, -1));
  7494. this.add(cameraNZ);
  7495. }
  7496. update(renderer, scene) {
  7497. if (this.parent === null) this.updateMatrixWorld();
  7498. const renderTarget = this.renderTarget;
  7499. const [cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ] = this.children;
  7500. const currentRenderTarget = renderer.getRenderTarget();
  7501. const currentToneMapping = renderer.toneMapping;
  7502. const currentXrEnabled = renderer.xr.enabled;
  7503. renderer.toneMapping = NoToneMapping;
  7504. renderer.xr.enabled = false;
  7505. const generateMipmaps = renderTarget.texture.generateMipmaps;
  7506. renderTarget.texture.generateMipmaps = false;
  7507. renderer.setRenderTarget(renderTarget, 0);
  7508. renderer.render(scene, cameraPX);
  7509. renderer.setRenderTarget(renderTarget, 1);
  7510. renderer.render(scene, cameraNX);
  7511. renderer.setRenderTarget(renderTarget, 2);
  7512. renderer.render(scene, cameraPY);
  7513. renderer.setRenderTarget(renderTarget, 3);
  7514. renderer.render(scene, cameraNY);
  7515. renderer.setRenderTarget(renderTarget, 4);
  7516. renderer.render(scene, cameraPZ);
  7517. renderTarget.texture.generateMipmaps = generateMipmaps;
  7518. renderer.setRenderTarget(renderTarget, 5);
  7519. renderer.render(scene, cameraNZ);
  7520. renderer.setRenderTarget(currentRenderTarget);
  7521. renderer.toneMapping = currentToneMapping;
  7522. renderer.xr.enabled = currentXrEnabled;
  7523. renderTarget.texture.needsPMREMUpdate = true;
  7524. }
  7525. }
  7526. class CubeTexture extends Texture {
  7527. constructor(images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding) {
  7528. images = images !== undefined ? images : [];
  7529. mapping = mapping !== undefined ? mapping : CubeReflectionMapping;
  7530. super(images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding);
  7531. this.isCubeTexture = true;
  7532. this.flipY = false;
  7533. }
  7534. get images() {
  7535. return this.image;
  7536. }
  7537. set images(value) {
  7538. this.image = value;
  7539. }
  7540. }
  7541. class WebGLCubeRenderTarget extends WebGLRenderTarget {
  7542. constructor(size, options = {}) {
  7543. super(size, size, options);
  7544. this.isWebGLCubeRenderTarget = true;
  7545. const image = {
  7546. width: size,
  7547. height: size,
  7548. depth: 1
  7549. };
  7550. const images = [image, image, image, image, image, image];
  7551. this.texture = new CubeTexture(images, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding); // By convention -- likely based on the RenderMan spec from the 1990's -- cube maps are specified by WebGL (and three.js)
  7552. // in a coordinate system in which positive-x is to the right when looking up the positive-z axis -- in other words,
  7553. // in a left-handed coordinate system. By continuing this convention, preexisting cube maps continued to render correctly.
  7554. // three.js uses a right-handed coordinate system. So environment maps used in three.js appear to have px and nx swapped
  7555. // and the flag isRenderTargetTexture controls this conversion. The flip is not required when using WebGLCubeRenderTarget.texture
  7556. // as a cube texture (this is detected when isRenderTargetTexture is set to true for cube textures).
  7557. this.texture.isRenderTargetTexture = true;
  7558. this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false;
  7559. this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter;
  7560. }
  7561. fromEquirectangularTexture(renderer, texture) {
  7562. this.texture.type = texture.type;
  7563. this.texture.encoding = texture.encoding;
  7564. this.texture.generateMipmaps = texture.generateMipmaps;
  7565. this.texture.minFilter = texture.minFilter;
  7566. this.texture.magFilter = texture.magFilter;
  7567. const shader = {
  7568. uniforms: {
  7569. tEquirect: {
  7570. value: null
  7571. }
  7572. },
  7573. vertexShader:
  7574. /* glsl */
  7575. `
  7576. varying vec3 vWorldDirection;
  7577. vec3 transformDirection( in vec3 dir, in mat4 matrix ) {
  7578. return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );
  7579. }
  7580. void main() {
  7581. vWorldDirection = transformDirection( position, modelMatrix );
  7582. #include <begin_vertex>
  7583. #include <project_vertex>
  7584. }
  7585. `,
  7586. fragmentShader:
  7587. /* glsl */
  7588. `
  7589. uniform sampler2D tEquirect;
  7590. varying vec3 vWorldDirection;
  7591. #include <common>
  7592. void main() {
  7593. vec3 direction = normalize( vWorldDirection );
  7594. vec2 sampleUV = equirectUv( direction );
  7595. gl_FragColor = texture2D( tEquirect, sampleUV );
  7596. }
  7597. `
  7598. };
  7599. const geometry = new BoxGeometry(5, 5, 5);
  7600. const material = new ShaderMaterial({
  7601. name: 'CubemapFromEquirect',
  7602. uniforms: cloneUniforms(shader.uniforms),
  7603. vertexShader: shader.vertexShader,
  7604. fragmentShader: shader.fragmentShader,
  7605. side: BackSide,
  7606. blending: NoBlending
  7607. });
  7608. material.uniforms.tEquirect.value = texture;
  7609. const mesh = new Mesh(geometry, material);
  7610. const currentMinFilter = texture.minFilter; // Avoid blurred poles
  7611. if (texture.minFilter === LinearMipmapLinearFilter) texture.minFilter = LinearFilter;
  7612. const camera = new CubeCamera(1, 10, this);
  7613. camera.update(renderer, mesh);
  7614. texture.minFilter = currentMinFilter;
  7615. mesh.geometry.dispose();
  7616. mesh.material.dispose();
  7617. return this;
  7618. }
  7619. clear(renderer, color, depth, stencil) {
  7620. const currentRenderTarget = renderer.getRenderTarget();
  7621. for (let i = 0; i < 6; i++) {
  7622. renderer.setRenderTarget(this, i);
  7623. renderer.clear(color, depth, stencil);
  7624. }
  7625. renderer.setRenderTarget(currentRenderTarget);
  7626. }
  7627. }
  7628. const _vector1 = /*@__PURE__*/new Vector3();
  7629. const _vector2 = /*@__PURE__*/new Vector3();
  7630. const _normalMatrix = /*@__PURE__*/new Matrix3();
  7631. class Plane {
  7632. constructor(normal = new Vector3(1, 0, 0), constant = 0) {
  7633. this.isPlane = true; // normal is assumed to be normalized
  7634. this.normal = normal;
  7635. this.constant = constant;
  7636. }
  7637. set(normal, constant) {
  7638. this.normal.copy(normal);
  7639. this.constant = constant;
  7640. return this;
  7641. }
  7642. setComponents(x, y, z, w) {
  7643. this.normal.set(x, y, z);
  7644. this.constant = w;
  7645. return this;
  7646. }
  7647. setFromNormalAndCoplanarPoint(normal, point) {
  7648. this.normal.copy(normal);
  7649. this.constant = -point.dot(this.normal);
  7650. return this;
  7651. }
  7652. setFromCoplanarPoints(a, b, c) {
  7653. 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)?
  7654. this.setFromNormalAndCoplanarPoint(normal, a);
  7655. return this;
  7656. }
  7657. copy(plane) {
  7658. this.normal.copy(plane.normal);
  7659. this.constant = plane.constant;
  7660. return this;
  7661. }
  7662. normalize() {
  7663. // Note: will lead to a divide by zero if the plane is invalid.
  7664. const inverseNormalLength = 1.0 / this.normal.length();
  7665. this.normal.multiplyScalar(inverseNormalLength);
  7666. this.constant *= inverseNormalLength;
  7667. return this;
  7668. }
  7669. negate() {
  7670. this.constant *= -1;
  7671. this.normal.negate();
  7672. return this;
  7673. }
  7674. distanceToPoint(point) {
  7675. return this.normal.dot(point) + this.constant;
  7676. }
  7677. distanceToSphere(sphere) {
  7678. return this.distanceToPoint(sphere.center) - sphere.radius;
  7679. }
  7680. projectPoint(point, target) {
  7681. return target.copy(this.normal).multiplyScalar(-this.distanceToPoint(point)).add(point);
  7682. }
  7683. intersectLine(line, target) {
  7684. const direction = line.delta(_vector1);
  7685. const denominator = this.normal.dot(direction);
  7686. if (denominator === 0) {
  7687. // line is coplanar, return origin
  7688. if (this.distanceToPoint(line.start) === 0) {
  7689. return target.copy(line.start);
  7690. } // Unsure if this is the correct method to handle this case.
  7691. return null;
  7692. }
  7693. const t = -(line.start.dot(this.normal) + this.constant) / denominator;
  7694. if (t < 0 || t > 1) {
  7695. return null;
  7696. }
  7697. return target.copy(direction).multiplyScalar(t).add(line.start);
  7698. }
  7699. intersectsLine(line) {
  7700. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  7701. const startSign = this.distanceToPoint(line.start);
  7702. const endSign = this.distanceToPoint(line.end);
  7703. return startSign < 0 && endSign > 0 || endSign < 0 && startSign > 0;
  7704. }
  7705. intersectsBox(box) {
  7706. return box.intersectsPlane(this);
  7707. }
  7708. intersectsSphere(sphere) {
  7709. return sphere.intersectsPlane(this);
  7710. }
  7711. coplanarPoint(target) {
  7712. return target.copy(this.normal).multiplyScalar(-this.constant);
  7713. }
  7714. applyMatrix4(matrix, optionalNormalMatrix) {
  7715. const normalMatrix = optionalNormalMatrix || _normalMatrix.getNormalMatrix(matrix);
  7716. const referencePoint = this.coplanarPoint(_vector1).applyMatrix4(matrix);
  7717. const normal = this.normal.applyMatrix3(normalMatrix).normalize();
  7718. this.constant = -referencePoint.dot(normal);
  7719. return this;
  7720. }
  7721. translate(offset) {
  7722. this.constant -= offset.dot(this.normal);
  7723. return this;
  7724. }
  7725. equals(plane) {
  7726. return plane.normal.equals(this.normal) && plane.constant === this.constant;
  7727. }
  7728. clone() {
  7729. return new this.constructor().copy(this);
  7730. }
  7731. }
  7732. const _sphere$2 = /*@__PURE__*/new Sphere();
  7733. const _vector$7 = /*@__PURE__*/new Vector3();
  7734. class Frustum {
  7735. constructor(p0 = new Plane(), p1 = new Plane(), p2 = new Plane(), p3 = new Plane(), p4 = new Plane(), p5 = new Plane()) {
  7736. this.planes = [p0, p1, p2, p3, p4, p5];
  7737. }
  7738. set(p0, p1, p2, p3, p4, p5) {
  7739. const planes = this.planes;
  7740. planes[0].copy(p0);
  7741. planes[1].copy(p1);
  7742. planes[2].copy(p2);
  7743. planes[3].copy(p3);
  7744. planes[4].copy(p4);
  7745. planes[5].copy(p5);
  7746. return this;
  7747. }
  7748. copy(frustum) {
  7749. const planes = this.planes;
  7750. for (let i = 0; i < 6; i++) {
  7751. planes[i].copy(frustum.planes[i]);
  7752. }
  7753. return this;
  7754. }
  7755. setFromProjectionMatrix(m) {
  7756. const planes = this.planes;
  7757. const me = m.elements;
  7758. const me0 = me[0],
  7759. me1 = me[1],
  7760. me2 = me[2],
  7761. me3 = me[3];
  7762. const me4 = me[4],
  7763. me5 = me[5],
  7764. me6 = me[6],
  7765. me7 = me[7];
  7766. const me8 = me[8],
  7767. me9 = me[9],
  7768. me10 = me[10],
  7769. me11 = me[11];
  7770. const me12 = me[12],
  7771. me13 = me[13],
  7772. me14 = me[14],
  7773. me15 = me[15];
  7774. planes[0].setComponents(me3 - me0, me7 - me4, me11 - me8, me15 - me12).normalize();
  7775. planes[1].setComponents(me3 + me0, me7 + me4, me11 + me8, me15 + me12).normalize();
  7776. planes[2].setComponents(me3 + me1, me7 + me5, me11 + me9, me15 + me13).normalize();
  7777. planes[3].setComponents(me3 - me1, me7 - me5, me11 - me9, me15 - me13).normalize();
  7778. planes[4].setComponents(me3 - me2, me7 - me6, me11 - me10, me15 - me14).normalize();
  7779. planes[5].setComponents(me3 + me2, me7 + me6, me11 + me10, me15 + me14).normalize();
  7780. return this;
  7781. }
  7782. intersectsObject(object) {
  7783. const geometry = object.geometry;
  7784. if (geometry.boundingSphere === null) geometry.computeBoundingSphere();
  7785. _sphere$2.copy(geometry.boundingSphere).applyMatrix4(object.matrixWorld);
  7786. return this.intersectsSphere(_sphere$2);
  7787. }
  7788. intersectsSprite(sprite) {
  7789. _sphere$2.center.set(0, 0, 0);
  7790. _sphere$2.radius = 0.7071067811865476;
  7791. _sphere$2.applyMatrix4(sprite.matrixWorld);
  7792. return this.intersectsSphere(_sphere$2);
  7793. }
  7794. intersectsSphere(sphere) {
  7795. const planes = this.planes;
  7796. const center = sphere.center;
  7797. const negRadius = -sphere.radius;
  7798. for (let i = 0; i < 6; i++) {
  7799. const distance = planes[i].distanceToPoint(center);
  7800. if (distance < negRadius) {
  7801. return false;
  7802. }
  7803. }
  7804. return true;
  7805. }
  7806. intersectsBox(box) {
  7807. const planes = this.planes;
  7808. for (let i = 0; i < 6; i++) {
  7809. const plane = planes[i]; // corner at max distance
  7810. _vector$7.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  7811. _vector$7.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  7812. _vector$7.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  7813. if (plane.distanceToPoint(_vector$7) < 0) {
  7814. return false;
  7815. }
  7816. }
  7817. return true;
  7818. }
  7819. containsPoint(point) {
  7820. const planes = this.planes;
  7821. for (let i = 0; i < 6; i++) {
  7822. if (planes[i].distanceToPoint(point) < 0) {
  7823. return false;
  7824. }
  7825. }
  7826. return true;
  7827. }
  7828. clone() {
  7829. return new this.constructor().copy(this);
  7830. }
  7831. }
  7832. function WebGLAnimation() {
  7833. let context = null;
  7834. let isAnimating = false;
  7835. let animationLoop = null;
  7836. let requestId = null;
  7837. function onAnimationFrame(time, frame) {
  7838. animationLoop(time, frame);
  7839. requestId = context.requestAnimationFrame(onAnimationFrame);
  7840. }
  7841. return {
  7842. start: function () {
  7843. if (isAnimating === true) return;
  7844. if (animationLoop === null) return;
  7845. requestId = context.requestAnimationFrame(onAnimationFrame);
  7846. isAnimating = true;
  7847. },
  7848. stop: function () {
  7849. context.cancelAnimationFrame(requestId);
  7850. isAnimating = false;
  7851. },
  7852. setAnimationLoop: function (callback) {
  7853. animationLoop = callback;
  7854. },
  7855. setContext: function (value) {
  7856. context = value;
  7857. }
  7858. };
  7859. }
  7860. function WebGLAttributes(gl, capabilities) {
  7861. const isWebGL2 = capabilities.isWebGL2;
  7862. const buffers = new WeakMap();
  7863. function createBuffer(attribute, bufferType) {
  7864. const array = attribute.array;
  7865. const usage = attribute.usage;
  7866. const buffer = gl.createBuffer();
  7867. gl.bindBuffer(bufferType, buffer);
  7868. gl.bufferData(bufferType, array, usage);
  7869. attribute.onUploadCallback();
  7870. let type;
  7871. if (array instanceof Float32Array) {
  7872. type = gl.FLOAT;
  7873. } else if (array instanceof Uint16Array) {
  7874. if (attribute.isFloat16BufferAttribute) {
  7875. if (isWebGL2) {
  7876. type = gl.HALF_FLOAT;
  7877. } else {
  7878. throw new Error('THREE.WebGLAttributes: Usage of Float16BufferAttribute requires WebGL2.');
  7879. }
  7880. } else {
  7881. type = gl.UNSIGNED_SHORT;
  7882. }
  7883. } else if (array instanceof Int16Array) {
  7884. type = gl.SHORT;
  7885. } else if (array instanceof Uint32Array) {
  7886. type = gl.UNSIGNED_INT;
  7887. } else if (array instanceof Int32Array) {
  7888. type = gl.INT;
  7889. } else if (array instanceof Int8Array) {
  7890. type = gl.BYTE;
  7891. } else if (array instanceof Uint8Array) {
  7892. type = gl.UNSIGNED_BYTE;
  7893. } else if (array instanceof Uint8ClampedArray) {
  7894. type = gl.UNSIGNED_BYTE;
  7895. } else {
  7896. throw new Error('THREE.WebGLAttributes: Unsupported buffer data format: ' + array);
  7897. }
  7898. return {
  7899. buffer: buffer,
  7900. type: type,
  7901. bytesPerElement: array.BYTES_PER_ELEMENT,
  7902. version: attribute.version
  7903. };
  7904. }
  7905. function updateBuffer(buffer, attribute, bufferType) {
  7906. const array = attribute.array;
  7907. const updateRange = attribute.updateRange;
  7908. gl.bindBuffer(bufferType, buffer);
  7909. if (updateRange.count === -1) {
  7910. // Not using update ranges
  7911. gl.bufferSubData(bufferType, 0, array);
  7912. } else {
  7913. if (isWebGL2) {
  7914. gl.bufferSubData(bufferType, updateRange.offset * array.BYTES_PER_ELEMENT, array, updateRange.offset, updateRange.count);
  7915. } else {
  7916. gl.bufferSubData(bufferType, updateRange.offset * array.BYTES_PER_ELEMENT, array.subarray(updateRange.offset, updateRange.offset + updateRange.count));
  7917. }
  7918. updateRange.count = -1; // reset range
  7919. }
  7920. } //
  7921. function get(attribute) {
  7922. if (attribute.isInterleavedBufferAttribute) attribute = attribute.data;
  7923. return buffers.get(attribute);
  7924. }
  7925. function remove(attribute) {
  7926. if (attribute.isInterleavedBufferAttribute) attribute = attribute.data;
  7927. const data = buffers.get(attribute);
  7928. if (data) {
  7929. gl.deleteBuffer(data.buffer);
  7930. buffers.delete(attribute);
  7931. }
  7932. }
  7933. function update(attribute, bufferType) {
  7934. if (attribute.isGLBufferAttribute) {
  7935. const cached = buffers.get(attribute);
  7936. if (!cached || cached.version < attribute.version) {
  7937. buffers.set(attribute, {
  7938. buffer: attribute.buffer,
  7939. type: attribute.type,
  7940. bytesPerElement: attribute.elementSize,
  7941. version: attribute.version
  7942. });
  7943. }
  7944. return;
  7945. }
  7946. if (attribute.isInterleavedBufferAttribute) attribute = attribute.data;
  7947. const data = buffers.get(attribute);
  7948. if (data === undefined) {
  7949. buffers.set(attribute, createBuffer(attribute, bufferType));
  7950. } else if (data.version < attribute.version) {
  7951. updateBuffer(data.buffer, attribute, bufferType);
  7952. data.version = attribute.version;
  7953. }
  7954. }
  7955. return {
  7956. get: get,
  7957. remove: remove,
  7958. update: update
  7959. };
  7960. }
  7961. class PlaneGeometry extends BufferGeometry {
  7962. constructor(width = 1, height = 1, widthSegments = 1, heightSegments = 1) {
  7963. super();
  7964. this.type = 'PlaneGeometry';
  7965. this.parameters = {
  7966. width: width,
  7967. height: height,
  7968. widthSegments: widthSegments,
  7969. heightSegments: heightSegments
  7970. };
  7971. const width_half = width / 2;
  7972. const height_half = height / 2;
  7973. const gridX = Math.floor(widthSegments);
  7974. const gridY = Math.floor(heightSegments);
  7975. const gridX1 = gridX + 1;
  7976. const gridY1 = gridY + 1;
  7977. const segment_width = width / gridX;
  7978. const segment_height = height / gridY; //
  7979. const indices = [];
  7980. const vertices = [];
  7981. const normals = [];
  7982. const uvs = [];
  7983. for (let iy = 0; iy < gridY1; iy++) {
  7984. const y = iy * segment_height - height_half;
  7985. for (let ix = 0; ix < gridX1; ix++) {
  7986. const x = ix * segment_width - width_half;
  7987. vertices.push(x, -y, 0);
  7988. normals.push(0, 0, 1);
  7989. uvs.push(ix / gridX);
  7990. uvs.push(1 - iy / gridY);
  7991. }
  7992. }
  7993. for (let iy = 0; iy < gridY; iy++) {
  7994. for (let ix = 0; ix < gridX; ix++) {
  7995. const a = ix + gridX1 * iy;
  7996. const b = ix + gridX1 * (iy + 1);
  7997. const c = ix + 1 + gridX1 * (iy + 1);
  7998. const d = ix + 1 + gridX1 * iy;
  7999. indices.push(a, b, d);
  8000. indices.push(b, c, d);
  8001. }
  8002. }
  8003. this.setIndex(indices);
  8004. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  8005. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  8006. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  8007. }
  8008. static fromJSON(data) {
  8009. return new PlaneGeometry(data.width, data.height, data.widthSegments, data.heightSegments);
  8010. }
  8011. }
  8012. var alphamap_fragment = "#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, vUv ).g;\n#endif";
  8013. var alphamap_pars_fragment = "#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif";
  8014. var alphatest_fragment = "#ifdef USE_ALPHATEST\n\tif ( diffuseColor.a < alphaTest ) discard;\n#endif";
  8015. var alphatest_pars_fragment = "#ifdef USE_ALPHATEST\n\tuniform float alphaTest;\n#endif";
  8016. 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.roughness );\n\t#endif\n#endif";
  8017. var aomap_pars_fragment = "#ifdef USE_AOMAP\n\tuniform sampler2D aoMap;\n\tuniform float aoMapIntensity;\n#endif";
  8018. var begin_vertex = "vec3 transformed = vec3( position );";
  8019. var beginnormal_vertex = "vec3 objectNormal = vec3( normal );\n#ifdef USE_TANGENT\n\tvec3 objectTangent = vec3( tangent.xyz );\n#endif";
  8020. var bsdfs = "vec3 BRDF_Lambert( const in vec3 diffuseColor ) {\n\treturn RECIPROCAL_PI * diffuseColor;\n}\nvec3 F_Schlick( const in vec3 f0, const in float f90, const in float dotVH ) {\n\tfloat fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH );\n\treturn f0 * ( 1.0 - fresnel ) + ( f90 * fresnel );\n}\nfloat V_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_GGX( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in vec3 f0, const in float f90, const in float roughness ) {\n\tfloat alpha = pow2( roughness );\n\tvec3 halfDir = normalize( lightDir + viewDir );\n\tfloat dotNL = saturate( dot( normal, lightDir ) );\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat dotVH = saturate( dot( viewDir, halfDir ) );\n\tvec3 F = F_Schlick( f0, f90, dotVH );\n\tfloat V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n\tfloat D = D_GGX( alpha, dotNH );\n\treturn F * ( V * 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}\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_BlinnPhong( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in vec3 specularColor, const in float shininess ) {\n\tvec3 halfDir = normalize( lightDir + viewDir );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat dotVH = saturate( dot( viewDir, halfDir ) );\n\tvec3 F = F_Schlick( specularColor, 1.0, dotVH );\n\tfloat G = G_BlinnPhong_Implicit( );\n\tfloat D = D_BlinnPhong( shininess, dotNH );\n\treturn F * ( G * D );\n}\n#if defined( USE_SHEEN )\nfloat D_Charlie( float roughness, float dotNH ) {\n\tfloat alpha = pow2( roughness );\n\tfloat invAlpha = 1.0 / alpha;\n\tfloat cos2h = dotNH * dotNH;\n\tfloat sin2h = max( 1.0 - cos2h, 0.0078125 );\n\treturn ( 2.0 + invAlpha ) * pow( sin2h, invAlpha * 0.5 ) / ( 2.0 * PI );\n}\nfloat V_Neubelt( float dotNV, float dotNL ) {\n\treturn saturate( 1.0 / ( 4.0 * ( dotNL + dotNV - dotNL * dotNV ) ) );\n}\nvec3 BRDF_Sheen( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, vec3 sheenColor, const in float sheenRoughness ) {\n\tvec3 halfDir = normalize( lightDir + viewDir );\n\tfloat dotNL = saturate( dot( normal, lightDir ) );\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat D = D_Charlie( sheenRoughness, dotNH );\n\tfloat V = V_Neubelt( dotNV, dotNL );\n\treturn sheenColor * ( D * V );\n}\n#endif";
  8021. 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, float faceDirection ) {\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 ) * faceDirection;\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";
  8022. 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";
  8023. var clipping_planes_pars_fragment = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n\tuniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];\n#endif";
  8024. var clipping_planes_pars_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n#endif";
  8025. var clipping_planes_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvClipPosition = - mvPosition.xyz;\n#endif";
  8026. var color_fragment = "#if defined( USE_COLOR_ALPHA )\n\tdiffuseColor *= vColor;\n#elif defined( USE_COLOR )\n\tdiffuseColor.rgb *= vColor;\n#endif";
  8027. var color_pars_fragment = "#if defined( USE_COLOR_ALPHA )\n\tvarying vec4 vColor;\n#elif defined( USE_COLOR )\n\tvarying vec3 vColor;\n#endif";
  8028. var color_pars_vertex = "#if defined( USE_COLOR_ALPHA )\n\tvarying vec4 vColor;\n#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR )\n\tvarying vec3 vColor;\n#endif";
  8029. var color_vertex = "#if defined( USE_COLOR_ALPHA )\n\tvColor = vec4( 1.0 );\n#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR )\n\tvColor = vec3( 1.0 );\n#endif\n#ifdef USE_COLOR\n\tvColor *= color;\n#endif\n#ifdef USE_INSTANCING_COLOR\n\tvColor.xyz *= instanceColor.xyz;\n#endif";
  8030. 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 max3( const in vec3 v ) { return max( max( v.x, v.y ), v.z ); }\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 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 USE_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}\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}";
  8031. var cube_uv_reflection_fragment = "#ifdef ENVMAP_TYPE_CUBE_UV\n\t#define cubeUV_minMipLevel 4.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\tvec2 uv = getUV( direction, face ) * ( faceSize - 2.0 ) + 1.0;\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\tuv.x += filterInt * 3.0 * cubeUV_minTileSize;\n\t\tuv.y += 4.0 * ( exp2( CUBEUV_MAX_MIP ) - faceSize );\n\t\tuv.x *= CUBEUV_TEXEL_WIDTH;\n\t\tuv.y *= CUBEUV_TEXEL_HEIGHT;\n\t\t#ifdef texture2DGradEXT\n\t\t\treturn texture2DGradEXT( envMap, uv, vec2( 0.0 ), vec2( 0.0 ) ).rgb;\n\t\t#else\n\t\t\treturn texture2D( envMap, uv ).rgb;\n\t\t#endif\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_MAX_MIP );\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";
  8032. 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";
  8033. var displacementmap_pars_vertex = "#ifdef USE_DISPLACEMENTMAP\n\tuniform sampler2D displacementMap;\n\tuniform float displacementScale;\n\tuniform float displacementBias;\n#endif";
  8034. var displacementmap_vertex = "#ifdef USE_DISPLACEMENTMAP\n\ttransformed += normalize( objectNormal ) * ( texture2D( displacementMap, vUv ).x * displacementScale + displacementBias );\n#endif";
  8035. var emissivemap_fragment = "#ifdef USE_EMISSIVEMAP\n\tvec4 emissiveColor = texture2D( emissiveMap, vUv );\n\ttotalEmissiveRadiance *= emissiveColor.rgb;\n#endif";
  8036. var emissivemap_pars_fragment = "#ifdef USE_EMISSIVEMAP\n\tuniform sampler2D emissiveMap;\n#endif";
  8037. var encodings_fragment = "gl_FragColor = linearToOutputTexel( gl_FragColor );";
  8038. var encodings_pars_fragment = "vec4 LinearToLinear( in vec4 value ) {\n\treturn value;\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}";
  8039. 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#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";
  8040. var envmap_common_pars_fragment = "#ifdef USE_ENVMAP\n\tuniform float envMapIntensity;\n\tuniform float flipEnvMap;\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";
  8041. 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";
  8042. 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";
  8043. 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";
  8044. var fog_vertex = "#ifdef USE_FOG\n\tvFogDepth = - mvPosition.z;\n#endif";
  8045. var fog_pars_vertex = "#ifdef USE_FOG\n\tvarying float vFogDepth;\n#endif";
  8046. var fog_fragment = "#ifdef USE_FOG\n\t#ifdef FOG_EXP2\n\t\tfloat fogFactor = 1.0 - exp( - fogDensity * fogDensity * vFogDepth * vFogDepth );\n\t#else\n\t\tfloat fogFactor = smoothstep( fogNear, fogFar, vFogDepth );\n\t#endif\n\tgl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor );\n#endif";
  8047. var fog_pars_fragment = "#ifdef USE_FOG\n\tuniform vec3 fogColor;\n\tvarying float vFogDepth;\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";
  8048. 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 vec3( texture2D( gradientMap, coord ).r );\n\t#else\n\t\treturn ( coord.x < 0.7 ) ? vec3( 0.7 ) : vec3( 1.0 );\n\t#endif\n}";
  8049. var lightmap_fragment = "#ifdef USE_LIGHTMAP\n\tvec4 lightMapTexel = texture2D( lightMap, vUv2 );\n\tvec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity;\n\treflectedLight.indirectDiffuse += lightMapIrradiance;\n#endif";
  8050. var lightmap_pars_fragment = "#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif";
  8051. 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.normal );\n#ifdef DOUBLE_SIDED\n\tvIndirectBack += getAmbientLightIrradiance( ambientLightColor );\n\tvIndirectBack += getLightProbeIrradiance( lightProbe, backGeometry.normal );\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\tgetPointLightInfo( pointLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = 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\tgetSpotLightInfo( spotLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = 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\tgetDirectionalLightInfo( directionalLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = 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.normal );\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvIndirectBack += getHemisphereLightIrradiance( hemisphereLights[ i ], backGeometry.normal );\n\t\t#endif\n\t}\n\t#pragma unroll_loop_end\n#endif";
  8052. 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 vec3 normal ) {\n\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\tvec3 irradiance = shGetIrradianceAt( worldNormal, lightProbe );\n\treturn irradiance;\n}\nvec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) {\n\tvec3 irradiance = ambientLightColor;\n\treturn irradiance;\n}\nfloat getDistanceAttenuation( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) {\n\t#if defined ( PHYSICALLY_CORRECT_LIGHTS )\n\t\tfloat distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 );\n\t\tif ( cutoffDistance > 0.0 ) {\n\t\t\tdistanceFalloff *= pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) );\n\t\t}\n\t\treturn distanceFalloff;\n\t#else\n\t\tif ( cutoffDistance > 0.0 && decayExponent > 0.0 ) {\n\t\t\treturn pow( saturate( - lightDistance / cutoffDistance + 1.0 ), decayExponent );\n\t\t}\n\t\treturn 1.0;\n\t#endif\n}\nfloat getSpotAttenuation( const in float coneCosine, const in float penumbraCosine, const in float angleCosine ) {\n\treturn smoothstep( coneCosine, penumbraCosine, angleCosine );\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 getDirectionalLightInfo( const in DirectionalLight directionalLight, const in GeometricContext geometry, out IncidentLight light ) {\n\t\tlight.color = directionalLight.color;\n\t\tlight.direction = directionalLight.direction;\n\t\tlight.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 getPointLightInfo( const in PointLight pointLight, const in GeometricContext geometry, out IncidentLight light ) {\n\t\tvec3 lVector = pointLight.position - geometry.position;\n\t\tlight.direction = normalize( lVector );\n\t\tfloat lightDistance = length( lVector );\n\t\tlight.color = pointLight.color;\n\t\tlight.color *= getDistanceAttenuation( lightDistance, pointLight.distance, pointLight.decay );\n\t\tlight.visible = ( light.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 getSpotLightInfo( const in SpotLight spotLight, const in GeometricContext geometry, out IncidentLight light ) {\n\t\tvec3 lVector = spotLight.position - geometry.position;\n\t\tlight.direction = normalize( lVector );\n\t\tfloat angleCos = dot( light.direction, spotLight.direction );\n\t\tfloat spotAttenuation = getSpotAttenuation( spotLight.coneCos, spotLight.penumbraCos, angleCos );\n\t\tif ( spotAttenuation > 0.0 ) {\n\t\t\tfloat lightDistance = length( lVector );\n\t\t\tlight.color = spotLight.color * spotAttenuation;\n\t\t\tlight.color *= getDistanceAttenuation( lightDistance, spotLight.distance, spotLight.decay );\n\t\t\tlight.visible = ( light.color != vec3( 0.0 ) );\n\t\t} else {\n\t\t\tlight.color = vec3( 0.0 );\n\t\t\tlight.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 vec3 normal ) {\n\t\tfloat dotNL = dot( normal, hemiLight.direction );\n\t\tfloat hemiDiffuseWeight = 0.5 * dotNL + 0.5;\n\t\tvec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight );\n\t\treturn irradiance;\n\t}\n#endif";
  8053. var envmap_physical_pars_fragment = "#if defined( USE_ENVMAP )\n\tvec3 getIBLIrradiance( const in vec3 normal ) {\n\t\t#if defined( ENVMAP_TYPE_CUBE_UV )\n\t\t\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, worldNormal, 1.0 );\n\t\t\treturn PI * envMapColor.rgb * envMapIntensity;\n\t\t#else\n\t\t\treturn vec3( 0.0 );\n\t\t#endif\n\t}\n\tvec3 getIBLRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness ) {\n\t\t#if defined( ENVMAP_TYPE_CUBE_UV )\n\t\t\tvec3 reflectVec = reflect( - viewDir, normal );\n\t\t\treflectVec = normalize( mix( reflectVec, normal, roughness * roughness) );\n\t\t\treflectVec = inverseTransformDirection( reflectVec, viewMatrix );\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, reflectVec, roughness );\n\t\t\treturn envMapColor.rgb * envMapIntensity;\n\t\t#else\n\t\t\treturn vec3( 0.0 );\n\t\t#endif\n\t}\n#endif";
  8054. var lights_toon_fragment = "ToonMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;";
  8055. var lights_toon_pars_fragment = "varying vec3 vViewPosition;\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\treflectedLight.directDiffuse += irradiance * BRDF_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_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)";
  8056. var lights_phong_fragment = "BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;";
  8057. var lights_phong_pars_fragment = "varying vec3 vViewPosition;\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\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n\treflectedLight.directSpecular += irradiance * BRDF_BlinnPhong( directLight.direction, geometry.viewDir, geometry.normal, 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_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)";
  8058. 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.roughness = max( roughnessFactor, 0.0525 );material.roughness += geometryRoughness;\nmaterial.roughness = min( material.roughness, 1.0 );\n#ifdef IOR\n\t#ifdef SPECULAR\n\t\tfloat specularIntensityFactor = specularIntensity;\n\t\tvec3 specularColorFactor = specularColor;\n\t\t#ifdef USE_SPECULARINTENSITYMAP\n\t\t\tspecularIntensityFactor *= texture2D( specularIntensityMap, vUv ).a;\n\t\t#endif\n\t\t#ifdef USE_SPECULARCOLORMAP\n\t\t\tspecularColorFactor *= texture2D( specularColorMap, vUv ).rgb;\n\t\t#endif\n\t\tmaterial.specularF90 = mix( specularIntensityFactor, 1.0, metalnessFactor );\n\t#else\n\t\tfloat specularIntensityFactor = 1.0;\n\t\tvec3 specularColorFactor = vec3( 1.0 );\n\t\tmaterial.specularF90 = 1.0;\n\t#endif\n\tmaterial.specularColor = mix( min( pow2( ( ior - 1.0 ) / ( ior + 1.0 ) ) * specularColorFactor, vec3( 1.0 ) ) * specularIntensityFactor, diffuseColor.rgb, metalnessFactor );\n#else\n\tmaterial.specularColor = mix( vec3( 0.04 ), diffuseColor.rgb, metalnessFactor );\n\tmaterial.specularF90 = 1.0;\n#endif\n#ifdef USE_CLEARCOAT\n\tmaterial.clearcoat = clearcoat;\n\tmaterial.clearcoatRoughness = clearcoatRoughness;\n\tmaterial.clearcoatF0 = vec3( 0.04 );\n\tmaterial.clearcoatF90 = 1.0;\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 = sheenColor;\n\t#ifdef USE_SHEENCOLORMAP\n\t\tmaterial.sheenColor *= texture2D( sheenColorMap, vUv ).rgb;\n\t#endif\n\tmaterial.sheenRoughness = clamp( sheenRoughness, 0.07, 1.0 );\n\t#ifdef USE_SHEENROUGHNESSMAP\n\t\tmaterial.sheenRoughness *= texture2D( sheenRoughnessMap, vUv ).a;\n\t#endif\n#endif";
  8059. var lights_physical_pars_fragment = "struct PhysicalMaterial {\n\tvec3 diffuseColor;\n\tfloat roughness;\n\tvec3 specularColor;\n\tfloat specularF90;\n\t#ifdef USE_CLEARCOAT\n\t\tfloat clearcoat;\n\t\tfloat clearcoatRoughness;\n\t\tvec3 clearcoatF0;\n\t\tfloat clearcoatF90;\n\t#endif\n\t#ifdef USE_SHEEN\n\t\tvec3 sheenColor;\n\t\tfloat sheenRoughness;\n\t#endif\n};\nvec3 clearcoatSpecular = vec3( 0.0 );\nvec3 sheenSpecular = vec3( 0.0 );\nfloat IBLSheenBRDF( const in vec3 normal, const in vec3 viewDir, const in float roughness) {\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat r2 = roughness * roughness;\n\tfloat a = roughness < 0.25 ? -339.2 * r2 + 161.4 * roughness - 25.9 : -8.48 * r2 + 14.3 * roughness - 9.95;\n\tfloat b = roughness < 0.25 ? 44.0 * r2 - 23.7 * roughness + 3.26 : 1.97 * r2 - 3.27 * roughness + 0.72;\n\tfloat DG = exp( a * dotNV + b ) + ( roughness < 0.25 ? 0.0 : 0.1 * ( roughness - 0.25 ) );\n\treturn saturate( DG * RECIPROCAL_PI );\n}\nvec2 DFGApprox( const in vec3 normal, const in vec3 viewDir, const in float roughness ) {\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\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\tvec2 fab = vec2( - 1.04, 1.04 ) * a004 + r.zw;\n\treturn fab;\n}\nvec3 EnvironmentBRDF( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness ) {\n\tvec2 fab = DFGApprox( normal, viewDir, roughness );\n\treturn specularColor * fab.x + specularF90 * fab.y;\n}\nvoid computeMultiscattering( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) {\n\tvec2 fab = DFGApprox( normal, viewDir, roughness );\n\tvec3 FssEss = specularColor * fab.x + specularF90 * fab.y;\n\tfloat Ess = fab.x + fab.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}\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.roughness;\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#ifdef USE_CLEARCOAT\n\t\tfloat dotNLcc = saturate( dot( geometry.clearcoatNormal, directLight.direction ) );\n\t\tvec3 ccIrradiance = dotNLcc * directLight.color;\n\t\tclearcoatSpecular += ccIrradiance * BRDF_GGX( directLight.direction, geometry.viewDir, geometry.clearcoatNormal, material.clearcoatF0, material.clearcoatF90, material.clearcoatRoughness );\n\t#endif\n\t#ifdef USE_SHEEN\n\t\tsheenSpecular += irradiance * BRDF_Sheen( directLight.direction, geometry.viewDir, geometry.normal, material.sheenColor, material.sheenRoughness );\n\t#endif\n\treflectedLight.directSpecular += irradiance * BRDF_GGX( directLight.direction, geometry.viewDir, geometry.normal, material.specularColor, material.specularF90, material.roughness );\n\treflectedLight.directDiffuse += irradiance * BRDF_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_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 USE_CLEARCOAT\n\t\tclearcoatSpecular += clearcoatRadiance * EnvironmentBRDF( geometry.clearcoatNormal, geometry.viewDir, material.clearcoatF0, material.clearcoatF90, material.clearcoatRoughness );\n\t#endif\n\t#ifdef USE_SHEEN\n\t\tsheenSpecular += irradiance * material.sheenColor * IBLSheenBRDF( geometry.normal, geometry.viewDir, material.sheenRoughness );\n\t#endif\n\tvec3 singleScattering = vec3( 0.0 );\n\tvec3 multiScattering = vec3( 0.0 );\n\tvec3 cosineWeightedIrradiance = irradiance * RECIPROCAL_PI;\n\tcomputeMultiscattering( geometry.normal, geometry.viewDir, material.specularColor, material.specularF90, material.roughness, singleScattering, multiScattering );\n\tvec3 diffuse = material.diffuseColor * ( 1.0 - ( singleScattering + multiScattering ) );\n\treflectedLight.indirectSpecular += 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}";
  8060. var lights_fragment_begin = "\nGeometricContext geometry;\ngeometry.position = - vViewPosition;\ngeometry.normal = normal;\ngeometry.viewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition );\n#ifdef USE_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\tgetPointLightInfo( 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\tgetSpotLightInfo( 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\tgetDirectionalLightInfo( 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.normal );\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.normal );\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";
  8061. var lights_fragment_maps = "#if defined( RE_IndirectDiffuse )\n\t#ifdef USE_LIGHTMAP\n\t\tvec4 lightMapTexel = texture2D( lightMap, vUv2 );\n\t\tvec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity;\n\t\tirradiance += lightMapIrradiance;\n\t#endif\n\t#if defined( USE_ENVMAP ) && defined( STANDARD ) && defined( ENVMAP_TYPE_CUBE_UV )\n\t\tiblIrradiance += getIBLIrradiance( geometry.normal );\n\t#endif\n#endif\n#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular )\n\tradiance += getIBLRadiance( geometry.viewDir, geometry.normal, material.roughness );\n\t#ifdef USE_CLEARCOAT\n\t\tclearcoatRadiance += getIBLRadiance( geometry.viewDir, geometry.clearcoatNormal, material.clearcoatRoughness );\n\t#endif\n#endif";
  8062. 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";
  8063. 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";
  8064. 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";
  8065. 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";
  8066. 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";
  8067. var map_fragment = "#ifdef USE_MAP\n\tvec4 sampledDiffuseColor = texture2D( map, vUv );\n\t#ifdef DECODE_VIDEO_TEXTURE\n\t\tsampledDiffuseColor = vec4( mix( pow( sampledDiffuseColor.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), sampledDiffuseColor.rgb * 0.0773993808, vec3( lessThanEqual( sampledDiffuseColor.rgb, vec3( 0.04045 ) ) ) ), sampledDiffuseColor.w );\n\t#endif\n\tdiffuseColor *= sampledDiffuseColor;\n#endif";
  8068. var map_pars_fragment = "#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif";
  8069. 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\tdiffuseColor *= texture2D( map, uv );\n#endif\n#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, uv ).g;\n#endif";
  8070. 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";
  8071. var metalnessmap_fragment = "float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n\tvec4 texelMetalness = texture2D( metalnessMap, vUv );\n\tmetalnessFactor *= texelMetalness.b;\n#endif";
  8072. var metalnessmap_pars_fragment = "#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif";
  8073. var morphcolor_vertex = "#if defined( USE_MORPHCOLORS ) && defined( MORPHTARGETS_TEXTURE )\n\tvColor *= morphTargetBaseInfluence;\n\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\t#if defined( USE_COLOR_ALPHA )\n\t\t\tif ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ) * morphTargetInfluences[ i ];\n\t\t#elif defined( USE_COLOR )\n\t\t\tif ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ).rgb * morphTargetInfluences[ i ];\n\t\t#endif\n\t}\n#endif";
  8074. var morphnormal_vertex = "#ifdef USE_MORPHNORMALS\n\tobjectNormal *= morphTargetBaseInfluence;\n\t#ifdef MORPHTARGETS_TEXTURE\n\t\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\t\tif ( morphTargetInfluences[ i ] != 0.0 ) objectNormal += getMorph( gl_VertexID, i, 1 ).xyz * morphTargetInfluences[ i ];\n\t\t}\n\t#else\n\t\tobjectNormal += morphNormal0 * morphTargetInfluences[ 0 ];\n\t\tobjectNormal += morphNormal1 * morphTargetInfluences[ 1 ];\n\t\tobjectNormal += morphNormal2 * morphTargetInfluences[ 2 ];\n\t\tobjectNormal += morphNormal3 * morphTargetInfluences[ 3 ];\n\t#endif\n#endif";
  8075. var morphtarget_pars_vertex = "#ifdef USE_MORPHTARGETS\n\tuniform float morphTargetBaseInfluence;\n\t#ifdef MORPHTARGETS_TEXTURE\n\t\tuniform float morphTargetInfluences[ MORPHTARGETS_COUNT ];\n\t\tuniform sampler2DArray morphTargetsTexture;\n\t\tuniform ivec2 morphTargetsTextureSize;\n\t\tvec4 getMorph( const in int vertexIndex, const in int morphTargetIndex, const in int offset ) {\n\t\t\tint texelIndex = vertexIndex * MORPHTARGETS_TEXTURE_STRIDE + offset;\n\t\t\tint y = texelIndex / morphTargetsTextureSize.x;\n\t\t\tint x = texelIndex - y * morphTargetsTextureSize.x;\n\t\t\tivec3 morphUV = ivec3( x, y, morphTargetIndex );\n\t\t\treturn texelFetch( morphTargetsTexture, morphUV, 0 );\n\t\t}\n\t#else\n\t\t#ifndef USE_MORPHNORMALS\n\t\t\tuniform float morphTargetInfluences[ 8 ];\n\t\t#else\n\t\t\tuniform float morphTargetInfluences[ 4 ];\n\t\t#endif\n\t#endif\n#endif";
  8076. var morphtarget_vertex = "#ifdef USE_MORPHTARGETS\n\ttransformed *= morphTargetBaseInfluence;\n\t#ifdef MORPHTARGETS_TEXTURE\n\t\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\t\tif ( morphTargetInfluences[ i ] != 0.0 ) transformed += getMorph( gl_VertexID, i, 0 ).xyz * morphTargetInfluences[ i ];\n\t\t}\n\t#else\n\t\ttransformed += morphTarget0 * morphTargetInfluences[ 0 ];\n\t\ttransformed += morphTarget1 * morphTargetInfluences[ 1 ];\n\t\ttransformed += morphTarget2 * morphTargetInfluences[ 2 ];\n\t\ttransformed += morphTarget3 * morphTargetInfluences[ 3 ];\n\t\t#ifndef USE_MORPHNORMALS\n\t\t\ttransformed += morphTarget4 * morphTargetInfluences[ 4 ];\n\t\t\ttransformed += morphTarget5 * morphTargetInfluences[ 5 ];\n\t\t\ttransformed += morphTarget6 * morphTargetInfluences[ 6 ];\n\t\t\ttransformed += morphTarget7 * morphTargetInfluences[ 7 ];\n\t\t#endif\n\t#endif\n#endif";
  8077. var normal_fragment_begin = "float faceDirection = gl_FrontFacing ? 1.0 : - 1.0;\n#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 * faceDirection;\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 * faceDirection;\n\t\t\tbitangent = bitangent * faceDirection;\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;";
  8078. 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 * faceDirection;\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, faceDirection );\n\t#endif\n#elif defined( USE_BUMPMAP )\n\tnormal = perturbNormalArb( - vViewPosition, normal, dHdxy_fwd(), faceDirection );\n#endif";
  8079. var normal_pars_fragment = "#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";
  8080. var normal_pars_vertex = "#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";
  8081. var normal_vertex = "#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";
  8082. 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, float faceDirection ) {\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\tvec3 N = surf_norm;\n\t\tvec3 q1perp = cross( q1, N );\n\t\tvec3 q0perp = cross( N, q0 );\n\t\tvec3 T = q1perp * st0.x + q0perp * st1.x;\n\t\tvec3 B = q1perp * st0.y + q0perp * st1.y;\n\t\tfloat det = max( dot( T, T ), dot( B, B ) );\n\t\tfloat scale = ( det == 0.0 ) ? 0.0 : faceDirection * inversesqrt( det );\n\t\treturn normalize( T * ( mapN.x * scale ) + B * ( mapN.y * scale ) + N * mapN.z );\n\t}\n#endif";
  8083. var clearcoat_normal_fragment_begin = "#ifdef USE_CLEARCOAT\n\tvec3 clearcoatNormal = geometryNormal;\n#endif";
  8084. 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, faceDirection );\n\t#endif\n#endif";
  8085. 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";
  8086. var output_fragment = "#ifdef OPAQUE\ndiffuseColor.a = 1.0;\n#endif\n#ifdef USE_TRANSMISSION\ndiffuseColor.a *= transmissionAlpha + 0.1;\n#endif\ngl_FragColor = vec4( outgoingLight, diffuseColor.a );";
  8087. 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}";
  8088. var premultiplied_alpha_fragment = "#ifdef PREMULTIPLIED_ALPHA\n\tgl_FragColor.rgb *= gl_FragColor.a;\n#endif";
  8089. 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;";
  8090. var dithering_fragment = "#ifdef DITHERING\n\tgl_FragColor.rgb = dithering( gl_FragColor.rgb );\n#endif";
  8091. 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";
  8092. var roughnessmap_fragment = "float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n\tvec4 texelRoughness = texture2D( roughnessMap, vUv );\n\troughnessFactor *= texelRoughness.g;\n#endif";
  8093. var roughnessmap_pars_fragment = "#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif";
  8094. 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";
  8095. 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";
  8096. 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";
  8097. 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}";
  8098. 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";
  8099. var skinning_pars_vertex = "#ifdef USE_SKINNING\n\tuniform mat4 bindMatrix;\n\tuniform mat4 bindMatrixInverse;\n\tuniform highp sampler2D boneTexture;\n\tuniform int boneTextureSize;\n\tmat4 getBoneMatrix( const in float i ) {\n\t\tfloat j = i * 4.0;\n\t\tfloat x = mod( j, float( boneTextureSize ) );\n\t\tfloat y = floor( j / float( boneTextureSize ) );\n\t\tfloat dx = 1.0 / float( boneTextureSize );\n\t\tfloat dy = 1.0 / float( boneTextureSize );\n\t\ty = dy * ( y + 0.5 );\n\t\tvec4 v1 = texture2D( boneTexture, vec2( dx * ( x + 0.5 ), y ) );\n\t\tvec4 v2 = texture2D( boneTexture, vec2( dx * ( x + 1.5 ), y ) );\n\t\tvec4 v3 = texture2D( boneTexture, vec2( dx * ( x + 2.5 ), y ) );\n\t\tvec4 v4 = texture2D( boneTexture, vec2( dx * ( x + 3.5 ), y ) );\n\t\tmat4 bone = mat4( v1, v2, v3, v4 );\n\t\treturn bone;\n\t}\n#endif";
  8100. 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";
  8101. 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";
  8102. 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";
  8103. var specularmap_pars_fragment = "#ifdef USE_SPECULARMAP\n\tuniform sampler2D specularMap;\n#endif";
  8104. var tonemapping_fragment = "#if defined( TONE_MAPPING )\n\tgl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif";
  8105. 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; }";
  8106. var transmission_fragment = "#ifdef USE_TRANSMISSION\n\tfloat transmissionAlpha = 1.0;\n\tfloat transmissionFactor = transmission;\n\tfloat thicknessFactor = thickness;\n\t#ifdef USE_TRANSMISSIONMAP\n\t\ttransmissionFactor *= texture2D( transmissionMap, vUv ).r;\n\t#endif\n\t#ifdef USE_THICKNESSMAP\n\t\tthicknessFactor *= texture2D( thicknessMap, vUv ).g;\n\t#endif\n\tvec3 pos = vWorldPosition;\n\tvec3 v = normalize( cameraPosition - pos );\n\tvec3 n = inverseTransformDirection( normal, viewMatrix );\n\tvec4 transmission = getIBLVolumeRefraction(\n\t\tn, v, roughnessFactor, material.diffuseColor, material.specularColor, material.specularF90,\n\t\tpos, modelMatrix, viewMatrix, projectionMatrix, ior, thicknessFactor,\n\t\tattenuationColor, attenuationDistance );\n\ttotalDiffuse = mix( totalDiffuse, transmission.rgb, transmissionFactor );\n\ttransmissionAlpha = mix( transmissionAlpha, transmission.a, transmissionFactor );\n#endif";
  8107. var transmission_pars_fragment = "#ifdef USE_TRANSMISSION\n\tuniform float transmission;\n\tuniform float thickness;\n\tuniform float attenuationDistance;\n\tuniform vec3 attenuationColor;\n\t#ifdef USE_TRANSMISSIONMAP\n\t\tuniform sampler2D transmissionMap;\n\t#endif\n\t#ifdef USE_THICKNESSMAP\n\t\tuniform sampler2D thicknessMap;\n\t#endif\n\tuniform vec2 transmissionSamplerSize;\n\tuniform sampler2D transmissionSamplerMap;\n\tuniform mat4 modelMatrix;\n\tuniform mat4 projectionMatrix;\n\tvarying vec3 vWorldPosition;\n\tvec3 getVolumeTransmissionRay( const in vec3 n, const in vec3 v, const in float thickness, const in float ior, const in mat4 modelMatrix ) {\n\t\tvec3 refractionVector = refract( - v, normalize( n ), 1.0 / ior );\n\t\tvec3 modelScale;\n\t\tmodelScale.x = length( vec3( modelMatrix[ 0 ].xyz ) );\n\t\tmodelScale.y = length( vec3( modelMatrix[ 1 ].xyz ) );\n\t\tmodelScale.z = length( vec3( modelMatrix[ 2 ].xyz ) );\n\t\treturn normalize( refractionVector ) * thickness * modelScale;\n\t}\n\tfloat applyIorToRoughness( const in float roughness, const in float ior ) {\n\t\treturn roughness * clamp( ior * 2.0 - 2.0, 0.0, 1.0 );\n\t}\n\tvec4 getTransmissionSample( const in vec2 fragCoord, const in float roughness, const in float ior ) {\n\t\tfloat framebufferLod = log2( transmissionSamplerSize.x ) * applyIorToRoughness( roughness, ior );\n\t\t#ifdef texture2DLodEXT\n\t\t\treturn texture2DLodEXT( transmissionSamplerMap, fragCoord.xy, framebufferLod );\n\t\t#else\n\t\t\treturn texture2D( transmissionSamplerMap, fragCoord.xy, framebufferLod );\n\t\t#endif\n\t}\n\tvec3 applyVolumeAttenuation( const in vec3 radiance, const in float transmissionDistance, const in vec3 attenuationColor, const in float attenuationDistance ) {\n\t\tif ( attenuationDistance == 0.0 ) {\n\t\t\treturn radiance;\n\t\t} else {\n\t\t\tvec3 attenuationCoefficient = -log( attenuationColor ) / attenuationDistance;\n\t\t\tvec3 transmittance = exp( - attenuationCoefficient * transmissionDistance );\t\t\treturn transmittance * radiance;\n\t\t}\n\t}\n\tvec4 getIBLVolumeRefraction( const in vec3 n, const in vec3 v, const in float roughness, const in vec3 diffuseColor,\n\t\tconst in vec3 specularColor, const in float specularF90, const in vec3 position, const in mat4 modelMatrix,\n\t\tconst in mat4 viewMatrix, const in mat4 projMatrix, const in float ior, const in float thickness,\n\t\tconst in vec3 attenuationColor, const in float attenuationDistance ) {\n\t\tvec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );\n\t\tvec3 refractedRayExit = position + transmissionRay;\n\t\tvec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 );\n\t\tvec2 refractionCoords = ndcPos.xy / ndcPos.w;\n\t\trefractionCoords += 1.0;\n\t\trefractionCoords /= 2.0;\n\t\tvec4 transmittedLight = getTransmissionSample( refractionCoords, roughness, ior );\n\t\tvec3 attenuatedColor = applyVolumeAttenuation( transmittedLight.rgb, length( transmissionRay ), attenuationColor, attenuationDistance );\n\t\tvec3 F = EnvironmentBRDF( n, v, specularColor, specularF90, roughness );\n\t\treturn vec4( ( 1.0 - F ) * attenuatedColor * diffuseColor, transmittedLight.a );\n\t}\n#endif";
  8108. var uv_pars_fragment = "#if ( defined( USE_UV ) && ! defined( UVS_VERTEX_ONLY ) )\n\tvarying vec2 vUv;\n#endif";
  8109. 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";
  8110. var uv_vertex = "#ifdef USE_UV\n\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n#endif";
  8111. var uv2_pars_fragment = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvarying vec2 vUv2;\n#endif";
  8112. 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";
  8113. var uv2_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvUv2 = ( uv2Transform * vec3( uv2, 1 ) ).xy;\n#endif";
  8114. var worldpos_vertex = "#if defined( USE_ENVMAP ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP ) || defined ( USE_TRANSMISSION )\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";
  8115. const vertex$g = "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}";
  8116. const fragment$g = "uniform sampler2D t2D;\nvarying vec2 vUv;\nvoid main() {\n\tgl_FragColor = texture2D( t2D, vUv );\n\t#ifdef DECODE_VIDEO_TEXTURE\n\t\tgl_FragColor = vec4( mix( pow( gl_FragColor.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), gl_FragColor.rgb * 0.0773993808, vec3( lessThanEqual( gl_FragColor.rgb, vec3( 0.04045 ) ) ) ), gl_FragColor.w );\n\t#endif\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n}";
  8117. const vertex$f = "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}";
  8118. const fragment$f = "#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}";
  8119. const vertex$e = "#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}";
  8120. const fragment$e = "#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 <alphatest_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}";
  8121. const vertex$d = "#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}";
  8122. const fragment$d = "#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 <alphatest_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}";
  8123. const vertex$c = "varying vec3 vWorldDirection;\n#include <common>\nvoid main() {\n\tvWorldDirection = transformDirection( position, modelMatrix );\n\t#include <begin_vertex>\n\t#include <project_vertex>\n}";
  8124. const fragment$c = "uniform sampler2D tEquirect;\nvarying vec3 vWorldDirection;\n#include <common>\nvoid main() {\n\tvec3 direction = normalize( vWorldDirection );\n\tvec2 sampleUV = equirectUv( direction );\n\tgl_FragColor = texture2D( tEquirect, sampleUV );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n}";
  8125. const vertex$b = "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 <morphcolor_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}";
  8126. const fragment$b = "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\t#include <output_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n}";
  8127. const vertex$a = "#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 <morphcolor_vertex>\n\t#if defined ( USE_ENVMAP ) || defined ( USE_SKINNING )\n\t\t#include <beginnormal_vertex>\n\t\t#include <morphnormal_vertex>\n\t\t#include <skinbase_vertex>\n\t\t#include <skinnormal_vertex>\n\t\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 <clipping_planes_vertex>\n\t#include <worldpos_vertex>\n\t#include <envmap_vertex>\n\t#include <fog_vertex>\n}";
  8128. const fragment$a = "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 <alphatest_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\tvec4 lightMapTexel = texture2D( lightMap, vUv2 );\n\t\treflectedLight.indirectDiffuse += lightMapTexel.rgb * lightMapIntensity * RECIPROCAL_PI;\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\t#include <output_fragment>\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}";
  8129. const vertex$9 = "#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 <morphcolor_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}";
  8130. const fragment$9 = "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 <alphatest_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_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_Lambert( diffuseColor.rgb ) * getShadowMask();\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\t#include <envmap_fragment>\n\t#include <output_fragment>\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}";
  8131. const vertex$8 = "#define MATCAP\nvarying vec3 vViewPosition;\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 <normal_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 <morphcolor_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 <normal_vertex>\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}";
  8132. const fragment$8 = "#define MATCAP\nuniform vec3 diffuse;\nuniform float opacity;\nuniform sampler2D matcap;\nvarying vec3 vViewPosition;\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 <alphatest_pars_fragment>\n#include <fog_pars_fragment>\n#include <normal_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#else\n\t\tvec4 matcapColor = vec4( vec3( mix( 0.2, 0.8, uv.y ) ), 1.0 );\n\t#endif\n\tvec3 outgoingLight = diffuseColor.rgb * matcapColor.rgb;\n\t#include <output_fragment>\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}";
  8133. const vertex$7 = "#define NORMAL\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP )\n\tvarying vec3 vViewPosition;\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <normal_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\t#include <normal_vertex>\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}";
  8134. const fragment$7 = "#define NORMAL\nuniform float opacity;\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP )\n\tvarying vec3 vViewPosition;\n#endif\n#include <packing>\n#include <uv_pars_fragment>\n#include <normal_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\t#ifdef OPAQUE\n\t\tgl_FragColor.a = 1.0;\n\t#endif\n}";
  8135. const vertex$6 = "#define PHONG\nvarying vec3 vViewPosition;\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 <normal_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 <morphcolor_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 <normal_vertex>\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}";
  8136. const fragment$6 = "#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 <alphatest_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 <normal_pars_fragment>\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\t#include <output_fragment>\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}";
  8137. const vertex$5 = "#define STANDARD\nvarying vec3 vViewPosition;\n#ifdef USE_TRANSMISSION\n\tvarying vec3 vWorldPosition;\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 <normal_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 <morphcolor_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 <normal_vertex>\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#ifdef USE_TRANSMISSION\n\tvWorldPosition = worldPosition.xyz;\n#endif\n}";
  8138. const fragment$5 = "#define STANDARD\n#ifdef PHYSICAL\n\t#define IOR\n\t#define SPECULAR\n#endif\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float roughness;\nuniform float metalness;\nuniform float opacity;\n#ifdef IOR\n\tuniform float ior;\n#endif\n#ifdef SPECULAR\n\tuniform float specularIntensity;\n\tuniform vec3 specularColor;\n\t#ifdef USE_SPECULARINTENSITYMAP\n\t\tuniform sampler2D specularIntensityMap;\n\t#endif\n\t#ifdef USE_SPECULARCOLORMAP\n\t\tuniform sampler2D specularColorMap;\n\t#endif\n#endif\n#ifdef USE_CLEARCOAT\n\tuniform float clearcoat;\n\tuniform float clearcoatRoughness;\n#endif\n#ifdef USE_SHEEN\n\tuniform vec3 sheenColor;\n\tuniform float sheenRoughness;\n\t#ifdef USE_SHEENCOLORMAP\n\t\tuniform sampler2D sheenColorMap;\n\t#endif\n\t#ifdef USE_SHEENROUGHNESSMAP\n\t\tuniform sampler2D sheenRoughnessMap;\n\t#endif\n#endif\nvarying vec3 vViewPosition;\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 <alphatest_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_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 <normal_pars_fragment>\n#include <lights_physical_pars_fragment>\n#include <transmission_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#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 <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 totalDiffuse = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse;\n\tvec3 totalSpecular = reflectedLight.directSpecular + reflectedLight.indirectSpecular;\n\t#include <transmission_fragment>\n\tvec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance;\n\t#ifdef USE_SHEEN\n\t\tfloat sheenEnergyComp = 1.0 - 0.157 * max3( material.sheenColor );\n\t\toutgoingLight = outgoingLight * sheenEnergyComp + sheenSpecular;\n\t#endif\n\t#ifdef USE_CLEARCOAT\n\t\tfloat dotNVcc = saturate( dot( geometry.clearcoatNormal, geometry.viewDir ) );\n\t\tvec3 Fcc = F_Schlick( material.clearcoatF0, material.clearcoatF90, dotNVcc );\n\t\toutgoingLight = outgoingLight * ( 1.0 - material.clearcoat * Fcc ) + clearcoatSpecular * material.clearcoat;\n\t#endif\n\t#include <output_fragment>\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}";
  8139. const vertex$4 = "#define TOON\nvarying vec3 vViewPosition;\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 <normal_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 <morphcolor_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 <normal_vertex>\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}";
  8140. const fragment$4 = "#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 <alphatest_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 <normal_pars_fragment>\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\t#include <output_fragment>\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}";
  8141. const vertex$3 = "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 <morphcolor_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}";
  8142. const fragment$3 = "uniform vec3 diffuse;\nuniform float opacity;\n#include <common>\n#include <color_pars_fragment>\n#include <map_particle_pars_fragment>\n#include <alphatest_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\t#include <output_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n}";
  8143. const vertex$2 = "#include <common>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\nvoid main() {\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 <worldpos_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}";
  8144. const fragment$2 = "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}";
  8145. const vertex$1 = "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}";
  8146. const fragment$1 = "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 <alphatest_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\t#include <output_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n}";
  8147. const ShaderChunk = {
  8148. alphamap_fragment: alphamap_fragment,
  8149. alphamap_pars_fragment: alphamap_pars_fragment,
  8150. alphatest_fragment: alphatest_fragment,
  8151. alphatest_pars_fragment: alphatest_pars_fragment,
  8152. aomap_fragment: aomap_fragment,
  8153. aomap_pars_fragment: aomap_pars_fragment,
  8154. begin_vertex: begin_vertex,
  8155. beginnormal_vertex: beginnormal_vertex,
  8156. bsdfs: bsdfs,
  8157. bumpmap_pars_fragment: bumpmap_pars_fragment,
  8158. clipping_planes_fragment: clipping_planes_fragment,
  8159. clipping_planes_pars_fragment: clipping_planes_pars_fragment,
  8160. clipping_planes_pars_vertex: clipping_planes_pars_vertex,
  8161. clipping_planes_vertex: clipping_planes_vertex,
  8162. color_fragment: color_fragment,
  8163. color_pars_fragment: color_pars_fragment,
  8164. color_pars_vertex: color_pars_vertex,
  8165. color_vertex: color_vertex,
  8166. common: common,
  8167. cube_uv_reflection_fragment: cube_uv_reflection_fragment,
  8168. defaultnormal_vertex: defaultnormal_vertex,
  8169. displacementmap_pars_vertex: displacementmap_pars_vertex,
  8170. displacementmap_vertex: displacementmap_vertex,
  8171. emissivemap_fragment: emissivemap_fragment,
  8172. emissivemap_pars_fragment: emissivemap_pars_fragment,
  8173. encodings_fragment: encodings_fragment,
  8174. encodings_pars_fragment: encodings_pars_fragment,
  8175. envmap_fragment: envmap_fragment,
  8176. envmap_common_pars_fragment: envmap_common_pars_fragment,
  8177. envmap_pars_fragment: envmap_pars_fragment,
  8178. envmap_pars_vertex: envmap_pars_vertex,
  8179. envmap_physical_pars_fragment: envmap_physical_pars_fragment,
  8180. envmap_vertex: envmap_vertex,
  8181. fog_vertex: fog_vertex,
  8182. fog_pars_vertex: fog_pars_vertex,
  8183. fog_fragment: fog_fragment,
  8184. fog_pars_fragment: fog_pars_fragment,
  8185. gradientmap_pars_fragment: gradientmap_pars_fragment,
  8186. lightmap_fragment: lightmap_fragment,
  8187. lightmap_pars_fragment: lightmap_pars_fragment,
  8188. lights_lambert_vertex: lights_lambert_vertex,
  8189. lights_pars_begin: lights_pars_begin,
  8190. lights_toon_fragment: lights_toon_fragment,
  8191. lights_toon_pars_fragment: lights_toon_pars_fragment,
  8192. lights_phong_fragment: lights_phong_fragment,
  8193. lights_phong_pars_fragment: lights_phong_pars_fragment,
  8194. lights_physical_fragment: lights_physical_fragment,
  8195. lights_physical_pars_fragment: lights_physical_pars_fragment,
  8196. lights_fragment_begin: lights_fragment_begin,
  8197. lights_fragment_maps: lights_fragment_maps,
  8198. lights_fragment_end: lights_fragment_end,
  8199. logdepthbuf_fragment: logdepthbuf_fragment,
  8200. logdepthbuf_pars_fragment: logdepthbuf_pars_fragment,
  8201. logdepthbuf_pars_vertex: logdepthbuf_pars_vertex,
  8202. logdepthbuf_vertex: logdepthbuf_vertex,
  8203. map_fragment: map_fragment,
  8204. map_pars_fragment: map_pars_fragment,
  8205. map_particle_fragment: map_particle_fragment,
  8206. map_particle_pars_fragment: map_particle_pars_fragment,
  8207. metalnessmap_fragment: metalnessmap_fragment,
  8208. metalnessmap_pars_fragment: metalnessmap_pars_fragment,
  8209. morphcolor_vertex: morphcolor_vertex,
  8210. morphnormal_vertex: morphnormal_vertex,
  8211. morphtarget_pars_vertex: morphtarget_pars_vertex,
  8212. morphtarget_vertex: morphtarget_vertex,
  8213. normal_fragment_begin: normal_fragment_begin,
  8214. normal_fragment_maps: normal_fragment_maps,
  8215. normal_pars_fragment: normal_pars_fragment,
  8216. normal_pars_vertex: normal_pars_vertex,
  8217. normal_vertex: normal_vertex,
  8218. normalmap_pars_fragment: normalmap_pars_fragment,
  8219. clearcoat_normal_fragment_begin: clearcoat_normal_fragment_begin,
  8220. clearcoat_normal_fragment_maps: clearcoat_normal_fragment_maps,
  8221. clearcoat_pars_fragment: clearcoat_pars_fragment,
  8222. output_fragment: output_fragment,
  8223. packing: packing,
  8224. premultiplied_alpha_fragment: premultiplied_alpha_fragment,
  8225. project_vertex: project_vertex,
  8226. dithering_fragment: dithering_fragment,
  8227. dithering_pars_fragment: dithering_pars_fragment,
  8228. roughnessmap_fragment: roughnessmap_fragment,
  8229. roughnessmap_pars_fragment: roughnessmap_pars_fragment,
  8230. shadowmap_pars_fragment: shadowmap_pars_fragment,
  8231. shadowmap_pars_vertex: shadowmap_pars_vertex,
  8232. shadowmap_vertex: shadowmap_vertex,
  8233. shadowmask_pars_fragment: shadowmask_pars_fragment,
  8234. skinbase_vertex: skinbase_vertex,
  8235. skinning_pars_vertex: skinning_pars_vertex,
  8236. skinning_vertex: skinning_vertex,
  8237. skinnormal_vertex: skinnormal_vertex,
  8238. specularmap_fragment: specularmap_fragment,
  8239. specularmap_pars_fragment: specularmap_pars_fragment,
  8240. tonemapping_fragment: tonemapping_fragment,
  8241. tonemapping_pars_fragment: tonemapping_pars_fragment,
  8242. transmission_fragment: transmission_fragment,
  8243. transmission_pars_fragment: transmission_pars_fragment,
  8244. uv_pars_fragment: uv_pars_fragment,
  8245. uv_pars_vertex: uv_pars_vertex,
  8246. uv_vertex: uv_vertex,
  8247. uv2_pars_fragment: uv2_pars_fragment,
  8248. uv2_pars_vertex: uv2_pars_vertex,
  8249. uv2_vertex: uv2_vertex,
  8250. worldpos_vertex: worldpos_vertex,
  8251. background_vert: vertex$g,
  8252. background_frag: fragment$g,
  8253. cube_vert: vertex$f,
  8254. cube_frag: fragment$f,
  8255. depth_vert: vertex$e,
  8256. depth_frag: fragment$e,
  8257. distanceRGBA_vert: vertex$d,
  8258. distanceRGBA_frag: fragment$d,
  8259. equirect_vert: vertex$c,
  8260. equirect_frag: fragment$c,
  8261. linedashed_vert: vertex$b,
  8262. linedashed_frag: fragment$b,
  8263. meshbasic_vert: vertex$a,
  8264. meshbasic_frag: fragment$a,
  8265. meshlambert_vert: vertex$9,
  8266. meshlambert_frag: fragment$9,
  8267. meshmatcap_vert: vertex$8,
  8268. meshmatcap_frag: fragment$8,
  8269. meshnormal_vert: vertex$7,
  8270. meshnormal_frag: fragment$7,
  8271. meshphong_vert: vertex$6,
  8272. meshphong_frag: fragment$6,
  8273. meshphysical_vert: vertex$5,
  8274. meshphysical_frag: fragment$5,
  8275. meshtoon_vert: vertex$4,
  8276. meshtoon_frag: fragment$4,
  8277. points_vert: vertex$3,
  8278. points_frag: fragment$3,
  8279. shadow_vert: vertex$2,
  8280. shadow_frag: fragment$2,
  8281. sprite_vert: vertex$1,
  8282. sprite_frag: fragment$1
  8283. };
  8284. /**
  8285. * Uniforms library for shared webgl shaders
  8286. */
  8287. const UniformsLib = {
  8288. common: {
  8289. diffuse: {
  8290. value: new Color(0xffffff)
  8291. },
  8292. opacity: {
  8293. value: 1.0
  8294. },
  8295. map: {
  8296. value: null
  8297. },
  8298. uvTransform: {
  8299. value: new Matrix3()
  8300. },
  8301. uv2Transform: {
  8302. value: new Matrix3()
  8303. },
  8304. alphaMap: {
  8305. value: null
  8306. },
  8307. alphaTest: {
  8308. value: 0
  8309. }
  8310. },
  8311. specularmap: {
  8312. specularMap: {
  8313. value: null
  8314. }
  8315. },
  8316. envmap: {
  8317. envMap: {
  8318. value: null
  8319. },
  8320. flipEnvMap: {
  8321. value: -1
  8322. },
  8323. reflectivity: {
  8324. value: 1.0
  8325. },
  8326. // basic, lambert, phong
  8327. ior: {
  8328. value: 1.5
  8329. },
  8330. // physical
  8331. refractionRatio: {
  8332. value: 0.98
  8333. } // basic, lambert, phong
  8334. },
  8335. aomap: {
  8336. aoMap: {
  8337. value: null
  8338. },
  8339. aoMapIntensity: {
  8340. value: 1
  8341. }
  8342. },
  8343. lightmap: {
  8344. lightMap: {
  8345. value: null
  8346. },
  8347. lightMapIntensity: {
  8348. value: 1
  8349. }
  8350. },
  8351. emissivemap: {
  8352. emissiveMap: {
  8353. value: null
  8354. }
  8355. },
  8356. bumpmap: {
  8357. bumpMap: {
  8358. value: null
  8359. },
  8360. bumpScale: {
  8361. value: 1
  8362. }
  8363. },
  8364. normalmap: {
  8365. normalMap: {
  8366. value: null
  8367. },
  8368. normalScale: {
  8369. value: new Vector2(1, 1)
  8370. }
  8371. },
  8372. displacementmap: {
  8373. displacementMap: {
  8374. value: null
  8375. },
  8376. displacementScale: {
  8377. value: 1
  8378. },
  8379. displacementBias: {
  8380. value: 0
  8381. }
  8382. },
  8383. roughnessmap: {
  8384. roughnessMap: {
  8385. value: null
  8386. }
  8387. },
  8388. metalnessmap: {
  8389. metalnessMap: {
  8390. value: null
  8391. }
  8392. },
  8393. gradientmap: {
  8394. gradientMap: {
  8395. value: null
  8396. }
  8397. },
  8398. fog: {
  8399. fogDensity: {
  8400. value: 0.00025
  8401. },
  8402. fogNear: {
  8403. value: 1
  8404. },
  8405. fogFar: {
  8406. value: 2000
  8407. },
  8408. fogColor: {
  8409. value: new Color(0xffffff)
  8410. }
  8411. },
  8412. lights: {
  8413. ambientLightColor: {
  8414. value: []
  8415. },
  8416. lightProbe: {
  8417. value: []
  8418. },
  8419. directionalLights: {
  8420. value: [],
  8421. properties: {
  8422. direction: {},
  8423. color: {}
  8424. }
  8425. },
  8426. directionalLightShadows: {
  8427. value: [],
  8428. properties: {
  8429. shadowBias: {},
  8430. shadowNormalBias: {},
  8431. shadowRadius: {},
  8432. shadowMapSize: {}
  8433. }
  8434. },
  8435. directionalShadowMap: {
  8436. value: []
  8437. },
  8438. directionalShadowMatrix: {
  8439. value: []
  8440. },
  8441. spotLights: {
  8442. value: [],
  8443. properties: {
  8444. color: {},
  8445. position: {},
  8446. direction: {},
  8447. distance: {},
  8448. coneCos: {},
  8449. penumbraCos: {},
  8450. decay: {}
  8451. }
  8452. },
  8453. spotLightShadows: {
  8454. value: [],
  8455. properties: {
  8456. shadowBias: {},
  8457. shadowNormalBias: {},
  8458. shadowRadius: {},
  8459. shadowMapSize: {}
  8460. }
  8461. },
  8462. spotShadowMap: {
  8463. value: []
  8464. },
  8465. spotShadowMatrix: {
  8466. value: []
  8467. },
  8468. pointLights: {
  8469. value: [],
  8470. properties: {
  8471. color: {},
  8472. position: {},
  8473. decay: {},
  8474. distance: {}
  8475. }
  8476. },
  8477. pointLightShadows: {
  8478. value: [],
  8479. properties: {
  8480. shadowBias: {},
  8481. shadowNormalBias: {},
  8482. shadowRadius: {},
  8483. shadowMapSize: {},
  8484. shadowCameraNear: {},
  8485. shadowCameraFar: {}
  8486. }
  8487. },
  8488. pointShadowMap: {
  8489. value: []
  8490. },
  8491. pointShadowMatrix: {
  8492. value: []
  8493. },
  8494. hemisphereLights: {
  8495. value: [],
  8496. properties: {
  8497. direction: {},
  8498. skyColor: {},
  8499. groundColor: {}
  8500. }
  8501. },
  8502. // TODO (abelnation): RectAreaLight BRDF data needs to be moved from example to main src
  8503. rectAreaLights: {
  8504. value: [],
  8505. properties: {
  8506. color: {},
  8507. position: {},
  8508. width: {},
  8509. height: {}
  8510. }
  8511. },
  8512. ltc_1: {
  8513. value: null
  8514. },
  8515. ltc_2: {
  8516. value: null
  8517. }
  8518. },
  8519. points: {
  8520. diffuse: {
  8521. value: new Color(0xffffff)
  8522. },
  8523. opacity: {
  8524. value: 1.0
  8525. },
  8526. size: {
  8527. value: 1.0
  8528. },
  8529. scale: {
  8530. value: 1.0
  8531. },
  8532. map: {
  8533. value: null
  8534. },
  8535. alphaMap: {
  8536. value: null
  8537. },
  8538. alphaTest: {
  8539. value: 0
  8540. },
  8541. uvTransform: {
  8542. value: new Matrix3()
  8543. }
  8544. },
  8545. sprite: {
  8546. diffuse: {
  8547. value: new Color(0xffffff)
  8548. },
  8549. opacity: {
  8550. value: 1.0
  8551. },
  8552. center: {
  8553. value: new Vector2(0.5, 0.5)
  8554. },
  8555. rotation: {
  8556. value: 0.0
  8557. },
  8558. map: {
  8559. value: null
  8560. },
  8561. alphaMap: {
  8562. value: null
  8563. },
  8564. alphaTest: {
  8565. value: 0
  8566. },
  8567. uvTransform: {
  8568. value: new Matrix3()
  8569. }
  8570. }
  8571. };
  8572. const ShaderLib = {
  8573. basic: {
  8574. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.specularmap, UniformsLib.envmap, UniformsLib.aomap, UniformsLib.lightmap, UniformsLib.fog]),
  8575. vertexShader: ShaderChunk.meshbasic_vert,
  8576. fragmentShader: ShaderChunk.meshbasic_frag
  8577. },
  8578. lambert: {
  8579. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.specularmap, UniformsLib.envmap, UniformsLib.aomap, UniformsLib.lightmap, UniformsLib.emissivemap, UniformsLib.fog, UniformsLib.lights, {
  8580. emissive: {
  8581. value: new Color(0x000000)
  8582. }
  8583. }]),
  8584. vertexShader: ShaderChunk.meshlambert_vert,
  8585. fragmentShader: ShaderChunk.meshlambert_frag
  8586. },
  8587. phong: {
  8588. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.specularmap, UniformsLib.envmap, UniformsLib.aomap, UniformsLib.lightmap, UniformsLib.emissivemap, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, UniformsLib.fog, UniformsLib.lights, {
  8589. emissive: {
  8590. value: new Color(0x000000)
  8591. },
  8592. specular: {
  8593. value: new Color(0x111111)
  8594. },
  8595. shininess: {
  8596. value: 30
  8597. }
  8598. }]),
  8599. vertexShader: ShaderChunk.meshphong_vert,
  8600. fragmentShader: ShaderChunk.meshphong_frag
  8601. },
  8602. standard: {
  8603. 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, {
  8604. emissive: {
  8605. value: new Color(0x000000)
  8606. },
  8607. roughness: {
  8608. value: 1.0
  8609. },
  8610. metalness: {
  8611. value: 0.0
  8612. },
  8613. envMapIntensity: {
  8614. value: 1
  8615. } // temporary
  8616. }]),
  8617. vertexShader: ShaderChunk.meshphysical_vert,
  8618. fragmentShader: ShaderChunk.meshphysical_frag
  8619. },
  8620. toon: {
  8621. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.aomap, UniformsLib.lightmap, UniformsLib.emissivemap, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, UniformsLib.gradientmap, UniformsLib.fog, UniformsLib.lights, {
  8622. emissive: {
  8623. value: new Color(0x000000)
  8624. }
  8625. }]),
  8626. vertexShader: ShaderChunk.meshtoon_vert,
  8627. fragmentShader: ShaderChunk.meshtoon_frag
  8628. },
  8629. matcap: {
  8630. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, UniformsLib.fog, {
  8631. matcap: {
  8632. value: null
  8633. }
  8634. }]),
  8635. vertexShader: ShaderChunk.meshmatcap_vert,
  8636. fragmentShader: ShaderChunk.meshmatcap_frag
  8637. },
  8638. points: {
  8639. uniforms: mergeUniforms([UniformsLib.points, UniformsLib.fog]),
  8640. vertexShader: ShaderChunk.points_vert,
  8641. fragmentShader: ShaderChunk.points_frag
  8642. },
  8643. dashed: {
  8644. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.fog, {
  8645. scale: {
  8646. value: 1
  8647. },
  8648. dashSize: {
  8649. value: 1
  8650. },
  8651. totalSize: {
  8652. value: 2
  8653. }
  8654. }]),
  8655. vertexShader: ShaderChunk.linedashed_vert,
  8656. fragmentShader: ShaderChunk.linedashed_frag
  8657. },
  8658. depth: {
  8659. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.displacementmap]),
  8660. vertexShader: ShaderChunk.depth_vert,
  8661. fragmentShader: ShaderChunk.depth_frag
  8662. },
  8663. normal: {
  8664. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.bumpmap, UniformsLib.normalmap, UniformsLib.displacementmap, {
  8665. opacity: {
  8666. value: 1.0
  8667. }
  8668. }]),
  8669. vertexShader: ShaderChunk.meshnormal_vert,
  8670. fragmentShader: ShaderChunk.meshnormal_frag
  8671. },
  8672. sprite: {
  8673. uniforms: mergeUniforms([UniformsLib.sprite, UniformsLib.fog]),
  8674. vertexShader: ShaderChunk.sprite_vert,
  8675. fragmentShader: ShaderChunk.sprite_frag
  8676. },
  8677. background: {
  8678. uniforms: {
  8679. uvTransform: {
  8680. value: new Matrix3()
  8681. },
  8682. t2D: {
  8683. value: null
  8684. }
  8685. },
  8686. vertexShader: ShaderChunk.background_vert,
  8687. fragmentShader: ShaderChunk.background_frag
  8688. },
  8689. /* -------------------------------------------------------------------------
  8690. // Cube map shader
  8691. ------------------------------------------------------------------------- */
  8692. cube: {
  8693. uniforms: mergeUniforms([UniformsLib.envmap, {
  8694. opacity: {
  8695. value: 1.0
  8696. }
  8697. }]),
  8698. vertexShader: ShaderChunk.cube_vert,
  8699. fragmentShader: ShaderChunk.cube_frag
  8700. },
  8701. equirect: {
  8702. uniforms: {
  8703. tEquirect: {
  8704. value: null
  8705. }
  8706. },
  8707. vertexShader: ShaderChunk.equirect_vert,
  8708. fragmentShader: ShaderChunk.equirect_frag
  8709. },
  8710. distanceRGBA: {
  8711. uniforms: mergeUniforms([UniformsLib.common, UniformsLib.displacementmap, {
  8712. referencePosition: {
  8713. value: new Vector3()
  8714. },
  8715. nearDistance: {
  8716. value: 1
  8717. },
  8718. farDistance: {
  8719. value: 1000
  8720. }
  8721. }]),
  8722. vertexShader: ShaderChunk.distanceRGBA_vert,
  8723. fragmentShader: ShaderChunk.distanceRGBA_frag
  8724. },
  8725. shadow: {
  8726. uniforms: mergeUniforms([UniformsLib.lights, UniformsLib.fog, {
  8727. color: {
  8728. value: new Color(0x00000)
  8729. },
  8730. opacity: {
  8731. value: 1.0
  8732. }
  8733. }]),
  8734. vertexShader: ShaderChunk.shadow_vert,
  8735. fragmentShader: ShaderChunk.shadow_frag
  8736. }
  8737. };
  8738. ShaderLib.physical = {
  8739. uniforms: mergeUniforms([ShaderLib.standard.uniforms, {
  8740. clearcoat: {
  8741. value: 0
  8742. },
  8743. clearcoatMap: {
  8744. value: null
  8745. },
  8746. clearcoatRoughness: {
  8747. value: 0
  8748. },
  8749. clearcoatRoughnessMap: {
  8750. value: null
  8751. },
  8752. clearcoatNormalScale: {
  8753. value: new Vector2(1, 1)
  8754. },
  8755. clearcoatNormalMap: {
  8756. value: null
  8757. },
  8758. sheen: {
  8759. value: 0
  8760. },
  8761. sheenColor: {
  8762. value: new Color(0x000000)
  8763. },
  8764. sheenColorMap: {
  8765. value: null
  8766. },
  8767. sheenRoughness: {
  8768. value: 1
  8769. },
  8770. sheenRoughnessMap: {
  8771. value: null
  8772. },
  8773. transmission: {
  8774. value: 0
  8775. },
  8776. transmissionMap: {
  8777. value: null
  8778. },
  8779. transmissionSamplerSize: {
  8780. value: new Vector2()
  8781. },
  8782. transmissionSamplerMap: {
  8783. value: null
  8784. },
  8785. thickness: {
  8786. value: 0
  8787. },
  8788. thicknessMap: {
  8789. value: null
  8790. },
  8791. attenuationDistance: {
  8792. value: 0
  8793. },
  8794. attenuationColor: {
  8795. value: new Color(0x000000)
  8796. },
  8797. specularIntensity: {
  8798. value: 1
  8799. },
  8800. specularIntensityMap: {
  8801. value: null
  8802. },
  8803. specularColor: {
  8804. value: new Color(1, 1, 1)
  8805. },
  8806. specularColorMap: {
  8807. value: null
  8808. }
  8809. }]),
  8810. vertexShader: ShaderChunk.meshphysical_vert,
  8811. fragmentShader: ShaderChunk.meshphysical_frag
  8812. };
  8813. function WebGLBackground(renderer, cubemaps, state, objects, alpha, premultipliedAlpha) {
  8814. const clearColor = new Color(0x000000);
  8815. let clearAlpha = alpha === true ? 0 : 1;
  8816. let planeMesh;
  8817. let boxMesh;
  8818. let currentBackground = null;
  8819. let currentBackgroundVersion = 0;
  8820. let currentTonemapping = null;
  8821. function render(renderList, scene) {
  8822. let forceClear = false;
  8823. let background = scene.isScene === true ? scene.background : null;
  8824. if (background && background.isTexture) {
  8825. background = cubemaps.get(background);
  8826. } // Ignore background in AR
  8827. // TODO: Reconsider this.
  8828. const xr = renderer.xr;
  8829. const session = xr.getSession && xr.getSession();
  8830. if (session && session.environmentBlendMode === 'additive') {
  8831. background = null;
  8832. }
  8833. if (background === null) {
  8834. setClear(clearColor, clearAlpha);
  8835. } else if (background && background.isColor) {
  8836. setClear(background, 1);
  8837. forceClear = true;
  8838. }
  8839. if (renderer.autoClear || forceClear) {
  8840. renderer.clear(renderer.autoClearColor, renderer.autoClearDepth, renderer.autoClearStencil);
  8841. }
  8842. if (background && (background.isCubeTexture || background.mapping === CubeUVReflectionMapping)) {
  8843. if (boxMesh === undefined) {
  8844. boxMesh = new Mesh(new BoxGeometry(1, 1, 1), new ShaderMaterial({
  8845. name: 'BackgroundCubeMaterial',
  8846. uniforms: cloneUniforms(ShaderLib.cube.uniforms),
  8847. vertexShader: ShaderLib.cube.vertexShader,
  8848. fragmentShader: ShaderLib.cube.fragmentShader,
  8849. side: BackSide,
  8850. depthTest: false,
  8851. depthWrite: false,
  8852. fog: false
  8853. }));
  8854. boxMesh.geometry.deleteAttribute('normal');
  8855. boxMesh.geometry.deleteAttribute('uv');
  8856. boxMesh.onBeforeRender = function (renderer, scene, camera) {
  8857. this.matrixWorld.copyPosition(camera.matrixWorld);
  8858. }; // enable code injection for non-built-in material
  8859. Object.defineProperty(boxMesh.material, 'envMap', {
  8860. get: function () {
  8861. return this.uniforms.envMap.value;
  8862. }
  8863. });
  8864. objects.update(boxMesh);
  8865. }
  8866. boxMesh.material.uniforms.envMap.value = background;
  8867. boxMesh.material.uniforms.flipEnvMap.value = background.isCubeTexture && background.isRenderTargetTexture === false ? -1 : 1;
  8868. if (currentBackground !== background || currentBackgroundVersion !== background.version || currentTonemapping !== renderer.toneMapping) {
  8869. boxMesh.material.needsUpdate = true;
  8870. currentBackground = background;
  8871. currentBackgroundVersion = background.version;
  8872. currentTonemapping = renderer.toneMapping;
  8873. }
  8874. boxMesh.layers.enableAll(); // push to the pre-sorted opaque render list
  8875. renderList.unshift(boxMesh, boxMesh.geometry, boxMesh.material, 0, 0, null);
  8876. } else if (background && background.isTexture) {
  8877. if (planeMesh === undefined) {
  8878. planeMesh = new Mesh(new PlaneGeometry(2, 2), new ShaderMaterial({
  8879. name: 'BackgroundMaterial',
  8880. uniforms: cloneUniforms(ShaderLib.background.uniforms),
  8881. vertexShader: ShaderLib.background.vertexShader,
  8882. fragmentShader: ShaderLib.background.fragmentShader,
  8883. side: FrontSide,
  8884. depthTest: false,
  8885. depthWrite: false,
  8886. fog: false
  8887. }));
  8888. planeMesh.geometry.deleteAttribute('normal'); // enable code injection for non-built-in material
  8889. Object.defineProperty(planeMesh.material, 'map', {
  8890. get: function () {
  8891. return this.uniforms.t2D.value;
  8892. }
  8893. });
  8894. objects.update(planeMesh);
  8895. }
  8896. planeMesh.material.uniforms.t2D.value = background;
  8897. if (background.matrixAutoUpdate === true) {
  8898. background.updateMatrix();
  8899. }
  8900. planeMesh.material.uniforms.uvTransform.value.copy(background.matrix);
  8901. if (currentBackground !== background || currentBackgroundVersion !== background.version || currentTonemapping !== renderer.toneMapping) {
  8902. planeMesh.material.needsUpdate = true;
  8903. currentBackground = background;
  8904. currentBackgroundVersion = background.version;
  8905. currentTonemapping = renderer.toneMapping;
  8906. }
  8907. planeMesh.layers.enableAll(); // push to the pre-sorted opaque render list
  8908. renderList.unshift(planeMesh, planeMesh.geometry, planeMesh.material, 0, 0, null);
  8909. }
  8910. }
  8911. function setClear(color, alpha) {
  8912. state.buffers.color.setClear(color.r, color.g, color.b, alpha, premultipliedAlpha);
  8913. }
  8914. return {
  8915. getClearColor: function () {
  8916. return clearColor;
  8917. },
  8918. setClearColor: function (color, alpha = 1) {
  8919. clearColor.set(color);
  8920. clearAlpha = alpha;
  8921. setClear(clearColor, clearAlpha);
  8922. },
  8923. getClearAlpha: function () {
  8924. return clearAlpha;
  8925. },
  8926. setClearAlpha: function (alpha) {
  8927. clearAlpha = alpha;
  8928. setClear(clearColor, clearAlpha);
  8929. },
  8930. render: render
  8931. };
  8932. }
  8933. function WebGLBindingStates(gl, extensions, attributes, capabilities) {
  8934. const maxVertexAttributes = gl.getParameter(gl.MAX_VERTEX_ATTRIBS);
  8935. const extension = capabilities.isWebGL2 ? null : extensions.get('OES_vertex_array_object');
  8936. const vaoAvailable = capabilities.isWebGL2 || extension !== null;
  8937. const bindingStates = {};
  8938. const defaultState = createBindingState(null);
  8939. let currentState = defaultState;
  8940. let forceUpdate = false;
  8941. function setup(object, material, program, geometry, index) {
  8942. let updateBuffers = false;
  8943. if (vaoAvailable) {
  8944. const state = getBindingState(geometry, program, material);
  8945. if (currentState !== state) {
  8946. currentState = state;
  8947. bindVertexArrayObject(currentState.object);
  8948. }
  8949. updateBuffers = needsUpdate(object, geometry, program, index);
  8950. if (updateBuffers) saveCache(object, geometry, program, index);
  8951. } else {
  8952. const wireframe = material.wireframe === true;
  8953. if (currentState.geometry !== geometry.id || currentState.program !== program.id || currentState.wireframe !== wireframe) {
  8954. currentState.geometry = geometry.id;
  8955. currentState.program = program.id;
  8956. currentState.wireframe = wireframe;
  8957. updateBuffers = true;
  8958. }
  8959. }
  8960. if (index !== null) {
  8961. attributes.update(index, gl.ELEMENT_ARRAY_BUFFER);
  8962. }
  8963. if (updateBuffers || forceUpdate) {
  8964. forceUpdate = false;
  8965. setupVertexAttributes(object, material, program, geometry);
  8966. if (index !== null) {
  8967. gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, attributes.get(index).buffer);
  8968. }
  8969. }
  8970. }
  8971. function createVertexArrayObject() {
  8972. if (capabilities.isWebGL2) return gl.createVertexArray();
  8973. return extension.createVertexArrayOES();
  8974. }
  8975. function bindVertexArrayObject(vao) {
  8976. if (capabilities.isWebGL2) return gl.bindVertexArray(vao);
  8977. return extension.bindVertexArrayOES(vao);
  8978. }
  8979. function deleteVertexArrayObject(vao) {
  8980. if (capabilities.isWebGL2) return gl.deleteVertexArray(vao);
  8981. return extension.deleteVertexArrayOES(vao);
  8982. }
  8983. function getBindingState(geometry, program, material) {
  8984. const wireframe = material.wireframe === true;
  8985. let programMap = bindingStates[geometry.id];
  8986. if (programMap === undefined) {
  8987. programMap = {};
  8988. bindingStates[geometry.id] = programMap;
  8989. }
  8990. let stateMap = programMap[program.id];
  8991. if (stateMap === undefined) {
  8992. stateMap = {};
  8993. programMap[program.id] = stateMap;
  8994. }
  8995. let state = stateMap[wireframe];
  8996. if (state === undefined) {
  8997. state = createBindingState(createVertexArrayObject());
  8998. stateMap[wireframe] = state;
  8999. }
  9000. return state;
  9001. }
  9002. function createBindingState(vao) {
  9003. const newAttributes = [];
  9004. const enabledAttributes = [];
  9005. const attributeDivisors = [];
  9006. for (let i = 0; i < maxVertexAttributes; i++) {
  9007. newAttributes[i] = 0;
  9008. enabledAttributes[i] = 0;
  9009. attributeDivisors[i] = 0;
  9010. }
  9011. return {
  9012. // for backward compatibility on non-VAO support browser
  9013. geometry: null,
  9014. program: null,
  9015. wireframe: false,
  9016. newAttributes: newAttributes,
  9017. enabledAttributes: enabledAttributes,
  9018. attributeDivisors: attributeDivisors,
  9019. object: vao,
  9020. attributes: {},
  9021. index: null
  9022. };
  9023. }
  9024. function needsUpdate(object, geometry, program, index) {
  9025. const cachedAttributes = currentState.attributes;
  9026. const geometryAttributes = geometry.attributes;
  9027. let attributesNum = 0;
  9028. const programAttributes = program.getAttributes();
  9029. for (const name in programAttributes) {
  9030. const programAttribute = programAttributes[name];
  9031. if (programAttribute.location >= 0) {
  9032. const cachedAttribute = cachedAttributes[name];
  9033. let geometryAttribute = geometryAttributes[name];
  9034. if (geometryAttribute === undefined) {
  9035. if (name === 'instanceMatrix' && object.instanceMatrix) geometryAttribute = object.instanceMatrix;
  9036. if (name === 'instanceColor' && object.instanceColor) geometryAttribute = object.instanceColor;
  9037. }
  9038. if (cachedAttribute === undefined) return true;
  9039. if (cachedAttribute.attribute !== geometryAttribute) return true;
  9040. if (geometryAttribute && cachedAttribute.data !== geometryAttribute.data) return true;
  9041. attributesNum++;
  9042. }
  9043. }
  9044. if (currentState.attributesNum !== attributesNum) return true;
  9045. if (currentState.index !== index) return true;
  9046. return false;
  9047. }
  9048. function saveCache(object, geometry, program, index) {
  9049. const cache = {};
  9050. const attributes = geometry.attributes;
  9051. let attributesNum = 0;
  9052. const programAttributes = program.getAttributes();
  9053. for (const name in programAttributes) {
  9054. const programAttribute = programAttributes[name];
  9055. if (programAttribute.location >= 0) {
  9056. let attribute = attributes[name];
  9057. if (attribute === undefined) {
  9058. if (name === 'instanceMatrix' && object.instanceMatrix) attribute = object.instanceMatrix;
  9059. if (name === 'instanceColor' && object.instanceColor) attribute = object.instanceColor;
  9060. }
  9061. const data = {};
  9062. data.attribute = attribute;
  9063. if (attribute && attribute.data) {
  9064. data.data = attribute.data;
  9065. }
  9066. cache[name] = data;
  9067. attributesNum++;
  9068. }
  9069. }
  9070. currentState.attributes = cache;
  9071. currentState.attributesNum = attributesNum;
  9072. currentState.index = index;
  9073. }
  9074. function initAttributes() {
  9075. const newAttributes = currentState.newAttributes;
  9076. for (let i = 0, il = newAttributes.length; i < il; i++) {
  9077. newAttributes[i] = 0;
  9078. }
  9079. }
  9080. function enableAttribute(attribute) {
  9081. enableAttributeAndDivisor(attribute, 0);
  9082. }
  9083. function enableAttributeAndDivisor(attribute, meshPerAttribute) {
  9084. const newAttributes = currentState.newAttributes;
  9085. const enabledAttributes = currentState.enabledAttributes;
  9086. const attributeDivisors = currentState.attributeDivisors;
  9087. newAttributes[attribute] = 1;
  9088. if (enabledAttributes[attribute] === 0) {
  9089. gl.enableVertexAttribArray(attribute);
  9090. enabledAttributes[attribute] = 1;
  9091. }
  9092. if (attributeDivisors[attribute] !== meshPerAttribute) {
  9093. const extension = capabilities.isWebGL2 ? gl : extensions.get('ANGLE_instanced_arrays');
  9094. extension[capabilities.isWebGL2 ? 'vertexAttribDivisor' : 'vertexAttribDivisorANGLE'](attribute, meshPerAttribute);
  9095. attributeDivisors[attribute] = meshPerAttribute;
  9096. }
  9097. }
  9098. function disableUnusedAttributes() {
  9099. const newAttributes = currentState.newAttributes;
  9100. const enabledAttributes = currentState.enabledAttributes;
  9101. for (let i = 0, il = enabledAttributes.length; i < il; i++) {
  9102. if (enabledAttributes[i] !== newAttributes[i]) {
  9103. gl.disableVertexAttribArray(i);
  9104. enabledAttributes[i] = 0;
  9105. }
  9106. }
  9107. }
  9108. function vertexAttribPointer(index, size, type, normalized, stride, offset) {
  9109. if (capabilities.isWebGL2 === true && (type === gl.INT || type === gl.UNSIGNED_INT)) {
  9110. gl.vertexAttribIPointer(index, size, type, stride, offset);
  9111. } else {
  9112. gl.vertexAttribPointer(index, size, type, normalized, stride, offset);
  9113. }
  9114. }
  9115. function setupVertexAttributes(object, material, program, geometry) {
  9116. if (capabilities.isWebGL2 === false && (object.isInstancedMesh || geometry.isInstancedBufferGeometry)) {
  9117. if (extensions.get('ANGLE_instanced_arrays') === null) return;
  9118. }
  9119. initAttributes();
  9120. const geometryAttributes = geometry.attributes;
  9121. const programAttributes = program.getAttributes();
  9122. const materialDefaultAttributeValues = material.defaultAttributeValues;
  9123. for (const name in programAttributes) {
  9124. const programAttribute = programAttributes[name];
  9125. if (programAttribute.location >= 0) {
  9126. let geometryAttribute = geometryAttributes[name];
  9127. if (geometryAttribute === undefined) {
  9128. if (name === 'instanceMatrix' && object.instanceMatrix) geometryAttribute = object.instanceMatrix;
  9129. if (name === 'instanceColor' && object.instanceColor) geometryAttribute = object.instanceColor;
  9130. }
  9131. if (geometryAttribute !== undefined) {
  9132. const normalized = geometryAttribute.normalized;
  9133. const size = geometryAttribute.itemSize;
  9134. const attribute = attributes.get(geometryAttribute); // TODO Attribute may not be available on context restore
  9135. if (attribute === undefined) continue;
  9136. const buffer = attribute.buffer;
  9137. const type = attribute.type;
  9138. const bytesPerElement = attribute.bytesPerElement;
  9139. if (geometryAttribute.isInterleavedBufferAttribute) {
  9140. const data = geometryAttribute.data;
  9141. const stride = data.stride;
  9142. const offset = geometryAttribute.offset;
  9143. if (data.isInstancedInterleavedBuffer) {
  9144. for (let i = 0; i < programAttribute.locationSize; i++) {
  9145. enableAttributeAndDivisor(programAttribute.location + i, data.meshPerAttribute);
  9146. }
  9147. if (object.isInstancedMesh !== true && geometry._maxInstanceCount === undefined) {
  9148. geometry._maxInstanceCount = data.meshPerAttribute * data.count;
  9149. }
  9150. } else {
  9151. for (let i = 0; i < programAttribute.locationSize; i++) {
  9152. enableAttribute(programAttribute.location + i);
  9153. }
  9154. }
  9155. gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
  9156. for (let i = 0; i < programAttribute.locationSize; i++) {
  9157. vertexAttribPointer(programAttribute.location + i, size / programAttribute.locationSize, type, normalized, stride * bytesPerElement, (offset + size / programAttribute.locationSize * i) * bytesPerElement);
  9158. }
  9159. } else {
  9160. if (geometryAttribute.isInstancedBufferAttribute) {
  9161. for (let i = 0; i < programAttribute.locationSize; i++) {
  9162. enableAttributeAndDivisor(programAttribute.location + i, geometryAttribute.meshPerAttribute);
  9163. }
  9164. if (object.isInstancedMesh !== true && geometry._maxInstanceCount === undefined) {
  9165. geometry._maxInstanceCount = geometryAttribute.meshPerAttribute * geometryAttribute.count;
  9166. }
  9167. } else {
  9168. for (let i = 0; i < programAttribute.locationSize; i++) {
  9169. enableAttribute(programAttribute.location + i);
  9170. }
  9171. }
  9172. gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
  9173. for (let i = 0; i < programAttribute.locationSize; i++) {
  9174. vertexAttribPointer(programAttribute.location + i, size / programAttribute.locationSize, type, normalized, size * bytesPerElement, size / programAttribute.locationSize * i * bytesPerElement);
  9175. }
  9176. }
  9177. } else if (materialDefaultAttributeValues !== undefined) {
  9178. const value = materialDefaultAttributeValues[name];
  9179. if (value !== undefined) {
  9180. switch (value.length) {
  9181. case 2:
  9182. gl.vertexAttrib2fv(programAttribute.location, value);
  9183. break;
  9184. case 3:
  9185. gl.vertexAttrib3fv(programAttribute.location, value);
  9186. break;
  9187. case 4:
  9188. gl.vertexAttrib4fv(programAttribute.location, value);
  9189. break;
  9190. default:
  9191. gl.vertexAttrib1fv(programAttribute.location, value);
  9192. }
  9193. }
  9194. }
  9195. }
  9196. }
  9197. disableUnusedAttributes();
  9198. }
  9199. function dispose() {
  9200. reset();
  9201. for (const geometryId in bindingStates) {
  9202. const programMap = bindingStates[geometryId];
  9203. for (const programId in programMap) {
  9204. const stateMap = programMap[programId];
  9205. for (const wireframe in stateMap) {
  9206. deleteVertexArrayObject(stateMap[wireframe].object);
  9207. delete stateMap[wireframe];
  9208. }
  9209. delete programMap[programId];
  9210. }
  9211. delete bindingStates[geometryId];
  9212. }
  9213. }
  9214. function releaseStatesOfGeometry(geometry) {
  9215. if (bindingStates[geometry.id] === undefined) return;
  9216. const programMap = bindingStates[geometry.id];
  9217. for (const programId in programMap) {
  9218. const stateMap = programMap[programId];
  9219. for (const wireframe in stateMap) {
  9220. deleteVertexArrayObject(stateMap[wireframe].object);
  9221. delete stateMap[wireframe];
  9222. }
  9223. delete programMap[programId];
  9224. }
  9225. delete bindingStates[geometry.id];
  9226. }
  9227. function releaseStatesOfProgram(program) {
  9228. for (const geometryId in bindingStates) {
  9229. const programMap = bindingStates[geometryId];
  9230. if (programMap[program.id] === undefined) continue;
  9231. const stateMap = programMap[program.id];
  9232. for (const wireframe in stateMap) {
  9233. deleteVertexArrayObject(stateMap[wireframe].object);
  9234. delete stateMap[wireframe];
  9235. }
  9236. delete programMap[program.id];
  9237. }
  9238. }
  9239. function reset() {
  9240. resetDefaultState();
  9241. forceUpdate = true;
  9242. if (currentState === defaultState) return;
  9243. currentState = defaultState;
  9244. bindVertexArrayObject(currentState.object);
  9245. } // for backward-compatibility
  9246. function resetDefaultState() {
  9247. defaultState.geometry = null;
  9248. defaultState.program = null;
  9249. defaultState.wireframe = false;
  9250. }
  9251. return {
  9252. setup: setup,
  9253. reset: reset,
  9254. resetDefaultState: resetDefaultState,
  9255. dispose: dispose,
  9256. releaseStatesOfGeometry: releaseStatesOfGeometry,
  9257. releaseStatesOfProgram: releaseStatesOfProgram,
  9258. initAttributes: initAttributes,
  9259. enableAttribute: enableAttribute,
  9260. disableUnusedAttributes: disableUnusedAttributes
  9261. };
  9262. }
  9263. function WebGLBufferRenderer(gl, extensions, info, capabilities) {
  9264. const isWebGL2 = capabilities.isWebGL2;
  9265. let mode;
  9266. function setMode(value) {
  9267. mode = value;
  9268. }
  9269. function render(start, count) {
  9270. gl.drawArrays(mode, start, count);
  9271. info.update(count, mode, 1);
  9272. }
  9273. function renderInstances(start, count, primcount) {
  9274. if (primcount === 0) return;
  9275. let extension, methodName;
  9276. if (isWebGL2) {
  9277. extension = gl;
  9278. methodName = 'drawArraysInstanced';
  9279. } else {
  9280. extension = extensions.get('ANGLE_instanced_arrays');
  9281. methodName = 'drawArraysInstancedANGLE';
  9282. if (extension === null) {
  9283. console.error('THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.');
  9284. return;
  9285. }
  9286. }
  9287. extension[methodName](mode, start, count, primcount);
  9288. info.update(count, mode, primcount);
  9289. } //
  9290. this.setMode = setMode;
  9291. this.render = render;
  9292. this.renderInstances = renderInstances;
  9293. }
  9294. function WebGLCapabilities(gl, extensions, parameters) {
  9295. let maxAnisotropy;
  9296. function getMaxAnisotropy() {
  9297. if (maxAnisotropy !== undefined) return maxAnisotropy;
  9298. if (extensions.has('EXT_texture_filter_anisotropic') === true) {
  9299. const extension = extensions.get('EXT_texture_filter_anisotropic');
  9300. maxAnisotropy = gl.getParameter(extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT);
  9301. } else {
  9302. maxAnisotropy = 0;
  9303. }
  9304. return maxAnisotropy;
  9305. }
  9306. function getMaxPrecision(precision) {
  9307. if (precision === 'highp') {
  9308. if (gl.getShaderPrecisionFormat(gl.VERTEX_SHADER, gl.HIGH_FLOAT).precision > 0 && gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.HIGH_FLOAT).precision > 0) {
  9309. return 'highp';
  9310. }
  9311. precision = 'mediump';
  9312. }
  9313. if (precision === 'mediump') {
  9314. if (gl.getShaderPrecisionFormat(gl.VERTEX_SHADER, gl.MEDIUM_FLOAT).precision > 0 && gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.MEDIUM_FLOAT).precision > 0) {
  9315. return 'mediump';
  9316. }
  9317. }
  9318. return 'lowp';
  9319. }
  9320. const isWebGL2 = typeof WebGL2RenderingContext !== 'undefined' && gl instanceof WebGL2RenderingContext || typeof WebGL2ComputeRenderingContext !== 'undefined' && gl instanceof WebGL2ComputeRenderingContext;
  9321. let precision = parameters.precision !== undefined ? parameters.precision : 'highp';
  9322. const maxPrecision = getMaxPrecision(precision);
  9323. if (maxPrecision !== precision) {
  9324. console.warn('THREE.WebGLRenderer:', precision, 'not supported, using', maxPrecision, 'instead.');
  9325. precision = maxPrecision;
  9326. }
  9327. const drawBuffers = isWebGL2 || extensions.has('WEBGL_draw_buffers');
  9328. const logarithmicDepthBuffer = parameters.logarithmicDepthBuffer === true;
  9329. const maxTextures = gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS);
  9330. const maxVertexTextures = gl.getParameter(gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  9331. const maxTextureSize = gl.getParameter(gl.MAX_TEXTURE_SIZE);
  9332. const maxCubemapSize = gl.getParameter(gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  9333. const maxAttributes = gl.getParameter(gl.MAX_VERTEX_ATTRIBS);
  9334. const maxVertexUniforms = gl.getParameter(gl.MAX_VERTEX_UNIFORM_VECTORS);
  9335. const maxVaryings = gl.getParameter(gl.MAX_VARYING_VECTORS);
  9336. const maxFragmentUniforms = gl.getParameter(gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  9337. const vertexTextures = maxVertexTextures > 0;
  9338. const floatFragmentTextures = isWebGL2 || extensions.has('OES_texture_float');
  9339. const floatVertexTextures = vertexTextures && floatFragmentTextures;
  9340. const maxSamples = isWebGL2 ? gl.getParameter(gl.MAX_SAMPLES) : 0;
  9341. return {
  9342. isWebGL2: isWebGL2,
  9343. drawBuffers: drawBuffers,
  9344. getMaxAnisotropy: getMaxAnisotropy,
  9345. getMaxPrecision: getMaxPrecision,
  9346. precision: precision,
  9347. logarithmicDepthBuffer: logarithmicDepthBuffer,
  9348. maxTextures: maxTextures,
  9349. maxVertexTextures: maxVertexTextures,
  9350. maxTextureSize: maxTextureSize,
  9351. maxCubemapSize: maxCubemapSize,
  9352. maxAttributes: maxAttributes,
  9353. maxVertexUniforms: maxVertexUniforms,
  9354. maxVaryings: maxVaryings,
  9355. maxFragmentUniforms: maxFragmentUniforms,
  9356. vertexTextures: vertexTextures,
  9357. floatFragmentTextures: floatFragmentTextures,
  9358. floatVertexTextures: floatVertexTextures,
  9359. maxSamples: maxSamples
  9360. };
  9361. }
  9362. function WebGLClipping(properties) {
  9363. const scope = this;
  9364. let globalState = null,
  9365. numGlobalPlanes = 0,
  9366. localClippingEnabled = false,
  9367. renderingShadows = false;
  9368. const plane = new Plane(),
  9369. viewNormalMatrix = new Matrix3(),
  9370. uniform = {
  9371. value: null,
  9372. needsUpdate: false
  9373. };
  9374. this.uniform = uniform;
  9375. this.numPlanes = 0;
  9376. this.numIntersection = 0;
  9377. this.init = function (planes, enableLocalClipping, camera) {
  9378. const enabled = planes.length !== 0 || enableLocalClipping || // enable state of previous frame - the clipping code has to
  9379. // run another frame in order to reset the state:
  9380. numGlobalPlanes !== 0 || localClippingEnabled;
  9381. localClippingEnabled = enableLocalClipping;
  9382. globalState = projectPlanes(planes, camera, 0);
  9383. numGlobalPlanes = planes.length;
  9384. return enabled;
  9385. };
  9386. this.beginShadows = function () {
  9387. renderingShadows = true;
  9388. projectPlanes(null);
  9389. };
  9390. this.endShadows = function () {
  9391. renderingShadows = false;
  9392. resetGlobalState();
  9393. };
  9394. this.setState = function (material, camera, useCache) {
  9395. const planes = material.clippingPlanes,
  9396. clipIntersection = material.clipIntersection,
  9397. clipShadows = material.clipShadows;
  9398. const materialProperties = properties.get(material);
  9399. if (!localClippingEnabled || planes === null || planes.length === 0 || renderingShadows && !clipShadows) {
  9400. // there's no local clipping
  9401. if (renderingShadows) {
  9402. // there's no global clipping
  9403. projectPlanes(null);
  9404. } else {
  9405. resetGlobalState();
  9406. }
  9407. } else {
  9408. const nGlobal = renderingShadows ? 0 : numGlobalPlanes,
  9409. lGlobal = nGlobal * 4;
  9410. let dstArray = materialProperties.clippingState || null;
  9411. uniform.value = dstArray; // ensure unique state
  9412. dstArray = projectPlanes(planes, camera, lGlobal, useCache);
  9413. for (let i = 0; i !== lGlobal; ++i) {
  9414. dstArray[i] = globalState[i];
  9415. }
  9416. materialProperties.clippingState = dstArray;
  9417. this.numIntersection = clipIntersection ? this.numPlanes : 0;
  9418. this.numPlanes += nGlobal;
  9419. }
  9420. };
  9421. function resetGlobalState() {
  9422. if (uniform.value !== globalState) {
  9423. uniform.value = globalState;
  9424. uniform.needsUpdate = numGlobalPlanes > 0;
  9425. }
  9426. scope.numPlanes = numGlobalPlanes;
  9427. scope.numIntersection = 0;
  9428. }
  9429. function projectPlanes(planes, camera, dstOffset, skipTransform) {
  9430. const nPlanes = planes !== null ? planes.length : 0;
  9431. let dstArray = null;
  9432. if (nPlanes !== 0) {
  9433. dstArray = uniform.value;
  9434. if (skipTransform !== true || dstArray === null) {
  9435. const flatSize = dstOffset + nPlanes * 4,
  9436. viewMatrix = camera.matrixWorldInverse;
  9437. viewNormalMatrix.getNormalMatrix(viewMatrix);
  9438. if (dstArray === null || dstArray.length < flatSize) {
  9439. dstArray = new Float32Array(flatSize);
  9440. }
  9441. for (let i = 0, i4 = dstOffset; i !== nPlanes; ++i, i4 += 4) {
  9442. plane.copy(planes[i]).applyMatrix4(viewMatrix, viewNormalMatrix);
  9443. plane.normal.toArray(dstArray, i4);
  9444. dstArray[i4 + 3] = plane.constant;
  9445. }
  9446. }
  9447. uniform.value = dstArray;
  9448. uniform.needsUpdate = true;
  9449. }
  9450. scope.numPlanes = nPlanes;
  9451. scope.numIntersection = 0;
  9452. return dstArray;
  9453. }
  9454. }
  9455. function WebGLCubeMaps(renderer) {
  9456. let cubemaps = new WeakMap();
  9457. function mapTextureMapping(texture, mapping) {
  9458. if (mapping === EquirectangularReflectionMapping) {
  9459. texture.mapping = CubeReflectionMapping;
  9460. } else if (mapping === EquirectangularRefractionMapping) {
  9461. texture.mapping = CubeRefractionMapping;
  9462. }
  9463. return texture;
  9464. }
  9465. function get(texture) {
  9466. if (texture && texture.isTexture && texture.isRenderTargetTexture === false) {
  9467. const mapping = texture.mapping;
  9468. if (mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping) {
  9469. if (cubemaps.has(texture)) {
  9470. const cubemap = cubemaps.get(texture).texture;
  9471. return mapTextureMapping(cubemap, texture.mapping);
  9472. } else {
  9473. const image = texture.image;
  9474. if (image && image.height > 0) {
  9475. const renderTarget = new WebGLCubeRenderTarget(image.height / 2);
  9476. renderTarget.fromEquirectangularTexture(renderer, texture);
  9477. cubemaps.set(texture, renderTarget);
  9478. texture.addEventListener('dispose', onTextureDispose);
  9479. return mapTextureMapping(renderTarget.texture, texture.mapping);
  9480. } else {
  9481. // image not yet ready. try the conversion next frame
  9482. return null;
  9483. }
  9484. }
  9485. }
  9486. }
  9487. return texture;
  9488. }
  9489. function onTextureDispose(event) {
  9490. const texture = event.target;
  9491. texture.removeEventListener('dispose', onTextureDispose);
  9492. const cubemap = cubemaps.get(texture);
  9493. if (cubemap !== undefined) {
  9494. cubemaps.delete(texture);
  9495. cubemap.dispose();
  9496. }
  9497. }
  9498. function dispose() {
  9499. cubemaps = new WeakMap();
  9500. }
  9501. return {
  9502. get: get,
  9503. dispose: dispose
  9504. };
  9505. }
  9506. class OrthographicCamera extends Camera {
  9507. constructor(left = -1, right = 1, top = 1, bottom = -1, near = 0.1, far = 2000) {
  9508. super();
  9509. this.isOrthographicCamera = true;
  9510. this.type = 'OrthographicCamera';
  9511. this.zoom = 1;
  9512. this.view = null;
  9513. this.left = left;
  9514. this.right = right;
  9515. this.top = top;
  9516. this.bottom = bottom;
  9517. this.near = near;
  9518. this.far = far;
  9519. this.updateProjectionMatrix();
  9520. }
  9521. copy(source, recursive) {
  9522. super.copy(source, recursive);
  9523. this.left = source.left;
  9524. this.right = source.right;
  9525. this.top = source.top;
  9526. this.bottom = source.bottom;
  9527. this.near = source.near;
  9528. this.far = source.far;
  9529. this.zoom = source.zoom;
  9530. this.view = source.view === null ? null : Object.assign({}, source.view);
  9531. return this;
  9532. }
  9533. setViewOffset(fullWidth, fullHeight, x, y, width, height) {
  9534. if (this.view === null) {
  9535. this.view = {
  9536. enabled: true,
  9537. fullWidth: 1,
  9538. fullHeight: 1,
  9539. offsetX: 0,
  9540. offsetY: 0,
  9541. width: 1,
  9542. height: 1
  9543. };
  9544. }
  9545. this.view.enabled = true;
  9546. this.view.fullWidth = fullWidth;
  9547. this.view.fullHeight = fullHeight;
  9548. this.view.offsetX = x;
  9549. this.view.offsetY = y;
  9550. this.view.width = width;
  9551. this.view.height = height;
  9552. this.updateProjectionMatrix();
  9553. }
  9554. clearViewOffset() {
  9555. if (this.view !== null) {
  9556. this.view.enabled = false;
  9557. }
  9558. this.updateProjectionMatrix();
  9559. }
  9560. updateProjectionMatrix() {
  9561. const dx = (this.right - this.left) / (2 * this.zoom);
  9562. const dy = (this.top - this.bottom) / (2 * this.zoom);
  9563. const cx = (this.right + this.left) / 2;
  9564. const cy = (this.top + this.bottom) / 2;
  9565. let left = cx - dx;
  9566. let right = cx + dx;
  9567. let top = cy + dy;
  9568. let bottom = cy - dy;
  9569. if (this.view !== null && this.view.enabled) {
  9570. const scaleW = (this.right - this.left) / this.view.fullWidth / this.zoom;
  9571. const scaleH = (this.top - this.bottom) / this.view.fullHeight / this.zoom;
  9572. left += scaleW * this.view.offsetX;
  9573. right = left + scaleW * this.view.width;
  9574. top -= scaleH * this.view.offsetY;
  9575. bottom = top - scaleH * this.view.height;
  9576. }
  9577. this.projectionMatrix.makeOrthographic(left, right, top, bottom, this.near, this.far);
  9578. this.projectionMatrixInverse.copy(this.projectionMatrix).invert();
  9579. }
  9580. toJSON(meta) {
  9581. const data = super.toJSON(meta);
  9582. data.object.zoom = this.zoom;
  9583. data.object.left = this.left;
  9584. data.object.right = this.right;
  9585. data.object.top = this.top;
  9586. data.object.bottom = this.bottom;
  9587. data.object.near = this.near;
  9588. data.object.far = this.far;
  9589. if (this.view !== null) data.object.view = Object.assign({}, this.view);
  9590. return data;
  9591. }
  9592. }
  9593. const LOD_MIN = 4; // The standard deviations (radians) associated with the extra mips. These are
  9594. // chosen to approximate a Trowbridge-Reitz distribution function times the
  9595. // geometric shadowing function. These sigma values squared must match the
  9596. // variance #defines in cube_uv_reflection_fragment.glsl.js.
  9597. const EXTRA_LOD_SIGMA = [0.125, 0.215, 0.35, 0.446, 0.526, 0.582]; // The maximum length of the blur for loop. Smaller sigmas will use fewer
  9598. // samples and exit early, but not recompile the shader.
  9599. const MAX_SAMPLES = 20;
  9600. const _flatCamera = /*@__PURE__*/new OrthographicCamera();
  9601. const _clearColor = /*@__PURE__*/new Color();
  9602. let _oldTarget = null; // Golden Ratio
  9603. const PHI = (1 + Math.sqrt(5)) / 2;
  9604. const INV_PHI = 1 / PHI; // Vertices of a dodecahedron (except the opposites, which represent the
  9605. // same axis), used as axis directions evenly spread on a sphere.
  9606. const _axisDirections = [/*@__PURE__*/new Vector3(1, 1, 1), /*@__PURE__*/new Vector3(-1, 1, 1), /*@__PURE__*/new Vector3(1, 1, -1), /*@__PURE__*/new Vector3(-1, 1, -1), /*@__PURE__*/new Vector3(0, PHI, INV_PHI), /*@__PURE__*/new Vector3(0, PHI, -INV_PHI), /*@__PURE__*/new Vector3(INV_PHI, 0, PHI), /*@__PURE__*/new Vector3(-INV_PHI, 0, PHI), /*@__PURE__*/new Vector3(PHI, INV_PHI, 0), /*@__PURE__*/new Vector3(-PHI, INV_PHI, 0)];
  9607. /**
  9608. * This class generates a Prefiltered, Mipmapped Radiance Environment Map
  9609. * (PMREM) from a cubeMap environment texture. This allows different levels of
  9610. * blur to be quickly accessed based on material roughness. It is packed into a
  9611. * special CubeUV format that allows us to perform custom interpolation so that
  9612. * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap
  9613. * chain, it only goes down to the LOD_MIN level (above), and then creates extra
  9614. * even more filtered 'mips' at the same LOD_MIN resolution, associated with
  9615. * higher roughness levels. In this way we maintain resolution to smoothly
  9616. * interpolate diffuse lighting while limiting sampling computation.
  9617. *
  9618. * Paper: Fast, Accurate Image-Based Lighting
  9619. * https://drive.google.com/file/d/15y8r_UpKlU9SvV4ILb0C3qCPecS8pvLz/view
  9620. */
  9621. class PMREMGenerator {
  9622. constructor(renderer) {
  9623. this._renderer = renderer;
  9624. this._pingPongRenderTarget = null;
  9625. this._lodMax = 0;
  9626. this._cubeSize = 0;
  9627. this._lodPlanes = [];
  9628. this._sizeLods = [];
  9629. this._sigmas = [];
  9630. this._blurMaterial = null;
  9631. this._cubemapMaterial = null;
  9632. this._equirectMaterial = null;
  9633. this._compileMaterial(this._blurMaterial);
  9634. }
  9635. /**
  9636. * Generates a PMREM from a supplied Scene, which can be faster than using an
  9637. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  9638. * in radians to be applied to the scene before PMREM generation. Optional near
  9639. * and far planes ensure the scene is rendered in its entirety (the cubeCamera
  9640. * is placed at the origin).
  9641. */
  9642. fromScene(scene, sigma = 0, near = 0.1, far = 100) {
  9643. _oldTarget = this._renderer.getRenderTarget();
  9644. this._setSize(256);
  9645. const cubeUVRenderTarget = this._allocateTargets();
  9646. cubeUVRenderTarget.depthBuffer = true;
  9647. this._sceneToCubeUV(scene, near, far, cubeUVRenderTarget);
  9648. if (sigma > 0) {
  9649. this._blur(cubeUVRenderTarget, 0, 0, sigma);
  9650. }
  9651. this._applyPMREM(cubeUVRenderTarget);
  9652. this._cleanup(cubeUVRenderTarget);
  9653. return cubeUVRenderTarget;
  9654. }
  9655. /**
  9656. * Generates a PMREM from an equirectangular texture, which can be either LDR
  9657. * or HDR. The ideal input image size is 1k (1024 x 512),
  9658. * as this matches best with the 256 x 256 cubemap output.
  9659. */
  9660. fromEquirectangular(equirectangular, renderTarget = null) {
  9661. return this._fromTexture(equirectangular, renderTarget);
  9662. }
  9663. /**
  9664. * Generates a PMREM from an cubemap texture, which can be either LDR
  9665. * or HDR. The ideal input cube size is 256 x 256,
  9666. * as this matches best with the 256 x 256 cubemap output.
  9667. */
  9668. fromCubemap(cubemap, renderTarget = null) {
  9669. return this._fromTexture(cubemap, renderTarget);
  9670. }
  9671. /**
  9672. * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during
  9673. * your texture's network fetch for increased concurrency.
  9674. */
  9675. compileCubemapShader() {
  9676. if (this._cubemapMaterial === null) {
  9677. this._cubemapMaterial = _getCubemapMaterial();
  9678. this._compileMaterial(this._cubemapMaterial);
  9679. }
  9680. }
  9681. /**
  9682. * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during
  9683. * your texture's network fetch for increased concurrency.
  9684. */
  9685. compileEquirectangularShader() {
  9686. if (this._equirectMaterial === null) {
  9687. this._equirectMaterial = _getEquirectMaterial();
  9688. this._compileMaterial(this._equirectMaterial);
  9689. }
  9690. }
  9691. /**
  9692. * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class,
  9693. * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on
  9694. * one of them will cause any others to also become unusable.
  9695. */
  9696. dispose() {
  9697. this._dispose();
  9698. if (this._cubemapMaterial !== null) this._cubemapMaterial.dispose();
  9699. if (this._equirectMaterial !== null) this._equirectMaterial.dispose();
  9700. } // private interface
  9701. _setSize(cubeSize) {
  9702. this._lodMax = Math.floor(Math.log2(cubeSize));
  9703. this._cubeSize = Math.pow(2, this._lodMax);
  9704. }
  9705. _dispose() {
  9706. if (this._blurMaterial !== null) this._blurMaterial.dispose();
  9707. if (this._pingPongRenderTarget !== null) this._pingPongRenderTarget.dispose();
  9708. for (let i = 0; i < this._lodPlanes.length; i++) {
  9709. this._lodPlanes[i].dispose();
  9710. }
  9711. }
  9712. _cleanup(outputTarget) {
  9713. this._renderer.setRenderTarget(_oldTarget);
  9714. outputTarget.scissorTest = false;
  9715. _setViewport(outputTarget, 0, 0, outputTarget.width, outputTarget.height);
  9716. }
  9717. _fromTexture(texture, renderTarget) {
  9718. if (texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping) {
  9719. this._setSize(texture.image.length === 0 ? 16 : texture.image[0].width || texture.image[0].image.width);
  9720. } else {
  9721. // Equirectangular
  9722. this._setSize(texture.image.width / 4);
  9723. }
  9724. _oldTarget = this._renderer.getRenderTarget();
  9725. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  9726. this._textureToCubeUV(texture, cubeUVRenderTarget);
  9727. this._applyPMREM(cubeUVRenderTarget);
  9728. this._cleanup(cubeUVRenderTarget);
  9729. return cubeUVRenderTarget;
  9730. }
  9731. _allocateTargets() {
  9732. const width = 3 * Math.max(this._cubeSize, 16 * 7);
  9733. const height = 4 * this._cubeSize;
  9734. const params = {
  9735. magFilter: LinearFilter,
  9736. minFilter: LinearFilter,
  9737. generateMipmaps: false,
  9738. type: HalfFloatType,
  9739. format: RGBAFormat,
  9740. encoding: LinearEncoding,
  9741. depthBuffer: false
  9742. };
  9743. const cubeUVRenderTarget = _createRenderTarget(width, height, params);
  9744. if (this._pingPongRenderTarget === null || this._pingPongRenderTarget.width !== width) {
  9745. if (this._pingPongRenderTarget !== null) {
  9746. this._dispose();
  9747. }
  9748. this._pingPongRenderTarget = _createRenderTarget(width, height, params);
  9749. const {
  9750. _lodMax
  9751. } = this;
  9752. ({
  9753. sizeLods: this._sizeLods,
  9754. lodPlanes: this._lodPlanes,
  9755. sigmas: this._sigmas
  9756. } = _createPlanes(_lodMax));
  9757. this._blurMaterial = _getBlurShader(_lodMax, width, height);
  9758. }
  9759. return cubeUVRenderTarget;
  9760. }
  9761. _compileMaterial(material) {
  9762. const tmpMesh = new Mesh(this._lodPlanes[0], material);
  9763. this._renderer.compile(tmpMesh, _flatCamera);
  9764. }
  9765. _sceneToCubeUV(scene, near, far, cubeUVRenderTarget) {
  9766. const fov = 90;
  9767. const aspect = 1;
  9768. const cubeCamera = new PerspectiveCamera(fov, aspect, near, far);
  9769. const upSign = [1, -1, 1, 1, 1, 1];
  9770. const forwardSign = [1, 1, 1, -1, -1, -1];
  9771. const renderer = this._renderer;
  9772. const originalAutoClear = renderer.autoClear;
  9773. const toneMapping = renderer.toneMapping;
  9774. renderer.getClearColor(_clearColor);
  9775. renderer.toneMapping = NoToneMapping;
  9776. renderer.autoClear = false;
  9777. const backgroundMaterial = new MeshBasicMaterial({
  9778. name: 'PMREM.Background',
  9779. side: BackSide,
  9780. depthWrite: false,
  9781. depthTest: false
  9782. });
  9783. const backgroundBox = new Mesh(new BoxGeometry(), backgroundMaterial);
  9784. let useSolidColor = false;
  9785. const background = scene.background;
  9786. if (background) {
  9787. if (background.isColor) {
  9788. backgroundMaterial.color.copy(background);
  9789. scene.background = null;
  9790. useSolidColor = true;
  9791. }
  9792. } else {
  9793. backgroundMaterial.color.copy(_clearColor);
  9794. useSolidColor = true;
  9795. }
  9796. for (let i = 0; i < 6; i++) {
  9797. const col = i % 3;
  9798. if (col === 0) {
  9799. cubeCamera.up.set(0, upSign[i], 0);
  9800. cubeCamera.lookAt(forwardSign[i], 0, 0);
  9801. } else if (col === 1) {
  9802. cubeCamera.up.set(0, 0, upSign[i]);
  9803. cubeCamera.lookAt(0, forwardSign[i], 0);
  9804. } else {
  9805. cubeCamera.up.set(0, upSign[i], 0);
  9806. cubeCamera.lookAt(0, 0, forwardSign[i]);
  9807. }
  9808. const size = this._cubeSize;
  9809. _setViewport(cubeUVRenderTarget, col * size, i > 2 ? size : 0, size, size);
  9810. renderer.setRenderTarget(cubeUVRenderTarget);
  9811. if (useSolidColor) {
  9812. renderer.render(backgroundBox, cubeCamera);
  9813. }
  9814. renderer.render(scene, cubeCamera);
  9815. }
  9816. backgroundBox.geometry.dispose();
  9817. backgroundBox.material.dispose();
  9818. renderer.toneMapping = toneMapping;
  9819. renderer.autoClear = originalAutoClear;
  9820. scene.background = background;
  9821. }
  9822. _textureToCubeUV(texture, cubeUVRenderTarget) {
  9823. const renderer = this._renderer;
  9824. const isCubeTexture = texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping;
  9825. if (isCubeTexture) {
  9826. if (this._cubemapMaterial === null) {
  9827. this._cubemapMaterial = _getCubemapMaterial();
  9828. }
  9829. this._cubemapMaterial.uniforms.flipEnvMap.value = texture.isRenderTargetTexture === false ? -1 : 1;
  9830. } else {
  9831. if (this._equirectMaterial === null) {
  9832. this._equirectMaterial = _getEquirectMaterial();
  9833. }
  9834. }
  9835. const material = isCubeTexture ? this._cubemapMaterial : this._equirectMaterial;
  9836. const mesh = new Mesh(this._lodPlanes[0], material);
  9837. const uniforms = material.uniforms;
  9838. uniforms['envMap'].value = texture;
  9839. const size = this._cubeSize;
  9840. _setViewport(cubeUVRenderTarget, 0, 0, 3 * size, 2 * size);
  9841. renderer.setRenderTarget(cubeUVRenderTarget);
  9842. renderer.render(mesh, _flatCamera);
  9843. }
  9844. _applyPMREM(cubeUVRenderTarget) {
  9845. const renderer = this._renderer;
  9846. const autoClear = renderer.autoClear;
  9847. renderer.autoClear = false;
  9848. for (let i = 1; i < this._lodPlanes.length; i++) {
  9849. const sigma = Math.sqrt(this._sigmas[i] * this._sigmas[i] - this._sigmas[i - 1] * this._sigmas[i - 1]);
  9850. const poleAxis = _axisDirections[(i - 1) % _axisDirections.length];
  9851. this._blur(cubeUVRenderTarget, i - 1, i, sigma, poleAxis);
  9852. }
  9853. renderer.autoClear = autoClear;
  9854. }
  9855. /**
  9856. * This is a two-pass Gaussian blur for a cubemap. Normally this is done
  9857. * vertically and horizontally, but this breaks down on a cube. Here we apply
  9858. * the blur latitudinally (around the poles), and then longitudinally (towards
  9859. * the poles) to approximate the orthogonally-separable blur. It is least
  9860. * accurate at the poles, but still does a decent job.
  9861. */
  9862. _blur(cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis) {
  9863. const pingPongRenderTarget = this._pingPongRenderTarget;
  9864. this._halfBlur(cubeUVRenderTarget, pingPongRenderTarget, lodIn, lodOut, sigma, 'latitudinal', poleAxis);
  9865. this._halfBlur(pingPongRenderTarget, cubeUVRenderTarget, lodOut, lodOut, sigma, 'longitudinal', poleAxis);
  9866. }
  9867. _halfBlur(targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis) {
  9868. const renderer = this._renderer;
  9869. const blurMaterial = this._blurMaterial;
  9870. if (direction !== 'latitudinal' && direction !== 'longitudinal') {
  9871. console.error('blur direction must be either latitudinal or longitudinal!');
  9872. } // Number of standard deviations at which to cut off the discrete approximation.
  9873. const STANDARD_DEVIATIONS = 3;
  9874. const blurMesh = new Mesh(this._lodPlanes[lodOut], blurMaterial);
  9875. const blurUniforms = blurMaterial.uniforms;
  9876. const pixels = this._sizeLods[lodIn] - 1;
  9877. const radiansPerPixel = isFinite(sigmaRadians) ? Math.PI / (2 * pixels) : 2 * Math.PI / (2 * MAX_SAMPLES - 1);
  9878. const sigmaPixels = sigmaRadians / radiansPerPixel;
  9879. const samples = isFinite(sigmaRadians) ? 1 + Math.floor(STANDARD_DEVIATIONS * sigmaPixels) : MAX_SAMPLES;
  9880. if (samples > MAX_SAMPLES) {
  9881. console.warn(`sigmaRadians, ${sigmaRadians}, is too large and will clip, as it requested ${samples} samples when the maximum is set to ${MAX_SAMPLES}`);
  9882. }
  9883. const weights = [];
  9884. let sum = 0;
  9885. for (let i = 0; i < MAX_SAMPLES; ++i) {
  9886. const x = i / sigmaPixels;
  9887. const weight = Math.exp(-x * x / 2);
  9888. weights.push(weight);
  9889. if (i === 0) {
  9890. sum += weight;
  9891. } else if (i < samples) {
  9892. sum += 2 * weight;
  9893. }
  9894. }
  9895. for (let i = 0; i < weights.length; i++) {
  9896. weights[i] = weights[i] / sum;
  9897. }
  9898. blurUniforms['envMap'].value = targetIn.texture;
  9899. blurUniforms['samples'].value = samples;
  9900. blurUniforms['weights'].value = weights;
  9901. blurUniforms['latitudinal'].value = direction === 'latitudinal';
  9902. if (poleAxis) {
  9903. blurUniforms['poleAxis'].value = poleAxis;
  9904. }
  9905. const {
  9906. _lodMax
  9907. } = this;
  9908. blurUniforms['dTheta'].value = radiansPerPixel;
  9909. blurUniforms['mipInt'].value = _lodMax - lodIn;
  9910. const outputSize = this._sizeLods[lodOut];
  9911. const x = 3 * outputSize * (lodOut > _lodMax - LOD_MIN ? lodOut - _lodMax + LOD_MIN : 0);
  9912. const y = 4 * (this._cubeSize - outputSize);
  9913. _setViewport(targetOut, x, y, 3 * outputSize, 2 * outputSize);
  9914. renderer.setRenderTarget(targetOut);
  9915. renderer.render(blurMesh, _flatCamera);
  9916. }
  9917. }
  9918. function _createPlanes(lodMax) {
  9919. const lodPlanes = [];
  9920. const sizeLods = [];
  9921. const sigmas = [];
  9922. let lod = lodMax;
  9923. const totalLods = lodMax - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length;
  9924. for (let i = 0; i < totalLods; i++) {
  9925. const sizeLod = Math.pow(2, lod);
  9926. sizeLods.push(sizeLod);
  9927. let sigma = 1.0 / sizeLod;
  9928. if (i > lodMax - LOD_MIN) {
  9929. sigma = EXTRA_LOD_SIGMA[i - lodMax + LOD_MIN - 1];
  9930. } else if (i === 0) {
  9931. sigma = 0;
  9932. }
  9933. sigmas.push(sigma);
  9934. const texelSize = 1.0 / (sizeLod - 2);
  9935. const min = -texelSize;
  9936. const max = 1 + texelSize;
  9937. const uv1 = [min, min, max, min, max, max, min, min, max, max, min, max];
  9938. const cubeFaces = 6;
  9939. const vertices = 6;
  9940. const positionSize = 3;
  9941. const uvSize = 2;
  9942. const faceIndexSize = 1;
  9943. const position = new Float32Array(positionSize * vertices * cubeFaces);
  9944. const uv = new Float32Array(uvSize * vertices * cubeFaces);
  9945. const faceIndex = new Float32Array(faceIndexSize * vertices * cubeFaces);
  9946. for (let face = 0; face < cubeFaces; face++) {
  9947. const x = face % 3 * 2 / 3 - 1;
  9948. const y = face > 2 ? 0 : -1;
  9949. 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];
  9950. position.set(coordinates, positionSize * vertices * face);
  9951. uv.set(uv1, uvSize * vertices * face);
  9952. const fill = [face, face, face, face, face, face];
  9953. faceIndex.set(fill, faceIndexSize * vertices * face);
  9954. }
  9955. const planes = new BufferGeometry();
  9956. planes.setAttribute('position', new BufferAttribute(position, positionSize));
  9957. planes.setAttribute('uv', new BufferAttribute(uv, uvSize));
  9958. planes.setAttribute('faceIndex', new BufferAttribute(faceIndex, faceIndexSize));
  9959. lodPlanes.push(planes);
  9960. if (lod > LOD_MIN) {
  9961. lod--;
  9962. }
  9963. }
  9964. return {
  9965. lodPlanes,
  9966. sizeLods,
  9967. sigmas
  9968. };
  9969. }
  9970. function _createRenderTarget(width, height, params) {
  9971. const cubeUVRenderTarget = new WebGLRenderTarget(width, height, params);
  9972. cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping;
  9973. cubeUVRenderTarget.texture.name = 'PMREM.cubeUv';
  9974. cubeUVRenderTarget.scissorTest = true;
  9975. return cubeUVRenderTarget;
  9976. }
  9977. function _setViewport(target, x, y, width, height) {
  9978. target.viewport.set(x, y, width, height);
  9979. target.scissor.set(x, y, width, height);
  9980. }
  9981. function _getBlurShader(lodMax, width, height) {
  9982. const weights = new Float32Array(MAX_SAMPLES);
  9983. const poleAxis = new Vector3(0, 1, 0);
  9984. const shaderMaterial = new ShaderMaterial({
  9985. name: 'SphericalGaussianBlur',
  9986. defines: {
  9987. 'n': MAX_SAMPLES,
  9988. 'CUBEUV_TEXEL_WIDTH': 1.0 / width,
  9989. 'CUBEUV_TEXEL_HEIGHT': 1.0 / height,
  9990. 'CUBEUV_MAX_MIP': `${lodMax}.0`
  9991. },
  9992. uniforms: {
  9993. 'envMap': {
  9994. value: null
  9995. },
  9996. 'samples': {
  9997. value: 1
  9998. },
  9999. 'weights': {
  10000. value: weights
  10001. },
  10002. 'latitudinal': {
  10003. value: false
  10004. },
  10005. 'dTheta': {
  10006. value: 0
  10007. },
  10008. 'mipInt': {
  10009. value: 0
  10010. },
  10011. 'poleAxis': {
  10012. value: poleAxis
  10013. }
  10014. },
  10015. vertexShader: _getCommonVertexShader(),
  10016. fragmentShader:
  10017. /* glsl */
  10018. `
  10019. precision mediump float;
  10020. precision mediump int;
  10021. varying vec3 vOutputDirection;
  10022. uniform sampler2D envMap;
  10023. uniform int samples;
  10024. uniform float weights[ n ];
  10025. uniform bool latitudinal;
  10026. uniform float dTheta;
  10027. uniform float mipInt;
  10028. uniform vec3 poleAxis;
  10029. #define ENVMAP_TYPE_CUBE_UV
  10030. #include <cube_uv_reflection_fragment>
  10031. vec3 getSample( float theta, vec3 axis ) {
  10032. float cosTheta = cos( theta );
  10033. // Rodrigues' axis-angle rotation
  10034. vec3 sampleDirection = vOutputDirection * cosTheta
  10035. + cross( axis, vOutputDirection ) * sin( theta )
  10036. + axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta );
  10037. return bilinearCubeUV( envMap, sampleDirection, mipInt );
  10038. }
  10039. void main() {
  10040. vec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection );
  10041. if ( all( equal( axis, vec3( 0.0 ) ) ) ) {
  10042. axis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x );
  10043. }
  10044. axis = normalize( axis );
  10045. gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );
  10046. gl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis );
  10047. for ( int i = 1; i < n; i++ ) {
  10048. if ( i >= samples ) {
  10049. break;
  10050. }
  10051. float theta = dTheta * float( i );
  10052. gl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis );
  10053. gl_FragColor.rgb += weights[ i ] * getSample( theta, axis );
  10054. }
  10055. }
  10056. `,
  10057. blending: NoBlending,
  10058. depthTest: false,
  10059. depthWrite: false
  10060. });
  10061. return shaderMaterial;
  10062. }
  10063. function _getEquirectMaterial() {
  10064. return new ShaderMaterial({
  10065. name: 'EquirectangularToCubeUV',
  10066. uniforms: {
  10067. 'envMap': {
  10068. value: null
  10069. }
  10070. },
  10071. vertexShader: _getCommonVertexShader(),
  10072. fragmentShader:
  10073. /* glsl */
  10074. `
  10075. precision mediump float;
  10076. precision mediump int;
  10077. varying vec3 vOutputDirection;
  10078. uniform sampler2D envMap;
  10079. #include <common>
  10080. void main() {
  10081. vec3 outputDirection = normalize( vOutputDirection );
  10082. vec2 uv = equirectUv( outputDirection );
  10083. gl_FragColor = vec4( texture2D ( envMap, uv ).rgb, 1.0 );
  10084. }
  10085. `,
  10086. blending: NoBlending,
  10087. depthTest: false,
  10088. depthWrite: false
  10089. });
  10090. }
  10091. function _getCubemapMaterial() {
  10092. return new ShaderMaterial({
  10093. name: 'CubemapToCubeUV',
  10094. uniforms: {
  10095. 'envMap': {
  10096. value: null
  10097. },
  10098. 'flipEnvMap': {
  10099. value: -1
  10100. }
  10101. },
  10102. vertexShader: _getCommonVertexShader(),
  10103. fragmentShader:
  10104. /* glsl */
  10105. `
  10106. precision mediump float;
  10107. precision mediump int;
  10108. uniform float flipEnvMap;
  10109. varying vec3 vOutputDirection;
  10110. uniform samplerCube envMap;
  10111. void main() {
  10112. gl_FragColor = textureCube( envMap, vec3( flipEnvMap * vOutputDirection.x, vOutputDirection.yz ) );
  10113. }
  10114. `,
  10115. blending: NoBlending,
  10116. depthTest: false,
  10117. depthWrite: false
  10118. });
  10119. }
  10120. function _getCommonVertexShader() {
  10121. return (
  10122. /* glsl */
  10123. `
  10124. precision mediump float;
  10125. precision mediump int;
  10126. attribute float faceIndex;
  10127. varying vec3 vOutputDirection;
  10128. // RH coordinate system; PMREM face-indexing convention
  10129. vec3 getDirection( vec2 uv, float face ) {
  10130. uv = 2.0 * uv - 1.0;
  10131. vec3 direction = vec3( uv, 1.0 );
  10132. if ( face == 0.0 ) {
  10133. direction = direction.zyx; // ( 1, v, u ) pos x
  10134. } else if ( face == 1.0 ) {
  10135. direction = direction.xzy;
  10136. direction.xz *= -1.0; // ( -u, 1, -v ) pos y
  10137. } else if ( face == 2.0 ) {
  10138. direction.x *= -1.0; // ( -u, v, 1 ) pos z
  10139. } else if ( face == 3.0 ) {
  10140. direction = direction.zyx;
  10141. direction.xz *= -1.0; // ( -1, v, -u ) neg x
  10142. } else if ( face == 4.0 ) {
  10143. direction = direction.xzy;
  10144. direction.xy *= -1.0; // ( -u, -1, v ) neg y
  10145. } else if ( face == 5.0 ) {
  10146. direction.z *= -1.0; // ( u, v, -1 ) neg z
  10147. }
  10148. return direction;
  10149. }
  10150. void main() {
  10151. vOutputDirection = getDirection( uv, faceIndex );
  10152. gl_Position = vec4( position, 1.0 );
  10153. }
  10154. `
  10155. );
  10156. }
  10157. function WebGLCubeUVMaps(renderer) {
  10158. let cubeUVmaps = new WeakMap();
  10159. let pmremGenerator = null;
  10160. function get(texture) {
  10161. if (texture && texture.isTexture) {
  10162. const mapping = texture.mapping;
  10163. const isEquirectMap = mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping;
  10164. const isCubeMap = mapping === CubeReflectionMapping || mapping === CubeRefractionMapping; // equirect/cube map to cubeUV conversion
  10165. if (isEquirectMap || isCubeMap) {
  10166. if (texture.isRenderTargetTexture && texture.needsPMREMUpdate === true) {
  10167. texture.needsPMREMUpdate = false;
  10168. let renderTarget = cubeUVmaps.get(texture);
  10169. if (pmremGenerator === null) pmremGenerator = new PMREMGenerator(renderer);
  10170. renderTarget = isEquirectMap ? pmremGenerator.fromEquirectangular(texture, renderTarget) : pmremGenerator.fromCubemap(texture, renderTarget);
  10171. cubeUVmaps.set(texture, renderTarget);
  10172. return renderTarget.texture;
  10173. } else {
  10174. if (cubeUVmaps.has(texture)) {
  10175. return cubeUVmaps.get(texture).texture;
  10176. } else {
  10177. const image = texture.image;
  10178. if (isEquirectMap && image && image.height > 0 || isCubeMap && image && isCubeTextureComplete(image)) {
  10179. if (pmremGenerator === null) pmremGenerator = new PMREMGenerator(renderer);
  10180. const renderTarget = isEquirectMap ? pmremGenerator.fromEquirectangular(texture) : pmremGenerator.fromCubemap(texture);
  10181. cubeUVmaps.set(texture, renderTarget);
  10182. texture.addEventListener('dispose', onTextureDispose);
  10183. return renderTarget.texture;
  10184. } else {
  10185. // image not yet ready. try the conversion next frame
  10186. return null;
  10187. }
  10188. }
  10189. }
  10190. }
  10191. }
  10192. return texture;
  10193. }
  10194. function isCubeTextureComplete(image) {
  10195. let count = 0;
  10196. const length = 6;
  10197. for (let i = 0; i < length; i++) {
  10198. if (image[i] !== undefined) count++;
  10199. }
  10200. return count === length;
  10201. }
  10202. function onTextureDispose(event) {
  10203. const texture = event.target;
  10204. texture.removeEventListener('dispose', onTextureDispose);
  10205. const cubemapUV = cubeUVmaps.get(texture);
  10206. if (cubemapUV !== undefined) {
  10207. cubeUVmaps.delete(texture);
  10208. cubemapUV.dispose();
  10209. }
  10210. }
  10211. function dispose() {
  10212. cubeUVmaps = new WeakMap();
  10213. if (pmremGenerator !== null) {
  10214. pmremGenerator.dispose();
  10215. pmremGenerator = null;
  10216. }
  10217. }
  10218. return {
  10219. get: get,
  10220. dispose: dispose
  10221. };
  10222. }
  10223. function WebGLExtensions(gl) {
  10224. const extensions = {};
  10225. function getExtension(name) {
  10226. if (extensions[name] !== undefined) {
  10227. return extensions[name];
  10228. }
  10229. let extension;
  10230. switch (name) {
  10231. case 'WEBGL_depth_texture':
  10232. extension = gl.getExtension('WEBGL_depth_texture') || gl.getExtension('MOZ_WEBGL_depth_texture') || gl.getExtension('WEBKIT_WEBGL_depth_texture');
  10233. break;
  10234. case 'EXT_texture_filter_anisotropic':
  10235. extension = gl.getExtension('EXT_texture_filter_anisotropic') || gl.getExtension('MOZ_EXT_texture_filter_anisotropic') || gl.getExtension('WEBKIT_EXT_texture_filter_anisotropic');
  10236. break;
  10237. case 'WEBGL_compressed_texture_s3tc':
  10238. extension = gl.getExtension('WEBGL_compressed_texture_s3tc') || gl.getExtension('MOZ_WEBGL_compressed_texture_s3tc') || gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  10239. break;
  10240. case 'WEBGL_compressed_texture_pvrtc':
  10241. extension = gl.getExtension('WEBGL_compressed_texture_pvrtc') || gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  10242. break;
  10243. default:
  10244. extension = gl.getExtension(name);
  10245. }
  10246. extensions[name] = extension;
  10247. return extension;
  10248. }
  10249. return {
  10250. has: function (name) {
  10251. return getExtension(name) !== null;
  10252. },
  10253. init: function (capabilities) {
  10254. if (capabilities.isWebGL2) {
  10255. getExtension('EXT_color_buffer_float');
  10256. } else {
  10257. getExtension('WEBGL_depth_texture');
  10258. getExtension('OES_texture_float');
  10259. getExtension('OES_texture_half_float');
  10260. getExtension('OES_texture_half_float_linear');
  10261. getExtension('OES_standard_derivatives');
  10262. getExtension('OES_element_index_uint');
  10263. getExtension('OES_vertex_array_object');
  10264. getExtension('ANGLE_instanced_arrays');
  10265. }
  10266. getExtension('OES_texture_float_linear');
  10267. getExtension('EXT_color_buffer_half_float');
  10268. getExtension('WEBGL_multisampled_render_to_texture');
  10269. },
  10270. get: function (name) {
  10271. const extension = getExtension(name);
  10272. if (extension === null) {
  10273. console.warn('THREE.WebGLRenderer: ' + name + ' extension not supported.');
  10274. }
  10275. return extension;
  10276. }
  10277. };
  10278. }
  10279. function WebGLGeometries(gl, attributes, info, bindingStates) {
  10280. const geometries = {};
  10281. const wireframeAttributes = new WeakMap();
  10282. function onGeometryDispose(event) {
  10283. const geometry = event.target;
  10284. if (geometry.index !== null) {
  10285. attributes.remove(geometry.index);
  10286. }
  10287. for (const name in geometry.attributes) {
  10288. attributes.remove(geometry.attributes[name]);
  10289. }
  10290. geometry.removeEventListener('dispose', onGeometryDispose);
  10291. delete geometries[geometry.id];
  10292. const attribute = wireframeAttributes.get(geometry);
  10293. if (attribute) {
  10294. attributes.remove(attribute);
  10295. wireframeAttributes.delete(geometry);
  10296. }
  10297. bindingStates.releaseStatesOfGeometry(geometry);
  10298. if (geometry.isInstancedBufferGeometry === true) {
  10299. delete geometry._maxInstanceCount;
  10300. } //
  10301. info.memory.geometries--;
  10302. }
  10303. function get(object, geometry) {
  10304. if (geometries[geometry.id] === true) return geometry;
  10305. geometry.addEventListener('dispose', onGeometryDispose);
  10306. geometries[geometry.id] = true;
  10307. info.memory.geometries++;
  10308. return geometry;
  10309. }
  10310. function update(geometry) {
  10311. const geometryAttributes = geometry.attributes; // Updating index buffer in VAO now. See WebGLBindingStates.
  10312. for (const name in geometryAttributes) {
  10313. attributes.update(geometryAttributes[name], gl.ARRAY_BUFFER);
  10314. } // morph targets
  10315. const morphAttributes = geometry.morphAttributes;
  10316. for (const name in morphAttributes) {
  10317. const array = morphAttributes[name];
  10318. for (let i = 0, l = array.length; i < l; i++) {
  10319. attributes.update(array[i], gl.ARRAY_BUFFER);
  10320. }
  10321. }
  10322. }
  10323. function updateWireframeAttribute(geometry) {
  10324. const indices = [];
  10325. const geometryIndex = geometry.index;
  10326. const geometryPosition = geometry.attributes.position;
  10327. let version = 0;
  10328. if (geometryIndex !== null) {
  10329. const array = geometryIndex.array;
  10330. version = geometryIndex.version;
  10331. for (let i = 0, l = array.length; i < l; i += 3) {
  10332. const a = array[i + 0];
  10333. const b = array[i + 1];
  10334. const c = array[i + 2];
  10335. indices.push(a, b, b, c, c, a);
  10336. }
  10337. } else {
  10338. const array = geometryPosition.array;
  10339. version = geometryPosition.version;
  10340. for (let i = 0, l = array.length / 3 - 1; i < l; i += 3) {
  10341. const a = i + 0;
  10342. const b = i + 1;
  10343. const c = i + 2;
  10344. indices.push(a, b, b, c, c, a);
  10345. }
  10346. }
  10347. const attribute = new (arrayNeedsUint32(indices) ? Uint32BufferAttribute : Uint16BufferAttribute)(indices, 1);
  10348. attribute.version = version; // Updating index buffer in VAO now. See WebGLBindingStates
  10349. //
  10350. const previousAttribute = wireframeAttributes.get(geometry);
  10351. if (previousAttribute) attributes.remove(previousAttribute); //
  10352. wireframeAttributes.set(geometry, attribute);
  10353. }
  10354. function getWireframeAttribute(geometry) {
  10355. const currentAttribute = wireframeAttributes.get(geometry);
  10356. if (currentAttribute) {
  10357. const geometryIndex = geometry.index;
  10358. if (geometryIndex !== null) {
  10359. // if the attribute is obsolete, create a new one
  10360. if (currentAttribute.version < geometryIndex.version) {
  10361. updateWireframeAttribute(geometry);
  10362. }
  10363. }
  10364. } else {
  10365. updateWireframeAttribute(geometry);
  10366. }
  10367. return wireframeAttributes.get(geometry);
  10368. }
  10369. return {
  10370. get: get,
  10371. update: update,
  10372. getWireframeAttribute: getWireframeAttribute
  10373. };
  10374. }
  10375. function WebGLIndexedBufferRenderer(gl, extensions, info, capabilities) {
  10376. const isWebGL2 = capabilities.isWebGL2;
  10377. let mode;
  10378. function setMode(value) {
  10379. mode = value;
  10380. }
  10381. let type, bytesPerElement;
  10382. function setIndex(value) {
  10383. type = value.type;
  10384. bytesPerElement = value.bytesPerElement;
  10385. }
  10386. function render(start, count) {
  10387. gl.drawElements(mode, count, type, start * bytesPerElement);
  10388. info.update(count, mode, 1);
  10389. }
  10390. function renderInstances(start, count, primcount) {
  10391. if (primcount === 0) return;
  10392. let extension, methodName;
  10393. if (isWebGL2) {
  10394. extension = gl;
  10395. methodName = 'drawElementsInstanced';
  10396. } else {
  10397. extension = extensions.get('ANGLE_instanced_arrays');
  10398. methodName = 'drawElementsInstancedANGLE';
  10399. if (extension === null) {
  10400. console.error('THREE.WebGLIndexedBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.');
  10401. return;
  10402. }
  10403. }
  10404. extension[methodName](mode, count, type, start * bytesPerElement, primcount);
  10405. info.update(count, mode, primcount);
  10406. } //
  10407. this.setMode = setMode;
  10408. this.setIndex = setIndex;
  10409. this.render = render;
  10410. this.renderInstances = renderInstances;
  10411. }
  10412. function WebGLInfo(gl) {
  10413. const memory = {
  10414. geometries: 0,
  10415. textures: 0
  10416. };
  10417. const render = {
  10418. frame: 0,
  10419. calls: 0,
  10420. triangles: 0,
  10421. points: 0,
  10422. lines: 0
  10423. };
  10424. function update(count, mode, instanceCount) {
  10425. render.calls++;
  10426. switch (mode) {
  10427. case gl.TRIANGLES:
  10428. render.triangles += instanceCount * (count / 3);
  10429. break;
  10430. case gl.LINES:
  10431. render.lines += instanceCount * (count / 2);
  10432. break;
  10433. case gl.LINE_STRIP:
  10434. render.lines += instanceCount * (count - 1);
  10435. break;
  10436. case gl.LINE_LOOP:
  10437. render.lines += instanceCount * count;
  10438. break;
  10439. case gl.POINTS:
  10440. render.points += instanceCount * count;
  10441. break;
  10442. default:
  10443. console.error('THREE.WebGLInfo: Unknown draw mode:', mode);
  10444. break;
  10445. }
  10446. }
  10447. function reset() {
  10448. render.frame++;
  10449. render.calls = 0;
  10450. render.triangles = 0;
  10451. render.points = 0;
  10452. render.lines = 0;
  10453. }
  10454. return {
  10455. memory: memory,
  10456. render: render,
  10457. programs: null,
  10458. autoReset: true,
  10459. reset: reset,
  10460. update: update
  10461. };
  10462. }
  10463. function numericalSort(a, b) {
  10464. return a[0] - b[0];
  10465. }
  10466. function absNumericalSort(a, b) {
  10467. return Math.abs(b[1]) - Math.abs(a[1]);
  10468. }
  10469. function denormalize(morph, attribute) {
  10470. let denominator = 1;
  10471. const array = attribute.isInterleavedBufferAttribute ? attribute.data.array : attribute.array;
  10472. if (array instanceof Int8Array) denominator = 127;else if (array instanceof Int16Array) denominator = 32767;else if (array instanceof Int32Array) denominator = 2147483647;else console.error('THREE.WebGLMorphtargets: Unsupported morph attribute data type: ', array);
  10473. morph.divideScalar(denominator);
  10474. }
  10475. function WebGLMorphtargets(gl, capabilities, textures) {
  10476. const influencesList = {};
  10477. const morphInfluences = new Float32Array(8);
  10478. const morphTextures = new WeakMap();
  10479. const morph = new Vector4();
  10480. const workInfluences = [];
  10481. for (let i = 0; i < 8; i++) {
  10482. workInfluences[i] = [i, 0];
  10483. }
  10484. function update(object, geometry, material, program) {
  10485. const objectInfluences = object.morphTargetInfluences;
  10486. if (capabilities.isWebGL2 === true) {
  10487. // instead of using attributes, the WebGL 2 code path encodes morph targets
  10488. // into an array of data textures. Each layer represents a single morph target.
  10489. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  10490. const morphTargetsCount = morphAttribute !== undefined ? morphAttribute.length : 0;
  10491. let entry = morphTextures.get(geometry);
  10492. if (entry === undefined || entry.count !== morphTargetsCount) {
  10493. if (entry !== undefined) entry.texture.dispose();
  10494. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  10495. const hasMorphNormals = geometry.morphAttributes.normal !== undefined;
  10496. const hasMorphColors = geometry.morphAttributes.color !== undefined;
  10497. const morphTargets = geometry.morphAttributes.position || [];
  10498. const morphNormals = geometry.morphAttributes.normal || [];
  10499. const morphColors = geometry.morphAttributes.color || [];
  10500. let vertexDataCount = 0;
  10501. if (hasMorphPosition === true) vertexDataCount = 1;
  10502. if (hasMorphNormals === true) vertexDataCount = 2;
  10503. if (hasMorphColors === true) vertexDataCount = 3;
  10504. let width = geometry.attributes.position.count * vertexDataCount;
  10505. let height = 1;
  10506. if (width > capabilities.maxTextureSize) {
  10507. height = Math.ceil(width / capabilities.maxTextureSize);
  10508. width = capabilities.maxTextureSize;
  10509. }
  10510. const buffer = new Float32Array(width * height * 4 * morphTargetsCount);
  10511. const texture = new DataArrayTexture(buffer, width, height, morphTargetsCount);
  10512. texture.type = FloatType;
  10513. texture.needsUpdate = true; // fill buffer
  10514. const vertexDataStride = vertexDataCount * 4;
  10515. for (let i = 0; i < morphTargetsCount; i++) {
  10516. const morphTarget = morphTargets[i];
  10517. const morphNormal = morphNormals[i];
  10518. const morphColor = morphColors[i];
  10519. const offset = width * height * 4 * i;
  10520. for (let j = 0; j < morphTarget.count; j++) {
  10521. const stride = j * vertexDataStride;
  10522. if (hasMorphPosition === true) {
  10523. morph.fromBufferAttribute(morphTarget, j);
  10524. if (morphTarget.normalized === true) denormalize(morph, morphTarget);
  10525. buffer[offset + stride + 0] = morph.x;
  10526. buffer[offset + stride + 1] = morph.y;
  10527. buffer[offset + stride + 2] = morph.z;
  10528. buffer[offset + stride + 3] = 0;
  10529. }
  10530. if (hasMorphNormals === true) {
  10531. morph.fromBufferAttribute(morphNormal, j);
  10532. if (morphNormal.normalized === true) denormalize(morph, morphNormal);
  10533. buffer[offset + stride + 4] = morph.x;
  10534. buffer[offset + stride + 5] = morph.y;
  10535. buffer[offset + stride + 6] = morph.z;
  10536. buffer[offset + stride + 7] = 0;
  10537. }
  10538. if (hasMorphColors === true) {
  10539. morph.fromBufferAttribute(morphColor, j);
  10540. if (morphColor.normalized === true) denormalize(morph, morphColor);
  10541. buffer[offset + stride + 8] = morph.x;
  10542. buffer[offset + stride + 9] = morph.y;
  10543. buffer[offset + stride + 10] = morph.z;
  10544. buffer[offset + stride + 11] = morphColor.itemSize === 4 ? morph.w : 1;
  10545. }
  10546. }
  10547. }
  10548. entry = {
  10549. count: morphTargetsCount,
  10550. texture: texture,
  10551. size: new Vector2(width, height)
  10552. };
  10553. morphTextures.set(geometry, entry);
  10554. function disposeTexture() {
  10555. texture.dispose();
  10556. morphTextures.delete(geometry);
  10557. geometry.removeEventListener('dispose', disposeTexture);
  10558. }
  10559. geometry.addEventListener('dispose', disposeTexture);
  10560. } //
  10561. let morphInfluencesSum = 0;
  10562. for (let i = 0; i < objectInfluences.length; i++) {
  10563. morphInfluencesSum += objectInfluences[i];
  10564. }
  10565. const morphBaseInfluence = geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
  10566. program.getUniforms().setValue(gl, 'morphTargetBaseInfluence', morphBaseInfluence);
  10567. program.getUniforms().setValue(gl, 'morphTargetInfluences', objectInfluences);
  10568. program.getUniforms().setValue(gl, 'morphTargetsTexture', entry.texture, textures);
  10569. program.getUniforms().setValue(gl, 'morphTargetsTextureSize', entry.size);
  10570. } else {
  10571. // When object doesn't have morph target influences defined, we treat it as a 0-length array
  10572. // This is important to make sure we set up morphTargetBaseInfluence / morphTargetInfluences
  10573. const length = objectInfluences === undefined ? 0 : objectInfluences.length;
  10574. let influences = influencesList[geometry.id];
  10575. if (influences === undefined || influences.length !== length) {
  10576. // initialise list
  10577. influences = [];
  10578. for (let i = 0; i < length; i++) {
  10579. influences[i] = [i, 0];
  10580. }
  10581. influencesList[geometry.id] = influences;
  10582. } // Collect influences
  10583. for (let i = 0; i < length; i++) {
  10584. const influence = influences[i];
  10585. influence[0] = i;
  10586. influence[1] = objectInfluences[i];
  10587. }
  10588. influences.sort(absNumericalSort);
  10589. for (let i = 0; i < 8; i++) {
  10590. if (i < length && influences[i][1]) {
  10591. workInfluences[i][0] = influences[i][0];
  10592. workInfluences[i][1] = influences[i][1];
  10593. } else {
  10594. workInfluences[i][0] = Number.MAX_SAFE_INTEGER;
  10595. workInfluences[i][1] = 0;
  10596. }
  10597. }
  10598. workInfluences.sort(numericalSort);
  10599. const morphTargets = geometry.morphAttributes.position;
  10600. const morphNormals = geometry.morphAttributes.normal;
  10601. let morphInfluencesSum = 0;
  10602. for (let i = 0; i < 8; i++) {
  10603. const influence = workInfluences[i];
  10604. const index = influence[0];
  10605. const value = influence[1];
  10606. if (index !== Number.MAX_SAFE_INTEGER && value) {
  10607. if (morphTargets && geometry.getAttribute('morphTarget' + i) !== morphTargets[index]) {
  10608. geometry.setAttribute('morphTarget' + i, morphTargets[index]);
  10609. }
  10610. if (morphNormals && geometry.getAttribute('morphNormal' + i) !== morphNormals[index]) {
  10611. geometry.setAttribute('morphNormal' + i, morphNormals[index]);
  10612. }
  10613. morphInfluences[i] = value;
  10614. morphInfluencesSum += value;
  10615. } else {
  10616. if (morphTargets && geometry.hasAttribute('morphTarget' + i) === true) {
  10617. geometry.deleteAttribute('morphTarget' + i);
  10618. }
  10619. if (morphNormals && geometry.hasAttribute('morphNormal' + i) === true) {
  10620. geometry.deleteAttribute('morphNormal' + i);
  10621. }
  10622. morphInfluences[i] = 0;
  10623. }
  10624. } // GLSL shader uses formula baseinfluence * base + sum(target * influence)
  10625. // This allows us to switch between absolute morphs and relative morphs without changing shader code
  10626. // When baseinfluence = 1 - sum(influence), the above is equivalent to sum((target - base) * influence)
  10627. const morphBaseInfluence = geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
  10628. program.getUniforms().setValue(gl, 'morphTargetBaseInfluence', morphBaseInfluence);
  10629. program.getUniforms().setValue(gl, 'morphTargetInfluences', morphInfluences);
  10630. }
  10631. }
  10632. return {
  10633. update: update
  10634. };
  10635. }
  10636. function WebGLObjects(gl, geometries, attributes, info) {
  10637. let updateMap = new WeakMap();
  10638. function update(object) {
  10639. const frame = info.render.frame;
  10640. const geometry = object.geometry;
  10641. const buffergeometry = geometries.get(object, geometry); // Update once per frame
  10642. if (updateMap.get(buffergeometry) !== frame) {
  10643. geometries.update(buffergeometry);
  10644. updateMap.set(buffergeometry, frame);
  10645. }
  10646. if (object.isInstancedMesh) {
  10647. if (object.hasEventListener('dispose', onInstancedMeshDispose) === false) {
  10648. object.addEventListener('dispose', onInstancedMeshDispose);
  10649. }
  10650. attributes.update(object.instanceMatrix, gl.ARRAY_BUFFER);
  10651. if (object.instanceColor !== null) {
  10652. attributes.update(object.instanceColor, gl.ARRAY_BUFFER);
  10653. }
  10654. }
  10655. return buffergeometry;
  10656. }
  10657. function dispose() {
  10658. updateMap = new WeakMap();
  10659. }
  10660. function onInstancedMeshDispose(event) {
  10661. const instancedMesh = event.target;
  10662. instancedMesh.removeEventListener('dispose', onInstancedMeshDispose);
  10663. attributes.remove(instancedMesh.instanceMatrix);
  10664. if (instancedMesh.instanceColor !== null) attributes.remove(instancedMesh.instanceColor);
  10665. }
  10666. return {
  10667. update: update,
  10668. dispose: dispose
  10669. };
  10670. }
  10671. /**
  10672. * Uniforms of a program.
  10673. * Those form a tree structure with a special top-level container for the root,
  10674. * which you get by calling 'new WebGLUniforms( gl, program )'.
  10675. *
  10676. *
  10677. * Properties of inner nodes including the top-level container:
  10678. *
  10679. * .seq - array of nested uniforms
  10680. * .map - nested uniforms by name
  10681. *
  10682. *
  10683. * Methods of all nodes except the top-level container:
  10684. *
  10685. * .setValue( gl, value, [textures] )
  10686. *
  10687. * uploads a uniform value(s)
  10688. * the 'textures' parameter is needed for sampler uniforms
  10689. *
  10690. *
  10691. * Static methods of the top-level container (textures factorizations):
  10692. *
  10693. * .upload( gl, seq, values, textures )
  10694. *
  10695. * sets uniforms in 'seq' to 'values[id].value'
  10696. *
  10697. * .seqWithValue( seq, values ) : filteredSeq
  10698. *
  10699. * filters 'seq' entries with corresponding entry in values
  10700. *
  10701. *
  10702. * Methods of the top-level container (textures factorizations):
  10703. *
  10704. * .setValue( gl, name, value, textures )
  10705. *
  10706. * sets uniform with name 'name' to 'value'
  10707. *
  10708. * .setOptional( gl, obj, prop )
  10709. *
  10710. * like .set for an optional property of the object
  10711. *
  10712. */
  10713. const emptyTexture = new Texture();
  10714. const emptyArrayTexture = new DataArrayTexture();
  10715. const empty3dTexture = new Data3DTexture();
  10716. const emptyCubeTexture = new CubeTexture(); // --- Utilities ---
  10717. // Array Caches (provide typed arrays for temporary by size)
  10718. const arrayCacheF32 = [];
  10719. const arrayCacheI32 = []; // Float32Array caches used for uploading Matrix uniforms
  10720. const mat4array = new Float32Array(16);
  10721. const mat3array = new Float32Array(9);
  10722. const mat2array = new Float32Array(4); // Flattening for arrays of vectors and matrices
  10723. function flatten(array, nBlocks, blockSize) {
  10724. const firstElem = array[0];
  10725. if (firstElem <= 0 || firstElem > 0) return array; // unoptimized: ! isNaN( firstElem )
  10726. // see http://jacksondunstan.com/articles/983
  10727. const n = nBlocks * blockSize;
  10728. let r = arrayCacheF32[n];
  10729. if (r === undefined) {
  10730. r = new Float32Array(n);
  10731. arrayCacheF32[n] = r;
  10732. }
  10733. if (nBlocks !== 0) {
  10734. firstElem.toArray(r, 0);
  10735. for (let i = 1, offset = 0; i !== nBlocks; ++i) {
  10736. offset += blockSize;
  10737. array[i].toArray(r, offset);
  10738. }
  10739. }
  10740. return r;
  10741. }
  10742. function arraysEqual(a, b) {
  10743. if (a.length !== b.length) return false;
  10744. for (let i = 0, l = a.length; i < l; i++) {
  10745. if (a[i] !== b[i]) return false;
  10746. }
  10747. return true;
  10748. }
  10749. function copyArray(a, b) {
  10750. for (let i = 0, l = b.length; i < l; i++) {
  10751. a[i] = b[i];
  10752. }
  10753. } // Texture unit allocation
  10754. function allocTexUnits(textures, n) {
  10755. let r = arrayCacheI32[n];
  10756. if (r === undefined) {
  10757. r = new Int32Array(n);
  10758. arrayCacheI32[n] = r;
  10759. }
  10760. for (let i = 0; i !== n; ++i) {
  10761. r[i] = textures.allocateTextureUnit();
  10762. }
  10763. return r;
  10764. } // --- Setters ---
  10765. // Note: Defining these methods externally, because they come in a bunch
  10766. // and this way their names minify.
  10767. // Single scalar
  10768. function setValueV1f(gl, v) {
  10769. const cache = this.cache;
  10770. if (cache[0] === v) return;
  10771. gl.uniform1f(this.addr, v);
  10772. cache[0] = v;
  10773. } // Single float vector (from flat array or THREE.VectorN)
  10774. function setValueV2f(gl, v) {
  10775. const cache = this.cache;
  10776. if (v.x !== undefined) {
  10777. if (cache[0] !== v.x || cache[1] !== v.y) {
  10778. gl.uniform2f(this.addr, v.x, v.y);
  10779. cache[0] = v.x;
  10780. cache[1] = v.y;
  10781. }
  10782. } else {
  10783. if (arraysEqual(cache, v)) return;
  10784. gl.uniform2fv(this.addr, v);
  10785. copyArray(cache, v);
  10786. }
  10787. }
  10788. function setValueV3f(gl, v) {
  10789. const cache = this.cache;
  10790. if (v.x !== undefined) {
  10791. if (cache[0] !== v.x || cache[1] !== v.y || cache[2] !== v.z) {
  10792. gl.uniform3f(this.addr, v.x, v.y, v.z);
  10793. cache[0] = v.x;
  10794. cache[1] = v.y;
  10795. cache[2] = v.z;
  10796. }
  10797. } else if (v.r !== undefined) {
  10798. if (cache[0] !== v.r || cache[1] !== v.g || cache[2] !== v.b) {
  10799. gl.uniform3f(this.addr, v.r, v.g, v.b);
  10800. cache[0] = v.r;
  10801. cache[1] = v.g;
  10802. cache[2] = v.b;
  10803. }
  10804. } else {
  10805. if (arraysEqual(cache, v)) return;
  10806. gl.uniform3fv(this.addr, v);
  10807. copyArray(cache, v);
  10808. }
  10809. }
  10810. function setValueV4f(gl, v) {
  10811. const cache = this.cache;
  10812. if (v.x !== undefined) {
  10813. if (cache[0] !== v.x || cache[1] !== v.y || cache[2] !== v.z || cache[3] !== v.w) {
  10814. gl.uniform4f(this.addr, v.x, v.y, v.z, v.w);
  10815. cache[0] = v.x;
  10816. cache[1] = v.y;
  10817. cache[2] = v.z;
  10818. cache[3] = v.w;
  10819. }
  10820. } else {
  10821. if (arraysEqual(cache, v)) return;
  10822. gl.uniform4fv(this.addr, v);
  10823. copyArray(cache, v);
  10824. }
  10825. } // Single matrix (from flat array or THREE.MatrixN)
  10826. function setValueM2(gl, v) {
  10827. const cache = this.cache;
  10828. const elements = v.elements;
  10829. if (elements === undefined) {
  10830. if (arraysEqual(cache, v)) return;
  10831. gl.uniformMatrix2fv(this.addr, false, v);
  10832. copyArray(cache, v);
  10833. } else {
  10834. if (arraysEqual(cache, elements)) return;
  10835. mat2array.set(elements);
  10836. gl.uniformMatrix2fv(this.addr, false, mat2array);
  10837. copyArray(cache, elements);
  10838. }
  10839. }
  10840. function setValueM3(gl, v) {
  10841. const cache = this.cache;
  10842. const elements = v.elements;
  10843. if (elements === undefined) {
  10844. if (arraysEqual(cache, v)) return;
  10845. gl.uniformMatrix3fv(this.addr, false, v);
  10846. copyArray(cache, v);
  10847. } else {
  10848. if (arraysEqual(cache, elements)) return;
  10849. mat3array.set(elements);
  10850. gl.uniformMatrix3fv(this.addr, false, mat3array);
  10851. copyArray(cache, elements);
  10852. }
  10853. }
  10854. function setValueM4(gl, v) {
  10855. const cache = this.cache;
  10856. const elements = v.elements;
  10857. if (elements === undefined) {
  10858. if (arraysEqual(cache, v)) return;
  10859. gl.uniformMatrix4fv(this.addr, false, v);
  10860. copyArray(cache, v);
  10861. } else {
  10862. if (arraysEqual(cache, elements)) return;
  10863. mat4array.set(elements);
  10864. gl.uniformMatrix4fv(this.addr, false, mat4array);
  10865. copyArray(cache, elements);
  10866. }
  10867. } // Single integer / boolean
  10868. function setValueV1i(gl, v) {
  10869. const cache = this.cache;
  10870. if (cache[0] === v) return;
  10871. gl.uniform1i(this.addr, v);
  10872. cache[0] = v;
  10873. } // Single integer / boolean vector (from flat array)
  10874. function setValueV2i(gl, v) {
  10875. const cache = this.cache;
  10876. if (arraysEqual(cache, v)) return;
  10877. gl.uniform2iv(this.addr, v);
  10878. copyArray(cache, v);
  10879. }
  10880. function setValueV3i(gl, v) {
  10881. const cache = this.cache;
  10882. if (arraysEqual(cache, v)) return;
  10883. gl.uniform3iv(this.addr, v);
  10884. copyArray(cache, v);
  10885. }
  10886. function setValueV4i(gl, v) {
  10887. const cache = this.cache;
  10888. if (arraysEqual(cache, v)) return;
  10889. gl.uniform4iv(this.addr, v);
  10890. copyArray(cache, v);
  10891. } // Single unsigned integer
  10892. function setValueV1ui(gl, v) {
  10893. const cache = this.cache;
  10894. if (cache[0] === v) return;
  10895. gl.uniform1ui(this.addr, v);
  10896. cache[0] = v;
  10897. } // Single unsigned integer vector (from flat array)
  10898. function setValueV2ui(gl, v) {
  10899. const cache = this.cache;
  10900. if (arraysEqual(cache, v)) return;
  10901. gl.uniform2uiv(this.addr, v);
  10902. copyArray(cache, v);
  10903. }
  10904. function setValueV3ui(gl, v) {
  10905. const cache = this.cache;
  10906. if (arraysEqual(cache, v)) return;
  10907. gl.uniform3uiv(this.addr, v);
  10908. copyArray(cache, v);
  10909. }
  10910. function setValueV4ui(gl, v) {
  10911. const cache = this.cache;
  10912. if (arraysEqual(cache, v)) return;
  10913. gl.uniform4uiv(this.addr, v);
  10914. copyArray(cache, v);
  10915. } // Single texture (2D / Cube)
  10916. function setValueT1(gl, v, textures) {
  10917. const cache = this.cache;
  10918. const unit = textures.allocateTextureUnit();
  10919. if (cache[0] !== unit) {
  10920. gl.uniform1i(this.addr, unit);
  10921. cache[0] = unit;
  10922. }
  10923. textures.setTexture2D(v || emptyTexture, unit);
  10924. }
  10925. function setValueT3D1(gl, v, textures) {
  10926. const cache = this.cache;
  10927. const unit = textures.allocateTextureUnit();
  10928. if (cache[0] !== unit) {
  10929. gl.uniform1i(this.addr, unit);
  10930. cache[0] = unit;
  10931. }
  10932. textures.setTexture3D(v || empty3dTexture, unit);
  10933. }
  10934. function setValueT6(gl, v, textures) {
  10935. const cache = this.cache;
  10936. const unit = textures.allocateTextureUnit();
  10937. if (cache[0] !== unit) {
  10938. gl.uniform1i(this.addr, unit);
  10939. cache[0] = unit;
  10940. }
  10941. textures.setTextureCube(v || emptyCubeTexture, unit);
  10942. }
  10943. function setValueT2DArray1(gl, v, textures) {
  10944. const cache = this.cache;
  10945. const unit = textures.allocateTextureUnit();
  10946. if (cache[0] !== unit) {
  10947. gl.uniform1i(this.addr, unit);
  10948. cache[0] = unit;
  10949. }
  10950. textures.setTexture2DArray(v || emptyArrayTexture, unit);
  10951. } // Helper to pick the right setter for the singular case
  10952. function getSingularSetter(type) {
  10953. switch (type) {
  10954. case 0x1406:
  10955. return setValueV1f;
  10956. // FLOAT
  10957. case 0x8b50:
  10958. return setValueV2f;
  10959. // _VEC2
  10960. case 0x8b51:
  10961. return setValueV3f;
  10962. // _VEC3
  10963. case 0x8b52:
  10964. return setValueV4f;
  10965. // _VEC4
  10966. case 0x8b5a:
  10967. return setValueM2;
  10968. // _MAT2
  10969. case 0x8b5b:
  10970. return setValueM3;
  10971. // _MAT3
  10972. case 0x8b5c:
  10973. return setValueM4;
  10974. // _MAT4
  10975. case 0x1404:
  10976. case 0x8b56:
  10977. return setValueV1i;
  10978. // INT, BOOL
  10979. case 0x8b53:
  10980. case 0x8b57:
  10981. return setValueV2i;
  10982. // _VEC2
  10983. case 0x8b54:
  10984. case 0x8b58:
  10985. return setValueV3i;
  10986. // _VEC3
  10987. case 0x8b55:
  10988. case 0x8b59:
  10989. return setValueV4i;
  10990. // _VEC4
  10991. case 0x1405:
  10992. return setValueV1ui;
  10993. // UINT
  10994. case 0x8dc6:
  10995. return setValueV2ui;
  10996. // _VEC2
  10997. case 0x8dc7:
  10998. return setValueV3ui;
  10999. // _VEC3
  11000. case 0x8dc8:
  11001. return setValueV4ui;
  11002. // _VEC4
  11003. case 0x8b5e: // SAMPLER_2D
  11004. case 0x8d66: // SAMPLER_EXTERNAL_OES
  11005. case 0x8dca: // INT_SAMPLER_2D
  11006. case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
  11007. case 0x8b62:
  11008. // SAMPLER_2D_SHADOW
  11009. return setValueT1;
  11010. case 0x8b5f: // SAMPLER_3D
  11011. case 0x8dcb: // INT_SAMPLER_3D
  11012. case 0x8dd3:
  11013. // UNSIGNED_INT_SAMPLER_3D
  11014. return setValueT3D1;
  11015. case 0x8b60: // SAMPLER_CUBE
  11016. case 0x8dcc: // INT_SAMPLER_CUBE
  11017. case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
  11018. case 0x8dc5:
  11019. // SAMPLER_CUBE_SHADOW
  11020. return setValueT6;
  11021. case 0x8dc1: // SAMPLER_2D_ARRAY
  11022. case 0x8dcf: // INT_SAMPLER_2D_ARRAY
  11023. case 0x8dd7: // UNSIGNED_INT_SAMPLER_2D_ARRAY
  11024. case 0x8dc4:
  11025. // SAMPLER_2D_ARRAY_SHADOW
  11026. return setValueT2DArray1;
  11027. }
  11028. } // Array of scalars
  11029. function setValueV1fArray(gl, v) {
  11030. gl.uniform1fv(this.addr, v);
  11031. } // Array of vectors (from flat array or array of THREE.VectorN)
  11032. function setValueV2fArray(gl, v) {
  11033. const data = flatten(v, this.size, 2);
  11034. gl.uniform2fv(this.addr, data);
  11035. }
  11036. function setValueV3fArray(gl, v) {
  11037. const data = flatten(v, this.size, 3);
  11038. gl.uniform3fv(this.addr, data);
  11039. }
  11040. function setValueV4fArray(gl, v) {
  11041. const data = flatten(v, this.size, 4);
  11042. gl.uniform4fv(this.addr, data);
  11043. } // Array of matrices (from flat array or array of THREE.MatrixN)
  11044. function setValueM2Array(gl, v) {
  11045. const data = flatten(v, this.size, 4);
  11046. gl.uniformMatrix2fv(this.addr, false, data);
  11047. }
  11048. function setValueM3Array(gl, v) {
  11049. const data = flatten(v, this.size, 9);
  11050. gl.uniformMatrix3fv(this.addr, false, data);
  11051. }
  11052. function setValueM4Array(gl, v) {
  11053. const data = flatten(v, this.size, 16);
  11054. gl.uniformMatrix4fv(this.addr, false, data);
  11055. } // Array of integer / boolean
  11056. function setValueV1iArray(gl, v) {
  11057. gl.uniform1iv(this.addr, v);
  11058. } // Array of integer / boolean vectors (from flat array)
  11059. function setValueV2iArray(gl, v) {
  11060. gl.uniform2iv(this.addr, v);
  11061. }
  11062. function setValueV3iArray(gl, v) {
  11063. gl.uniform3iv(this.addr, v);
  11064. }
  11065. function setValueV4iArray(gl, v) {
  11066. gl.uniform4iv(this.addr, v);
  11067. } // Array of unsigned integer
  11068. function setValueV1uiArray(gl, v) {
  11069. gl.uniform1uiv(this.addr, v);
  11070. } // Array of unsigned integer vectors (from flat array)
  11071. function setValueV2uiArray(gl, v) {
  11072. gl.uniform2uiv(this.addr, v);
  11073. }
  11074. function setValueV3uiArray(gl, v) {
  11075. gl.uniform3uiv(this.addr, v);
  11076. }
  11077. function setValueV4uiArray(gl, v) {
  11078. gl.uniform4uiv(this.addr, v);
  11079. } // Array of textures (2D / 3D / Cube / 2DArray)
  11080. function setValueT1Array(gl, v, textures) {
  11081. const n = v.length;
  11082. const units = allocTexUnits(textures, n);
  11083. gl.uniform1iv(this.addr, units);
  11084. for (let i = 0; i !== n; ++i) {
  11085. textures.setTexture2D(v[i] || emptyTexture, units[i]);
  11086. }
  11087. }
  11088. function setValueT3DArray(gl, v, textures) {
  11089. const n = v.length;
  11090. const units = allocTexUnits(textures, n);
  11091. gl.uniform1iv(this.addr, units);
  11092. for (let i = 0; i !== n; ++i) {
  11093. textures.setTexture3D(v[i] || empty3dTexture, units[i]);
  11094. }
  11095. }
  11096. function setValueT6Array(gl, v, textures) {
  11097. const n = v.length;
  11098. const units = allocTexUnits(textures, n);
  11099. gl.uniform1iv(this.addr, units);
  11100. for (let i = 0; i !== n; ++i) {
  11101. textures.setTextureCube(v[i] || emptyCubeTexture, units[i]);
  11102. }
  11103. }
  11104. function setValueT2DArrayArray(gl, v, textures) {
  11105. const n = v.length;
  11106. const units = allocTexUnits(textures, n);
  11107. gl.uniform1iv(this.addr, units);
  11108. for (let i = 0; i !== n; ++i) {
  11109. textures.setTexture2DArray(v[i] || emptyArrayTexture, units[i]);
  11110. }
  11111. } // Helper to pick the right setter for a pure (bottom-level) array
  11112. function getPureArraySetter(type) {
  11113. switch (type) {
  11114. case 0x1406:
  11115. return setValueV1fArray;
  11116. // FLOAT
  11117. case 0x8b50:
  11118. return setValueV2fArray;
  11119. // _VEC2
  11120. case 0x8b51:
  11121. return setValueV3fArray;
  11122. // _VEC3
  11123. case 0x8b52:
  11124. return setValueV4fArray;
  11125. // _VEC4
  11126. case 0x8b5a:
  11127. return setValueM2Array;
  11128. // _MAT2
  11129. case 0x8b5b:
  11130. return setValueM3Array;
  11131. // _MAT3
  11132. case 0x8b5c:
  11133. return setValueM4Array;
  11134. // _MAT4
  11135. case 0x1404:
  11136. case 0x8b56:
  11137. return setValueV1iArray;
  11138. // INT, BOOL
  11139. case 0x8b53:
  11140. case 0x8b57:
  11141. return setValueV2iArray;
  11142. // _VEC2
  11143. case 0x8b54:
  11144. case 0x8b58:
  11145. return setValueV3iArray;
  11146. // _VEC3
  11147. case 0x8b55:
  11148. case 0x8b59:
  11149. return setValueV4iArray;
  11150. // _VEC4
  11151. case 0x1405:
  11152. return setValueV1uiArray;
  11153. // UINT
  11154. case 0x8dc6:
  11155. return setValueV2uiArray;
  11156. // _VEC2
  11157. case 0x8dc7:
  11158. return setValueV3uiArray;
  11159. // _VEC3
  11160. case 0x8dc8:
  11161. return setValueV4uiArray;
  11162. // _VEC4
  11163. case 0x8b5e: // SAMPLER_2D
  11164. case 0x8d66: // SAMPLER_EXTERNAL_OES
  11165. case 0x8dca: // INT_SAMPLER_2D
  11166. case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
  11167. case 0x8b62:
  11168. // SAMPLER_2D_SHADOW
  11169. return setValueT1Array;
  11170. case 0x8b5f: // SAMPLER_3D
  11171. case 0x8dcb: // INT_SAMPLER_3D
  11172. case 0x8dd3:
  11173. // UNSIGNED_INT_SAMPLER_3D
  11174. return setValueT3DArray;
  11175. case 0x8b60: // SAMPLER_CUBE
  11176. case 0x8dcc: // INT_SAMPLER_CUBE
  11177. case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
  11178. case 0x8dc5:
  11179. // SAMPLER_CUBE_SHADOW
  11180. return setValueT6Array;
  11181. case 0x8dc1: // SAMPLER_2D_ARRAY
  11182. case 0x8dcf: // INT_SAMPLER_2D_ARRAY
  11183. case 0x8dd7: // UNSIGNED_INT_SAMPLER_2D_ARRAY
  11184. case 0x8dc4:
  11185. // SAMPLER_2D_ARRAY_SHADOW
  11186. return setValueT2DArrayArray;
  11187. }
  11188. } // --- Uniform Classes ---
  11189. class SingleUniform {
  11190. constructor(id, activeInfo, addr) {
  11191. this.id = id;
  11192. this.addr = addr;
  11193. this.cache = [];
  11194. this.setValue = getSingularSetter(activeInfo.type); // this.path = activeInfo.name; // DEBUG
  11195. }
  11196. }
  11197. class PureArrayUniform {
  11198. constructor(id, activeInfo, addr) {
  11199. this.id = id;
  11200. this.addr = addr;
  11201. this.cache = [];
  11202. this.size = activeInfo.size;
  11203. this.setValue = getPureArraySetter(activeInfo.type); // this.path = activeInfo.name; // DEBUG
  11204. }
  11205. }
  11206. class StructuredUniform {
  11207. constructor(id) {
  11208. this.id = id;
  11209. this.seq = [];
  11210. this.map = {};
  11211. }
  11212. setValue(gl, value, textures) {
  11213. const seq = this.seq;
  11214. for (let i = 0, n = seq.length; i !== n; ++i) {
  11215. const u = seq[i];
  11216. u.setValue(gl, value[u.id], textures);
  11217. }
  11218. }
  11219. } // --- Top-level ---
  11220. // Parser - builds up the property tree from the path strings
  11221. const RePathPart = /(\w+)(\])?(\[|\.)?/g; // extracts
  11222. // - the identifier (member name or array index)
  11223. // - followed by an optional right bracket (found when array index)
  11224. // - followed by an optional left bracket or dot (type of subscript)
  11225. //
  11226. // Note: These portions can be read in a non-overlapping fashion and
  11227. // allow straightforward parsing of the hierarchy that WebGL encodes
  11228. // in the uniform names.
  11229. function addUniform(container, uniformObject) {
  11230. container.seq.push(uniformObject);
  11231. container.map[uniformObject.id] = uniformObject;
  11232. }
  11233. function parseUniform(activeInfo, addr, container) {
  11234. const path = activeInfo.name,
  11235. pathLength = path.length; // reset RegExp object, because of the early exit of a previous run
  11236. RePathPart.lastIndex = 0;
  11237. while (true) {
  11238. const match = RePathPart.exec(path),
  11239. matchEnd = RePathPart.lastIndex;
  11240. let id = match[1];
  11241. const idIsIndex = match[2] === ']',
  11242. subscript = match[3];
  11243. if (idIsIndex) id = id | 0; // convert to integer
  11244. if (subscript === undefined || subscript === '[' && matchEnd + 2 === pathLength) {
  11245. // bare name or "pure" bottom-level array "[0]" suffix
  11246. addUniform(container, subscript === undefined ? new SingleUniform(id, activeInfo, addr) : new PureArrayUniform(id, activeInfo, addr));
  11247. break;
  11248. } else {
  11249. // step into inner node / create it in case it doesn't exist
  11250. const map = container.map;
  11251. let next = map[id];
  11252. if (next === undefined) {
  11253. next = new StructuredUniform(id);
  11254. addUniform(container, next);
  11255. }
  11256. container = next;
  11257. }
  11258. }
  11259. } // Root Container
  11260. class WebGLUniforms {
  11261. constructor(gl, program) {
  11262. this.seq = [];
  11263. this.map = {};
  11264. const n = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS);
  11265. for (let i = 0; i < n; ++i) {
  11266. const info = gl.getActiveUniform(program, i),
  11267. addr = gl.getUniformLocation(program, info.name);
  11268. parseUniform(info, addr, this);
  11269. }
  11270. }
  11271. setValue(gl, name, value, textures) {
  11272. const u = this.map[name];
  11273. if (u !== undefined) u.setValue(gl, value, textures);
  11274. }
  11275. setOptional(gl, object, name) {
  11276. const v = object[name];
  11277. if (v !== undefined) this.setValue(gl, name, v);
  11278. }
  11279. static upload(gl, seq, values, textures) {
  11280. for (let i = 0, n = seq.length; i !== n; ++i) {
  11281. const u = seq[i],
  11282. v = values[u.id];
  11283. if (v.needsUpdate !== false) {
  11284. // note: always updating when .needsUpdate is undefined
  11285. u.setValue(gl, v.value, textures);
  11286. }
  11287. }
  11288. }
  11289. static seqWithValue(seq, values) {
  11290. const r = [];
  11291. for (let i = 0, n = seq.length; i !== n; ++i) {
  11292. const u = seq[i];
  11293. if (u.id in values) r.push(u);
  11294. }
  11295. return r;
  11296. }
  11297. }
  11298. function WebGLShader(gl, type, string) {
  11299. const shader = gl.createShader(type);
  11300. gl.shaderSource(shader, string);
  11301. gl.compileShader(shader);
  11302. return shader;
  11303. }
  11304. let programIdCount = 0;
  11305. function handleSource(string, errorLine) {
  11306. const lines = string.split('\n');
  11307. const lines2 = [];
  11308. const from = Math.max(errorLine - 6, 0);
  11309. const to = Math.min(errorLine + 6, lines.length);
  11310. for (let i = from; i < to; i++) {
  11311. lines2.push(i + 1 + ': ' + lines[i]);
  11312. }
  11313. return lines2.join('\n');
  11314. }
  11315. function getEncodingComponents(encoding) {
  11316. switch (encoding) {
  11317. case LinearEncoding:
  11318. return ['Linear', '( value )'];
  11319. case sRGBEncoding:
  11320. return ['sRGB', '( value )'];
  11321. default:
  11322. console.warn('THREE.WebGLProgram: Unsupported encoding:', encoding);
  11323. return ['Linear', '( value )'];
  11324. }
  11325. }
  11326. function getShaderErrors(gl, shader, type) {
  11327. const status = gl.getShaderParameter(shader, gl.COMPILE_STATUS);
  11328. const errors = gl.getShaderInfoLog(shader).trim();
  11329. if (status && errors === '') return '';
  11330. const errorMatches = /ERROR: 0:(\d+)/.exec(errors);
  11331. if (errorMatches) {
  11332. // --enable-privileged-webgl-extension
  11333. // console.log( '**' + type + '**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) );
  11334. const errorLine = parseInt(errorMatches[0]);
  11335. return type.toUpperCase() + '\n\n' + errors + '\n\n' + handleSource(gl.getShaderSource(shader), errorLine);
  11336. } else {
  11337. return errors;
  11338. }
  11339. }
  11340. function getTexelEncodingFunction(functionName, encoding) {
  11341. const components = getEncodingComponents(encoding);
  11342. return 'vec4 ' + functionName + '( vec4 value ) { return LinearTo' + components[0] + components[1] + '; }';
  11343. }
  11344. function getToneMappingFunction(functionName, toneMapping) {
  11345. let toneMappingName;
  11346. switch (toneMapping) {
  11347. case LinearToneMapping:
  11348. toneMappingName = 'Linear';
  11349. break;
  11350. case ReinhardToneMapping:
  11351. toneMappingName = 'Reinhard';
  11352. break;
  11353. case CineonToneMapping:
  11354. toneMappingName = 'OptimizedCineon';
  11355. break;
  11356. case ACESFilmicToneMapping:
  11357. toneMappingName = 'ACESFilmic';
  11358. break;
  11359. case CustomToneMapping:
  11360. toneMappingName = 'Custom';
  11361. break;
  11362. default:
  11363. console.warn('THREE.WebGLProgram: Unsupported toneMapping:', toneMapping);
  11364. toneMappingName = 'Linear';
  11365. }
  11366. return 'vec3 ' + functionName + '( vec3 color ) { return ' + toneMappingName + 'ToneMapping( color ); }';
  11367. }
  11368. function generateExtensions(parameters) {
  11369. const chunks = [parameters.extensionDerivatives || !!parameters.envMapCubeUVHeight || 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.transmission) && parameters.rendererExtensionShaderTextureLod ? '#extension GL_EXT_shader_texture_lod : enable' : ''];
  11370. return chunks.filter(filterEmptyLine).join('\n');
  11371. }
  11372. function generateDefines(defines) {
  11373. const chunks = [];
  11374. for (const name in defines) {
  11375. const value = defines[name];
  11376. if (value === false) continue;
  11377. chunks.push('#define ' + name + ' ' + value);
  11378. }
  11379. return chunks.join('\n');
  11380. }
  11381. function fetchAttributeLocations(gl, program) {
  11382. const attributes = {};
  11383. const n = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES);
  11384. for (let i = 0; i < n; i++) {
  11385. const info = gl.getActiveAttrib(program, i);
  11386. const name = info.name;
  11387. let locationSize = 1;
  11388. if (info.type === gl.FLOAT_MAT2) locationSize = 2;
  11389. if (info.type === gl.FLOAT_MAT3) locationSize = 3;
  11390. if (info.type === gl.FLOAT_MAT4) locationSize = 4; // console.log( 'THREE.WebGLProgram: ACTIVE VERTEX ATTRIBUTE:', name, i );
  11391. attributes[name] = {
  11392. type: info.type,
  11393. location: gl.getAttribLocation(program, name),
  11394. locationSize: locationSize
  11395. };
  11396. }
  11397. return attributes;
  11398. }
  11399. function filterEmptyLine(string) {
  11400. return string !== '';
  11401. }
  11402. function replaceLightNums(string, parameters) {
  11403. 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);
  11404. }
  11405. function replaceClippingPlaneNums(string, parameters) {
  11406. return string.replace(/NUM_CLIPPING_PLANES/g, parameters.numClippingPlanes).replace(/UNION_CLIPPING_PLANES/g, parameters.numClippingPlanes - parameters.numClipIntersection);
  11407. } // Resolve Includes
  11408. const includePattern = /^[ \t]*#include +<([\w\d./]+)>/gm;
  11409. function resolveIncludes(string) {
  11410. return string.replace(includePattern, includeReplacer);
  11411. }
  11412. function includeReplacer(match, include) {
  11413. const string = ShaderChunk[include];
  11414. if (string === undefined) {
  11415. throw new Error('Can not resolve #include <' + include + '>');
  11416. }
  11417. return resolveIncludes(string);
  11418. } // Unroll Loops
  11419. const deprecatedUnrollLoopPattern = /#pragma unroll_loop[\s]+?for \( int i \= (\d+)\; i < (\d+)\; i \+\+ \) \{([\s\S]+?)(?=\})\}/g;
  11420. 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;
  11421. function unrollLoops(string) {
  11422. return string.replace(unrollLoopPattern, loopReplacer).replace(deprecatedUnrollLoopPattern, deprecatedLoopReplacer);
  11423. }
  11424. function deprecatedLoopReplacer(match, start, end, snippet) {
  11425. console.warn('WebGLProgram: #pragma unroll_loop shader syntax is deprecated. Please use #pragma unroll_loop_start syntax instead.');
  11426. return loopReplacer(match, start, end, snippet);
  11427. }
  11428. function loopReplacer(match, start, end, snippet) {
  11429. let string = '';
  11430. for (let i = parseInt(start); i < parseInt(end); i++) {
  11431. string += snippet.replace(/\[\s*i\s*\]/g, '[ ' + i + ' ]').replace(/UNROLLED_LOOP_INDEX/g, i);
  11432. }
  11433. return string;
  11434. } //
  11435. function generatePrecision(parameters) {
  11436. let precisionstring = 'precision ' + parameters.precision + ' float;\nprecision ' + parameters.precision + ' int;';
  11437. if (parameters.precision === 'highp') {
  11438. precisionstring += '\n#define HIGH_PRECISION';
  11439. } else if (parameters.precision === 'mediump') {
  11440. precisionstring += '\n#define MEDIUM_PRECISION';
  11441. } else if (parameters.precision === 'lowp') {
  11442. precisionstring += '\n#define LOW_PRECISION';
  11443. }
  11444. return precisionstring;
  11445. }
  11446. function generateShadowMapTypeDefine(parameters) {
  11447. let shadowMapTypeDefine = 'SHADOWMAP_TYPE_BASIC';
  11448. if (parameters.shadowMapType === PCFShadowMap) {
  11449. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF';
  11450. } else if (parameters.shadowMapType === PCFSoftShadowMap) {
  11451. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF_SOFT';
  11452. } else if (parameters.shadowMapType === VSMShadowMap) {
  11453. shadowMapTypeDefine = 'SHADOWMAP_TYPE_VSM';
  11454. }
  11455. return shadowMapTypeDefine;
  11456. }
  11457. function generateEnvMapTypeDefine(parameters) {
  11458. let envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  11459. if (parameters.envMap) {
  11460. switch (parameters.envMapMode) {
  11461. case CubeReflectionMapping:
  11462. case CubeRefractionMapping:
  11463. envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  11464. break;
  11465. case CubeUVReflectionMapping:
  11466. envMapTypeDefine = 'ENVMAP_TYPE_CUBE_UV';
  11467. break;
  11468. }
  11469. }
  11470. return envMapTypeDefine;
  11471. }
  11472. function generateEnvMapModeDefine(parameters) {
  11473. let envMapModeDefine = 'ENVMAP_MODE_REFLECTION';
  11474. if (parameters.envMap) {
  11475. switch (parameters.envMapMode) {
  11476. case CubeRefractionMapping:
  11477. envMapModeDefine = 'ENVMAP_MODE_REFRACTION';
  11478. break;
  11479. }
  11480. }
  11481. return envMapModeDefine;
  11482. }
  11483. function generateEnvMapBlendingDefine(parameters) {
  11484. let envMapBlendingDefine = 'ENVMAP_BLENDING_NONE';
  11485. if (parameters.envMap) {
  11486. switch (parameters.combine) {
  11487. case MultiplyOperation:
  11488. envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  11489. break;
  11490. case MixOperation:
  11491. envMapBlendingDefine = 'ENVMAP_BLENDING_MIX';
  11492. break;
  11493. case AddOperation:
  11494. envMapBlendingDefine = 'ENVMAP_BLENDING_ADD';
  11495. break;
  11496. }
  11497. }
  11498. return envMapBlendingDefine;
  11499. }
  11500. function generateCubeUVSize(parameters) {
  11501. const imageHeight = parameters.envMapCubeUVHeight;
  11502. if (imageHeight === null) return null;
  11503. const maxMip = Math.log2(imageHeight) - 2;
  11504. const texelHeight = 1.0 / imageHeight;
  11505. const texelWidth = 1.0 / (3 * Math.max(Math.pow(2, maxMip), 7 * 16));
  11506. return {
  11507. texelWidth,
  11508. texelHeight,
  11509. maxMip
  11510. };
  11511. }
  11512. function WebGLProgram(renderer, cacheKey, parameters, bindingStates) {
  11513. // TODO Send this event to Three.js DevTools
  11514. // console.log( 'WebGLProgram', cacheKey );
  11515. const gl = renderer.getContext();
  11516. const defines = parameters.defines;
  11517. let vertexShader = parameters.vertexShader;
  11518. let fragmentShader = parameters.fragmentShader;
  11519. const shadowMapTypeDefine = generateShadowMapTypeDefine(parameters);
  11520. const envMapTypeDefine = generateEnvMapTypeDefine(parameters);
  11521. const envMapModeDefine = generateEnvMapModeDefine(parameters);
  11522. const envMapBlendingDefine = generateEnvMapBlendingDefine(parameters);
  11523. const envMapCubeUVSize = generateCubeUVSize(parameters);
  11524. const customExtensions = parameters.isWebGL2 ? '' : generateExtensions(parameters);
  11525. const customDefines = generateDefines(defines);
  11526. const program = gl.createProgram();
  11527. let prefixVertex, prefixFragment;
  11528. let versionString = parameters.glslVersion ? '#version ' + parameters.glslVersion + '\n' : '';
  11529. if (parameters.isRawShaderMaterial) {
  11530. prefixVertex = [customDefines].filter(filterEmptyLine).join('\n');
  11531. if (prefixVertex.length > 0) {
  11532. prefixVertex += '\n';
  11533. }
  11534. prefixFragment = [customExtensions, customDefines].filter(filterEmptyLine).join('\n');
  11535. if (prefixFragment.length > 0) {
  11536. prefixFragment += '\n';
  11537. }
  11538. } else {
  11539. 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' : '', 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.specularIntensityMap ? '#define USE_SPECULARINTENSITYMAP' : '', parameters.specularColorMap ? '#define USE_SPECULARCOLORMAP' : '', parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '', parameters.metalnessMap ? '#define USE_METALNESSMAP' : '', parameters.alphaMap ? '#define USE_ALPHAMAP' : '', parameters.transmission ? '#define USE_TRANSMISSION' : '', parameters.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '', parameters.thicknessMap ? '#define USE_THICKNESSMAP' : '', parameters.sheenColorMap ? '#define USE_SHEENCOLORMAP' : '', parameters.sheenRoughnessMap ? '#define USE_SHEENROUGHNESSMAP' : '', parameters.vertexTangents ? '#define USE_TANGENT' : '', parameters.vertexColors ? '#define USE_COLOR' : '', parameters.vertexAlphas ? '#define USE_COLOR_ALPHA' : '', parameters.vertexUvs ? '#define USE_UV' : '', parameters.uvsVertexOnly ? '#define UVS_VERTEX_ONLY' : '', parameters.flatShading ? '#define FLAT_SHADED' : '', parameters.skinning ? '#define USE_SKINNING' : '', parameters.morphTargets ? '#define USE_MORPHTARGETS' : '', parameters.morphNormals && parameters.flatShading === false ? '#define USE_MORPHNORMALS' : '', parameters.morphColors && parameters.isWebGL2 ? '#define USE_MORPHCOLORS' : '', parameters.morphTargetsCount > 0 && parameters.isWebGL2 ? '#define MORPHTARGETS_TEXTURE' : '', parameters.morphTargetsCount > 0 && parameters.isWebGL2 ? '#define MORPHTARGETS_TEXTURE_STRIDE ' + parameters.morphTextureStride : '', parameters.morphTargetsCount > 0 && parameters.isWebGL2 ? '#define MORPHTARGETS_COUNT ' + parameters.morphTargetsCount : '', 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', '#if defined( USE_COLOR_ALPHA )', ' attribute vec4 color;', '#elif defined( USE_COLOR )', ' attribute vec3 color;', '#endif', '#if ( defined( USE_MORPHTARGETS ) && ! defined( MORPHTARGETS_TEXTURE ) )', ' 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');
  11540. prefixFragment = [customExtensions, generatePrecision(parameters), '#define SHADER_NAME ' + parameters.shaderName, customDefines, 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 : '', envMapCubeUVSize ? '#define CUBEUV_TEXEL_WIDTH ' + envMapCubeUVSize.texelWidth : '', envMapCubeUVSize ? '#define CUBEUV_TEXEL_HEIGHT ' + envMapCubeUVSize.texelHeight : '', envMapCubeUVSize ? '#define CUBEUV_MAX_MIP ' + envMapCubeUVSize.maxMip + '.0' : '', 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.clearcoat ? '#define USE_CLEARCOAT' : '', parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '', parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '', parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '', parameters.specularMap ? '#define USE_SPECULARMAP' : '', parameters.specularIntensityMap ? '#define USE_SPECULARINTENSITYMAP' : '', parameters.specularColorMap ? '#define USE_SPECULARCOLORMAP' : '', parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '', parameters.metalnessMap ? '#define USE_METALNESSMAP' : '', parameters.alphaMap ? '#define USE_ALPHAMAP' : '', parameters.alphaTest ? '#define USE_ALPHATEST' : '', parameters.sheen ? '#define USE_SHEEN' : '', parameters.sheenColorMap ? '#define USE_SHEENCOLORMAP' : '', parameters.sheenRoughnessMap ? '#define USE_SHEENROUGHNESSMAP' : '', parameters.transmission ? '#define USE_TRANSMISSION' : '', parameters.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '', parameters.thicknessMap ? '#define USE_THICKNESSMAP' : '', parameters.decodeVideoTexture ? '#define DECODE_VIDEO_TEXTURE' : '', parameters.vertexTangents ? '#define USE_TANGENT' : '', parameters.vertexColors || parameters.instancingColor ? '#define USE_COLOR' : '', parameters.vertexAlphas ? '#define USE_COLOR_ALPHA' : '', 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' : '', '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
  11541. parameters.toneMapping !== NoToneMapping ? getToneMappingFunction('toneMapping', parameters.toneMapping) : '', parameters.dithering ? '#define DITHERING' : '', parameters.opaque ? '#define OPAQUE' : '', ShaderChunk['encodings_pars_fragment'], // this code is required here because it is used by the various encoding/decoding function defined below
  11542. getTexelEncodingFunction('linearToOutputTexel', parameters.outputEncoding), parameters.useDepthPacking ? '#define DEPTH_PACKING ' + parameters.depthPacking : '', '\n'].filter(filterEmptyLine).join('\n');
  11543. }
  11544. vertexShader = resolveIncludes(vertexShader);
  11545. vertexShader = replaceLightNums(vertexShader, parameters);
  11546. vertexShader = replaceClippingPlaneNums(vertexShader, parameters);
  11547. fragmentShader = resolveIncludes(fragmentShader);
  11548. fragmentShader = replaceLightNums(fragmentShader, parameters);
  11549. fragmentShader = replaceClippingPlaneNums(fragmentShader, parameters);
  11550. vertexShader = unrollLoops(vertexShader);
  11551. fragmentShader = unrollLoops(fragmentShader);
  11552. if (parameters.isWebGL2 && parameters.isRawShaderMaterial !== true) {
  11553. // GLSL 3.0 conversion for built-in materials and ShaderMaterial
  11554. versionString = '#version 300 es\n';
  11555. prefixVertex = ['precision mediump sampler2DArray;', '#define attribute in', '#define varying out', '#define texture2D texture'].join('\n') + '\n' + prefixVertex;
  11556. prefixFragment = ['#define varying in', parameters.glslVersion === GLSL3 ? '' : 'layout(location = 0) 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;
  11557. }
  11558. const vertexGlsl = versionString + prefixVertex + vertexShader;
  11559. const fragmentGlsl = versionString + prefixFragment + fragmentShader; // console.log( '*VERTEX*', vertexGlsl );
  11560. // console.log( '*FRAGMENT*', fragmentGlsl );
  11561. const glVertexShader = WebGLShader(gl, gl.VERTEX_SHADER, vertexGlsl);
  11562. const glFragmentShader = WebGLShader(gl, gl.FRAGMENT_SHADER, fragmentGlsl);
  11563. gl.attachShader(program, glVertexShader);
  11564. gl.attachShader(program, glFragmentShader); // Force a particular attribute to index 0.
  11565. if (parameters.index0AttributeName !== undefined) {
  11566. gl.bindAttribLocation(program, 0, parameters.index0AttributeName);
  11567. } else if (parameters.morphTargets === true) {
  11568. // programs with morphTargets displace position out of attribute 0
  11569. gl.bindAttribLocation(program, 0, 'position');
  11570. }
  11571. gl.linkProgram(program); // check for link errors
  11572. if (renderer.debug.checkShaderErrors) {
  11573. const programLog = gl.getProgramInfoLog(program).trim();
  11574. const vertexLog = gl.getShaderInfoLog(glVertexShader).trim();
  11575. const fragmentLog = gl.getShaderInfoLog(glFragmentShader).trim();
  11576. let runnable = true;
  11577. let haveDiagnostics = true;
  11578. if (gl.getProgramParameter(program, gl.LINK_STATUS) === false) {
  11579. runnable = false;
  11580. const vertexErrors = getShaderErrors(gl, glVertexShader, 'vertex');
  11581. const fragmentErrors = getShaderErrors(gl, glFragmentShader, 'fragment');
  11582. console.error('THREE.WebGLProgram: Shader Error ' + gl.getError() + ' - ' + 'VALIDATE_STATUS ' + gl.getProgramParameter(program, gl.VALIDATE_STATUS) + '\n\n' + 'Program Info Log: ' + programLog + '\n' + vertexErrors + '\n' + fragmentErrors);
  11583. } else if (programLog !== '') {
  11584. console.warn('THREE.WebGLProgram: Program Info Log:', programLog);
  11585. } else if (vertexLog === '' || fragmentLog === '') {
  11586. haveDiagnostics = false;
  11587. }
  11588. if (haveDiagnostics) {
  11589. this.diagnostics = {
  11590. runnable: runnable,
  11591. programLog: programLog,
  11592. vertexShader: {
  11593. log: vertexLog,
  11594. prefix: prefixVertex
  11595. },
  11596. fragmentShader: {
  11597. log: fragmentLog,
  11598. prefix: prefixFragment
  11599. }
  11600. };
  11601. }
  11602. } // Clean up
  11603. // Crashes in iOS9 and iOS10. #18402
  11604. // gl.detachShader( program, glVertexShader );
  11605. // gl.detachShader( program, glFragmentShader );
  11606. gl.deleteShader(glVertexShader);
  11607. gl.deleteShader(glFragmentShader); // set up caching for uniform locations
  11608. let cachedUniforms;
  11609. this.getUniforms = function () {
  11610. if (cachedUniforms === undefined) {
  11611. cachedUniforms = new WebGLUniforms(gl, program);
  11612. }
  11613. return cachedUniforms;
  11614. }; // set up caching for attribute locations
  11615. let cachedAttributes;
  11616. this.getAttributes = function () {
  11617. if (cachedAttributes === undefined) {
  11618. cachedAttributes = fetchAttributeLocations(gl, program);
  11619. }
  11620. return cachedAttributes;
  11621. }; // free resource
  11622. this.destroy = function () {
  11623. bindingStates.releaseStatesOfProgram(this);
  11624. gl.deleteProgram(program);
  11625. this.program = undefined;
  11626. }; //
  11627. this.name = parameters.shaderName;
  11628. this.id = programIdCount++;
  11629. this.cacheKey = cacheKey;
  11630. this.usedTimes = 1;
  11631. this.program = program;
  11632. this.vertexShader = glVertexShader;
  11633. this.fragmentShader = glFragmentShader;
  11634. return this;
  11635. }
  11636. let _id = 0;
  11637. class WebGLShaderCache {
  11638. constructor() {
  11639. this.shaderCache = new Map();
  11640. this.materialCache = new Map();
  11641. }
  11642. update(material) {
  11643. const vertexShader = material.vertexShader;
  11644. const fragmentShader = material.fragmentShader;
  11645. const vertexShaderStage = this._getShaderStage(vertexShader);
  11646. const fragmentShaderStage = this._getShaderStage(fragmentShader);
  11647. const materialShaders = this._getShaderCacheForMaterial(material);
  11648. if (materialShaders.has(vertexShaderStage) === false) {
  11649. materialShaders.add(vertexShaderStage);
  11650. vertexShaderStage.usedTimes++;
  11651. }
  11652. if (materialShaders.has(fragmentShaderStage) === false) {
  11653. materialShaders.add(fragmentShaderStage);
  11654. fragmentShaderStage.usedTimes++;
  11655. }
  11656. return this;
  11657. }
  11658. remove(material) {
  11659. const materialShaders = this.materialCache.get(material);
  11660. for (const shaderStage of materialShaders) {
  11661. shaderStage.usedTimes--;
  11662. if (shaderStage.usedTimes === 0) this.shaderCache.delete(shaderStage.code);
  11663. }
  11664. this.materialCache.delete(material);
  11665. return this;
  11666. }
  11667. getVertexShaderID(material) {
  11668. return this._getShaderStage(material.vertexShader).id;
  11669. }
  11670. getFragmentShaderID(material) {
  11671. return this._getShaderStage(material.fragmentShader).id;
  11672. }
  11673. dispose() {
  11674. this.shaderCache.clear();
  11675. this.materialCache.clear();
  11676. }
  11677. _getShaderCacheForMaterial(material) {
  11678. const cache = this.materialCache;
  11679. if (cache.has(material) === false) {
  11680. cache.set(material, new Set());
  11681. }
  11682. return cache.get(material);
  11683. }
  11684. _getShaderStage(code) {
  11685. const cache = this.shaderCache;
  11686. if (cache.has(code) === false) {
  11687. const stage = new WebGLShaderStage(code);
  11688. cache.set(code, stage);
  11689. }
  11690. return cache.get(code);
  11691. }
  11692. }
  11693. class WebGLShaderStage {
  11694. constructor(code) {
  11695. this.id = _id++;
  11696. this.code = code;
  11697. this.usedTimes = 0;
  11698. }
  11699. }
  11700. function WebGLPrograms(renderer, cubemaps, cubeuvmaps, extensions, capabilities, bindingStates, clipping) {
  11701. const _programLayers = new Layers();
  11702. const _customShaders = new WebGLShaderCache();
  11703. const programs = [];
  11704. const isWebGL2 = capabilities.isWebGL2;
  11705. const logarithmicDepthBuffer = capabilities.logarithmicDepthBuffer;
  11706. const vertexTextures = capabilities.vertexTextures;
  11707. let precision = capabilities.precision;
  11708. const shaderIDs = {
  11709. MeshDepthMaterial: 'depth',
  11710. MeshDistanceMaterial: 'distanceRGBA',
  11711. MeshNormalMaterial: 'normal',
  11712. MeshBasicMaterial: 'basic',
  11713. MeshLambertMaterial: 'lambert',
  11714. MeshPhongMaterial: 'phong',
  11715. MeshToonMaterial: 'toon',
  11716. MeshStandardMaterial: 'physical',
  11717. MeshPhysicalMaterial: 'physical',
  11718. MeshMatcapMaterial: 'matcap',
  11719. LineBasicMaterial: 'basic',
  11720. LineDashedMaterial: 'dashed',
  11721. PointsMaterial: 'points',
  11722. ShadowMaterial: 'shadow',
  11723. SpriteMaterial: 'sprite'
  11724. };
  11725. function getParameters(material, lights, shadows, scene, object) {
  11726. const fog = scene.fog;
  11727. const geometry = object.geometry;
  11728. const environment = material.isMeshStandardMaterial ? scene.environment : null;
  11729. const envMap = (material.isMeshStandardMaterial ? cubeuvmaps : cubemaps).get(material.envMap || environment);
  11730. const envMapCubeUVHeight = !!envMap && envMap.mapping === CubeUVReflectionMapping ? envMap.image.height : null;
  11731. const shaderID = shaderIDs[material.type]; // heuristics to create shader parameters according to lights in the scene
  11732. // (not to blow over maxLights budget)
  11733. if (material.precision !== null) {
  11734. precision = capabilities.getMaxPrecision(material.precision);
  11735. if (precision !== material.precision) {
  11736. console.warn('THREE.WebGLProgram.getParameters:', material.precision, 'not supported, using', precision, 'instead.');
  11737. }
  11738. } //
  11739. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  11740. const morphTargetsCount = morphAttribute !== undefined ? morphAttribute.length : 0;
  11741. let morphTextureStride = 0;
  11742. if (geometry.morphAttributes.position !== undefined) morphTextureStride = 1;
  11743. if (geometry.morphAttributes.normal !== undefined) morphTextureStride = 2;
  11744. if (geometry.morphAttributes.color !== undefined) morphTextureStride = 3; //
  11745. let vertexShader, fragmentShader;
  11746. let customVertexShaderID, customFragmentShaderID;
  11747. if (shaderID) {
  11748. const shader = ShaderLib[shaderID];
  11749. vertexShader = shader.vertexShader;
  11750. fragmentShader = shader.fragmentShader;
  11751. } else {
  11752. vertexShader = material.vertexShader;
  11753. fragmentShader = material.fragmentShader;
  11754. _customShaders.update(material);
  11755. customVertexShaderID = _customShaders.getVertexShaderID(material);
  11756. customFragmentShaderID = _customShaders.getFragmentShaderID(material);
  11757. }
  11758. const currentRenderTarget = renderer.getRenderTarget();
  11759. const useAlphaTest = material.alphaTest > 0;
  11760. const useClearcoat = material.clearcoat > 0;
  11761. const parameters = {
  11762. isWebGL2: isWebGL2,
  11763. shaderID: shaderID,
  11764. shaderName: material.type,
  11765. vertexShader: vertexShader,
  11766. fragmentShader: fragmentShader,
  11767. defines: material.defines,
  11768. customVertexShaderID: customVertexShaderID,
  11769. customFragmentShaderID: customFragmentShaderID,
  11770. isRawShaderMaterial: material.isRawShaderMaterial === true,
  11771. glslVersion: material.glslVersion,
  11772. precision: precision,
  11773. instancing: object.isInstancedMesh === true,
  11774. instancingColor: object.isInstancedMesh === true && object.instanceColor !== null,
  11775. supportsVertexTextures: vertexTextures,
  11776. outputEncoding: currentRenderTarget === null ? renderer.outputEncoding : currentRenderTarget.isXRRenderTarget === true ? currentRenderTarget.texture.encoding : LinearEncoding,
  11777. map: !!material.map,
  11778. matcap: !!material.matcap,
  11779. envMap: !!envMap,
  11780. envMapMode: envMap && envMap.mapping,
  11781. envMapCubeUVHeight: envMapCubeUVHeight,
  11782. lightMap: !!material.lightMap,
  11783. aoMap: !!material.aoMap,
  11784. emissiveMap: !!material.emissiveMap,
  11785. bumpMap: !!material.bumpMap,
  11786. normalMap: !!material.normalMap,
  11787. objectSpaceNormalMap: material.normalMapType === ObjectSpaceNormalMap,
  11788. tangentSpaceNormalMap: material.normalMapType === TangentSpaceNormalMap,
  11789. decodeVideoTexture: !!material.map && material.map.isVideoTexture === true && material.map.encoding === sRGBEncoding,
  11790. clearcoat: useClearcoat,
  11791. clearcoatMap: useClearcoat && !!material.clearcoatMap,
  11792. clearcoatRoughnessMap: useClearcoat && !!material.clearcoatRoughnessMap,
  11793. clearcoatNormalMap: useClearcoat && !!material.clearcoatNormalMap,
  11794. displacementMap: !!material.displacementMap,
  11795. roughnessMap: !!material.roughnessMap,
  11796. metalnessMap: !!material.metalnessMap,
  11797. specularMap: !!material.specularMap,
  11798. specularIntensityMap: !!material.specularIntensityMap,
  11799. specularColorMap: !!material.specularColorMap,
  11800. opaque: material.transparent === false && material.blending === NormalBlending,
  11801. alphaMap: !!material.alphaMap,
  11802. alphaTest: useAlphaTest,
  11803. gradientMap: !!material.gradientMap,
  11804. sheen: material.sheen > 0,
  11805. sheenColorMap: !!material.sheenColorMap,
  11806. sheenRoughnessMap: !!material.sheenRoughnessMap,
  11807. transmission: material.transmission > 0,
  11808. transmissionMap: !!material.transmissionMap,
  11809. thicknessMap: !!material.thicknessMap,
  11810. combine: material.combine,
  11811. vertexTangents: !!material.normalMap && !!geometry.attributes.tangent,
  11812. vertexColors: material.vertexColors,
  11813. vertexAlphas: material.vertexColors === true && !!geometry.attributes.color && geometry.attributes.color.itemSize === 4,
  11814. 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 || !!material.thicknessMap || !!material.specularIntensityMap || !!material.specularColorMap || !!material.sheenColorMap || !!material.sheenRoughnessMap,
  11815. uvsVertexOnly: !(!!material.map || !!material.bumpMap || !!material.normalMap || !!material.specularMap || !!material.alphaMap || !!material.emissiveMap || !!material.roughnessMap || !!material.metalnessMap || !!material.clearcoatNormalMap || material.transmission > 0 || !!material.transmissionMap || !!material.thicknessMap || !!material.specularIntensityMap || !!material.specularColorMap || material.sheen > 0 || !!material.sheenColorMap || !!material.sheenRoughnessMap) && !!material.displacementMap,
  11816. fog: !!fog,
  11817. useFog: material.fog === true,
  11818. fogExp2: fog && fog.isFogExp2,
  11819. flatShading: !!material.flatShading,
  11820. sizeAttenuation: material.sizeAttenuation,
  11821. logarithmicDepthBuffer: logarithmicDepthBuffer,
  11822. skinning: object.isSkinnedMesh === true,
  11823. morphTargets: geometry.morphAttributes.position !== undefined,
  11824. morphNormals: geometry.morphAttributes.normal !== undefined,
  11825. morphColors: geometry.morphAttributes.color !== undefined,
  11826. morphTargetsCount: morphTargetsCount,
  11827. morphTextureStride: morphTextureStride,
  11828. numDirLights: lights.directional.length,
  11829. numPointLights: lights.point.length,
  11830. numSpotLights: lights.spot.length,
  11831. numRectAreaLights: lights.rectArea.length,
  11832. numHemiLights: lights.hemi.length,
  11833. numDirLightShadows: lights.directionalShadowMap.length,
  11834. numPointLightShadows: lights.pointShadowMap.length,
  11835. numSpotLightShadows: lights.spotShadowMap.length,
  11836. numClippingPlanes: clipping.numPlanes,
  11837. numClipIntersection: clipping.numIntersection,
  11838. dithering: material.dithering,
  11839. shadowMapEnabled: renderer.shadowMap.enabled && shadows.length > 0,
  11840. shadowMapType: renderer.shadowMap.type,
  11841. toneMapping: material.toneMapped ? renderer.toneMapping : NoToneMapping,
  11842. physicallyCorrectLights: renderer.physicallyCorrectLights,
  11843. premultipliedAlpha: material.premultipliedAlpha,
  11844. doubleSided: material.side === DoubleSide,
  11845. flipSided: material.side === BackSide,
  11846. useDepthPacking: !!material.depthPacking,
  11847. depthPacking: material.depthPacking || 0,
  11848. index0AttributeName: material.index0AttributeName,
  11849. extensionDerivatives: material.extensions && material.extensions.derivatives,
  11850. extensionFragDepth: material.extensions && material.extensions.fragDepth,
  11851. extensionDrawBuffers: material.extensions && material.extensions.drawBuffers,
  11852. extensionShaderTextureLOD: material.extensions && material.extensions.shaderTextureLOD,
  11853. rendererExtensionFragDepth: isWebGL2 || extensions.has('EXT_frag_depth'),
  11854. rendererExtensionDrawBuffers: isWebGL2 || extensions.has('WEBGL_draw_buffers'),
  11855. rendererExtensionShaderTextureLod: isWebGL2 || extensions.has('EXT_shader_texture_lod'),
  11856. customProgramCacheKey: material.customProgramCacheKey()
  11857. };
  11858. return parameters;
  11859. }
  11860. function getProgramCacheKey(parameters) {
  11861. const array = [];
  11862. if (parameters.shaderID) {
  11863. array.push(parameters.shaderID);
  11864. } else {
  11865. array.push(parameters.customVertexShaderID);
  11866. array.push(parameters.customFragmentShaderID);
  11867. }
  11868. if (parameters.defines !== undefined) {
  11869. for (const name in parameters.defines) {
  11870. array.push(name);
  11871. array.push(parameters.defines[name]);
  11872. }
  11873. }
  11874. if (parameters.isRawShaderMaterial === false) {
  11875. getProgramCacheKeyParameters(array, parameters);
  11876. getProgramCacheKeyBooleans(array, parameters);
  11877. array.push(renderer.outputEncoding);
  11878. }
  11879. array.push(parameters.customProgramCacheKey);
  11880. return array.join();
  11881. }
  11882. function getProgramCacheKeyParameters(array, parameters) {
  11883. array.push(parameters.precision);
  11884. array.push(parameters.outputEncoding);
  11885. array.push(parameters.envMapMode);
  11886. array.push(parameters.envMapCubeUVHeight);
  11887. array.push(parameters.combine);
  11888. array.push(parameters.vertexUvs);
  11889. array.push(parameters.fogExp2);
  11890. array.push(parameters.sizeAttenuation);
  11891. array.push(parameters.morphTargetsCount);
  11892. array.push(parameters.morphAttributeCount);
  11893. array.push(parameters.numDirLights);
  11894. array.push(parameters.numPointLights);
  11895. array.push(parameters.numSpotLights);
  11896. array.push(parameters.numHemiLights);
  11897. array.push(parameters.numRectAreaLights);
  11898. array.push(parameters.numDirLightShadows);
  11899. array.push(parameters.numPointLightShadows);
  11900. array.push(parameters.numSpotLightShadows);
  11901. array.push(parameters.shadowMapType);
  11902. array.push(parameters.toneMapping);
  11903. array.push(parameters.numClippingPlanes);
  11904. array.push(parameters.numClipIntersection);
  11905. array.push(parameters.depthPacking);
  11906. }
  11907. function getProgramCacheKeyBooleans(array, parameters) {
  11908. _programLayers.disableAll();
  11909. if (parameters.isWebGL2) _programLayers.enable(0);
  11910. if (parameters.supportsVertexTextures) _programLayers.enable(1);
  11911. if (parameters.instancing) _programLayers.enable(2);
  11912. if (parameters.instancingColor) _programLayers.enable(3);
  11913. if (parameters.map) _programLayers.enable(4);
  11914. if (parameters.matcap) _programLayers.enable(5);
  11915. if (parameters.envMap) _programLayers.enable(6);
  11916. if (parameters.lightMap) _programLayers.enable(7);
  11917. if (parameters.aoMap) _programLayers.enable(8);
  11918. if (parameters.emissiveMap) _programLayers.enable(9);
  11919. if (parameters.bumpMap) _programLayers.enable(10);
  11920. if (parameters.normalMap) _programLayers.enable(11);
  11921. if (parameters.objectSpaceNormalMap) _programLayers.enable(12);
  11922. if (parameters.tangentSpaceNormalMap) _programLayers.enable(13);
  11923. if (parameters.clearcoat) _programLayers.enable(14);
  11924. if (parameters.clearcoatMap) _programLayers.enable(15);
  11925. if (parameters.clearcoatRoughnessMap) _programLayers.enable(16);
  11926. if (parameters.clearcoatNormalMap) _programLayers.enable(17);
  11927. if (parameters.displacementMap) _programLayers.enable(18);
  11928. if (parameters.specularMap) _programLayers.enable(19);
  11929. if (parameters.roughnessMap) _programLayers.enable(20);
  11930. if (parameters.metalnessMap) _programLayers.enable(21);
  11931. if (parameters.gradientMap) _programLayers.enable(22);
  11932. if (parameters.alphaMap) _programLayers.enable(23);
  11933. if (parameters.alphaTest) _programLayers.enable(24);
  11934. if (parameters.vertexColors) _programLayers.enable(25);
  11935. if (parameters.vertexAlphas) _programLayers.enable(26);
  11936. if (parameters.vertexUvs) _programLayers.enable(27);
  11937. if (parameters.vertexTangents) _programLayers.enable(28);
  11938. if (parameters.uvsVertexOnly) _programLayers.enable(29);
  11939. if (parameters.fog) _programLayers.enable(30);
  11940. array.push(_programLayers.mask);
  11941. _programLayers.disableAll();
  11942. if (parameters.useFog) _programLayers.enable(0);
  11943. if (parameters.flatShading) _programLayers.enable(1);
  11944. if (parameters.logarithmicDepthBuffer) _programLayers.enable(2);
  11945. if (parameters.skinning) _programLayers.enable(3);
  11946. if (parameters.morphTargets) _programLayers.enable(4);
  11947. if (parameters.morphNormals) _programLayers.enable(5);
  11948. if (parameters.morphColors) _programLayers.enable(6);
  11949. if (parameters.premultipliedAlpha) _programLayers.enable(7);
  11950. if (parameters.shadowMapEnabled) _programLayers.enable(8);
  11951. if (parameters.physicallyCorrectLights) _programLayers.enable(9);
  11952. if (parameters.doubleSided) _programLayers.enable(10);
  11953. if (parameters.flipSided) _programLayers.enable(11);
  11954. if (parameters.useDepthPacking) _programLayers.enable(12);
  11955. if (parameters.dithering) _programLayers.enable(13);
  11956. if (parameters.specularIntensityMap) _programLayers.enable(14);
  11957. if (parameters.specularColorMap) _programLayers.enable(15);
  11958. if (parameters.transmission) _programLayers.enable(16);
  11959. if (parameters.transmissionMap) _programLayers.enable(17);
  11960. if (parameters.thicknessMap) _programLayers.enable(18);
  11961. if (parameters.sheen) _programLayers.enable(19);
  11962. if (parameters.sheenColorMap) _programLayers.enable(20);
  11963. if (parameters.sheenRoughnessMap) _programLayers.enable(21);
  11964. if (parameters.decodeVideoTexture) _programLayers.enable(22);
  11965. if (parameters.opaque) _programLayers.enable(23);
  11966. array.push(_programLayers.mask);
  11967. }
  11968. function getUniforms(material) {
  11969. const shaderID = shaderIDs[material.type];
  11970. let uniforms;
  11971. if (shaderID) {
  11972. const shader = ShaderLib[shaderID];
  11973. uniforms = UniformsUtils.clone(shader.uniforms);
  11974. } else {
  11975. uniforms = material.uniforms;
  11976. }
  11977. return uniforms;
  11978. }
  11979. function acquireProgram(parameters, cacheKey) {
  11980. let program; // Check if code has been already compiled
  11981. for (let p = 0, pl = programs.length; p < pl; p++) {
  11982. const preexistingProgram = programs[p];
  11983. if (preexistingProgram.cacheKey === cacheKey) {
  11984. program = preexistingProgram;
  11985. ++program.usedTimes;
  11986. break;
  11987. }
  11988. }
  11989. if (program === undefined) {
  11990. program = new WebGLProgram(renderer, cacheKey, parameters, bindingStates);
  11991. programs.push(program);
  11992. }
  11993. return program;
  11994. }
  11995. function releaseProgram(program) {
  11996. if (--program.usedTimes === 0) {
  11997. // Remove from unordered set
  11998. const i = programs.indexOf(program);
  11999. programs[i] = programs[programs.length - 1];
  12000. programs.pop(); // Free WebGL resources
  12001. program.destroy();
  12002. }
  12003. }
  12004. function releaseShaderCache(material) {
  12005. _customShaders.remove(material);
  12006. }
  12007. function dispose() {
  12008. _customShaders.dispose();
  12009. }
  12010. return {
  12011. getParameters: getParameters,
  12012. getProgramCacheKey: getProgramCacheKey,
  12013. getUniforms: getUniforms,
  12014. acquireProgram: acquireProgram,
  12015. releaseProgram: releaseProgram,
  12016. releaseShaderCache: releaseShaderCache,
  12017. // Exposed for resource monitoring & error feedback via renderer.info:
  12018. programs: programs,
  12019. dispose: dispose
  12020. };
  12021. }
  12022. function WebGLProperties() {
  12023. let properties = new WeakMap();
  12024. function get(object) {
  12025. let map = properties.get(object);
  12026. if (map === undefined) {
  12027. map = {};
  12028. properties.set(object, map);
  12029. }
  12030. return map;
  12031. }
  12032. function remove(object) {
  12033. properties.delete(object);
  12034. }
  12035. function update(object, key, value) {
  12036. properties.get(object)[key] = value;
  12037. }
  12038. function dispose() {
  12039. properties = new WeakMap();
  12040. }
  12041. return {
  12042. get: get,
  12043. remove: remove,
  12044. update: update,
  12045. dispose: dispose
  12046. };
  12047. }
  12048. function painterSortStable(a, b) {
  12049. if (a.groupOrder !== b.groupOrder) {
  12050. return a.groupOrder - b.groupOrder;
  12051. } else if (a.renderOrder !== b.renderOrder) {
  12052. return a.renderOrder - b.renderOrder;
  12053. } else if (a.material.id !== b.material.id) {
  12054. return a.material.id - b.material.id;
  12055. } else if (a.z !== b.z) {
  12056. return a.z - b.z;
  12057. } else {
  12058. return a.id - b.id;
  12059. }
  12060. }
  12061. function reversePainterSortStable(a, b) {
  12062. if (a.groupOrder !== b.groupOrder) {
  12063. return a.groupOrder - b.groupOrder;
  12064. } else if (a.renderOrder !== b.renderOrder) {
  12065. return a.renderOrder - b.renderOrder;
  12066. } else if (a.z !== b.z) {
  12067. return b.z - a.z;
  12068. } else {
  12069. return a.id - b.id;
  12070. }
  12071. }
  12072. function WebGLRenderList() {
  12073. const renderItems = [];
  12074. let renderItemsIndex = 0;
  12075. const opaque = [];
  12076. const transmissive = [];
  12077. const transparent = [];
  12078. function init() {
  12079. renderItemsIndex = 0;
  12080. opaque.length = 0;
  12081. transmissive.length = 0;
  12082. transparent.length = 0;
  12083. }
  12084. function getNextRenderItem(object, geometry, material, groupOrder, z, group) {
  12085. let renderItem = renderItems[renderItemsIndex];
  12086. if (renderItem === undefined) {
  12087. renderItem = {
  12088. id: object.id,
  12089. object: object,
  12090. geometry: geometry,
  12091. material: material,
  12092. groupOrder: groupOrder,
  12093. renderOrder: object.renderOrder,
  12094. z: z,
  12095. group: group
  12096. };
  12097. renderItems[renderItemsIndex] = renderItem;
  12098. } else {
  12099. renderItem.id = object.id;
  12100. renderItem.object = object;
  12101. renderItem.geometry = geometry;
  12102. renderItem.material = material;
  12103. renderItem.groupOrder = groupOrder;
  12104. renderItem.renderOrder = object.renderOrder;
  12105. renderItem.z = z;
  12106. renderItem.group = group;
  12107. }
  12108. renderItemsIndex++;
  12109. return renderItem;
  12110. }
  12111. function push(object, geometry, material, groupOrder, z, group) {
  12112. const renderItem = getNextRenderItem(object, geometry, material, groupOrder, z, group);
  12113. if (material.transmission > 0.0) {
  12114. transmissive.push(renderItem);
  12115. } else if (material.transparent === true) {
  12116. transparent.push(renderItem);
  12117. } else {
  12118. opaque.push(renderItem);
  12119. }
  12120. }
  12121. function unshift(object, geometry, material, groupOrder, z, group) {
  12122. const renderItem = getNextRenderItem(object, geometry, material, groupOrder, z, group);
  12123. if (material.transmission > 0.0) {
  12124. transmissive.unshift(renderItem);
  12125. } else if (material.transparent === true) {
  12126. transparent.unshift(renderItem);
  12127. } else {
  12128. opaque.unshift(renderItem);
  12129. }
  12130. }
  12131. function sort(customOpaqueSort, customTransparentSort) {
  12132. if (opaque.length > 1) opaque.sort(customOpaqueSort || painterSortStable);
  12133. if (transmissive.length > 1) transmissive.sort(customTransparentSort || reversePainterSortStable);
  12134. if (transparent.length > 1) transparent.sort(customTransparentSort || reversePainterSortStable);
  12135. }
  12136. function finish() {
  12137. // Clear references from inactive renderItems in the list
  12138. for (let i = renderItemsIndex, il = renderItems.length; i < il; i++) {
  12139. const renderItem = renderItems[i];
  12140. if (renderItem.id === null) break;
  12141. renderItem.id = null;
  12142. renderItem.object = null;
  12143. renderItem.geometry = null;
  12144. renderItem.material = null;
  12145. renderItem.group = null;
  12146. }
  12147. }
  12148. return {
  12149. opaque: opaque,
  12150. transmissive: transmissive,
  12151. transparent: transparent,
  12152. init: init,
  12153. push: push,
  12154. unshift: unshift,
  12155. finish: finish,
  12156. sort: sort
  12157. };
  12158. }
  12159. function WebGLRenderLists() {
  12160. let lists = new WeakMap();
  12161. function get(scene, renderCallDepth) {
  12162. let list;
  12163. if (lists.has(scene) === false) {
  12164. list = new WebGLRenderList();
  12165. lists.set(scene, [list]);
  12166. } else {
  12167. if (renderCallDepth >= lists.get(scene).length) {
  12168. list = new WebGLRenderList();
  12169. lists.get(scene).push(list);
  12170. } else {
  12171. list = lists.get(scene)[renderCallDepth];
  12172. }
  12173. }
  12174. return list;
  12175. }
  12176. function dispose() {
  12177. lists = new WeakMap();
  12178. }
  12179. return {
  12180. get: get,
  12181. dispose: dispose
  12182. };
  12183. }
  12184. function UniformsCache() {
  12185. const lights = {};
  12186. return {
  12187. get: function (light) {
  12188. if (lights[light.id] !== undefined) {
  12189. return lights[light.id];
  12190. }
  12191. let uniforms;
  12192. switch (light.type) {
  12193. case 'DirectionalLight':
  12194. uniforms = {
  12195. direction: new Vector3(),
  12196. color: new Color()
  12197. };
  12198. break;
  12199. case 'SpotLight':
  12200. uniforms = {
  12201. position: new Vector3(),
  12202. direction: new Vector3(),
  12203. color: new Color(),
  12204. distance: 0,
  12205. coneCos: 0,
  12206. penumbraCos: 0,
  12207. decay: 0
  12208. };
  12209. break;
  12210. case 'PointLight':
  12211. uniforms = {
  12212. position: new Vector3(),
  12213. color: new Color(),
  12214. distance: 0,
  12215. decay: 0
  12216. };
  12217. break;
  12218. case 'HemisphereLight':
  12219. uniforms = {
  12220. direction: new Vector3(),
  12221. skyColor: new Color(),
  12222. groundColor: new Color()
  12223. };
  12224. break;
  12225. case 'RectAreaLight':
  12226. uniforms = {
  12227. color: new Color(),
  12228. position: new Vector3(),
  12229. halfWidth: new Vector3(),
  12230. halfHeight: new Vector3()
  12231. };
  12232. break;
  12233. }
  12234. lights[light.id] = uniforms;
  12235. return uniforms;
  12236. }
  12237. };
  12238. }
  12239. function ShadowUniformsCache() {
  12240. const lights = {};
  12241. return {
  12242. get: function (light) {
  12243. if (lights[light.id] !== undefined) {
  12244. return lights[light.id];
  12245. }
  12246. let uniforms;
  12247. switch (light.type) {
  12248. case 'DirectionalLight':
  12249. uniforms = {
  12250. shadowBias: 0,
  12251. shadowNormalBias: 0,
  12252. shadowRadius: 1,
  12253. shadowMapSize: new Vector2()
  12254. };
  12255. break;
  12256. case 'SpotLight':
  12257. uniforms = {
  12258. shadowBias: 0,
  12259. shadowNormalBias: 0,
  12260. shadowRadius: 1,
  12261. shadowMapSize: new Vector2()
  12262. };
  12263. break;
  12264. case 'PointLight':
  12265. uniforms = {
  12266. shadowBias: 0,
  12267. shadowNormalBias: 0,
  12268. shadowRadius: 1,
  12269. shadowMapSize: new Vector2(),
  12270. shadowCameraNear: 1,
  12271. shadowCameraFar: 1000
  12272. };
  12273. break;
  12274. // TODO (abelnation): set RectAreaLight shadow uniforms
  12275. }
  12276. lights[light.id] = uniforms;
  12277. return uniforms;
  12278. }
  12279. };
  12280. }
  12281. let nextVersion = 0;
  12282. function shadowCastingLightsFirst(lightA, lightB) {
  12283. return (lightB.castShadow ? 1 : 0) - (lightA.castShadow ? 1 : 0);
  12284. }
  12285. function WebGLLights(extensions, capabilities) {
  12286. const cache = new UniformsCache();
  12287. const shadowCache = ShadowUniformsCache();
  12288. const state = {
  12289. version: 0,
  12290. hash: {
  12291. directionalLength: -1,
  12292. pointLength: -1,
  12293. spotLength: -1,
  12294. rectAreaLength: -1,
  12295. hemiLength: -1,
  12296. numDirectionalShadows: -1,
  12297. numPointShadows: -1,
  12298. numSpotShadows: -1
  12299. },
  12300. ambient: [0, 0, 0],
  12301. probe: [],
  12302. directional: [],
  12303. directionalShadow: [],
  12304. directionalShadowMap: [],
  12305. directionalShadowMatrix: [],
  12306. spot: [],
  12307. spotShadow: [],
  12308. spotShadowMap: [],
  12309. spotShadowMatrix: [],
  12310. rectArea: [],
  12311. rectAreaLTC1: null,
  12312. rectAreaLTC2: null,
  12313. point: [],
  12314. pointShadow: [],
  12315. pointShadowMap: [],
  12316. pointShadowMatrix: [],
  12317. hemi: []
  12318. };
  12319. for (let i = 0; i < 9; i++) state.probe.push(new Vector3());
  12320. const vector3 = new Vector3();
  12321. const matrix4 = new Matrix4();
  12322. const matrix42 = new Matrix4();
  12323. function setup(lights, physicallyCorrectLights) {
  12324. let r = 0,
  12325. g = 0,
  12326. b = 0;
  12327. for (let i = 0; i < 9; i++) state.probe[i].set(0, 0, 0);
  12328. let directionalLength = 0;
  12329. let pointLength = 0;
  12330. let spotLength = 0;
  12331. let rectAreaLength = 0;
  12332. let hemiLength = 0;
  12333. let numDirectionalShadows = 0;
  12334. let numPointShadows = 0;
  12335. let numSpotShadows = 0;
  12336. lights.sort(shadowCastingLightsFirst); // artist-friendly light intensity scaling factor
  12337. const scaleFactor = physicallyCorrectLights !== true ? Math.PI : 1;
  12338. for (let i = 0, l = lights.length; i < l; i++) {
  12339. const light = lights[i];
  12340. const color = light.color;
  12341. const intensity = light.intensity;
  12342. const distance = light.distance;
  12343. const shadowMap = light.shadow && light.shadow.map ? light.shadow.map.texture : null;
  12344. if (light.isAmbientLight) {
  12345. r += color.r * intensity * scaleFactor;
  12346. g += color.g * intensity * scaleFactor;
  12347. b += color.b * intensity * scaleFactor;
  12348. } else if (light.isLightProbe) {
  12349. for (let j = 0; j < 9; j++) {
  12350. state.probe[j].addScaledVector(light.sh.coefficients[j], intensity);
  12351. }
  12352. } else if (light.isDirectionalLight) {
  12353. const uniforms = cache.get(light);
  12354. uniforms.color.copy(light.color).multiplyScalar(light.intensity * scaleFactor);
  12355. if (light.castShadow) {
  12356. const shadow = light.shadow;
  12357. const shadowUniforms = shadowCache.get(light);
  12358. shadowUniforms.shadowBias = shadow.bias;
  12359. shadowUniforms.shadowNormalBias = shadow.normalBias;
  12360. shadowUniforms.shadowRadius = shadow.radius;
  12361. shadowUniforms.shadowMapSize = shadow.mapSize;
  12362. state.directionalShadow[directionalLength] = shadowUniforms;
  12363. state.directionalShadowMap[directionalLength] = shadowMap;
  12364. state.directionalShadowMatrix[directionalLength] = light.shadow.matrix;
  12365. numDirectionalShadows++;
  12366. }
  12367. state.directional[directionalLength] = uniforms;
  12368. directionalLength++;
  12369. } else if (light.isSpotLight) {
  12370. const uniforms = cache.get(light);
  12371. uniforms.position.setFromMatrixPosition(light.matrixWorld);
  12372. uniforms.color.copy(color).multiplyScalar(intensity * scaleFactor);
  12373. uniforms.distance = distance;
  12374. uniforms.coneCos = Math.cos(light.angle);
  12375. uniforms.penumbraCos = Math.cos(light.angle * (1 - light.penumbra));
  12376. uniforms.decay = light.decay;
  12377. if (light.castShadow) {
  12378. const shadow = light.shadow;
  12379. const shadowUniforms = shadowCache.get(light);
  12380. shadowUniforms.shadowBias = shadow.bias;
  12381. shadowUniforms.shadowNormalBias = shadow.normalBias;
  12382. shadowUniforms.shadowRadius = shadow.radius;
  12383. shadowUniforms.shadowMapSize = shadow.mapSize;
  12384. state.spotShadow[spotLength] = shadowUniforms;
  12385. state.spotShadowMap[spotLength] = shadowMap;
  12386. state.spotShadowMatrix[spotLength] = light.shadow.matrix;
  12387. numSpotShadows++;
  12388. }
  12389. state.spot[spotLength] = uniforms;
  12390. spotLength++;
  12391. } else if (light.isRectAreaLight) {
  12392. const uniforms = cache.get(light); // (a) intensity is the total visible light emitted
  12393. //uniforms.color.copy( color ).multiplyScalar( intensity / ( light.width * light.height * Math.PI ) );
  12394. // (b) intensity is the brightness of the light
  12395. uniforms.color.copy(color).multiplyScalar(intensity);
  12396. uniforms.halfWidth.set(light.width * 0.5, 0.0, 0.0);
  12397. uniforms.halfHeight.set(0.0, light.height * 0.5, 0.0);
  12398. state.rectArea[rectAreaLength] = uniforms;
  12399. rectAreaLength++;
  12400. } else if (light.isPointLight) {
  12401. const uniforms = cache.get(light);
  12402. uniforms.color.copy(light.color).multiplyScalar(light.intensity * scaleFactor);
  12403. uniforms.distance = light.distance;
  12404. uniforms.decay = light.decay;
  12405. if (light.castShadow) {
  12406. const shadow = light.shadow;
  12407. const shadowUniforms = shadowCache.get(light);
  12408. shadowUniforms.shadowBias = shadow.bias;
  12409. shadowUniforms.shadowNormalBias = shadow.normalBias;
  12410. shadowUniforms.shadowRadius = shadow.radius;
  12411. shadowUniforms.shadowMapSize = shadow.mapSize;
  12412. shadowUniforms.shadowCameraNear = shadow.camera.near;
  12413. shadowUniforms.shadowCameraFar = shadow.camera.far;
  12414. state.pointShadow[pointLength] = shadowUniforms;
  12415. state.pointShadowMap[pointLength] = shadowMap;
  12416. state.pointShadowMatrix[pointLength] = light.shadow.matrix;
  12417. numPointShadows++;
  12418. }
  12419. state.point[pointLength] = uniforms;
  12420. pointLength++;
  12421. } else if (light.isHemisphereLight) {
  12422. const uniforms = cache.get(light);
  12423. uniforms.skyColor.copy(light.color).multiplyScalar(intensity * scaleFactor);
  12424. uniforms.groundColor.copy(light.groundColor).multiplyScalar(intensity * scaleFactor);
  12425. state.hemi[hemiLength] = uniforms;
  12426. hemiLength++;
  12427. }
  12428. }
  12429. if (rectAreaLength > 0) {
  12430. if (capabilities.isWebGL2) {
  12431. // WebGL 2
  12432. state.rectAreaLTC1 = UniformsLib.LTC_FLOAT_1;
  12433. state.rectAreaLTC2 = UniformsLib.LTC_FLOAT_2;
  12434. } else {
  12435. // WebGL 1
  12436. if (extensions.has('OES_texture_float_linear') === true) {
  12437. state.rectAreaLTC1 = UniformsLib.LTC_FLOAT_1;
  12438. state.rectAreaLTC2 = UniformsLib.LTC_FLOAT_2;
  12439. } else if (extensions.has('OES_texture_half_float_linear') === true) {
  12440. state.rectAreaLTC1 = UniformsLib.LTC_HALF_1;
  12441. state.rectAreaLTC2 = UniformsLib.LTC_HALF_2;
  12442. } else {
  12443. console.error('THREE.WebGLRenderer: Unable to use RectAreaLight. Missing WebGL extensions.');
  12444. }
  12445. }
  12446. }
  12447. state.ambient[0] = r;
  12448. state.ambient[1] = g;
  12449. state.ambient[2] = b;
  12450. const hash = state.hash;
  12451. 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) {
  12452. state.directional.length = directionalLength;
  12453. state.spot.length = spotLength;
  12454. state.rectArea.length = rectAreaLength;
  12455. state.point.length = pointLength;
  12456. state.hemi.length = hemiLength;
  12457. state.directionalShadow.length = numDirectionalShadows;
  12458. state.directionalShadowMap.length = numDirectionalShadows;
  12459. state.pointShadow.length = numPointShadows;
  12460. state.pointShadowMap.length = numPointShadows;
  12461. state.spotShadow.length = numSpotShadows;
  12462. state.spotShadowMap.length = numSpotShadows;
  12463. state.directionalShadowMatrix.length = numDirectionalShadows;
  12464. state.pointShadowMatrix.length = numPointShadows;
  12465. state.spotShadowMatrix.length = numSpotShadows;
  12466. hash.directionalLength = directionalLength;
  12467. hash.pointLength = pointLength;
  12468. hash.spotLength = spotLength;
  12469. hash.rectAreaLength = rectAreaLength;
  12470. hash.hemiLength = hemiLength;
  12471. hash.numDirectionalShadows = numDirectionalShadows;
  12472. hash.numPointShadows = numPointShadows;
  12473. hash.numSpotShadows = numSpotShadows;
  12474. state.version = nextVersion++;
  12475. }
  12476. }
  12477. function setupView(lights, camera) {
  12478. let directionalLength = 0;
  12479. let pointLength = 0;
  12480. let spotLength = 0;
  12481. let rectAreaLength = 0;
  12482. let hemiLength = 0;
  12483. const viewMatrix = camera.matrixWorldInverse;
  12484. for (let i = 0, l = lights.length; i < l; i++) {
  12485. const light = lights[i];
  12486. if (light.isDirectionalLight) {
  12487. const uniforms = state.directional[directionalLength];
  12488. uniforms.direction.setFromMatrixPosition(light.matrixWorld);
  12489. vector3.setFromMatrixPosition(light.target.matrixWorld);
  12490. uniforms.direction.sub(vector3);
  12491. uniforms.direction.transformDirection(viewMatrix);
  12492. directionalLength++;
  12493. } else if (light.isSpotLight) {
  12494. const uniforms = state.spot[spotLength];
  12495. uniforms.position.setFromMatrixPosition(light.matrixWorld);
  12496. uniforms.position.applyMatrix4(viewMatrix);
  12497. uniforms.direction.setFromMatrixPosition(light.matrixWorld);
  12498. vector3.setFromMatrixPosition(light.target.matrixWorld);
  12499. uniforms.direction.sub(vector3);
  12500. uniforms.direction.transformDirection(viewMatrix);
  12501. spotLength++;
  12502. } else if (light.isRectAreaLight) {
  12503. const uniforms = state.rectArea[rectAreaLength];
  12504. uniforms.position.setFromMatrixPosition(light.matrixWorld);
  12505. uniforms.position.applyMatrix4(viewMatrix); // extract local rotation of light to derive width/height half vectors
  12506. matrix42.identity();
  12507. matrix4.copy(light.matrixWorld);
  12508. matrix4.premultiply(viewMatrix);
  12509. matrix42.extractRotation(matrix4);
  12510. uniforms.halfWidth.set(light.width * 0.5, 0.0, 0.0);
  12511. uniforms.halfHeight.set(0.0, light.height * 0.5, 0.0);
  12512. uniforms.halfWidth.applyMatrix4(matrix42);
  12513. uniforms.halfHeight.applyMatrix4(matrix42);
  12514. rectAreaLength++;
  12515. } else if (light.isPointLight) {
  12516. const uniforms = state.point[pointLength];
  12517. uniforms.position.setFromMatrixPosition(light.matrixWorld);
  12518. uniforms.position.applyMatrix4(viewMatrix);
  12519. pointLength++;
  12520. } else if (light.isHemisphereLight) {
  12521. const uniforms = state.hemi[hemiLength];
  12522. uniforms.direction.setFromMatrixPosition(light.matrixWorld);
  12523. uniforms.direction.transformDirection(viewMatrix);
  12524. hemiLength++;
  12525. }
  12526. }
  12527. }
  12528. return {
  12529. setup: setup,
  12530. setupView: setupView,
  12531. state: state
  12532. };
  12533. }
  12534. function WebGLRenderState(extensions, capabilities) {
  12535. const lights = new WebGLLights(extensions, capabilities);
  12536. const lightsArray = [];
  12537. const shadowsArray = [];
  12538. function init() {
  12539. lightsArray.length = 0;
  12540. shadowsArray.length = 0;
  12541. }
  12542. function pushLight(light) {
  12543. lightsArray.push(light);
  12544. }
  12545. function pushShadow(shadowLight) {
  12546. shadowsArray.push(shadowLight);
  12547. }
  12548. function setupLights(physicallyCorrectLights) {
  12549. lights.setup(lightsArray, physicallyCorrectLights);
  12550. }
  12551. function setupLightsView(camera) {
  12552. lights.setupView(lightsArray, camera);
  12553. }
  12554. const state = {
  12555. lightsArray: lightsArray,
  12556. shadowsArray: shadowsArray,
  12557. lights: lights
  12558. };
  12559. return {
  12560. init: init,
  12561. state: state,
  12562. setupLights: setupLights,
  12563. setupLightsView: setupLightsView,
  12564. pushLight: pushLight,
  12565. pushShadow: pushShadow
  12566. };
  12567. }
  12568. function WebGLRenderStates(extensions, capabilities) {
  12569. let renderStates = new WeakMap();
  12570. function get(scene, renderCallDepth = 0) {
  12571. let renderState;
  12572. if (renderStates.has(scene) === false) {
  12573. renderState = new WebGLRenderState(extensions, capabilities);
  12574. renderStates.set(scene, [renderState]);
  12575. } else {
  12576. if (renderCallDepth >= renderStates.get(scene).length) {
  12577. renderState = new WebGLRenderState(extensions, capabilities);
  12578. renderStates.get(scene).push(renderState);
  12579. } else {
  12580. renderState = renderStates.get(scene)[renderCallDepth];
  12581. }
  12582. }
  12583. return renderState;
  12584. }
  12585. function dispose() {
  12586. renderStates = new WeakMap();
  12587. }
  12588. return {
  12589. get: get,
  12590. dispose: dispose
  12591. };
  12592. }
  12593. class MeshDepthMaterial extends Material {
  12594. constructor(parameters) {
  12595. super();
  12596. this.isMeshDepthMaterial = true;
  12597. this.type = 'MeshDepthMaterial';
  12598. this.depthPacking = BasicDepthPacking;
  12599. this.map = null;
  12600. this.alphaMap = null;
  12601. this.displacementMap = null;
  12602. this.displacementScale = 1;
  12603. this.displacementBias = 0;
  12604. this.wireframe = false;
  12605. this.wireframeLinewidth = 1;
  12606. this.setValues(parameters);
  12607. }
  12608. copy(source) {
  12609. super.copy(source);
  12610. this.depthPacking = source.depthPacking;
  12611. this.map = source.map;
  12612. this.alphaMap = source.alphaMap;
  12613. this.displacementMap = source.displacementMap;
  12614. this.displacementScale = source.displacementScale;
  12615. this.displacementBias = source.displacementBias;
  12616. this.wireframe = source.wireframe;
  12617. this.wireframeLinewidth = source.wireframeLinewidth;
  12618. return this;
  12619. }
  12620. }
  12621. class MeshDistanceMaterial extends Material {
  12622. constructor(parameters) {
  12623. super();
  12624. this.isMeshDistanceMaterial = true;
  12625. this.type = 'MeshDistanceMaterial';
  12626. this.referencePosition = new Vector3();
  12627. this.nearDistance = 1;
  12628. this.farDistance = 1000;
  12629. this.map = null;
  12630. this.alphaMap = null;
  12631. this.displacementMap = null;
  12632. this.displacementScale = 1;
  12633. this.displacementBias = 0;
  12634. this.setValues(parameters);
  12635. }
  12636. copy(source) {
  12637. super.copy(source);
  12638. this.referencePosition.copy(source.referencePosition);
  12639. this.nearDistance = source.nearDistance;
  12640. this.farDistance = source.farDistance;
  12641. this.map = source.map;
  12642. this.alphaMap = source.alphaMap;
  12643. this.displacementMap = source.displacementMap;
  12644. this.displacementScale = source.displacementScale;
  12645. this.displacementBias = source.displacementBias;
  12646. return this;
  12647. }
  12648. }
  12649. const vertex = "void main() {\n\tgl_Position = vec4( position, 1.0 );\n}";
  12650. const fragment = "uniform sampler2D shadow_pass;\nuniform vec2 resolution;\nuniform float radius;\n#include <packing>\nvoid main() {\n\tconst float samples = float( VSM_SAMPLES );\n\tfloat mean = 0.0;\n\tfloat squared_mean = 0.0;\n\tfloat uvStride = samples <= 1.0 ? 0.0 : 2.0 / ( samples - 1.0 );\n\tfloat uvStart = samples <= 1.0 ? 0.0 : - 1.0;\n\tfor ( float i = 0.0; i < samples; i ++ ) {\n\t\tfloat uvOffset = uvStart + i * uvStride;\n\t\t#ifdef HORIZONTAL_PASS\n\t\t\tvec2 distribution = unpackRGBATo2Half( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( uvOffset, 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, uvOffset ) * radius ) / resolution ) );\n\t\t\tmean += depth;\n\t\t\tsquared_mean += depth * depth;\n\t\t#endif\n\t}\n\tmean = mean / samples;\n\tsquared_mean = squared_mean / samples;\n\tfloat std_dev = sqrt( squared_mean - mean * mean );\n\tgl_FragColor = pack2HalfToRGBA( vec2( mean, std_dev ) );\n}";
  12651. function WebGLShadowMap(_renderer, _objects, _capabilities) {
  12652. let _frustum = new Frustum();
  12653. const _shadowMapSize = new Vector2(),
  12654. _viewportSize = new Vector2(),
  12655. _viewport = new Vector4(),
  12656. _depthMaterial = new MeshDepthMaterial({
  12657. depthPacking: RGBADepthPacking
  12658. }),
  12659. _distanceMaterial = new MeshDistanceMaterial(),
  12660. _materialCache = {},
  12661. _maxTextureSize = _capabilities.maxTextureSize;
  12662. const shadowSide = {
  12663. 0: BackSide,
  12664. 1: FrontSide,
  12665. 2: DoubleSide
  12666. };
  12667. const shadowMaterialVertical = new ShaderMaterial({
  12668. defines: {
  12669. VSM_SAMPLES: 8
  12670. },
  12671. uniforms: {
  12672. shadow_pass: {
  12673. value: null
  12674. },
  12675. resolution: {
  12676. value: new Vector2()
  12677. },
  12678. radius: {
  12679. value: 4.0
  12680. }
  12681. },
  12682. vertexShader: vertex,
  12683. fragmentShader: fragment
  12684. });
  12685. const shadowMaterialHorizontal = shadowMaterialVertical.clone();
  12686. shadowMaterialHorizontal.defines.HORIZONTAL_PASS = 1;
  12687. const fullScreenTri = new BufferGeometry();
  12688. fullScreenTri.setAttribute('position', new BufferAttribute(new Float32Array([-1, -1, 0.5, 3, -1, 0.5, -1, 3, 0.5]), 3));
  12689. const fullScreenMesh = new Mesh(fullScreenTri, shadowMaterialVertical);
  12690. const scope = this;
  12691. this.enabled = false;
  12692. this.autoUpdate = true;
  12693. this.needsUpdate = false;
  12694. this.type = PCFShadowMap;
  12695. this.render = function (lights, scene, camera) {
  12696. if (scope.enabled === false) return;
  12697. if (scope.autoUpdate === false && scope.needsUpdate === false) return;
  12698. if (lights.length === 0) return;
  12699. const currentRenderTarget = _renderer.getRenderTarget();
  12700. const activeCubeFace = _renderer.getActiveCubeFace();
  12701. const activeMipmapLevel = _renderer.getActiveMipmapLevel();
  12702. const _state = _renderer.state; // Set GL state for depth map.
  12703. _state.setBlending(NoBlending);
  12704. _state.buffers.color.setClear(1, 1, 1, 1);
  12705. _state.buffers.depth.setTest(true);
  12706. _state.setScissorTest(false); // render depth map
  12707. for (let i = 0, il = lights.length; i < il; i++) {
  12708. const light = lights[i];
  12709. const shadow = light.shadow;
  12710. if (shadow === undefined) {
  12711. console.warn('THREE.WebGLShadowMap:', light, 'has no shadow.');
  12712. continue;
  12713. }
  12714. if (shadow.autoUpdate === false && shadow.needsUpdate === false) continue;
  12715. _shadowMapSize.copy(shadow.mapSize);
  12716. const shadowFrameExtents = shadow.getFrameExtents();
  12717. _shadowMapSize.multiply(shadowFrameExtents);
  12718. _viewportSize.copy(shadow.mapSize);
  12719. if (_shadowMapSize.x > _maxTextureSize || _shadowMapSize.y > _maxTextureSize) {
  12720. if (_shadowMapSize.x > _maxTextureSize) {
  12721. _viewportSize.x = Math.floor(_maxTextureSize / shadowFrameExtents.x);
  12722. _shadowMapSize.x = _viewportSize.x * shadowFrameExtents.x;
  12723. shadow.mapSize.x = _viewportSize.x;
  12724. }
  12725. if (_shadowMapSize.y > _maxTextureSize) {
  12726. _viewportSize.y = Math.floor(_maxTextureSize / shadowFrameExtents.y);
  12727. _shadowMapSize.y = _viewportSize.y * shadowFrameExtents.y;
  12728. shadow.mapSize.y = _viewportSize.y;
  12729. }
  12730. }
  12731. if (shadow.map === null && !shadow.isPointLightShadow && this.type === VSMShadowMap) {
  12732. shadow.map = new WebGLRenderTarget(_shadowMapSize.x, _shadowMapSize.y);
  12733. shadow.map.texture.name = light.name + '.shadowMap';
  12734. shadow.mapPass = new WebGLRenderTarget(_shadowMapSize.x, _shadowMapSize.y);
  12735. shadow.camera.updateProjectionMatrix();
  12736. }
  12737. if (shadow.map === null) {
  12738. const pars = {
  12739. minFilter: NearestFilter,
  12740. magFilter: NearestFilter,
  12741. format: RGBAFormat
  12742. };
  12743. shadow.map = new WebGLRenderTarget(_shadowMapSize.x, _shadowMapSize.y, pars);
  12744. shadow.map.texture.name = light.name + '.shadowMap';
  12745. shadow.camera.updateProjectionMatrix();
  12746. }
  12747. _renderer.setRenderTarget(shadow.map);
  12748. _renderer.clear();
  12749. const viewportCount = shadow.getViewportCount();
  12750. for (let vp = 0; vp < viewportCount; vp++) {
  12751. const viewport = shadow.getViewport(vp);
  12752. _viewport.set(_viewportSize.x * viewport.x, _viewportSize.y * viewport.y, _viewportSize.x * viewport.z, _viewportSize.y * viewport.w);
  12753. _state.viewport(_viewport);
  12754. shadow.updateMatrices(light, vp);
  12755. _frustum = shadow.getFrustum();
  12756. renderObject(scene, camera, shadow.camera, light, this.type);
  12757. } // do blur pass for VSM
  12758. if (!shadow.isPointLightShadow && this.type === VSMShadowMap) {
  12759. VSMPass(shadow, camera);
  12760. }
  12761. shadow.needsUpdate = false;
  12762. }
  12763. scope.needsUpdate = false;
  12764. _renderer.setRenderTarget(currentRenderTarget, activeCubeFace, activeMipmapLevel);
  12765. };
  12766. function VSMPass(shadow, camera) {
  12767. const geometry = _objects.update(fullScreenMesh);
  12768. if (shadowMaterialVertical.defines.VSM_SAMPLES !== shadow.blurSamples) {
  12769. shadowMaterialVertical.defines.VSM_SAMPLES = shadow.blurSamples;
  12770. shadowMaterialHorizontal.defines.VSM_SAMPLES = shadow.blurSamples;
  12771. shadowMaterialVertical.needsUpdate = true;
  12772. shadowMaterialHorizontal.needsUpdate = true;
  12773. } // vertical pass
  12774. shadowMaterialVertical.uniforms.shadow_pass.value = shadow.map.texture;
  12775. shadowMaterialVertical.uniforms.resolution.value = shadow.mapSize;
  12776. shadowMaterialVertical.uniforms.radius.value = shadow.radius;
  12777. _renderer.setRenderTarget(shadow.mapPass);
  12778. _renderer.clear();
  12779. _renderer.renderBufferDirect(camera, null, geometry, shadowMaterialVertical, fullScreenMesh, null); // horizontal pass
  12780. shadowMaterialHorizontal.uniforms.shadow_pass.value = shadow.mapPass.texture;
  12781. shadowMaterialHorizontal.uniforms.resolution.value = shadow.mapSize;
  12782. shadowMaterialHorizontal.uniforms.radius.value = shadow.radius;
  12783. _renderer.setRenderTarget(shadow.map);
  12784. _renderer.clear();
  12785. _renderer.renderBufferDirect(camera, null, geometry, shadowMaterialHorizontal, fullScreenMesh, null);
  12786. }
  12787. function getDepthMaterial(object, material, light, shadowCameraNear, shadowCameraFar, type) {
  12788. let result = null;
  12789. const customMaterial = light.isPointLight === true ? object.customDistanceMaterial : object.customDepthMaterial;
  12790. if (customMaterial !== undefined) {
  12791. result = customMaterial;
  12792. } else {
  12793. result = light.isPointLight === true ? _distanceMaterial : _depthMaterial;
  12794. }
  12795. if (_renderer.localClippingEnabled && material.clipShadows === true && material.clippingPlanes.length !== 0 || material.displacementMap && material.displacementScale !== 0 || material.alphaMap && material.alphaTest > 0) {
  12796. // in this case we need a unique material instance reflecting the
  12797. // appropriate state
  12798. const keyA = result.uuid,
  12799. keyB = material.uuid;
  12800. let materialsForVariant = _materialCache[keyA];
  12801. if (materialsForVariant === undefined) {
  12802. materialsForVariant = {};
  12803. _materialCache[keyA] = materialsForVariant;
  12804. }
  12805. let cachedMaterial = materialsForVariant[keyB];
  12806. if (cachedMaterial === undefined) {
  12807. cachedMaterial = result.clone();
  12808. materialsForVariant[keyB] = cachedMaterial;
  12809. }
  12810. result = cachedMaterial;
  12811. }
  12812. result.visible = material.visible;
  12813. result.wireframe = material.wireframe;
  12814. if (type === VSMShadowMap) {
  12815. result.side = material.shadowSide !== null ? material.shadowSide : material.side;
  12816. } else {
  12817. result.side = material.shadowSide !== null ? material.shadowSide : shadowSide[material.side];
  12818. }
  12819. result.alphaMap = material.alphaMap;
  12820. result.alphaTest = material.alphaTest;
  12821. result.clipShadows = material.clipShadows;
  12822. result.clippingPlanes = material.clippingPlanes;
  12823. result.clipIntersection = material.clipIntersection;
  12824. result.displacementMap = material.displacementMap;
  12825. result.displacementScale = material.displacementScale;
  12826. result.displacementBias = material.displacementBias;
  12827. result.wireframeLinewidth = material.wireframeLinewidth;
  12828. result.linewidth = material.linewidth;
  12829. if (light.isPointLight === true && result.isMeshDistanceMaterial === true) {
  12830. result.referencePosition.setFromMatrixPosition(light.matrixWorld);
  12831. result.nearDistance = shadowCameraNear;
  12832. result.farDistance = shadowCameraFar;
  12833. }
  12834. return result;
  12835. }
  12836. function renderObject(object, camera, shadowCamera, light, type) {
  12837. if (object.visible === false) return;
  12838. const visible = object.layers.test(camera.layers);
  12839. if (visible && (object.isMesh || object.isLine || object.isPoints)) {
  12840. if ((object.castShadow || object.receiveShadow && type === VSMShadowMap) && (!object.frustumCulled || _frustum.intersectsObject(object))) {
  12841. object.modelViewMatrix.multiplyMatrices(shadowCamera.matrixWorldInverse, object.matrixWorld);
  12842. const geometry = _objects.update(object);
  12843. const material = object.material;
  12844. if (Array.isArray(material)) {
  12845. const groups = geometry.groups;
  12846. for (let k = 0, kl = groups.length; k < kl; k++) {
  12847. const group = groups[k];
  12848. const groupMaterial = material[group.materialIndex];
  12849. if (groupMaterial && groupMaterial.visible) {
  12850. const depthMaterial = getDepthMaterial(object, groupMaterial, light, shadowCamera.near, shadowCamera.far, type);
  12851. _renderer.renderBufferDirect(shadowCamera, null, geometry, depthMaterial, object, group);
  12852. }
  12853. }
  12854. } else if (material.visible) {
  12855. const depthMaterial = getDepthMaterial(object, material, light, shadowCamera.near, shadowCamera.far, type);
  12856. _renderer.renderBufferDirect(shadowCamera, null, geometry, depthMaterial, object, null);
  12857. }
  12858. }
  12859. }
  12860. const children = object.children;
  12861. for (let i = 0, l = children.length; i < l; i++) {
  12862. renderObject(children[i], camera, shadowCamera, light, type);
  12863. }
  12864. }
  12865. }
  12866. function WebGLState(gl, extensions, capabilities) {
  12867. const isWebGL2 = capabilities.isWebGL2;
  12868. function ColorBuffer() {
  12869. let locked = false;
  12870. const color = new Vector4();
  12871. let currentColorMask = null;
  12872. const currentColorClear = new Vector4(0, 0, 0, 0);
  12873. return {
  12874. setMask: function (colorMask) {
  12875. if (currentColorMask !== colorMask && !locked) {
  12876. gl.colorMask(colorMask, colorMask, colorMask, colorMask);
  12877. currentColorMask = colorMask;
  12878. }
  12879. },
  12880. setLocked: function (lock) {
  12881. locked = lock;
  12882. },
  12883. setClear: function (r, g, b, a, premultipliedAlpha) {
  12884. if (premultipliedAlpha === true) {
  12885. r *= a;
  12886. g *= a;
  12887. b *= a;
  12888. }
  12889. color.set(r, g, b, a);
  12890. if (currentColorClear.equals(color) === false) {
  12891. gl.clearColor(r, g, b, a);
  12892. currentColorClear.copy(color);
  12893. }
  12894. },
  12895. reset: function () {
  12896. locked = false;
  12897. currentColorMask = null;
  12898. currentColorClear.set(-1, 0, 0, 0); // set to invalid state
  12899. }
  12900. };
  12901. }
  12902. function DepthBuffer() {
  12903. let locked = false;
  12904. let currentDepthMask = null;
  12905. let currentDepthFunc = null;
  12906. let currentDepthClear = null;
  12907. return {
  12908. setTest: function (depthTest) {
  12909. if (depthTest) {
  12910. enable(gl.DEPTH_TEST);
  12911. } else {
  12912. disable(gl.DEPTH_TEST);
  12913. }
  12914. },
  12915. setMask: function (depthMask) {
  12916. if (currentDepthMask !== depthMask && !locked) {
  12917. gl.depthMask(depthMask);
  12918. currentDepthMask = depthMask;
  12919. }
  12920. },
  12921. setFunc: function (depthFunc) {
  12922. if (currentDepthFunc !== depthFunc) {
  12923. if (depthFunc) {
  12924. switch (depthFunc) {
  12925. case NeverDepth:
  12926. gl.depthFunc(gl.NEVER);
  12927. break;
  12928. case AlwaysDepth:
  12929. gl.depthFunc(gl.ALWAYS);
  12930. break;
  12931. case LessDepth:
  12932. gl.depthFunc(gl.LESS);
  12933. break;
  12934. case LessEqualDepth:
  12935. gl.depthFunc(gl.LEQUAL);
  12936. break;
  12937. case EqualDepth:
  12938. gl.depthFunc(gl.EQUAL);
  12939. break;
  12940. case GreaterEqualDepth:
  12941. gl.depthFunc(gl.GEQUAL);
  12942. break;
  12943. case GreaterDepth:
  12944. gl.depthFunc(gl.GREATER);
  12945. break;
  12946. case NotEqualDepth:
  12947. gl.depthFunc(gl.NOTEQUAL);
  12948. break;
  12949. default:
  12950. gl.depthFunc(gl.LEQUAL);
  12951. }
  12952. } else {
  12953. gl.depthFunc(gl.LEQUAL);
  12954. }
  12955. currentDepthFunc = depthFunc;
  12956. }
  12957. },
  12958. setLocked: function (lock) {
  12959. locked = lock;
  12960. },
  12961. setClear: function (depth) {
  12962. if (currentDepthClear !== depth) {
  12963. gl.clearDepth(depth);
  12964. currentDepthClear = depth;
  12965. }
  12966. },
  12967. reset: function () {
  12968. locked = false;
  12969. currentDepthMask = null;
  12970. currentDepthFunc = null;
  12971. currentDepthClear = null;
  12972. }
  12973. };
  12974. }
  12975. function StencilBuffer() {
  12976. let locked = false;
  12977. let currentStencilMask = null;
  12978. let currentStencilFunc = null;
  12979. let currentStencilRef = null;
  12980. let currentStencilFuncMask = null;
  12981. let currentStencilFail = null;
  12982. let currentStencilZFail = null;
  12983. let currentStencilZPass = null;
  12984. let currentStencilClear = null;
  12985. return {
  12986. setTest: function (stencilTest) {
  12987. if (!locked) {
  12988. if (stencilTest) {
  12989. enable(gl.STENCIL_TEST);
  12990. } else {
  12991. disable(gl.STENCIL_TEST);
  12992. }
  12993. }
  12994. },
  12995. setMask: function (stencilMask) {
  12996. if (currentStencilMask !== stencilMask && !locked) {
  12997. gl.stencilMask(stencilMask);
  12998. currentStencilMask = stencilMask;
  12999. }
  13000. },
  13001. setFunc: function (stencilFunc, stencilRef, stencilMask) {
  13002. if (currentStencilFunc !== stencilFunc || currentStencilRef !== stencilRef || currentStencilFuncMask !== stencilMask) {
  13003. gl.stencilFunc(stencilFunc, stencilRef, stencilMask);
  13004. currentStencilFunc = stencilFunc;
  13005. currentStencilRef = stencilRef;
  13006. currentStencilFuncMask = stencilMask;
  13007. }
  13008. },
  13009. setOp: function (stencilFail, stencilZFail, stencilZPass) {
  13010. if (currentStencilFail !== stencilFail || currentStencilZFail !== stencilZFail || currentStencilZPass !== stencilZPass) {
  13011. gl.stencilOp(stencilFail, stencilZFail, stencilZPass);
  13012. currentStencilFail = stencilFail;
  13013. currentStencilZFail = stencilZFail;
  13014. currentStencilZPass = stencilZPass;
  13015. }
  13016. },
  13017. setLocked: function (lock) {
  13018. locked = lock;
  13019. },
  13020. setClear: function (stencil) {
  13021. if (currentStencilClear !== stencil) {
  13022. gl.clearStencil(stencil);
  13023. currentStencilClear = stencil;
  13024. }
  13025. },
  13026. reset: function () {
  13027. locked = false;
  13028. currentStencilMask = null;
  13029. currentStencilFunc = null;
  13030. currentStencilRef = null;
  13031. currentStencilFuncMask = null;
  13032. currentStencilFail = null;
  13033. currentStencilZFail = null;
  13034. currentStencilZPass = null;
  13035. currentStencilClear = null;
  13036. }
  13037. };
  13038. } //
  13039. const colorBuffer = new ColorBuffer();
  13040. const depthBuffer = new DepthBuffer();
  13041. const stencilBuffer = new StencilBuffer();
  13042. let enabledCapabilities = {};
  13043. let currentBoundFramebuffers = {};
  13044. let currentDrawbuffers = new WeakMap();
  13045. let defaultDrawbuffers = [];
  13046. let currentProgram = null;
  13047. let currentBlendingEnabled = false;
  13048. let currentBlending = null;
  13049. let currentBlendEquation = null;
  13050. let currentBlendSrc = null;
  13051. let currentBlendDst = null;
  13052. let currentBlendEquationAlpha = null;
  13053. let currentBlendSrcAlpha = null;
  13054. let currentBlendDstAlpha = null;
  13055. let currentPremultipledAlpha = false;
  13056. let currentFlipSided = null;
  13057. let currentCullFace = null;
  13058. let currentLineWidth = null;
  13059. let currentPolygonOffsetFactor = null;
  13060. let currentPolygonOffsetUnits = null;
  13061. const maxTextures = gl.getParameter(gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  13062. let lineWidthAvailable = false;
  13063. let version = 0;
  13064. const glVersion = gl.getParameter(gl.VERSION);
  13065. if (glVersion.indexOf('WebGL') !== -1) {
  13066. version = parseFloat(/^WebGL (\d)/.exec(glVersion)[1]);
  13067. lineWidthAvailable = version >= 1.0;
  13068. } else if (glVersion.indexOf('OpenGL ES') !== -1) {
  13069. version = parseFloat(/^OpenGL ES (\d)/.exec(glVersion)[1]);
  13070. lineWidthAvailable = version >= 2.0;
  13071. }
  13072. let currentTextureSlot = null;
  13073. let currentBoundTextures = {};
  13074. const scissorParam = gl.getParameter(gl.SCISSOR_BOX);
  13075. const viewportParam = gl.getParameter(gl.VIEWPORT);
  13076. const currentScissor = new Vector4().fromArray(scissorParam);
  13077. const currentViewport = new Vector4().fromArray(viewportParam);
  13078. function createTexture(type, target, count) {
  13079. const data = new Uint8Array(4); // 4 is required to match default unpack alignment of 4.
  13080. const texture = gl.createTexture();
  13081. gl.bindTexture(type, texture);
  13082. gl.texParameteri(type, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  13083. gl.texParameteri(type, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  13084. for (let i = 0; i < count; i++) {
  13085. gl.texImage2D(target + i, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data);
  13086. }
  13087. return texture;
  13088. }
  13089. const emptyTextures = {};
  13090. emptyTextures[gl.TEXTURE_2D] = createTexture(gl.TEXTURE_2D, gl.TEXTURE_2D, 1);
  13091. emptyTextures[gl.TEXTURE_CUBE_MAP] = createTexture(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_CUBE_MAP_POSITIVE_X, 6); // init
  13092. colorBuffer.setClear(0, 0, 0, 1);
  13093. depthBuffer.setClear(1);
  13094. stencilBuffer.setClear(0);
  13095. enable(gl.DEPTH_TEST);
  13096. depthBuffer.setFunc(LessEqualDepth);
  13097. setFlipSided(false);
  13098. setCullFace(CullFaceBack);
  13099. enable(gl.CULL_FACE);
  13100. setBlending(NoBlending); //
  13101. function enable(id) {
  13102. if (enabledCapabilities[id] !== true) {
  13103. gl.enable(id);
  13104. enabledCapabilities[id] = true;
  13105. }
  13106. }
  13107. function disable(id) {
  13108. if (enabledCapabilities[id] !== false) {
  13109. gl.disable(id);
  13110. enabledCapabilities[id] = false;
  13111. }
  13112. }
  13113. function bindFramebuffer(target, framebuffer) {
  13114. if (currentBoundFramebuffers[target] !== framebuffer) {
  13115. gl.bindFramebuffer(target, framebuffer);
  13116. currentBoundFramebuffers[target] = framebuffer;
  13117. if (isWebGL2) {
  13118. // gl.DRAW_FRAMEBUFFER is equivalent to gl.FRAMEBUFFER
  13119. if (target === gl.DRAW_FRAMEBUFFER) {
  13120. currentBoundFramebuffers[gl.FRAMEBUFFER] = framebuffer;
  13121. }
  13122. if (target === gl.FRAMEBUFFER) {
  13123. currentBoundFramebuffers[gl.DRAW_FRAMEBUFFER] = framebuffer;
  13124. }
  13125. }
  13126. return true;
  13127. }
  13128. return false;
  13129. }
  13130. function drawBuffers(renderTarget, framebuffer) {
  13131. let drawBuffers = defaultDrawbuffers;
  13132. let needsUpdate = false;
  13133. if (renderTarget) {
  13134. drawBuffers = currentDrawbuffers.get(framebuffer);
  13135. if (drawBuffers === undefined) {
  13136. drawBuffers = [];
  13137. currentDrawbuffers.set(framebuffer, drawBuffers);
  13138. }
  13139. if (renderTarget.isWebGLMultipleRenderTargets) {
  13140. const textures = renderTarget.texture;
  13141. if (drawBuffers.length !== textures.length || drawBuffers[0] !== gl.COLOR_ATTACHMENT0) {
  13142. for (let i = 0, il = textures.length; i < il; i++) {
  13143. drawBuffers[i] = gl.COLOR_ATTACHMENT0 + i;
  13144. }
  13145. drawBuffers.length = textures.length;
  13146. needsUpdate = true;
  13147. }
  13148. } else {
  13149. if (drawBuffers[0] !== gl.COLOR_ATTACHMENT0) {
  13150. drawBuffers[0] = gl.COLOR_ATTACHMENT0;
  13151. needsUpdate = true;
  13152. }
  13153. }
  13154. } else {
  13155. if (drawBuffers[0] !== gl.BACK) {
  13156. drawBuffers[0] = gl.BACK;
  13157. needsUpdate = true;
  13158. }
  13159. }
  13160. if (needsUpdate) {
  13161. if (capabilities.isWebGL2) {
  13162. gl.drawBuffers(drawBuffers);
  13163. } else {
  13164. extensions.get('WEBGL_draw_buffers').drawBuffersWEBGL(drawBuffers);
  13165. }
  13166. }
  13167. }
  13168. function useProgram(program) {
  13169. if (currentProgram !== program) {
  13170. gl.useProgram(program);
  13171. currentProgram = program;
  13172. return true;
  13173. }
  13174. return false;
  13175. }
  13176. const equationToGL = {
  13177. [AddEquation]: gl.FUNC_ADD,
  13178. [SubtractEquation]: gl.FUNC_SUBTRACT,
  13179. [ReverseSubtractEquation]: gl.FUNC_REVERSE_SUBTRACT
  13180. };
  13181. if (isWebGL2) {
  13182. equationToGL[MinEquation] = gl.MIN;
  13183. equationToGL[MaxEquation] = gl.MAX;
  13184. } else {
  13185. const extension = extensions.get('EXT_blend_minmax');
  13186. if (extension !== null) {
  13187. equationToGL[MinEquation] = extension.MIN_EXT;
  13188. equationToGL[MaxEquation] = extension.MAX_EXT;
  13189. }
  13190. }
  13191. const factorToGL = {
  13192. [ZeroFactor]: gl.ZERO,
  13193. [OneFactor]: gl.ONE,
  13194. [SrcColorFactor]: gl.SRC_COLOR,
  13195. [SrcAlphaFactor]: gl.SRC_ALPHA,
  13196. [SrcAlphaSaturateFactor]: gl.SRC_ALPHA_SATURATE,
  13197. [DstColorFactor]: gl.DST_COLOR,
  13198. [DstAlphaFactor]: gl.DST_ALPHA,
  13199. [OneMinusSrcColorFactor]: gl.ONE_MINUS_SRC_COLOR,
  13200. [OneMinusSrcAlphaFactor]: gl.ONE_MINUS_SRC_ALPHA,
  13201. [OneMinusDstColorFactor]: gl.ONE_MINUS_DST_COLOR,
  13202. [OneMinusDstAlphaFactor]: gl.ONE_MINUS_DST_ALPHA
  13203. };
  13204. function setBlending(blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha) {
  13205. if (blending === NoBlending) {
  13206. if (currentBlendingEnabled === true) {
  13207. disable(gl.BLEND);
  13208. currentBlendingEnabled = false;
  13209. }
  13210. return;
  13211. }
  13212. if (currentBlendingEnabled === false) {
  13213. enable(gl.BLEND);
  13214. currentBlendingEnabled = true;
  13215. }
  13216. if (blending !== CustomBlending) {
  13217. if (blending !== currentBlending || premultipliedAlpha !== currentPremultipledAlpha) {
  13218. if (currentBlendEquation !== AddEquation || currentBlendEquationAlpha !== AddEquation) {
  13219. gl.blendEquation(gl.FUNC_ADD);
  13220. currentBlendEquation = AddEquation;
  13221. currentBlendEquationAlpha = AddEquation;
  13222. }
  13223. if (premultipliedAlpha) {
  13224. switch (blending) {
  13225. case NormalBlending:
  13226. gl.blendFuncSeparate(gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
  13227. break;
  13228. case AdditiveBlending:
  13229. gl.blendFunc(gl.ONE, gl.ONE);
  13230. break;
  13231. case SubtractiveBlending:
  13232. gl.blendFuncSeparate(gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE);
  13233. break;
  13234. case MultiplyBlending:
  13235. gl.blendFuncSeparate(gl.ZERO, gl.SRC_COLOR, gl.ZERO, gl.SRC_ALPHA);
  13236. break;
  13237. default:
  13238. console.error('THREE.WebGLState: Invalid blending: ', blending);
  13239. break;
  13240. }
  13241. } else {
  13242. switch (blending) {
  13243. case NormalBlending:
  13244. gl.blendFuncSeparate(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
  13245. break;
  13246. case AdditiveBlending:
  13247. gl.blendFunc(gl.SRC_ALPHA, gl.ONE);
  13248. break;
  13249. case SubtractiveBlending:
  13250. gl.blendFuncSeparate(gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE);
  13251. break;
  13252. case MultiplyBlending:
  13253. gl.blendFunc(gl.ZERO, gl.SRC_COLOR);
  13254. break;
  13255. default:
  13256. console.error('THREE.WebGLState: Invalid blending: ', blending);
  13257. break;
  13258. }
  13259. }
  13260. currentBlendSrc = null;
  13261. currentBlendDst = null;
  13262. currentBlendSrcAlpha = null;
  13263. currentBlendDstAlpha = null;
  13264. currentBlending = blending;
  13265. currentPremultipledAlpha = premultipliedAlpha;
  13266. }
  13267. return;
  13268. } // custom blending
  13269. blendEquationAlpha = blendEquationAlpha || blendEquation;
  13270. blendSrcAlpha = blendSrcAlpha || blendSrc;
  13271. blendDstAlpha = blendDstAlpha || blendDst;
  13272. if (blendEquation !== currentBlendEquation || blendEquationAlpha !== currentBlendEquationAlpha) {
  13273. gl.blendEquationSeparate(equationToGL[blendEquation], equationToGL[blendEquationAlpha]);
  13274. currentBlendEquation = blendEquation;
  13275. currentBlendEquationAlpha = blendEquationAlpha;
  13276. }
  13277. if (blendSrc !== currentBlendSrc || blendDst !== currentBlendDst || blendSrcAlpha !== currentBlendSrcAlpha || blendDstAlpha !== currentBlendDstAlpha) {
  13278. gl.blendFuncSeparate(factorToGL[blendSrc], factorToGL[blendDst], factorToGL[blendSrcAlpha], factorToGL[blendDstAlpha]);
  13279. currentBlendSrc = blendSrc;
  13280. currentBlendDst = blendDst;
  13281. currentBlendSrcAlpha = blendSrcAlpha;
  13282. currentBlendDstAlpha = blendDstAlpha;
  13283. }
  13284. currentBlending = blending;
  13285. currentPremultipledAlpha = null;
  13286. }
  13287. function setMaterial(material, frontFaceCW) {
  13288. material.side === DoubleSide ? disable(gl.CULL_FACE) : enable(gl.CULL_FACE);
  13289. let flipSided = material.side === BackSide;
  13290. if (frontFaceCW) flipSided = !flipSided;
  13291. setFlipSided(flipSided);
  13292. 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);
  13293. depthBuffer.setFunc(material.depthFunc);
  13294. depthBuffer.setTest(material.depthTest);
  13295. depthBuffer.setMask(material.depthWrite);
  13296. colorBuffer.setMask(material.colorWrite);
  13297. const stencilWrite = material.stencilWrite;
  13298. stencilBuffer.setTest(stencilWrite);
  13299. if (stencilWrite) {
  13300. stencilBuffer.setMask(material.stencilWriteMask);
  13301. stencilBuffer.setFunc(material.stencilFunc, material.stencilRef, material.stencilFuncMask);
  13302. stencilBuffer.setOp(material.stencilFail, material.stencilZFail, material.stencilZPass);
  13303. }
  13304. setPolygonOffset(material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits);
  13305. material.alphaToCoverage === true ? enable(gl.SAMPLE_ALPHA_TO_COVERAGE) : disable(gl.SAMPLE_ALPHA_TO_COVERAGE);
  13306. } //
  13307. function setFlipSided(flipSided) {
  13308. if (currentFlipSided !== flipSided) {
  13309. if (flipSided) {
  13310. gl.frontFace(gl.CW);
  13311. } else {
  13312. gl.frontFace(gl.CCW);
  13313. }
  13314. currentFlipSided = flipSided;
  13315. }
  13316. }
  13317. function setCullFace(cullFace) {
  13318. if (cullFace !== CullFaceNone) {
  13319. enable(gl.CULL_FACE);
  13320. if (cullFace !== currentCullFace) {
  13321. if (cullFace === CullFaceBack) {
  13322. gl.cullFace(gl.BACK);
  13323. } else if (cullFace === CullFaceFront) {
  13324. gl.cullFace(gl.FRONT);
  13325. } else {
  13326. gl.cullFace(gl.FRONT_AND_BACK);
  13327. }
  13328. }
  13329. } else {
  13330. disable(gl.CULL_FACE);
  13331. }
  13332. currentCullFace = cullFace;
  13333. }
  13334. function setLineWidth(width) {
  13335. if (width !== currentLineWidth) {
  13336. if (lineWidthAvailable) gl.lineWidth(width);
  13337. currentLineWidth = width;
  13338. }
  13339. }
  13340. function setPolygonOffset(polygonOffset, factor, units) {
  13341. if (polygonOffset) {
  13342. enable(gl.POLYGON_OFFSET_FILL);
  13343. if (currentPolygonOffsetFactor !== factor || currentPolygonOffsetUnits !== units) {
  13344. gl.polygonOffset(factor, units);
  13345. currentPolygonOffsetFactor = factor;
  13346. currentPolygonOffsetUnits = units;
  13347. }
  13348. } else {
  13349. disable(gl.POLYGON_OFFSET_FILL);
  13350. }
  13351. }
  13352. function setScissorTest(scissorTest) {
  13353. if (scissorTest) {
  13354. enable(gl.SCISSOR_TEST);
  13355. } else {
  13356. disable(gl.SCISSOR_TEST);
  13357. }
  13358. } // texture
  13359. function activeTexture(webglSlot) {
  13360. if (webglSlot === undefined) webglSlot = gl.TEXTURE0 + maxTextures - 1;
  13361. if (currentTextureSlot !== webglSlot) {
  13362. gl.activeTexture(webglSlot);
  13363. currentTextureSlot = webglSlot;
  13364. }
  13365. }
  13366. function bindTexture(webglType, webglTexture) {
  13367. if (currentTextureSlot === null) {
  13368. activeTexture();
  13369. }
  13370. let boundTexture = currentBoundTextures[currentTextureSlot];
  13371. if (boundTexture === undefined) {
  13372. boundTexture = {
  13373. type: undefined,
  13374. texture: undefined
  13375. };
  13376. currentBoundTextures[currentTextureSlot] = boundTexture;
  13377. }
  13378. if (boundTexture.type !== webglType || boundTexture.texture !== webglTexture) {
  13379. gl.bindTexture(webglType, webglTexture || emptyTextures[webglType]);
  13380. boundTexture.type = webglType;
  13381. boundTexture.texture = webglTexture;
  13382. }
  13383. }
  13384. function unbindTexture() {
  13385. const boundTexture = currentBoundTextures[currentTextureSlot];
  13386. if (boundTexture !== undefined && boundTexture.type !== undefined) {
  13387. gl.bindTexture(boundTexture.type, null);
  13388. boundTexture.type = undefined;
  13389. boundTexture.texture = undefined;
  13390. }
  13391. }
  13392. function compressedTexImage2D() {
  13393. try {
  13394. gl.compressedTexImage2D.apply(gl, arguments);
  13395. } catch (error) {
  13396. console.error('THREE.WebGLState:', error);
  13397. }
  13398. }
  13399. function texSubImage2D() {
  13400. try {
  13401. gl.texSubImage2D.apply(gl, arguments);
  13402. } catch (error) {
  13403. console.error('THREE.WebGLState:', error);
  13404. }
  13405. }
  13406. function texSubImage3D() {
  13407. try {
  13408. gl.texSubImage3D.apply(gl, arguments);
  13409. } catch (error) {
  13410. console.error('THREE.WebGLState:', error);
  13411. }
  13412. }
  13413. function compressedTexSubImage2D() {
  13414. try {
  13415. gl.compressedTexSubImage2D.apply(gl, arguments);
  13416. } catch (error) {
  13417. console.error('THREE.WebGLState:', error);
  13418. }
  13419. }
  13420. function texStorage2D() {
  13421. try {
  13422. gl.texStorage2D.apply(gl, arguments);
  13423. } catch (error) {
  13424. console.error('THREE.WebGLState:', error);
  13425. }
  13426. }
  13427. function texStorage3D() {
  13428. try {
  13429. gl.texStorage3D.apply(gl, arguments);
  13430. } catch (error) {
  13431. console.error('THREE.WebGLState:', error);
  13432. }
  13433. }
  13434. function texImage2D() {
  13435. try {
  13436. gl.texImage2D.apply(gl, arguments);
  13437. } catch (error) {
  13438. console.error('THREE.WebGLState:', error);
  13439. }
  13440. }
  13441. function texImage3D() {
  13442. try {
  13443. gl.texImage3D.apply(gl, arguments);
  13444. } catch (error) {
  13445. console.error('THREE.WebGLState:', error);
  13446. }
  13447. } //
  13448. function scissor(scissor) {
  13449. if (currentScissor.equals(scissor) === false) {
  13450. gl.scissor(scissor.x, scissor.y, scissor.z, scissor.w);
  13451. currentScissor.copy(scissor);
  13452. }
  13453. }
  13454. function viewport(viewport) {
  13455. if (currentViewport.equals(viewport) === false) {
  13456. gl.viewport(viewport.x, viewport.y, viewport.z, viewport.w);
  13457. currentViewport.copy(viewport);
  13458. }
  13459. } //
  13460. function reset() {
  13461. // reset state
  13462. gl.disable(gl.BLEND);
  13463. gl.disable(gl.CULL_FACE);
  13464. gl.disable(gl.DEPTH_TEST);
  13465. gl.disable(gl.POLYGON_OFFSET_FILL);
  13466. gl.disable(gl.SCISSOR_TEST);
  13467. gl.disable(gl.STENCIL_TEST);
  13468. gl.disable(gl.SAMPLE_ALPHA_TO_COVERAGE);
  13469. gl.blendEquation(gl.FUNC_ADD);
  13470. gl.blendFunc(gl.ONE, gl.ZERO);
  13471. gl.blendFuncSeparate(gl.ONE, gl.ZERO, gl.ONE, gl.ZERO);
  13472. gl.colorMask(true, true, true, true);
  13473. gl.clearColor(0, 0, 0, 0);
  13474. gl.depthMask(true);
  13475. gl.depthFunc(gl.LESS);
  13476. gl.clearDepth(1);
  13477. gl.stencilMask(0xffffffff);
  13478. gl.stencilFunc(gl.ALWAYS, 0, 0xffffffff);
  13479. gl.stencilOp(gl.KEEP, gl.KEEP, gl.KEEP);
  13480. gl.clearStencil(0);
  13481. gl.cullFace(gl.BACK);
  13482. gl.frontFace(gl.CCW);
  13483. gl.polygonOffset(0, 0);
  13484. gl.activeTexture(gl.TEXTURE0);
  13485. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  13486. if (isWebGL2 === true) {
  13487. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, null);
  13488. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, null);
  13489. }
  13490. gl.useProgram(null);
  13491. gl.lineWidth(1);
  13492. gl.scissor(0, 0, gl.canvas.width, gl.canvas.height);
  13493. gl.viewport(0, 0, gl.canvas.width, gl.canvas.height); // reset internals
  13494. enabledCapabilities = {};
  13495. currentTextureSlot = null;
  13496. currentBoundTextures = {};
  13497. currentBoundFramebuffers = {};
  13498. currentDrawbuffers = new WeakMap();
  13499. defaultDrawbuffers = [];
  13500. currentProgram = null;
  13501. currentBlendingEnabled = false;
  13502. currentBlending = null;
  13503. currentBlendEquation = null;
  13504. currentBlendSrc = null;
  13505. currentBlendDst = null;
  13506. currentBlendEquationAlpha = null;
  13507. currentBlendSrcAlpha = null;
  13508. currentBlendDstAlpha = null;
  13509. currentPremultipledAlpha = false;
  13510. currentFlipSided = null;
  13511. currentCullFace = null;
  13512. currentLineWidth = null;
  13513. currentPolygonOffsetFactor = null;
  13514. currentPolygonOffsetUnits = null;
  13515. currentScissor.set(0, 0, gl.canvas.width, gl.canvas.height);
  13516. currentViewport.set(0, 0, gl.canvas.width, gl.canvas.height);
  13517. colorBuffer.reset();
  13518. depthBuffer.reset();
  13519. stencilBuffer.reset();
  13520. }
  13521. return {
  13522. buffers: {
  13523. color: colorBuffer,
  13524. depth: depthBuffer,
  13525. stencil: stencilBuffer
  13526. },
  13527. enable: enable,
  13528. disable: disable,
  13529. bindFramebuffer: bindFramebuffer,
  13530. drawBuffers: drawBuffers,
  13531. useProgram: useProgram,
  13532. setBlending: setBlending,
  13533. setMaterial: setMaterial,
  13534. setFlipSided: setFlipSided,
  13535. setCullFace: setCullFace,
  13536. setLineWidth: setLineWidth,
  13537. setPolygonOffset: setPolygonOffset,
  13538. setScissorTest: setScissorTest,
  13539. activeTexture: activeTexture,
  13540. bindTexture: bindTexture,
  13541. unbindTexture: unbindTexture,
  13542. compressedTexImage2D: compressedTexImage2D,
  13543. texImage2D: texImage2D,
  13544. texImage3D: texImage3D,
  13545. texStorage2D: texStorage2D,
  13546. texStorage3D: texStorage3D,
  13547. texSubImage2D: texSubImage2D,
  13548. texSubImage3D: texSubImage3D,
  13549. compressedTexSubImage2D: compressedTexSubImage2D,
  13550. scissor: scissor,
  13551. viewport: viewport,
  13552. reset: reset
  13553. };
  13554. }
  13555. function WebGLTextures(_gl, extensions, state, properties, capabilities, utils, info) {
  13556. const isWebGL2 = capabilities.isWebGL2;
  13557. const maxTextures = capabilities.maxTextures;
  13558. const maxCubemapSize = capabilities.maxCubemapSize;
  13559. const maxTextureSize = capabilities.maxTextureSize;
  13560. const maxSamples = capabilities.maxSamples;
  13561. const multisampledRTTExt = extensions.has('WEBGL_multisampled_render_to_texture') ? extensions.get('WEBGL_multisampled_render_to_texture') : null;
  13562. const supportsInvalidateFramebuffer = /OculusBrowser/g.test(navigator.userAgent);
  13563. const _videoTextures = new WeakMap();
  13564. let _canvas;
  13565. const _sources = new WeakMap(); // maps WebglTexture objects to instances of Source
  13566. // cordova iOS (as of 5.0) still uses UIWebView, which provides OffscreenCanvas,
  13567. // also OffscreenCanvas.getContext("webgl"), but not OffscreenCanvas.getContext("2d")!
  13568. // Some implementations may only implement OffscreenCanvas partially (e.g. lacking 2d).
  13569. let useOffscreenCanvas = false;
  13570. try {
  13571. useOffscreenCanvas = typeof OffscreenCanvas !== 'undefined' // eslint-disable-next-line compat/compat
  13572. && new OffscreenCanvas(1, 1).getContext('2d') !== null;
  13573. } catch (err) {// Ignore any errors
  13574. }
  13575. function createCanvas(width, height) {
  13576. // Use OffscreenCanvas when available. Specially needed in web workers
  13577. return useOffscreenCanvas ? // eslint-disable-next-line compat/compat
  13578. new OffscreenCanvas(width, height) : createElementNS('canvas');
  13579. }
  13580. function resizeImage(image, needsPowerOfTwo, needsNewCanvas, maxSize) {
  13581. let scale = 1; // handle case if texture exceeds max size
  13582. if (image.width > maxSize || image.height > maxSize) {
  13583. scale = maxSize / Math.max(image.width, image.height);
  13584. } // only perform resize if necessary
  13585. if (scale < 1 || needsPowerOfTwo === true) {
  13586. // only perform resize for certain image types
  13587. if (typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement || typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement || typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap) {
  13588. const floor = needsPowerOfTwo ? floorPowerOfTwo : Math.floor;
  13589. const width = floor(scale * image.width);
  13590. const height = floor(scale * image.height);
  13591. if (_canvas === undefined) _canvas = createCanvas(width, height); // cube textures can't reuse the same canvas
  13592. const canvas = needsNewCanvas ? createCanvas(width, height) : _canvas;
  13593. canvas.width = width;
  13594. canvas.height = height;
  13595. const context = canvas.getContext('2d');
  13596. context.drawImage(image, 0, 0, width, height);
  13597. console.warn('THREE.WebGLRenderer: Texture has been resized from (' + image.width + 'x' + image.height + ') to (' + width + 'x' + height + ').');
  13598. return canvas;
  13599. } else {
  13600. if ('data' in image) {
  13601. console.warn('THREE.WebGLRenderer: Image in DataTexture is too big (' + image.width + 'x' + image.height + ').');
  13602. }
  13603. return image;
  13604. }
  13605. }
  13606. return image;
  13607. }
  13608. function isPowerOfTwo$1(image) {
  13609. return isPowerOfTwo(image.width) && isPowerOfTwo(image.height);
  13610. }
  13611. function textureNeedsPowerOfTwo(texture) {
  13612. if (isWebGL2) return false;
  13613. return texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping || texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter;
  13614. }
  13615. function textureNeedsGenerateMipmaps(texture, supportsMips) {
  13616. return texture.generateMipmaps && supportsMips && texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter;
  13617. }
  13618. function generateMipmap(target) {
  13619. _gl.generateMipmap(target);
  13620. }
  13621. function getInternalFormat(internalFormatName, glFormat, glType, encoding, isVideoTexture = false) {
  13622. if (isWebGL2 === false) return glFormat;
  13623. if (internalFormatName !== null) {
  13624. if (_gl[internalFormatName] !== undefined) return _gl[internalFormatName];
  13625. console.warn('THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\'');
  13626. }
  13627. let internalFormat = glFormat;
  13628. if (glFormat === _gl.RED) {
  13629. if (glType === _gl.FLOAT) internalFormat = _gl.R32F;
  13630. if (glType === _gl.HALF_FLOAT) internalFormat = _gl.R16F;
  13631. if (glType === _gl.UNSIGNED_BYTE) internalFormat = _gl.R8;
  13632. }
  13633. if (glFormat === _gl.RG) {
  13634. if (glType === _gl.FLOAT) internalFormat = _gl.RG32F;
  13635. if (glType === _gl.HALF_FLOAT) internalFormat = _gl.RG16F;
  13636. if (glType === _gl.UNSIGNED_BYTE) internalFormat = _gl.RG8;
  13637. }
  13638. if (glFormat === _gl.RGBA) {
  13639. if (glType === _gl.FLOAT) internalFormat = _gl.RGBA32F;
  13640. if (glType === _gl.HALF_FLOAT) internalFormat = _gl.RGBA16F;
  13641. if (glType === _gl.UNSIGNED_BYTE) internalFormat = encoding === sRGBEncoding && isVideoTexture === false ? _gl.SRGB8_ALPHA8 : _gl.RGBA8;
  13642. if (glType === _gl.UNSIGNED_SHORT_4_4_4_4) internalFormat = _gl.RGBA4;
  13643. if (glType === _gl.UNSIGNED_SHORT_5_5_5_1) internalFormat = _gl.RGB5_A1;
  13644. }
  13645. if (internalFormat === _gl.R16F || internalFormat === _gl.R32F || internalFormat === _gl.RG16F || internalFormat === _gl.RG32F || internalFormat === _gl.RGBA16F || internalFormat === _gl.RGBA32F) {
  13646. extensions.get('EXT_color_buffer_float');
  13647. }
  13648. return internalFormat;
  13649. }
  13650. function getMipLevels(texture, image, supportsMips) {
  13651. if (textureNeedsGenerateMipmaps(texture, supportsMips) === true || texture.isFramebufferTexture && texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter) {
  13652. return Math.log2(Math.max(image.width, image.height)) + 1;
  13653. } else if (texture.mipmaps !== undefined && texture.mipmaps.length > 0) {
  13654. // user-defined mipmaps
  13655. return texture.mipmaps.length;
  13656. } else if (texture.isCompressedTexture && Array.isArray(texture.image)) {
  13657. return image.mipmaps.length;
  13658. } else {
  13659. // texture without mipmaps (only base level)
  13660. return 1;
  13661. }
  13662. } // Fallback filters for non-power-of-2 textures
  13663. function filterFallback(f) {
  13664. if (f === NearestFilter || f === NearestMipmapNearestFilter || f === NearestMipmapLinearFilter) {
  13665. return _gl.NEAREST;
  13666. }
  13667. return _gl.LINEAR;
  13668. } //
  13669. function onTextureDispose(event) {
  13670. const texture = event.target;
  13671. texture.removeEventListener('dispose', onTextureDispose);
  13672. deallocateTexture(texture);
  13673. if (texture.isVideoTexture) {
  13674. _videoTextures.delete(texture);
  13675. }
  13676. }
  13677. function onRenderTargetDispose(event) {
  13678. const renderTarget = event.target;
  13679. renderTarget.removeEventListener('dispose', onRenderTargetDispose);
  13680. deallocateRenderTarget(renderTarget);
  13681. } //
  13682. function deallocateTexture(texture) {
  13683. const textureProperties = properties.get(texture);
  13684. if (textureProperties.__webglInit === undefined) return; // check if it's necessary to remove the WebGLTexture object
  13685. const source = texture.source;
  13686. const webglTextures = _sources.get(source);
  13687. if (webglTextures) {
  13688. const webglTexture = webglTextures[textureProperties.__cacheKey];
  13689. webglTexture.usedTimes--; // the WebGLTexture object is not used anymore, remove it
  13690. if (webglTexture.usedTimes === 0) {
  13691. deleteTexture(texture);
  13692. } // remove the weak map entry if no WebGLTexture uses the source anymore
  13693. if (Object.keys(webglTextures).length === 0) {
  13694. _sources.delete(source);
  13695. }
  13696. }
  13697. properties.remove(texture);
  13698. }
  13699. function deleteTexture(texture) {
  13700. const textureProperties = properties.get(texture);
  13701. _gl.deleteTexture(textureProperties.__webglTexture);
  13702. const source = texture.source;
  13703. const webglTextures = _sources.get(source);
  13704. delete webglTextures[textureProperties.__cacheKey];
  13705. info.memory.textures--;
  13706. }
  13707. function deallocateRenderTarget(renderTarget) {
  13708. const texture = renderTarget.texture;
  13709. const renderTargetProperties = properties.get(renderTarget);
  13710. const textureProperties = properties.get(texture);
  13711. if (textureProperties.__webglTexture !== undefined) {
  13712. _gl.deleteTexture(textureProperties.__webglTexture);
  13713. info.memory.textures--;
  13714. }
  13715. if (renderTarget.depthTexture) {
  13716. renderTarget.depthTexture.dispose();
  13717. }
  13718. if (renderTarget.isWebGLCubeRenderTarget) {
  13719. for (let i = 0; i < 6; i++) {
  13720. _gl.deleteFramebuffer(renderTargetProperties.__webglFramebuffer[i]);
  13721. if (renderTargetProperties.__webglDepthbuffer) _gl.deleteRenderbuffer(renderTargetProperties.__webglDepthbuffer[i]);
  13722. }
  13723. } else {
  13724. _gl.deleteFramebuffer(renderTargetProperties.__webglFramebuffer);
  13725. if (renderTargetProperties.__webglDepthbuffer) _gl.deleteRenderbuffer(renderTargetProperties.__webglDepthbuffer);
  13726. if (renderTargetProperties.__webglMultisampledFramebuffer) _gl.deleteFramebuffer(renderTargetProperties.__webglMultisampledFramebuffer);
  13727. if (renderTargetProperties.__webglColorRenderbuffer) _gl.deleteRenderbuffer(renderTargetProperties.__webglColorRenderbuffer);
  13728. if (renderTargetProperties.__webglDepthRenderbuffer) _gl.deleteRenderbuffer(renderTargetProperties.__webglDepthRenderbuffer);
  13729. }
  13730. if (renderTarget.isWebGLMultipleRenderTargets) {
  13731. for (let i = 0, il = texture.length; i < il; i++) {
  13732. const attachmentProperties = properties.get(texture[i]);
  13733. if (attachmentProperties.__webglTexture) {
  13734. _gl.deleteTexture(attachmentProperties.__webglTexture);
  13735. info.memory.textures--;
  13736. }
  13737. properties.remove(texture[i]);
  13738. }
  13739. }
  13740. properties.remove(texture);
  13741. properties.remove(renderTarget);
  13742. } //
  13743. let textureUnits = 0;
  13744. function resetTextureUnits() {
  13745. textureUnits = 0;
  13746. }
  13747. function allocateTextureUnit() {
  13748. const textureUnit = textureUnits;
  13749. if (textureUnit >= maxTextures) {
  13750. console.warn('THREE.WebGLTextures: Trying to use ' + textureUnit + ' texture units while this GPU supports only ' + maxTextures);
  13751. }
  13752. textureUnits += 1;
  13753. return textureUnit;
  13754. }
  13755. function getTextureCacheKey(texture) {
  13756. const array = [];
  13757. array.push(texture.wrapS);
  13758. array.push(texture.wrapT);
  13759. array.push(texture.magFilter);
  13760. array.push(texture.minFilter);
  13761. array.push(texture.anisotropy);
  13762. array.push(texture.internalFormat);
  13763. array.push(texture.format);
  13764. array.push(texture.type);
  13765. array.push(texture.generateMipmaps);
  13766. array.push(texture.premultiplyAlpha);
  13767. array.push(texture.flipY);
  13768. array.push(texture.unpackAlignment);
  13769. array.push(texture.encoding);
  13770. return array.join();
  13771. } //
  13772. function setTexture2D(texture, slot) {
  13773. const textureProperties = properties.get(texture);
  13774. if (texture.isVideoTexture) updateVideoTexture(texture);
  13775. if (texture.isRenderTargetTexture === false && texture.version > 0 && textureProperties.__version !== texture.version) {
  13776. const image = texture.image;
  13777. if (image === null) {
  13778. console.warn('THREE.WebGLRenderer: Texture marked for update but no image data found.');
  13779. } else if (image.complete === false) {
  13780. console.warn('THREE.WebGLRenderer: Texture marked for update but image is incomplete');
  13781. } else {
  13782. uploadTexture(textureProperties, texture, slot);
  13783. return;
  13784. }
  13785. }
  13786. state.activeTexture(_gl.TEXTURE0 + slot);
  13787. state.bindTexture(_gl.TEXTURE_2D, textureProperties.__webglTexture);
  13788. }
  13789. function setTexture2DArray(texture, slot) {
  13790. const textureProperties = properties.get(texture);
  13791. if (texture.version > 0 && textureProperties.__version !== texture.version) {
  13792. uploadTexture(textureProperties, texture, slot);
  13793. return;
  13794. }
  13795. state.activeTexture(_gl.TEXTURE0 + slot);
  13796. state.bindTexture(_gl.TEXTURE_2D_ARRAY, textureProperties.__webglTexture);
  13797. }
  13798. function setTexture3D(texture, slot) {
  13799. const textureProperties = properties.get(texture);
  13800. if (texture.version > 0 && textureProperties.__version !== texture.version) {
  13801. uploadTexture(textureProperties, texture, slot);
  13802. return;
  13803. }
  13804. state.activeTexture(_gl.TEXTURE0 + slot);
  13805. state.bindTexture(_gl.TEXTURE_3D, textureProperties.__webglTexture);
  13806. }
  13807. function setTextureCube(texture, slot) {
  13808. const textureProperties = properties.get(texture);
  13809. if (texture.version > 0 && textureProperties.__version !== texture.version) {
  13810. uploadCubeTexture(textureProperties, texture, slot);
  13811. return;
  13812. }
  13813. state.activeTexture(_gl.TEXTURE0 + slot);
  13814. state.bindTexture(_gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture);
  13815. }
  13816. const wrappingToGL = {
  13817. [RepeatWrapping]: _gl.REPEAT,
  13818. [ClampToEdgeWrapping]: _gl.CLAMP_TO_EDGE,
  13819. [MirroredRepeatWrapping]: _gl.MIRRORED_REPEAT
  13820. };
  13821. const filterToGL = {
  13822. [NearestFilter]: _gl.NEAREST,
  13823. [NearestMipmapNearestFilter]: _gl.NEAREST_MIPMAP_NEAREST,
  13824. [NearestMipmapLinearFilter]: _gl.NEAREST_MIPMAP_LINEAR,
  13825. [LinearFilter]: _gl.LINEAR,
  13826. [LinearMipmapNearestFilter]: _gl.LINEAR_MIPMAP_NEAREST,
  13827. [LinearMipmapLinearFilter]: _gl.LINEAR_MIPMAP_LINEAR
  13828. };
  13829. function setTextureParameters(textureType, texture, supportsMips) {
  13830. if (supportsMips) {
  13831. _gl.texParameteri(textureType, _gl.TEXTURE_WRAP_S, wrappingToGL[texture.wrapS]);
  13832. _gl.texParameteri(textureType, _gl.TEXTURE_WRAP_T, wrappingToGL[texture.wrapT]);
  13833. if (textureType === _gl.TEXTURE_3D || textureType === _gl.TEXTURE_2D_ARRAY) {
  13834. _gl.texParameteri(textureType, _gl.TEXTURE_WRAP_R, wrappingToGL[texture.wrapR]);
  13835. }
  13836. _gl.texParameteri(textureType, _gl.TEXTURE_MAG_FILTER, filterToGL[texture.magFilter]);
  13837. _gl.texParameteri(textureType, _gl.TEXTURE_MIN_FILTER, filterToGL[texture.minFilter]);
  13838. } else {
  13839. _gl.texParameteri(textureType, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE);
  13840. _gl.texParameteri(textureType, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE);
  13841. if (textureType === _gl.TEXTURE_3D || textureType === _gl.TEXTURE_2D_ARRAY) {
  13842. _gl.texParameteri(textureType, _gl.TEXTURE_WRAP_R, _gl.CLAMP_TO_EDGE);
  13843. }
  13844. if (texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping) {
  13845. console.warn('THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping.');
  13846. }
  13847. _gl.texParameteri(textureType, _gl.TEXTURE_MAG_FILTER, filterFallback(texture.magFilter));
  13848. _gl.texParameteri(textureType, _gl.TEXTURE_MIN_FILTER, filterFallback(texture.minFilter));
  13849. if (texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter) {
  13850. console.warn('THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.');
  13851. }
  13852. }
  13853. if (extensions.has('EXT_texture_filter_anisotropic') === true) {
  13854. const extension = extensions.get('EXT_texture_filter_anisotropic');
  13855. if (texture.type === FloatType && extensions.has('OES_texture_float_linear') === false) return; // verify extension for WebGL 1 and WebGL 2
  13856. if (isWebGL2 === false && texture.type === HalfFloatType && extensions.has('OES_texture_half_float_linear') === false) return; // verify extension for WebGL 1 only
  13857. if (texture.anisotropy > 1 || properties.get(texture).__currentAnisotropy) {
  13858. _gl.texParameterf(textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(texture.anisotropy, capabilities.getMaxAnisotropy()));
  13859. properties.get(texture).__currentAnisotropy = texture.anisotropy;
  13860. }
  13861. }
  13862. }
  13863. function initTexture(textureProperties, texture) {
  13864. let forceUpload = false;
  13865. if (textureProperties.__webglInit === undefined) {
  13866. textureProperties.__webglInit = true;
  13867. texture.addEventListener('dispose', onTextureDispose);
  13868. } // create Source <-> WebGLTextures mapping if necessary
  13869. const source = texture.source;
  13870. let webglTextures = _sources.get(source);
  13871. if (webglTextures === undefined) {
  13872. webglTextures = {};
  13873. _sources.set(source, webglTextures);
  13874. } // check if there is already a WebGLTexture object for the given texture parameters
  13875. const textureCacheKey = getTextureCacheKey(texture);
  13876. if (textureCacheKey !== textureProperties.__cacheKey) {
  13877. // if not, create a new instance of WebGLTexture
  13878. if (webglTextures[textureCacheKey] === undefined) {
  13879. // create new entry
  13880. webglTextures[textureCacheKey] = {
  13881. texture: _gl.createTexture(),
  13882. usedTimes: 0
  13883. };
  13884. info.memory.textures++; // when a new instance of WebGLTexture was created, a texture upload is required
  13885. // even if the image contents are identical
  13886. forceUpload = true;
  13887. }
  13888. webglTextures[textureCacheKey].usedTimes++; // every time the texture cache key changes, it's necessary to check if an instance of
  13889. // WebGLTexture can be deleted in order to avoid a memory leak.
  13890. const webglTexture = webglTextures[textureProperties.__cacheKey];
  13891. if (webglTexture !== undefined) {
  13892. webglTextures[textureProperties.__cacheKey].usedTimes--;
  13893. if (webglTexture.usedTimes === 0) {
  13894. deleteTexture(texture);
  13895. }
  13896. } // store references to cache key and WebGLTexture object
  13897. textureProperties.__cacheKey = textureCacheKey;
  13898. textureProperties.__webglTexture = webglTextures[textureCacheKey].texture;
  13899. }
  13900. return forceUpload;
  13901. }
  13902. function uploadTexture(textureProperties, texture, slot) {
  13903. let textureType = _gl.TEXTURE_2D;
  13904. if (texture.isDataArrayTexture) textureType = _gl.TEXTURE_2D_ARRAY;
  13905. if (texture.isData3DTexture) textureType = _gl.TEXTURE_3D;
  13906. const forceUpload = initTexture(textureProperties, texture);
  13907. const source = texture.source;
  13908. state.activeTexture(_gl.TEXTURE0 + slot);
  13909. state.bindTexture(textureType, textureProperties.__webglTexture);
  13910. if (source.version !== source.__currentVersion || forceUpload === true) {
  13911. _gl.pixelStorei(_gl.UNPACK_FLIP_Y_WEBGL, texture.flipY);
  13912. _gl.pixelStorei(_gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha);
  13913. _gl.pixelStorei(_gl.UNPACK_ALIGNMENT, texture.unpackAlignment);
  13914. _gl.pixelStorei(_gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, _gl.NONE);
  13915. const needsPowerOfTwo = textureNeedsPowerOfTwo(texture) && isPowerOfTwo$1(texture.image) === false;
  13916. let image = resizeImage(texture.image, needsPowerOfTwo, false, maxTextureSize);
  13917. image = verifyColorSpace(texture, image);
  13918. const supportsMips = isPowerOfTwo$1(image) || isWebGL2,
  13919. glFormat = utils.convert(texture.format, texture.encoding);
  13920. let glType = utils.convert(texture.type),
  13921. glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType, texture.encoding, texture.isVideoTexture);
  13922. setTextureParameters(textureType, texture, supportsMips);
  13923. let mipmap;
  13924. const mipmaps = texture.mipmaps;
  13925. const useTexStorage = isWebGL2 && texture.isVideoTexture !== true;
  13926. const allocateMemory = source.__currentVersion === undefined || forceUpload === true;
  13927. const levels = getMipLevels(texture, image, supportsMips);
  13928. if (texture.isDepthTexture) {
  13929. // populate depth texture with dummy data
  13930. glInternalFormat = _gl.DEPTH_COMPONENT;
  13931. if (isWebGL2) {
  13932. if (texture.type === FloatType) {
  13933. glInternalFormat = _gl.DEPTH_COMPONENT32F;
  13934. } else if (texture.type === UnsignedIntType) {
  13935. glInternalFormat = _gl.DEPTH_COMPONENT24;
  13936. } else if (texture.type === UnsignedInt248Type) {
  13937. glInternalFormat = _gl.DEPTH24_STENCIL8;
  13938. } else {
  13939. glInternalFormat = _gl.DEPTH_COMPONENT16; // WebGL2 requires sized internalformat for glTexImage2D
  13940. }
  13941. } else {
  13942. if (texture.type === FloatType) {
  13943. console.error('WebGLRenderer: Floating point depth texture requires WebGL2.');
  13944. }
  13945. } // validation checks for WebGL 1
  13946. if (texture.format === DepthFormat && glInternalFormat === _gl.DEPTH_COMPONENT) {
  13947. // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  13948. // DEPTH_COMPONENT and type is not UNSIGNED_SHORT or UNSIGNED_INT
  13949. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  13950. if (texture.type !== UnsignedShortType && texture.type !== UnsignedIntType) {
  13951. console.warn('THREE.WebGLRenderer: Use UnsignedShortType or UnsignedIntType for DepthFormat DepthTexture.');
  13952. texture.type = UnsignedIntType;
  13953. glType = utils.convert(texture.type);
  13954. }
  13955. }
  13956. if (texture.format === DepthStencilFormat && glInternalFormat === _gl.DEPTH_COMPONENT) {
  13957. // Depth stencil textures need the DEPTH_STENCIL internal format
  13958. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  13959. glInternalFormat = _gl.DEPTH_STENCIL; // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  13960. // DEPTH_STENCIL and type is not UNSIGNED_INT_24_8_WEBGL.
  13961. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  13962. if (texture.type !== UnsignedInt248Type) {
  13963. console.warn('THREE.WebGLRenderer: Use UnsignedInt248Type for DepthStencilFormat DepthTexture.');
  13964. texture.type = UnsignedInt248Type;
  13965. glType = utils.convert(texture.type);
  13966. }
  13967. } //
  13968. if (allocateMemory) {
  13969. if (useTexStorage) {
  13970. state.texStorage2D(_gl.TEXTURE_2D, 1, glInternalFormat, image.width, image.height);
  13971. } else {
  13972. state.texImage2D(_gl.TEXTURE_2D, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, null);
  13973. }
  13974. }
  13975. } else if (texture.isDataTexture) {
  13976. // use manually created mipmaps if available
  13977. // if there are no manual mipmaps
  13978. // set 0 level mipmap and then use GL to generate other mipmap levels
  13979. if (mipmaps.length > 0 && supportsMips) {
  13980. if (useTexStorage && allocateMemory) {
  13981. state.texStorage2D(_gl.TEXTURE_2D, levels, glInternalFormat, mipmaps[0].width, mipmaps[0].height);
  13982. }
  13983. for (let i = 0, il = mipmaps.length; i < il; i++) {
  13984. mipmap = mipmaps[i];
  13985. if (useTexStorage) {
  13986. state.texSubImage2D(_gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data);
  13987. } else {
  13988. state.texImage2D(_gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data);
  13989. }
  13990. }
  13991. texture.generateMipmaps = false;
  13992. } else {
  13993. if (useTexStorage) {
  13994. if (allocateMemory) {
  13995. state.texStorage2D(_gl.TEXTURE_2D, levels, glInternalFormat, image.width, image.height);
  13996. }
  13997. state.texSubImage2D(_gl.TEXTURE_2D, 0, 0, 0, image.width, image.height, glFormat, glType, image.data);
  13998. } else {
  13999. state.texImage2D(_gl.TEXTURE_2D, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, image.data);
  14000. }
  14001. }
  14002. } else if (texture.isCompressedTexture) {
  14003. if (useTexStorage && allocateMemory) {
  14004. state.texStorage2D(_gl.TEXTURE_2D, levels, glInternalFormat, mipmaps[0].width, mipmaps[0].height);
  14005. }
  14006. for (let i = 0, il = mipmaps.length; i < il; i++) {
  14007. mipmap = mipmaps[i];
  14008. if (texture.format !== RGBAFormat) {
  14009. if (glFormat !== null) {
  14010. if (useTexStorage) {
  14011. state.compressedTexSubImage2D(_gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data);
  14012. } else {
  14013. state.compressedTexImage2D(_gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data);
  14014. }
  14015. } else {
  14016. console.warn('THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()');
  14017. }
  14018. } else {
  14019. if (useTexStorage) {
  14020. state.texSubImage2D(_gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data);
  14021. } else {
  14022. state.texImage2D(_gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data);
  14023. }
  14024. }
  14025. }
  14026. } else if (texture.isDataArrayTexture) {
  14027. if (useTexStorage) {
  14028. if (allocateMemory) {
  14029. state.texStorage3D(_gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, image.width, image.height, image.depth);
  14030. }
  14031. state.texSubImage3D(_gl.TEXTURE_2D_ARRAY, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data);
  14032. } else {
  14033. state.texImage3D(_gl.TEXTURE_2D_ARRAY, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data);
  14034. }
  14035. } else if (texture.isData3DTexture) {
  14036. if (useTexStorage) {
  14037. if (allocateMemory) {
  14038. state.texStorage3D(_gl.TEXTURE_3D, levels, glInternalFormat, image.width, image.height, image.depth);
  14039. }
  14040. state.texSubImage3D(_gl.TEXTURE_3D, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data);
  14041. } else {
  14042. state.texImage3D(_gl.TEXTURE_3D, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data);
  14043. }
  14044. } else if (texture.isFramebufferTexture) {
  14045. if (allocateMemory) {
  14046. if (useTexStorage) {
  14047. state.texStorage2D(_gl.TEXTURE_2D, levels, glInternalFormat, image.width, image.height);
  14048. } else {
  14049. let width = image.width,
  14050. height = image.height;
  14051. for (let i = 0; i < levels; i++) {
  14052. state.texImage2D(_gl.TEXTURE_2D, i, glInternalFormat, width, height, 0, glFormat, glType, null);
  14053. width >>= 1;
  14054. height >>= 1;
  14055. }
  14056. }
  14057. }
  14058. } else {
  14059. // regular Texture (image, video, canvas)
  14060. // use manually created mipmaps if available
  14061. // if there are no manual mipmaps
  14062. // set 0 level mipmap and then use GL to generate other mipmap levels
  14063. if (mipmaps.length > 0 && supportsMips) {
  14064. if (useTexStorage && allocateMemory) {
  14065. state.texStorage2D(_gl.TEXTURE_2D, levels, glInternalFormat, mipmaps[0].width, mipmaps[0].height);
  14066. }
  14067. for (let i = 0, il = mipmaps.length; i < il; i++) {
  14068. mipmap = mipmaps[i];
  14069. if (useTexStorage) {
  14070. state.texSubImage2D(_gl.TEXTURE_2D, i, 0, 0, glFormat, glType, mipmap);
  14071. } else {
  14072. state.texImage2D(_gl.TEXTURE_2D, i, glInternalFormat, glFormat, glType, mipmap);
  14073. }
  14074. }
  14075. texture.generateMipmaps = false;
  14076. } else {
  14077. if (useTexStorage) {
  14078. if (allocateMemory) {
  14079. state.texStorage2D(_gl.TEXTURE_2D, levels, glInternalFormat, image.width, image.height);
  14080. }
  14081. state.texSubImage2D(_gl.TEXTURE_2D, 0, 0, 0, glFormat, glType, image);
  14082. } else {
  14083. state.texImage2D(_gl.TEXTURE_2D, 0, glInternalFormat, glFormat, glType, image);
  14084. }
  14085. }
  14086. }
  14087. if (textureNeedsGenerateMipmaps(texture, supportsMips)) {
  14088. generateMipmap(textureType);
  14089. }
  14090. source.__currentVersion = source.version;
  14091. if (texture.onUpdate) texture.onUpdate(texture);
  14092. }
  14093. textureProperties.__version = texture.version;
  14094. }
  14095. function uploadCubeTexture(textureProperties, texture, slot) {
  14096. if (texture.image.length !== 6) return;
  14097. const forceUpload = initTexture(textureProperties, texture);
  14098. const source = texture.source;
  14099. state.activeTexture(_gl.TEXTURE0 + slot);
  14100. state.bindTexture(_gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture);
  14101. if (source.version !== source.__currentVersion || forceUpload === true) {
  14102. _gl.pixelStorei(_gl.UNPACK_FLIP_Y_WEBGL, texture.flipY);
  14103. _gl.pixelStorei(_gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha);
  14104. _gl.pixelStorei(_gl.UNPACK_ALIGNMENT, texture.unpackAlignment);
  14105. _gl.pixelStorei(_gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, _gl.NONE);
  14106. const isCompressed = texture.isCompressedTexture || texture.image[0].isCompressedTexture;
  14107. const isDataTexture = texture.image[0] && texture.image[0].isDataTexture;
  14108. const cubeImage = [];
  14109. for (let i = 0; i < 6; i++) {
  14110. if (!isCompressed && !isDataTexture) {
  14111. cubeImage[i] = resizeImage(texture.image[i], false, true, maxCubemapSize);
  14112. } else {
  14113. cubeImage[i] = isDataTexture ? texture.image[i].image : texture.image[i];
  14114. }
  14115. cubeImage[i] = verifyColorSpace(texture, cubeImage[i]);
  14116. }
  14117. const image = cubeImage[0],
  14118. supportsMips = isPowerOfTwo$1(image) || isWebGL2,
  14119. glFormat = utils.convert(texture.format, texture.encoding),
  14120. glType = utils.convert(texture.type),
  14121. glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType, texture.encoding);
  14122. const useTexStorage = isWebGL2 && texture.isVideoTexture !== true;
  14123. const allocateMemory = source.__currentVersion === undefined || forceUpload === true;
  14124. let levels = getMipLevels(texture, image, supportsMips);
  14125. setTextureParameters(_gl.TEXTURE_CUBE_MAP, texture, supportsMips);
  14126. let mipmaps;
  14127. if (isCompressed) {
  14128. if (useTexStorage && allocateMemory) {
  14129. state.texStorage2D(_gl.TEXTURE_CUBE_MAP, levels, glInternalFormat, image.width, image.height);
  14130. }
  14131. for (let i = 0; i < 6; i++) {
  14132. mipmaps = cubeImage[i].mipmaps;
  14133. for (let j = 0; j < mipmaps.length; j++) {
  14134. const mipmap = mipmaps[j];
  14135. if (texture.format !== RGBAFormat) {
  14136. if (glFormat !== null) {
  14137. if (useTexStorage) {
  14138. state.compressedTexSubImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data);
  14139. } else {
  14140. state.compressedTexImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data);
  14141. }
  14142. } else {
  14143. console.warn('THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()');
  14144. }
  14145. } else {
  14146. if (useTexStorage) {
  14147. state.texSubImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data);
  14148. } else {
  14149. state.texImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data);
  14150. }
  14151. }
  14152. }
  14153. }
  14154. } else {
  14155. mipmaps = texture.mipmaps;
  14156. if (useTexStorage && allocateMemory) {
  14157. // TODO: Uniformly handle mipmap definitions
  14158. // Normal textures and compressed cube textures define base level + mips with their mipmap array
  14159. // Uncompressed cube textures use their mipmap array only for mips (no base level)
  14160. if (mipmaps.length > 0) levels++;
  14161. state.texStorage2D(_gl.TEXTURE_CUBE_MAP, levels, glInternalFormat, cubeImage[0].width, cubeImage[0].height);
  14162. }
  14163. for (let i = 0; i < 6; i++) {
  14164. if (isDataTexture) {
  14165. if (useTexStorage) {
  14166. state.texSubImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, cubeImage[i].width, cubeImage[i].height, glFormat, glType, cubeImage[i].data);
  14167. } else {
  14168. state.texImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glInternalFormat, cubeImage[i].width, cubeImage[i].height, 0, glFormat, glType, cubeImage[i].data);
  14169. }
  14170. for (let j = 0; j < mipmaps.length; j++) {
  14171. const mipmap = mipmaps[j];
  14172. const mipmapImage = mipmap.image[i].image;
  14173. if (useTexStorage) {
  14174. state.texSubImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, 0, 0, mipmapImage.width, mipmapImage.height, glFormat, glType, mipmapImage.data);
  14175. } else {
  14176. state.texImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, glInternalFormat, mipmapImage.width, mipmapImage.height, 0, glFormat, glType, mipmapImage.data);
  14177. }
  14178. }
  14179. } else {
  14180. if (useTexStorage) {
  14181. state.texSubImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, glFormat, glType, cubeImage[i]);
  14182. } else {
  14183. state.texImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glInternalFormat, glFormat, glType, cubeImage[i]);
  14184. }
  14185. for (let j = 0; j < mipmaps.length; j++) {
  14186. const mipmap = mipmaps[j];
  14187. if (useTexStorage) {
  14188. state.texSubImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, 0, 0, glFormat, glType, mipmap.image[i]);
  14189. } else {
  14190. state.texImage2D(_gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, glInternalFormat, glFormat, glType, mipmap.image[i]);
  14191. }
  14192. }
  14193. }
  14194. }
  14195. }
  14196. if (textureNeedsGenerateMipmaps(texture, supportsMips)) {
  14197. // We assume images for cube map have the same size.
  14198. generateMipmap(_gl.TEXTURE_CUBE_MAP);
  14199. }
  14200. source.__currentVersion = source.version;
  14201. if (texture.onUpdate) texture.onUpdate(texture);
  14202. }
  14203. textureProperties.__version = texture.version;
  14204. } // Render targets
  14205. // Setup storage for target texture and bind it to correct framebuffer
  14206. function setupFrameBufferTexture(framebuffer, renderTarget, texture, attachment, textureTarget) {
  14207. const glFormat = utils.convert(texture.format, texture.encoding);
  14208. const glType = utils.convert(texture.type);
  14209. const glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType, texture.encoding);
  14210. const renderTargetProperties = properties.get(renderTarget);
  14211. if (!renderTargetProperties.__hasExternalTextures) {
  14212. if (textureTarget === _gl.TEXTURE_3D || textureTarget === _gl.TEXTURE_2D_ARRAY) {
  14213. state.texImage3D(textureTarget, 0, glInternalFormat, renderTarget.width, renderTarget.height, renderTarget.depth, 0, glFormat, glType, null);
  14214. } else {
  14215. state.texImage2D(textureTarget, 0, glInternalFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null);
  14216. }
  14217. }
  14218. state.bindFramebuffer(_gl.FRAMEBUFFER, framebuffer);
  14219. if (useMultisampledRTT(renderTarget)) {
  14220. multisampledRTTExt.framebufferTexture2DMultisampleEXT(_gl.FRAMEBUFFER, attachment, textureTarget, properties.get(texture).__webglTexture, 0, getRenderTargetSamples(renderTarget));
  14221. } else {
  14222. _gl.framebufferTexture2D(_gl.FRAMEBUFFER, attachment, textureTarget, properties.get(texture).__webglTexture, 0);
  14223. }
  14224. state.bindFramebuffer(_gl.FRAMEBUFFER, null);
  14225. } // Setup storage for internal depth/stencil buffers and bind to correct framebuffer
  14226. function setupRenderBufferStorage(renderbuffer, renderTarget, isMultisample) {
  14227. _gl.bindRenderbuffer(_gl.RENDERBUFFER, renderbuffer);
  14228. if (renderTarget.depthBuffer && !renderTarget.stencilBuffer) {
  14229. let glInternalFormat = _gl.DEPTH_COMPONENT16;
  14230. if (isMultisample || useMultisampledRTT(renderTarget)) {
  14231. const depthTexture = renderTarget.depthTexture;
  14232. if (depthTexture && depthTexture.isDepthTexture) {
  14233. if (depthTexture.type === FloatType) {
  14234. glInternalFormat = _gl.DEPTH_COMPONENT32F;
  14235. } else if (depthTexture.type === UnsignedIntType) {
  14236. glInternalFormat = _gl.DEPTH_COMPONENT24;
  14237. }
  14238. }
  14239. const samples = getRenderTargetSamples(renderTarget);
  14240. if (useMultisampledRTT(renderTarget)) {
  14241. multisampledRTTExt.renderbufferStorageMultisampleEXT(_gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height);
  14242. } else {
  14243. _gl.renderbufferStorageMultisample(_gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height);
  14244. }
  14245. } else {
  14246. _gl.renderbufferStorage(_gl.RENDERBUFFER, glInternalFormat, renderTarget.width, renderTarget.height);
  14247. }
  14248. _gl.framebufferRenderbuffer(_gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer);
  14249. } else if (renderTarget.depthBuffer && renderTarget.stencilBuffer) {
  14250. const samples = getRenderTargetSamples(renderTarget);
  14251. if (isMultisample && useMultisampledRTT(renderTarget) === false) {
  14252. _gl.renderbufferStorageMultisample(_gl.RENDERBUFFER, samples, _gl.DEPTH24_STENCIL8, renderTarget.width, renderTarget.height);
  14253. } else if (useMultisampledRTT(renderTarget)) {
  14254. multisampledRTTExt.renderbufferStorageMultisampleEXT(_gl.RENDERBUFFER, samples, _gl.DEPTH24_STENCIL8, renderTarget.width, renderTarget.height);
  14255. } else {
  14256. _gl.renderbufferStorage(_gl.RENDERBUFFER, _gl.DEPTH_STENCIL, renderTarget.width, renderTarget.height);
  14257. }
  14258. _gl.framebufferRenderbuffer(_gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer);
  14259. } else {
  14260. // Use the first texture for MRT so far
  14261. const texture = renderTarget.isWebGLMultipleRenderTargets === true ? renderTarget.texture[0] : renderTarget.texture;
  14262. const glFormat = utils.convert(texture.format, texture.encoding);
  14263. const glType = utils.convert(texture.type);
  14264. const glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType, texture.encoding);
  14265. const samples = getRenderTargetSamples(renderTarget);
  14266. if (isMultisample && useMultisampledRTT(renderTarget) === false) {
  14267. _gl.renderbufferStorageMultisample(_gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height);
  14268. } else if (useMultisampledRTT(renderTarget)) {
  14269. multisampledRTTExt.renderbufferStorageMultisampleEXT(_gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height);
  14270. } else {
  14271. _gl.renderbufferStorage(_gl.RENDERBUFFER, glInternalFormat, renderTarget.width, renderTarget.height);
  14272. }
  14273. }
  14274. _gl.bindRenderbuffer(_gl.RENDERBUFFER, null);
  14275. } // Setup resources for a Depth Texture for a FBO (needs an extension)
  14276. function setupDepthTexture(framebuffer, renderTarget) {
  14277. const isCube = renderTarget && renderTarget.isWebGLCubeRenderTarget;
  14278. if (isCube) throw new Error('Depth Texture with cube render targets is not supported');
  14279. state.bindFramebuffer(_gl.FRAMEBUFFER, framebuffer);
  14280. if (!(renderTarget.depthTexture && renderTarget.depthTexture.isDepthTexture)) {
  14281. throw new Error('renderTarget.depthTexture must be an instance of THREE.DepthTexture');
  14282. } // upload an empty depth texture with framebuffer size
  14283. if (!properties.get(renderTarget.depthTexture).__webglTexture || renderTarget.depthTexture.image.width !== renderTarget.width || renderTarget.depthTexture.image.height !== renderTarget.height) {
  14284. renderTarget.depthTexture.image.width = renderTarget.width;
  14285. renderTarget.depthTexture.image.height = renderTarget.height;
  14286. renderTarget.depthTexture.needsUpdate = true;
  14287. }
  14288. setTexture2D(renderTarget.depthTexture, 0);
  14289. const webglDepthTexture = properties.get(renderTarget.depthTexture).__webglTexture;
  14290. const samples = getRenderTargetSamples(renderTarget);
  14291. if (renderTarget.depthTexture.format === DepthFormat) {
  14292. if (useMultisampledRTT(renderTarget)) {
  14293. multisampledRTTExt.framebufferTexture2DMultisampleEXT(_gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0, samples);
  14294. } else {
  14295. _gl.framebufferTexture2D(_gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0);
  14296. }
  14297. } else if (renderTarget.depthTexture.format === DepthStencilFormat) {
  14298. if (useMultisampledRTT(renderTarget)) {
  14299. multisampledRTTExt.framebufferTexture2DMultisampleEXT(_gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0, samples);
  14300. } else {
  14301. _gl.framebufferTexture2D(_gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0);
  14302. }
  14303. } else {
  14304. throw new Error('Unknown depthTexture format');
  14305. }
  14306. } // Setup GL resources for a non-texture depth buffer
  14307. function setupDepthRenderbuffer(renderTarget) {
  14308. const renderTargetProperties = properties.get(renderTarget);
  14309. const isCube = renderTarget.isWebGLCubeRenderTarget === true;
  14310. if (renderTarget.depthTexture && !renderTargetProperties.__autoAllocateDepthBuffer) {
  14311. if (isCube) throw new Error('target.depthTexture not supported in Cube render targets');
  14312. setupDepthTexture(renderTargetProperties.__webglFramebuffer, renderTarget);
  14313. } else {
  14314. if (isCube) {
  14315. renderTargetProperties.__webglDepthbuffer = [];
  14316. for (let i = 0; i < 6; i++) {
  14317. state.bindFramebuffer(_gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer[i]);
  14318. renderTargetProperties.__webglDepthbuffer[i] = _gl.createRenderbuffer();
  14319. setupRenderBufferStorage(renderTargetProperties.__webglDepthbuffer[i], renderTarget, false);
  14320. }
  14321. } else {
  14322. state.bindFramebuffer(_gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer);
  14323. renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer();
  14324. setupRenderBufferStorage(renderTargetProperties.__webglDepthbuffer, renderTarget, false);
  14325. }
  14326. }
  14327. state.bindFramebuffer(_gl.FRAMEBUFFER, null);
  14328. } // rebind framebuffer with external textures
  14329. function rebindTextures(renderTarget, colorTexture, depthTexture) {
  14330. const renderTargetProperties = properties.get(renderTarget);
  14331. if (colorTexture !== undefined) {
  14332. setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer, renderTarget, renderTarget.texture, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D);
  14333. }
  14334. if (depthTexture !== undefined) {
  14335. setupDepthRenderbuffer(renderTarget);
  14336. }
  14337. } // Set up GL resources for the render target
  14338. function setupRenderTarget(renderTarget) {
  14339. const texture = renderTarget.texture;
  14340. const renderTargetProperties = properties.get(renderTarget);
  14341. const textureProperties = properties.get(texture);
  14342. renderTarget.addEventListener('dispose', onRenderTargetDispose);
  14343. if (renderTarget.isWebGLMultipleRenderTargets !== true) {
  14344. if (textureProperties.__webglTexture === undefined) {
  14345. textureProperties.__webglTexture = _gl.createTexture();
  14346. }
  14347. textureProperties.__version = texture.version;
  14348. info.memory.textures++;
  14349. }
  14350. const isCube = renderTarget.isWebGLCubeRenderTarget === true;
  14351. const isMultipleRenderTargets = renderTarget.isWebGLMultipleRenderTargets === true;
  14352. const supportsMips = isPowerOfTwo$1(renderTarget) || isWebGL2; // Setup framebuffer
  14353. if (isCube) {
  14354. renderTargetProperties.__webglFramebuffer = [];
  14355. for (let i = 0; i < 6; i++) {
  14356. renderTargetProperties.__webglFramebuffer[i] = _gl.createFramebuffer();
  14357. }
  14358. } else {
  14359. renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer();
  14360. if (isMultipleRenderTargets) {
  14361. if (capabilities.drawBuffers) {
  14362. const textures = renderTarget.texture;
  14363. for (let i = 0, il = textures.length; i < il; i++) {
  14364. const attachmentProperties = properties.get(textures[i]);
  14365. if (attachmentProperties.__webglTexture === undefined) {
  14366. attachmentProperties.__webglTexture = _gl.createTexture();
  14367. info.memory.textures++;
  14368. }
  14369. }
  14370. } else {
  14371. console.warn('THREE.WebGLRenderer: WebGLMultipleRenderTargets can only be used with WebGL2 or WEBGL_draw_buffers extension.');
  14372. }
  14373. } else if (isWebGL2 && renderTarget.samples > 0 && useMultisampledRTT(renderTarget) === false) {
  14374. renderTargetProperties.__webglMultisampledFramebuffer = _gl.createFramebuffer();
  14375. renderTargetProperties.__webglColorRenderbuffer = _gl.createRenderbuffer();
  14376. _gl.bindRenderbuffer(_gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer);
  14377. const glFormat = utils.convert(texture.format, texture.encoding);
  14378. const glType = utils.convert(texture.type);
  14379. const glInternalFormat = getInternalFormat(texture.internalFormat, glFormat, glType, texture.encoding);
  14380. const samples = getRenderTargetSamples(renderTarget);
  14381. _gl.renderbufferStorageMultisample(_gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height);
  14382. state.bindFramebuffer(_gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer);
  14383. _gl.framebufferRenderbuffer(_gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer);
  14384. _gl.bindRenderbuffer(_gl.RENDERBUFFER, null);
  14385. if (renderTarget.depthBuffer) {
  14386. renderTargetProperties.__webglDepthRenderbuffer = _gl.createRenderbuffer();
  14387. setupRenderBufferStorage(renderTargetProperties.__webglDepthRenderbuffer, renderTarget, true);
  14388. }
  14389. state.bindFramebuffer(_gl.FRAMEBUFFER, null);
  14390. }
  14391. } // Setup color buffer
  14392. if (isCube) {
  14393. state.bindTexture(_gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture);
  14394. setTextureParameters(_gl.TEXTURE_CUBE_MAP, texture, supportsMips);
  14395. for (let i = 0; i < 6; i++) {
  14396. setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer[i], renderTarget, texture, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i);
  14397. }
  14398. if (textureNeedsGenerateMipmaps(texture, supportsMips)) {
  14399. generateMipmap(_gl.TEXTURE_CUBE_MAP);
  14400. }
  14401. state.unbindTexture();
  14402. } else if (isMultipleRenderTargets) {
  14403. const textures = renderTarget.texture;
  14404. for (let i = 0, il = textures.length; i < il; i++) {
  14405. const attachment = textures[i];
  14406. const attachmentProperties = properties.get(attachment);
  14407. state.bindTexture(_gl.TEXTURE_2D, attachmentProperties.__webglTexture);
  14408. setTextureParameters(_gl.TEXTURE_2D, attachment, supportsMips);
  14409. setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer, renderTarget, attachment, _gl.COLOR_ATTACHMENT0 + i, _gl.TEXTURE_2D);
  14410. if (textureNeedsGenerateMipmaps(attachment, supportsMips)) {
  14411. generateMipmap(_gl.TEXTURE_2D);
  14412. }
  14413. }
  14414. state.unbindTexture();
  14415. } else {
  14416. let glTextureType = _gl.TEXTURE_2D;
  14417. if (renderTarget.isWebGL3DRenderTarget || renderTarget.isWebGLArrayRenderTarget) {
  14418. if (isWebGL2) {
  14419. glTextureType = renderTarget.isWebGL3DRenderTarget ? _gl.TEXTURE_3D : _gl.TEXTURE_2D_ARRAY;
  14420. } else {
  14421. console.error('THREE.WebGLTextures: THREE.Data3DTexture and THREE.DataArrayTexture only supported with WebGL2.');
  14422. }
  14423. }
  14424. state.bindTexture(glTextureType, textureProperties.__webglTexture);
  14425. setTextureParameters(glTextureType, texture, supportsMips);
  14426. setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer, renderTarget, texture, _gl.COLOR_ATTACHMENT0, glTextureType);
  14427. if (textureNeedsGenerateMipmaps(texture, supportsMips)) {
  14428. generateMipmap(glTextureType);
  14429. }
  14430. state.unbindTexture();
  14431. } // Setup depth and stencil buffers
  14432. if (renderTarget.depthBuffer) {
  14433. setupDepthRenderbuffer(renderTarget);
  14434. }
  14435. }
  14436. function updateRenderTargetMipmap(renderTarget) {
  14437. const supportsMips = isPowerOfTwo$1(renderTarget) || isWebGL2;
  14438. const textures = renderTarget.isWebGLMultipleRenderTargets === true ? renderTarget.texture : [renderTarget.texture];
  14439. for (let i = 0, il = textures.length; i < il; i++) {
  14440. const texture = textures[i];
  14441. if (textureNeedsGenerateMipmaps(texture, supportsMips)) {
  14442. const target = renderTarget.isWebGLCubeRenderTarget ? _gl.TEXTURE_CUBE_MAP : _gl.TEXTURE_2D;
  14443. const webglTexture = properties.get(texture).__webglTexture;
  14444. state.bindTexture(target, webglTexture);
  14445. generateMipmap(target);
  14446. state.unbindTexture();
  14447. }
  14448. }
  14449. }
  14450. function updateMultisampleRenderTarget(renderTarget) {
  14451. if (isWebGL2 && renderTarget.samples > 0 && useMultisampledRTT(renderTarget) === false) {
  14452. const width = renderTarget.width;
  14453. const height = renderTarget.height;
  14454. let mask = _gl.COLOR_BUFFER_BIT;
  14455. const invalidationArray = [_gl.COLOR_ATTACHMENT0];
  14456. const depthStyle = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT;
  14457. if (renderTarget.depthBuffer) {
  14458. invalidationArray.push(depthStyle);
  14459. }
  14460. const renderTargetProperties = properties.get(renderTarget);
  14461. const ignoreDepthValues = renderTargetProperties.__ignoreDepthValues !== undefined ? renderTargetProperties.__ignoreDepthValues : false;
  14462. if (ignoreDepthValues === false) {
  14463. if (renderTarget.depthBuffer) mask |= _gl.DEPTH_BUFFER_BIT;
  14464. if (renderTarget.stencilBuffer) mask |= _gl.STENCIL_BUFFER_BIT;
  14465. }
  14466. state.bindFramebuffer(_gl.READ_FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer);
  14467. state.bindFramebuffer(_gl.DRAW_FRAMEBUFFER, renderTargetProperties.__webglFramebuffer);
  14468. if (ignoreDepthValues === true) {
  14469. _gl.invalidateFramebuffer(_gl.READ_FRAMEBUFFER, [depthStyle]);
  14470. _gl.invalidateFramebuffer(_gl.DRAW_FRAMEBUFFER, [depthStyle]);
  14471. }
  14472. _gl.blitFramebuffer(0, 0, width, height, 0, 0, width, height, mask, _gl.NEAREST);
  14473. if (supportsInvalidateFramebuffer) {
  14474. _gl.invalidateFramebuffer(_gl.READ_FRAMEBUFFER, invalidationArray);
  14475. }
  14476. state.bindFramebuffer(_gl.READ_FRAMEBUFFER, null);
  14477. state.bindFramebuffer(_gl.DRAW_FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer);
  14478. }
  14479. }
  14480. function getRenderTargetSamples(renderTarget) {
  14481. return Math.min(maxSamples, renderTarget.samples);
  14482. }
  14483. function useMultisampledRTT(renderTarget) {
  14484. const renderTargetProperties = properties.get(renderTarget);
  14485. return isWebGL2 && renderTarget.samples > 0 && extensions.has('WEBGL_multisampled_render_to_texture') === true && renderTargetProperties.__useRenderToTexture !== false;
  14486. }
  14487. function updateVideoTexture(texture) {
  14488. const frame = info.render.frame; // Check the last frame we updated the VideoTexture
  14489. if (_videoTextures.get(texture) !== frame) {
  14490. _videoTextures.set(texture, frame);
  14491. texture.update();
  14492. }
  14493. }
  14494. function verifyColorSpace(texture, image) {
  14495. const encoding = texture.encoding;
  14496. const format = texture.format;
  14497. const type = texture.type;
  14498. if (texture.isCompressedTexture === true || texture.isVideoTexture === true || texture.format === _SRGBAFormat) return image;
  14499. if (encoding !== LinearEncoding) {
  14500. // sRGB
  14501. if (encoding === sRGBEncoding) {
  14502. if (isWebGL2 === false) {
  14503. // in WebGL 1, try to use EXT_sRGB extension and unsized formats
  14504. if (extensions.has('EXT_sRGB') === true && format === RGBAFormat) {
  14505. texture.format = _SRGBAFormat; // it's not possible to generate mips in WebGL 1 with this extension
  14506. texture.minFilter = LinearFilter;
  14507. texture.generateMipmaps = false;
  14508. } else {
  14509. // slow fallback (CPU decode)
  14510. image = ImageUtils.sRGBToLinear(image);
  14511. }
  14512. } else {
  14513. // in WebGL 2 uncompressed textures can only be sRGB encoded if they have the RGBA8 format
  14514. if (format !== RGBAFormat || type !== UnsignedByteType) {
  14515. console.warn('THREE.WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType.');
  14516. }
  14517. }
  14518. } else {
  14519. console.error('THREE.WebGLTextures: Unsupported texture encoding:', encoding);
  14520. }
  14521. }
  14522. return image;
  14523. } //
  14524. this.allocateTextureUnit = allocateTextureUnit;
  14525. this.resetTextureUnits = resetTextureUnits;
  14526. this.setTexture2D = setTexture2D;
  14527. this.setTexture2DArray = setTexture2DArray;
  14528. this.setTexture3D = setTexture3D;
  14529. this.setTextureCube = setTextureCube;
  14530. this.rebindTextures = rebindTextures;
  14531. this.setupRenderTarget = setupRenderTarget;
  14532. this.updateRenderTargetMipmap = updateRenderTargetMipmap;
  14533. this.updateMultisampleRenderTarget = updateMultisampleRenderTarget;
  14534. this.setupDepthRenderbuffer = setupDepthRenderbuffer;
  14535. this.setupFrameBufferTexture = setupFrameBufferTexture;
  14536. this.useMultisampledRTT = useMultisampledRTT;
  14537. }
  14538. function WebGLUtils(gl, extensions, capabilities) {
  14539. const isWebGL2 = capabilities.isWebGL2;
  14540. function convert(p, encoding = null) {
  14541. let extension;
  14542. if (p === UnsignedByteType) return gl.UNSIGNED_BYTE;
  14543. if (p === UnsignedShort4444Type) return gl.UNSIGNED_SHORT_4_4_4_4;
  14544. if (p === UnsignedShort5551Type) return gl.UNSIGNED_SHORT_5_5_5_1;
  14545. if (p === ByteType) return gl.BYTE;
  14546. if (p === ShortType) return gl.SHORT;
  14547. if (p === UnsignedShortType) return gl.UNSIGNED_SHORT;
  14548. if (p === IntType) return gl.INT;
  14549. if (p === UnsignedIntType) return gl.UNSIGNED_INT;
  14550. if (p === FloatType) return gl.FLOAT;
  14551. if (p === HalfFloatType) {
  14552. if (isWebGL2) return gl.HALF_FLOAT;
  14553. extension = extensions.get('OES_texture_half_float');
  14554. if (extension !== null) {
  14555. return extension.HALF_FLOAT_OES;
  14556. } else {
  14557. return null;
  14558. }
  14559. }
  14560. if (p === AlphaFormat) return gl.ALPHA;
  14561. if (p === RGBAFormat) return gl.RGBA;
  14562. if (p === LuminanceFormat) return gl.LUMINANCE;
  14563. if (p === LuminanceAlphaFormat) return gl.LUMINANCE_ALPHA;
  14564. if (p === DepthFormat) return gl.DEPTH_COMPONENT;
  14565. if (p === DepthStencilFormat) return gl.DEPTH_STENCIL;
  14566. if (p === RedFormat) return gl.RED;
  14567. if (p === RGBFormat) {
  14568. console.warn('THREE.WebGLRenderer: THREE.RGBFormat has been removed. Use THREE.RGBAFormat instead. https://github.com/mrdoob/three.js/pull/23228');
  14569. return gl.RGBA;
  14570. } // WebGL 1 sRGB fallback
  14571. if (p === _SRGBAFormat) {
  14572. extension = extensions.get('EXT_sRGB');
  14573. if (extension !== null) {
  14574. return extension.SRGB_ALPHA_EXT;
  14575. } else {
  14576. return null;
  14577. }
  14578. } // WebGL2 formats.
  14579. if (p === RedIntegerFormat) return gl.RED_INTEGER;
  14580. if (p === RGFormat) return gl.RG;
  14581. if (p === RGIntegerFormat) return gl.RG_INTEGER;
  14582. if (p === RGBAIntegerFormat) return gl.RGBA_INTEGER; // S3TC
  14583. if (p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format) {
  14584. if (encoding === sRGBEncoding) {
  14585. extension = extensions.get('WEBGL_compressed_texture_s3tc_srgb');
  14586. if (extension !== null) {
  14587. if (p === RGB_S3TC_DXT1_Format) return extension.COMPRESSED_SRGB_S3TC_DXT1_EXT;
  14588. if (p === RGBA_S3TC_DXT1_Format) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;
  14589. if (p === RGBA_S3TC_DXT3_Format) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;
  14590. if (p === RGBA_S3TC_DXT5_Format) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT;
  14591. } else {
  14592. return null;
  14593. }
  14594. } else {
  14595. extension = extensions.get('WEBGL_compressed_texture_s3tc');
  14596. if (extension !== null) {
  14597. if (p === RGB_S3TC_DXT1_Format) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  14598. if (p === RGBA_S3TC_DXT1_Format) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  14599. if (p === RGBA_S3TC_DXT3_Format) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  14600. if (p === RGBA_S3TC_DXT5_Format) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  14601. } else {
  14602. return null;
  14603. }
  14604. }
  14605. } // PVRTC
  14606. if (p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format) {
  14607. extension = extensions.get('WEBGL_compressed_texture_pvrtc');
  14608. if (extension !== null) {
  14609. if (p === RGB_PVRTC_4BPPV1_Format) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  14610. if (p === RGB_PVRTC_2BPPV1_Format) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  14611. if (p === RGBA_PVRTC_4BPPV1_Format) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  14612. if (p === RGBA_PVRTC_2BPPV1_Format) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  14613. } else {
  14614. return null;
  14615. }
  14616. } // ETC1
  14617. if (p === RGB_ETC1_Format) {
  14618. extension = extensions.get('WEBGL_compressed_texture_etc1');
  14619. if (extension !== null) {
  14620. return extension.COMPRESSED_RGB_ETC1_WEBGL;
  14621. } else {
  14622. return null;
  14623. }
  14624. } // ETC2
  14625. if (p === RGB_ETC2_Format || p === RGBA_ETC2_EAC_Format) {
  14626. extension = extensions.get('WEBGL_compressed_texture_etc');
  14627. if (extension !== null) {
  14628. if (p === RGB_ETC2_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB8_ETC2 : extension.COMPRESSED_RGB8_ETC2;
  14629. if (p === RGBA_ETC2_EAC_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC : extension.COMPRESSED_RGBA8_ETC2_EAC;
  14630. } else {
  14631. return null;
  14632. }
  14633. } // ASTC
  14634. 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) {
  14635. extension = extensions.get('WEBGL_compressed_texture_astc');
  14636. if (extension !== null) {
  14637. if (p === RGBA_ASTC_4x4_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR : extension.COMPRESSED_RGBA_ASTC_4x4_KHR;
  14638. if (p === RGBA_ASTC_5x4_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR : extension.COMPRESSED_RGBA_ASTC_5x4_KHR;
  14639. if (p === RGBA_ASTC_5x5_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR : extension.COMPRESSED_RGBA_ASTC_5x5_KHR;
  14640. if (p === RGBA_ASTC_6x5_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR : extension.COMPRESSED_RGBA_ASTC_6x5_KHR;
  14641. if (p === RGBA_ASTC_6x6_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR : extension.COMPRESSED_RGBA_ASTC_6x6_KHR;
  14642. if (p === RGBA_ASTC_8x5_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR : extension.COMPRESSED_RGBA_ASTC_8x5_KHR;
  14643. if (p === RGBA_ASTC_8x6_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR : extension.COMPRESSED_RGBA_ASTC_8x6_KHR;
  14644. if (p === RGBA_ASTC_8x8_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR : extension.COMPRESSED_RGBA_ASTC_8x8_KHR;
  14645. if (p === RGBA_ASTC_10x5_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR : extension.COMPRESSED_RGBA_ASTC_10x5_KHR;
  14646. if (p === RGBA_ASTC_10x6_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR : extension.COMPRESSED_RGBA_ASTC_10x6_KHR;
  14647. if (p === RGBA_ASTC_10x8_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR : extension.COMPRESSED_RGBA_ASTC_10x8_KHR;
  14648. if (p === RGBA_ASTC_10x10_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR : extension.COMPRESSED_RGBA_ASTC_10x10_KHR;
  14649. if (p === RGBA_ASTC_12x10_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR : extension.COMPRESSED_RGBA_ASTC_12x10_KHR;
  14650. if (p === RGBA_ASTC_12x12_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR : extension.COMPRESSED_RGBA_ASTC_12x12_KHR;
  14651. } else {
  14652. return null;
  14653. }
  14654. } // BPTC
  14655. if (p === RGBA_BPTC_Format) {
  14656. extension = extensions.get('EXT_texture_compression_bptc');
  14657. if (extension !== null) {
  14658. if (p === RGBA_BPTC_Format) return encoding === sRGBEncoding ? extension.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT : extension.COMPRESSED_RGBA_BPTC_UNORM_EXT;
  14659. } else {
  14660. return null;
  14661. }
  14662. } //
  14663. if (p === UnsignedInt248Type) {
  14664. if (isWebGL2) return gl.UNSIGNED_INT_24_8;
  14665. extension = extensions.get('WEBGL_depth_texture');
  14666. if (extension !== null) {
  14667. return extension.UNSIGNED_INT_24_8_WEBGL;
  14668. } else {
  14669. return null;
  14670. }
  14671. } // if "p" can't be resolved, assume the user defines a WebGL constant as a string (fallback/workaround for packed RGB formats)
  14672. return gl[p] !== undefined ? gl[p] : null;
  14673. }
  14674. return {
  14675. convert: convert
  14676. };
  14677. }
  14678. class ArrayCamera extends PerspectiveCamera {
  14679. constructor(array = []) {
  14680. super();
  14681. this.isArrayCamera = true;
  14682. this.cameras = array;
  14683. }
  14684. }
  14685. class Group extends Object3D {
  14686. constructor() {
  14687. super();
  14688. this.isGroup = true;
  14689. this.type = 'Group';
  14690. }
  14691. }
  14692. const _moveEvent = {
  14693. type: 'move'
  14694. };
  14695. class WebXRController {
  14696. constructor() {
  14697. this._targetRay = null;
  14698. this._grip = null;
  14699. this._hand = null;
  14700. }
  14701. getHandSpace() {
  14702. if (this._hand === null) {
  14703. this._hand = new Group();
  14704. this._hand.matrixAutoUpdate = false;
  14705. this._hand.visible = false;
  14706. this._hand.joints = {};
  14707. this._hand.inputState = {
  14708. pinching: false
  14709. };
  14710. }
  14711. return this._hand;
  14712. }
  14713. getTargetRaySpace() {
  14714. if (this._targetRay === null) {
  14715. this._targetRay = new Group();
  14716. this._targetRay.matrixAutoUpdate = false;
  14717. this._targetRay.visible = false;
  14718. this._targetRay.hasLinearVelocity = false;
  14719. this._targetRay.linearVelocity = new Vector3();
  14720. this._targetRay.hasAngularVelocity = false;
  14721. this._targetRay.angularVelocity = new Vector3();
  14722. }
  14723. return this._targetRay;
  14724. }
  14725. getGripSpace() {
  14726. if (this._grip === null) {
  14727. this._grip = new Group();
  14728. this._grip.matrixAutoUpdate = false;
  14729. this._grip.visible = false;
  14730. this._grip.hasLinearVelocity = false;
  14731. this._grip.linearVelocity = new Vector3();
  14732. this._grip.hasAngularVelocity = false;
  14733. this._grip.angularVelocity = new Vector3();
  14734. }
  14735. return this._grip;
  14736. }
  14737. dispatchEvent(event) {
  14738. if (this._targetRay !== null) {
  14739. this._targetRay.dispatchEvent(event);
  14740. }
  14741. if (this._grip !== null) {
  14742. this._grip.dispatchEvent(event);
  14743. }
  14744. if (this._hand !== null) {
  14745. this._hand.dispatchEvent(event);
  14746. }
  14747. return this;
  14748. }
  14749. disconnect(inputSource) {
  14750. this.dispatchEvent({
  14751. type: 'disconnected',
  14752. data: inputSource
  14753. });
  14754. if (this._targetRay !== null) {
  14755. this._targetRay.visible = false;
  14756. }
  14757. if (this._grip !== null) {
  14758. this._grip.visible = false;
  14759. }
  14760. if (this._hand !== null) {
  14761. this._hand.visible = false;
  14762. }
  14763. return this;
  14764. }
  14765. update(inputSource, frame, referenceSpace) {
  14766. let inputPose = null;
  14767. let gripPose = null;
  14768. let handPose = null;
  14769. const targetRay = this._targetRay;
  14770. const grip = this._grip;
  14771. const hand = this._hand;
  14772. if (inputSource && frame.session.visibilityState !== 'visible-blurred') {
  14773. if (targetRay !== null) {
  14774. inputPose = frame.getPose(inputSource.targetRaySpace, referenceSpace);
  14775. if (inputPose !== null) {
  14776. targetRay.matrix.fromArray(inputPose.transform.matrix);
  14777. targetRay.matrix.decompose(targetRay.position, targetRay.rotation, targetRay.scale);
  14778. if (inputPose.linearVelocity) {
  14779. targetRay.hasLinearVelocity = true;
  14780. targetRay.linearVelocity.copy(inputPose.linearVelocity);
  14781. } else {
  14782. targetRay.hasLinearVelocity = false;
  14783. }
  14784. if (inputPose.angularVelocity) {
  14785. targetRay.hasAngularVelocity = true;
  14786. targetRay.angularVelocity.copy(inputPose.angularVelocity);
  14787. } else {
  14788. targetRay.hasAngularVelocity = false;
  14789. }
  14790. this.dispatchEvent(_moveEvent);
  14791. }
  14792. }
  14793. if (hand && inputSource.hand) {
  14794. handPose = true;
  14795. for (const inputjoint of inputSource.hand.values()) {
  14796. // Update the joints groups with the XRJoint poses
  14797. const jointPose = frame.getJointPose(inputjoint, referenceSpace);
  14798. if (hand.joints[inputjoint.jointName] === undefined) {
  14799. // The transform of this joint will be updated with the joint pose on each frame
  14800. const joint = new Group();
  14801. joint.matrixAutoUpdate = false;
  14802. joint.visible = false;
  14803. hand.joints[inputjoint.jointName] = joint; // ??
  14804. hand.add(joint);
  14805. }
  14806. const joint = hand.joints[inputjoint.jointName];
  14807. if (jointPose !== null) {
  14808. joint.matrix.fromArray(jointPose.transform.matrix);
  14809. joint.matrix.decompose(joint.position, joint.rotation, joint.scale);
  14810. joint.jointRadius = jointPose.radius;
  14811. }
  14812. joint.visible = jointPose !== null;
  14813. } // Custom events
  14814. // Check pinchz
  14815. const indexTip = hand.joints['index-finger-tip'];
  14816. const thumbTip = hand.joints['thumb-tip'];
  14817. const distance = indexTip.position.distanceTo(thumbTip.position);
  14818. const distanceToPinch = 0.02;
  14819. const threshold = 0.005;
  14820. if (hand.inputState.pinching && distance > distanceToPinch + threshold) {
  14821. hand.inputState.pinching = false;
  14822. this.dispatchEvent({
  14823. type: 'pinchend',
  14824. handedness: inputSource.handedness,
  14825. target: this
  14826. });
  14827. } else if (!hand.inputState.pinching && distance <= distanceToPinch - threshold) {
  14828. hand.inputState.pinching = true;
  14829. this.dispatchEvent({
  14830. type: 'pinchstart',
  14831. handedness: inputSource.handedness,
  14832. target: this
  14833. });
  14834. }
  14835. } else {
  14836. if (grip !== null && inputSource.gripSpace) {
  14837. gripPose = frame.getPose(inputSource.gripSpace, referenceSpace);
  14838. if (gripPose !== null) {
  14839. grip.matrix.fromArray(gripPose.transform.matrix);
  14840. grip.matrix.decompose(grip.position, grip.rotation, grip.scale);
  14841. if (gripPose.linearVelocity) {
  14842. grip.hasLinearVelocity = true;
  14843. grip.linearVelocity.copy(gripPose.linearVelocity);
  14844. } else {
  14845. grip.hasLinearVelocity = false;
  14846. }
  14847. if (gripPose.angularVelocity) {
  14848. grip.hasAngularVelocity = true;
  14849. grip.angularVelocity.copy(gripPose.angularVelocity);
  14850. } else {
  14851. grip.hasAngularVelocity = false;
  14852. }
  14853. }
  14854. }
  14855. }
  14856. }
  14857. if (targetRay !== null) {
  14858. targetRay.visible = inputPose !== null;
  14859. }
  14860. if (grip !== null) {
  14861. grip.visible = gripPose !== null;
  14862. }
  14863. if (hand !== null) {
  14864. hand.visible = handPose !== null;
  14865. }
  14866. return this;
  14867. }
  14868. }
  14869. class DepthTexture extends Texture {
  14870. constructor(width, height, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, format) {
  14871. format = format !== undefined ? format : DepthFormat;
  14872. if (format !== DepthFormat && format !== DepthStencilFormat) {
  14873. throw new Error('DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat');
  14874. }
  14875. if (type === undefined && format === DepthFormat) type = UnsignedIntType;
  14876. if (type === undefined && format === DepthStencilFormat) type = UnsignedInt248Type;
  14877. super(null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy);
  14878. this.isDepthTexture = true;
  14879. this.image = {
  14880. width: width,
  14881. height: height
  14882. };
  14883. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  14884. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  14885. this.flipY = false;
  14886. this.generateMipmaps = false;
  14887. }
  14888. }
  14889. class WebXRManager extends EventDispatcher {
  14890. constructor(renderer, gl) {
  14891. super();
  14892. const scope = this;
  14893. let session = null;
  14894. let framebufferScaleFactor = 1.0;
  14895. let referenceSpace = null;
  14896. let referenceSpaceType = 'local-floor';
  14897. let customReferenceSpace = null;
  14898. let pose = null;
  14899. let glBinding = null;
  14900. let glProjLayer = null;
  14901. let glBaseLayer = null;
  14902. let xrFrame = null;
  14903. const attributes = gl.getContextAttributes();
  14904. let initialRenderTarget = null;
  14905. let newRenderTarget = null;
  14906. const controllers = [];
  14907. const inputSourcesMap = new Map(); //
  14908. const cameraL = new PerspectiveCamera();
  14909. cameraL.layers.enable(1);
  14910. cameraL.viewport = new Vector4();
  14911. const cameraR = new PerspectiveCamera();
  14912. cameraR.layers.enable(2);
  14913. cameraR.viewport = new Vector4();
  14914. const cameras = [cameraL, cameraR];
  14915. const cameraVR = new ArrayCamera();
  14916. cameraVR.layers.enable(1);
  14917. cameraVR.layers.enable(2);
  14918. let _currentDepthNear = null;
  14919. let _currentDepthFar = null; //
  14920. this.cameraAutoUpdate = true;
  14921. this.enabled = false;
  14922. this.isPresenting = false;
  14923. this.getController = function (index) {
  14924. let controller = controllers[index];
  14925. if (controller === undefined) {
  14926. controller = new WebXRController();
  14927. controllers[index] = controller;
  14928. }
  14929. return controller.getTargetRaySpace();
  14930. };
  14931. this.getControllerGrip = function (index) {
  14932. let controller = controllers[index];
  14933. if (controller === undefined) {
  14934. controller = new WebXRController();
  14935. controllers[index] = controller;
  14936. }
  14937. return controller.getGripSpace();
  14938. };
  14939. this.getHand = function (index) {
  14940. let controller = controllers[index];
  14941. if (controller === undefined) {
  14942. controller = new WebXRController();
  14943. controllers[index] = controller;
  14944. }
  14945. return controller.getHandSpace();
  14946. }; //
  14947. function onSessionEvent(event) {
  14948. const controller = inputSourcesMap.get(event.inputSource);
  14949. if (controller !== undefined) {
  14950. controller.dispatchEvent({
  14951. type: event.type,
  14952. data: event.inputSource
  14953. });
  14954. }
  14955. }
  14956. function onSessionEnd() {
  14957. session.removeEventListener('select', onSessionEvent);
  14958. session.removeEventListener('selectstart', onSessionEvent);
  14959. session.removeEventListener('selectend', onSessionEvent);
  14960. session.removeEventListener('squeeze', onSessionEvent);
  14961. session.removeEventListener('squeezestart', onSessionEvent);
  14962. session.removeEventListener('squeezeend', onSessionEvent);
  14963. session.removeEventListener('end', onSessionEnd);
  14964. session.removeEventListener('inputsourceschange', onInputSourcesChange);
  14965. inputSourcesMap.forEach(function (controller, inputSource) {
  14966. if (controller !== undefined) {
  14967. controller.disconnect(inputSource);
  14968. }
  14969. });
  14970. inputSourcesMap.clear();
  14971. _currentDepthNear = null;
  14972. _currentDepthFar = null; // restore framebuffer/rendering state
  14973. renderer.setRenderTarget(initialRenderTarget);
  14974. glBaseLayer = null;
  14975. glProjLayer = null;
  14976. glBinding = null;
  14977. session = null;
  14978. newRenderTarget = null; //
  14979. animation.stop();
  14980. scope.isPresenting = false;
  14981. scope.dispatchEvent({
  14982. type: 'sessionend'
  14983. });
  14984. }
  14985. this.setFramebufferScaleFactor = function (value) {
  14986. framebufferScaleFactor = value;
  14987. if (scope.isPresenting === true) {
  14988. console.warn('THREE.WebXRManager: Cannot change framebuffer scale while presenting.');
  14989. }
  14990. };
  14991. this.setReferenceSpaceType = function (value) {
  14992. referenceSpaceType = value;
  14993. if (scope.isPresenting === true) {
  14994. console.warn('THREE.WebXRManager: Cannot change reference space type while presenting.');
  14995. }
  14996. };
  14997. this.getReferenceSpace = function () {
  14998. return customReferenceSpace || referenceSpace;
  14999. };
  15000. this.setReferenceSpace = function (space) {
  15001. customReferenceSpace = space;
  15002. };
  15003. this.getBaseLayer = function () {
  15004. return glProjLayer !== null ? glProjLayer : glBaseLayer;
  15005. };
  15006. this.getBinding = function () {
  15007. return glBinding;
  15008. };
  15009. this.getFrame = function () {
  15010. return xrFrame;
  15011. };
  15012. this.getSession = function () {
  15013. return session;
  15014. };
  15015. this.setSession = async function (value) {
  15016. session = value;
  15017. if (session !== null) {
  15018. initialRenderTarget = renderer.getRenderTarget();
  15019. session.addEventListener('select', onSessionEvent);
  15020. session.addEventListener('selectstart', onSessionEvent);
  15021. session.addEventListener('selectend', onSessionEvent);
  15022. session.addEventListener('squeeze', onSessionEvent);
  15023. session.addEventListener('squeezestart', onSessionEvent);
  15024. session.addEventListener('squeezeend', onSessionEvent);
  15025. session.addEventListener('end', onSessionEnd);
  15026. session.addEventListener('inputsourceschange', onInputSourcesChange);
  15027. if (attributes.xrCompatible !== true) {
  15028. await gl.makeXRCompatible();
  15029. }
  15030. if (session.renderState.layers === undefined || renderer.capabilities.isWebGL2 === false) {
  15031. const layerInit = {
  15032. antialias: session.renderState.layers === undefined ? attributes.antialias : true,
  15033. alpha: attributes.alpha,
  15034. depth: attributes.depth,
  15035. stencil: attributes.stencil,
  15036. framebufferScaleFactor: framebufferScaleFactor
  15037. };
  15038. glBaseLayer = new XRWebGLLayer(session, gl, layerInit);
  15039. session.updateRenderState({
  15040. baseLayer: glBaseLayer
  15041. });
  15042. newRenderTarget = new WebGLRenderTarget(glBaseLayer.framebufferWidth, glBaseLayer.framebufferHeight, {
  15043. format: RGBAFormat,
  15044. type: UnsignedByteType,
  15045. encoding: renderer.outputEncoding
  15046. });
  15047. } else {
  15048. let depthFormat = null;
  15049. let depthType = null;
  15050. let glDepthFormat = null;
  15051. if (attributes.depth) {
  15052. glDepthFormat = attributes.stencil ? gl.DEPTH24_STENCIL8 : gl.DEPTH_COMPONENT24;
  15053. depthFormat = attributes.stencil ? DepthStencilFormat : DepthFormat;
  15054. depthType = attributes.stencil ? UnsignedInt248Type : UnsignedIntType;
  15055. }
  15056. const projectionlayerInit = {
  15057. colorFormat: renderer.outputEncoding === sRGBEncoding ? gl.SRGB8_ALPHA8 : gl.RGBA8,
  15058. depthFormat: glDepthFormat,
  15059. scaleFactor: framebufferScaleFactor
  15060. };
  15061. glBinding = new XRWebGLBinding(session, gl);
  15062. glProjLayer = glBinding.createProjectionLayer(projectionlayerInit);
  15063. session.updateRenderState({
  15064. layers: [glProjLayer]
  15065. });
  15066. newRenderTarget = new WebGLRenderTarget(glProjLayer.textureWidth, glProjLayer.textureHeight, {
  15067. format: RGBAFormat,
  15068. type: UnsignedByteType,
  15069. depthTexture: new DepthTexture(glProjLayer.textureWidth, glProjLayer.textureHeight, depthType, undefined, undefined, undefined, undefined, undefined, undefined, depthFormat),
  15070. stencilBuffer: attributes.stencil,
  15071. encoding: renderer.outputEncoding,
  15072. samples: attributes.antialias ? 4 : 0
  15073. });
  15074. const renderTargetProperties = renderer.properties.get(newRenderTarget);
  15075. renderTargetProperties.__ignoreDepthValues = glProjLayer.ignoreDepthValues;
  15076. }
  15077. newRenderTarget.isXRRenderTarget = true; // TODO Remove this when possible, see #23278
  15078. // Set foveation to maximum.
  15079. this.setFoveation(1.0);
  15080. customReferenceSpace = null;
  15081. referenceSpace = await session.requestReferenceSpace(referenceSpaceType);
  15082. animation.setContext(session);
  15083. animation.start();
  15084. scope.isPresenting = true;
  15085. scope.dispatchEvent({
  15086. type: 'sessionstart'
  15087. });
  15088. }
  15089. };
  15090. function onInputSourcesChange(event) {
  15091. const inputSources = session.inputSources; // Assign controllers to available inputSources
  15092. for (let i = 0; i < inputSources.length; i++) {
  15093. const index = inputSources[i].handedness === 'right' ? 1 : 0;
  15094. inputSourcesMap.set(inputSources[i], controllers[index]);
  15095. } // Notify disconnected
  15096. for (let i = 0; i < event.removed.length; i++) {
  15097. const inputSource = event.removed[i];
  15098. const controller = inputSourcesMap.get(inputSource);
  15099. if (controller) {
  15100. controller.dispatchEvent({
  15101. type: 'disconnected',
  15102. data: inputSource
  15103. });
  15104. inputSourcesMap.delete(inputSource);
  15105. }
  15106. } // Notify connected
  15107. for (let i = 0; i < event.added.length; i++) {
  15108. const inputSource = event.added[i];
  15109. const controller = inputSourcesMap.get(inputSource);
  15110. if (controller) {
  15111. controller.dispatchEvent({
  15112. type: 'connected',
  15113. data: inputSource
  15114. });
  15115. }
  15116. }
  15117. } //
  15118. const cameraLPos = new Vector3();
  15119. const cameraRPos = new Vector3();
  15120. /**
  15121. * Assumes 2 cameras that are parallel and share an X-axis, and that
  15122. * the cameras' projection and world matrices have already been set.
  15123. * And that near and far planes are identical for both cameras.
  15124. * Visualization of this technique: https://computergraphics.stackexchange.com/a/4765
  15125. */
  15126. function setProjectionFromUnion(camera, cameraL, cameraR) {
  15127. cameraLPos.setFromMatrixPosition(cameraL.matrixWorld);
  15128. cameraRPos.setFromMatrixPosition(cameraR.matrixWorld);
  15129. const ipd = cameraLPos.distanceTo(cameraRPos);
  15130. const projL = cameraL.projectionMatrix.elements;
  15131. const projR = cameraR.projectionMatrix.elements; // VR systems will have identical far and near planes, and
  15132. // most likely identical top and bottom frustum extents.
  15133. // Use the left camera for these values.
  15134. const near = projL[14] / (projL[10] - 1);
  15135. const far = projL[14] / (projL[10] + 1);
  15136. const topFov = (projL[9] + 1) / projL[5];
  15137. const bottomFov = (projL[9] - 1) / projL[5];
  15138. const leftFov = (projL[8] - 1) / projL[0];
  15139. const rightFov = (projR[8] + 1) / projR[0];
  15140. const left = near * leftFov;
  15141. const right = near * rightFov; // Calculate the new camera's position offset from the
  15142. // left camera. xOffset should be roughly half `ipd`.
  15143. const zOffset = ipd / (-leftFov + rightFov);
  15144. const xOffset = zOffset * -leftFov; // TODO: Better way to apply this offset?
  15145. cameraL.matrixWorld.decompose(camera.position, camera.quaternion, camera.scale);
  15146. camera.translateX(xOffset);
  15147. camera.translateZ(zOffset);
  15148. camera.matrixWorld.compose(camera.position, camera.quaternion, camera.scale);
  15149. camera.matrixWorldInverse.copy(camera.matrixWorld).invert(); // Find the union of the frustum values of the cameras and scale
  15150. // the values so that the near plane's position does not change in world space,
  15151. // although must now be relative to the new union camera.
  15152. const near2 = near + zOffset;
  15153. const far2 = far + zOffset;
  15154. const left2 = left - xOffset;
  15155. const right2 = right + (ipd - xOffset);
  15156. const top2 = topFov * far / far2 * near2;
  15157. const bottom2 = bottomFov * far / far2 * near2;
  15158. camera.projectionMatrix.makePerspective(left2, right2, top2, bottom2, near2, far2);
  15159. }
  15160. function updateCamera(camera, parent) {
  15161. if (parent === null) {
  15162. camera.matrixWorld.copy(camera.matrix);
  15163. } else {
  15164. camera.matrixWorld.multiplyMatrices(parent.matrixWorld, camera.matrix);
  15165. }
  15166. camera.matrixWorldInverse.copy(camera.matrixWorld).invert();
  15167. }
  15168. this.updateCamera = function (camera) {
  15169. if (session === null) return;
  15170. cameraVR.near = cameraR.near = cameraL.near = camera.near;
  15171. cameraVR.far = cameraR.far = cameraL.far = camera.far;
  15172. if (_currentDepthNear !== cameraVR.near || _currentDepthFar !== cameraVR.far) {
  15173. // Note that the new renderState won't apply until the next frame. See #18320
  15174. session.updateRenderState({
  15175. depthNear: cameraVR.near,
  15176. depthFar: cameraVR.far
  15177. });
  15178. _currentDepthNear = cameraVR.near;
  15179. _currentDepthFar = cameraVR.far;
  15180. }
  15181. const parent = camera.parent;
  15182. const cameras = cameraVR.cameras;
  15183. updateCamera(cameraVR, parent);
  15184. for (let i = 0; i < cameras.length; i++) {
  15185. updateCamera(cameras[i], parent);
  15186. }
  15187. cameraVR.matrixWorld.decompose(cameraVR.position, cameraVR.quaternion, cameraVR.scale); // update user camera and its children
  15188. camera.position.copy(cameraVR.position);
  15189. camera.quaternion.copy(cameraVR.quaternion);
  15190. camera.scale.copy(cameraVR.scale);
  15191. camera.matrix.copy(cameraVR.matrix);
  15192. camera.matrixWorld.copy(cameraVR.matrixWorld);
  15193. const children = camera.children;
  15194. for (let i = 0, l = children.length; i < l; i++) {
  15195. children[i].updateMatrixWorld(true);
  15196. } // update projection matrix for proper view frustum culling
  15197. if (cameras.length === 2) {
  15198. setProjectionFromUnion(cameraVR, cameraL, cameraR);
  15199. } else {
  15200. // assume single camera setup (AR)
  15201. cameraVR.projectionMatrix.copy(cameraL.projectionMatrix);
  15202. }
  15203. };
  15204. this.getCamera = function () {
  15205. return cameraVR;
  15206. };
  15207. this.getFoveation = function () {
  15208. if (glProjLayer !== null) {
  15209. return glProjLayer.fixedFoveation;
  15210. }
  15211. if (glBaseLayer !== null) {
  15212. return glBaseLayer.fixedFoveation;
  15213. }
  15214. return undefined;
  15215. };
  15216. this.setFoveation = function (foveation) {
  15217. // 0 = no foveation = full resolution
  15218. // 1 = maximum foveation = the edges render at lower resolution
  15219. if (glProjLayer !== null) {
  15220. glProjLayer.fixedFoveation = foveation;
  15221. }
  15222. if (glBaseLayer !== null && glBaseLayer.fixedFoveation !== undefined) {
  15223. glBaseLayer.fixedFoveation = foveation;
  15224. }
  15225. }; // Animation Loop
  15226. let onAnimationFrameCallback = null;
  15227. function onAnimationFrame(time, frame) {
  15228. pose = frame.getViewerPose(customReferenceSpace || referenceSpace);
  15229. xrFrame = frame;
  15230. if (pose !== null) {
  15231. const views = pose.views;
  15232. if (glBaseLayer !== null) {
  15233. renderer.setRenderTargetFramebuffer(newRenderTarget, glBaseLayer.framebuffer);
  15234. renderer.setRenderTarget(newRenderTarget);
  15235. }
  15236. let cameraVRNeedsUpdate = false; // check if it's necessary to rebuild cameraVR's camera list
  15237. if (views.length !== cameraVR.cameras.length) {
  15238. cameraVR.cameras.length = 0;
  15239. cameraVRNeedsUpdate = true;
  15240. }
  15241. for (let i = 0; i < views.length; i++) {
  15242. const view = views[i];
  15243. let viewport = null;
  15244. if (glBaseLayer !== null) {
  15245. viewport = glBaseLayer.getViewport(view);
  15246. } else {
  15247. const glSubImage = glBinding.getViewSubImage(glProjLayer, view);
  15248. viewport = glSubImage.viewport; // For side-by-side projection, we only produce a single texture for both eyes.
  15249. if (i === 0) {
  15250. renderer.setRenderTargetTextures(newRenderTarget, glSubImage.colorTexture, glProjLayer.ignoreDepthValues ? undefined : glSubImage.depthStencilTexture);
  15251. renderer.setRenderTarget(newRenderTarget);
  15252. }
  15253. }
  15254. const camera = cameras[i];
  15255. camera.matrix.fromArray(view.transform.matrix);
  15256. camera.projectionMatrix.fromArray(view.projectionMatrix);
  15257. camera.viewport.set(viewport.x, viewport.y, viewport.width, viewport.height);
  15258. if (i === 0) {
  15259. cameraVR.matrix.copy(camera.matrix);
  15260. }
  15261. if (cameraVRNeedsUpdate === true) {
  15262. cameraVR.cameras.push(camera);
  15263. }
  15264. }
  15265. } //
  15266. const inputSources = session.inputSources;
  15267. for (let i = 0; i < controllers.length; i++) {
  15268. const inputSource = inputSources[i];
  15269. const controller = inputSourcesMap.get(inputSource);
  15270. if (controller !== undefined) {
  15271. controller.update(inputSource, frame, customReferenceSpace || referenceSpace);
  15272. }
  15273. }
  15274. if (onAnimationFrameCallback) onAnimationFrameCallback(time, frame);
  15275. xrFrame = null;
  15276. }
  15277. const animation = new WebGLAnimation();
  15278. animation.setAnimationLoop(onAnimationFrame);
  15279. this.setAnimationLoop = function (callback) {
  15280. onAnimationFrameCallback = callback;
  15281. };
  15282. this.dispose = function () {};
  15283. }
  15284. }
  15285. function WebGLMaterials(renderer, properties) {
  15286. function refreshFogUniforms(uniforms, fog) {
  15287. uniforms.fogColor.value.copy(fog.color);
  15288. if (fog.isFog) {
  15289. uniforms.fogNear.value = fog.near;
  15290. uniforms.fogFar.value = fog.far;
  15291. } else if (fog.isFogExp2) {
  15292. uniforms.fogDensity.value = fog.density;
  15293. }
  15294. }
  15295. function refreshMaterialUniforms(uniforms, material, pixelRatio, height, transmissionRenderTarget) {
  15296. if (material.isMeshBasicMaterial) {
  15297. refreshUniformsCommon(uniforms, material);
  15298. } else if (material.isMeshLambertMaterial) {
  15299. refreshUniformsCommon(uniforms, material);
  15300. } else if (material.isMeshToonMaterial) {
  15301. refreshUniformsCommon(uniforms, material);
  15302. refreshUniformsToon(uniforms, material);
  15303. } else if (material.isMeshPhongMaterial) {
  15304. refreshUniformsCommon(uniforms, material);
  15305. refreshUniformsPhong(uniforms, material);
  15306. } else if (material.isMeshStandardMaterial) {
  15307. refreshUniformsCommon(uniforms, material);
  15308. refreshUniformsStandard(uniforms, material);
  15309. if (material.isMeshPhysicalMaterial) {
  15310. refreshUniformsPhysical(uniforms, material, transmissionRenderTarget);
  15311. }
  15312. } else if (material.isMeshMatcapMaterial) {
  15313. refreshUniformsCommon(uniforms, material);
  15314. refreshUniformsMatcap(uniforms, material);
  15315. } else if (material.isMeshDepthMaterial) {
  15316. refreshUniformsCommon(uniforms, material);
  15317. } else if (material.isMeshDistanceMaterial) {
  15318. refreshUniformsCommon(uniforms, material);
  15319. refreshUniformsDistance(uniforms, material);
  15320. } else if (material.isMeshNormalMaterial) {
  15321. refreshUniformsCommon(uniforms, material);
  15322. } else if (material.isLineBasicMaterial) {
  15323. refreshUniformsLine(uniforms, material);
  15324. if (material.isLineDashedMaterial) {
  15325. refreshUniformsDash(uniforms, material);
  15326. }
  15327. } else if (material.isPointsMaterial) {
  15328. refreshUniformsPoints(uniforms, material, pixelRatio, height);
  15329. } else if (material.isSpriteMaterial) {
  15330. refreshUniformsSprites(uniforms, material);
  15331. } else if (material.isShadowMaterial) {
  15332. uniforms.color.value.copy(material.color);
  15333. uniforms.opacity.value = material.opacity;
  15334. } else if (material.isShaderMaterial) {
  15335. material.uniformsNeedUpdate = false; // #15581
  15336. }
  15337. }
  15338. function refreshUniformsCommon(uniforms, material) {
  15339. uniforms.opacity.value = material.opacity;
  15340. if (material.color) {
  15341. uniforms.diffuse.value.copy(material.color);
  15342. }
  15343. if (material.emissive) {
  15344. uniforms.emissive.value.copy(material.emissive).multiplyScalar(material.emissiveIntensity);
  15345. }
  15346. if (material.map) {
  15347. uniforms.map.value = material.map;
  15348. }
  15349. if (material.alphaMap) {
  15350. uniforms.alphaMap.value = material.alphaMap;
  15351. }
  15352. if (material.bumpMap) {
  15353. uniforms.bumpMap.value = material.bumpMap;
  15354. uniforms.bumpScale.value = material.bumpScale;
  15355. if (material.side === BackSide) uniforms.bumpScale.value *= -1;
  15356. }
  15357. if (material.displacementMap) {
  15358. uniforms.displacementMap.value = material.displacementMap;
  15359. uniforms.displacementScale.value = material.displacementScale;
  15360. uniforms.displacementBias.value = material.displacementBias;
  15361. }
  15362. if (material.emissiveMap) {
  15363. uniforms.emissiveMap.value = material.emissiveMap;
  15364. }
  15365. if (material.normalMap) {
  15366. uniforms.normalMap.value = material.normalMap;
  15367. uniforms.normalScale.value.copy(material.normalScale);
  15368. if (material.side === BackSide) uniforms.normalScale.value.negate();
  15369. }
  15370. if (material.specularMap) {
  15371. uniforms.specularMap.value = material.specularMap;
  15372. }
  15373. if (material.alphaTest > 0) {
  15374. uniforms.alphaTest.value = material.alphaTest;
  15375. }
  15376. const envMap = properties.get(material).envMap;
  15377. if (envMap) {
  15378. uniforms.envMap.value = envMap;
  15379. uniforms.flipEnvMap.value = envMap.isCubeTexture && envMap.isRenderTargetTexture === false ? -1 : 1;
  15380. uniforms.reflectivity.value = material.reflectivity;
  15381. uniforms.ior.value = material.ior;
  15382. uniforms.refractionRatio.value = material.refractionRatio;
  15383. }
  15384. if (material.lightMap) {
  15385. uniforms.lightMap.value = material.lightMap; // artist-friendly light intensity scaling factor
  15386. const scaleFactor = renderer.physicallyCorrectLights !== true ? Math.PI : 1;
  15387. uniforms.lightMapIntensity.value = material.lightMapIntensity * scaleFactor;
  15388. }
  15389. if (material.aoMap) {
  15390. uniforms.aoMap.value = material.aoMap;
  15391. uniforms.aoMapIntensity.value = material.aoMapIntensity;
  15392. } // uv repeat and offset setting priorities
  15393. // 1. color map
  15394. // 2. specular map
  15395. // 3. displacementMap map
  15396. // 4. normal map
  15397. // 5. bump map
  15398. // 6. roughnessMap map
  15399. // 7. metalnessMap map
  15400. // 8. alphaMap map
  15401. // 9. emissiveMap map
  15402. // 10. clearcoat map
  15403. // 11. clearcoat normal map
  15404. // 12. clearcoat roughnessMap map
  15405. // 13. specular intensity map
  15406. // 14. specular tint map
  15407. // 15. transmission map
  15408. // 16. thickness map
  15409. let uvScaleMap;
  15410. if (material.map) {
  15411. uvScaleMap = material.map;
  15412. } else if (material.specularMap) {
  15413. uvScaleMap = material.specularMap;
  15414. } else if (material.displacementMap) {
  15415. uvScaleMap = material.displacementMap;
  15416. } else if (material.normalMap) {
  15417. uvScaleMap = material.normalMap;
  15418. } else if (material.bumpMap) {
  15419. uvScaleMap = material.bumpMap;
  15420. } else if (material.roughnessMap) {
  15421. uvScaleMap = material.roughnessMap;
  15422. } else if (material.metalnessMap) {
  15423. uvScaleMap = material.metalnessMap;
  15424. } else if (material.alphaMap) {
  15425. uvScaleMap = material.alphaMap;
  15426. } else if (material.emissiveMap) {
  15427. uvScaleMap = material.emissiveMap;
  15428. } else if (material.clearcoatMap) {
  15429. uvScaleMap = material.clearcoatMap;
  15430. } else if (material.clearcoatNormalMap) {
  15431. uvScaleMap = material.clearcoatNormalMap;
  15432. } else if (material.clearcoatRoughnessMap) {
  15433. uvScaleMap = material.clearcoatRoughnessMap;
  15434. } else if (material.specularIntensityMap) {
  15435. uvScaleMap = material.specularIntensityMap;
  15436. } else if (material.specularColorMap) {
  15437. uvScaleMap = material.specularColorMap;
  15438. } else if (material.transmissionMap) {
  15439. uvScaleMap = material.transmissionMap;
  15440. } else if (material.thicknessMap) {
  15441. uvScaleMap = material.thicknessMap;
  15442. } else if (material.sheenColorMap) {
  15443. uvScaleMap = material.sheenColorMap;
  15444. } else if (material.sheenRoughnessMap) {
  15445. uvScaleMap = material.sheenRoughnessMap;
  15446. }
  15447. if (uvScaleMap !== undefined) {
  15448. // backwards compatibility
  15449. if (uvScaleMap.isWebGLRenderTarget) {
  15450. uvScaleMap = uvScaleMap.texture;
  15451. }
  15452. if (uvScaleMap.matrixAutoUpdate === true) {
  15453. uvScaleMap.updateMatrix();
  15454. }
  15455. uniforms.uvTransform.value.copy(uvScaleMap.matrix);
  15456. } // uv repeat and offset setting priorities for uv2
  15457. // 1. ao map
  15458. // 2. light map
  15459. let uv2ScaleMap;
  15460. if (material.aoMap) {
  15461. uv2ScaleMap = material.aoMap;
  15462. } else if (material.lightMap) {
  15463. uv2ScaleMap = material.lightMap;
  15464. }
  15465. if (uv2ScaleMap !== undefined) {
  15466. // backwards compatibility
  15467. if (uv2ScaleMap.isWebGLRenderTarget) {
  15468. uv2ScaleMap = uv2ScaleMap.texture;
  15469. }
  15470. if (uv2ScaleMap.matrixAutoUpdate === true) {
  15471. uv2ScaleMap.updateMatrix();
  15472. }
  15473. uniforms.uv2Transform.value.copy(uv2ScaleMap.matrix);
  15474. }
  15475. }
  15476. function refreshUniformsLine(uniforms, material) {
  15477. uniforms.diffuse.value.copy(material.color);
  15478. uniforms.opacity.value = material.opacity;
  15479. }
  15480. function refreshUniformsDash(uniforms, material) {
  15481. uniforms.dashSize.value = material.dashSize;
  15482. uniforms.totalSize.value = material.dashSize + material.gapSize;
  15483. uniforms.scale.value = material.scale;
  15484. }
  15485. function refreshUniformsPoints(uniforms, material, pixelRatio, height) {
  15486. uniforms.diffuse.value.copy(material.color);
  15487. uniforms.opacity.value = material.opacity;
  15488. uniforms.size.value = material.size * pixelRatio;
  15489. uniforms.scale.value = height * 0.5;
  15490. if (material.map) {
  15491. uniforms.map.value = material.map;
  15492. }
  15493. if (material.alphaMap) {
  15494. uniforms.alphaMap.value = material.alphaMap;
  15495. }
  15496. if (material.alphaTest > 0) {
  15497. uniforms.alphaTest.value = material.alphaTest;
  15498. } // uv repeat and offset setting priorities
  15499. // 1. color map
  15500. // 2. alpha map
  15501. let uvScaleMap;
  15502. if (material.map) {
  15503. uvScaleMap = material.map;
  15504. } else if (material.alphaMap) {
  15505. uvScaleMap = material.alphaMap;
  15506. }
  15507. if (uvScaleMap !== undefined) {
  15508. if (uvScaleMap.matrixAutoUpdate === true) {
  15509. uvScaleMap.updateMatrix();
  15510. }
  15511. uniforms.uvTransform.value.copy(uvScaleMap.matrix);
  15512. }
  15513. }
  15514. function refreshUniformsSprites(uniforms, material) {
  15515. uniforms.diffuse.value.copy(material.color);
  15516. uniforms.opacity.value = material.opacity;
  15517. uniforms.rotation.value = material.rotation;
  15518. if (material.map) {
  15519. uniforms.map.value = material.map;
  15520. }
  15521. if (material.alphaMap) {
  15522. uniforms.alphaMap.value = material.alphaMap;
  15523. }
  15524. if (material.alphaTest > 0) {
  15525. uniforms.alphaTest.value = material.alphaTest;
  15526. } // uv repeat and offset setting priorities
  15527. // 1. color map
  15528. // 2. alpha map
  15529. let uvScaleMap;
  15530. if (material.map) {
  15531. uvScaleMap = material.map;
  15532. } else if (material.alphaMap) {
  15533. uvScaleMap = material.alphaMap;
  15534. }
  15535. if (uvScaleMap !== undefined) {
  15536. if (uvScaleMap.matrixAutoUpdate === true) {
  15537. uvScaleMap.updateMatrix();
  15538. }
  15539. uniforms.uvTransform.value.copy(uvScaleMap.matrix);
  15540. }
  15541. }
  15542. function refreshUniformsPhong(uniforms, material) {
  15543. uniforms.specular.value.copy(material.specular);
  15544. uniforms.shininess.value = Math.max(material.shininess, 1e-4); // to prevent pow( 0.0, 0.0 )
  15545. }
  15546. function refreshUniformsToon(uniforms, material) {
  15547. if (material.gradientMap) {
  15548. uniforms.gradientMap.value = material.gradientMap;
  15549. }
  15550. }
  15551. function refreshUniformsStandard(uniforms, material) {
  15552. uniforms.roughness.value = material.roughness;
  15553. uniforms.metalness.value = material.metalness;
  15554. if (material.roughnessMap) {
  15555. uniforms.roughnessMap.value = material.roughnessMap;
  15556. }
  15557. if (material.metalnessMap) {
  15558. uniforms.metalnessMap.value = material.metalnessMap;
  15559. }
  15560. const envMap = properties.get(material).envMap;
  15561. if (envMap) {
  15562. //uniforms.envMap.value = material.envMap; // part of uniforms common
  15563. uniforms.envMapIntensity.value = material.envMapIntensity;
  15564. }
  15565. }
  15566. function refreshUniformsPhysical(uniforms, material, transmissionRenderTarget) {
  15567. uniforms.ior.value = material.ior; // also part of uniforms common
  15568. if (material.sheen > 0) {
  15569. uniforms.sheenColor.value.copy(material.sheenColor).multiplyScalar(material.sheen);
  15570. uniforms.sheenRoughness.value = material.sheenRoughness;
  15571. if (material.sheenColorMap) {
  15572. uniforms.sheenColorMap.value = material.sheenColorMap;
  15573. }
  15574. if (material.sheenRoughnessMap) {
  15575. uniforms.sheenRoughnessMap.value = material.sheenRoughnessMap;
  15576. }
  15577. }
  15578. if (material.clearcoat > 0) {
  15579. uniforms.clearcoat.value = material.clearcoat;
  15580. uniforms.clearcoatRoughness.value = material.clearcoatRoughness;
  15581. if (material.clearcoatMap) {
  15582. uniforms.clearcoatMap.value = material.clearcoatMap;
  15583. }
  15584. if (material.clearcoatRoughnessMap) {
  15585. uniforms.clearcoatRoughnessMap.value = material.clearcoatRoughnessMap;
  15586. }
  15587. if (material.clearcoatNormalMap) {
  15588. uniforms.clearcoatNormalScale.value.copy(material.clearcoatNormalScale);
  15589. uniforms.clearcoatNormalMap.value = material.clearcoatNormalMap;
  15590. if (material.side === BackSide) {
  15591. uniforms.clearcoatNormalScale.value.negate();
  15592. }
  15593. }
  15594. }
  15595. if (material.transmission > 0) {
  15596. uniforms.transmission.value = material.transmission;
  15597. uniforms.transmissionSamplerMap.value = transmissionRenderTarget.texture;
  15598. uniforms.transmissionSamplerSize.value.set(transmissionRenderTarget.width, transmissionRenderTarget.height);
  15599. if (material.transmissionMap) {
  15600. uniforms.transmissionMap.value = material.transmissionMap;
  15601. }
  15602. uniforms.thickness.value = material.thickness;
  15603. if (material.thicknessMap) {
  15604. uniforms.thicknessMap.value = material.thicknessMap;
  15605. }
  15606. uniforms.attenuationDistance.value = material.attenuationDistance;
  15607. uniforms.attenuationColor.value.copy(material.attenuationColor);
  15608. }
  15609. uniforms.specularIntensity.value = material.specularIntensity;
  15610. uniforms.specularColor.value.copy(material.specularColor);
  15611. if (material.specularIntensityMap) {
  15612. uniforms.specularIntensityMap.value = material.specularIntensityMap;
  15613. }
  15614. if (material.specularColorMap) {
  15615. uniforms.specularColorMap.value = material.specularColorMap;
  15616. }
  15617. }
  15618. function refreshUniformsMatcap(uniforms, material) {
  15619. if (material.matcap) {
  15620. uniforms.matcap.value = material.matcap;
  15621. }
  15622. }
  15623. function refreshUniformsDistance(uniforms, material) {
  15624. uniforms.referencePosition.value.copy(material.referencePosition);
  15625. uniforms.nearDistance.value = material.nearDistance;
  15626. uniforms.farDistance.value = material.farDistance;
  15627. }
  15628. return {
  15629. refreshFogUniforms: refreshFogUniforms,
  15630. refreshMaterialUniforms: refreshMaterialUniforms
  15631. };
  15632. }
  15633. function createCanvasElement() {
  15634. const canvas = createElementNS('canvas');
  15635. canvas.style.display = 'block';
  15636. return canvas;
  15637. }
  15638. function WebGLRenderer(parameters = {}) {
  15639. this.isWebGLRenderer = true;
  15640. const _canvas = parameters.canvas !== undefined ? parameters.canvas : createCanvasElement(),
  15641. _context = parameters.context !== undefined ? parameters.context : null,
  15642. _depth = parameters.depth !== undefined ? parameters.depth : true,
  15643. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  15644. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  15645. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  15646. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false,
  15647. _powerPreference = parameters.powerPreference !== undefined ? parameters.powerPreference : 'default',
  15648. _failIfMajorPerformanceCaveat = parameters.failIfMajorPerformanceCaveat !== undefined ? parameters.failIfMajorPerformanceCaveat : false;
  15649. let _alpha;
  15650. if (_context !== null) {
  15651. _alpha = _context.getContextAttributes().alpha;
  15652. } else {
  15653. _alpha = parameters.alpha !== undefined ? parameters.alpha : false;
  15654. }
  15655. let currentRenderList = null;
  15656. let currentRenderState = null; // render() can be called from within a callback triggered by another render.
  15657. // We track this so that the nested render call gets its list and state isolated from the parent render call.
  15658. const renderListStack = [];
  15659. const renderStateStack = []; // public properties
  15660. this.domElement = _canvas; // Debug configuration container
  15661. this.debug = {
  15662. /**
  15663. * Enables error checking and reporting when shader programs are being compiled
  15664. * @type {boolean}
  15665. */
  15666. checkShaderErrors: true
  15667. }; // clearing
  15668. this.autoClear = true;
  15669. this.autoClearColor = true;
  15670. this.autoClearDepth = true;
  15671. this.autoClearStencil = true; // scene graph
  15672. this.sortObjects = true; // user-defined clipping
  15673. this.clippingPlanes = [];
  15674. this.localClippingEnabled = false; // physically based shading
  15675. this.outputEncoding = LinearEncoding; // physical lights
  15676. this.physicallyCorrectLights = false; // tone mapping
  15677. this.toneMapping = NoToneMapping;
  15678. this.toneMappingExposure = 1.0; //
  15679. Object.defineProperties(this, {
  15680. // @deprecated since r136, 0e21088102b4de7e0a0a33140620b7a3424b9e6d
  15681. gammaFactor: {
  15682. get: function () {
  15683. console.warn('THREE.WebGLRenderer: .gammaFactor has been removed.');
  15684. return 2;
  15685. },
  15686. set: function () {
  15687. console.warn('THREE.WebGLRenderer: .gammaFactor has been removed.');
  15688. }
  15689. }
  15690. }); // internal properties
  15691. const _this = this;
  15692. let _isContextLost = false; // internal state cache
  15693. let _currentActiveCubeFace = 0;
  15694. let _currentActiveMipmapLevel = 0;
  15695. let _currentRenderTarget = null;
  15696. let _currentMaterialId = -1;
  15697. let _currentCamera = null;
  15698. const _currentViewport = new Vector4();
  15699. const _currentScissor = new Vector4();
  15700. let _currentScissorTest = null; //
  15701. let _width = _canvas.width;
  15702. let _height = _canvas.height;
  15703. let _pixelRatio = 1;
  15704. let _opaqueSort = null;
  15705. let _transparentSort = null;
  15706. const _viewport = new Vector4(0, 0, _width, _height);
  15707. const _scissor = new Vector4(0, 0, _width, _height);
  15708. let _scissorTest = false; // frustum
  15709. const _frustum = new Frustum(); // clipping
  15710. let _clippingEnabled = false;
  15711. let _localClippingEnabled = false; // transmission
  15712. let _transmissionRenderTarget = null; // camera matrices cache
  15713. const _projScreenMatrix = new Matrix4();
  15714. const _vector2 = new Vector2();
  15715. const _vector3 = new Vector3();
  15716. const _emptyScene = {
  15717. background: null,
  15718. fog: null,
  15719. environment: null,
  15720. overrideMaterial: null,
  15721. isScene: true
  15722. };
  15723. function getTargetPixelRatio() {
  15724. return _currentRenderTarget === null ? _pixelRatio : 1;
  15725. } // initialize
  15726. let _gl = _context;
  15727. function getContext(contextNames, contextAttributes) {
  15728. for (let i = 0; i < contextNames.length; i++) {
  15729. const contextName = contextNames[i];
  15730. const context = _canvas.getContext(contextName, contextAttributes);
  15731. if (context !== null) return context;
  15732. }
  15733. return null;
  15734. }
  15735. try {
  15736. const contextAttributes = {
  15737. alpha: true,
  15738. depth: _depth,
  15739. stencil: _stencil,
  15740. antialias: _antialias,
  15741. premultipliedAlpha: _premultipliedAlpha,
  15742. preserveDrawingBuffer: _preserveDrawingBuffer,
  15743. powerPreference: _powerPreference,
  15744. failIfMajorPerformanceCaveat: _failIfMajorPerformanceCaveat
  15745. }; // OffscreenCanvas does not have setAttribute, see #22811
  15746. if ('setAttribute' in _canvas) _canvas.setAttribute('data-engine', `three.js r${REVISION}`); // event listeners must be registered before WebGL context is created, see #12753
  15747. _canvas.addEventListener('webglcontextlost', onContextLost, false);
  15748. _canvas.addEventListener('webglcontextrestored', onContextRestore, false);
  15749. _canvas.addEventListener('webglcontextcreationerror', onContextCreationError, false);
  15750. if (_gl === null) {
  15751. const contextNames = ['webgl2', 'webgl', 'experimental-webgl'];
  15752. if (_this.isWebGL1Renderer === true) {
  15753. contextNames.shift();
  15754. }
  15755. _gl = getContext(contextNames, contextAttributes);
  15756. if (_gl === null) {
  15757. if (getContext(contextNames)) {
  15758. throw new Error('Error creating WebGL context with your selected attributes.');
  15759. } else {
  15760. throw new Error('Error creating WebGL context.');
  15761. }
  15762. }
  15763. } // Some experimental-webgl implementations do not have getShaderPrecisionFormat
  15764. if (_gl.getShaderPrecisionFormat === undefined) {
  15765. _gl.getShaderPrecisionFormat = function () {
  15766. return {
  15767. 'rangeMin': 1,
  15768. 'rangeMax': 1,
  15769. 'precision': 1
  15770. };
  15771. };
  15772. }
  15773. } catch (error) {
  15774. console.error('THREE.WebGLRenderer: ' + error.message);
  15775. throw error;
  15776. }
  15777. let extensions, capabilities, state, info;
  15778. let properties, textures, cubemaps, cubeuvmaps, attributes, geometries, objects;
  15779. let programCache, materials, renderLists, renderStates, clipping, shadowMap;
  15780. let background, morphtargets, bufferRenderer, indexedBufferRenderer;
  15781. let utils, bindingStates;
  15782. function initGLContext() {
  15783. extensions = new WebGLExtensions(_gl);
  15784. capabilities = new WebGLCapabilities(_gl, extensions, parameters);
  15785. extensions.init(capabilities);
  15786. utils = new WebGLUtils(_gl, extensions, capabilities);
  15787. state = new WebGLState(_gl, extensions, capabilities);
  15788. info = new WebGLInfo(_gl);
  15789. properties = new WebGLProperties();
  15790. textures = new WebGLTextures(_gl, extensions, state, properties, capabilities, utils, info);
  15791. cubemaps = new WebGLCubeMaps(_this);
  15792. cubeuvmaps = new WebGLCubeUVMaps(_this);
  15793. attributes = new WebGLAttributes(_gl, capabilities);
  15794. bindingStates = new WebGLBindingStates(_gl, extensions, attributes, capabilities);
  15795. geometries = new WebGLGeometries(_gl, attributes, info, bindingStates);
  15796. objects = new WebGLObjects(_gl, geometries, attributes, info);
  15797. morphtargets = new WebGLMorphtargets(_gl, capabilities, textures);
  15798. clipping = new WebGLClipping(properties);
  15799. programCache = new WebGLPrograms(_this, cubemaps, cubeuvmaps, extensions, capabilities, bindingStates, clipping);
  15800. materials = new WebGLMaterials(_this, properties);
  15801. renderLists = new WebGLRenderLists();
  15802. renderStates = new WebGLRenderStates(extensions, capabilities);
  15803. background = new WebGLBackground(_this, cubemaps, state, objects, _alpha, _premultipliedAlpha);
  15804. shadowMap = new WebGLShadowMap(_this, objects, capabilities);
  15805. bufferRenderer = new WebGLBufferRenderer(_gl, extensions, info, capabilities);
  15806. indexedBufferRenderer = new WebGLIndexedBufferRenderer(_gl, extensions, info, capabilities);
  15807. info.programs = programCache.programs;
  15808. _this.capabilities = capabilities;
  15809. _this.extensions = extensions;
  15810. _this.properties = properties;
  15811. _this.renderLists = renderLists;
  15812. _this.shadowMap = shadowMap;
  15813. _this.state = state;
  15814. _this.info = info;
  15815. }
  15816. initGLContext(); // xr
  15817. const xr = new WebXRManager(_this, _gl);
  15818. this.xr = xr; // API
  15819. this.getContext = function () {
  15820. return _gl;
  15821. };
  15822. this.getContextAttributes = function () {
  15823. return _gl.getContextAttributes();
  15824. };
  15825. this.forceContextLoss = function () {
  15826. const extension = extensions.get('WEBGL_lose_context');
  15827. if (extension) extension.loseContext();
  15828. };
  15829. this.forceContextRestore = function () {
  15830. const extension = extensions.get('WEBGL_lose_context');
  15831. if (extension) extension.restoreContext();
  15832. };
  15833. this.getPixelRatio = function () {
  15834. return _pixelRatio;
  15835. };
  15836. this.setPixelRatio = function (value) {
  15837. if (value === undefined) return;
  15838. _pixelRatio = value;
  15839. this.setSize(_width, _height, false);
  15840. };
  15841. this.getSize = function (target) {
  15842. return target.set(_width, _height);
  15843. };
  15844. this.setSize = function (width, height, updateStyle) {
  15845. if (xr.isPresenting) {
  15846. console.warn('THREE.WebGLRenderer: Can\'t change size while VR device is presenting.');
  15847. return;
  15848. }
  15849. _width = width;
  15850. _height = height;
  15851. _canvas.width = Math.floor(width * _pixelRatio);
  15852. _canvas.height = Math.floor(height * _pixelRatio);
  15853. if (updateStyle !== false) {
  15854. _canvas.style.width = width + 'px';
  15855. _canvas.style.height = height + 'px';
  15856. }
  15857. this.setViewport(0, 0, width, height);
  15858. };
  15859. this.getDrawingBufferSize = function (target) {
  15860. return target.set(_width * _pixelRatio, _height * _pixelRatio).floor();
  15861. };
  15862. this.setDrawingBufferSize = function (width, height, pixelRatio) {
  15863. _width = width;
  15864. _height = height;
  15865. _pixelRatio = pixelRatio;
  15866. _canvas.width = Math.floor(width * pixelRatio);
  15867. _canvas.height = Math.floor(height * pixelRatio);
  15868. this.setViewport(0, 0, width, height);
  15869. };
  15870. this.getCurrentViewport = function (target) {
  15871. return target.copy(_currentViewport);
  15872. };
  15873. this.getViewport = function (target) {
  15874. return target.copy(_viewport);
  15875. };
  15876. this.setViewport = function (x, y, width, height) {
  15877. if (x.isVector4) {
  15878. _viewport.set(x.x, x.y, x.z, x.w);
  15879. } else {
  15880. _viewport.set(x, y, width, height);
  15881. }
  15882. state.viewport(_currentViewport.copy(_viewport).multiplyScalar(_pixelRatio).floor());
  15883. };
  15884. this.getScissor = function (target) {
  15885. return target.copy(_scissor);
  15886. };
  15887. this.setScissor = function (x, y, width, height) {
  15888. if (x.isVector4) {
  15889. _scissor.set(x.x, x.y, x.z, x.w);
  15890. } else {
  15891. _scissor.set(x, y, width, height);
  15892. }
  15893. state.scissor(_currentScissor.copy(_scissor).multiplyScalar(_pixelRatio).floor());
  15894. };
  15895. this.getScissorTest = function () {
  15896. return _scissorTest;
  15897. };
  15898. this.setScissorTest = function (boolean) {
  15899. state.setScissorTest(_scissorTest = boolean);
  15900. };
  15901. this.setOpaqueSort = function (method) {
  15902. _opaqueSort = method;
  15903. };
  15904. this.setTransparentSort = function (method) {
  15905. _transparentSort = method;
  15906. }; // Clearing
  15907. this.getClearColor = function (target) {
  15908. return target.copy(background.getClearColor());
  15909. };
  15910. this.setClearColor = function () {
  15911. background.setClearColor.apply(background, arguments);
  15912. };
  15913. this.getClearAlpha = function () {
  15914. return background.getClearAlpha();
  15915. };
  15916. this.setClearAlpha = function () {
  15917. background.setClearAlpha.apply(background, arguments);
  15918. };
  15919. this.clear = function (color = true, depth = true, stencil = true) {
  15920. let bits = 0;
  15921. if (color) bits |= _gl.COLOR_BUFFER_BIT;
  15922. if (depth) bits |= _gl.DEPTH_BUFFER_BIT;
  15923. if (stencil) bits |= _gl.STENCIL_BUFFER_BIT;
  15924. _gl.clear(bits);
  15925. };
  15926. this.clearColor = function () {
  15927. this.clear(true, false, false);
  15928. };
  15929. this.clearDepth = function () {
  15930. this.clear(false, true, false);
  15931. };
  15932. this.clearStencil = function () {
  15933. this.clear(false, false, true);
  15934. }; //
  15935. this.dispose = function () {
  15936. _canvas.removeEventListener('webglcontextlost', onContextLost, false);
  15937. _canvas.removeEventListener('webglcontextrestored', onContextRestore, false);
  15938. _canvas.removeEventListener('webglcontextcreationerror', onContextCreationError, false);
  15939. renderLists.dispose();
  15940. renderStates.dispose();
  15941. properties.dispose();
  15942. cubemaps.dispose();
  15943. cubeuvmaps.dispose();
  15944. objects.dispose();
  15945. bindingStates.dispose();
  15946. programCache.dispose();
  15947. xr.dispose();
  15948. xr.removeEventListener('sessionstart', onXRSessionStart);
  15949. xr.removeEventListener('sessionend', onXRSessionEnd);
  15950. if (_transmissionRenderTarget) {
  15951. _transmissionRenderTarget.dispose();
  15952. _transmissionRenderTarget = null;
  15953. }
  15954. animation.stop();
  15955. }; // Events
  15956. function onContextLost(event) {
  15957. event.preventDefault();
  15958. console.log('THREE.WebGLRenderer: Context Lost.');
  15959. _isContextLost = true;
  15960. }
  15961. function
  15962. /* event */
  15963. onContextRestore() {
  15964. console.log('THREE.WebGLRenderer: Context Restored.');
  15965. _isContextLost = false;
  15966. const infoAutoReset = info.autoReset;
  15967. const shadowMapEnabled = shadowMap.enabled;
  15968. const shadowMapAutoUpdate = shadowMap.autoUpdate;
  15969. const shadowMapNeedsUpdate = shadowMap.needsUpdate;
  15970. const shadowMapType = shadowMap.type;
  15971. initGLContext();
  15972. info.autoReset = infoAutoReset;
  15973. shadowMap.enabled = shadowMapEnabled;
  15974. shadowMap.autoUpdate = shadowMapAutoUpdate;
  15975. shadowMap.needsUpdate = shadowMapNeedsUpdate;
  15976. shadowMap.type = shadowMapType;
  15977. }
  15978. function onContextCreationError(event) {
  15979. console.error('THREE.WebGLRenderer: A WebGL context could not be created. Reason: ', event.statusMessage);
  15980. }
  15981. function onMaterialDispose(event) {
  15982. const material = event.target;
  15983. material.removeEventListener('dispose', onMaterialDispose);
  15984. deallocateMaterial(material);
  15985. } // Buffer deallocation
  15986. function deallocateMaterial(material) {
  15987. releaseMaterialProgramReferences(material);
  15988. properties.remove(material);
  15989. }
  15990. function releaseMaterialProgramReferences(material) {
  15991. const programs = properties.get(material).programs;
  15992. if (programs !== undefined) {
  15993. programs.forEach(function (program) {
  15994. programCache.releaseProgram(program);
  15995. });
  15996. if (material.isShaderMaterial) {
  15997. programCache.releaseShaderCache(material);
  15998. }
  15999. }
  16000. } // Buffer rendering
  16001. this.renderBufferDirect = function (camera, scene, geometry, material, object, group) {
  16002. if (scene === null) scene = _emptyScene; // renderBufferDirect second parameter used to be fog (could be null)
  16003. const frontFaceCW = object.isMesh && object.matrixWorld.determinant() < 0;
  16004. const program = setProgram(camera, scene, geometry, material, object);
  16005. state.setMaterial(material, frontFaceCW); //
  16006. let index = geometry.index;
  16007. const position = geometry.attributes.position; //
  16008. if (index === null) {
  16009. if (position === undefined || position.count === 0) return;
  16010. } else if (index.count === 0) {
  16011. return;
  16012. } //
  16013. let rangeFactor = 1;
  16014. if (material.wireframe === true) {
  16015. index = geometries.getWireframeAttribute(geometry);
  16016. rangeFactor = 2;
  16017. }
  16018. bindingStates.setup(object, material, program, geometry, index);
  16019. let attribute;
  16020. let renderer = bufferRenderer;
  16021. if (index !== null) {
  16022. attribute = attributes.get(index);
  16023. renderer = indexedBufferRenderer;
  16024. renderer.setIndex(attribute);
  16025. } //
  16026. const dataCount = index !== null ? index.count : position.count;
  16027. const rangeStart = geometry.drawRange.start * rangeFactor;
  16028. const rangeCount = geometry.drawRange.count * rangeFactor;
  16029. const groupStart = group !== null ? group.start * rangeFactor : 0;
  16030. const groupCount = group !== null ? group.count * rangeFactor : Infinity;
  16031. const drawStart = Math.max(rangeStart, groupStart);
  16032. const drawEnd = Math.min(dataCount, rangeStart + rangeCount, groupStart + groupCount) - 1;
  16033. const drawCount = Math.max(0, drawEnd - drawStart + 1);
  16034. if (drawCount === 0) return; //
  16035. if (object.isMesh) {
  16036. if (material.wireframe === true) {
  16037. state.setLineWidth(material.wireframeLinewidth * getTargetPixelRatio());
  16038. renderer.setMode(_gl.LINES);
  16039. } else {
  16040. renderer.setMode(_gl.TRIANGLES);
  16041. }
  16042. } else if (object.isLine) {
  16043. let lineWidth = material.linewidth;
  16044. if (lineWidth === undefined) lineWidth = 1; // Not using Line*Material
  16045. state.setLineWidth(lineWidth * getTargetPixelRatio());
  16046. if (object.isLineSegments) {
  16047. renderer.setMode(_gl.LINES);
  16048. } else if (object.isLineLoop) {
  16049. renderer.setMode(_gl.LINE_LOOP);
  16050. } else {
  16051. renderer.setMode(_gl.LINE_STRIP);
  16052. }
  16053. } else if (object.isPoints) {
  16054. renderer.setMode(_gl.POINTS);
  16055. } else if (object.isSprite) {
  16056. renderer.setMode(_gl.TRIANGLES);
  16057. }
  16058. if (object.isInstancedMesh) {
  16059. renderer.renderInstances(drawStart, drawCount, object.count);
  16060. } else if (geometry.isInstancedBufferGeometry) {
  16061. const instanceCount = Math.min(geometry.instanceCount, geometry._maxInstanceCount);
  16062. renderer.renderInstances(drawStart, drawCount, instanceCount);
  16063. } else {
  16064. renderer.render(drawStart, drawCount);
  16065. }
  16066. }; // Compile
  16067. this.compile = function (scene, camera) {
  16068. currentRenderState = renderStates.get(scene);
  16069. currentRenderState.init();
  16070. renderStateStack.push(currentRenderState);
  16071. scene.traverseVisible(function (object) {
  16072. if (object.isLight && object.layers.test(camera.layers)) {
  16073. currentRenderState.pushLight(object);
  16074. if (object.castShadow) {
  16075. currentRenderState.pushShadow(object);
  16076. }
  16077. }
  16078. });
  16079. currentRenderState.setupLights(_this.physicallyCorrectLights);
  16080. scene.traverse(function (object) {
  16081. const material = object.material;
  16082. if (material) {
  16083. if (Array.isArray(material)) {
  16084. for (let i = 0; i < material.length; i++) {
  16085. const material2 = material[i];
  16086. getProgram(material2, scene, object);
  16087. }
  16088. } else {
  16089. getProgram(material, scene, object);
  16090. }
  16091. }
  16092. });
  16093. renderStateStack.pop();
  16094. currentRenderState = null;
  16095. }; // Animation Loop
  16096. let onAnimationFrameCallback = null;
  16097. function onAnimationFrame(time) {
  16098. if (onAnimationFrameCallback) onAnimationFrameCallback(time);
  16099. }
  16100. function onXRSessionStart() {
  16101. animation.stop();
  16102. }
  16103. function onXRSessionEnd() {
  16104. animation.start();
  16105. }
  16106. const animation = new WebGLAnimation();
  16107. animation.setAnimationLoop(onAnimationFrame);
  16108. if (typeof self !== 'undefined') animation.setContext(self);
  16109. this.setAnimationLoop = function (callback) {
  16110. onAnimationFrameCallback = callback;
  16111. xr.setAnimationLoop(callback);
  16112. callback === null ? animation.stop() : animation.start();
  16113. };
  16114. xr.addEventListener('sessionstart', onXRSessionStart);
  16115. xr.addEventListener('sessionend', onXRSessionEnd); // Rendering
  16116. this.render = function (scene, camera) {
  16117. if (camera !== undefined && camera.isCamera !== true) {
  16118. console.error('THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.');
  16119. return;
  16120. }
  16121. if (_isContextLost === true) return; // update scene graph
  16122. if (scene.autoUpdate === true) scene.updateMatrixWorld(); // update camera matrices and frustum
  16123. if (camera.parent === null) camera.updateMatrixWorld();
  16124. if (xr.enabled === true && xr.isPresenting === true) {
  16125. if (xr.cameraAutoUpdate === true) xr.updateCamera(camera);
  16126. camera = xr.getCamera(); // use XR camera for rendering
  16127. } //
  16128. if (scene.isScene === true) scene.onBeforeRender(_this, scene, camera, _currentRenderTarget);
  16129. currentRenderState = renderStates.get(scene, renderStateStack.length);
  16130. currentRenderState.init();
  16131. renderStateStack.push(currentRenderState);
  16132. _projScreenMatrix.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse);
  16133. _frustum.setFromProjectionMatrix(_projScreenMatrix);
  16134. _localClippingEnabled = this.localClippingEnabled;
  16135. _clippingEnabled = clipping.init(this.clippingPlanes, _localClippingEnabled, camera);
  16136. currentRenderList = renderLists.get(scene, renderListStack.length);
  16137. currentRenderList.init();
  16138. renderListStack.push(currentRenderList);
  16139. projectObject(scene, camera, 0, _this.sortObjects);
  16140. currentRenderList.finish();
  16141. if (_this.sortObjects === true) {
  16142. currentRenderList.sort(_opaqueSort, _transparentSort);
  16143. } //
  16144. if (_clippingEnabled === true) clipping.beginShadows();
  16145. const shadowsArray = currentRenderState.state.shadowsArray;
  16146. shadowMap.render(shadowsArray, scene, camera);
  16147. if (_clippingEnabled === true) clipping.endShadows(); //
  16148. if (this.info.autoReset === true) this.info.reset(); //
  16149. background.render(currentRenderList, scene); // render scene
  16150. currentRenderState.setupLights(_this.physicallyCorrectLights);
  16151. if (camera.isArrayCamera) {
  16152. const cameras = camera.cameras;
  16153. for (let i = 0, l = cameras.length; i < l; i++) {
  16154. const camera2 = cameras[i];
  16155. renderScene(currentRenderList, scene, camera2, camera2.viewport);
  16156. }
  16157. } else {
  16158. renderScene(currentRenderList, scene, camera);
  16159. } //
  16160. if (_currentRenderTarget !== null) {
  16161. // resolve multisample renderbuffers to a single-sample texture if necessary
  16162. textures.updateMultisampleRenderTarget(_currentRenderTarget); // Generate mipmap if we're using any kind of mipmap filtering
  16163. textures.updateRenderTargetMipmap(_currentRenderTarget);
  16164. } //
  16165. if (scene.isScene === true) scene.onAfterRender(_this, scene, camera); // _gl.finish();
  16166. bindingStates.resetDefaultState();
  16167. _currentMaterialId = -1;
  16168. _currentCamera = null;
  16169. renderStateStack.pop();
  16170. if (renderStateStack.length > 0) {
  16171. currentRenderState = renderStateStack[renderStateStack.length - 1];
  16172. } else {
  16173. currentRenderState = null;
  16174. }
  16175. renderListStack.pop();
  16176. if (renderListStack.length > 0) {
  16177. currentRenderList = renderListStack[renderListStack.length - 1];
  16178. } else {
  16179. currentRenderList = null;
  16180. }
  16181. };
  16182. function projectObject(object, camera, groupOrder, sortObjects) {
  16183. if (object.visible === false) return;
  16184. const visible = object.layers.test(camera.layers);
  16185. if (visible) {
  16186. if (object.isGroup) {
  16187. groupOrder = object.renderOrder;
  16188. } else if (object.isLOD) {
  16189. if (object.autoUpdate === true) object.update(camera);
  16190. } else if (object.isLight) {
  16191. currentRenderState.pushLight(object);
  16192. if (object.castShadow) {
  16193. currentRenderState.pushShadow(object);
  16194. }
  16195. } else if (object.isSprite) {
  16196. if (!object.frustumCulled || _frustum.intersectsSprite(object)) {
  16197. if (sortObjects) {
  16198. _vector3.setFromMatrixPosition(object.matrixWorld).applyMatrix4(_projScreenMatrix);
  16199. }
  16200. const geometry = objects.update(object);
  16201. const material = object.material;
  16202. if (material.visible) {
  16203. currentRenderList.push(object, geometry, material, groupOrder, _vector3.z, null);
  16204. }
  16205. }
  16206. } else if (object.isMesh || object.isLine || object.isPoints) {
  16207. if (object.isSkinnedMesh) {
  16208. // update skeleton only once in a frame
  16209. if (object.skeleton.frame !== info.render.frame) {
  16210. object.skeleton.update();
  16211. object.skeleton.frame = info.render.frame;
  16212. }
  16213. }
  16214. if (!object.frustumCulled || _frustum.intersectsObject(object)) {
  16215. if (sortObjects) {
  16216. _vector3.setFromMatrixPosition(object.matrixWorld).applyMatrix4(_projScreenMatrix);
  16217. }
  16218. const geometry = objects.update(object);
  16219. const material = object.material;
  16220. if (Array.isArray(material)) {
  16221. const groups = geometry.groups;
  16222. for (let i = 0, l = groups.length; i < l; i++) {
  16223. const group = groups[i];
  16224. const groupMaterial = material[group.materialIndex];
  16225. if (groupMaterial && groupMaterial.visible) {
  16226. currentRenderList.push(object, geometry, groupMaterial, groupOrder, _vector3.z, group);
  16227. }
  16228. }
  16229. } else if (material.visible) {
  16230. currentRenderList.push(object, geometry, material, groupOrder, _vector3.z, null);
  16231. }
  16232. }
  16233. }
  16234. }
  16235. const children = object.children;
  16236. for (let i = 0, l = children.length; i < l; i++) {
  16237. projectObject(children[i], camera, groupOrder, sortObjects);
  16238. }
  16239. }
  16240. function renderScene(currentRenderList, scene, camera, viewport) {
  16241. const opaqueObjects = currentRenderList.opaque;
  16242. const transmissiveObjects = currentRenderList.transmissive;
  16243. const transparentObjects = currentRenderList.transparent;
  16244. currentRenderState.setupLightsView(camera);
  16245. if (transmissiveObjects.length > 0) renderTransmissionPass(opaqueObjects, scene, camera);
  16246. if (viewport) state.viewport(_currentViewport.copy(viewport));
  16247. if (opaqueObjects.length > 0) renderObjects(opaqueObjects, scene, camera);
  16248. if (transmissiveObjects.length > 0) renderObjects(transmissiveObjects, scene, camera);
  16249. if (transparentObjects.length > 0) renderObjects(transparentObjects, scene, camera); // Ensure depth buffer writing is enabled so it can be cleared on next render
  16250. state.buffers.depth.setTest(true);
  16251. state.buffers.depth.setMask(true);
  16252. state.buffers.color.setMask(true);
  16253. state.setPolygonOffset(false);
  16254. }
  16255. function renderTransmissionPass(opaqueObjects, scene, camera) {
  16256. const isWebGL2 = capabilities.isWebGL2;
  16257. if (_transmissionRenderTarget === null) {
  16258. _transmissionRenderTarget = new WebGLRenderTarget(1, 1, {
  16259. generateMipmaps: true,
  16260. type: extensions.has('EXT_color_buffer_half_float') ? HalfFloatType : UnsignedByteType,
  16261. minFilter: LinearMipmapLinearFilter,
  16262. samples: isWebGL2 && _antialias === true ? 4 : 0
  16263. });
  16264. }
  16265. _this.getDrawingBufferSize(_vector2);
  16266. if (isWebGL2) {
  16267. _transmissionRenderTarget.setSize(_vector2.x, _vector2.y);
  16268. } else {
  16269. _transmissionRenderTarget.setSize(floorPowerOfTwo(_vector2.x), floorPowerOfTwo(_vector2.y));
  16270. } //
  16271. const currentRenderTarget = _this.getRenderTarget();
  16272. _this.setRenderTarget(_transmissionRenderTarget);
  16273. _this.clear(); // Turn off the features which can affect the frag color for opaque objects pass.
  16274. // Otherwise they are applied twice in opaque objects pass and transmission objects pass.
  16275. const currentToneMapping = _this.toneMapping;
  16276. _this.toneMapping = NoToneMapping;
  16277. renderObjects(opaqueObjects, scene, camera);
  16278. _this.toneMapping = currentToneMapping;
  16279. textures.updateMultisampleRenderTarget(_transmissionRenderTarget);
  16280. textures.updateRenderTargetMipmap(_transmissionRenderTarget);
  16281. _this.setRenderTarget(currentRenderTarget);
  16282. }
  16283. function renderObjects(renderList, scene, camera) {
  16284. const overrideMaterial = scene.isScene === true ? scene.overrideMaterial : null;
  16285. for (let i = 0, l = renderList.length; i < l; i++) {
  16286. const renderItem = renderList[i];
  16287. const object = renderItem.object;
  16288. const geometry = renderItem.geometry;
  16289. const material = overrideMaterial === null ? renderItem.material : overrideMaterial;
  16290. const group = renderItem.group;
  16291. if (object.layers.test(camera.layers)) {
  16292. renderObject(object, scene, camera, geometry, material, group);
  16293. }
  16294. }
  16295. }
  16296. function renderObject(object, scene, camera, geometry, material, group) {
  16297. object.onBeforeRender(_this, scene, camera, geometry, material, group);
  16298. object.modelViewMatrix.multiplyMatrices(camera.matrixWorldInverse, object.matrixWorld);
  16299. object.normalMatrix.getNormalMatrix(object.modelViewMatrix);
  16300. material.onBeforeRender(_this, scene, camera, geometry, object, group);
  16301. if (material.transparent === true && material.side === DoubleSide) {
  16302. material.side = BackSide;
  16303. material.needsUpdate = true;
  16304. _this.renderBufferDirect(camera, scene, geometry, material, object, group);
  16305. material.side = FrontSide;
  16306. material.needsUpdate = true;
  16307. _this.renderBufferDirect(camera, scene, geometry, material, object, group);
  16308. material.side = DoubleSide;
  16309. } else {
  16310. _this.renderBufferDirect(camera, scene, geometry, material, object, group);
  16311. }
  16312. object.onAfterRender(_this, scene, camera, geometry, material, group);
  16313. }
  16314. function getProgram(material, scene, object) {
  16315. if (scene.isScene !== true) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...
  16316. const materialProperties = properties.get(material);
  16317. const lights = currentRenderState.state.lights;
  16318. const shadowsArray = currentRenderState.state.shadowsArray;
  16319. const lightsStateVersion = lights.state.version;
  16320. const parameters = programCache.getParameters(material, lights.state, shadowsArray, scene, object);
  16321. const programCacheKey = programCache.getProgramCacheKey(parameters);
  16322. let programs = materialProperties.programs; // always update environment and fog - changing these trigger an getProgram call, but it's possible that the program doesn't change
  16323. materialProperties.environment = material.isMeshStandardMaterial ? scene.environment : null;
  16324. materialProperties.fog = scene.fog;
  16325. materialProperties.envMap = (material.isMeshStandardMaterial ? cubeuvmaps : cubemaps).get(material.envMap || materialProperties.environment);
  16326. if (programs === undefined) {
  16327. // new material
  16328. material.addEventListener('dispose', onMaterialDispose);
  16329. programs = new Map();
  16330. materialProperties.programs = programs;
  16331. }
  16332. let program = programs.get(programCacheKey);
  16333. if (program !== undefined) {
  16334. // early out if program and light state is identical
  16335. if (materialProperties.currentProgram === program && materialProperties.lightsStateVersion === lightsStateVersion) {
  16336. updateCommonMaterialProperties(material, parameters);
  16337. return program;
  16338. }
  16339. } else {
  16340. parameters.uniforms = programCache.getUniforms(material);
  16341. material.onBuild(object, parameters, _this);
  16342. material.onBeforeCompile(parameters, _this);
  16343. program = programCache.acquireProgram(parameters, programCacheKey);
  16344. programs.set(programCacheKey, program);
  16345. materialProperties.uniforms = parameters.uniforms;
  16346. }
  16347. const uniforms = materialProperties.uniforms;
  16348. if (!material.isShaderMaterial && !material.isRawShaderMaterial || material.clipping === true) {
  16349. uniforms.clippingPlanes = clipping.uniform;
  16350. }
  16351. updateCommonMaterialProperties(material, parameters); // store the light setup it was created for
  16352. materialProperties.needsLights = materialNeedsLights(material);
  16353. materialProperties.lightsStateVersion = lightsStateVersion;
  16354. if (materialProperties.needsLights) {
  16355. // wire up the material to this renderer's lighting state
  16356. uniforms.ambientLightColor.value = lights.state.ambient;
  16357. uniforms.lightProbe.value = lights.state.probe;
  16358. uniforms.directionalLights.value = lights.state.directional;
  16359. uniforms.directionalLightShadows.value = lights.state.directionalShadow;
  16360. uniforms.spotLights.value = lights.state.spot;
  16361. uniforms.spotLightShadows.value = lights.state.spotShadow;
  16362. uniforms.rectAreaLights.value = lights.state.rectArea;
  16363. uniforms.ltc_1.value = lights.state.rectAreaLTC1;
  16364. uniforms.ltc_2.value = lights.state.rectAreaLTC2;
  16365. uniforms.pointLights.value = lights.state.point;
  16366. uniforms.pointLightShadows.value = lights.state.pointShadow;
  16367. uniforms.hemisphereLights.value = lights.state.hemi;
  16368. uniforms.directionalShadowMap.value = lights.state.directionalShadowMap;
  16369. uniforms.directionalShadowMatrix.value = lights.state.directionalShadowMatrix;
  16370. uniforms.spotShadowMap.value = lights.state.spotShadowMap;
  16371. uniforms.spotShadowMatrix.value = lights.state.spotShadowMatrix;
  16372. uniforms.pointShadowMap.value = lights.state.pointShadowMap;
  16373. uniforms.pointShadowMatrix.value = lights.state.pointShadowMatrix; // TODO (abelnation): add area lights shadow info to uniforms
  16374. }
  16375. const progUniforms = program.getUniforms();
  16376. const uniformsList = WebGLUniforms.seqWithValue(progUniforms.seq, uniforms);
  16377. materialProperties.currentProgram = program;
  16378. materialProperties.uniformsList = uniformsList;
  16379. return program;
  16380. }
  16381. function updateCommonMaterialProperties(material, parameters) {
  16382. const materialProperties = properties.get(material);
  16383. materialProperties.outputEncoding = parameters.outputEncoding;
  16384. materialProperties.instancing = parameters.instancing;
  16385. materialProperties.skinning = parameters.skinning;
  16386. materialProperties.morphTargets = parameters.morphTargets;
  16387. materialProperties.morphNormals = parameters.morphNormals;
  16388. materialProperties.morphColors = parameters.morphColors;
  16389. materialProperties.morphTargetsCount = parameters.morphTargetsCount;
  16390. materialProperties.numClippingPlanes = parameters.numClippingPlanes;
  16391. materialProperties.numIntersection = parameters.numClipIntersection;
  16392. materialProperties.vertexAlphas = parameters.vertexAlphas;
  16393. materialProperties.vertexTangents = parameters.vertexTangents;
  16394. materialProperties.toneMapping = parameters.toneMapping;
  16395. }
  16396. function setProgram(camera, scene, geometry, material, object) {
  16397. if (scene.isScene !== true) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...
  16398. textures.resetTextureUnits();
  16399. const fog = scene.fog;
  16400. const environment = material.isMeshStandardMaterial ? scene.environment : null;
  16401. const encoding = _currentRenderTarget === null ? _this.outputEncoding : _currentRenderTarget.isXRRenderTarget === true ? _currentRenderTarget.texture.encoding : LinearEncoding;
  16402. const envMap = (material.isMeshStandardMaterial ? cubeuvmaps : cubemaps).get(material.envMap || environment);
  16403. const vertexAlphas = material.vertexColors === true && !!geometry.attributes.color && geometry.attributes.color.itemSize === 4;
  16404. const vertexTangents = !!material.normalMap && !!geometry.attributes.tangent;
  16405. const morphTargets = !!geometry.morphAttributes.position;
  16406. const morphNormals = !!geometry.morphAttributes.normal;
  16407. const morphColors = !!geometry.morphAttributes.color;
  16408. const toneMapping = material.toneMapped ? _this.toneMapping : NoToneMapping;
  16409. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  16410. const morphTargetsCount = morphAttribute !== undefined ? morphAttribute.length : 0;
  16411. const materialProperties = properties.get(material);
  16412. const lights = currentRenderState.state.lights;
  16413. if (_clippingEnabled === true) {
  16414. if (_localClippingEnabled === true || camera !== _currentCamera) {
  16415. const useCache = camera === _currentCamera && material.id === _currentMaterialId; // we might want to call this function with some ClippingGroup
  16416. // object instead of the material, once it becomes feasible
  16417. // (#8465, #8379)
  16418. clipping.setState(material, camera, useCache);
  16419. }
  16420. } //
  16421. let needsProgramChange = false;
  16422. if (material.version === materialProperties.__version) {
  16423. if (materialProperties.needsLights && materialProperties.lightsStateVersion !== lights.state.version) {
  16424. needsProgramChange = true;
  16425. } else if (materialProperties.outputEncoding !== encoding) {
  16426. needsProgramChange = true;
  16427. } else if (object.isInstancedMesh && materialProperties.instancing === false) {
  16428. needsProgramChange = true;
  16429. } else if (!object.isInstancedMesh && materialProperties.instancing === true) {
  16430. needsProgramChange = true;
  16431. } else if (object.isSkinnedMesh && materialProperties.skinning === false) {
  16432. needsProgramChange = true;
  16433. } else if (!object.isSkinnedMesh && materialProperties.skinning === true) {
  16434. needsProgramChange = true;
  16435. } else if (materialProperties.envMap !== envMap) {
  16436. needsProgramChange = true;
  16437. } else if (material.fog === true && materialProperties.fog !== fog) {
  16438. needsProgramChange = true;
  16439. } else if (materialProperties.numClippingPlanes !== undefined && (materialProperties.numClippingPlanes !== clipping.numPlanes || materialProperties.numIntersection !== clipping.numIntersection)) {
  16440. needsProgramChange = true;
  16441. } else if (materialProperties.vertexAlphas !== vertexAlphas) {
  16442. needsProgramChange = true;
  16443. } else if (materialProperties.vertexTangents !== vertexTangents) {
  16444. needsProgramChange = true;
  16445. } else if (materialProperties.morphTargets !== morphTargets) {
  16446. needsProgramChange = true;
  16447. } else if (materialProperties.morphNormals !== morphNormals) {
  16448. needsProgramChange = true;
  16449. } else if (materialProperties.morphColors !== morphColors) {
  16450. needsProgramChange = true;
  16451. } else if (materialProperties.toneMapping !== toneMapping) {
  16452. needsProgramChange = true;
  16453. } else if (capabilities.isWebGL2 === true && materialProperties.morphTargetsCount !== morphTargetsCount) {
  16454. needsProgramChange = true;
  16455. }
  16456. } else {
  16457. needsProgramChange = true;
  16458. materialProperties.__version = material.version;
  16459. } //
  16460. let program = materialProperties.currentProgram;
  16461. if (needsProgramChange === true) {
  16462. program = getProgram(material, scene, object);
  16463. }
  16464. let refreshProgram = false;
  16465. let refreshMaterial = false;
  16466. let refreshLights = false;
  16467. const p_uniforms = program.getUniforms(),
  16468. m_uniforms = materialProperties.uniforms;
  16469. if (state.useProgram(program.program)) {
  16470. refreshProgram = true;
  16471. refreshMaterial = true;
  16472. refreshLights = true;
  16473. }
  16474. if (material.id !== _currentMaterialId) {
  16475. _currentMaterialId = material.id;
  16476. refreshMaterial = true;
  16477. }
  16478. if (refreshProgram || _currentCamera !== camera) {
  16479. p_uniforms.setValue(_gl, 'projectionMatrix', camera.projectionMatrix);
  16480. if (capabilities.logarithmicDepthBuffer) {
  16481. p_uniforms.setValue(_gl, 'logDepthBufFC', 2.0 / (Math.log(camera.far + 1.0) / Math.LN2));
  16482. }
  16483. if (_currentCamera !== camera) {
  16484. _currentCamera = camera; // lighting uniforms depend on the camera so enforce an update
  16485. // now, in case this material supports lights - or later, when
  16486. // the next material that does gets activated:
  16487. refreshMaterial = true; // set to true on material change
  16488. refreshLights = true; // remains set until update done
  16489. } // load material specific uniforms
  16490. // (shader material also gets them for the sake of genericity)
  16491. if (material.isShaderMaterial || material.isMeshPhongMaterial || material.isMeshToonMaterial || material.isMeshStandardMaterial || material.envMap) {
  16492. const uCamPos = p_uniforms.map.cameraPosition;
  16493. if (uCamPos !== undefined) {
  16494. uCamPos.setValue(_gl, _vector3.setFromMatrixPosition(camera.matrixWorld));
  16495. }
  16496. }
  16497. if (material.isMeshPhongMaterial || material.isMeshToonMaterial || material.isMeshLambertMaterial || material.isMeshBasicMaterial || material.isMeshStandardMaterial || material.isShaderMaterial) {
  16498. p_uniforms.setValue(_gl, 'isOrthographic', camera.isOrthographicCamera === true);
  16499. }
  16500. if (material.isMeshPhongMaterial || material.isMeshToonMaterial || material.isMeshLambertMaterial || material.isMeshBasicMaterial || material.isMeshStandardMaterial || material.isShaderMaterial || material.isShadowMaterial || object.isSkinnedMesh) {
  16501. p_uniforms.setValue(_gl, 'viewMatrix', camera.matrixWorldInverse);
  16502. }
  16503. } // skinning and morph target uniforms must be set even if material didn't change
  16504. // auto-setting of texture unit for bone and morph texture must go before other textures
  16505. // otherwise textures used for skinning and morphing can take over texture units reserved for other material textures
  16506. if (object.isSkinnedMesh) {
  16507. p_uniforms.setOptional(_gl, object, 'bindMatrix');
  16508. p_uniforms.setOptional(_gl, object, 'bindMatrixInverse');
  16509. const skeleton = object.skeleton;
  16510. if (skeleton) {
  16511. if (capabilities.floatVertexTextures) {
  16512. if (skeleton.boneTexture === null) skeleton.computeBoneTexture();
  16513. p_uniforms.setValue(_gl, 'boneTexture', skeleton.boneTexture, textures);
  16514. p_uniforms.setValue(_gl, 'boneTextureSize', skeleton.boneTextureSize);
  16515. } else {
  16516. console.warn('THREE.WebGLRenderer: SkinnedMesh can only be used with WebGL 2. With WebGL 1 OES_texture_float and vertex textures support is required.');
  16517. }
  16518. }
  16519. }
  16520. const morphAttributes = geometry.morphAttributes;
  16521. if (morphAttributes.position !== undefined || morphAttributes.normal !== undefined || morphAttributes.color !== undefined && capabilities.isWebGL2 === true) {
  16522. morphtargets.update(object, geometry, material, program);
  16523. }
  16524. if (refreshMaterial || materialProperties.receiveShadow !== object.receiveShadow) {
  16525. materialProperties.receiveShadow = object.receiveShadow;
  16526. p_uniforms.setValue(_gl, 'receiveShadow', object.receiveShadow);
  16527. }
  16528. if (refreshMaterial) {
  16529. p_uniforms.setValue(_gl, 'toneMappingExposure', _this.toneMappingExposure);
  16530. if (materialProperties.needsLights) {
  16531. // the current material requires lighting info
  16532. // note: all lighting uniforms are always set correctly
  16533. // they simply reference the renderer's state for their
  16534. // values
  16535. //
  16536. // use the current material's .needsUpdate flags to set
  16537. // the GL state when required
  16538. markUniformsLightsNeedsUpdate(m_uniforms, refreshLights);
  16539. } // refresh uniforms common to several materials
  16540. if (fog && material.fog === true) {
  16541. materials.refreshFogUniforms(m_uniforms, fog);
  16542. }
  16543. materials.refreshMaterialUniforms(m_uniforms, material, _pixelRatio, _height, _transmissionRenderTarget);
  16544. WebGLUniforms.upload(_gl, materialProperties.uniformsList, m_uniforms, textures);
  16545. }
  16546. if (material.isShaderMaterial && material.uniformsNeedUpdate === true) {
  16547. WebGLUniforms.upload(_gl, materialProperties.uniformsList, m_uniforms, textures);
  16548. material.uniformsNeedUpdate = false;
  16549. }
  16550. if (material.isSpriteMaterial) {
  16551. p_uniforms.setValue(_gl, 'center', object.center);
  16552. } // common matrices
  16553. p_uniforms.setValue(_gl, 'modelViewMatrix', object.modelViewMatrix);
  16554. p_uniforms.setValue(_gl, 'normalMatrix', object.normalMatrix);
  16555. p_uniforms.setValue(_gl, 'modelMatrix', object.matrixWorld);
  16556. return program;
  16557. } // If uniforms are marked as clean, they don't need to be loaded to the GPU.
  16558. function markUniformsLightsNeedsUpdate(uniforms, value) {
  16559. uniforms.ambientLightColor.needsUpdate = value;
  16560. uniforms.lightProbe.needsUpdate = value;
  16561. uniforms.directionalLights.needsUpdate = value;
  16562. uniforms.directionalLightShadows.needsUpdate = value;
  16563. uniforms.pointLights.needsUpdate = value;
  16564. uniforms.pointLightShadows.needsUpdate = value;
  16565. uniforms.spotLights.needsUpdate = value;
  16566. uniforms.spotLightShadows.needsUpdate = value;
  16567. uniforms.rectAreaLights.needsUpdate = value;
  16568. uniforms.hemisphereLights.needsUpdate = value;
  16569. }
  16570. function materialNeedsLights(material) {
  16571. return material.isMeshLambertMaterial || material.isMeshToonMaterial || material.isMeshPhongMaterial || material.isMeshStandardMaterial || material.isShadowMaterial || material.isShaderMaterial && material.lights === true;
  16572. }
  16573. this.getActiveCubeFace = function () {
  16574. return _currentActiveCubeFace;
  16575. };
  16576. this.getActiveMipmapLevel = function () {
  16577. return _currentActiveMipmapLevel;
  16578. };
  16579. this.getRenderTarget = function () {
  16580. return _currentRenderTarget;
  16581. };
  16582. this.setRenderTargetTextures = function (renderTarget, colorTexture, depthTexture) {
  16583. properties.get(renderTarget.texture).__webglTexture = colorTexture;
  16584. properties.get(renderTarget.depthTexture).__webglTexture = depthTexture;
  16585. const renderTargetProperties = properties.get(renderTarget);
  16586. renderTargetProperties.__hasExternalTextures = true;
  16587. if (renderTargetProperties.__hasExternalTextures) {
  16588. renderTargetProperties.__autoAllocateDepthBuffer = depthTexture === undefined;
  16589. if (!renderTargetProperties.__autoAllocateDepthBuffer) {
  16590. // The multisample_render_to_texture extension doesn't work properly if there
  16591. // are midframe flushes and an external depth buffer. Disable use of the extension.
  16592. if (extensions.has('WEBGL_multisampled_render_to_texture') === true) {
  16593. console.warn('THREE.WebGLRenderer: Render-to-texture extension was disabled because an external texture was provided');
  16594. renderTargetProperties.__useRenderToTexture = false;
  16595. }
  16596. }
  16597. }
  16598. };
  16599. this.setRenderTargetFramebuffer = function (renderTarget, defaultFramebuffer) {
  16600. const renderTargetProperties = properties.get(renderTarget);
  16601. renderTargetProperties.__webglFramebuffer = defaultFramebuffer;
  16602. renderTargetProperties.__useDefaultFramebuffer = defaultFramebuffer === undefined;
  16603. };
  16604. this.setRenderTarget = function (renderTarget, activeCubeFace = 0, activeMipmapLevel = 0) {
  16605. _currentRenderTarget = renderTarget;
  16606. _currentActiveCubeFace = activeCubeFace;
  16607. _currentActiveMipmapLevel = activeMipmapLevel;
  16608. let useDefaultFramebuffer = true;
  16609. if (renderTarget) {
  16610. const renderTargetProperties = properties.get(renderTarget);
  16611. if (renderTargetProperties.__useDefaultFramebuffer !== undefined) {
  16612. // We need to make sure to rebind the framebuffer.
  16613. state.bindFramebuffer(_gl.FRAMEBUFFER, null);
  16614. useDefaultFramebuffer = false;
  16615. } else if (renderTargetProperties.__webglFramebuffer === undefined) {
  16616. textures.setupRenderTarget(renderTarget);
  16617. } else if (renderTargetProperties.__hasExternalTextures) {
  16618. // Color and depth texture must be rebound in order for the swapchain to update.
  16619. textures.rebindTextures(renderTarget, properties.get(renderTarget.texture).__webglTexture, properties.get(renderTarget.depthTexture).__webglTexture);
  16620. }
  16621. }
  16622. let framebuffer = null;
  16623. let isCube = false;
  16624. let isRenderTarget3D = false;
  16625. if (renderTarget) {
  16626. const texture = renderTarget.texture;
  16627. if (texture.isData3DTexture || texture.isDataArrayTexture) {
  16628. isRenderTarget3D = true;
  16629. }
  16630. const __webglFramebuffer = properties.get(renderTarget).__webglFramebuffer;
  16631. if (renderTarget.isWebGLCubeRenderTarget) {
  16632. framebuffer = __webglFramebuffer[activeCubeFace];
  16633. isCube = true;
  16634. } else if (capabilities.isWebGL2 && renderTarget.samples > 0 && textures.useMultisampledRTT(renderTarget) === false) {
  16635. framebuffer = properties.get(renderTarget).__webglMultisampledFramebuffer;
  16636. } else {
  16637. framebuffer = __webglFramebuffer;
  16638. }
  16639. _currentViewport.copy(renderTarget.viewport);
  16640. _currentScissor.copy(renderTarget.scissor);
  16641. _currentScissorTest = renderTarget.scissorTest;
  16642. } else {
  16643. _currentViewport.copy(_viewport).multiplyScalar(_pixelRatio).floor();
  16644. _currentScissor.copy(_scissor).multiplyScalar(_pixelRatio).floor();
  16645. _currentScissorTest = _scissorTest;
  16646. }
  16647. const framebufferBound = state.bindFramebuffer(_gl.FRAMEBUFFER, framebuffer);
  16648. if (framebufferBound && capabilities.drawBuffers && useDefaultFramebuffer) {
  16649. state.drawBuffers(renderTarget, framebuffer);
  16650. }
  16651. state.viewport(_currentViewport);
  16652. state.scissor(_currentScissor);
  16653. state.setScissorTest(_currentScissorTest);
  16654. if (isCube) {
  16655. const textureProperties = properties.get(renderTarget.texture);
  16656. _gl.framebufferTexture2D(_gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + activeCubeFace, textureProperties.__webglTexture, activeMipmapLevel);
  16657. } else if (isRenderTarget3D) {
  16658. const textureProperties = properties.get(renderTarget.texture);
  16659. const layer = activeCubeFace || 0;
  16660. _gl.framebufferTextureLayer(_gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, textureProperties.__webglTexture, activeMipmapLevel || 0, layer);
  16661. }
  16662. _currentMaterialId = -1; // reset current material to ensure correct uniform bindings
  16663. };
  16664. this.readRenderTargetPixels = function (renderTarget, x, y, width, height, buffer, activeCubeFaceIndex) {
  16665. if (!(renderTarget && renderTarget.isWebGLRenderTarget)) {
  16666. console.error('THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.');
  16667. return;
  16668. }
  16669. let framebuffer = properties.get(renderTarget).__webglFramebuffer;
  16670. if (renderTarget.isWebGLCubeRenderTarget && activeCubeFaceIndex !== undefined) {
  16671. framebuffer = framebuffer[activeCubeFaceIndex];
  16672. }
  16673. if (framebuffer) {
  16674. state.bindFramebuffer(_gl.FRAMEBUFFER, framebuffer);
  16675. try {
  16676. const texture = renderTarget.texture;
  16677. const textureFormat = texture.format;
  16678. const textureType = texture.type;
  16679. if (textureFormat !== RGBAFormat && utils.convert(textureFormat) !== _gl.getParameter(_gl.IMPLEMENTATION_COLOR_READ_FORMAT)) {
  16680. console.error('THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.');
  16681. return;
  16682. }
  16683. const halfFloatSupportedByExt = textureType === HalfFloatType && (extensions.has('EXT_color_buffer_half_float') || capabilities.isWebGL2 && extensions.has('EXT_color_buffer_float'));
  16684. if (textureType !== UnsignedByteType && utils.convert(textureType) !== _gl.getParameter(_gl.IMPLEMENTATION_COLOR_READ_TYPE) && // Edge and Chrome Mac < 52 (#9513)
  16685. !(textureType === FloatType && (capabilities.isWebGL2 || extensions.has('OES_texture_float') || extensions.has('WEBGL_color_buffer_float'))) && // Chrome Mac >= 52 and Firefox
  16686. !halfFloatSupportedByExt) {
  16687. console.error('THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.');
  16688. return;
  16689. } // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604)
  16690. if (x >= 0 && x <= renderTarget.width - width && y >= 0 && y <= renderTarget.height - height) {
  16691. _gl.readPixels(x, y, width, height, utils.convert(textureFormat), utils.convert(textureType), buffer);
  16692. }
  16693. } finally {
  16694. // restore framebuffer of current render target if necessary
  16695. const framebuffer = _currentRenderTarget !== null ? properties.get(_currentRenderTarget).__webglFramebuffer : null;
  16696. state.bindFramebuffer(_gl.FRAMEBUFFER, framebuffer);
  16697. }
  16698. }
  16699. };
  16700. this.copyFramebufferToTexture = function (position, texture, level = 0) {
  16701. const levelScale = Math.pow(2, -level);
  16702. const width = Math.floor(texture.image.width * levelScale);
  16703. const height = Math.floor(texture.image.height * levelScale);
  16704. textures.setTexture2D(texture, 0);
  16705. _gl.copyTexSubImage2D(_gl.TEXTURE_2D, level, 0, 0, position.x, position.y, width, height);
  16706. state.unbindTexture();
  16707. };
  16708. this.copyTextureToTexture = function (position, srcTexture, dstTexture, level = 0) {
  16709. const width = srcTexture.image.width;
  16710. const height = srcTexture.image.height;
  16711. const glFormat = utils.convert(dstTexture.format);
  16712. const glType = utils.convert(dstTexture.type);
  16713. textures.setTexture2D(dstTexture, 0); // As another texture upload may have changed pixelStorei
  16714. // parameters, make sure they are correct for the dstTexture
  16715. _gl.pixelStorei(_gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY);
  16716. _gl.pixelStorei(_gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha);
  16717. _gl.pixelStorei(_gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment);
  16718. if (srcTexture.isDataTexture) {
  16719. _gl.texSubImage2D(_gl.TEXTURE_2D, level, position.x, position.y, width, height, glFormat, glType, srcTexture.image.data);
  16720. } else {
  16721. if (srcTexture.isCompressedTexture) {
  16722. _gl.compressedTexSubImage2D(_gl.TEXTURE_2D, level, position.x, position.y, srcTexture.mipmaps[0].width, srcTexture.mipmaps[0].height, glFormat, srcTexture.mipmaps[0].data);
  16723. } else {
  16724. _gl.texSubImage2D(_gl.TEXTURE_2D, level, position.x, position.y, glFormat, glType, srcTexture.image);
  16725. }
  16726. } // Generate mipmaps only when copying level 0
  16727. if (level === 0 && dstTexture.generateMipmaps) _gl.generateMipmap(_gl.TEXTURE_2D);
  16728. state.unbindTexture();
  16729. };
  16730. this.copyTextureToTexture3D = function (sourceBox, position, srcTexture, dstTexture, level = 0) {
  16731. if (_this.isWebGL1Renderer) {
  16732. console.warn('THREE.WebGLRenderer.copyTextureToTexture3D: can only be used with WebGL2.');
  16733. return;
  16734. }
  16735. const width = sourceBox.max.x - sourceBox.min.x + 1;
  16736. const height = sourceBox.max.y - sourceBox.min.y + 1;
  16737. const depth = sourceBox.max.z - sourceBox.min.z + 1;
  16738. const glFormat = utils.convert(dstTexture.format);
  16739. const glType = utils.convert(dstTexture.type);
  16740. let glTarget;
  16741. if (dstTexture.isData3DTexture) {
  16742. textures.setTexture3D(dstTexture, 0);
  16743. glTarget = _gl.TEXTURE_3D;
  16744. } else if (dstTexture.isDataArrayTexture) {
  16745. textures.setTexture2DArray(dstTexture, 0);
  16746. glTarget = _gl.TEXTURE_2D_ARRAY;
  16747. } else {
  16748. console.warn('THREE.WebGLRenderer.copyTextureToTexture3D: only supports THREE.DataTexture3D and THREE.DataTexture2DArray.');
  16749. return;
  16750. }
  16751. _gl.pixelStorei(_gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY);
  16752. _gl.pixelStorei(_gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha);
  16753. _gl.pixelStorei(_gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment);
  16754. const unpackRowLen = _gl.getParameter(_gl.UNPACK_ROW_LENGTH);
  16755. const unpackImageHeight = _gl.getParameter(_gl.UNPACK_IMAGE_HEIGHT);
  16756. const unpackSkipPixels = _gl.getParameter(_gl.UNPACK_SKIP_PIXELS);
  16757. const unpackSkipRows = _gl.getParameter(_gl.UNPACK_SKIP_ROWS);
  16758. const unpackSkipImages = _gl.getParameter(_gl.UNPACK_SKIP_IMAGES);
  16759. const image = srcTexture.isCompressedTexture ? srcTexture.mipmaps[0] : srcTexture.image;
  16760. _gl.pixelStorei(_gl.UNPACK_ROW_LENGTH, image.width);
  16761. _gl.pixelStorei(_gl.UNPACK_IMAGE_HEIGHT, image.height);
  16762. _gl.pixelStorei(_gl.UNPACK_SKIP_PIXELS, sourceBox.min.x);
  16763. _gl.pixelStorei(_gl.UNPACK_SKIP_ROWS, sourceBox.min.y);
  16764. _gl.pixelStorei(_gl.UNPACK_SKIP_IMAGES, sourceBox.min.z);
  16765. if (srcTexture.isDataTexture || srcTexture.isData3DTexture) {
  16766. _gl.texSubImage3D(glTarget, level, position.x, position.y, position.z, width, height, depth, glFormat, glType, image.data);
  16767. } else {
  16768. if (srcTexture.isCompressedTexture) {
  16769. console.warn('THREE.WebGLRenderer.copyTextureToTexture3D: untested support for compressed srcTexture.');
  16770. _gl.compressedTexSubImage3D(glTarget, level, position.x, position.y, position.z, width, height, depth, glFormat, image.data);
  16771. } else {
  16772. _gl.texSubImage3D(glTarget, level, position.x, position.y, position.z, width, height, depth, glFormat, glType, image);
  16773. }
  16774. }
  16775. _gl.pixelStorei(_gl.UNPACK_ROW_LENGTH, unpackRowLen);
  16776. _gl.pixelStorei(_gl.UNPACK_IMAGE_HEIGHT, unpackImageHeight);
  16777. _gl.pixelStorei(_gl.UNPACK_SKIP_PIXELS, unpackSkipPixels);
  16778. _gl.pixelStorei(_gl.UNPACK_SKIP_ROWS, unpackSkipRows);
  16779. _gl.pixelStorei(_gl.UNPACK_SKIP_IMAGES, unpackSkipImages); // Generate mipmaps only when copying level 0
  16780. if (level === 0 && dstTexture.generateMipmaps) _gl.generateMipmap(glTarget);
  16781. state.unbindTexture();
  16782. };
  16783. this.initTexture = function (texture) {
  16784. textures.setTexture2D(texture, 0);
  16785. state.unbindTexture();
  16786. };
  16787. this.resetState = function () {
  16788. _currentActiveCubeFace = 0;
  16789. _currentActiveMipmapLevel = 0;
  16790. _currentRenderTarget = null;
  16791. state.reset();
  16792. bindingStates.reset();
  16793. };
  16794. if (typeof __THREE_DEVTOOLS__ !== 'undefined') {
  16795. __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent('observe', {
  16796. detail: this
  16797. }));
  16798. }
  16799. }
  16800. class WebGL1Renderer extends WebGLRenderer {}
  16801. WebGL1Renderer.prototype.isWebGL1Renderer = true;
  16802. class FogExp2 {
  16803. constructor(color, density = 0.00025) {
  16804. this.isFogExp2 = true;
  16805. this.name = '';
  16806. this.color = new Color(color);
  16807. this.density = density;
  16808. }
  16809. clone() {
  16810. return new FogExp2(this.color, this.density);
  16811. }
  16812. toJSON() {
  16813. return {
  16814. type: 'FogExp2',
  16815. color: this.color.getHex(),
  16816. density: this.density
  16817. };
  16818. }
  16819. }
  16820. class Fog {
  16821. constructor(color, near = 1, far = 1000) {
  16822. this.isFog = true;
  16823. this.name = '';
  16824. this.color = new Color(color);
  16825. this.near = near;
  16826. this.far = far;
  16827. }
  16828. clone() {
  16829. return new Fog(this.color, this.near, this.far);
  16830. }
  16831. toJSON() {
  16832. return {
  16833. type: 'Fog',
  16834. color: this.color.getHex(),
  16835. near: this.near,
  16836. far: this.far
  16837. };
  16838. }
  16839. }
  16840. class Scene extends Object3D {
  16841. constructor() {
  16842. super();
  16843. this.isScene = true;
  16844. this.type = 'Scene';
  16845. this.background = null;
  16846. this.environment = null;
  16847. this.fog = null;
  16848. this.overrideMaterial = null;
  16849. this.autoUpdate = true; // checked by the renderer
  16850. if (typeof __THREE_DEVTOOLS__ !== 'undefined') {
  16851. __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent('observe', {
  16852. detail: this
  16853. }));
  16854. }
  16855. }
  16856. copy(source, recursive) {
  16857. super.copy(source, recursive);
  16858. if (source.background !== null) this.background = source.background.clone();
  16859. if (source.environment !== null) this.environment = source.environment.clone();
  16860. if (source.fog !== null) this.fog = source.fog.clone();
  16861. if (source.overrideMaterial !== null) this.overrideMaterial = source.overrideMaterial.clone();
  16862. this.autoUpdate = source.autoUpdate;
  16863. this.matrixAutoUpdate = source.matrixAutoUpdate;
  16864. return this;
  16865. }
  16866. toJSON(meta) {
  16867. const data = super.toJSON(meta);
  16868. if (this.fog !== null) data.object.fog = this.fog.toJSON();
  16869. return data;
  16870. }
  16871. }
  16872. class InterleavedBuffer {
  16873. constructor(array, stride) {
  16874. this.isInterleavedBuffer = true;
  16875. this.array = array;
  16876. this.stride = stride;
  16877. this.count = array !== undefined ? array.length / stride : 0;
  16878. this.usage = StaticDrawUsage;
  16879. this.updateRange = {
  16880. offset: 0,
  16881. count: -1
  16882. };
  16883. this.version = 0;
  16884. this.uuid = generateUUID();
  16885. }
  16886. onUploadCallback() {}
  16887. set needsUpdate(value) {
  16888. if (value === true) this.version++;
  16889. }
  16890. setUsage(value) {
  16891. this.usage = value;
  16892. return this;
  16893. }
  16894. copy(source) {
  16895. this.array = new source.array.constructor(source.array);
  16896. this.count = source.count;
  16897. this.stride = source.stride;
  16898. this.usage = source.usage;
  16899. return this;
  16900. }
  16901. copyAt(index1, attribute, index2) {
  16902. index1 *= this.stride;
  16903. index2 *= attribute.stride;
  16904. for (let i = 0, l = this.stride; i < l; i++) {
  16905. this.array[index1 + i] = attribute.array[index2 + i];
  16906. }
  16907. return this;
  16908. }
  16909. set(value, offset = 0) {
  16910. this.array.set(value, offset);
  16911. return this;
  16912. }
  16913. clone(data) {
  16914. if (data.arrayBuffers === undefined) {
  16915. data.arrayBuffers = {};
  16916. }
  16917. if (this.array.buffer._uuid === undefined) {
  16918. this.array.buffer._uuid = generateUUID();
  16919. }
  16920. if (data.arrayBuffers[this.array.buffer._uuid] === undefined) {
  16921. data.arrayBuffers[this.array.buffer._uuid] = this.array.slice(0).buffer;
  16922. }
  16923. const array = new this.array.constructor(data.arrayBuffers[this.array.buffer._uuid]);
  16924. const ib = new this.constructor(array, this.stride);
  16925. ib.setUsage(this.usage);
  16926. return ib;
  16927. }
  16928. onUpload(callback) {
  16929. this.onUploadCallback = callback;
  16930. return this;
  16931. }
  16932. toJSON(data) {
  16933. if (data.arrayBuffers === undefined) {
  16934. data.arrayBuffers = {};
  16935. } // generate UUID for array buffer if necessary
  16936. if (this.array.buffer._uuid === undefined) {
  16937. this.array.buffer._uuid = generateUUID();
  16938. }
  16939. if (data.arrayBuffers[this.array.buffer._uuid] === undefined) {
  16940. data.arrayBuffers[this.array.buffer._uuid] = Array.prototype.slice.call(new Uint32Array(this.array.buffer));
  16941. } //
  16942. return {
  16943. uuid: this.uuid,
  16944. buffer: this.array.buffer._uuid,
  16945. type: this.array.constructor.name,
  16946. stride: this.stride
  16947. };
  16948. }
  16949. }
  16950. const _vector$6 = /*@__PURE__*/new Vector3();
  16951. class InterleavedBufferAttribute {
  16952. constructor(interleavedBuffer, itemSize, offset, normalized = false) {
  16953. this.isInterleavedBufferAttribute = true;
  16954. this.name = '';
  16955. this.data = interleavedBuffer;
  16956. this.itemSize = itemSize;
  16957. this.offset = offset;
  16958. this.normalized = normalized === true;
  16959. }
  16960. get count() {
  16961. return this.data.count;
  16962. }
  16963. get array() {
  16964. return this.data.array;
  16965. }
  16966. set needsUpdate(value) {
  16967. this.data.needsUpdate = value;
  16968. }
  16969. applyMatrix4(m) {
  16970. for (let i = 0, l = this.data.count; i < l; i++) {
  16971. _vector$6.fromBufferAttribute(this, i);
  16972. _vector$6.applyMatrix4(m);
  16973. this.setXYZ(i, _vector$6.x, _vector$6.y, _vector$6.z);
  16974. }
  16975. return this;
  16976. }
  16977. applyNormalMatrix(m) {
  16978. for (let i = 0, l = this.count; i < l; i++) {
  16979. _vector$6.fromBufferAttribute(this, i);
  16980. _vector$6.applyNormalMatrix(m);
  16981. this.setXYZ(i, _vector$6.x, _vector$6.y, _vector$6.z);
  16982. }
  16983. return this;
  16984. }
  16985. transformDirection(m) {
  16986. for (let i = 0, l = this.count; i < l; i++) {
  16987. _vector$6.fromBufferAttribute(this, i);
  16988. _vector$6.transformDirection(m);
  16989. this.setXYZ(i, _vector$6.x, _vector$6.y, _vector$6.z);
  16990. }
  16991. return this;
  16992. }
  16993. setX(index, x) {
  16994. this.data.array[index * this.data.stride + this.offset] = x;
  16995. return this;
  16996. }
  16997. setY(index, y) {
  16998. this.data.array[index * this.data.stride + this.offset + 1] = y;
  16999. return this;
  17000. }
  17001. setZ(index, z) {
  17002. this.data.array[index * this.data.stride + this.offset + 2] = z;
  17003. return this;
  17004. }
  17005. setW(index, w) {
  17006. this.data.array[index * this.data.stride + this.offset + 3] = w;
  17007. return this;
  17008. }
  17009. getX(index) {
  17010. return this.data.array[index * this.data.stride + this.offset];
  17011. }
  17012. getY(index) {
  17013. return this.data.array[index * this.data.stride + this.offset + 1];
  17014. }
  17015. getZ(index) {
  17016. return this.data.array[index * this.data.stride + this.offset + 2];
  17017. }
  17018. getW(index) {
  17019. return this.data.array[index * this.data.stride + this.offset + 3];
  17020. }
  17021. setXY(index, x, y) {
  17022. index = index * this.data.stride + this.offset;
  17023. this.data.array[index + 0] = x;
  17024. this.data.array[index + 1] = y;
  17025. return this;
  17026. }
  17027. setXYZ(index, x, y, z) {
  17028. index = index * this.data.stride + this.offset;
  17029. this.data.array[index + 0] = x;
  17030. this.data.array[index + 1] = y;
  17031. this.data.array[index + 2] = z;
  17032. return this;
  17033. }
  17034. setXYZW(index, x, y, z, w) {
  17035. index = index * this.data.stride + this.offset;
  17036. this.data.array[index + 0] = x;
  17037. this.data.array[index + 1] = y;
  17038. this.data.array[index + 2] = z;
  17039. this.data.array[index + 3] = w;
  17040. return this;
  17041. }
  17042. clone(data) {
  17043. if (data === undefined) {
  17044. console.log('THREE.InterleavedBufferAttribute.clone(): Cloning an interlaved buffer attribute will deinterleave buffer data.');
  17045. const array = [];
  17046. for (let i = 0; i < this.count; i++) {
  17047. const index = i * this.data.stride + this.offset;
  17048. for (let j = 0; j < this.itemSize; j++) {
  17049. array.push(this.data.array[index + j]);
  17050. }
  17051. }
  17052. return new BufferAttribute(new this.array.constructor(array), this.itemSize, this.normalized);
  17053. } else {
  17054. if (data.interleavedBuffers === undefined) {
  17055. data.interleavedBuffers = {};
  17056. }
  17057. if (data.interleavedBuffers[this.data.uuid] === undefined) {
  17058. data.interleavedBuffers[this.data.uuid] = this.data.clone(data);
  17059. }
  17060. return new InterleavedBufferAttribute(data.interleavedBuffers[this.data.uuid], this.itemSize, this.offset, this.normalized);
  17061. }
  17062. }
  17063. toJSON(data) {
  17064. if (data === undefined) {
  17065. console.log('THREE.InterleavedBufferAttribute.toJSON(): Serializing an interlaved buffer attribute will deinterleave buffer data.');
  17066. const array = [];
  17067. for (let i = 0; i < this.count; i++) {
  17068. const index = i * this.data.stride + this.offset;
  17069. for (let j = 0; j < this.itemSize; j++) {
  17070. array.push(this.data.array[index + j]);
  17071. }
  17072. } // deinterleave data and save it as an ordinary buffer attribute for now
  17073. return {
  17074. itemSize: this.itemSize,
  17075. type: this.array.constructor.name,
  17076. array: array,
  17077. normalized: this.normalized
  17078. };
  17079. } else {
  17080. // save as true interlaved attribtue
  17081. if (data.interleavedBuffers === undefined) {
  17082. data.interleavedBuffers = {};
  17083. }
  17084. if (data.interleavedBuffers[this.data.uuid] === undefined) {
  17085. data.interleavedBuffers[this.data.uuid] = this.data.toJSON(data);
  17086. }
  17087. return {
  17088. isInterleavedBufferAttribute: true,
  17089. itemSize: this.itemSize,
  17090. data: this.data.uuid,
  17091. offset: this.offset,
  17092. normalized: this.normalized
  17093. };
  17094. }
  17095. }
  17096. }
  17097. class SpriteMaterial extends Material {
  17098. constructor(parameters) {
  17099. super();
  17100. this.isSpriteMaterial = true;
  17101. this.type = 'SpriteMaterial';
  17102. this.color = new Color(0xffffff);
  17103. this.map = null;
  17104. this.alphaMap = null;
  17105. this.rotation = 0;
  17106. this.sizeAttenuation = true;
  17107. this.transparent = true;
  17108. this.fog = true;
  17109. this.setValues(parameters);
  17110. }
  17111. copy(source) {
  17112. super.copy(source);
  17113. this.color.copy(source.color);
  17114. this.map = source.map;
  17115. this.alphaMap = source.alphaMap;
  17116. this.rotation = source.rotation;
  17117. this.sizeAttenuation = source.sizeAttenuation;
  17118. this.fog = source.fog;
  17119. return this;
  17120. }
  17121. }
  17122. let _geometry;
  17123. const _intersectPoint = /*@__PURE__*/new Vector3();
  17124. const _worldScale = /*@__PURE__*/new Vector3();
  17125. const _mvPosition = /*@__PURE__*/new Vector3();
  17126. const _alignedPosition = /*@__PURE__*/new Vector2();
  17127. const _rotatedPosition = /*@__PURE__*/new Vector2();
  17128. const _viewWorldMatrix = /*@__PURE__*/new Matrix4();
  17129. const _vA = /*@__PURE__*/new Vector3();
  17130. const _vB = /*@__PURE__*/new Vector3();
  17131. const _vC = /*@__PURE__*/new Vector3();
  17132. const _uvA = /*@__PURE__*/new Vector2();
  17133. const _uvB = /*@__PURE__*/new Vector2();
  17134. const _uvC = /*@__PURE__*/new Vector2();
  17135. class Sprite extends Object3D {
  17136. constructor(material) {
  17137. super();
  17138. this.isSprite = true;
  17139. this.type = 'Sprite';
  17140. if (_geometry === undefined) {
  17141. _geometry = new BufferGeometry();
  17142. 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]);
  17143. const interleavedBuffer = new InterleavedBuffer(float32Array, 5);
  17144. _geometry.setIndex([0, 1, 2, 0, 2, 3]);
  17145. _geometry.setAttribute('position', new InterleavedBufferAttribute(interleavedBuffer, 3, 0, false));
  17146. _geometry.setAttribute('uv', new InterleavedBufferAttribute(interleavedBuffer, 2, 3, false));
  17147. }
  17148. this.geometry = _geometry;
  17149. this.material = material !== undefined ? material : new SpriteMaterial();
  17150. this.center = new Vector2(0.5, 0.5);
  17151. }
  17152. raycast(raycaster, intersects) {
  17153. if (raycaster.camera === null) {
  17154. console.error('THREE.Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.');
  17155. }
  17156. _worldScale.setFromMatrixScale(this.matrixWorld);
  17157. _viewWorldMatrix.copy(raycaster.camera.matrixWorld);
  17158. this.modelViewMatrix.multiplyMatrices(raycaster.camera.matrixWorldInverse, this.matrixWorld);
  17159. _mvPosition.setFromMatrixPosition(this.modelViewMatrix);
  17160. if (raycaster.camera.isPerspectiveCamera && this.material.sizeAttenuation === false) {
  17161. _worldScale.multiplyScalar(-_mvPosition.z);
  17162. }
  17163. const rotation = this.material.rotation;
  17164. let sin, cos;
  17165. if (rotation !== 0) {
  17166. cos = Math.cos(rotation);
  17167. sin = Math.sin(rotation);
  17168. }
  17169. const center = this.center;
  17170. transformVertex(_vA.set(-0.5, -0.5, 0), _mvPosition, center, _worldScale, sin, cos);
  17171. transformVertex(_vB.set(0.5, -0.5, 0), _mvPosition, center, _worldScale, sin, cos);
  17172. transformVertex(_vC.set(0.5, 0.5, 0), _mvPosition, center, _worldScale, sin, cos);
  17173. _uvA.set(0, 0);
  17174. _uvB.set(1, 0);
  17175. _uvC.set(1, 1); // check first triangle
  17176. let intersect = raycaster.ray.intersectTriangle(_vA, _vB, _vC, false, _intersectPoint);
  17177. if (intersect === null) {
  17178. // check second triangle
  17179. transformVertex(_vB.set(-0.5, 0.5, 0), _mvPosition, center, _worldScale, sin, cos);
  17180. _uvB.set(0, 1);
  17181. intersect = raycaster.ray.intersectTriangle(_vA, _vC, _vB, false, _intersectPoint);
  17182. if (intersect === null) {
  17183. return;
  17184. }
  17185. }
  17186. const distance = raycaster.ray.origin.distanceTo(_intersectPoint);
  17187. if (distance < raycaster.near || distance > raycaster.far) return;
  17188. intersects.push({
  17189. distance: distance,
  17190. point: _intersectPoint.clone(),
  17191. uv: Triangle.getUV(_intersectPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2()),
  17192. face: null,
  17193. object: this
  17194. });
  17195. }
  17196. copy(source) {
  17197. super.copy(source);
  17198. if (source.center !== undefined) this.center.copy(source.center);
  17199. this.material = source.material;
  17200. return this;
  17201. }
  17202. }
  17203. function transformVertex(vertexPosition, mvPosition, center, scale, sin, cos) {
  17204. // compute position in camera space
  17205. _alignedPosition.subVectors(vertexPosition, center).addScalar(0.5).multiply(scale); // to check if rotation is not zero
  17206. if (sin !== undefined) {
  17207. _rotatedPosition.x = cos * _alignedPosition.x - sin * _alignedPosition.y;
  17208. _rotatedPosition.y = sin * _alignedPosition.x + cos * _alignedPosition.y;
  17209. } else {
  17210. _rotatedPosition.copy(_alignedPosition);
  17211. }
  17212. vertexPosition.copy(mvPosition);
  17213. vertexPosition.x += _rotatedPosition.x;
  17214. vertexPosition.y += _rotatedPosition.y; // transform to world space
  17215. vertexPosition.applyMatrix4(_viewWorldMatrix);
  17216. }
  17217. const _v1$2 = /*@__PURE__*/new Vector3();
  17218. const _v2$1 = /*@__PURE__*/new Vector3();
  17219. class LOD extends Object3D {
  17220. constructor() {
  17221. super();
  17222. this._currentLevel = 0;
  17223. this.type = 'LOD';
  17224. Object.defineProperties(this, {
  17225. levels: {
  17226. enumerable: true,
  17227. value: []
  17228. },
  17229. isLOD: {
  17230. value: true
  17231. }
  17232. });
  17233. this.autoUpdate = true;
  17234. }
  17235. copy(source) {
  17236. super.copy(source, false);
  17237. const levels = source.levels;
  17238. for (let i = 0, l = levels.length; i < l; i++) {
  17239. const level = levels[i];
  17240. this.addLevel(level.object.clone(), level.distance);
  17241. }
  17242. this.autoUpdate = source.autoUpdate;
  17243. return this;
  17244. }
  17245. addLevel(object, distance = 0) {
  17246. distance = Math.abs(distance);
  17247. const levels = this.levels;
  17248. let l;
  17249. for (l = 0; l < levels.length; l++) {
  17250. if (distance < levels[l].distance) {
  17251. break;
  17252. }
  17253. }
  17254. levels.splice(l, 0, {
  17255. distance: distance,
  17256. object: object
  17257. });
  17258. this.add(object);
  17259. return this;
  17260. }
  17261. getCurrentLevel() {
  17262. return this._currentLevel;
  17263. }
  17264. getObjectForDistance(distance) {
  17265. const levels = this.levels;
  17266. if (levels.length > 0) {
  17267. let i, l;
  17268. for (i = 1, l = levels.length; i < l; i++) {
  17269. if (distance < levels[i].distance) {
  17270. break;
  17271. }
  17272. }
  17273. return levels[i - 1].object;
  17274. }
  17275. return null;
  17276. }
  17277. raycast(raycaster, intersects) {
  17278. const levels = this.levels;
  17279. if (levels.length > 0) {
  17280. _v1$2.setFromMatrixPosition(this.matrixWorld);
  17281. const distance = raycaster.ray.origin.distanceTo(_v1$2);
  17282. this.getObjectForDistance(distance).raycast(raycaster, intersects);
  17283. }
  17284. }
  17285. update(camera) {
  17286. const levels = this.levels;
  17287. if (levels.length > 1) {
  17288. _v1$2.setFromMatrixPosition(camera.matrixWorld);
  17289. _v2$1.setFromMatrixPosition(this.matrixWorld);
  17290. const distance = _v1$2.distanceTo(_v2$1) / camera.zoom;
  17291. levels[0].object.visible = true;
  17292. let i, l;
  17293. for (i = 1, l = levels.length; i < l; i++) {
  17294. if (distance >= levels[i].distance) {
  17295. levels[i - 1].object.visible = false;
  17296. levels[i].object.visible = true;
  17297. } else {
  17298. break;
  17299. }
  17300. }
  17301. this._currentLevel = i - 1;
  17302. for (; i < l; i++) {
  17303. levels[i].object.visible = false;
  17304. }
  17305. }
  17306. }
  17307. toJSON(meta) {
  17308. const data = super.toJSON(meta);
  17309. if (this.autoUpdate === false) data.object.autoUpdate = false;
  17310. data.object.levels = [];
  17311. const levels = this.levels;
  17312. for (let i = 0, l = levels.length; i < l; i++) {
  17313. const level = levels[i];
  17314. data.object.levels.push({
  17315. object: level.object.uuid,
  17316. distance: level.distance
  17317. });
  17318. }
  17319. return data;
  17320. }
  17321. }
  17322. const _basePosition = /*@__PURE__*/new Vector3();
  17323. const _skinIndex = /*@__PURE__*/new Vector4();
  17324. const _skinWeight = /*@__PURE__*/new Vector4();
  17325. const _vector$5 = /*@__PURE__*/new Vector3();
  17326. const _matrix = /*@__PURE__*/new Matrix4();
  17327. class SkinnedMesh extends Mesh {
  17328. constructor(geometry, material) {
  17329. super(geometry, material);
  17330. this.isSkinnedMesh = true;
  17331. this.type = 'SkinnedMesh';
  17332. this.bindMode = 'attached';
  17333. this.bindMatrix = new Matrix4();
  17334. this.bindMatrixInverse = new Matrix4();
  17335. }
  17336. copy(source) {
  17337. super.copy(source);
  17338. this.bindMode = source.bindMode;
  17339. this.bindMatrix.copy(source.bindMatrix);
  17340. this.bindMatrixInverse.copy(source.bindMatrixInverse);
  17341. this.skeleton = source.skeleton;
  17342. return this;
  17343. }
  17344. bind(skeleton, bindMatrix) {
  17345. this.skeleton = skeleton;
  17346. if (bindMatrix === undefined) {
  17347. this.updateMatrixWorld(true);
  17348. this.skeleton.calculateInverses();
  17349. bindMatrix = this.matrixWorld;
  17350. }
  17351. this.bindMatrix.copy(bindMatrix);
  17352. this.bindMatrixInverse.copy(bindMatrix).invert();
  17353. }
  17354. pose() {
  17355. this.skeleton.pose();
  17356. }
  17357. normalizeSkinWeights() {
  17358. const vector = new Vector4();
  17359. const skinWeight = this.geometry.attributes.skinWeight;
  17360. for (let i = 0, l = skinWeight.count; i < l; i++) {
  17361. vector.fromBufferAttribute(skinWeight, i);
  17362. const scale = 1.0 / vector.manhattanLength();
  17363. if (scale !== Infinity) {
  17364. vector.multiplyScalar(scale);
  17365. } else {
  17366. vector.set(1, 0, 0, 0); // do something reasonable
  17367. }
  17368. skinWeight.setXYZW(i, vector.x, vector.y, vector.z, vector.w);
  17369. }
  17370. }
  17371. updateMatrixWorld(force) {
  17372. super.updateMatrixWorld(force);
  17373. if (this.bindMode === 'attached') {
  17374. this.bindMatrixInverse.copy(this.matrixWorld).invert();
  17375. } else if (this.bindMode === 'detached') {
  17376. this.bindMatrixInverse.copy(this.bindMatrix).invert();
  17377. } else {
  17378. console.warn('THREE.SkinnedMesh: Unrecognized bindMode: ' + this.bindMode);
  17379. }
  17380. }
  17381. boneTransform(index, target) {
  17382. const skeleton = this.skeleton;
  17383. const geometry = this.geometry;
  17384. _skinIndex.fromBufferAttribute(geometry.attributes.skinIndex, index);
  17385. _skinWeight.fromBufferAttribute(geometry.attributes.skinWeight, index);
  17386. _basePosition.copy(target).applyMatrix4(this.bindMatrix);
  17387. target.set(0, 0, 0);
  17388. for (let i = 0; i < 4; i++) {
  17389. const weight = _skinWeight.getComponent(i);
  17390. if (weight !== 0) {
  17391. const boneIndex = _skinIndex.getComponent(i);
  17392. _matrix.multiplyMatrices(skeleton.bones[boneIndex].matrixWorld, skeleton.boneInverses[boneIndex]);
  17393. target.addScaledVector(_vector$5.copy(_basePosition).applyMatrix4(_matrix), weight);
  17394. }
  17395. }
  17396. return target.applyMatrix4(this.bindMatrixInverse);
  17397. }
  17398. }
  17399. class Bone extends Object3D {
  17400. constructor() {
  17401. super();
  17402. this.isBone = true;
  17403. this.type = 'Bone';
  17404. }
  17405. }
  17406. class DataTexture extends Texture {
  17407. constructor(data = null, width = 1, height = 1, format, type, mapping, wrapS, wrapT, magFilter = NearestFilter, minFilter = NearestFilter, anisotropy, encoding) {
  17408. super(null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding);
  17409. this.isDataTexture = true;
  17410. this.image = {
  17411. data: data,
  17412. width: width,
  17413. height: height
  17414. };
  17415. this.generateMipmaps = false;
  17416. this.flipY = false;
  17417. this.unpackAlignment = 1;
  17418. }
  17419. }
  17420. const _offsetMatrix = /*@__PURE__*/new Matrix4();
  17421. const _identityMatrix = /*@__PURE__*/new Matrix4();
  17422. class Skeleton {
  17423. constructor(bones = [], boneInverses = []) {
  17424. this.uuid = generateUUID();
  17425. this.bones = bones.slice(0);
  17426. this.boneInverses = boneInverses;
  17427. this.boneMatrices = null;
  17428. this.boneTexture = null;
  17429. this.boneTextureSize = 0;
  17430. this.frame = -1;
  17431. this.init();
  17432. }
  17433. init() {
  17434. const bones = this.bones;
  17435. const boneInverses = this.boneInverses;
  17436. this.boneMatrices = new Float32Array(bones.length * 16); // calculate inverse bone matrices if necessary
  17437. if (boneInverses.length === 0) {
  17438. this.calculateInverses();
  17439. } else {
  17440. // handle special case
  17441. if (bones.length !== boneInverses.length) {
  17442. console.warn('THREE.Skeleton: Number of inverse bone matrices does not match amount of bones.');
  17443. this.boneInverses = [];
  17444. for (let i = 0, il = this.bones.length; i < il; i++) {
  17445. this.boneInverses.push(new Matrix4());
  17446. }
  17447. }
  17448. }
  17449. }
  17450. calculateInverses() {
  17451. this.boneInverses.length = 0;
  17452. for (let i = 0, il = this.bones.length; i < il; i++) {
  17453. const inverse = new Matrix4();
  17454. if (this.bones[i]) {
  17455. inverse.copy(this.bones[i].matrixWorld).invert();
  17456. }
  17457. this.boneInverses.push(inverse);
  17458. }
  17459. }
  17460. pose() {
  17461. // recover the bind-time world matrices
  17462. for (let i = 0, il = this.bones.length; i < il; i++) {
  17463. const bone = this.bones[i];
  17464. if (bone) {
  17465. bone.matrixWorld.copy(this.boneInverses[i]).invert();
  17466. }
  17467. } // compute the local matrices, positions, rotations and scales
  17468. for (let i = 0, il = this.bones.length; i < il; i++) {
  17469. const bone = this.bones[i];
  17470. if (bone) {
  17471. if (bone.parent && bone.parent.isBone) {
  17472. bone.matrix.copy(bone.parent.matrixWorld).invert();
  17473. bone.matrix.multiply(bone.matrixWorld);
  17474. } else {
  17475. bone.matrix.copy(bone.matrixWorld);
  17476. }
  17477. bone.matrix.decompose(bone.position, bone.quaternion, bone.scale);
  17478. }
  17479. }
  17480. }
  17481. update() {
  17482. const bones = this.bones;
  17483. const boneInverses = this.boneInverses;
  17484. const boneMatrices = this.boneMatrices;
  17485. const boneTexture = this.boneTexture; // flatten bone matrices to array
  17486. for (let i = 0, il = bones.length; i < il; i++) {
  17487. // compute the offset between the current and the original transform
  17488. const matrix = bones[i] ? bones[i].matrixWorld : _identityMatrix;
  17489. _offsetMatrix.multiplyMatrices(matrix, boneInverses[i]);
  17490. _offsetMatrix.toArray(boneMatrices, i * 16);
  17491. }
  17492. if (boneTexture !== null) {
  17493. boneTexture.needsUpdate = true;
  17494. }
  17495. }
  17496. clone() {
  17497. return new Skeleton(this.bones, this.boneInverses);
  17498. }
  17499. computeBoneTexture() {
  17500. // layout (1 matrix = 4 pixels)
  17501. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  17502. // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8)
  17503. // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16)
  17504. // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32)
  17505. // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64)
  17506. let size = Math.sqrt(this.bones.length * 4); // 4 pixels needed for 1 matrix
  17507. size = ceilPowerOfTwo(size);
  17508. size = Math.max(size, 4);
  17509. const boneMatrices = new Float32Array(size * size * 4); // 4 floats per RGBA pixel
  17510. boneMatrices.set(this.boneMatrices); // copy current values
  17511. const boneTexture = new DataTexture(boneMatrices, size, size, RGBAFormat, FloatType);
  17512. boneTexture.needsUpdate = true;
  17513. this.boneMatrices = boneMatrices;
  17514. this.boneTexture = boneTexture;
  17515. this.boneTextureSize = size;
  17516. return this;
  17517. }
  17518. getBoneByName(name) {
  17519. for (let i = 0, il = this.bones.length; i < il; i++) {
  17520. const bone = this.bones[i];
  17521. if (bone.name === name) {
  17522. return bone;
  17523. }
  17524. }
  17525. return undefined;
  17526. }
  17527. dispose() {
  17528. if (this.boneTexture !== null) {
  17529. this.boneTexture.dispose();
  17530. this.boneTexture = null;
  17531. }
  17532. }
  17533. fromJSON(json, bones) {
  17534. this.uuid = json.uuid;
  17535. for (let i = 0, l = json.bones.length; i < l; i++) {
  17536. const uuid = json.bones[i];
  17537. let bone = bones[uuid];
  17538. if (bone === undefined) {
  17539. console.warn('THREE.Skeleton: No bone found with UUID:', uuid);
  17540. bone = new Bone();
  17541. }
  17542. this.bones.push(bone);
  17543. this.boneInverses.push(new Matrix4().fromArray(json.boneInverses[i]));
  17544. }
  17545. this.init();
  17546. return this;
  17547. }
  17548. toJSON() {
  17549. const data = {
  17550. metadata: {
  17551. version: 4.5,
  17552. type: 'Skeleton',
  17553. generator: 'Skeleton.toJSON'
  17554. },
  17555. bones: [],
  17556. boneInverses: []
  17557. };
  17558. data.uuid = this.uuid;
  17559. const bones = this.bones;
  17560. const boneInverses = this.boneInverses;
  17561. for (let i = 0, l = bones.length; i < l; i++) {
  17562. const bone = bones[i];
  17563. data.bones.push(bone.uuid);
  17564. const boneInverse = boneInverses[i];
  17565. data.boneInverses.push(boneInverse.toArray());
  17566. }
  17567. return data;
  17568. }
  17569. }
  17570. class InstancedBufferAttribute extends BufferAttribute {
  17571. constructor(array, itemSize, normalized, meshPerAttribute = 1) {
  17572. if (typeof normalized === 'number') {
  17573. meshPerAttribute = normalized;
  17574. normalized = false;
  17575. console.error('THREE.InstancedBufferAttribute: The constructor now expects normalized as the third argument.');
  17576. }
  17577. super(array, itemSize, normalized);
  17578. this.isInstancedBufferAttribute = true;
  17579. this.meshPerAttribute = meshPerAttribute;
  17580. }
  17581. copy(source) {
  17582. super.copy(source);
  17583. this.meshPerAttribute = source.meshPerAttribute;
  17584. return this;
  17585. }
  17586. toJSON() {
  17587. const data = super.toJSON();
  17588. data.meshPerAttribute = this.meshPerAttribute;
  17589. data.isInstancedBufferAttribute = true;
  17590. return data;
  17591. }
  17592. }
  17593. const _instanceLocalMatrix = /*@__PURE__*/new Matrix4();
  17594. const _instanceWorldMatrix = /*@__PURE__*/new Matrix4();
  17595. const _instanceIntersects = [];
  17596. const _mesh = /*@__PURE__*/new Mesh();
  17597. class InstancedMesh extends Mesh {
  17598. constructor(geometry, material, count) {
  17599. super(geometry, material);
  17600. this.isInstancedMesh = true;
  17601. this.instanceMatrix = new InstancedBufferAttribute(new Float32Array(count * 16), 16);
  17602. this.instanceColor = null;
  17603. this.count = count;
  17604. this.frustumCulled = false;
  17605. }
  17606. copy(source) {
  17607. super.copy(source);
  17608. this.instanceMatrix.copy(source.instanceMatrix);
  17609. if (source.instanceColor !== null) this.instanceColor = source.instanceColor.clone();
  17610. this.count = source.count;
  17611. return this;
  17612. }
  17613. getColorAt(index, color) {
  17614. color.fromArray(this.instanceColor.array, index * 3);
  17615. }
  17616. getMatrixAt(index, matrix) {
  17617. matrix.fromArray(this.instanceMatrix.array, index * 16);
  17618. }
  17619. raycast(raycaster, intersects) {
  17620. const matrixWorld = this.matrixWorld;
  17621. const raycastTimes = this.count;
  17622. _mesh.geometry = this.geometry;
  17623. _mesh.material = this.material;
  17624. if (_mesh.material === undefined) return;
  17625. for (let instanceId = 0; instanceId < raycastTimes; instanceId++) {
  17626. // calculate the world matrix for each instance
  17627. this.getMatrixAt(instanceId, _instanceLocalMatrix);
  17628. _instanceWorldMatrix.multiplyMatrices(matrixWorld, _instanceLocalMatrix); // the mesh represents this single instance
  17629. _mesh.matrixWorld = _instanceWorldMatrix;
  17630. _mesh.raycast(raycaster, _instanceIntersects); // process the result of raycast
  17631. for (let i = 0, l = _instanceIntersects.length; i < l; i++) {
  17632. const intersect = _instanceIntersects[i];
  17633. intersect.instanceId = instanceId;
  17634. intersect.object = this;
  17635. intersects.push(intersect);
  17636. }
  17637. _instanceIntersects.length = 0;
  17638. }
  17639. }
  17640. setColorAt(index, color) {
  17641. if (this.instanceColor === null) {
  17642. this.instanceColor = new InstancedBufferAttribute(new Float32Array(this.instanceMatrix.count * 3), 3);
  17643. }
  17644. color.toArray(this.instanceColor.array, index * 3);
  17645. }
  17646. setMatrixAt(index, matrix) {
  17647. matrix.toArray(this.instanceMatrix.array, index * 16);
  17648. }
  17649. updateMorphTargets() {}
  17650. dispose() {
  17651. this.dispatchEvent({
  17652. type: 'dispose'
  17653. });
  17654. }
  17655. }
  17656. class LineBasicMaterial extends Material {
  17657. constructor(parameters) {
  17658. super();
  17659. this.isLineBasicMaterial = true;
  17660. this.type = 'LineBasicMaterial';
  17661. this.color = new Color(0xffffff);
  17662. this.linewidth = 1;
  17663. this.linecap = 'round';
  17664. this.linejoin = 'round';
  17665. this.fog = true;
  17666. this.setValues(parameters);
  17667. }
  17668. copy(source) {
  17669. super.copy(source);
  17670. this.color.copy(source.color);
  17671. this.linewidth = source.linewidth;
  17672. this.linecap = source.linecap;
  17673. this.linejoin = source.linejoin;
  17674. this.fog = source.fog;
  17675. return this;
  17676. }
  17677. }
  17678. const _start$1 = /*@__PURE__*/new Vector3();
  17679. const _end$1 = /*@__PURE__*/new Vector3();
  17680. const _inverseMatrix$1 = /*@__PURE__*/new Matrix4();
  17681. const _ray$1 = /*@__PURE__*/new Ray();
  17682. const _sphere$1 = /*@__PURE__*/new Sphere();
  17683. class Line extends Object3D {
  17684. constructor(geometry = new BufferGeometry(), material = new LineBasicMaterial()) {
  17685. super();
  17686. this.isLine = true;
  17687. this.type = 'Line';
  17688. this.geometry = geometry;
  17689. this.material = material;
  17690. this.updateMorphTargets();
  17691. }
  17692. copy(source) {
  17693. super.copy(source);
  17694. this.material = source.material;
  17695. this.geometry = source.geometry;
  17696. return this;
  17697. }
  17698. computeLineDistances() {
  17699. const geometry = this.geometry;
  17700. if (geometry.isBufferGeometry) {
  17701. // we assume non-indexed geometry
  17702. if (geometry.index === null) {
  17703. const positionAttribute = geometry.attributes.position;
  17704. const lineDistances = [0];
  17705. for (let i = 1, l = positionAttribute.count; i < l; i++) {
  17706. _start$1.fromBufferAttribute(positionAttribute, i - 1);
  17707. _end$1.fromBufferAttribute(positionAttribute, i);
  17708. lineDistances[i] = lineDistances[i - 1];
  17709. lineDistances[i] += _start$1.distanceTo(_end$1);
  17710. }
  17711. geometry.setAttribute('lineDistance', new Float32BufferAttribute(lineDistances, 1));
  17712. } else {
  17713. console.warn('THREE.Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.');
  17714. }
  17715. } else if (geometry.isGeometry) {
  17716. console.error('THREE.Line.computeLineDistances() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');
  17717. }
  17718. return this;
  17719. }
  17720. raycast(raycaster, intersects) {
  17721. const geometry = this.geometry;
  17722. const matrixWorld = this.matrixWorld;
  17723. const threshold = raycaster.params.Line.threshold;
  17724. const drawRange = geometry.drawRange; // Checking boundingSphere distance to ray
  17725. if (geometry.boundingSphere === null) geometry.computeBoundingSphere();
  17726. _sphere$1.copy(geometry.boundingSphere);
  17727. _sphere$1.applyMatrix4(matrixWorld);
  17728. _sphere$1.radius += threshold;
  17729. if (raycaster.ray.intersectsSphere(_sphere$1) === false) return; //
  17730. _inverseMatrix$1.copy(matrixWorld).invert();
  17731. _ray$1.copy(raycaster.ray).applyMatrix4(_inverseMatrix$1);
  17732. const localThreshold = threshold / ((this.scale.x + this.scale.y + this.scale.z) / 3);
  17733. const localThresholdSq = localThreshold * localThreshold;
  17734. const vStart = new Vector3();
  17735. const vEnd = new Vector3();
  17736. const interSegment = new Vector3();
  17737. const interRay = new Vector3();
  17738. const step = this.isLineSegments ? 2 : 1;
  17739. if (geometry.isBufferGeometry) {
  17740. const index = geometry.index;
  17741. const attributes = geometry.attributes;
  17742. const positionAttribute = attributes.position;
  17743. if (index !== null) {
  17744. const start = Math.max(0, drawRange.start);
  17745. const end = Math.min(index.count, drawRange.start + drawRange.count);
  17746. for (let i = start, l = end - 1; i < l; i += step) {
  17747. const a = index.getX(i);
  17748. const b = index.getX(i + 1);
  17749. vStart.fromBufferAttribute(positionAttribute, a);
  17750. vEnd.fromBufferAttribute(positionAttribute, b);
  17751. const distSq = _ray$1.distanceSqToSegment(vStart, vEnd, interRay, interSegment);
  17752. if (distSq > localThresholdSq) continue;
  17753. interRay.applyMatrix4(this.matrixWorld); //Move back to world space for distance calculation
  17754. const distance = raycaster.ray.origin.distanceTo(interRay);
  17755. if (distance < raycaster.near || distance > raycaster.far) continue;
  17756. intersects.push({
  17757. distance: distance,
  17758. // What do we want? intersection point on the ray or on the segment??
  17759. // point: raycaster.ray.at( distance ),
  17760. point: interSegment.clone().applyMatrix4(this.matrixWorld),
  17761. index: i,
  17762. face: null,
  17763. faceIndex: null,
  17764. object: this
  17765. });
  17766. }
  17767. } else {
  17768. const start = Math.max(0, drawRange.start);
  17769. const end = Math.min(positionAttribute.count, drawRange.start + drawRange.count);
  17770. for (let i = start, l = end - 1; i < l; i += step) {
  17771. vStart.fromBufferAttribute(positionAttribute, i);
  17772. vEnd.fromBufferAttribute(positionAttribute, i + 1);
  17773. const distSq = _ray$1.distanceSqToSegment(vStart, vEnd, interRay, interSegment);
  17774. if (distSq > localThresholdSq) continue;
  17775. interRay.applyMatrix4(this.matrixWorld); //Move back to world space for distance calculation
  17776. const distance = raycaster.ray.origin.distanceTo(interRay);
  17777. if (distance < raycaster.near || distance > raycaster.far) continue;
  17778. intersects.push({
  17779. distance: distance,
  17780. // What do we want? intersection point on the ray or on the segment??
  17781. // point: raycaster.ray.at( distance ),
  17782. point: interSegment.clone().applyMatrix4(this.matrixWorld),
  17783. index: i,
  17784. face: null,
  17785. faceIndex: null,
  17786. object: this
  17787. });
  17788. }
  17789. }
  17790. } else if (geometry.isGeometry) {
  17791. console.error('THREE.Line.raycast() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');
  17792. }
  17793. }
  17794. updateMorphTargets() {
  17795. const geometry = this.geometry;
  17796. if (geometry.isBufferGeometry) {
  17797. const morphAttributes = geometry.morphAttributes;
  17798. const keys = Object.keys(morphAttributes);
  17799. if (keys.length > 0) {
  17800. const morphAttribute = morphAttributes[keys[0]];
  17801. if (morphAttribute !== undefined) {
  17802. this.morphTargetInfluences = [];
  17803. this.morphTargetDictionary = {};
  17804. for (let m = 0, ml = morphAttribute.length; m < ml; m++) {
  17805. const name = morphAttribute[m].name || String(m);
  17806. this.morphTargetInfluences.push(0);
  17807. this.morphTargetDictionary[name] = m;
  17808. }
  17809. }
  17810. }
  17811. } else {
  17812. const morphTargets = geometry.morphTargets;
  17813. if (morphTargets !== undefined && morphTargets.length > 0) {
  17814. console.error('THREE.Line.updateMorphTargets() does not support THREE.Geometry. Use THREE.BufferGeometry instead.');
  17815. }
  17816. }
  17817. }
  17818. }
  17819. const _start = /*@__PURE__*/new Vector3();
  17820. const _end = /*@__PURE__*/new Vector3();
  17821. class LineSegments extends Line {
  17822. constructor(geometry, material) {
  17823. super(geometry, material);
  17824. this.isLineSegments = true;
  17825. this.type = 'LineSegments';
  17826. }
  17827. computeLineDistances() {
  17828. const geometry = this.geometry;
  17829. if (geometry.isBufferGeometry) {
  17830. // we assume non-indexed geometry
  17831. if (geometry.index === null) {
  17832. const positionAttribute = geometry.attributes.position;
  17833. const lineDistances = [];
  17834. for (let i = 0, l = positionAttribute.count; i < l; i += 2) {
  17835. _start.fromBufferAttribute(positionAttribute, i);
  17836. _end.fromBufferAttribute(positionAttribute, i + 1);
  17837. lineDistances[i] = i === 0 ? 0 : lineDistances[i - 1];
  17838. lineDistances[i + 1] = lineDistances[i] + _start.distanceTo(_end);
  17839. }
  17840. geometry.setAttribute('lineDistance', new Float32BufferAttribute(lineDistances, 1));
  17841. } else {
  17842. console.warn('THREE.LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.');
  17843. }
  17844. } else if (geometry.isGeometry) {
  17845. console.error('THREE.LineSegments.computeLineDistances() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');
  17846. }
  17847. return this;
  17848. }
  17849. }
  17850. class LineLoop extends Line {
  17851. constructor(geometry, material) {
  17852. super(geometry, material);
  17853. this.isLineLoop = true;
  17854. this.type = 'LineLoop';
  17855. }
  17856. }
  17857. class PointsMaterial extends Material {
  17858. constructor(parameters) {
  17859. super();
  17860. this.isPointsMaterial = true;
  17861. this.type = 'PointsMaterial';
  17862. this.color = new Color(0xffffff);
  17863. this.map = null;
  17864. this.alphaMap = null;
  17865. this.size = 1;
  17866. this.sizeAttenuation = true;
  17867. this.fog = true;
  17868. this.setValues(parameters);
  17869. }
  17870. copy(source) {
  17871. super.copy(source);
  17872. this.color.copy(source.color);
  17873. this.map = source.map;
  17874. this.alphaMap = source.alphaMap;
  17875. this.size = source.size;
  17876. this.sizeAttenuation = source.sizeAttenuation;
  17877. this.fog = source.fog;
  17878. return this;
  17879. }
  17880. }
  17881. const _inverseMatrix = /*@__PURE__*/new Matrix4();
  17882. const _ray = /*@__PURE__*/new Ray();
  17883. const _sphere = /*@__PURE__*/new Sphere();
  17884. const _position$2 = /*@__PURE__*/new Vector3();
  17885. class Points extends Object3D {
  17886. constructor(geometry = new BufferGeometry(), material = new PointsMaterial()) {
  17887. super();
  17888. this.isPoints = true;
  17889. this.type = 'Points';
  17890. this.geometry = geometry;
  17891. this.material = material;
  17892. this.updateMorphTargets();
  17893. }
  17894. copy(source) {
  17895. super.copy(source);
  17896. this.material = source.material;
  17897. this.geometry = source.geometry;
  17898. return this;
  17899. }
  17900. raycast(raycaster, intersects) {
  17901. const geometry = this.geometry;
  17902. const matrixWorld = this.matrixWorld;
  17903. const threshold = raycaster.params.Points.threshold;
  17904. const drawRange = geometry.drawRange; // Checking boundingSphere distance to ray
  17905. if (geometry.boundingSphere === null) geometry.computeBoundingSphere();
  17906. _sphere.copy(geometry.boundingSphere);
  17907. _sphere.applyMatrix4(matrixWorld);
  17908. _sphere.radius += threshold;
  17909. if (raycaster.ray.intersectsSphere(_sphere) === false) return; //
  17910. _inverseMatrix.copy(matrixWorld).invert();
  17911. _ray.copy(raycaster.ray).applyMatrix4(_inverseMatrix);
  17912. const localThreshold = threshold / ((this.scale.x + this.scale.y + this.scale.z) / 3);
  17913. const localThresholdSq = localThreshold * localThreshold;
  17914. if (geometry.isBufferGeometry) {
  17915. const index = geometry.index;
  17916. const attributes = geometry.attributes;
  17917. const positionAttribute = attributes.position;
  17918. if (index !== null) {
  17919. const start = Math.max(0, drawRange.start);
  17920. const end = Math.min(index.count, drawRange.start + drawRange.count);
  17921. for (let i = start, il = end; i < il; i++) {
  17922. const a = index.getX(i);
  17923. _position$2.fromBufferAttribute(positionAttribute, a);
  17924. testPoint(_position$2, a, localThresholdSq, matrixWorld, raycaster, intersects, this);
  17925. }
  17926. } else {
  17927. const start = Math.max(0, drawRange.start);
  17928. const end = Math.min(positionAttribute.count, drawRange.start + drawRange.count);
  17929. for (let i = start, l = end; i < l; i++) {
  17930. _position$2.fromBufferAttribute(positionAttribute, i);
  17931. testPoint(_position$2, i, localThresholdSq, matrixWorld, raycaster, intersects, this);
  17932. }
  17933. }
  17934. } else {
  17935. console.error('THREE.Points.raycast() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');
  17936. }
  17937. }
  17938. updateMorphTargets() {
  17939. const geometry = this.geometry;
  17940. if (geometry.isBufferGeometry) {
  17941. const morphAttributes = geometry.morphAttributes;
  17942. const keys = Object.keys(morphAttributes);
  17943. if (keys.length > 0) {
  17944. const morphAttribute = morphAttributes[keys[0]];
  17945. if (morphAttribute !== undefined) {
  17946. this.morphTargetInfluences = [];
  17947. this.morphTargetDictionary = {};
  17948. for (let m = 0, ml = morphAttribute.length; m < ml; m++) {
  17949. const name = morphAttribute[m].name || String(m);
  17950. this.morphTargetInfluences.push(0);
  17951. this.morphTargetDictionary[name] = m;
  17952. }
  17953. }
  17954. }
  17955. } else {
  17956. const morphTargets = geometry.morphTargets;
  17957. if (morphTargets !== undefined && morphTargets.length > 0) {
  17958. console.error('THREE.Points.updateMorphTargets() does not support THREE.Geometry. Use THREE.BufferGeometry instead.');
  17959. }
  17960. }
  17961. }
  17962. }
  17963. function testPoint(point, index, localThresholdSq, matrixWorld, raycaster, intersects, object) {
  17964. const rayPointDistanceSq = _ray.distanceSqToPoint(point);
  17965. if (rayPointDistanceSq < localThresholdSq) {
  17966. const intersectPoint = new Vector3();
  17967. _ray.closestPointToPoint(point, intersectPoint);
  17968. intersectPoint.applyMatrix4(matrixWorld);
  17969. const distance = raycaster.ray.origin.distanceTo(intersectPoint);
  17970. if (distance < raycaster.near || distance > raycaster.far) return;
  17971. intersects.push({
  17972. distance: distance,
  17973. distanceToRay: Math.sqrt(rayPointDistanceSq),
  17974. point: intersectPoint,
  17975. index: index,
  17976. face: null,
  17977. object: object
  17978. });
  17979. }
  17980. }
  17981. class VideoTexture extends Texture {
  17982. constructor(video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy) {
  17983. super(video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy);
  17984. this.isVideoTexture = true;
  17985. this.minFilter = minFilter !== undefined ? minFilter : LinearFilter;
  17986. this.magFilter = magFilter !== undefined ? magFilter : LinearFilter;
  17987. this.generateMipmaps = false;
  17988. const scope = this;
  17989. function updateVideo() {
  17990. scope.needsUpdate = true;
  17991. video.requestVideoFrameCallback(updateVideo);
  17992. }
  17993. if ('requestVideoFrameCallback' in video) {
  17994. video.requestVideoFrameCallback(updateVideo);
  17995. }
  17996. }
  17997. clone() {
  17998. return new this.constructor(this.image).copy(this);
  17999. }
  18000. update() {
  18001. const video = this.image;
  18002. const hasVideoFrameCallback = ('requestVideoFrameCallback' in video);
  18003. if (hasVideoFrameCallback === false && video.readyState >= video.HAVE_CURRENT_DATA) {
  18004. this.needsUpdate = true;
  18005. }
  18006. }
  18007. }
  18008. class FramebufferTexture extends Texture {
  18009. constructor(width, height, format) {
  18010. super({
  18011. width,
  18012. height
  18013. });
  18014. this.isFramebufferTexture = true;
  18015. this.format = format;
  18016. this.magFilter = NearestFilter;
  18017. this.minFilter = NearestFilter;
  18018. this.generateMipmaps = false;
  18019. this.needsUpdate = true;
  18020. }
  18021. }
  18022. class CompressedTexture extends Texture {
  18023. constructor(mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding) {
  18024. super(null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding);
  18025. this.isCompressedTexture = true;
  18026. this.image = {
  18027. width: width,
  18028. height: height
  18029. };
  18030. this.mipmaps = mipmaps; // no flipping for cube textures
  18031. // (also flipping doesn't work for compressed textures )
  18032. this.flipY = false; // can't generate mipmaps for compressed textures
  18033. // mips must be embedded in DDS files
  18034. this.generateMipmaps = false;
  18035. }
  18036. }
  18037. class CanvasTexture extends Texture {
  18038. constructor(canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy) {
  18039. super(canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy);
  18040. this.isCanvasTexture = true;
  18041. this.needsUpdate = true;
  18042. }
  18043. }
  18044. /**
  18045. * Extensible curve object.
  18046. *
  18047. * Some common of curve methods:
  18048. * .getPoint( t, optionalTarget ), .getTangent( t, optionalTarget )
  18049. * .getPointAt( u, optionalTarget ), .getTangentAt( u, optionalTarget )
  18050. * .getPoints(), .getSpacedPoints()
  18051. * .getLength()
  18052. * .updateArcLengths()
  18053. *
  18054. * This following curves inherit from THREE.Curve:
  18055. *
  18056. * -- 2D curves --
  18057. * THREE.ArcCurve
  18058. * THREE.CubicBezierCurve
  18059. * THREE.EllipseCurve
  18060. * THREE.LineCurve
  18061. * THREE.QuadraticBezierCurve
  18062. * THREE.SplineCurve
  18063. *
  18064. * -- 3D curves --
  18065. * THREE.CatmullRomCurve3
  18066. * THREE.CubicBezierCurve3
  18067. * THREE.LineCurve3
  18068. * THREE.QuadraticBezierCurve3
  18069. *
  18070. * A series of curves can be represented as a THREE.CurvePath.
  18071. *
  18072. **/
  18073. class Curve {
  18074. constructor() {
  18075. this.type = 'Curve';
  18076. this.arcLengthDivisions = 200;
  18077. } // Virtual base class method to overwrite and implement in subclasses
  18078. // - t [0 .. 1]
  18079. getPoint() {
  18080. console.warn('THREE.Curve: .getPoint() not implemented.');
  18081. return null;
  18082. } // Get point at relative position in curve according to arc length
  18083. // - u [0 .. 1]
  18084. getPointAt(u, optionalTarget) {
  18085. const t = this.getUtoTmapping(u);
  18086. return this.getPoint(t, optionalTarget);
  18087. } // Get sequence of points using getPoint( t )
  18088. getPoints(divisions = 5) {
  18089. const points = [];
  18090. for (let d = 0; d <= divisions; d++) {
  18091. points.push(this.getPoint(d / divisions));
  18092. }
  18093. return points;
  18094. } // Get sequence of points using getPointAt( u )
  18095. getSpacedPoints(divisions = 5) {
  18096. const points = [];
  18097. for (let d = 0; d <= divisions; d++) {
  18098. points.push(this.getPointAt(d / divisions));
  18099. }
  18100. return points;
  18101. } // Get total curve arc length
  18102. getLength() {
  18103. const lengths = this.getLengths();
  18104. return lengths[lengths.length - 1];
  18105. } // Get list of cumulative segment lengths
  18106. getLengths(divisions = this.arcLengthDivisions) {
  18107. if (this.cacheArcLengths && this.cacheArcLengths.length === divisions + 1 && !this.needsUpdate) {
  18108. return this.cacheArcLengths;
  18109. }
  18110. this.needsUpdate = false;
  18111. const cache = [];
  18112. let current,
  18113. last = this.getPoint(0);
  18114. let sum = 0;
  18115. cache.push(0);
  18116. for (let p = 1; p <= divisions; p++) {
  18117. current = this.getPoint(p / divisions);
  18118. sum += current.distanceTo(last);
  18119. cache.push(sum);
  18120. last = current;
  18121. }
  18122. this.cacheArcLengths = cache;
  18123. return cache; // { sums: cache, sum: sum }; Sum is in the last element.
  18124. }
  18125. updateArcLengths() {
  18126. this.needsUpdate = true;
  18127. this.getLengths();
  18128. } // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equidistant
  18129. getUtoTmapping(u, distance) {
  18130. const arcLengths = this.getLengths();
  18131. let i = 0;
  18132. const il = arcLengths.length;
  18133. let targetArcLength; // The targeted u distance value to get
  18134. if (distance) {
  18135. targetArcLength = distance;
  18136. } else {
  18137. targetArcLength = u * arcLengths[il - 1];
  18138. } // binary search for the index with largest value smaller than target u distance
  18139. let low = 0,
  18140. high = il - 1,
  18141. comparison;
  18142. while (low <= high) {
  18143. 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
  18144. comparison = arcLengths[i] - targetArcLength;
  18145. if (comparison < 0) {
  18146. low = i + 1;
  18147. } else if (comparison > 0) {
  18148. high = i - 1;
  18149. } else {
  18150. high = i;
  18151. break; // DONE
  18152. }
  18153. }
  18154. i = high;
  18155. if (arcLengths[i] === targetArcLength) {
  18156. return i / (il - 1);
  18157. } // we could get finer grain at lengths, or use simple interpolation between two points
  18158. const lengthBefore = arcLengths[i];
  18159. const lengthAfter = arcLengths[i + 1];
  18160. const segmentLength = lengthAfter - lengthBefore; // determine where we are between the 'before' and 'after' points
  18161. const segmentFraction = (targetArcLength - lengthBefore) / segmentLength; // add that fractional amount to t
  18162. const t = (i + segmentFraction) / (il - 1);
  18163. return t;
  18164. } // Returns a unit vector tangent at t
  18165. // In case any sub curve does not implement its tangent derivation,
  18166. // 2 points a small delta apart will be used to find its gradient
  18167. // which seems to give a reasonable approximation
  18168. getTangent(t, optionalTarget) {
  18169. const delta = 0.0001;
  18170. let t1 = t - delta;
  18171. let t2 = t + delta; // Capping in case of danger
  18172. if (t1 < 0) t1 = 0;
  18173. if (t2 > 1) t2 = 1;
  18174. const pt1 = this.getPoint(t1);
  18175. const pt2 = this.getPoint(t2);
  18176. const tangent = optionalTarget || (pt1.isVector2 ? new Vector2() : new Vector3());
  18177. tangent.copy(pt2).sub(pt1).normalize();
  18178. return tangent;
  18179. }
  18180. getTangentAt(u, optionalTarget) {
  18181. const t = this.getUtoTmapping(u);
  18182. return this.getTangent(t, optionalTarget);
  18183. }
  18184. computeFrenetFrames(segments, closed) {
  18185. // see http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  18186. const normal = new Vector3();
  18187. const tangents = [];
  18188. const normals = [];
  18189. const binormals = [];
  18190. const vec = new Vector3();
  18191. const mat = new Matrix4(); // compute the tangent vectors for each segment on the curve
  18192. for (let i = 0; i <= segments; i++) {
  18193. const u = i / segments;
  18194. tangents[i] = this.getTangentAt(u, new Vector3());
  18195. } // select an initial normal vector perpendicular to the first tangent vector,
  18196. // and in the direction of the minimum tangent xyz component
  18197. normals[0] = new Vector3();
  18198. binormals[0] = new Vector3();
  18199. let min = Number.MAX_VALUE;
  18200. const tx = Math.abs(tangents[0].x);
  18201. const ty = Math.abs(tangents[0].y);
  18202. const tz = Math.abs(tangents[0].z);
  18203. if (tx <= min) {
  18204. min = tx;
  18205. normal.set(1, 0, 0);
  18206. }
  18207. if (ty <= min) {
  18208. min = ty;
  18209. normal.set(0, 1, 0);
  18210. }
  18211. if (tz <= min) {
  18212. normal.set(0, 0, 1);
  18213. }
  18214. vec.crossVectors(tangents[0], normal).normalize();
  18215. normals[0].crossVectors(tangents[0], vec);
  18216. binormals[0].crossVectors(tangents[0], normals[0]); // compute the slowly-varying normal and binormal vectors for each segment on the curve
  18217. for (let i = 1; i <= segments; i++) {
  18218. normals[i] = normals[i - 1].clone();
  18219. binormals[i] = binormals[i - 1].clone();
  18220. vec.crossVectors(tangents[i - 1], tangents[i]);
  18221. if (vec.length() > Number.EPSILON) {
  18222. vec.normalize();
  18223. const theta = Math.acos(clamp(tangents[i - 1].dot(tangents[i]), -1, 1)); // clamp for floating pt errors
  18224. normals[i].applyMatrix4(mat.makeRotationAxis(vec, theta));
  18225. }
  18226. binormals[i].crossVectors(tangents[i], normals[i]);
  18227. } // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  18228. if (closed === true) {
  18229. let theta = Math.acos(clamp(normals[0].dot(normals[segments]), -1, 1));
  18230. theta /= segments;
  18231. if (tangents[0].dot(vec.crossVectors(normals[0], normals[segments])) > 0) {
  18232. theta = -theta;
  18233. }
  18234. for (let i = 1; i <= segments; i++) {
  18235. // twist a little...
  18236. normals[i].applyMatrix4(mat.makeRotationAxis(tangents[i], theta * i));
  18237. binormals[i].crossVectors(tangents[i], normals[i]);
  18238. }
  18239. }
  18240. return {
  18241. tangents: tangents,
  18242. normals: normals,
  18243. binormals: binormals
  18244. };
  18245. }
  18246. clone() {
  18247. return new this.constructor().copy(this);
  18248. }
  18249. copy(source) {
  18250. this.arcLengthDivisions = source.arcLengthDivisions;
  18251. return this;
  18252. }
  18253. toJSON() {
  18254. const data = {
  18255. metadata: {
  18256. version: 4.5,
  18257. type: 'Curve',
  18258. generator: 'Curve.toJSON'
  18259. }
  18260. };
  18261. data.arcLengthDivisions = this.arcLengthDivisions;
  18262. data.type = this.type;
  18263. return data;
  18264. }
  18265. fromJSON(json) {
  18266. this.arcLengthDivisions = json.arcLengthDivisions;
  18267. return this;
  18268. }
  18269. }
  18270. class EllipseCurve extends Curve {
  18271. constructor(aX = 0, aY = 0, xRadius = 1, yRadius = 1, aStartAngle = 0, aEndAngle = Math.PI * 2, aClockwise = false, aRotation = 0) {
  18272. super();
  18273. this.isEllipseCurve = true;
  18274. this.type = 'EllipseCurve';
  18275. this.aX = aX;
  18276. this.aY = aY;
  18277. this.xRadius = xRadius;
  18278. this.yRadius = yRadius;
  18279. this.aStartAngle = aStartAngle;
  18280. this.aEndAngle = aEndAngle;
  18281. this.aClockwise = aClockwise;
  18282. this.aRotation = aRotation;
  18283. }
  18284. getPoint(t, optionalTarget) {
  18285. const point = optionalTarget || new Vector2();
  18286. const twoPi = Math.PI * 2;
  18287. let deltaAngle = this.aEndAngle - this.aStartAngle;
  18288. const samePoints = Math.abs(deltaAngle) < Number.EPSILON; // ensures that deltaAngle is 0 .. 2 PI
  18289. while (deltaAngle < 0) deltaAngle += twoPi;
  18290. while (deltaAngle > twoPi) deltaAngle -= twoPi;
  18291. if (deltaAngle < Number.EPSILON) {
  18292. if (samePoints) {
  18293. deltaAngle = 0;
  18294. } else {
  18295. deltaAngle = twoPi;
  18296. }
  18297. }
  18298. if (this.aClockwise === true && !samePoints) {
  18299. if (deltaAngle === twoPi) {
  18300. deltaAngle = -twoPi;
  18301. } else {
  18302. deltaAngle = deltaAngle - twoPi;
  18303. }
  18304. }
  18305. const angle = this.aStartAngle + t * deltaAngle;
  18306. let x = this.aX + this.xRadius * Math.cos(angle);
  18307. let y = this.aY + this.yRadius * Math.sin(angle);
  18308. if (this.aRotation !== 0) {
  18309. const cos = Math.cos(this.aRotation);
  18310. const sin = Math.sin(this.aRotation);
  18311. const tx = x - this.aX;
  18312. const ty = y - this.aY; // Rotate the point about the center of the ellipse.
  18313. x = tx * cos - ty * sin + this.aX;
  18314. y = tx * sin + ty * cos + this.aY;
  18315. }
  18316. return point.set(x, y);
  18317. }
  18318. copy(source) {
  18319. super.copy(source);
  18320. this.aX = source.aX;
  18321. this.aY = source.aY;
  18322. this.xRadius = source.xRadius;
  18323. this.yRadius = source.yRadius;
  18324. this.aStartAngle = source.aStartAngle;
  18325. this.aEndAngle = source.aEndAngle;
  18326. this.aClockwise = source.aClockwise;
  18327. this.aRotation = source.aRotation;
  18328. return this;
  18329. }
  18330. toJSON() {
  18331. const data = super.toJSON();
  18332. data.aX = this.aX;
  18333. data.aY = this.aY;
  18334. data.xRadius = this.xRadius;
  18335. data.yRadius = this.yRadius;
  18336. data.aStartAngle = this.aStartAngle;
  18337. data.aEndAngle = this.aEndAngle;
  18338. data.aClockwise = this.aClockwise;
  18339. data.aRotation = this.aRotation;
  18340. return data;
  18341. }
  18342. fromJSON(json) {
  18343. super.fromJSON(json);
  18344. this.aX = json.aX;
  18345. this.aY = json.aY;
  18346. this.xRadius = json.xRadius;
  18347. this.yRadius = json.yRadius;
  18348. this.aStartAngle = json.aStartAngle;
  18349. this.aEndAngle = json.aEndAngle;
  18350. this.aClockwise = json.aClockwise;
  18351. this.aRotation = json.aRotation;
  18352. return this;
  18353. }
  18354. }
  18355. class ArcCurve extends EllipseCurve {
  18356. constructor(aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise) {
  18357. super(aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise);
  18358. this.isArcCurve = true;
  18359. this.type = 'ArcCurve';
  18360. }
  18361. }
  18362. /**
  18363. * Centripetal CatmullRom Curve - which is useful for avoiding
  18364. * cusps and self-intersections in non-uniform catmull rom curves.
  18365. * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf
  18366. *
  18367. * curve.type accepts centripetal(default), chordal and catmullrom
  18368. * curve.tension is used for catmullrom which defaults to 0.5
  18369. */
  18370. /*
  18371. Based on an optimized c++ solution in
  18372. - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/
  18373. - http://ideone.com/NoEbVM
  18374. This CubicPoly class could be used for reusing some variables and calculations,
  18375. but for three.js curve use, it could be possible inlined and flatten into a single function call
  18376. which can be placed in CurveUtils.
  18377. */
  18378. function CubicPoly() {
  18379. let c0 = 0,
  18380. c1 = 0,
  18381. c2 = 0,
  18382. c3 = 0;
  18383. /*
  18384. * Compute coefficients for a cubic polynomial
  18385. * p(s) = c0 + c1*s + c2*s^2 + c3*s^3
  18386. * such that
  18387. * p(0) = x0, p(1) = x1
  18388. * and
  18389. * p'(0) = t0, p'(1) = t1.
  18390. */
  18391. function init(x0, x1, t0, t1) {
  18392. c0 = x0;
  18393. c1 = t0;
  18394. c2 = -3 * x0 + 3 * x1 - 2 * t0 - t1;
  18395. c3 = 2 * x0 - 2 * x1 + t0 + t1;
  18396. }
  18397. return {
  18398. initCatmullRom: function (x0, x1, x2, x3, tension) {
  18399. init(x1, x2, tension * (x2 - x0), tension * (x3 - x1));
  18400. },
  18401. initNonuniformCatmullRom: function (x0, x1, x2, x3, dt0, dt1, dt2) {
  18402. // compute tangents when parameterized in [t1,t2]
  18403. let t1 = (x1 - x0) / dt0 - (x2 - x0) / (dt0 + dt1) + (x2 - x1) / dt1;
  18404. let t2 = (x2 - x1) / dt1 - (x3 - x1) / (dt1 + dt2) + (x3 - x2) / dt2; // rescale tangents for parametrization in [0,1]
  18405. t1 *= dt1;
  18406. t2 *= dt1;
  18407. init(x1, x2, t1, t2);
  18408. },
  18409. calc: function (t) {
  18410. const t2 = t * t;
  18411. const t3 = t2 * t;
  18412. return c0 + c1 * t + c2 * t2 + c3 * t3;
  18413. }
  18414. };
  18415. } //
  18416. const tmp = new Vector3();
  18417. const px = new CubicPoly(),
  18418. py = new CubicPoly(),
  18419. pz = new CubicPoly();
  18420. class CatmullRomCurve3 extends Curve {
  18421. constructor(points = [], closed = false, curveType = 'centripetal', tension = 0.5) {
  18422. super();
  18423. this.isCatmullRomCurve3 = true;
  18424. this.type = 'CatmullRomCurve3';
  18425. this.points = points;
  18426. this.closed = closed;
  18427. this.curveType = curveType;
  18428. this.tension = tension;
  18429. }
  18430. getPoint(t, optionalTarget = new Vector3()) {
  18431. const point = optionalTarget;
  18432. const points = this.points;
  18433. const l = points.length;
  18434. const p = (l - (this.closed ? 0 : 1)) * t;
  18435. let intPoint = Math.floor(p);
  18436. let weight = p - intPoint;
  18437. if (this.closed) {
  18438. intPoint += intPoint > 0 ? 0 : (Math.floor(Math.abs(intPoint) / l) + 1) * l;
  18439. } else if (weight === 0 && intPoint === l - 1) {
  18440. intPoint = l - 2;
  18441. weight = 1;
  18442. }
  18443. let p0, p3; // 4 points (p1 & p2 defined below)
  18444. if (this.closed || intPoint > 0) {
  18445. p0 = points[(intPoint - 1) % l];
  18446. } else {
  18447. // extrapolate first point
  18448. tmp.subVectors(points[0], points[1]).add(points[0]);
  18449. p0 = tmp;
  18450. }
  18451. const p1 = points[intPoint % l];
  18452. const p2 = points[(intPoint + 1) % l];
  18453. if (this.closed || intPoint + 2 < l) {
  18454. p3 = points[(intPoint + 2) % l];
  18455. } else {
  18456. // extrapolate last point
  18457. tmp.subVectors(points[l - 1], points[l - 2]).add(points[l - 1]);
  18458. p3 = tmp;
  18459. }
  18460. if (this.curveType === 'centripetal' || this.curveType === 'chordal') {
  18461. // init Centripetal / Chordal Catmull-Rom
  18462. const pow = this.curveType === 'chordal' ? 0.5 : 0.25;
  18463. let dt0 = Math.pow(p0.distanceToSquared(p1), pow);
  18464. let dt1 = Math.pow(p1.distanceToSquared(p2), pow);
  18465. let dt2 = Math.pow(p2.distanceToSquared(p3), pow); // safety check for repeated points
  18466. if (dt1 < 1e-4) dt1 = 1.0;
  18467. if (dt0 < 1e-4) dt0 = dt1;
  18468. if (dt2 < 1e-4) dt2 = dt1;
  18469. px.initNonuniformCatmullRom(p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2);
  18470. py.initNonuniformCatmullRom(p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2);
  18471. pz.initNonuniformCatmullRom(p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2);
  18472. } else if (this.curveType === 'catmullrom') {
  18473. px.initCatmullRom(p0.x, p1.x, p2.x, p3.x, this.tension);
  18474. py.initCatmullRom(p0.y, p1.y, p2.y, p3.y, this.tension);
  18475. pz.initCatmullRom(p0.z, p1.z, p2.z, p3.z, this.tension);
  18476. }
  18477. point.set(px.calc(weight), py.calc(weight), pz.calc(weight));
  18478. return point;
  18479. }
  18480. copy(source) {
  18481. super.copy(source);
  18482. this.points = [];
  18483. for (let i = 0, l = source.points.length; i < l; i++) {
  18484. const point = source.points[i];
  18485. this.points.push(point.clone());
  18486. }
  18487. this.closed = source.closed;
  18488. this.curveType = source.curveType;
  18489. this.tension = source.tension;
  18490. return this;
  18491. }
  18492. toJSON() {
  18493. const data = super.toJSON();
  18494. data.points = [];
  18495. for (let i = 0, l = this.points.length; i < l; i++) {
  18496. const point = this.points[i];
  18497. data.points.push(point.toArray());
  18498. }
  18499. data.closed = this.closed;
  18500. data.curveType = this.curveType;
  18501. data.tension = this.tension;
  18502. return data;
  18503. }
  18504. fromJSON(json) {
  18505. super.fromJSON(json);
  18506. this.points = [];
  18507. for (let i = 0, l = json.points.length; i < l; i++) {
  18508. const point = json.points[i];
  18509. this.points.push(new Vector3().fromArray(point));
  18510. }
  18511. this.closed = json.closed;
  18512. this.curveType = json.curveType;
  18513. this.tension = json.tension;
  18514. return this;
  18515. }
  18516. }
  18517. /**
  18518. * Bezier Curves formulas obtained from
  18519. * https://en.wikipedia.org/wiki/B%C3%A9zier_curve
  18520. */
  18521. function CatmullRom(t, p0, p1, p2, p3) {
  18522. const v0 = (p2 - p0) * 0.5;
  18523. const v1 = (p3 - p1) * 0.5;
  18524. const t2 = t * t;
  18525. const t3 = t * t2;
  18526. return (2 * p1 - 2 * p2 + v0 + v1) * t3 + (-3 * p1 + 3 * p2 - 2 * v0 - v1) * t2 + v0 * t + p1;
  18527. } //
  18528. function QuadraticBezierP0(t, p) {
  18529. const k = 1 - t;
  18530. return k * k * p;
  18531. }
  18532. function QuadraticBezierP1(t, p) {
  18533. return 2 * (1 - t) * t * p;
  18534. }
  18535. function QuadraticBezierP2(t, p) {
  18536. return t * t * p;
  18537. }
  18538. function QuadraticBezier(t, p0, p1, p2) {
  18539. return QuadraticBezierP0(t, p0) + QuadraticBezierP1(t, p1) + QuadraticBezierP2(t, p2);
  18540. } //
  18541. function CubicBezierP0(t, p) {
  18542. const k = 1 - t;
  18543. return k * k * k * p;
  18544. }
  18545. function CubicBezierP1(t, p) {
  18546. const k = 1 - t;
  18547. return 3 * k * k * t * p;
  18548. }
  18549. function CubicBezierP2(t, p) {
  18550. return 3 * (1 - t) * t * t * p;
  18551. }
  18552. function CubicBezierP3(t, p) {
  18553. return t * t * t * p;
  18554. }
  18555. function CubicBezier(t, p0, p1, p2, p3) {
  18556. return CubicBezierP0(t, p0) + CubicBezierP1(t, p1) + CubicBezierP2(t, p2) + CubicBezierP3(t, p3);
  18557. }
  18558. class CubicBezierCurve extends Curve {
  18559. constructor(v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2(), v3 = new Vector2()) {
  18560. super();
  18561. this.isCubicBezierCurve = true;
  18562. this.type = 'CubicBezierCurve';
  18563. this.v0 = v0;
  18564. this.v1 = v1;
  18565. this.v2 = v2;
  18566. this.v3 = v3;
  18567. }
  18568. getPoint(t, optionalTarget = new Vector2()) {
  18569. const point = optionalTarget;
  18570. const v0 = this.v0,
  18571. v1 = this.v1,
  18572. v2 = this.v2,
  18573. v3 = this.v3;
  18574. point.set(CubicBezier(t, v0.x, v1.x, v2.x, v3.x), CubicBezier(t, v0.y, v1.y, v2.y, v3.y));
  18575. return point;
  18576. }
  18577. copy(source) {
  18578. super.copy(source);
  18579. this.v0.copy(source.v0);
  18580. this.v1.copy(source.v1);
  18581. this.v2.copy(source.v2);
  18582. this.v3.copy(source.v3);
  18583. return this;
  18584. }
  18585. toJSON() {
  18586. const data = super.toJSON();
  18587. data.v0 = this.v0.toArray();
  18588. data.v1 = this.v1.toArray();
  18589. data.v2 = this.v2.toArray();
  18590. data.v3 = this.v3.toArray();
  18591. return data;
  18592. }
  18593. fromJSON(json) {
  18594. super.fromJSON(json);
  18595. this.v0.fromArray(json.v0);
  18596. this.v1.fromArray(json.v1);
  18597. this.v2.fromArray(json.v2);
  18598. this.v3.fromArray(json.v3);
  18599. return this;
  18600. }
  18601. }
  18602. class CubicBezierCurve3 extends Curve {
  18603. constructor(v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3(), v3 = new Vector3()) {
  18604. super();
  18605. this.isCubicBezierCurve3 = true;
  18606. this.type = 'CubicBezierCurve3';
  18607. this.v0 = v0;
  18608. this.v1 = v1;
  18609. this.v2 = v2;
  18610. this.v3 = v3;
  18611. }
  18612. getPoint(t, optionalTarget = new Vector3()) {
  18613. const point = optionalTarget;
  18614. const v0 = this.v0,
  18615. v1 = this.v1,
  18616. v2 = this.v2,
  18617. v3 = this.v3;
  18618. 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));
  18619. return point;
  18620. }
  18621. copy(source) {
  18622. super.copy(source);
  18623. this.v0.copy(source.v0);
  18624. this.v1.copy(source.v1);
  18625. this.v2.copy(source.v2);
  18626. this.v3.copy(source.v3);
  18627. return this;
  18628. }
  18629. toJSON() {
  18630. const data = super.toJSON();
  18631. data.v0 = this.v0.toArray();
  18632. data.v1 = this.v1.toArray();
  18633. data.v2 = this.v2.toArray();
  18634. data.v3 = this.v3.toArray();
  18635. return data;
  18636. }
  18637. fromJSON(json) {
  18638. super.fromJSON(json);
  18639. this.v0.fromArray(json.v0);
  18640. this.v1.fromArray(json.v1);
  18641. this.v2.fromArray(json.v2);
  18642. this.v3.fromArray(json.v3);
  18643. return this;
  18644. }
  18645. }
  18646. class LineCurve extends Curve {
  18647. constructor(v1 = new Vector2(), v2 = new Vector2()) {
  18648. super();
  18649. this.isLineCurve = true;
  18650. this.type = 'LineCurve';
  18651. this.v1 = v1;
  18652. this.v2 = v2;
  18653. }
  18654. getPoint(t, optionalTarget = new Vector2()) {
  18655. const point = optionalTarget;
  18656. if (t === 1) {
  18657. point.copy(this.v2);
  18658. } else {
  18659. point.copy(this.v2).sub(this.v1);
  18660. point.multiplyScalar(t).add(this.v1);
  18661. }
  18662. return point;
  18663. } // Line curve is linear, so we can overwrite default getPointAt
  18664. getPointAt(u, optionalTarget) {
  18665. return this.getPoint(u, optionalTarget);
  18666. }
  18667. getTangent(t, optionalTarget) {
  18668. const tangent = optionalTarget || new Vector2();
  18669. tangent.copy(this.v2).sub(this.v1).normalize();
  18670. return tangent;
  18671. }
  18672. copy(source) {
  18673. super.copy(source);
  18674. this.v1.copy(source.v1);
  18675. this.v2.copy(source.v2);
  18676. return this;
  18677. }
  18678. toJSON() {
  18679. const data = super.toJSON();
  18680. data.v1 = this.v1.toArray();
  18681. data.v2 = this.v2.toArray();
  18682. return data;
  18683. }
  18684. fromJSON(json) {
  18685. super.fromJSON(json);
  18686. this.v1.fromArray(json.v1);
  18687. this.v2.fromArray(json.v2);
  18688. return this;
  18689. }
  18690. }
  18691. class LineCurve3 extends Curve {
  18692. constructor(v1 = new Vector3(), v2 = new Vector3()) {
  18693. super();
  18694. this.isLineCurve3 = true;
  18695. this.type = 'LineCurve3';
  18696. this.v1 = v1;
  18697. this.v2 = v2;
  18698. }
  18699. getPoint(t, optionalTarget = new Vector3()) {
  18700. const point = optionalTarget;
  18701. if (t === 1) {
  18702. point.copy(this.v2);
  18703. } else {
  18704. point.copy(this.v2).sub(this.v1);
  18705. point.multiplyScalar(t).add(this.v1);
  18706. }
  18707. return point;
  18708. } // Line curve is linear, so we can overwrite default getPointAt
  18709. getPointAt(u, optionalTarget) {
  18710. return this.getPoint(u, optionalTarget);
  18711. }
  18712. copy(source) {
  18713. super.copy(source);
  18714. this.v1.copy(source.v1);
  18715. this.v2.copy(source.v2);
  18716. return this;
  18717. }
  18718. toJSON() {
  18719. const data = super.toJSON();
  18720. data.v1 = this.v1.toArray();
  18721. data.v2 = this.v2.toArray();
  18722. return data;
  18723. }
  18724. fromJSON(json) {
  18725. super.fromJSON(json);
  18726. this.v1.fromArray(json.v1);
  18727. this.v2.fromArray(json.v2);
  18728. return this;
  18729. }
  18730. }
  18731. class QuadraticBezierCurve extends Curve {
  18732. constructor(v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2()) {
  18733. super();
  18734. this.isQuadraticBezierCurve = true;
  18735. this.type = 'QuadraticBezierCurve';
  18736. this.v0 = v0;
  18737. this.v1 = v1;
  18738. this.v2 = v2;
  18739. }
  18740. getPoint(t, optionalTarget = new Vector2()) {
  18741. const point = optionalTarget;
  18742. const v0 = this.v0,
  18743. v1 = this.v1,
  18744. v2 = this.v2;
  18745. point.set(QuadraticBezier(t, v0.x, v1.x, v2.x), QuadraticBezier(t, v0.y, v1.y, v2.y));
  18746. return point;
  18747. }
  18748. copy(source) {
  18749. super.copy(source);
  18750. this.v0.copy(source.v0);
  18751. this.v1.copy(source.v1);
  18752. this.v2.copy(source.v2);
  18753. return this;
  18754. }
  18755. toJSON() {
  18756. const data = super.toJSON();
  18757. data.v0 = this.v0.toArray();
  18758. data.v1 = this.v1.toArray();
  18759. data.v2 = this.v2.toArray();
  18760. return data;
  18761. }
  18762. fromJSON(json) {
  18763. super.fromJSON(json);
  18764. this.v0.fromArray(json.v0);
  18765. this.v1.fromArray(json.v1);
  18766. this.v2.fromArray(json.v2);
  18767. return this;
  18768. }
  18769. }
  18770. class QuadraticBezierCurve3 extends Curve {
  18771. constructor(v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3()) {
  18772. super();
  18773. this.isQuadraticBezierCurve3 = true;
  18774. this.type = 'QuadraticBezierCurve3';
  18775. this.v0 = v0;
  18776. this.v1 = v1;
  18777. this.v2 = v2;
  18778. }
  18779. getPoint(t, optionalTarget = new Vector3()) {
  18780. const point = optionalTarget;
  18781. const v0 = this.v0,
  18782. v1 = this.v1,
  18783. v2 = this.v2;
  18784. 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));
  18785. return point;
  18786. }
  18787. copy(source) {
  18788. super.copy(source);
  18789. this.v0.copy(source.v0);
  18790. this.v1.copy(source.v1);
  18791. this.v2.copy(source.v2);
  18792. return this;
  18793. }
  18794. toJSON() {
  18795. const data = super.toJSON();
  18796. data.v0 = this.v0.toArray();
  18797. data.v1 = this.v1.toArray();
  18798. data.v2 = this.v2.toArray();
  18799. return data;
  18800. }
  18801. fromJSON(json) {
  18802. super.fromJSON(json);
  18803. this.v0.fromArray(json.v0);
  18804. this.v1.fromArray(json.v1);
  18805. this.v2.fromArray(json.v2);
  18806. return this;
  18807. }
  18808. }
  18809. class SplineCurve extends Curve {
  18810. constructor(points = []) {
  18811. super();
  18812. this.isSplineCurve = true;
  18813. this.type = 'SplineCurve';
  18814. this.points = points;
  18815. }
  18816. getPoint(t, optionalTarget = new Vector2()) {
  18817. const point = optionalTarget;
  18818. const points = this.points;
  18819. const p = (points.length - 1) * t;
  18820. const intPoint = Math.floor(p);
  18821. const weight = p - intPoint;
  18822. const p0 = points[intPoint === 0 ? intPoint : intPoint - 1];
  18823. const p1 = points[intPoint];
  18824. const p2 = points[intPoint > points.length - 2 ? points.length - 1 : intPoint + 1];
  18825. const p3 = points[intPoint > points.length - 3 ? points.length - 1 : intPoint + 2];
  18826. point.set(CatmullRom(weight, p0.x, p1.x, p2.x, p3.x), CatmullRom(weight, p0.y, p1.y, p2.y, p3.y));
  18827. return point;
  18828. }
  18829. copy(source) {
  18830. super.copy(source);
  18831. this.points = [];
  18832. for (let i = 0, l = source.points.length; i < l; i++) {
  18833. const point = source.points[i];
  18834. this.points.push(point.clone());
  18835. }
  18836. return this;
  18837. }
  18838. toJSON() {
  18839. const data = super.toJSON();
  18840. data.points = [];
  18841. for (let i = 0, l = this.points.length; i < l; i++) {
  18842. const point = this.points[i];
  18843. data.points.push(point.toArray());
  18844. }
  18845. return data;
  18846. }
  18847. fromJSON(json) {
  18848. super.fromJSON(json);
  18849. this.points = [];
  18850. for (let i = 0, l = json.points.length; i < l; i++) {
  18851. const point = json.points[i];
  18852. this.points.push(new Vector2().fromArray(point));
  18853. }
  18854. return this;
  18855. }
  18856. }
  18857. var Curves = /*#__PURE__*/Object.freeze({
  18858. __proto__: null,
  18859. ArcCurve: ArcCurve,
  18860. CatmullRomCurve3: CatmullRomCurve3,
  18861. CubicBezierCurve: CubicBezierCurve,
  18862. CubicBezierCurve3: CubicBezierCurve3,
  18863. EllipseCurve: EllipseCurve,
  18864. LineCurve: LineCurve,
  18865. LineCurve3: LineCurve3,
  18866. QuadraticBezierCurve: QuadraticBezierCurve,
  18867. QuadraticBezierCurve3: QuadraticBezierCurve3,
  18868. SplineCurve: SplineCurve
  18869. });
  18870. /**************************************************************
  18871. * Curved Path - a curve path is simply a array of connected
  18872. * curves, but retains the api of a curve
  18873. **************************************************************/
  18874. class CurvePath extends Curve {
  18875. constructor() {
  18876. super();
  18877. this.type = 'CurvePath';
  18878. this.curves = [];
  18879. this.autoClose = false; // Automatically closes the path
  18880. }
  18881. add(curve) {
  18882. this.curves.push(curve);
  18883. }
  18884. closePath() {
  18885. // Add a line curve if start and end of lines are not connected
  18886. const startPoint = this.curves[0].getPoint(0);
  18887. const endPoint = this.curves[this.curves.length - 1].getPoint(1);
  18888. if (!startPoint.equals(endPoint)) {
  18889. this.curves.push(new LineCurve(endPoint, startPoint));
  18890. }
  18891. } // To get accurate point with reference to
  18892. // entire path distance at time t,
  18893. // following has to be done:
  18894. // 1. Length of each sub path have to be known
  18895. // 2. Locate and identify type of curve
  18896. // 3. Get t for the curve
  18897. // 4. Return curve.getPointAt(t')
  18898. getPoint(t, optionalTarget) {
  18899. const d = t * this.getLength();
  18900. const curveLengths = this.getCurveLengths();
  18901. let i = 0; // To think about boundaries points.
  18902. while (i < curveLengths.length) {
  18903. if (curveLengths[i] >= d) {
  18904. const diff = curveLengths[i] - d;
  18905. const curve = this.curves[i];
  18906. const segmentLength = curve.getLength();
  18907. const u = segmentLength === 0 ? 0 : 1 - diff / segmentLength;
  18908. return curve.getPointAt(u, optionalTarget);
  18909. }
  18910. i++;
  18911. }
  18912. return null; // loop where sum != 0, sum > d , sum+1 <d
  18913. } // We cannot use the default THREE.Curve getPoint() with getLength() because in
  18914. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  18915. // getPoint() depends on getLength
  18916. getLength() {
  18917. const lens = this.getCurveLengths();
  18918. return lens[lens.length - 1];
  18919. } // cacheLengths must be recalculated.
  18920. updateArcLengths() {
  18921. this.needsUpdate = true;
  18922. this.cacheLengths = null;
  18923. this.getCurveLengths();
  18924. } // Compute lengths and cache them
  18925. // We cannot overwrite getLengths() because UtoT mapping uses it.
  18926. getCurveLengths() {
  18927. // We use cache values if curves and cache array are same length
  18928. if (this.cacheLengths && this.cacheLengths.length === this.curves.length) {
  18929. return this.cacheLengths;
  18930. } // Get length of sub-curve
  18931. // Push sums into cached array
  18932. const lengths = [];
  18933. let sums = 0;
  18934. for (let i = 0, l = this.curves.length; i < l; i++) {
  18935. sums += this.curves[i].getLength();
  18936. lengths.push(sums);
  18937. }
  18938. this.cacheLengths = lengths;
  18939. return lengths;
  18940. }
  18941. getSpacedPoints(divisions = 40) {
  18942. const points = [];
  18943. for (let i = 0; i <= divisions; i++) {
  18944. points.push(this.getPoint(i / divisions));
  18945. }
  18946. if (this.autoClose) {
  18947. points.push(points[0]);
  18948. }
  18949. return points;
  18950. }
  18951. getPoints(divisions = 12) {
  18952. const points = [];
  18953. let last;
  18954. for (let i = 0, curves = this.curves; i < curves.length; i++) {
  18955. const curve = curves[i];
  18956. const resolution = curve.isEllipseCurve ? divisions * 2 : curve.isLineCurve || curve.isLineCurve3 ? 1 : curve.isSplineCurve ? divisions * curve.points.length : divisions;
  18957. const pts = curve.getPoints(resolution);
  18958. for (let j = 0; j < pts.length; j++) {
  18959. const point = pts[j];
  18960. if (last && last.equals(point)) continue; // ensures no consecutive points are duplicates
  18961. points.push(point);
  18962. last = point;
  18963. }
  18964. }
  18965. if (this.autoClose && points.length > 1 && !points[points.length - 1].equals(points[0])) {
  18966. points.push(points[0]);
  18967. }
  18968. return points;
  18969. }
  18970. copy(source) {
  18971. super.copy(source);
  18972. this.curves = [];
  18973. for (let i = 0, l = source.curves.length; i < l; i++) {
  18974. const curve = source.curves[i];
  18975. this.curves.push(curve.clone());
  18976. }
  18977. this.autoClose = source.autoClose;
  18978. return this;
  18979. }
  18980. toJSON() {
  18981. const data = super.toJSON();
  18982. data.autoClose = this.autoClose;
  18983. data.curves = [];
  18984. for (let i = 0, l = this.curves.length; i < l; i++) {
  18985. const curve = this.curves[i];
  18986. data.curves.push(curve.toJSON());
  18987. }
  18988. return data;
  18989. }
  18990. fromJSON(json) {
  18991. super.fromJSON(json);
  18992. this.autoClose = json.autoClose;
  18993. this.curves = [];
  18994. for (let i = 0, l = json.curves.length; i < l; i++) {
  18995. const curve = json.curves[i];
  18996. this.curves.push(new Curves[curve.type]().fromJSON(curve));
  18997. }
  18998. return this;
  18999. }
  19000. }
  19001. class Path extends CurvePath {
  19002. constructor(points) {
  19003. super();
  19004. this.type = 'Path';
  19005. this.currentPoint = new Vector2();
  19006. if (points) {
  19007. this.setFromPoints(points);
  19008. }
  19009. }
  19010. setFromPoints(points) {
  19011. this.moveTo(points[0].x, points[0].y);
  19012. for (let i = 1, l = points.length; i < l; i++) {
  19013. this.lineTo(points[i].x, points[i].y);
  19014. }
  19015. return this;
  19016. }
  19017. moveTo(x, y) {
  19018. this.currentPoint.set(x, y); // TODO consider referencing vectors instead of copying?
  19019. return this;
  19020. }
  19021. lineTo(x, y) {
  19022. const curve = new LineCurve(this.currentPoint.clone(), new Vector2(x, y));
  19023. this.curves.push(curve);
  19024. this.currentPoint.set(x, y);
  19025. return this;
  19026. }
  19027. quadraticCurveTo(aCPx, aCPy, aX, aY) {
  19028. const curve = new QuadraticBezierCurve(this.currentPoint.clone(), new Vector2(aCPx, aCPy), new Vector2(aX, aY));
  19029. this.curves.push(curve);
  19030. this.currentPoint.set(aX, aY);
  19031. return this;
  19032. }
  19033. bezierCurveTo(aCP1x, aCP1y, aCP2x, aCP2y, aX, aY) {
  19034. const curve = new CubicBezierCurve(this.currentPoint.clone(), new Vector2(aCP1x, aCP1y), new Vector2(aCP2x, aCP2y), new Vector2(aX, aY));
  19035. this.curves.push(curve);
  19036. this.currentPoint.set(aX, aY);
  19037. return this;
  19038. }
  19039. splineThru(pts
  19040. /*Array of Vector*/
  19041. ) {
  19042. const npts = [this.currentPoint.clone()].concat(pts);
  19043. const curve = new SplineCurve(npts);
  19044. this.curves.push(curve);
  19045. this.currentPoint.copy(pts[pts.length - 1]);
  19046. return this;
  19047. }
  19048. arc(aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise) {
  19049. const x0 = this.currentPoint.x;
  19050. const y0 = this.currentPoint.y;
  19051. this.absarc(aX + x0, aY + y0, aRadius, aStartAngle, aEndAngle, aClockwise);
  19052. return this;
  19053. }
  19054. absarc(aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise) {
  19055. this.absellipse(aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise);
  19056. return this;
  19057. }
  19058. ellipse(aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation) {
  19059. const x0 = this.currentPoint.x;
  19060. const y0 = this.currentPoint.y;
  19061. this.absellipse(aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation);
  19062. return this;
  19063. }
  19064. absellipse(aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation) {
  19065. const curve = new EllipseCurve(aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation);
  19066. if (this.curves.length > 0) {
  19067. // if a previous curve is present, attempt to join
  19068. const firstPoint = curve.getPoint(0);
  19069. if (!firstPoint.equals(this.currentPoint)) {
  19070. this.lineTo(firstPoint.x, firstPoint.y);
  19071. }
  19072. }
  19073. this.curves.push(curve);
  19074. const lastPoint = curve.getPoint(1);
  19075. this.currentPoint.copy(lastPoint);
  19076. return this;
  19077. }
  19078. copy(source) {
  19079. super.copy(source);
  19080. this.currentPoint.copy(source.currentPoint);
  19081. return this;
  19082. }
  19083. toJSON() {
  19084. const data = super.toJSON();
  19085. data.currentPoint = this.currentPoint.toArray();
  19086. return data;
  19087. }
  19088. fromJSON(json) {
  19089. super.fromJSON(json);
  19090. this.currentPoint.fromArray(json.currentPoint);
  19091. return this;
  19092. }
  19093. }
  19094. class LatheGeometry extends BufferGeometry {
  19095. constructor(points = [new Vector2(0, 0.5), new Vector2(0.5, 0), new Vector2(0, -0.5)], segments = 12, phiStart = 0, phiLength = Math.PI * 2) {
  19096. super();
  19097. this.type = 'LatheGeometry';
  19098. this.parameters = {
  19099. points: points,
  19100. segments: segments,
  19101. phiStart: phiStart,
  19102. phiLength: phiLength
  19103. };
  19104. segments = Math.floor(segments); // clamp phiLength so it's in range of [ 0, 2PI ]
  19105. phiLength = clamp(phiLength, 0, Math.PI * 2); // buffers
  19106. const indices = [];
  19107. const vertices = [];
  19108. const uvs = [];
  19109. const initNormals = [];
  19110. const normals = []; // helper variables
  19111. const inverseSegments = 1.0 / segments;
  19112. const vertex = new Vector3();
  19113. const uv = new Vector2();
  19114. const normal = new Vector3();
  19115. const curNormal = new Vector3();
  19116. const prevNormal = new Vector3();
  19117. let dx = 0;
  19118. let dy = 0; // pre-compute normals for initial "meridian"
  19119. for (let j = 0; j <= points.length - 1; j++) {
  19120. switch (j) {
  19121. case 0:
  19122. // special handling for 1st vertex on path
  19123. dx = points[j + 1].x - points[j].x;
  19124. dy = points[j + 1].y - points[j].y;
  19125. normal.x = dy * 1.0;
  19126. normal.y = -dx;
  19127. normal.z = dy * 0.0;
  19128. prevNormal.copy(normal);
  19129. normal.normalize();
  19130. initNormals.push(normal.x, normal.y, normal.z);
  19131. break;
  19132. case points.length - 1:
  19133. // special handling for last Vertex on path
  19134. initNormals.push(prevNormal.x, prevNormal.y, prevNormal.z);
  19135. break;
  19136. default:
  19137. // default handling for all vertices in between
  19138. dx = points[j + 1].x - points[j].x;
  19139. dy = points[j + 1].y - points[j].y;
  19140. normal.x = dy * 1.0;
  19141. normal.y = -dx;
  19142. normal.z = dy * 0.0;
  19143. curNormal.copy(normal);
  19144. normal.x += prevNormal.x;
  19145. normal.y += prevNormal.y;
  19146. normal.z += prevNormal.z;
  19147. normal.normalize();
  19148. initNormals.push(normal.x, normal.y, normal.z);
  19149. prevNormal.copy(curNormal);
  19150. }
  19151. } // generate vertices, uvs and normals
  19152. for (let i = 0; i <= segments; i++) {
  19153. const phi = phiStart + i * inverseSegments * phiLength;
  19154. const sin = Math.sin(phi);
  19155. const cos = Math.cos(phi);
  19156. for (let j = 0; j <= points.length - 1; j++) {
  19157. // vertex
  19158. vertex.x = points[j].x * sin;
  19159. vertex.y = points[j].y;
  19160. vertex.z = points[j].x * cos;
  19161. vertices.push(vertex.x, vertex.y, vertex.z); // uv
  19162. uv.x = i / segments;
  19163. uv.y = j / (points.length - 1);
  19164. uvs.push(uv.x, uv.y); // normal
  19165. const x = initNormals[3 * j + 0] * sin;
  19166. const y = initNormals[3 * j + 1];
  19167. const z = initNormals[3 * j + 0] * cos;
  19168. normals.push(x, y, z);
  19169. }
  19170. } // indices
  19171. for (let i = 0; i < segments; i++) {
  19172. for (let j = 0; j < points.length - 1; j++) {
  19173. const base = j + i * points.length;
  19174. const a = base;
  19175. const b = base + points.length;
  19176. const c = base + points.length + 1;
  19177. const d = base + 1; // faces
  19178. indices.push(a, b, d);
  19179. indices.push(c, d, b);
  19180. }
  19181. } // build geometry
  19182. this.setIndex(indices);
  19183. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  19184. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  19185. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  19186. }
  19187. static fromJSON(data) {
  19188. return new LatheGeometry(data.points, data.segments, data.phiStart, data.phiLength);
  19189. }
  19190. }
  19191. class CapsuleGeometry extends LatheGeometry {
  19192. constructor(radius = 1, length = 1, capSegments = 4, radialSegments = 8) {
  19193. const path = new Path();
  19194. path.absarc(0, -length / 2, radius, Math.PI * 1.5, 0);
  19195. path.absarc(0, length / 2, radius, 0, Math.PI * 0.5);
  19196. super(path.getPoints(capSegments), radialSegments);
  19197. this.type = 'CapsuleGeometry';
  19198. this.parameters = {
  19199. radius: radius,
  19200. height: length,
  19201. capSegments: capSegments,
  19202. radialSegments: radialSegments
  19203. };
  19204. }
  19205. static fromJSON(data) {
  19206. return new CapsuleGeometry(data.radius, data.length, data.capSegments, data.radialSegments);
  19207. }
  19208. }
  19209. class CircleGeometry extends BufferGeometry {
  19210. constructor(radius = 1, segments = 8, thetaStart = 0, thetaLength = Math.PI * 2) {
  19211. super();
  19212. this.type = 'CircleGeometry';
  19213. this.parameters = {
  19214. radius: radius,
  19215. segments: segments,
  19216. thetaStart: thetaStart,
  19217. thetaLength: thetaLength
  19218. };
  19219. segments = Math.max(3, segments); // buffers
  19220. const indices = [];
  19221. const vertices = [];
  19222. const normals = [];
  19223. const uvs = []; // helper variables
  19224. const vertex = new Vector3();
  19225. const uv = new Vector2(); // center point
  19226. vertices.push(0, 0, 0);
  19227. normals.push(0, 0, 1);
  19228. uvs.push(0.5, 0.5);
  19229. for (let s = 0, i = 3; s <= segments; s++, i += 3) {
  19230. const segment = thetaStart + s / segments * thetaLength; // vertex
  19231. vertex.x = radius * Math.cos(segment);
  19232. vertex.y = radius * Math.sin(segment);
  19233. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  19234. normals.push(0, 0, 1); // uvs
  19235. uv.x = (vertices[i] / radius + 1) / 2;
  19236. uv.y = (vertices[i + 1] / radius + 1) / 2;
  19237. uvs.push(uv.x, uv.y);
  19238. } // indices
  19239. for (let i = 1; i <= segments; i++) {
  19240. indices.push(i, i + 1, 0);
  19241. } // build geometry
  19242. this.setIndex(indices);
  19243. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  19244. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  19245. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  19246. }
  19247. static fromJSON(data) {
  19248. return new CircleGeometry(data.radius, data.segments, data.thetaStart, data.thetaLength);
  19249. }
  19250. }
  19251. class CylinderGeometry extends BufferGeometry {
  19252. constructor(radiusTop = 1, radiusBottom = 1, height = 1, radialSegments = 8, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2) {
  19253. super();
  19254. this.type = 'CylinderGeometry';
  19255. this.parameters = {
  19256. radiusTop: radiusTop,
  19257. radiusBottom: radiusBottom,
  19258. height: height,
  19259. radialSegments: radialSegments,
  19260. heightSegments: heightSegments,
  19261. openEnded: openEnded,
  19262. thetaStart: thetaStart,
  19263. thetaLength: thetaLength
  19264. };
  19265. const scope = this;
  19266. radialSegments = Math.floor(radialSegments);
  19267. heightSegments = Math.floor(heightSegments); // buffers
  19268. const indices = [];
  19269. const vertices = [];
  19270. const normals = [];
  19271. const uvs = []; // helper variables
  19272. let index = 0;
  19273. const indexArray = [];
  19274. const halfHeight = height / 2;
  19275. let groupStart = 0; // generate geometry
  19276. generateTorso();
  19277. if (openEnded === false) {
  19278. if (radiusTop > 0) generateCap(true);
  19279. if (radiusBottom > 0) generateCap(false);
  19280. } // build geometry
  19281. this.setIndex(indices);
  19282. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  19283. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  19284. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  19285. function generateTorso() {
  19286. const normal = new Vector3();
  19287. const vertex = new Vector3();
  19288. let groupCount = 0; // this will be used to calculate the normal
  19289. const slope = (radiusBottom - radiusTop) / height; // generate vertices, normals and uvs
  19290. for (let y = 0; y <= heightSegments; y++) {
  19291. const indexRow = [];
  19292. const v = y / heightSegments; // calculate the radius of the current row
  19293. const radius = v * (radiusBottom - radiusTop) + radiusTop;
  19294. for (let x = 0; x <= radialSegments; x++) {
  19295. const u = x / radialSegments;
  19296. const theta = u * thetaLength + thetaStart;
  19297. const sinTheta = Math.sin(theta);
  19298. const cosTheta = Math.cos(theta); // vertex
  19299. vertex.x = radius * sinTheta;
  19300. vertex.y = -v * height + halfHeight;
  19301. vertex.z = radius * cosTheta;
  19302. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  19303. normal.set(sinTheta, slope, cosTheta).normalize();
  19304. normals.push(normal.x, normal.y, normal.z); // uv
  19305. uvs.push(u, 1 - v); // save index of vertex in respective row
  19306. indexRow.push(index++);
  19307. } // now save vertices of the row in our index array
  19308. indexArray.push(indexRow);
  19309. } // generate indices
  19310. for (let x = 0; x < radialSegments; x++) {
  19311. for (let y = 0; y < heightSegments; y++) {
  19312. // we use the index array to access the correct indices
  19313. const a = indexArray[y][x];
  19314. const b = indexArray[y + 1][x];
  19315. const c = indexArray[y + 1][x + 1];
  19316. const d = indexArray[y][x + 1]; // faces
  19317. indices.push(a, b, d);
  19318. indices.push(b, c, d); // update group counter
  19319. groupCount += 6;
  19320. }
  19321. } // add a group to the geometry. this will ensure multi material support
  19322. scope.addGroup(groupStart, groupCount, 0); // calculate new start value for groups
  19323. groupStart += groupCount;
  19324. }
  19325. function generateCap(top) {
  19326. // save the index of the first center vertex
  19327. const centerIndexStart = index;
  19328. const uv = new Vector2();
  19329. const vertex = new Vector3();
  19330. let groupCount = 0;
  19331. const radius = top === true ? radiusTop : radiusBottom;
  19332. const sign = top === true ? 1 : -1; // first we generate the center vertex data of the cap.
  19333. // because the geometry needs one set of uvs per face,
  19334. // we must generate a center vertex per face/segment
  19335. for (let x = 1; x <= radialSegments; x++) {
  19336. // vertex
  19337. vertices.push(0, halfHeight * sign, 0); // normal
  19338. normals.push(0, sign, 0); // uv
  19339. uvs.push(0.5, 0.5); // increase index
  19340. index++;
  19341. } // save the index of the last center vertex
  19342. const centerIndexEnd = index; // now we generate the surrounding vertices, normals and uvs
  19343. for (let x = 0; x <= radialSegments; x++) {
  19344. const u = x / radialSegments;
  19345. const theta = u * thetaLength + thetaStart;
  19346. const cosTheta = Math.cos(theta);
  19347. const sinTheta = Math.sin(theta); // vertex
  19348. vertex.x = radius * sinTheta;
  19349. vertex.y = halfHeight * sign;
  19350. vertex.z = radius * cosTheta;
  19351. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  19352. normals.push(0, sign, 0); // uv
  19353. uv.x = cosTheta * 0.5 + 0.5;
  19354. uv.y = sinTheta * 0.5 * sign + 0.5;
  19355. uvs.push(uv.x, uv.y); // increase index
  19356. index++;
  19357. } // generate indices
  19358. for (let x = 0; x < radialSegments; x++) {
  19359. const c = centerIndexStart + x;
  19360. const i = centerIndexEnd + x;
  19361. if (top === true) {
  19362. // face top
  19363. indices.push(i, i + 1, c);
  19364. } else {
  19365. // face bottom
  19366. indices.push(i + 1, i, c);
  19367. }
  19368. groupCount += 3;
  19369. } // add a group to the geometry. this will ensure multi material support
  19370. scope.addGroup(groupStart, groupCount, top === true ? 1 : 2); // calculate new start value for groups
  19371. groupStart += groupCount;
  19372. }
  19373. }
  19374. static fromJSON(data) {
  19375. return new CylinderGeometry(data.radiusTop, data.radiusBottom, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength);
  19376. }
  19377. }
  19378. class ConeGeometry extends CylinderGeometry {
  19379. constructor(radius = 1, height = 1, radialSegments = 8, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2) {
  19380. super(0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength);
  19381. this.type = 'ConeGeometry';
  19382. this.parameters = {
  19383. radius: radius,
  19384. height: height,
  19385. radialSegments: radialSegments,
  19386. heightSegments: heightSegments,
  19387. openEnded: openEnded,
  19388. thetaStart: thetaStart,
  19389. thetaLength: thetaLength
  19390. };
  19391. }
  19392. static fromJSON(data) {
  19393. return new ConeGeometry(data.radius, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength);
  19394. }
  19395. }
  19396. class PolyhedronGeometry extends BufferGeometry {
  19397. constructor(vertices = [], indices = [], radius = 1, detail = 0) {
  19398. super();
  19399. this.type = 'PolyhedronGeometry';
  19400. this.parameters = {
  19401. vertices: vertices,
  19402. indices: indices,
  19403. radius: radius,
  19404. detail: detail
  19405. }; // default buffer data
  19406. const vertexBuffer = [];
  19407. const uvBuffer = []; // the subdivision creates the vertex buffer data
  19408. subdivide(detail); // all vertices should lie on a conceptual sphere with a given radius
  19409. applyRadius(radius); // finally, create the uv data
  19410. generateUVs(); // build non-indexed geometry
  19411. this.setAttribute('position', new Float32BufferAttribute(vertexBuffer, 3));
  19412. this.setAttribute('normal', new Float32BufferAttribute(vertexBuffer.slice(), 3));
  19413. this.setAttribute('uv', new Float32BufferAttribute(uvBuffer, 2));
  19414. if (detail === 0) {
  19415. this.computeVertexNormals(); // flat normals
  19416. } else {
  19417. this.normalizeNormals(); // smooth normals
  19418. } // helper functions
  19419. function subdivide(detail) {
  19420. const a = new Vector3();
  19421. const b = new Vector3();
  19422. const c = new Vector3(); // iterate over all faces and apply a subdivison with the given detail value
  19423. for (let i = 0; i < indices.length; i += 3) {
  19424. // get the vertices of the face
  19425. getVertexByIndex(indices[i + 0], a);
  19426. getVertexByIndex(indices[i + 1], b);
  19427. getVertexByIndex(indices[i + 2], c); // perform subdivision
  19428. subdivideFace(a, b, c, detail);
  19429. }
  19430. }
  19431. function subdivideFace(a, b, c, detail) {
  19432. const cols = detail + 1; // we use this multidimensional array as a data structure for creating the subdivision
  19433. const v = []; // construct all of the vertices for this subdivision
  19434. for (let i = 0; i <= cols; i++) {
  19435. v[i] = [];
  19436. const aj = a.clone().lerp(c, i / cols);
  19437. const bj = b.clone().lerp(c, i / cols);
  19438. const rows = cols - i;
  19439. for (let j = 0; j <= rows; j++) {
  19440. if (j === 0 && i === cols) {
  19441. v[i][j] = aj;
  19442. } else {
  19443. v[i][j] = aj.clone().lerp(bj, j / rows);
  19444. }
  19445. }
  19446. } // construct all of the faces
  19447. for (let i = 0; i < cols; i++) {
  19448. for (let j = 0; j < 2 * (cols - i) - 1; j++) {
  19449. const k = Math.floor(j / 2);
  19450. if (j % 2 === 0) {
  19451. pushVertex(v[i][k + 1]);
  19452. pushVertex(v[i + 1][k]);
  19453. pushVertex(v[i][k]);
  19454. } else {
  19455. pushVertex(v[i][k + 1]);
  19456. pushVertex(v[i + 1][k + 1]);
  19457. pushVertex(v[i + 1][k]);
  19458. }
  19459. }
  19460. }
  19461. }
  19462. function applyRadius(radius) {
  19463. const vertex = new Vector3(); // iterate over the entire buffer and apply the radius to each vertex
  19464. for (let i = 0; i < vertexBuffer.length; i += 3) {
  19465. vertex.x = vertexBuffer[i + 0];
  19466. vertex.y = vertexBuffer[i + 1];
  19467. vertex.z = vertexBuffer[i + 2];
  19468. vertex.normalize().multiplyScalar(radius);
  19469. vertexBuffer[i + 0] = vertex.x;
  19470. vertexBuffer[i + 1] = vertex.y;
  19471. vertexBuffer[i + 2] = vertex.z;
  19472. }
  19473. }
  19474. function generateUVs() {
  19475. const vertex = new Vector3();
  19476. for (let i = 0; i < vertexBuffer.length; i += 3) {
  19477. vertex.x = vertexBuffer[i + 0];
  19478. vertex.y = vertexBuffer[i + 1];
  19479. vertex.z = vertexBuffer[i + 2];
  19480. const u = azimuth(vertex) / 2 / Math.PI + 0.5;
  19481. const v = inclination(vertex) / Math.PI + 0.5;
  19482. uvBuffer.push(u, 1 - v);
  19483. }
  19484. correctUVs();
  19485. correctSeam();
  19486. }
  19487. function correctSeam() {
  19488. // handle case when face straddles the seam, see #3269
  19489. for (let i = 0; i < uvBuffer.length; i += 6) {
  19490. // uv data of a single face
  19491. const x0 = uvBuffer[i + 0];
  19492. const x1 = uvBuffer[i + 2];
  19493. const x2 = uvBuffer[i + 4];
  19494. const max = Math.max(x0, x1, x2);
  19495. const min = Math.min(x0, x1, x2); // 0.9 is somewhat arbitrary
  19496. if (max > 0.9 && min < 0.1) {
  19497. if (x0 < 0.2) uvBuffer[i + 0] += 1;
  19498. if (x1 < 0.2) uvBuffer[i + 2] += 1;
  19499. if (x2 < 0.2) uvBuffer[i + 4] += 1;
  19500. }
  19501. }
  19502. }
  19503. function pushVertex(vertex) {
  19504. vertexBuffer.push(vertex.x, vertex.y, vertex.z);
  19505. }
  19506. function getVertexByIndex(index, vertex) {
  19507. const stride = index * 3;
  19508. vertex.x = vertices[stride + 0];
  19509. vertex.y = vertices[stride + 1];
  19510. vertex.z = vertices[stride + 2];
  19511. }
  19512. function correctUVs() {
  19513. const a = new Vector3();
  19514. const b = new Vector3();
  19515. const c = new Vector3();
  19516. const centroid = new Vector3();
  19517. const uvA = new Vector2();
  19518. const uvB = new Vector2();
  19519. const uvC = new Vector2();
  19520. for (let i = 0, j = 0; i < vertexBuffer.length; i += 9, j += 6) {
  19521. a.set(vertexBuffer[i + 0], vertexBuffer[i + 1], vertexBuffer[i + 2]);
  19522. b.set(vertexBuffer[i + 3], vertexBuffer[i + 4], vertexBuffer[i + 5]);
  19523. c.set(vertexBuffer[i + 6], vertexBuffer[i + 7], vertexBuffer[i + 8]);
  19524. uvA.set(uvBuffer[j + 0], uvBuffer[j + 1]);
  19525. uvB.set(uvBuffer[j + 2], uvBuffer[j + 3]);
  19526. uvC.set(uvBuffer[j + 4], uvBuffer[j + 5]);
  19527. centroid.copy(a).add(b).add(c).divideScalar(3);
  19528. const azi = azimuth(centroid);
  19529. correctUV(uvA, j + 0, a, azi);
  19530. correctUV(uvB, j + 2, b, azi);
  19531. correctUV(uvC, j + 4, c, azi);
  19532. }
  19533. }
  19534. function correctUV(uv, stride, vector, azimuth) {
  19535. if (azimuth < 0 && uv.x === 1) {
  19536. uvBuffer[stride] = uv.x - 1;
  19537. }
  19538. if (vector.x === 0 && vector.z === 0) {
  19539. uvBuffer[stride] = azimuth / 2 / Math.PI + 0.5;
  19540. }
  19541. } // Angle around the Y axis, counter-clockwise when looking from above.
  19542. function azimuth(vector) {
  19543. return Math.atan2(vector.z, -vector.x);
  19544. } // Angle above the XZ plane.
  19545. function inclination(vector) {
  19546. return Math.atan2(-vector.y, Math.sqrt(vector.x * vector.x + vector.z * vector.z));
  19547. }
  19548. }
  19549. static fromJSON(data) {
  19550. return new PolyhedronGeometry(data.vertices, data.indices, data.radius, data.details);
  19551. }
  19552. }
  19553. class DodecahedronGeometry extends PolyhedronGeometry {
  19554. constructor(radius = 1, detail = 0) {
  19555. const t = (1 + Math.sqrt(5)) / 2;
  19556. const r = 1 / t;
  19557. const vertices = [// (±1, ±1, ±1)
  19558. -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/φ, ±φ)
  19559. 0, -r, -t, 0, -r, t, 0, r, -t, 0, r, t, // (±1/φ, ±φ, 0)
  19560. -r, -t, 0, -r, t, 0, r, -t, 0, r, t, 0, // (±φ, 0, ±1/φ)
  19561. -t, 0, -r, t, 0, -r, -t, 0, r, t, 0, r];
  19562. 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];
  19563. super(vertices, indices, radius, detail);
  19564. this.type = 'DodecahedronGeometry';
  19565. this.parameters = {
  19566. radius: radius,
  19567. detail: detail
  19568. };
  19569. }
  19570. static fromJSON(data) {
  19571. return new DodecahedronGeometry(data.radius, data.detail);
  19572. }
  19573. }
  19574. const _v0 = new Vector3();
  19575. const _v1$1 = new Vector3();
  19576. const _normal = new Vector3();
  19577. const _triangle = new Triangle();
  19578. class EdgesGeometry extends BufferGeometry {
  19579. constructor(geometry = null, thresholdAngle = 1) {
  19580. super();
  19581. this.type = 'EdgesGeometry';
  19582. this.parameters = {
  19583. geometry: geometry,
  19584. thresholdAngle: thresholdAngle
  19585. };
  19586. if (geometry !== null) {
  19587. const precisionPoints = 4;
  19588. const precision = Math.pow(10, precisionPoints);
  19589. const thresholdDot = Math.cos(DEG2RAD * thresholdAngle);
  19590. const indexAttr = geometry.getIndex();
  19591. const positionAttr = geometry.getAttribute('position');
  19592. const indexCount = indexAttr ? indexAttr.count : positionAttr.count;
  19593. const indexArr = [0, 0, 0];
  19594. const vertKeys = ['a', 'b', 'c'];
  19595. const hashes = new Array(3);
  19596. const edgeData = {};
  19597. const vertices = [];
  19598. for (let i = 0; i < indexCount; i += 3) {
  19599. if (indexAttr) {
  19600. indexArr[0] = indexAttr.getX(i);
  19601. indexArr[1] = indexAttr.getX(i + 1);
  19602. indexArr[2] = indexAttr.getX(i + 2);
  19603. } else {
  19604. indexArr[0] = i;
  19605. indexArr[1] = i + 1;
  19606. indexArr[2] = i + 2;
  19607. }
  19608. const {
  19609. a,
  19610. b,
  19611. c
  19612. } = _triangle;
  19613. a.fromBufferAttribute(positionAttr, indexArr[0]);
  19614. b.fromBufferAttribute(positionAttr, indexArr[1]);
  19615. c.fromBufferAttribute(positionAttr, indexArr[2]);
  19616. _triangle.getNormal(_normal); // create hashes for the edge from the vertices
  19617. hashes[0] = `${Math.round(a.x * precision)},${Math.round(a.y * precision)},${Math.round(a.z * precision)}`;
  19618. hashes[1] = `${Math.round(b.x * precision)},${Math.round(b.y * precision)},${Math.round(b.z * precision)}`;
  19619. hashes[2] = `${Math.round(c.x * precision)},${Math.round(c.y * precision)},${Math.round(c.z * precision)}`; // skip degenerate triangles
  19620. if (hashes[0] === hashes[1] || hashes[1] === hashes[2] || hashes[2] === hashes[0]) {
  19621. continue;
  19622. } // iterate over every edge
  19623. for (let j = 0; j < 3; j++) {
  19624. // get the first and next vertex making up the edge
  19625. const jNext = (j + 1) % 3;
  19626. const vecHash0 = hashes[j];
  19627. const vecHash1 = hashes[jNext];
  19628. const v0 = _triangle[vertKeys[j]];
  19629. const v1 = _triangle[vertKeys[jNext]];
  19630. const hash = `${vecHash0}_${vecHash1}`;
  19631. const reverseHash = `${vecHash1}_${vecHash0}`;
  19632. if (reverseHash in edgeData && edgeData[reverseHash]) {
  19633. // if we found a sibling edge add it into the vertex array if
  19634. // it meets the angle threshold and delete the edge from the map.
  19635. if (_normal.dot(edgeData[reverseHash].normal) <= thresholdDot) {
  19636. vertices.push(v0.x, v0.y, v0.z);
  19637. vertices.push(v1.x, v1.y, v1.z);
  19638. }
  19639. edgeData[reverseHash] = null;
  19640. } else if (!(hash in edgeData)) {
  19641. // if we've already got an edge here then skip adding a new one
  19642. edgeData[hash] = {
  19643. index0: indexArr[j],
  19644. index1: indexArr[jNext],
  19645. normal: _normal.clone()
  19646. };
  19647. }
  19648. }
  19649. } // iterate over all remaining, unmatched edges and add them to the vertex array
  19650. for (const key in edgeData) {
  19651. if (edgeData[key]) {
  19652. const {
  19653. index0,
  19654. index1
  19655. } = edgeData[key];
  19656. _v0.fromBufferAttribute(positionAttr, index0);
  19657. _v1$1.fromBufferAttribute(positionAttr, index1);
  19658. vertices.push(_v0.x, _v0.y, _v0.z);
  19659. vertices.push(_v1$1.x, _v1$1.y, _v1$1.z);
  19660. }
  19661. }
  19662. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  19663. }
  19664. }
  19665. }
  19666. class Shape extends Path {
  19667. constructor(points) {
  19668. super(points);
  19669. this.uuid = generateUUID();
  19670. this.type = 'Shape';
  19671. this.holes = [];
  19672. }
  19673. getPointsHoles(divisions) {
  19674. const holesPts = [];
  19675. for (let i = 0, l = this.holes.length; i < l; i++) {
  19676. holesPts[i] = this.holes[i].getPoints(divisions);
  19677. }
  19678. return holesPts;
  19679. } // get points of shape and holes (keypoints based on segments parameter)
  19680. extractPoints(divisions) {
  19681. return {
  19682. shape: this.getPoints(divisions),
  19683. holes: this.getPointsHoles(divisions)
  19684. };
  19685. }
  19686. copy(source) {
  19687. super.copy(source);
  19688. this.holes = [];
  19689. for (let i = 0, l = source.holes.length; i < l; i++) {
  19690. const hole = source.holes[i];
  19691. this.holes.push(hole.clone());
  19692. }
  19693. return this;
  19694. }
  19695. toJSON() {
  19696. const data = super.toJSON();
  19697. data.uuid = this.uuid;
  19698. data.holes = [];
  19699. for (let i = 0, l = this.holes.length; i < l; i++) {
  19700. const hole = this.holes[i];
  19701. data.holes.push(hole.toJSON());
  19702. }
  19703. return data;
  19704. }
  19705. fromJSON(json) {
  19706. super.fromJSON(json);
  19707. this.uuid = json.uuid;
  19708. this.holes = [];
  19709. for (let i = 0, l = json.holes.length; i < l; i++) {
  19710. const hole = json.holes[i];
  19711. this.holes.push(new Path().fromJSON(hole));
  19712. }
  19713. return this;
  19714. }
  19715. }
  19716. /**
  19717. * Port from https://github.com/mapbox/earcut (v2.2.2)
  19718. */
  19719. const Earcut = {
  19720. triangulate: function (data, holeIndices, dim = 2) {
  19721. const hasHoles = holeIndices && holeIndices.length;
  19722. const outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  19723. let outerNode = linkedList(data, 0, outerLen, dim, true);
  19724. const triangles = [];
  19725. if (!outerNode || outerNode.next === outerNode.prev) return triangles;
  19726. let minX, minY, maxX, maxY, x, y, invSize;
  19727. 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
  19728. if (data.length > 80 * dim) {
  19729. minX = maxX = data[0];
  19730. minY = maxY = data[1];
  19731. for (let i = dim; i < outerLen; i += dim) {
  19732. x = data[i];
  19733. y = data[i + 1];
  19734. if (x < minX) minX = x;
  19735. if (y < minY) minY = y;
  19736. if (x > maxX) maxX = x;
  19737. if (y > maxY) maxY = y;
  19738. } // minX, minY and invSize are later used to transform coords into integers for z-order calculation
  19739. invSize = Math.max(maxX - minX, maxY - minY);
  19740. invSize = invSize !== 0 ? 1 / invSize : 0;
  19741. }
  19742. earcutLinked(outerNode, triangles, dim, minX, minY, invSize);
  19743. return triangles;
  19744. }
  19745. }; // create a circular doubly linked list from polygon points in the specified winding order
  19746. function linkedList(data, start, end, dim, clockwise) {
  19747. let i, last;
  19748. if (clockwise === signedArea(data, start, end, dim) > 0) {
  19749. for (i = start; i < end; i += dim) last = insertNode(i, data[i], data[i + 1], last);
  19750. } else {
  19751. for (i = end - dim; i >= start; i -= dim) last = insertNode(i, data[i], data[i + 1], last);
  19752. }
  19753. if (last && equals(last, last.next)) {
  19754. removeNode(last);
  19755. last = last.next;
  19756. }
  19757. return last;
  19758. } // eliminate colinear or duplicate points
  19759. function filterPoints(start, end) {
  19760. if (!start) return start;
  19761. if (!end) end = start;
  19762. let p = start,
  19763. again;
  19764. do {
  19765. again = false;
  19766. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  19767. removeNode(p);
  19768. p = end = p.prev;
  19769. if (p === p.next) break;
  19770. again = true;
  19771. } else {
  19772. p = p.next;
  19773. }
  19774. } while (again || p !== end);
  19775. return end;
  19776. } // main ear slicing loop which triangulates a polygon (given as a linked list)
  19777. function earcutLinked(ear, triangles, dim, minX, minY, invSize, pass) {
  19778. if (!ear) return; // interlink polygon nodes in z-order
  19779. if (!pass && invSize) indexCurve(ear, minX, minY, invSize);
  19780. let stop = ear,
  19781. prev,
  19782. next; // iterate through ears, slicing them one by one
  19783. while (ear.prev !== ear.next) {
  19784. prev = ear.prev;
  19785. next = ear.next;
  19786. if (invSize ? isEarHashed(ear, minX, minY, invSize) : isEar(ear)) {
  19787. // cut off the triangle
  19788. triangles.push(prev.i / dim);
  19789. triangles.push(ear.i / dim);
  19790. triangles.push(next.i / dim);
  19791. removeNode(ear); // skipping the next vertex leads to less sliver triangles
  19792. ear = next.next;
  19793. stop = next.next;
  19794. continue;
  19795. }
  19796. ear = next; // if we looped through the whole remaining polygon and can't find any more ears
  19797. if (ear === stop) {
  19798. // try filtering points and slicing again
  19799. if (!pass) {
  19800. earcutLinked(filterPoints(ear), triangles, dim, minX, minY, invSize, 1); // if this didn't work, try curing all small self-intersections locally
  19801. } else if (pass === 1) {
  19802. ear = cureLocalIntersections(filterPoints(ear), triangles, dim);
  19803. earcutLinked(ear, triangles, dim, minX, minY, invSize, 2); // as a last resort, try splitting the remaining polygon into two
  19804. } else if (pass === 2) {
  19805. splitEarcut(ear, triangles, dim, minX, minY, invSize);
  19806. }
  19807. break;
  19808. }
  19809. }
  19810. } // check whether a polygon node forms a valid ear with adjacent nodes
  19811. function isEar(ear) {
  19812. const a = ear.prev,
  19813. b = ear,
  19814. c = ear.next;
  19815. if (area(a, b, c) >= 0) return false; // reflex, can't be an ear
  19816. // now make sure we don't have other points inside the potential ear
  19817. let p = ear.next.next;
  19818. while (p !== ear.prev) {
  19819. 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;
  19820. p = p.next;
  19821. }
  19822. return true;
  19823. }
  19824. function isEarHashed(ear, minX, minY, invSize) {
  19825. const a = ear.prev,
  19826. b = ear,
  19827. c = ear.next;
  19828. if (area(a, b, c) >= 0) return false; // reflex, can't be an ear
  19829. // triangle bbox; min & max are calculated like this for speed
  19830. const minTX = a.x < b.x ? a.x < c.x ? a.x : c.x : b.x < c.x ? b.x : c.x,
  19831. minTY = a.y < b.y ? a.y < c.y ? a.y : c.y : b.y < c.y ? b.y : c.y,
  19832. maxTX = a.x > b.x ? a.x > c.x ? a.x : c.x : b.x > c.x ? b.x : c.x,
  19833. 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;
  19834. const minZ = zOrder(minTX, minTY, minX, minY, invSize),
  19835. maxZ = zOrder(maxTX, maxTY, minX, minY, invSize);
  19836. let p = ear.prevZ,
  19837. n = ear.nextZ; // look for points inside the triangle in both directions
  19838. while (p && p.z >= minZ && n && n.z <= maxZ) {
  19839. 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;
  19840. p = p.prevZ;
  19841. 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;
  19842. n = n.nextZ;
  19843. } // look for remaining points in decreasing z-order
  19844. while (p && p.z >= minZ) {
  19845. 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;
  19846. p = p.prevZ;
  19847. } // look for remaining points in increasing z-order
  19848. while (n && n.z <= maxZ) {
  19849. 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;
  19850. n = n.nextZ;
  19851. }
  19852. return true;
  19853. } // go through all polygon nodes and cure small local self-intersections
  19854. function cureLocalIntersections(start, triangles, dim) {
  19855. let p = start;
  19856. do {
  19857. const a = p.prev,
  19858. b = p.next.next;
  19859. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  19860. triangles.push(a.i / dim);
  19861. triangles.push(p.i / dim);
  19862. triangles.push(b.i / dim); // remove two nodes involved
  19863. removeNode(p);
  19864. removeNode(p.next);
  19865. p = start = b;
  19866. }
  19867. p = p.next;
  19868. } while (p !== start);
  19869. return filterPoints(p);
  19870. } // try splitting polygon into two and triangulate them independently
  19871. function splitEarcut(start, triangles, dim, minX, minY, invSize) {
  19872. // look for a valid diagonal that divides the polygon into two
  19873. let a = start;
  19874. do {
  19875. let b = a.next.next;
  19876. while (b !== a.prev) {
  19877. if (a.i !== b.i && isValidDiagonal(a, b)) {
  19878. // split the polygon in two by the diagonal
  19879. let c = splitPolygon(a, b); // filter colinear points around the cuts
  19880. a = filterPoints(a, a.next);
  19881. c = filterPoints(c, c.next); // run earcut on each half
  19882. earcutLinked(a, triangles, dim, minX, minY, invSize);
  19883. earcutLinked(c, triangles, dim, minX, minY, invSize);
  19884. return;
  19885. }
  19886. b = b.next;
  19887. }
  19888. a = a.next;
  19889. } while (a !== start);
  19890. } // link every hole into the outer loop, producing a single-ring polygon without holes
  19891. function eliminateHoles(data, holeIndices, outerNode, dim) {
  19892. const queue = [];
  19893. let i, len, start, end, list;
  19894. for (i = 0, len = holeIndices.length; i < len; i++) {
  19895. start = holeIndices[i] * dim;
  19896. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  19897. list = linkedList(data, start, end, dim, false);
  19898. if (list === list.next) list.steiner = true;
  19899. queue.push(getLeftmost(list));
  19900. }
  19901. queue.sort(compareX); // process holes from left to right
  19902. for (i = 0; i < queue.length; i++) {
  19903. eliminateHole(queue[i], outerNode);
  19904. outerNode = filterPoints(outerNode, outerNode.next);
  19905. }
  19906. return outerNode;
  19907. }
  19908. function compareX(a, b) {
  19909. return a.x - b.x;
  19910. } // find a bridge between vertices that connects hole with an outer ring and link it
  19911. function eliminateHole(hole, outerNode) {
  19912. outerNode = findHoleBridge(hole, outerNode);
  19913. if (outerNode) {
  19914. const b = splitPolygon(outerNode, hole); // filter collinear points around the cuts
  19915. filterPoints(outerNode, outerNode.next);
  19916. filterPoints(b, b.next);
  19917. }
  19918. } // David Eberly's algorithm for finding a bridge between hole and outer polygon
  19919. function findHoleBridge(hole, outerNode) {
  19920. let p = outerNode;
  19921. const hx = hole.x;
  19922. const hy = hole.y;
  19923. let qx = -Infinity,
  19924. m; // find a segment intersected by a ray from the hole's leftmost point to the left;
  19925. // segment's endpoint with lesser x will be potential connection point
  19926. do {
  19927. if (hy <= p.y && hy >= p.next.y && p.next.y !== p.y) {
  19928. const x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  19929. if (x <= hx && x > qx) {
  19930. qx = x;
  19931. if (x === hx) {
  19932. if (hy === p.y) return p;
  19933. if (hy === p.next.y) return p.next;
  19934. }
  19935. m = p.x < p.next.x ? p : p.next;
  19936. }
  19937. }
  19938. p = p.next;
  19939. } while (p !== outerNode);
  19940. if (!m) return null;
  19941. if (hx === qx) return m; // hole touches outer segment; pick leftmost endpoint
  19942. // look for points inside the triangle of hole point, segment intersection and endpoint;
  19943. // if there are no points found, we have a valid connection;
  19944. // otherwise choose the point of the minimum angle with the ray as connection point
  19945. const stop = m,
  19946. mx = m.x,
  19947. my = m.y;
  19948. let tanMin = Infinity,
  19949. tan;
  19950. p = m;
  19951. do {
  19952. 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)) {
  19953. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  19954. if (locallyInside(p, hole) && (tan < tanMin || tan === tanMin && (p.x > m.x || p.x === m.x && sectorContainsSector(m, p)))) {
  19955. m = p;
  19956. tanMin = tan;
  19957. }
  19958. }
  19959. p = p.next;
  19960. } while (p !== stop);
  19961. return m;
  19962. } // whether sector in vertex m contains sector in vertex p in the same coordinates
  19963. function sectorContainsSector(m, p) {
  19964. return area(m.prev, m, p.prev) < 0 && area(p.next, m, m.next) < 0;
  19965. } // interlink polygon nodes in z-order
  19966. function indexCurve(start, minX, minY, invSize) {
  19967. let p = start;
  19968. do {
  19969. if (p.z === null) p.z = zOrder(p.x, p.y, minX, minY, invSize);
  19970. p.prevZ = p.prev;
  19971. p.nextZ = p.next;
  19972. p = p.next;
  19973. } while (p !== start);
  19974. p.prevZ.nextZ = null;
  19975. p.prevZ = null;
  19976. sortLinked(p);
  19977. } // Simon Tatham's linked list merge sort algorithm
  19978. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  19979. function sortLinked(list) {
  19980. let i,
  19981. p,
  19982. q,
  19983. e,
  19984. tail,
  19985. numMerges,
  19986. pSize,
  19987. qSize,
  19988. inSize = 1;
  19989. do {
  19990. p = list;
  19991. list = null;
  19992. tail = null;
  19993. numMerges = 0;
  19994. while (p) {
  19995. numMerges++;
  19996. q = p;
  19997. pSize = 0;
  19998. for (i = 0; i < inSize; i++) {
  19999. pSize++;
  20000. q = q.nextZ;
  20001. if (!q) break;
  20002. }
  20003. qSize = inSize;
  20004. while (pSize > 0 || qSize > 0 && q) {
  20005. if (pSize !== 0 && (qSize === 0 || !q || p.z <= q.z)) {
  20006. e = p;
  20007. p = p.nextZ;
  20008. pSize--;
  20009. } else {
  20010. e = q;
  20011. q = q.nextZ;
  20012. qSize--;
  20013. }
  20014. if (tail) tail.nextZ = e;else list = e;
  20015. e.prevZ = tail;
  20016. tail = e;
  20017. }
  20018. p = q;
  20019. }
  20020. tail.nextZ = null;
  20021. inSize *= 2;
  20022. } while (numMerges > 1);
  20023. return list;
  20024. } // z-order of a point given coords and inverse of the longer side of data bbox
  20025. function zOrder(x, y, minX, minY, invSize) {
  20026. // coords are transformed into non-negative 15-bit integer range
  20027. x = 32767 * (x - minX) * invSize;
  20028. y = 32767 * (y - minY) * invSize;
  20029. x = (x | x << 8) & 0x00FF00FF;
  20030. x = (x | x << 4) & 0x0F0F0F0F;
  20031. x = (x | x << 2) & 0x33333333;
  20032. x = (x | x << 1) & 0x55555555;
  20033. y = (y | y << 8) & 0x00FF00FF;
  20034. y = (y | y << 4) & 0x0F0F0F0F;
  20035. y = (y | y << 2) & 0x33333333;
  20036. y = (y | y << 1) & 0x55555555;
  20037. return x | y << 1;
  20038. } // find the leftmost node of a polygon ring
  20039. function getLeftmost(start) {
  20040. let p = start,
  20041. leftmost = start;
  20042. do {
  20043. if (p.x < leftmost.x || p.x === leftmost.x && p.y < leftmost.y) leftmost = p;
  20044. p = p.next;
  20045. } while (p !== start);
  20046. return leftmost;
  20047. } // check if a point lies within a convex triangle
  20048. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  20049. 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;
  20050. } // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  20051. function isValidDiagonal(a, b) {
  20052. return a.next.i !== b.i && a.prev.i !== b.i && !intersectsPolygon(a, b) && ( // doesn't intersect other edges
  20053. locallyInside(a, b) && locallyInside(b, a) && middleInside(a, b) && ( // locally visible
  20054. area(a.prev, a, b.prev) || area(a, b.prev, b)) || // does not create opposite-facing sectors
  20055. equals(a, b) && area(a.prev, a, a.next) > 0 && area(b.prev, b, b.next) > 0); // special zero-length case
  20056. } // signed area of a triangle
  20057. function area(p, q, r) {
  20058. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  20059. } // check if two points are equal
  20060. function equals(p1, p2) {
  20061. return p1.x === p2.x && p1.y === p2.y;
  20062. } // check if two segments intersect
  20063. function intersects(p1, q1, p2, q2) {
  20064. const o1 = sign(area(p1, q1, p2));
  20065. const o2 = sign(area(p1, q1, q2));
  20066. const o3 = sign(area(p2, q2, p1));
  20067. const o4 = sign(area(p2, q2, q1));
  20068. if (o1 !== o2 && o3 !== o4) return true; // general case
  20069. if (o1 === 0 && onSegment(p1, p2, q1)) return true; // p1, q1 and p2 are collinear and p2 lies on p1q1
  20070. if (o2 === 0 && onSegment(p1, q2, q1)) return true; // p1, q1 and q2 are collinear and q2 lies on p1q1
  20071. if (o3 === 0 && onSegment(p2, p1, q2)) return true; // p2, q2 and p1 are collinear and p1 lies on p2q2
  20072. if (o4 === 0 && onSegment(p2, q1, q2)) return true; // p2, q2 and q1 are collinear and q1 lies on p2q2
  20073. return false;
  20074. } // for collinear points p, q, r, check if point q lies on segment pr
  20075. function onSegment(p, q, r) {
  20076. 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);
  20077. }
  20078. function sign(num) {
  20079. return num > 0 ? 1 : num < 0 ? -1 : 0;
  20080. } // check if a polygon diagonal intersects any polygon segments
  20081. function intersectsPolygon(a, b) {
  20082. let p = a;
  20083. do {
  20084. 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;
  20085. p = p.next;
  20086. } while (p !== a);
  20087. return false;
  20088. } // check if a polygon diagonal is locally inside the polygon
  20089. function locallyInside(a, b) {
  20090. 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;
  20091. } // check if the middle point of a polygon diagonal is inside the polygon
  20092. function middleInside(a, b) {
  20093. let p = a,
  20094. inside = false;
  20095. const px = (a.x + b.x) / 2,
  20096. py = (a.y + b.y) / 2;
  20097. do {
  20098. 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;
  20099. p = p.next;
  20100. } while (p !== a);
  20101. return inside;
  20102. } // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  20103. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  20104. function splitPolygon(a, b) {
  20105. const a2 = new Node(a.i, a.x, a.y),
  20106. b2 = new Node(b.i, b.x, b.y),
  20107. an = a.next,
  20108. bp = b.prev;
  20109. a.next = b;
  20110. b.prev = a;
  20111. a2.next = an;
  20112. an.prev = a2;
  20113. b2.next = a2;
  20114. a2.prev = b2;
  20115. bp.next = b2;
  20116. b2.prev = bp;
  20117. return b2;
  20118. } // create a node and optionally link it with previous one (in a circular doubly linked list)
  20119. function insertNode(i, x, y, last) {
  20120. const p = new Node(i, x, y);
  20121. if (!last) {
  20122. p.prev = p;
  20123. p.next = p;
  20124. } else {
  20125. p.next = last.next;
  20126. p.prev = last;
  20127. last.next.prev = p;
  20128. last.next = p;
  20129. }
  20130. return p;
  20131. }
  20132. function removeNode(p) {
  20133. p.next.prev = p.prev;
  20134. p.prev.next = p.next;
  20135. if (p.prevZ) p.prevZ.nextZ = p.nextZ;
  20136. if (p.nextZ) p.nextZ.prevZ = p.prevZ;
  20137. }
  20138. function Node(i, x, y) {
  20139. // vertex index in coordinates array
  20140. this.i = i; // vertex coordinates
  20141. this.x = x;
  20142. this.y = y; // previous and next vertex nodes in a polygon ring
  20143. this.prev = null;
  20144. this.next = null; // z-order curve value
  20145. this.z = null; // previous and next nodes in z-order
  20146. this.prevZ = null;
  20147. this.nextZ = null; // indicates whether this is a steiner point
  20148. this.steiner = false;
  20149. }
  20150. function signedArea(data, start, end, dim) {
  20151. let sum = 0;
  20152. for (let i = start, j = end - dim; i < end; i += dim) {
  20153. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  20154. j = i;
  20155. }
  20156. return sum;
  20157. }
  20158. class ShapeUtils {
  20159. // calculate area of the contour polygon
  20160. static area(contour) {
  20161. const n = contour.length;
  20162. let a = 0.0;
  20163. for (let p = n - 1, q = 0; q < n; p = q++) {
  20164. a += contour[p].x * contour[q].y - contour[q].x * contour[p].y;
  20165. }
  20166. return a * 0.5;
  20167. }
  20168. static isClockWise(pts) {
  20169. return ShapeUtils.area(pts) < 0;
  20170. }
  20171. static triangulateShape(contour, holes) {
  20172. const vertices = []; // flat array of vertices like [ x0,y0, x1,y1, x2,y2, ... ]
  20173. const holeIndices = []; // array of hole indices
  20174. const faces = []; // final array of vertex indices like [ [ a,b,d ], [ b,c,d ] ]
  20175. removeDupEndPts(contour);
  20176. addContour(vertices, contour); //
  20177. let holeIndex = contour.length;
  20178. holes.forEach(removeDupEndPts);
  20179. for (let i = 0; i < holes.length; i++) {
  20180. holeIndices.push(holeIndex);
  20181. holeIndex += holes[i].length;
  20182. addContour(vertices, holes[i]);
  20183. } //
  20184. const triangles = Earcut.triangulate(vertices, holeIndices); //
  20185. for (let i = 0; i < triangles.length; i += 3) {
  20186. faces.push(triangles.slice(i, i + 3));
  20187. }
  20188. return faces;
  20189. }
  20190. }
  20191. function removeDupEndPts(points) {
  20192. const l = points.length;
  20193. if (l > 2 && points[l - 1].equals(points[0])) {
  20194. points.pop();
  20195. }
  20196. }
  20197. function addContour(vertices, contour) {
  20198. for (let i = 0; i < contour.length; i++) {
  20199. vertices.push(contour[i].x);
  20200. vertices.push(contour[i].y);
  20201. }
  20202. }
  20203. /**
  20204. * Creates extruded geometry from a path shape.
  20205. *
  20206. * parameters = {
  20207. *
  20208. * curveSegments: <int>, // number of points on the curves
  20209. * steps: <int>, // number of points for z-side extrusions / used for subdividing segments of extrude spline too
  20210. * depth: <float>, // Depth to extrude the shape
  20211. *
  20212. * bevelEnabled: <bool>, // turn on bevel
  20213. * bevelThickness: <float>, // how deep into the original shape bevel goes
  20214. * bevelSize: <float>, // how far from shape outline (including bevelOffset) is bevel
  20215. * bevelOffset: <float>, // how far from shape outline does bevel start
  20216. * bevelSegments: <int>, // number of bevel layers
  20217. *
  20218. * extrudePath: <THREE.Curve> // curve to extrude shape along
  20219. *
  20220. * UVGenerator: <Object> // object that provides UV generator functions
  20221. *
  20222. * }
  20223. */
  20224. class ExtrudeGeometry extends BufferGeometry {
  20225. constructor(shapes = new Shape([new Vector2(0.5, 0.5), new Vector2(-0.5, 0.5), new Vector2(-0.5, -0.5), new Vector2(0.5, -0.5)]), options = {}) {
  20226. super();
  20227. this.type = 'ExtrudeGeometry';
  20228. this.parameters = {
  20229. shapes: shapes,
  20230. options: options
  20231. };
  20232. shapes = Array.isArray(shapes) ? shapes : [shapes];
  20233. const scope = this;
  20234. const verticesArray = [];
  20235. const uvArray = [];
  20236. for (let i = 0, l = shapes.length; i < l; i++) {
  20237. const shape = shapes[i];
  20238. addShape(shape);
  20239. } // build geometry
  20240. this.setAttribute('position', new Float32BufferAttribute(verticesArray, 3));
  20241. this.setAttribute('uv', new Float32BufferAttribute(uvArray, 2));
  20242. this.computeVertexNormals(); // functions
  20243. function addShape(shape) {
  20244. const placeholder = []; // options
  20245. const curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  20246. const steps = options.steps !== undefined ? options.steps : 1;
  20247. let depth = options.depth !== undefined ? options.depth : 1;
  20248. let bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true;
  20249. let bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 0.2;
  20250. let bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 0.1;
  20251. let bevelOffset = options.bevelOffset !== undefined ? options.bevelOffset : 0;
  20252. let bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  20253. const extrudePath = options.extrudePath;
  20254. const uvgen = options.UVGenerator !== undefined ? options.UVGenerator : WorldUVGenerator; // deprecated options
  20255. if (options.amount !== undefined) {
  20256. console.warn('THREE.ExtrudeBufferGeometry: amount has been renamed to depth.');
  20257. depth = options.amount;
  20258. } //
  20259. let extrudePts,
  20260. extrudeByPath = false;
  20261. let splineTube, binormal, normal, position2;
  20262. if (extrudePath) {
  20263. extrudePts = extrudePath.getSpacedPoints(steps);
  20264. extrudeByPath = true;
  20265. bevelEnabled = false; // bevels not supported for path extrusion
  20266. // SETUP TNB variables
  20267. // TODO1 - have a .isClosed in spline?
  20268. splineTube = extrudePath.computeFrenetFrames(steps, false); // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  20269. binormal = new Vector3();
  20270. normal = new Vector3();
  20271. position2 = new Vector3();
  20272. } // Safeguards if bevels are not enabled
  20273. if (!bevelEnabled) {
  20274. bevelSegments = 0;
  20275. bevelThickness = 0;
  20276. bevelSize = 0;
  20277. bevelOffset = 0;
  20278. } // Variables initialization
  20279. const shapePoints = shape.extractPoints(curveSegments);
  20280. let vertices = shapePoints.shape;
  20281. const holes = shapePoints.holes;
  20282. const reverse = !ShapeUtils.isClockWise(vertices);
  20283. if (reverse) {
  20284. vertices = vertices.reverse(); // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  20285. for (let h = 0, hl = holes.length; h < hl; h++) {
  20286. const ahole = holes[h];
  20287. if (ShapeUtils.isClockWise(ahole)) {
  20288. holes[h] = ahole.reverse();
  20289. }
  20290. }
  20291. }
  20292. const faces = ShapeUtils.triangulateShape(vertices, holes);
  20293. /* Vertices */
  20294. const contour = vertices; // vertices has all points but contour has only points of circumference
  20295. for (let h = 0, hl = holes.length; h < hl; h++) {
  20296. const ahole = holes[h];
  20297. vertices = vertices.concat(ahole);
  20298. }
  20299. function scalePt2(pt, vec, size) {
  20300. if (!vec) console.error('THREE.ExtrudeGeometry: vec does not exist');
  20301. return vec.clone().multiplyScalar(size).add(pt);
  20302. }
  20303. const vlen = vertices.length,
  20304. flen = faces.length; // Find directions for point movement
  20305. function getBevelVec(inPt, inPrev, inNext) {
  20306. // computes for inPt the corresponding point inPt' on a new contour
  20307. // shifted by 1 unit (length of normalized vector) to the left
  20308. // if we walk along contour clockwise, this new contour is outside the old one
  20309. //
  20310. // inPt' is the intersection of the two lines parallel to the two
  20311. // adjacent edges of inPt at a distance of 1 unit on the left side.
  20312. let v_trans_x, v_trans_y, shrink_by; // resulting translation vector for inPt
  20313. // good reading for geometry algorithms (here: line-line intersection)
  20314. // http://geomalgorithms.com/a05-_intersect-1.html
  20315. const v_prev_x = inPt.x - inPrev.x,
  20316. v_prev_y = inPt.y - inPrev.y;
  20317. const v_next_x = inNext.x - inPt.x,
  20318. v_next_y = inNext.y - inPt.y;
  20319. const v_prev_lensq = v_prev_x * v_prev_x + v_prev_y * v_prev_y; // check for collinear edges
  20320. const collinear0 = v_prev_x * v_next_y - v_prev_y * v_next_x;
  20321. if (Math.abs(collinear0) > Number.EPSILON) {
  20322. // not collinear
  20323. // length of vectors for normalizing
  20324. const v_prev_len = Math.sqrt(v_prev_lensq);
  20325. 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
  20326. const ptPrevShift_x = inPrev.x - v_prev_y / v_prev_len;
  20327. const ptPrevShift_y = inPrev.y + v_prev_x / v_prev_len;
  20328. const ptNextShift_x = inNext.x - v_next_y / v_next_len;
  20329. const ptNextShift_y = inNext.y + v_next_x / v_next_len; // scaling factor for v_prev to intersection point
  20330. 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
  20331. v_trans_x = ptPrevShift_x + v_prev_x * sf - inPt.x;
  20332. v_trans_y = ptPrevShift_y + v_prev_y * sf - inPt.y; // Don't normalize!, otherwise sharp corners become ugly
  20333. // but prevent crazy spikes
  20334. const v_trans_lensq = v_trans_x * v_trans_x + v_trans_y * v_trans_y;
  20335. if (v_trans_lensq <= 2) {
  20336. return new Vector2(v_trans_x, v_trans_y);
  20337. } else {
  20338. shrink_by = Math.sqrt(v_trans_lensq / 2);
  20339. }
  20340. } else {
  20341. // handle special case of collinear edges
  20342. let direction_eq = false; // assumes: opposite
  20343. if (v_prev_x > Number.EPSILON) {
  20344. if (v_next_x > Number.EPSILON) {
  20345. direction_eq = true;
  20346. }
  20347. } else {
  20348. if (v_prev_x < -Number.EPSILON) {
  20349. if (v_next_x < -Number.EPSILON) {
  20350. direction_eq = true;
  20351. }
  20352. } else {
  20353. if (Math.sign(v_prev_y) === Math.sign(v_next_y)) {
  20354. direction_eq = true;
  20355. }
  20356. }
  20357. }
  20358. if (direction_eq) {
  20359. // console.log("Warning: lines are a straight sequence");
  20360. v_trans_x = -v_prev_y;
  20361. v_trans_y = v_prev_x;
  20362. shrink_by = Math.sqrt(v_prev_lensq);
  20363. } else {
  20364. // console.log("Warning: lines are a straight spike");
  20365. v_trans_x = v_prev_x;
  20366. v_trans_y = v_prev_y;
  20367. shrink_by = Math.sqrt(v_prev_lensq / 2);
  20368. }
  20369. }
  20370. return new Vector2(v_trans_x / shrink_by, v_trans_y / shrink_by);
  20371. }
  20372. const contourMovements = [];
  20373. for (let i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i++, j++, k++) {
  20374. if (j === il) j = 0;
  20375. if (k === il) k = 0; // (j)---(i)---(k)
  20376. // console.log('i,j,k', i, j , k)
  20377. contourMovements[i] = getBevelVec(contour[i], contour[j], contour[k]);
  20378. }
  20379. const holesMovements = [];
  20380. let oneHoleMovements,
  20381. verticesMovements = contourMovements.concat();
  20382. for (let h = 0, hl = holes.length; h < hl; h++) {
  20383. const ahole = holes[h];
  20384. oneHoleMovements = [];
  20385. for (let i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i++, j++, k++) {
  20386. if (j === il) j = 0;
  20387. if (k === il) k = 0; // (j)---(i)---(k)
  20388. oneHoleMovements[i] = getBevelVec(ahole[i], ahole[j], ahole[k]);
  20389. }
  20390. holesMovements.push(oneHoleMovements);
  20391. verticesMovements = verticesMovements.concat(oneHoleMovements);
  20392. } // Loop bevelSegments, 1 for the front, 1 for the back
  20393. for (let b = 0; b < bevelSegments; b++) {
  20394. //for ( b = bevelSegments; b > 0; b -- ) {
  20395. const t = b / bevelSegments;
  20396. const z = bevelThickness * Math.cos(t * Math.PI / 2);
  20397. const bs = bevelSize * Math.sin(t * Math.PI / 2) + bevelOffset; // contract shape
  20398. for (let i = 0, il = contour.length; i < il; i++) {
  20399. const vert = scalePt2(contour[i], contourMovements[i], bs);
  20400. v(vert.x, vert.y, -z);
  20401. } // expand holes
  20402. for (let h = 0, hl = holes.length; h < hl; h++) {
  20403. const ahole = holes[h];
  20404. oneHoleMovements = holesMovements[h];
  20405. for (let i = 0, il = ahole.length; i < il; i++) {
  20406. const vert = scalePt2(ahole[i], oneHoleMovements[i], bs);
  20407. v(vert.x, vert.y, -z);
  20408. }
  20409. }
  20410. }
  20411. const bs = bevelSize + bevelOffset; // Back facing vertices
  20412. for (let i = 0; i < vlen; i++) {
  20413. const vert = bevelEnabled ? scalePt2(vertices[i], verticesMovements[i], bs) : vertices[i];
  20414. if (!extrudeByPath) {
  20415. v(vert.x, vert.y, 0);
  20416. } else {
  20417. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  20418. normal.copy(splineTube.normals[0]).multiplyScalar(vert.x);
  20419. binormal.copy(splineTube.binormals[0]).multiplyScalar(vert.y);
  20420. position2.copy(extrudePts[0]).add(normal).add(binormal);
  20421. v(position2.x, position2.y, position2.z);
  20422. }
  20423. } // Add stepped vertices...
  20424. // Including front facing vertices
  20425. for (let s = 1; s <= steps; s++) {
  20426. for (let i = 0; i < vlen; i++) {
  20427. const vert = bevelEnabled ? scalePt2(vertices[i], verticesMovements[i], bs) : vertices[i];
  20428. if (!extrudeByPath) {
  20429. v(vert.x, vert.y, depth / steps * s);
  20430. } else {
  20431. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  20432. normal.copy(splineTube.normals[s]).multiplyScalar(vert.x);
  20433. binormal.copy(splineTube.binormals[s]).multiplyScalar(vert.y);
  20434. position2.copy(extrudePts[s]).add(normal).add(binormal);
  20435. v(position2.x, position2.y, position2.z);
  20436. }
  20437. }
  20438. } // Add bevel segments planes
  20439. //for ( b = 1; b <= bevelSegments; b ++ ) {
  20440. for (let b = bevelSegments - 1; b >= 0; b--) {
  20441. const t = b / bevelSegments;
  20442. const z = bevelThickness * Math.cos(t * Math.PI / 2);
  20443. const bs = bevelSize * Math.sin(t * Math.PI / 2) + bevelOffset; // contract shape
  20444. for (let i = 0, il = contour.length; i < il; i++) {
  20445. const vert = scalePt2(contour[i], contourMovements[i], bs);
  20446. v(vert.x, vert.y, depth + z);
  20447. } // expand holes
  20448. for (let h = 0, hl = holes.length; h < hl; h++) {
  20449. const ahole = holes[h];
  20450. oneHoleMovements = holesMovements[h];
  20451. for (let i = 0, il = ahole.length; i < il; i++) {
  20452. const vert = scalePt2(ahole[i], oneHoleMovements[i], bs);
  20453. if (!extrudeByPath) {
  20454. v(vert.x, vert.y, depth + z);
  20455. } else {
  20456. v(vert.x, vert.y + extrudePts[steps - 1].y, extrudePts[steps - 1].x + z);
  20457. }
  20458. }
  20459. }
  20460. }
  20461. /* Faces */
  20462. // Top and bottom faces
  20463. buildLidFaces(); // Sides faces
  20464. buildSideFaces(); ///// Internal functions
  20465. function buildLidFaces() {
  20466. const start = verticesArray.length / 3;
  20467. if (bevelEnabled) {
  20468. let layer = 0; // steps + 1
  20469. let offset = vlen * layer; // Bottom faces
  20470. for (let i = 0; i < flen; i++) {
  20471. const face = faces[i];
  20472. f3(face[2] + offset, face[1] + offset, face[0] + offset);
  20473. }
  20474. layer = steps + bevelSegments * 2;
  20475. offset = vlen * layer; // Top faces
  20476. for (let i = 0; i < flen; i++) {
  20477. const face = faces[i];
  20478. f3(face[0] + offset, face[1] + offset, face[2] + offset);
  20479. }
  20480. } else {
  20481. // Bottom faces
  20482. for (let i = 0; i < flen; i++) {
  20483. const face = faces[i];
  20484. f3(face[2], face[1], face[0]);
  20485. } // Top faces
  20486. for (let i = 0; i < flen; i++) {
  20487. const face = faces[i];
  20488. f3(face[0] + vlen * steps, face[1] + vlen * steps, face[2] + vlen * steps);
  20489. }
  20490. }
  20491. scope.addGroup(start, verticesArray.length / 3 - start, 0);
  20492. } // Create faces for the z-sides of the shape
  20493. function buildSideFaces() {
  20494. const start = verticesArray.length / 3;
  20495. let layeroffset = 0;
  20496. sidewalls(contour, layeroffset);
  20497. layeroffset += contour.length;
  20498. for (let h = 0, hl = holes.length; h < hl; h++) {
  20499. const ahole = holes[h];
  20500. sidewalls(ahole, layeroffset); //, true
  20501. layeroffset += ahole.length;
  20502. }
  20503. scope.addGroup(start, verticesArray.length / 3 - start, 1);
  20504. }
  20505. function sidewalls(contour, layeroffset) {
  20506. let i = contour.length;
  20507. while (--i >= 0) {
  20508. const j = i;
  20509. let k = i - 1;
  20510. if (k < 0) k = contour.length - 1; //console.log('b', i,j, i-1, k,vertices.length);
  20511. for (let s = 0, sl = steps + bevelSegments * 2; s < sl; s++) {
  20512. const slen1 = vlen * s;
  20513. const slen2 = vlen * (s + 1);
  20514. const a = layeroffset + j + slen1,
  20515. b = layeroffset + k + slen1,
  20516. c = layeroffset + k + slen2,
  20517. d = layeroffset + j + slen2;
  20518. f4(a, b, c, d);
  20519. }
  20520. }
  20521. }
  20522. function v(x, y, z) {
  20523. placeholder.push(x);
  20524. placeholder.push(y);
  20525. placeholder.push(z);
  20526. }
  20527. function f3(a, b, c) {
  20528. addVertex(a);
  20529. addVertex(b);
  20530. addVertex(c);
  20531. const nextIndex = verticesArray.length / 3;
  20532. const uvs = uvgen.generateTopUV(scope, verticesArray, nextIndex - 3, nextIndex - 2, nextIndex - 1);
  20533. addUV(uvs[0]);
  20534. addUV(uvs[1]);
  20535. addUV(uvs[2]);
  20536. }
  20537. function f4(a, b, c, d) {
  20538. addVertex(a);
  20539. addVertex(b);
  20540. addVertex(d);
  20541. addVertex(b);
  20542. addVertex(c);
  20543. addVertex(d);
  20544. const nextIndex = verticesArray.length / 3;
  20545. const uvs = uvgen.generateSideWallUV(scope, verticesArray, nextIndex - 6, nextIndex - 3, nextIndex - 2, nextIndex - 1);
  20546. addUV(uvs[0]);
  20547. addUV(uvs[1]);
  20548. addUV(uvs[3]);
  20549. addUV(uvs[1]);
  20550. addUV(uvs[2]);
  20551. addUV(uvs[3]);
  20552. }
  20553. function addVertex(index) {
  20554. verticesArray.push(placeholder[index * 3 + 0]);
  20555. verticesArray.push(placeholder[index * 3 + 1]);
  20556. verticesArray.push(placeholder[index * 3 + 2]);
  20557. }
  20558. function addUV(vector2) {
  20559. uvArray.push(vector2.x);
  20560. uvArray.push(vector2.y);
  20561. }
  20562. }
  20563. }
  20564. toJSON() {
  20565. const data = super.toJSON();
  20566. const shapes = this.parameters.shapes;
  20567. const options = this.parameters.options;
  20568. return toJSON$1(shapes, options, data);
  20569. }
  20570. static fromJSON(data, shapes) {
  20571. const geometryShapes = [];
  20572. for (let j = 0, jl = data.shapes.length; j < jl; j++) {
  20573. const shape = shapes[data.shapes[j]];
  20574. geometryShapes.push(shape);
  20575. }
  20576. const extrudePath = data.options.extrudePath;
  20577. if (extrudePath !== undefined) {
  20578. data.options.extrudePath = new Curves[extrudePath.type]().fromJSON(extrudePath);
  20579. }
  20580. return new ExtrudeGeometry(geometryShapes, data.options);
  20581. }
  20582. }
  20583. const WorldUVGenerator = {
  20584. generateTopUV: function (geometry, vertices, indexA, indexB, indexC) {
  20585. const a_x = vertices[indexA * 3];
  20586. const a_y = vertices[indexA * 3 + 1];
  20587. const b_x = vertices[indexB * 3];
  20588. const b_y = vertices[indexB * 3 + 1];
  20589. const c_x = vertices[indexC * 3];
  20590. const c_y = vertices[indexC * 3 + 1];
  20591. return [new Vector2(a_x, a_y), new Vector2(b_x, b_y), new Vector2(c_x, c_y)];
  20592. },
  20593. generateSideWallUV: function (geometry, vertices, indexA, indexB, indexC, indexD) {
  20594. const a_x = vertices[indexA * 3];
  20595. const a_y = vertices[indexA * 3 + 1];
  20596. const a_z = vertices[indexA * 3 + 2];
  20597. const b_x = vertices[indexB * 3];
  20598. const b_y = vertices[indexB * 3 + 1];
  20599. const b_z = vertices[indexB * 3 + 2];
  20600. const c_x = vertices[indexC * 3];
  20601. const c_y = vertices[indexC * 3 + 1];
  20602. const c_z = vertices[indexC * 3 + 2];
  20603. const d_x = vertices[indexD * 3];
  20604. const d_y = vertices[indexD * 3 + 1];
  20605. const d_z = vertices[indexD * 3 + 2];
  20606. if (Math.abs(a_y - b_y) < Math.abs(a_x - b_x)) {
  20607. 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)];
  20608. } else {
  20609. 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)];
  20610. }
  20611. }
  20612. };
  20613. function toJSON$1(shapes, options, data) {
  20614. data.shapes = [];
  20615. if (Array.isArray(shapes)) {
  20616. for (let i = 0, l = shapes.length; i < l; i++) {
  20617. const shape = shapes[i];
  20618. data.shapes.push(shape.uuid);
  20619. }
  20620. } else {
  20621. data.shapes.push(shapes.uuid);
  20622. }
  20623. data.options = Object.assign({}, options);
  20624. if (options.extrudePath !== undefined) data.options.extrudePath = options.extrudePath.toJSON();
  20625. return data;
  20626. }
  20627. class IcosahedronGeometry extends PolyhedronGeometry {
  20628. constructor(radius = 1, detail = 0) {
  20629. const t = (1 + Math.sqrt(5)) / 2;
  20630. 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];
  20631. 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];
  20632. super(vertices, indices, radius, detail);
  20633. this.type = 'IcosahedronGeometry';
  20634. this.parameters = {
  20635. radius: radius,
  20636. detail: detail
  20637. };
  20638. }
  20639. static fromJSON(data) {
  20640. return new IcosahedronGeometry(data.radius, data.detail);
  20641. }
  20642. }
  20643. class OctahedronGeometry extends PolyhedronGeometry {
  20644. constructor(radius = 1, detail = 0) {
  20645. const vertices = [1, 0, 0, -1, 0, 0, 0, 1, 0, 0, -1, 0, 0, 0, 1, 0, 0, -1];
  20646. 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];
  20647. super(vertices, indices, radius, detail);
  20648. this.type = 'OctahedronGeometry';
  20649. this.parameters = {
  20650. radius: radius,
  20651. detail: detail
  20652. };
  20653. }
  20654. static fromJSON(data) {
  20655. return new OctahedronGeometry(data.radius, data.detail);
  20656. }
  20657. }
  20658. class RingGeometry extends BufferGeometry {
  20659. constructor(innerRadius = 0.5, outerRadius = 1, thetaSegments = 8, phiSegments = 1, thetaStart = 0, thetaLength = Math.PI * 2) {
  20660. super();
  20661. this.type = 'RingGeometry';
  20662. this.parameters = {
  20663. innerRadius: innerRadius,
  20664. outerRadius: outerRadius,
  20665. thetaSegments: thetaSegments,
  20666. phiSegments: phiSegments,
  20667. thetaStart: thetaStart,
  20668. thetaLength: thetaLength
  20669. };
  20670. thetaSegments = Math.max(3, thetaSegments);
  20671. phiSegments = Math.max(1, phiSegments); // buffers
  20672. const indices = [];
  20673. const vertices = [];
  20674. const normals = [];
  20675. const uvs = []; // some helper variables
  20676. let radius = innerRadius;
  20677. const radiusStep = (outerRadius - innerRadius) / phiSegments;
  20678. const vertex = new Vector3();
  20679. const uv = new Vector2(); // generate vertices, normals and uvs
  20680. for (let j = 0; j <= phiSegments; j++) {
  20681. for (let i = 0; i <= thetaSegments; i++) {
  20682. // values are generate from the inside of the ring to the outside
  20683. const segment = thetaStart + i / thetaSegments * thetaLength; // vertex
  20684. vertex.x = radius * Math.cos(segment);
  20685. vertex.y = radius * Math.sin(segment);
  20686. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  20687. normals.push(0, 0, 1); // uv
  20688. uv.x = (vertex.x / outerRadius + 1) / 2;
  20689. uv.y = (vertex.y / outerRadius + 1) / 2;
  20690. uvs.push(uv.x, uv.y);
  20691. } // increase the radius for next row of vertices
  20692. radius += radiusStep;
  20693. } // indices
  20694. for (let j = 0; j < phiSegments; j++) {
  20695. const thetaSegmentLevel = j * (thetaSegments + 1);
  20696. for (let i = 0; i < thetaSegments; i++) {
  20697. const segment = i + thetaSegmentLevel;
  20698. const a = segment;
  20699. const b = segment + thetaSegments + 1;
  20700. const c = segment + thetaSegments + 2;
  20701. const d = segment + 1; // faces
  20702. indices.push(a, b, d);
  20703. indices.push(b, c, d);
  20704. }
  20705. } // build geometry
  20706. this.setIndex(indices);
  20707. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  20708. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  20709. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  20710. }
  20711. static fromJSON(data) {
  20712. return new RingGeometry(data.innerRadius, data.outerRadius, data.thetaSegments, data.phiSegments, data.thetaStart, data.thetaLength);
  20713. }
  20714. }
  20715. class ShapeGeometry extends BufferGeometry {
  20716. constructor(shapes = new Shape([new Vector2(0, 0.5), new Vector2(-0.5, -0.5), new Vector2(0.5, -0.5)]), curveSegments = 12) {
  20717. super();
  20718. this.type = 'ShapeGeometry';
  20719. this.parameters = {
  20720. shapes: shapes,
  20721. curveSegments: curveSegments
  20722. }; // buffers
  20723. const indices = [];
  20724. const vertices = [];
  20725. const normals = [];
  20726. const uvs = []; // helper variables
  20727. let groupStart = 0;
  20728. let groupCount = 0; // allow single and array values for "shapes" parameter
  20729. if (Array.isArray(shapes) === false) {
  20730. addShape(shapes);
  20731. } else {
  20732. for (let i = 0; i < shapes.length; i++) {
  20733. addShape(shapes[i]);
  20734. this.addGroup(groupStart, groupCount, i); // enables MultiMaterial support
  20735. groupStart += groupCount;
  20736. groupCount = 0;
  20737. }
  20738. } // build geometry
  20739. this.setIndex(indices);
  20740. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  20741. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  20742. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2)); // helper functions
  20743. function addShape(shape) {
  20744. const indexOffset = vertices.length / 3;
  20745. const points = shape.extractPoints(curveSegments);
  20746. let shapeVertices = points.shape;
  20747. const shapeHoles = points.holes; // check direction of vertices
  20748. if (ShapeUtils.isClockWise(shapeVertices) === false) {
  20749. shapeVertices = shapeVertices.reverse();
  20750. }
  20751. for (let i = 0, l = shapeHoles.length; i < l; i++) {
  20752. const shapeHole = shapeHoles[i];
  20753. if (ShapeUtils.isClockWise(shapeHole) === true) {
  20754. shapeHoles[i] = shapeHole.reverse();
  20755. }
  20756. }
  20757. const faces = ShapeUtils.triangulateShape(shapeVertices, shapeHoles); // join vertices of inner and outer paths to a single array
  20758. for (let i = 0, l = shapeHoles.length; i < l; i++) {
  20759. const shapeHole = shapeHoles[i];
  20760. shapeVertices = shapeVertices.concat(shapeHole);
  20761. } // vertices, normals, uvs
  20762. for (let i = 0, l = shapeVertices.length; i < l; i++) {
  20763. const vertex = shapeVertices[i];
  20764. vertices.push(vertex.x, vertex.y, 0);
  20765. normals.push(0, 0, 1);
  20766. uvs.push(vertex.x, vertex.y); // world uvs
  20767. } // incides
  20768. for (let i = 0, l = faces.length; i < l; i++) {
  20769. const face = faces[i];
  20770. const a = face[0] + indexOffset;
  20771. const b = face[1] + indexOffset;
  20772. const c = face[2] + indexOffset;
  20773. indices.push(a, b, c);
  20774. groupCount += 3;
  20775. }
  20776. }
  20777. }
  20778. toJSON() {
  20779. const data = super.toJSON();
  20780. const shapes = this.parameters.shapes;
  20781. return toJSON(shapes, data);
  20782. }
  20783. static fromJSON(data, shapes) {
  20784. const geometryShapes = [];
  20785. for (let j = 0, jl = data.shapes.length; j < jl; j++) {
  20786. const shape = shapes[data.shapes[j]];
  20787. geometryShapes.push(shape);
  20788. }
  20789. return new ShapeGeometry(geometryShapes, data.curveSegments);
  20790. }
  20791. }
  20792. function toJSON(shapes, data) {
  20793. data.shapes = [];
  20794. if (Array.isArray(shapes)) {
  20795. for (let i = 0, l = shapes.length; i < l; i++) {
  20796. const shape = shapes[i];
  20797. data.shapes.push(shape.uuid);
  20798. }
  20799. } else {
  20800. data.shapes.push(shapes.uuid);
  20801. }
  20802. return data;
  20803. }
  20804. class SphereGeometry extends BufferGeometry {
  20805. constructor(radius = 1, widthSegments = 32, heightSegments = 16, phiStart = 0, phiLength = Math.PI * 2, thetaStart = 0, thetaLength = Math.PI) {
  20806. super();
  20807. this.type = 'SphereGeometry';
  20808. this.parameters = {
  20809. radius: radius,
  20810. widthSegments: widthSegments,
  20811. heightSegments: heightSegments,
  20812. phiStart: phiStart,
  20813. phiLength: phiLength,
  20814. thetaStart: thetaStart,
  20815. thetaLength: thetaLength
  20816. };
  20817. widthSegments = Math.max(3, Math.floor(widthSegments));
  20818. heightSegments = Math.max(2, Math.floor(heightSegments));
  20819. const thetaEnd = Math.min(thetaStart + thetaLength, Math.PI);
  20820. let index = 0;
  20821. const grid = [];
  20822. const vertex = new Vector3();
  20823. const normal = new Vector3(); // buffers
  20824. const indices = [];
  20825. const vertices = [];
  20826. const normals = [];
  20827. const uvs = []; // generate vertices, normals and uvs
  20828. for (let iy = 0; iy <= heightSegments; iy++) {
  20829. const verticesRow = [];
  20830. const v = iy / heightSegments; // special case for the poles
  20831. let uOffset = 0;
  20832. if (iy == 0 && thetaStart == 0) {
  20833. uOffset = 0.5 / widthSegments;
  20834. } else if (iy == heightSegments && thetaEnd == Math.PI) {
  20835. uOffset = -0.5 / widthSegments;
  20836. }
  20837. for (let ix = 0; ix <= widthSegments; ix++) {
  20838. const u = ix / widthSegments; // vertex
  20839. vertex.x = -radius * Math.cos(phiStart + u * phiLength) * Math.sin(thetaStart + v * thetaLength);
  20840. vertex.y = radius * Math.cos(thetaStart + v * thetaLength);
  20841. vertex.z = radius * Math.sin(phiStart + u * phiLength) * Math.sin(thetaStart + v * thetaLength);
  20842. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  20843. normal.copy(vertex).normalize();
  20844. normals.push(normal.x, normal.y, normal.z); // uv
  20845. uvs.push(u + uOffset, 1 - v);
  20846. verticesRow.push(index++);
  20847. }
  20848. grid.push(verticesRow);
  20849. } // indices
  20850. for (let iy = 0; iy < heightSegments; iy++) {
  20851. for (let ix = 0; ix < widthSegments; ix++) {
  20852. const a = grid[iy][ix + 1];
  20853. const b = grid[iy][ix];
  20854. const c = grid[iy + 1][ix];
  20855. const d = grid[iy + 1][ix + 1];
  20856. if (iy !== 0 || thetaStart > 0) indices.push(a, b, d);
  20857. if (iy !== heightSegments - 1 || thetaEnd < Math.PI) indices.push(b, c, d);
  20858. }
  20859. } // build geometry
  20860. this.setIndex(indices);
  20861. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  20862. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  20863. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  20864. }
  20865. static fromJSON(data) {
  20866. return new SphereGeometry(data.radius, data.widthSegments, data.heightSegments, data.phiStart, data.phiLength, data.thetaStart, data.thetaLength);
  20867. }
  20868. }
  20869. class TetrahedronGeometry extends PolyhedronGeometry {
  20870. constructor(radius = 1, detail = 0) {
  20871. const vertices = [1, 1, 1, -1, -1, 1, -1, 1, -1, 1, -1, -1];
  20872. const indices = [2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1];
  20873. super(vertices, indices, radius, detail);
  20874. this.type = 'TetrahedronGeometry';
  20875. this.parameters = {
  20876. radius: radius,
  20877. detail: detail
  20878. };
  20879. }
  20880. static fromJSON(data) {
  20881. return new TetrahedronGeometry(data.radius, data.detail);
  20882. }
  20883. }
  20884. class TorusGeometry extends BufferGeometry {
  20885. constructor(radius = 1, tube = 0.4, radialSegments = 8, tubularSegments = 6, arc = Math.PI * 2) {
  20886. super();
  20887. this.type = 'TorusGeometry';
  20888. this.parameters = {
  20889. radius: radius,
  20890. tube: tube,
  20891. radialSegments: radialSegments,
  20892. tubularSegments: tubularSegments,
  20893. arc: arc
  20894. };
  20895. radialSegments = Math.floor(radialSegments);
  20896. tubularSegments = Math.floor(tubularSegments); // buffers
  20897. const indices = [];
  20898. const vertices = [];
  20899. const normals = [];
  20900. const uvs = []; // helper variables
  20901. const center = new Vector3();
  20902. const vertex = new Vector3();
  20903. const normal = new Vector3(); // generate vertices, normals and uvs
  20904. for (let j = 0; j <= radialSegments; j++) {
  20905. for (let i = 0; i <= tubularSegments; i++) {
  20906. const u = i / tubularSegments * arc;
  20907. const v = j / radialSegments * Math.PI * 2; // vertex
  20908. vertex.x = (radius + tube * Math.cos(v)) * Math.cos(u);
  20909. vertex.y = (radius + tube * Math.cos(v)) * Math.sin(u);
  20910. vertex.z = tube * Math.sin(v);
  20911. vertices.push(vertex.x, vertex.y, vertex.z); // normal
  20912. center.x = radius * Math.cos(u);
  20913. center.y = radius * Math.sin(u);
  20914. normal.subVectors(vertex, center).normalize();
  20915. normals.push(normal.x, normal.y, normal.z); // uv
  20916. uvs.push(i / tubularSegments);
  20917. uvs.push(j / radialSegments);
  20918. }
  20919. } // generate indices
  20920. for (let j = 1; j <= radialSegments; j++) {
  20921. for (let i = 1; i <= tubularSegments; i++) {
  20922. // indices
  20923. const a = (tubularSegments + 1) * j + i - 1;
  20924. const b = (tubularSegments + 1) * (j - 1) + i - 1;
  20925. const c = (tubularSegments + 1) * (j - 1) + i;
  20926. const d = (tubularSegments + 1) * j + i; // faces
  20927. indices.push(a, b, d);
  20928. indices.push(b, c, d);
  20929. }
  20930. } // build geometry
  20931. this.setIndex(indices);
  20932. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  20933. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  20934. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  20935. }
  20936. static fromJSON(data) {
  20937. return new TorusGeometry(data.radius, data.tube, data.radialSegments, data.tubularSegments, data.arc);
  20938. }
  20939. }
  20940. class TorusKnotGeometry extends BufferGeometry {
  20941. constructor(radius = 1, tube = 0.4, tubularSegments = 64, radialSegments = 8, p = 2, q = 3) {
  20942. super();
  20943. this.type = 'TorusKnotGeometry';
  20944. this.parameters = {
  20945. radius: radius,
  20946. tube: tube,
  20947. tubularSegments: tubularSegments,
  20948. radialSegments: radialSegments,
  20949. p: p,
  20950. q: q
  20951. };
  20952. tubularSegments = Math.floor(tubularSegments);
  20953. radialSegments = Math.floor(radialSegments); // buffers
  20954. const indices = [];
  20955. const vertices = [];
  20956. const normals = [];
  20957. const uvs = []; // helper variables
  20958. const vertex = new Vector3();
  20959. const normal = new Vector3();
  20960. const P1 = new Vector3();
  20961. const P2 = new Vector3();
  20962. const B = new Vector3();
  20963. const T = new Vector3();
  20964. const N = new Vector3(); // generate vertices, normals and uvs
  20965. for (let i = 0; i <= tubularSegments; ++i) {
  20966. // the radian "u" is used to calculate the position on the torus curve of the current tubular segment
  20967. 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.
  20968. // these points are used to create a special "coordinate space", which is necessary to calculate the correct vertex positions
  20969. calculatePositionOnCurve(u, p, q, radius, P1);
  20970. calculatePositionOnCurve(u + 0.01, p, q, radius, P2); // calculate orthonormal basis
  20971. T.subVectors(P2, P1);
  20972. N.addVectors(P2, P1);
  20973. B.crossVectors(T, N);
  20974. N.crossVectors(B, T); // normalize B, N. T can be ignored, we don't use it
  20975. B.normalize();
  20976. N.normalize();
  20977. for (let j = 0; j <= radialSegments; ++j) {
  20978. // now calculate the vertices. they are nothing more than an extrusion of the torus curve.
  20979. // because we extrude a shape in the xy-plane, there is no need to calculate a z-value.
  20980. const v = j / radialSegments * Math.PI * 2;
  20981. const cx = -tube * Math.cos(v);
  20982. const cy = tube * Math.sin(v); // now calculate the final vertex position.
  20983. // first we orient the extrusion with our basis vectors, then we add it to the current position on the curve
  20984. vertex.x = P1.x + (cx * N.x + cy * B.x);
  20985. vertex.y = P1.y + (cx * N.y + cy * B.y);
  20986. vertex.z = P1.z + (cx * N.z + cy * B.z);
  20987. 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)
  20988. normal.subVectors(vertex, P1).normalize();
  20989. normals.push(normal.x, normal.y, normal.z); // uv
  20990. uvs.push(i / tubularSegments);
  20991. uvs.push(j / radialSegments);
  20992. }
  20993. } // generate indices
  20994. for (let j = 1; j <= tubularSegments; j++) {
  20995. for (let i = 1; i <= radialSegments; i++) {
  20996. // indices
  20997. const a = (radialSegments + 1) * (j - 1) + (i - 1);
  20998. const b = (radialSegments + 1) * j + (i - 1);
  20999. const c = (radialSegments + 1) * j + i;
  21000. const d = (radialSegments + 1) * (j - 1) + i; // faces
  21001. indices.push(a, b, d);
  21002. indices.push(b, c, d);
  21003. }
  21004. } // build geometry
  21005. this.setIndex(indices);
  21006. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  21007. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  21008. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2)); // this function calculates the current position on the torus curve
  21009. function calculatePositionOnCurve(u, p, q, radius, position) {
  21010. const cu = Math.cos(u);
  21011. const su = Math.sin(u);
  21012. const quOverP = q / p * u;
  21013. const cs = Math.cos(quOverP);
  21014. position.x = radius * (2 + cs) * 0.5 * cu;
  21015. position.y = radius * (2 + cs) * su * 0.5;
  21016. position.z = radius * Math.sin(quOverP) * 0.5;
  21017. }
  21018. }
  21019. static fromJSON(data) {
  21020. return new TorusKnotGeometry(data.radius, data.tube, data.tubularSegments, data.radialSegments, data.p, data.q);
  21021. }
  21022. }
  21023. class TubeGeometry extends BufferGeometry {
  21024. constructor(path = new QuadraticBezierCurve3(new Vector3(-1, -1, 0), new Vector3(-1, 1, 0), new Vector3(1, 1, 0)), tubularSegments = 64, radius = 1, radialSegments = 8, closed = false) {
  21025. super();
  21026. this.type = 'TubeGeometry';
  21027. this.parameters = {
  21028. path: path,
  21029. tubularSegments: tubularSegments,
  21030. radius: radius,
  21031. radialSegments: radialSegments,
  21032. closed: closed
  21033. };
  21034. const frames = path.computeFrenetFrames(tubularSegments, closed); // expose internals
  21035. this.tangents = frames.tangents;
  21036. this.normals = frames.normals;
  21037. this.binormals = frames.binormals; // helper variables
  21038. const vertex = new Vector3();
  21039. const normal = new Vector3();
  21040. const uv = new Vector2();
  21041. let P = new Vector3(); // buffer
  21042. const vertices = [];
  21043. const normals = [];
  21044. const uvs = [];
  21045. const indices = []; // create buffer data
  21046. generateBufferData(); // build geometry
  21047. this.setIndex(indices);
  21048. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  21049. this.setAttribute('normal', new Float32BufferAttribute(normals, 3));
  21050. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2)); // functions
  21051. function generateBufferData() {
  21052. for (let i = 0; i < tubularSegments; i++) {
  21053. generateSegment(i);
  21054. } // if the geometry is not closed, generate the last row of vertices and normals
  21055. // at the regular position on the given path
  21056. //
  21057. // if the geometry is closed, duplicate the first row of vertices and normals (uvs will differ)
  21058. generateSegment(closed === false ? tubularSegments : 0); // uvs are generated in a separate function.
  21059. // this makes it easy compute correct values for closed geometries
  21060. generateUVs(); // finally create faces
  21061. generateIndices();
  21062. }
  21063. function generateSegment(i) {
  21064. // we use getPointAt to sample evenly distributed points from the given path
  21065. P = path.getPointAt(i / tubularSegments, P); // retrieve corresponding normal and binormal
  21066. const N = frames.normals[i];
  21067. const B = frames.binormals[i]; // generate normals and vertices for the current segment
  21068. for (let j = 0; j <= radialSegments; j++) {
  21069. const v = j / radialSegments * Math.PI * 2;
  21070. const sin = Math.sin(v);
  21071. const cos = -Math.cos(v); // normal
  21072. normal.x = cos * N.x + sin * B.x;
  21073. normal.y = cos * N.y + sin * B.y;
  21074. normal.z = cos * N.z + sin * B.z;
  21075. normal.normalize();
  21076. normals.push(normal.x, normal.y, normal.z); // vertex
  21077. vertex.x = P.x + radius * normal.x;
  21078. vertex.y = P.y + radius * normal.y;
  21079. vertex.z = P.z + radius * normal.z;
  21080. vertices.push(vertex.x, vertex.y, vertex.z);
  21081. }
  21082. }
  21083. function generateIndices() {
  21084. for (let j = 1; j <= tubularSegments; j++) {
  21085. for (let i = 1; i <= radialSegments; i++) {
  21086. const a = (radialSegments + 1) * (j - 1) + (i - 1);
  21087. const b = (radialSegments + 1) * j + (i - 1);
  21088. const c = (radialSegments + 1) * j + i;
  21089. const d = (radialSegments + 1) * (j - 1) + i; // faces
  21090. indices.push(a, b, d);
  21091. indices.push(b, c, d);
  21092. }
  21093. }
  21094. }
  21095. function generateUVs() {
  21096. for (let i = 0; i <= tubularSegments; i++) {
  21097. for (let j = 0; j <= radialSegments; j++) {
  21098. uv.x = i / tubularSegments;
  21099. uv.y = j / radialSegments;
  21100. uvs.push(uv.x, uv.y);
  21101. }
  21102. }
  21103. }
  21104. }
  21105. toJSON() {
  21106. const data = super.toJSON();
  21107. data.path = this.parameters.path.toJSON();
  21108. return data;
  21109. }
  21110. static fromJSON(data) {
  21111. // This only works for built-in curves (e.g. CatmullRomCurve3).
  21112. // User defined curves or instances of CurvePath will not be deserialized.
  21113. return new TubeGeometry(new Curves[data.path.type]().fromJSON(data.path), data.tubularSegments, data.radius, data.radialSegments, data.closed);
  21114. }
  21115. }
  21116. class WireframeGeometry extends BufferGeometry {
  21117. constructor(geometry = null) {
  21118. super();
  21119. this.type = 'WireframeGeometry';
  21120. this.parameters = {
  21121. geometry: geometry
  21122. };
  21123. if (geometry !== null) {
  21124. // buffer
  21125. const vertices = [];
  21126. const edges = new Set(); // helper variables
  21127. const start = new Vector3();
  21128. const end = new Vector3();
  21129. if (geometry.index !== null) {
  21130. // indexed BufferGeometry
  21131. const position = geometry.attributes.position;
  21132. const indices = geometry.index;
  21133. let groups = geometry.groups;
  21134. if (groups.length === 0) {
  21135. groups = [{
  21136. start: 0,
  21137. count: indices.count,
  21138. materialIndex: 0
  21139. }];
  21140. } // create a data structure that contains all edges without duplicates
  21141. for (let o = 0, ol = groups.length; o < ol; ++o) {
  21142. const group = groups[o];
  21143. const groupStart = group.start;
  21144. const groupCount = group.count;
  21145. for (let i = groupStart, l = groupStart + groupCount; i < l; i += 3) {
  21146. for (let j = 0; j < 3; j++) {
  21147. const index1 = indices.getX(i + j);
  21148. const index2 = indices.getX(i + (j + 1) % 3);
  21149. start.fromBufferAttribute(position, index1);
  21150. end.fromBufferAttribute(position, index2);
  21151. if (isUniqueEdge(start, end, edges) === true) {
  21152. vertices.push(start.x, start.y, start.z);
  21153. vertices.push(end.x, end.y, end.z);
  21154. }
  21155. }
  21156. }
  21157. }
  21158. } else {
  21159. // non-indexed BufferGeometry
  21160. const position = geometry.attributes.position;
  21161. for (let i = 0, l = position.count / 3; i < l; i++) {
  21162. for (let j = 0; j < 3; j++) {
  21163. // three edges per triangle, an edge is represented as (index1, index2)
  21164. // e.g. the first triangle has the following edges: (0,1),(1,2),(2,0)
  21165. const index1 = 3 * i + j;
  21166. const index2 = 3 * i + (j + 1) % 3;
  21167. start.fromBufferAttribute(position, index1);
  21168. end.fromBufferAttribute(position, index2);
  21169. if (isUniqueEdge(start, end, edges) === true) {
  21170. vertices.push(start.x, start.y, start.z);
  21171. vertices.push(end.x, end.y, end.z);
  21172. }
  21173. }
  21174. }
  21175. } // build geometry
  21176. this.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  21177. }
  21178. }
  21179. }
  21180. function isUniqueEdge(start, end, edges) {
  21181. const hash1 = `${start.x},${start.y},${start.z}-${end.x},${end.y},${end.z}`;
  21182. const hash2 = `${end.x},${end.y},${end.z}-${start.x},${start.y},${start.z}`; // coincident edge
  21183. if (edges.has(hash1) === true || edges.has(hash2) === true) {
  21184. return false;
  21185. } else {
  21186. edges.add(hash1);
  21187. edges.add(hash2);
  21188. return true;
  21189. }
  21190. }
  21191. var Geometries = /*#__PURE__*/Object.freeze({
  21192. __proto__: null,
  21193. BoxGeometry: BoxGeometry,
  21194. BoxBufferGeometry: BoxGeometry,
  21195. CapsuleGeometry: CapsuleGeometry,
  21196. CapsuleBufferGeometry: CapsuleGeometry,
  21197. CircleGeometry: CircleGeometry,
  21198. CircleBufferGeometry: CircleGeometry,
  21199. ConeGeometry: ConeGeometry,
  21200. ConeBufferGeometry: ConeGeometry,
  21201. CylinderGeometry: CylinderGeometry,
  21202. CylinderBufferGeometry: CylinderGeometry,
  21203. DodecahedronGeometry: DodecahedronGeometry,
  21204. DodecahedronBufferGeometry: DodecahedronGeometry,
  21205. EdgesGeometry: EdgesGeometry,
  21206. ExtrudeGeometry: ExtrudeGeometry,
  21207. ExtrudeBufferGeometry: ExtrudeGeometry,
  21208. IcosahedronGeometry: IcosahedronGeometry,
  21209. IcosahedronBufferGeometry: IcosahedronGeometry,
  21210. LatheGeometry: LatheGeometry,
  21211. LatheBufferGeometry: LatheGeometry,
  21212. OctahedronGeometry: OctahedronGeometry,
  21213. OctahedronBufferGeometry: OctahedronGeometry,
  21214. PlaneGeometry: PlaneGeometry,
  21215. PlaneBufferGeometry: PlaneGeometry,
  21216. PolyhedronGeometry: PolyhedronGeometry,
  21217. PolyhedronBufferGeometry: PolyhedronGeometry,
  21218. RingGeometry: RingGeometry,
  21219. RingBufferGeometry: RingGeometry,
  21220. ShapeGeometry: ShapeGeometry,
  21221. ShapeBufferGeometry: ShapeGeometry,
  21222. SphereGeometry: SphereGeometry,
  21223. SphereBufferGeometry: SphereGeometry,
  21224. TetrahedronGeometry: TetrahedronGeometry,
  21225. TetrahedronBufferGeometry: TetrahedronGeometry,
  21226. TorusGeometry: TorusGeometry,
  21227. TorusBufferGeometry: TorusGeometry,
  21228. TorusKnotGeometry: TorusKnotGeometry,
  21229. TorusKnotBufferGeometry: TorusKnotGeometry,
  21230. TubeGeometry: TubeGeometry,
  21231. TubeBufferGeometry: TubeGeometry,
  21232. WireframeGeometry: WireframeGeometry
  21233. });
  21234. class ShadowMaterial extends Material {
  21235. constructor(parameters) {
  21236. super();
  21237. this.isShadowMaterial = true;
  21238. this.type = 'ShadowMaterial';
  21239. this.color = new Color(0x000000);
  21240. this.transparent = true;
  21241. this.fog = true;
  21242. this.setValues(parameters);
  21243. }
  21244. copy(source) {
  21245. super.copy(source);
  21246. this.color.copy(source.color);
  21247. this.fog = source.fog;
  21248. return this;
  21249. }
  21250. }
  21251. class RawShaderMaterial extends ShaderMaterial {
  21252. constructor(parameters) {
  21253. super(parameters);
  21254. this.isRawShaderMaterial = true;
  21255. this.type = 'RawShaderMaterial';
  21256. }
  21257. }
  21258. class MeshStandardMaterial extends Material {
  21259. constructor(parameters) {
  21260. super();
  21261. this.isMeshStandardMaterial = true;
  21262. this.defines = {
  21263. 'STANDARD': ''
  21264. };
  21265. this.type = 'MeshStandardMaterial';
  21266. this.color = new Color(0xffffff); // diffuse
  21267. this.roughness = 1.0;
  21268. this.metalness = 0.0;
  21269. this.map = null;
  21270. this.lightMap = null;
  21271. this.lightMapIntensity = 1.0;
  21272. this.aoMap = null;
  21273. this.aoMapIntensity = 1.0;
  21274. this.emissive = new Color(0x000000);
  21275. this.emissiveIntensity = 1.0;
  21276. this.emissiveMap = null;
  21277. this.bumpMap = null;
  21278. this.bumpScale = 1;
  21279. this.normalMap = null;
  21280. this.normalMapType = TangentSpaceNormalMap;
  21281. this.normalScale = new Vector2(1, 1);
  21282. this.displacementMap = null;
  21283. this.displacementScale = 1;
  21284. this.displacementBias = 0;
  21285. this.roughnessMap = null;
  21286. this.metalnessMap = null;
  21287. this.alphaMap = null;
  21288. this.envMap = null;
  21289. this.envMapIntensity = 1.0;
  21290. this.wireframe = false;
  21291. this.wireframeLinewidth = 1;
  21292. this.wireframeLinecap = 'round';
  21293. this.wireframeLinejoin = 'round';
  21294. this.flatShading = false;
  21295. this.fog = true;
  21296. this.setValues(parameters);
  21297. }
  21298. copy(source) {
  21299. super.copy(source);
  21300. this.defines = {
  21301. 'STANDARD': ''
  21302. };
  21303. this.color.copy(source.color);
  21304. this.roughness = source.roughness;
  21305. this.metalness = source.metalness;
  21306. this.map = source.map;
  21307. this.lightMap = source.lightMap;
  21308. this.lightMapIntensity = source.lightMapIntensity;
  21309. this.aoMap = source.aoMap;
  21310. this.aoMapIntensity = source.aoMapIntensity;
  21311. this.emissive.copy(source.emissive);
  21312. this.emissiveMap = source.emissiveMap;
  21313. this.emissiveIntensity = source.emissiveIntensity;
  21314. this.bumpMap = source.bumpMap;
  21315. this.bumpScale = source.bumpScale;
  21316. this.normalMap = source.normalMap;
  21317. this.normalMapType = source.normalMapType;
  21318. this.normalScale.copy(source.normalScale);
  21319. this.displacementMap = source.displacementMap;
  21320. this.displacementScale = source.displacementScale;
  21321. this.displacementBias = source.displacementBias;
  21322. this.roughnessMap = source.roughnessMap;
  21323. this.metalnessMap = source.metalnessMap;
  21324. this.alphaMap = source.alphaMap;
  21325. this.envMap = source.envMap;
  21326. this.envMapIntensity = source.envMapIntensity;
  21327. this.wireframe = source.wireframe;
  21328. this.wireframeLinewidth = source.wireframeLinewidth;
  21329. this.wireframeLinecap = source.wireframeLinecap;
  21330. this.wireframeLinejoin = source.wireframeLinejoin;
  21331. this.flatShading = source.flatShading;
  21332. this.fog = source.fog;
  21333. return this;
  21334. }
  21335. }
  21336. class MeshPhysicalMaterial extends MeshStandardMaterial {
  21337. constructor(parameters) {
  21338. super();
  21339. this.isMeshPhysicalMaterial = true;
  21340. this.defines = {
  21341. 'STANDARD': '',
  21342. 'PHYSICAL': ''
  21343. };
  21344. this.type = 'MeshPhysicalMaterial';
  21345. this.clearcoatMap = null;
  21346. this.clearcoatRoughness = 0.0;
  21347. this.clearcoatRoughnessMap = null;
  21348. this.clearcoatNormalScale = new Vector2(1, 1);
  21349. this.clearcoatNormalMap = null;
  21350. this.ior = 1.5;
  21351. Object.defineProperty(this, 'reflectivity', {
  21352. get: function () {
  21353. return clamp(2.5 * (this.ior - 1) / (this.ior + 1), 0, 1);
  21354. },
  21355. set: function (reflectivity) {
  21356. this.ior = (1 + 0.4 * reflectivity) / (1 - 0.4 * reflectivity);
  21357. }
  21358. });
  21359. this.sheenColor = new Color(0x000000);
  21360. this.sheenColorMap = null;
  21361. this.sheenRoughness = 1.0;
  21362. this.sheenRoughnessMap = null;
  21363. this.transmissionMap = null;
  21364. this.thickness = 0;
  21365. this.thicknessMap = null;
  21366. this.attenuationDistance = 0.0;
  21367. this.attenuationColor = new Color(1, 1, 1);
  21368. this.specularIntensity = 1.0;
  21369. this.specularIntensityMap = null;
  21370. this.specularColor = new Color(1, 1, 1);
  21371. this.specularColorMap = null;
  21372. this._sheen = 0.0;
  21373. this._clearcoat = 0;
  21374. this._transmission = 0;
  21375. this.setValues(parameters);
  21376. }
  21377. get sheen() {
  21378. return this._sheen;
  21379. }
  21380. set sheen(value) {
  21381. if (this._sheen > 0 !== value > 0) {
  21382. this.version++;
  21383. }
  21384. this._sheen = value;
  21385. }
  21386. get clearcoat() {
  21387. return this._clearcoat;
  21388. }
  21389. set clearcoat(value) {
  21390. if (this._clearcoat > 0 !== value > 0) {
  21391. this.version++;
  21392. }
  21393. this._clearcoat = value;
  21394. }
  21395. get transmission() {
  21396. return this._transmission;
  21397. }
  21398. set transmission(value) {
  21399. if (this._transmission > 0 !== value > 0) {
  21400. this.version++;
  21401. }
  21402. this._transmission = value;
  21403. }
  21404. copy(source) {
  21405. super.copy(source);
  21406. this.defines = {
  21407. 'STANDARD': '',
  21408. 'PHYSICAL': ''
  21409. };
  21410. this.clearcoat = source.clearcoat;
  21411. this.clearcoatMap = source.clearcoatMap;
  21412. this.clearcoatRoughness = source.clearcoatRoughness;
  21413. this.clearcoatRoughnessMap = source.clearcoatRoughnessMap;
  21414. this.clearcoatNormalMap = source.clearcoatNormalMap;
  21415. this.clearcoatNormalScale.copy(source.clearcoatNormalScale);
  21416. this.ior = source.ior;
  21417. this.sheen = source.sheen;
  21418. this.sheenColor.copy(source.sheenColor);
  21419. this.sheenColorMap = source.sheenColorMap;
  21420. this.sheenRoughness = source.sheenRoughness;
  21421. this.sheenRoughnessMap = source.sheenRoughnessMap;
  21422. this.transmission = source.transmission;
  21423. this.transmissionMap = source.transmissionMap;
  21424. this.thickness = source.thickness;
  21425. this.thicknessMap = source.thicknessMap;
  21426. this.attenuationDistance = source.attenuationDistance;
  21427. this.attenuationColor.copy(source.attenuationColor);
  21428. this.specularIntensity = source.specularIntensity;
  21429. this.specularIntensityMap = source.specularIntensityMap;
  21430. this.specularColor.copy(source.specularColor);
  21431. this.specularColorMap = source.specularColorMap;
  21432. return this;
  21433. }
  21434. }
  21435. class MeshPhongMaterial extends Material {
  21436. constructor(parameters) {
  21437. super();
  21438. this.isMeshPhongMaterial = true;
  21439. this.type = 'MeshPhongMaterial';
  21440. this.color = new Color(0xffffff); // diffuse
  21441. this.specular = new Color(0x111111);
  21442. this.shininess = 30;
  21443. this.map = null;
  21444. this.lightMap = null;
  21445. this.lightMapIntensity = 1.0;
  21446. this.aoMap = null;
  21447. this.aoMapIntensity = 1.0;
  21448. this.emissive = new Color(0x000000);
  21449. this.emissiveIntensity = 1.0;
  21450. this.emissiveMap = null;
  21451. this.bumpMap = null;
  21452. this.bumpScale = 1;
  21453. this.normalMap = null;
  21454. this.normalMapType = TangentSpaceNormalMap;
  21455. this.normalScale = new Vector2(1, 1);
  21456. this.displacementMap = null;
  21457. this.displacementScale = 1;
  21458. this.displacementBias = 0;
  21459. this.specularMap = null;
  21460. this.alphaMap = null;
  21461. this.envMap = null;
  21462. this.combine = MultiplyOperation;
  21463. this.reflectivity = 1;
  21464. this.refractionRatio = 0.98;
  21465. this.wireframe = false;
  21466. this.wireframeLinewidth = 1;
  21467. this.wireframeLinecap = 'round';
  21468. this.wireframeLinejoin = 'round';
  21469. this.flatShading = false;
  21470. this.fog = true;
  21471. this.setValues(parameters);
  21472. }
  21473. copy(source) {
  21474. super.copy(source);
  21475. this.color.copy(source.color);
  21476. this.specular.copy(source.specular);
  21477. this.shininess = source.shininess;
  21478. this.map = source.map;
  21479. this.lightMap = source.lightMap;
  21480. this.lightMapIntensity = source.lightMapIntensity;
  21481. this.aoMap = source.aoMap;
  21482. this.aoMapIntensity = source.aoMapIntensity;
  21483. this.emissive.copy(source.emissive);
  21484. this.emissiveMap = source.emissiveMap;
  21485. this.emissiveIntensity = source.emissiveIntensity;
  21486. this.bumpMap = source.bumpMap;
  21487. this.bumpScale = source.bumpScale;
  21488. this.normalMap = source.normalMap;
  21489. this.normalMapType = source.normalMapType;
  21490. this.normalScale.copy(source.normalScale);
  21491. this.displacementMap = source.displacementMap;
  21492. this.displacementScale = source.displacementScale;
  21493. this.displacementBias = source.displacementBias;
  21494. this.specularMap = source.specularMap;
  21495. this.alphaMap = source.alphaMap;
  21496. this.envMap = source.envMap;
  21497. this.combine = source.combine;
  21498. this.reflectivity = source.reflectivity;
  21499. this.refractionRatio = source.refractionRatio;
  21500. this.wireframe = source.wireframe;
  21501. this.wireframeLinewidth = source.wireframeLinewidth;
  21502. this.wireframeLinecap = source.wireframeLinecap;
  21503. this.wireframeLinejoin = source.wireframeLinejoin;
  21504. this.flatShading = source.flatShading;
  21505. this.fog = source.fog;
  21506. return this;
  21507. }
  21508. }
  21509. class MeshToonMaterial extends Material {
  21510. constructor(parameters) {
  21511. super();
  21512. this.isMeshToonMaterial = true;
  21513. this.defines = {
  21514. 'TOON': ''
  21515. };
  21516. this.type = 'MeshToonMaterial';
  21517. this.color = new Color(0xffffff);
  21518. this.map = null;
  21519. this.gradientMap = null;
  21520. this.lightMap = null;
  21521. this.lightMapIntensity = 1.0;
  21522. this.aoMap = null;
  21523. this.aoMapIntensity = 1.0;
  21524. this.emissive = new Color(0x000000);
  21525. this.emissiveIntensity = 1.0;
  21526. this.emissiveMap = null;
  21527. this.bumpMap = null;
  21528. this.bumpScale = 1;
  21529. this.normalMap = null;
  21530. this.normalMapType = TangentSpaceNormalMap;
  21531. this.normalScale = new Vector2(1, 1);
  21532. this.displacementMap = null;
  21533. this.displacementScale = 1;
  21534. this.displacementBias = 0;
  21535. this.alphaMap = null;
  21536. this.wireframe = false;
  21537. this.wireframeLinewidth = 1;
  21538. this.wireframeLinecap = 'round';
  21539. this.wireframeLinejoin = 'round';
  21540. this.fog = true;
  21541. this.setValues(parameters);
  21542. }
  21543. copy(source) {
  21544. super.copy(source);
  21545. this.color.copy(source.color);
  21546. this.map = source.map;
  21547. this.gradientMap = source.gradientMap;
  21548. this.lightMap = source.lightMap;
  21549. this.lightMapIntensity = source.lightMapIntensity;
  21550. this.aoMap = source.aoMap;
  21551. this.aoMapIntensity = source.aoMapIntensity;
  21552. this.emissive.copy(source.emissive);
  21553. this.emissiveMap = source.emissiveMap;
  21554. this.emissiveIntensity = source.emissiveIntensity;
  21555. this.bumpMap = source.bumpMap;
  21556. this.bumpScale = source.bumpScale;
  21557. this.normalMap = source.normalMap;
  21558. this.normalMapType = source.normalMapType;
  21559. this.normalScale.copy(source.normalScale);
  21560. this.displacementMap = source.displacementMap;
  21561. this.displacementScale = source.displacementScale;
  21562. this.displacementBias = source.displacementBias;
  21563. this.alphaMap = source.alphaMap;
  21564. this.wireframe = source.wireframe;
  21565. this.wireframeLinewidth = source.wireframeLinewidth;
  21566. this.wireframeLinecap = source.wireframeLinecap;
  21567. this.wireframeLinejoin = source.wireframeLinejoin;
  21568. this.fog = source.fog;
  21569. return this;
  21570. }
  21571. }
  21572. class MeshNormalMaterial extends Material {
  21573. constructor(parameters) {
  21574. super();
  21575. this.isMeshNormalMaterial = true;
  21576. this.type = 'MeshNormalMaterial';
  21577. this.bumpMap = null;
  21578. this.bumpScale = 1;
  21579. this.normalMap = null;
  21580. this.normalMapType = TangentSpaceNormalMap;
  21581. this.normalScale = new Vector2(1, 1);
  21582. this.displacementMap = null;
  21583. this.displacementScale = 1;
  21584. this.displacementBias = 0;
  21585. this.wireframe = false;
  21586. this.wireframeLinewidth = 1;
  21587. this.flatShading = false;
  21588. this.setValues(parameters);
  21589. }
  21590. copy(source) {
  21591. super.copy(source);
  21592. this.bumpMap = source.bumpMap;
  21593. this.bumpScale = source.bumpScale;
  21594. this.normalMap = source.normalMap;
  21595. this.normalMapType = source.normalMapType;
  21596. this.normalScale.copy(source.normalScale);
  21597. this.displacementMap = source.displacementMap;
  21598. this.displacementScale = source.displacementScale;
  21599. this.displacementBias = source.displacementBias;
  21600. this.wireframe = source.wireframe;
  21601. this.wireframeLinewidth = source.wireframeLinewidth;
  21602. this.flatShading = source.flatShading;
  21603. return this;
  21604. }
  21605. }
  21606. class MeshLambertMaterial extends Material {
  21607. constructor(parameters) {
  21608. super();
  21609. this.isMeshLambertMaterial = true;
  21610. this.type = 'MeshLambertMaterial';
  21611. this.color = new Color(0xffffff); // diffuse
  21612. this.map = null;
  21613. this.lightMap = null;
  21614. this.lightMapIntensity = 1.0;
  21615. this.aoMap = null;
  21616. this.aoMapIntensity = 1.0;
  21617. this.emissive = new Color(0x000000);
  21618. this.emissiveIntensity = 1.0;
  21619. this.emissiveMap = null;
  21620. this.specularMap = null;
  21621. this.alphaMap = null;
  21622. this.envMap = null;
  21623. this.combine = MultiplyOperation;
  21624. this.reflectivity = 1;
  21625. this.refractionRatio = 0.98;
  21626. this.wireframe = false;
  21627. this.wireframeLinewidth = 1;
  21628. this.wireframeLinecap = 'round';
  21629. this.wireframeLinejoin = 'round';
  21630. this.fog = true;
  21631. this.setValues(parameters);
  21632. }
  21633. copy(source) {
  21634. super.copy(source);
  21635. this.color.copy(source.color);
  21636. this.map = source.map;
  21637. this.lightMap = source.lightMap;
  21638. this.lightMapIntensity = source.lightMapIntensity;
  21639. this.aoMap = source.aoMap;
  21640. this.aoMapIntensity = source.aoMapIntensity;
  21641. this.emissive.copy(source.emissive);
  21642. this.emissiveMap = source.emissiveMap;
  21643. this.emissiveIntensity = source.emissiveIntensity;
  21644. this.specularMap = source.specularMap;
  21645. this.alphaMap = source.alphaMap;
  21646. this.envMap = source.envMap;
  21647. this.combine = source.combine;
  21648. this.reflectivity = source.reflectivity;
  21649. this.refractionRatio = source.refractionRatio;
  21650. this.wireframe = source.wireframe;
  21651. this.wireframeLinewidth = source.wireframeLinewidth;
  21652. this.wireframeLinecap = source.wireframeLinecap;
  21653. this.wireframeLinejoin = source.wireframeLinejoin;
  21654. this.fog = source.fog;
  21655. return this;
  21656. }
  21657. }
  21658. class MeshMatcapMaterial extends Material {
  21659. constructor(parameters) {
  21660. super();
  21661. this.isMeshMatcapMaterial = true;
  21662. this.defines = {
  21663. 'MATCAP': ''
  21664. };
  21665. this.type = 'MeshMatcapMaterial';
  21666. this.color = new Color(0xffffff); // diffuse
  21667. this.matcap = null;
  21668. this.map = null;
  21669. this.bumpMap = null;
  21670. this.bumpScale = 1;
  21671. this.normalMap = null;
  21672. this.normalMapType = TangentSpaceNormalMap;
  21673. this.normalScale = new Vector2(1, 1);
  21674. this.displacementMap = null;
  21675. this.displacementScale = 1;
  21676. this.displacementBias = 0;
  21677. this.alphaMap = null;
  21678. this.flatShading = false;
  21679. this.fog = true;
  21680. this.setValues(parameters);
  21681. }
  21682. copy(source) {
  21683. super.copy(source);
  21684. this.defines = {
  21685. 'MATCAP': ''
  21686. };
  21687. this.color.copy(source.color);
  21688. this.matcap = source.matcap;
  21689. this.map = source.map;
  21690. this.bumpMap = source.bumpMap;
  21691. this.bumpScale = source.bumpScale;
  21692. this.normalMap = source.normalMap;
  21693. this.normalMapType = source.normalMapType;
  21694. this.normalScale.copy(source.normalScale);
  21695. this.displacementMap = source.displacementMap;
  21696. this.displacementScale = source.displacementScale;
  21697. this.displacementBias = source.displacementBias;
  21698. this.alphaMap = source.alphaMap;
  21699. this.flatShading = source.flatShading;
  21700. this.fog = source.fog;
  21701. return this;
  21702. }
  21703. }
  21704. class LineDashedMaterial extends LineBasicMaterial {
  21705. constructor(parameters) {
  21706. super();
  21707. this.isLineDashedMaterial = true;
  21708. this.type = 'LineDashedMaterial';
  21709. this.scale = 1;
  21710. this.dashSize = 3;
  21711. this.gapSize = 1;
  21712. this.setValues(parameters);
  21713. }
  21714. copy(source) {
  21715. super.copy(source);
  21716. this.scale = source.scale;
  21717. this.dashSize = source.dashSize;
  21718. this.gapSize = source.gapSize;
  21719. return this;
  21720. }
  21721. }
  21722. const materialLib = {
  21723. ShadowMaterial,
  21724. SpriteMaterial,
  21725. RawShaderMaterial,
  21726. ShaderMaterial,
  21727. PointsMaterial,
  21728. MeshPhysicalMaterial,
  21729. MeshStandardMaterial,
  21730. MeshPhongMaterial,
  21731. MeshToonMaterial,
  21732. MeshNormalMaterial,
  21733. MeshLambertMaterial,
  21734. MeshDepthMaterial,
  21735. MeshDistanceMaterial,
  21736. MeshBasicMaterial,
  21737. MeshMatcapMaterial,
  21738. LineDashedMaterial,
  21739. LineBasicMaterial,
  21740. Material
  21741. };
  21742. Material.fromType = function (type) {
  21743. return new materialLib[type]();
  21744. };
  21745. const AnimationUtils = {
  21746. // same as Array.prototype.slice, but also works on typed arrays
  21747. arraySlice: function (array, from, to) {
  21748. if (AnimationUtils.isTypedArray(array)) {
  21749. // in ios9 array.subarray(from, undefined) will return empty array
  21750. // but array.subarray(from) or array.subarray(from, len) is correct
  21751. return new array.constructor(array.subarray(from, to !== undefined ? to : array.length));
  21752. }
  21753. return array.slice(from, to);
  21754. },
  21755. // converts an array to a specific type
  21756. convertArray: function (array, type, forceClone) {
  21757. if (!array || // let 'undefined' and 'null' pass
  21758. !forceClone && array.constructor === type) return array;
  21759. if (typeof type.BYTES_PER_ELEMENT === 'number') {
  21760. return new type(array); // create typed array
  21761. }
  21762. return Array.prototype.slice.call(array); // create Array
  21763. },
  21764. isTypedArray: function (object) {
  21765. return ArrayBuffer.isView(object) && !(object instanceof DataView);
  21766. },
  21767. // returns an array by which times and values can be sorted
  21768. getKeyframeOrder: function (times) {
  21769. function compareTime(i, j) {
  21770. return times[i] - times[j];
  21771. }
  21772. const n = times.length;
  21773. const result = new Array(n);
  21774. for (let i = 0; i !== n; ++i) result[i] = i;
  21775. result.sort(compareTime);
  21776. return result;
  21777. },
  21778. // uses the array previously returned by 'getKeyframeOrder' to sort data
  21779. sortedArray: function (values, stride, order) {
  21780. const nValues = values.length;
  21781. const result = new values.constructor(nValues);
  21782. for (let i = 0, dstOffset = 0; dstOffset !== nValues; ++i) {
  21783. const srcOffset = order[i] * stride;
  21784. for (let j = 0; j !== stride; ++j) {
  21785. result[dstOffset++] = values[srcOffset + j];
  21786. }
  21787. }
  21788. return result;
  21789. },
  21790. // function for parsing AOS keyframe formats
  21791. flattenJSON: function (jsonKeys, times, values, valuePropertyName) {
  21792. let i = 1,
  21793. key = jsonKeys[0];
  21794. while (key !== undefined && key[valuePropertyName] === undefined) {
  21795. key = jsonKeys[i++];
  21796. }
  21797. if (key === undefined) return; // no data
  21798. let value = key[valuePropertyName];
  21799. if (value === undefined) return; // no data
  21800. if (Array.isArray(value)) {
  21801. do {
  21802. value = key[valuePropertyName];
  21803. if (value !== undefined) {
  21804. times.push(key.time);
  21805. values.push.apply(values, value); // push all elements
  21806. }
  21807. key = jsonKeys[i++];
  21808. } while (key !== undefined);
  21809. } else if (value.toArray !== undefined) {
  21810. // ...assume THREE.Math-ish
  21811. do {
  21812. value = key[valuePropertyName];
  21813. if (value !== undefined) {
  21814. times.push(key.time);
  21815. value.toArray(values, values.length);
  21816. }
  21817. key = jsonKeys[i++];
  21818. } while (key !== undefined);
  21819. } else {
  21820. // otherwise push as-is
  21821. do {
  21822. value = key[valuePropertyName];
  21823. if (value !== undefined) {
  21824. times.push(key.time);
  21825. values.push(value);
  21826. }
  21827. key = jsonKeys[i++];
  21828. } while (key !== undefined);
  21829. }
  21830. },
  21831. subclip: function (sourceClip, name, startFrame, endFrame, fps = 30) {
  21832. const clip = sourceClip.clone();
  21833. clip.name = name;
  21834. const tracks = [];
  21835. for (let i = 0; i < clip.tracks.length; ++i) {
  21836. const track = clip.tracks[i];
  21837. const valueSize = track.getValueSize();
  21838. const times = [];
  21839. const values = [];
  21840. for (let j = 0; j < track.times.length; ++j) {
  21841. const frame = track.times[j] * fps;
  21842. if (frame < startFrame || frame >= endFrame) continue;
  21843. times.push(track.times[j]);
  21844. for (let k = 0; k < valueSize; ++k) {
  21845. values.push(track.values[j * valueSize + k]);
  21846. }
  21847. }
  21848. if (times.length === 0) continue;
  21849. track.times = AnimationUtils.convertArray(times, track.times.constructor);
  21850. track.values = AnimationUtils.convertArray(values, track.values.constructor);
  21851. tracks.push(track);
  21852. }
  21853. clip.tracks = tracks; // find minimum .times value across all tracks in the trimmed clip
  21854. let minStartTime = Infinity;
  21855. for (let i = 0; i < clip.tracks.length; ++i) {
  21856. if (minStartTime > clip.tracks[i].times[0]) {
  21857. minStartTime = clip.tracks[i].times[0];
  21858. }
  21859. } // shift all tracks such that clip begins at t=0
  21860. for (let i = 0; i < clip.tracks.length; ++i) {
  21861. clip.tracks[i].shift(-1 * minStartTime);
  21862. }
  21863. clip.resetDuration();
  21864. return clip;
  21865. },
  21866. makeClipAdditive: function (targetClip, referenceFrame = 0, referenceClip = targetClip, fps = 30) {
  21867. if (fps <= 0) fps = 30;
  21868. const numTracks = referenceClip.tracks.length;
  21869. const referenceTime = referenceFrame / fps; // Make each track's values relative to the values at the reference frame
  21870. for (let i = 0; i < numTracks; ++i) {
  21871. const referenceTrack = referenceClip.tracks[i];
  21872. const referenceTrackType = referenceTrack.ValueTypeName; // Skip this track if it's non-numeric
  21873. if (referenceTrackType === 'bool' || referenceTrackType === 'string') continue; // Find the track in the target clip whose name and type matches the reference track
  21874. const targetTrack = targetClip.tracks.find(function (track) {
  21875. return track.name === referenceTrack.name && track.ValueTypeName === referenceTrackType;
  21876. });
  21877. if (targetTrack === undefined) continue;
  21878. let referenceOffset = 0;
  21879. const referenceValueSize = referenceTrack.getValueSize();
  21880. if (referenceTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline) {
  21881. referenceOffset = referenceValueSize / 3;
  21882. }
  21883. let targetOffset = 0;
  21884. const targetValueSize = targetTrack.getValueSize();
  21885. if (targetTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline) {
  21886. targetOffset = targetValueSize / 3;
  21887. }
  21888. const lastIndex = referenceTrack.times.length - 1;
  21889. let referenceValue; // Find the value to subtract out of the track
  21890. if (referenceTime <= referenceTrack.times[0]) {
  21891. // Reference frame is earlier than the first keyframe, so just use the first keyframe
  21892. const startIndex = referenceOffset;
  21893. const endIndex = referenceValueSize - referenceOffset;
  21894. referenceValue = AnimationUtils.arraySlice(referenceTrack.values, startIndex, endIndex);
  21895. } else if (referenceTime >= referenceTrack.times[lastIndex]) {
  21896. // Reference frame is after the last keyframe, so just use the last keyframe
  21897. const startIndex = lastIndex * referenceValueSize + referenceOffset;
  21898. const endIndex = startIndex + referenceValueSize - referenceOffset;
  21899. referenceValue = AnimationUtils.arraySlice(referenceTrack.values, startIndex, endIndex);
  21900. } else {
  21901. // Interpolate to the reference value
  21902. const interpolant = referenceTrack.createInterpolant();
  21903. const startIndex = referenceOffset;
  21904. const endIndex = referenceValueSize - referenceOffset;
  21905. interpolant.evaluate(referenceTime);
  21906. referenceValue = AnimationUtils.arraySlice(interpolant.resultBuffer, startIndex, endIndex);
  21907. } // Conjugate the quaternion
  21908. if (referenceTrackType === 'quaternion') {
  21909. const referenceQuat = new Quaternion().fromArray(referenceValue).normalize().conjugate();
  21910. referenceQuat.toArray(referenceValue);
  21911. } // Subtract the reference value from all of the track values
  21912. const numTimes = targetTrack.times.length;
  21913. for (let j = 0; j < numTimes; ++j) {
  21914. const valueStart = j * targetValueSize + targetOffset;
  21915. if (referenceTrackType === 'quaternion') {
  21916. // Multiply the conjugate for quaternion track types
  21917. Quaternion.multiplyQuaternionsFlat(targetTrack.values, valueStart, referenceValue, 0, targetTrack.values, valueStart);
  21918. } else {
  21919. const valueEnd = targetValueSize - targetOffset * 2; // Subtract each value for all other numeric track types
  21920. for (let k = 0; k < valueEnd; ++k) {
  21921. targetTrack.values[valueStart + k] -= referenceValue[k];
  21922. }
  21923. }
  21924. }
  21925. }
  21926. targetClip.blendMode = AdditiveAnimationBlendMode;
  21927. return targetClip;
  21928. }
  21929. };
  21930. /**
  21931. * Abstract base class of interpolants over parametric samples.
  21932. *
  21933. * The parameter domain is one dimensional, typically the time or a path
  21934. * along a curve defined by the data.
  21935. *
  21936. * The sample values can have any dimensionality and derived classes may
  21937. * apply special interpretations to the data.
  21938. *
  21939. * This class provides the interval seek in a Template Method, deferring
  21940. * the actual interpolation to derived classes.
  21941. *
  21942. * Time complexity is O(1) for linear access crossing at most two points
  21943. * and O(log N) for random access, where N is the number of positions.
  21944. *
  21945. * References:
  21946. *
  21947. * http://www.oodesign.com/template-method-pattern.html
  21948. *
  21949. */
  21950. class Interpolant {
  21951. constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  21952. this.parameterPositions = parameterPositions;
  21953. this._cachedIndex = 0;
  21954. this.resultBuffer = resultBuffer !== undefined ? resultBuffer : new sampleValues.constructor(sampleSize);
  21955. this.sampleValues = sampleValues;
  21956. this.valueSize = sampleSize;
  21957. this.settings = null;
  21958. this.DefaultSettings_ = {};
  21959. }
  21960. evaluate(t) {
  21961. const pp = this.parameterPositions;
  21962. let i1 = this._cachedIndex,
  21963. t1 = pp[i1],
  21964. t0 = pp[i1 - 1];
  21965. validate_interval: {
  21966. seek: {
  21967. let right;
  21968. linear_scan: {
  21969. //- See http://jsperf.com/comparison-to-undefined/3
  21970. //- slower code:
  21971. //-
  21972. //- if ( t >= t1 || t1 === undefined ) {
  21973. forward_scan: if (!(t < t1)) {
  21974. for (let giveUpAt = i1 + 2;;) {
  21975. if (t1 === undefined) {
  21976. if (t < t0) break forward_scan; // after end
  21977. i1 = pp.length;
  21978. this._cachedIndex = i1;
  21979. return this.copySampleValue_(i1 - 1);
  21980. }
  21981. if (i1 === giveUpAt) break; // this loop
  21982. t0 = t1;
  21983. t1 = pp[++i1];
  21984. if (t < t1) {
  21985. // we have arrived at the sought interval
  21986. break seek;
  21987. }
  21988. } // prepare binary search on the right side of the index
  21989. right = pp.length;
  21990. break linear_scan;
  21991. } //- slower code:
  21992. //- if ( t < t0 || t0 === undefined ) {
  21993. if (!(t >= t0)) {
  21994. // looping?
  21995. const t1global = pp[1];
  21996. if (t < t1global) {
  21997. i1 = 2; // + 1, using the scan for the details
  21998. t0 = t1global;
  21999. } // linear reverse scan
  22000. for (let giveUpAt = i1 - 2;;) {
  22001. if (t0 === undefined) {
  22002. // before start
  22003. this._cachedIndex = 0;
  22004. return this.copySampleValue_(0);
  22005. }
  22006. if (i1 === giveUpAt) break; // this loop
  22007. t1 = t0;
  22008. t0 = pp[--i1 - 1];
  22009. if (t >= t0) {
  22010. // we have arrived at the sought interval
  22011. break seek;
  22012. }
  22013. } // prepare binary search on the left side of the index
  22014. right = i1;
  22015. i1 = 0;
  22016. break linear_scan;
  22017. } // the interval is valid
  22018. break validate_interval;
  22019. } // linear scan
  22020. // binary search
  22021. while (i1 < right) {
  22022. const mid = i1 + right >>> 1;
  22023. if (t < pp[mid]) {
  22024. right = mid;
  22025. } else {
  22026. i1 = mid + 1;
  22027. }
  22028. }
  22029. t1 = pp[i1];
  22030. t0 = pp[i1 - 1]; // check boundary cases, again
  22031. if (t0 === undefined) {
  22032. this._cachedIndex = 0;
  22033. return this.copySampleValue_(0);
  22034. }
  22035. if (t1 === undefined) {
  22036. i1 = pp.length;
  22037. this._cachedIndex = i1;
  22038. return this.copySampleValue_(i1 - 1);
  22039. }
  22040. } // seek
  22041. this._cachedIndex = i1;
  22042. this.intervalChanged_(i1, t0, t1);
  22043. } // validate_interval
  22044. return this.interpolate_(i1, t0, t, t1);
  22045. }
  22046. getSettings_() {
  22047. return this.settings || this.DefaultSettings_;
  22048. }
  22049. copySampleValue_(index) {
  22050. // copies a sample value to the result buffer
  22051. const result = this.resultBuffer,
  22052. values = this.sampleValues,
  22053. stride = this.valueSize,
  22054. offset = index * stride;
  22055. for (let i = 0; i !== stride; ++i) {
  22056. result[i] = values[offset + i];
  22057. }
  22058. return result;
  22059. } // Template methods for derived classes:
  22060. interpolate_() {
  22061. throw new Error('call to abstract method'); // implementations shall return this.resultBuffer
  22062. }
  22063. intervalChanged_() {// empty
  22064. }
  22065. }
  22066. /**
  22067. * Fast and simple cubic spline interpolant.
  22068. *
  22069. * It was derived from a Hermitian construction setting the first derivative
  22070. * at each sample position to the linear slope between neighboring positions
  22071. * over their parameter interval.
  22072. */
  22073. class CubicInterpolant extends Interpolant {
  22074. constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  22075. super(parameterPositions, sampleValues, sampleSize, resultBuffer);
  22076. this._weightPrev = -0;
  22077. this._offsetPrev = -0;
  22078. this._weightNext = -0;
  22079. this._offsetNext = -0;
  22080. this.DefaultSettings_ = {
  22081. endingStart: ZeroCurvatureEnding,
  22082. endingEnd: ZeroCurvatureEnding
  22083. };
  22084. }
  22085. intervalChanged_(i1, t0, t1) {
  22086. const pp = this.parameterPositions;
  22087. let iPrev = i1 - 2,
  22088. iNext = i1 + 1,
  22089. tPrev = pp[iPrev],
  22090. tNext = pp[iNext];
  22091. if (tPrev === undefined) {
  22092. switch (this.getSettings_().endingStart) {
  22093. case ZeroSlopeEnding:
  22094. // f'(t0) = 0
  22095. iPrev = i1;
  22096. tPrev = 2 * t0 - t1;
  22097. break;
  22098. case WrapAroundEnding:
  22099. // use the other end of the curve
  22100. iPrev = pp.length - 2;
  22101. tPrev = t0 + pp[iPrev] - pp[iPrev + 1];
  22102. break;
  22103. default:
  22104. // ZeroCurvatureEnding
  22105. // f''(t0) = 0 a.k.a. Natural Spline
  22106. iPrev = i1;
  22107. tPrev = t1;
  22108. }
  22109. }
  22110. if (tNext === undefined) {
  22111. switch (this.getSettings_().endingEnd) {
  22112. case ZeroSlopeEnding:
  22113. // f'(tN) = 0
  22114. iNext = i1;
  22115. tNext = 2 * t1 - t0;
  22116. break;
  22117. case WrapAroundEnding:
  22118. // use the other end of the curve
  22119. iNext = 1;
  22120. tNext = t1 + pp[1] - pp[0];
  22121. break;
  22122. default:
  22123. // ZeroCurvatureEnding
  22124. // f''(tN) = 0, a.k.a. Natural Spline
  22125. iNext = i1 - 1;
  22126. tNext = t0;
  22127. }
  22128. }
  22129. const halfDt = (t1 - t0) * 0.5,
  22130. stride = this.valueSize;
  22131. this._weightPrev = halfDt / (t0 - tPrev);
  22132. this._weightNext = halfDt / (tNext - t1);
  22133. this._offsetPrev = iPrev * stride;
  22134. this._offsetNext = iNext * stride;
  22135. }
  22136. interpolate_(i1, t0, t, t1) {
  22137. const result = this.resultBuffer,
  22138. values = this.sampleValues,
  22139. stride = this.valueSize,
  22140. o1 = i1 * stride,
  22141. o0 = o1 - stride,
  22142. oP = this._offsetPrev,
  22143. oN = this._offsetNext,
  22144. wP = this._weightPrev,
  22145. wN = this._weightNext,
  22146. p = (t - t0) / (t1 - t0),
  22147. pp = p * p,
  22148. ppp = pp * p; // evaluate polynomials
  22149. const sP = -wP * ppp + 2 * wP * pp - wP * p;
  22150. const s0 = (1 + wP) * ppp + (-1.5 - 2 * wP) * pp + (-0.5 + wP) * p + 1;
  22151. const s1 = (-1 - wN) * ppp + (1.5 + wN) * pp + 0.5 * p;
  22152. const sN = wN * ppp - wN * pp; // combine data linearly
  22153. for (let i = 0; i !== stride; ++i) {
  22154. result[i] = sP * values[oP + i] + s0 * values[o0 + i] + s1 * values[o1 + i] + sN * values[oN + i];
  22155. }
  22156. return result;
  22157. }
  22158. }
  22159. class LinearInterpolant extends Interpolant {
  22160. constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  22161. super(parameterPositions, sampleValues, sampleSize, resultBuffer);
  22162. }
  22163. interpolate_(i1, t0, t, t1) {
  22164. const result = this.resultBuffer,
  22165. values = this.sampleValues,
  22166. stride = this.valueSize,
  22167. offset1 = i1 * stride,
  22168. offset0 = offset1 - stride,
  22169. weight1 = (t - t0) / (t1 - t0),
  22170. weight0 = 1 - weight1;
  22171. for (let i = 0; i !== stride; ++i) {
  22172. result[i] = values[offset0 + i] * weight0 + values[offset1 + i] * weight1;
  22173. }
  22174. return result;
  22175. }
  22176. }
  22177. /**
  22178. *
  22179. * Interpolant that evaluates to the sample value at the position preceding
  22180. * the parameter.
  22181. */
  22182. class DiscreteInterpolant extends Interpolant {
  22183. constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  22184. super(parameterPositions, sampleValues, sampleSize, resultBuffer);
  22185. }
  22186. interpolate_(i1
  22187. /*, t0, t, t1 */
  22188. ) {
  22189. return this.copySampleValue_(i1 - 1);
  22190. }
  22191. }
  22192. class KeyframeTrack {
  22193. constructor(name, times, values, interpolation) {
  22194. if (name === undefined) throw new Error('THREE.KeyframeTrack: track name is undefined');
  22195. if (times === undefined || times.length === 0) throw new Error('THREE.KeyframeTrack: no keyframes in track named ' + name);
  22196. this.name = name;
  22197. this.times = AnimationUtils.convertArray(times, this.TimeBufferType);
  22198. this.values = AnimationUtils.convertArray(values, this.ValueBufferType);
  22199. this.setInterpolation(interpolation || this.DefaultInterpolation);
  22200. } // Serialization (in static context, because of constructor invocation
  22201. // and automatic invocation of .toJSON):
  22202. static toJSON(track) {
  22203. const trackType = track.constructor;
  22204. let json; // derived classes can define a static toJSON method
  22205. if (trackType.toJSON !== this.toJSON) {
  22206. json = trackType.toJSON(track);
  22207. } else {
  22208. // by default, we assume the data can be serialized as-is
  22209. json = {
  22210. 'name': track.name,
  22211. 'times': AnimationUtils.convertArray(track.times, Array),
  22212. 'values': AnimationUtils.convertArray(track.values, Array)
  22213. };
  22214. const interpolation = track.getInterpolation();
  22215. if (interpolation !== track.DefaultInterpolation) {
  22216. json.interpolation = interpolation;
  22217. }
  22218. }
  22219. json.type = track.ValueTypeName; // mandatory
  22220. return json;
  22221. }
  22222. InterpolantFactoryMethodDiscrete(result) {
  22223. return new DiscreteInterpolant(this.times, this.values, this.getValueSize(), result);
  22224. }
  22225. InterpolantFactoryMethodLinear(result) {
  22226. return new LinearInterpolant(this.times, this.values, this.getValueSize(), result);
  22227. }
  22228. InterpolantFactoryMethodSmooth(result) {
  22229. return new CubicInterpolant(this.times, this.values, this.getValueSize(), result);
  22230. }
  22231. setInterpolation(interpolation) {
  22232. let factoryMethod;
  22233. switch (interpolation) {
  22234. case InterpolateDiscrete:
  22235. factoryMethod = this.InterpolantFactoryMethodDiscrete;
  22236. break;
  22237. case InterpolateLinear:
  22238. factoryMethod = this.InterpolantFactoryMethodLinear;
  22239. break;
  22240. case InterpolateSmooth:
  22241. factoryMethod = this.InterpolantFactoryMethodSmooth;
  22242. break;
  22243. }
  22244. if (factoryMethod === undefined) {
  22245. const message = 'unsupported interpolation for ' + this.ValueTypeName + ' keyframe track named ' + this.name;
  22246. if (this.createInterpolant === undefined) {
  22247. // fall back to default, unless the default itself is messed up
  22248. if (interpolation !== this.DefaultInterpolation) {
  22249. this.setInterpolation(this.DefaultInterpolation);
  22250. } else {
  22251. throw new Error(message); // fatal, in this case
  22252. }
  22253. }
  22254. console.warn('THREE.KeyframeTrack:', message);
  22255. return this;
  22256. }
  22257. this.createInterpolant = factoryMethod;
  22258. return this;
  22259. }
  22260. getInterpolation() {
  22261. switch (this.createInterpolant) {
  22262. case this.InterpolantFactoryMethodDiscrete:
  22263. return InterpolateDiscrete;
  22264. case this.InterpolantFactoryMethodLinear:
  22265. return InterpolateLinear;
  22266. case this.InterpolantFactoryMethodSmooth:
  22267. return InterpolateSmooth;
  22268. }
  22269. }
  22270. getValueSize() {
  22271. return this.values.length / this.times.length;
  22272. } // move all keyframes either forwards or backwards in time
  22273. shift(timeOffset) {
  22274. if (timeOffset !== 0.0) {
  22275. const times = this.times;
  22276. for (let i = 0, n = times.length; i !== n; ++i) {
  22277. times[i] += timeOffset;
  22278. }
  22279. }
  22280. return this;
  22281. } // scale all keyframe times by a factor (useful for frame <-> seconds conversions)
  22282. scale(timeScale) {
  22283. if (timeScale !== 1.0) {
  22284. const times = this.times;
  22285. for (let i = 0, n = times.length; i !== n; ++i) {
  22286. times[i] *= timeScale;
  22287. }
  22288. }
  22289. return this;
  22290. } // removes keyframes before and after animation without changing any values within the range [startTime, endTime].
  22291. // IMPORTANT: We do not shift around keys to the start of the track time, because for interpolated keys this will change their values
  22292. trim(startTime, endTime) {
  22293. const times = this.times,
  22294. nKeys = times.length;
  22295. let from = 0,
  22296. to = nKeys - 1;
  22297. while (from !== nKeys && times[from] < startTime) {
  22298. ++from;
  22299. }
  22300. while (to !== -1 && times[to] > endTime) {
  22301. --to;
  22302. }
  22303. ++to; // inclusive -> exclusive bound
  22304. if (from !== 0 || to !== nKeys) {
  22305. // empty tracks are forbidden, so keep at least one keyframe
  22306. if (from >= to) {
  22307. to = Math.max(to, 1);
  22308. from = to - 1;
  22309. }
  22310. const stride = this.getValueSize();
  22311. this.times = AnimationUtils.arraySlice(times, from, to);
  22312. this.values = AnimationUtils.arraySlice(this.values, from * stride, to * stride);
  22313. }
  22314. return this;
  22315. } // ensure we do not get a GarbageInGarbageOut situation, make sure tracks are at least minimally viable
  22316. validate() {
  22317. let valid = true;
  22318. const valueSize = this.getValueSize();
  22319. if (valueSize - Math.floor(valueSize) !== 0) {
  22320. console.error('THREE.KeyframeTrack: Invalid value size in track.', this);
  22321. valid = false;
  22322. }
  22323. const times = this.times,
  22324. values = this.values,
  22325. nKeys = times.length;
  22326. if (nKeys === 0) {
  22327. console.error('THREE.KeyframeTrack: Track is empty.', this);
  22328. valid = false;
  22329. }
  22330. let prevTime = null;
  22331. for (let i = 0; i !== nKeys; i++) {
  22332. const currTime = times[i];
  22333. if (typeof currTime === 'number' && isNaN(currTime)) {
  22334. console.error('THREE.KeyframeTrack: Time is not a valid number.', this, i, currTime);
  22335. valid = false;
  22336. break;
  22337. }
  22338. if (prevTime !== null && prevTime > currTime) {
  22339. console.error('THREE.KeyframeTrack: Out of order keys.', this, i, currTime, prevTime);
  22340. valid = false;
  22341. break;
  22342. }
  22343. prevTime = currTime;
  22344. }
  22345. if (values !== undefined) {
  22346. if (AnimationUtils.isTypedArray(values)) {
  22347. for (let i = 0, n = values.length; i !== n; ++i) {
  22348. const value = values[i];
  22349. if (isNaN(value)) {
  22350. console.error('THREE.KeyframeTrack: Value is not a valid number.', this, i, value);
  22351. valid = false;
  22352. break;
  22353. }
  22354. }
  22355. }
  22356. }
  22357. return valid;
  22358. } // removes equivalent sequential keys as common in morph target sequences
  22359. // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0)
  22360. optimize() {
  22361. // times or values may be shared with other tracks, so overwriting is unsafe
  22362. const times = AnimationUtils.arraySlice(this.times),
  22363. values = AnimationUtils.arraySlice(this.values),
  22364. stride = this.getValueSize(),
  22365. smoothInterpolation = this.getInterpolation() === InterpolateSmooth,
  22366. lastIndex = times.length - 1;
  22367. let writeIndex = 1;
  22368. for (let i = 1; i < lastIndex; ++i) {
  22369. let keep = false;
  22370. const time = times[i];
  22371. const timeNext = times[i + 1]; // remove adjacent keyframes scheduled at the same time
  22372. if (time !== timeNext && (i !== 1 || time !== times[0])) {
  22373. if (!smoothInterpolation) {
  22374. // remove unnecessary keyframes same as their neighbors
  22375. const offset = i * stride,
  22376. offsetP = offset - stride,
  22377. offsetN = offset + stride;
  22378. for (let j = 0; j !== stride; ++j) {
  22379. const value = values[offset + j];
  22380. if (value !== values[offsetP + j] || value !== values[offsetN + j]) {
  22381. keep = true;
  22382. break;
  22383. }
  22384. }
  22385. } else {
  22386. keep = true;
  22387. }
  22388. } // in-place compaction
  22389. if (keep) {
  22390. if (i !== writeIndex) {
  22391. times[writeIndex] = times[i];
  22392. const readOffset = i * stride,
  22393. writeOffset = writeIndex * stride;
  22394. for (let j = 0; j !== stride; ++j) {
  22395. values[writeOffset + j] = values[readOffset + j];
  22396. }
  22397. }
  22398. ++writeIndex;
  22399. }
  22400. } // flush last keyframe (compaction looks ahead)
  22401. if (lastIndex > 0) {
  22402. times[writeIndex] = times[lastIndex];
  22403. for (let readOffset = lastIndex * stride, writeOffset = writeIndex * stride, j = 0; j !== stride; ++j) {
  22404. values[writeOffset + j] = values[readOffset + j];
  22405. }
  22406. ++writeIndex;
  22407. }
  22408. if (writeIndex !== times.length) {
  22409. this.times = AnimationUtils.arraySlice(times, 0, writeIndex);
  22410. this.values = AnimationUtils.arraySlice(values, 0, writeIndex * stride);
  22411. } else {
  22412. this.times = times;
  22413. this.values = values;
  22414. }
  22415. return this;
  22416. }
  22417. clone() {
  22418. const times = AnimationUtils.arraySlice(this.times, 0);
  22419. const values = AnimationUtils.arraySlice(this.values, 0);
  22420. const TypedKeyframeTrack = this.constructor;
  22421. const track = new TypedKeyframeTrack(this.name, times, values); // Interpolant argument to constructor is not saved, so copy the factory method directly.
  22422. track.createInterpolant = this.createInterpolant;
  22423. return track;
  22424. }
  22425. }
  22426. KeyframeTrack.prototype.TimeBufferType = Float32Array;
  22427. KeyframeTrack.prototype.ValueBufferType = Float32Array;
  22428. KeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear;
  22429. /**
  22430. * A Track of Boolean keyframe values.
  22431. */
  22432. class BooleanKeyframeTrack extends KeyframeTrack {}
  22433. BooleanKeyframeTrack.prototype.ValueTypeName = 'bool';
  22434. BooleanKeyframeTrack.prototype.ValueBufferType = Array;
  22435. BooleanKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  22436. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  22437. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined; // Note: Actually this track could have a optimized / compressed
  22438. /**
  22439. * A Track of keyframe values that represent color.
  22440. */
  22441. class ColorKeyframeTrack extends KeyframeTrack {}
  22442. ColorKeyframeTrack.prototype.ValueTypeName = 'color'; // ValueBufferType is inherited
  22443. /**
  22444. * A Track of numeric keyframe values.
  22445. */
  22446. class NumberKeyframeTrack extends KeyframeTrack {}
  22447. NumberKeyframeTrack.prototype.ValueTypeName = 'number'; // ValueBufferType is inherited
  22448. /**
  22449. * Spherical linear unit quaternion interpolant.
  22450. */
  22451. class QuaternionLinearInterpolant extends Interpolant {
  22452. constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  22453. super(parameterPositions, sampleValues, sampleSize, resultBuffer);
  22454. }
  22455. interpolate_(i1, t0, t, t1) {
  22456. const result = this.resultBuffer,
  22457. values = this.sampleValues,
  22458. stride = this.valueSize,
  22459. alpha = (t - t0) / (t1 - t0);
  22460. let offset = i1 * stride;
  22461. for (let end = offset + stride; offset !== end; offset += 4) {
  22462. Quaternion.slerpFlat(result, 0, values, offset - stride, values, offset, alpha);
  22463. }
  22464. return result;
  22465. }
  22466. }
  22467. /**
  22468. * A Track of quaternion keyframe values.
  22469. */
  22470. class QuaternionKeyframeTrack extends KeyframeTrack {
  22471. InterpolantFactoryMethodLinear(result) {
  22472. return new QuaternionLinearInterpolant(this.times, this.values, this.getValueSize(), result);
  22473. }
  22474. }
  22475. QuaternionKeyframeTrack.prototype.ValueTypeName = 'quaternion'; // ValueBufferType is inherited
  22476. QuaternionKeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear;
  22477. QuaternionKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  22478. /**
  22479. * A Track that interpolates Strings
  22480. */
  22481. class StringKeyframeTrack extends KeyframeTrack {}
  22482. StringKeyframeTrack.prototype.ValueTypeName = 'string';
  22483. StringKeyframeTrack.prototype.ValueBufferType = Array;
  22484. StringKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  22485. StringKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  22486. StringKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  22487. /**
  22488. * A Track of vectored keyframe values.
  22489. */
  22490. class VectorKeyframeTrack extends KeyframeTrack {}
  22491. VectorKeyframeTrack.prototype.ValueTypeName = 'vector'; // ValueBufferType is inherited
  22492. class AnimationClip {
  22493. constructor(name, duration = -1, tracks, blendMode = NormalAnimationBlendMode) {
  22494. this.name = name;
  22495. this.tracks = tracks;
  22496. this.duration = duration;
  22497. this.blendMode = blendMode;
  22498. this.uuid = generateUUID(); // this means it should figure out its duration by scanning the tracks
  22499. if (this.duration < 0) {
  22500. this.resetDuration();
  22501. }
  22502. }
  22503. static parse(json) {
  22504. const tracks = [],
  22505. jsonTracks = json.tracks,
  22506. frameTime = 1.0 / (json.fps || 1.0);
  22507. for (let i = 0, n = jsonTracks.length; i !== n; ++i) {
  22508. tracks.push(parseKeyframeTrack(jsonTracks[i]).scale(frameTime));
  22509. }
  22510. const clip = new this(json.name, json.duration, tracks, json.blendMode);
  22511. clip.uuid = json.uuid;
  22512. return clip;
  22513. }
  22514. static toJSON(clip) {
  22515. const tracks = [],
  22516. clipTracks = clip.tracks;
  22517. const json = {
  22518. 'name': clip.name,
  22519. 'duration': clip.duration,
  22520. 'tracks': tracks,
  22521. 'uuid': clip.uuid,
  22522. 'blendMode': clip.blendMode
  22523. };
  22524. for (let i = 0, n = clipTracks.length; i !== n; ++i) {
  22525. tracks.push(KeyframeTrack.toJSON(clipTracks[i]));
  22526. }
  22527. return json;
  22528. }
  22529. static CreateFromMorphTargetSequence(name, morphTargetSequence, fps, noLoop) {
  22530. const numMorphTargets = morphTargetSequence.length;
  22531. const tracks = [];
  22532. for (let i = 0; i < numMorphTargets; i++) {
  22533. let times = [];
  22534. let values = [];
  22535. times.push((i + numMorphTargets - 1) % numMorphTargets, i, (i + 1) % numMorphTargets);
  22536. values.push(0, 1, 0);
  22537. const order = AnimationUtils.getKeyframeOrder(times);
  22538. times = AnimationUtils.sortedArray(times, 1, order);
  22539. values = AnimationUtils.sortedArray(values, 1, order); // if there is a key at the first frame, duplicate it as the
  22540. // last frame as well for perfect loop.
  22541. if (!noLoop && times[0] === 0) {
  22542. times.push(numMorphTargets);
  22543. values.push(values[0]);
  22544. }
  22545. tracks.push(new NumberKeyframeTrack('.morphTargetInfluences[' + morphTargetSequence[i].name + ']', times, values).scale(1.0 / fps));
  22546. }
  22547. return new this(name, -1, tracks);
  22548. }
  22549. static findByName(objectOrClipArray, name) {
  22550. let clipArray = objectOrClipArray;
  22551. if (!Array.isArray(objectOrClipArray)) {
  22552. const o = objectOrClipArray;
  22553. clipArray = o.geometry && o.geometry.animations || o.animations;
  22554. }
  22555. for (let i = 0; i < clipArray.length; i++) {
  22556. if (clipArray[i].name === name) {
  22557. return clipArray[i];
  22558. }
  22559. }
  22560. return null;
  22561. }
  22562. static CreateClipsFromMorphTargetSequences(morphTargets, fps, noLoop) {
  22563. const animationToMorphTargets = {}; // tested with https://regex101.com/ on trick sequences
  22564. // such flamingo_flyA_003, flamingo_run1_003, crdeath0059
  22565. const pattern = /^([\w-]*?)([\d]+)$/; // sort morph target names into animation groups based
  22566. // patterns like Walk_001, Walk_002, Run_001, Run_002
  22567. for (let i = 0, il = morphTargets.length; i < il; i++) {
  22568. const morphTarget = morphTargets[i];
  22569. const parts = morphTarget.name.match(pattern);
  22570. if (parts && parts.length > 1) {
  22571. const name = parts[1];
  22572. let animationMorphTargets = animationToMorphTargets[name];
  22573. if (!animationMorphTargets) {
  22574. animationToMorphTargets[name] = animationMorphTargets = [];
  22575. }
  22576. animationMorphTargets.push(morphTarget);
  22577. }
  22578. }
  22579. const clips = [];
  22580. for (const name in animationToMorphTargets) {
  22581. clips.push(this.CreateFromMorphTargetSequence(name, animationToMorphTargets[name], fps, noLoop));
  22582. }
  22583. return clips;
  22584. } // parse the animation.hierarchy format
  22585. static parseAnimation(animation, bones) {
  22586. if (!animation) {
  22587. console.error('THREE.AnimationClip: No animation in JSONLoader data.');
  22588. return null;
  22589. }
  22590. const addNonemptyTrack = function (trackType, trackName, animationKeys, propertyName, destTracks) {
  22591. // only return track if there are actually keys.
  22592. if (animationKeys.length !== 0) {
  22593. const times = [];
  22594. const values = [];
  22595. AnimationUtils.flattenJSON(animationKeys, times, values, propertyName); // empty keys are filtered out, so check again
  22596. if (times.length !== 0) {
  22597. destTracks.push(new trackType(trackName, times, values));
  22598. }
  22599. }
  22600. };
  22601. const tracks = [];
  22602. const clipName = animation.name || 'default';
  22603. const fps = animation.fps || 30;
  22604. const blendMode = animation.blendMode; // automatic length determination in AnimationClip.
  22605. let duration = animation.length || -1;
  22606. const hierarchyTracks = animation.hierarchy || [];
  22607. for (let h = 0; h < hierarchyTracks.length; h++) {
  22608. const animationKeys = hierarchyTracks[h].keys; // skip empty tracks
  22609. if (!animationKeys || animationKeys.length === 0) continue; // process morph targets
  22610. if (animationKeys[0].morphTargets) {
  22611. // figure out all morph targets used in this track
  22612. const morphTargetNames = {};
  22613. let k;
  22614. for (k = 0; k < animationKeys.length; k++) {
  22615. if (animationKeys[k].morphTargets) {
  22616. for (let m = 0; m < animationKeys[k].morphTargets.length; m++) {
  22617. morphTargetNames[animationKeys[k].morphTargets[m]] = -1;
  22618. }
  22619. }
  22620. } // create a track for each morph target with all zero
  22621. // morphTargetInfluences except for the keys in which
  22622. // the morphTarget is named.
  22623. for (const morphTargetName in morphTargetNames) {
  22624. const times = [];
  22625. const values = [];
  22626. for (let m = 0; m !== animationKeys[k].morphTargets.length; ++m) {
  22627. const animationKey = animationKeys[k];
  22628. times.push(animationKey.time);
  22629. values.push(animationKey.morphTarget === morphTargetName ? 1 : 0);
  22630. }
  22631. tracks.push(new NumberKeyframeTrack('.morphTargetInfluence[' + morphTargetName + ']', times, values));
  22632. }
  22633. duration = morphTargetNames.length * fps;
  22634. } else {
  22635. // ...assume skeletal animation
  22636. const boneName = '.bones[' + bones[h].name + ']';
  22637. addNonemptyTrack(VectorKeyframeTrack, boneName + '.position', animationKeys, 'pos', tracks);
  22638. addNonemptyTrack(QuaternionKeyframeTrack, boneName + '.quaternion', animationKeys, 'rot', tracks);
  22639. addNonemptyTrack(VectorKeyframeTrack, boneName + '.scale', animationKeys, 'scl', tracks);
  22640. }
  22641. }
  22642. if (tracks.length === 0) {
  22643. return null;
  22644. }
  22645. const clip = new this(clipName, duration, tracks, blendMode);
  22646. return clip;
  22647. }
  22648. resetDuration() {
  22649. const tracks = this.tracks;
  22650. let duration = 0;
  22651. for (let i = 0, n = tracks.length; i !== n; ++i) {
  22652. const track = this.tracks[i];
  22653. duration = Math.max(duration, track.times[track.times.length - 1]);
  22654. }
  22655. this.duration = duration;
  22656. return this;
  22657. }
  22658. trim() {
  22659. for (let i = 0; i < this.tracks.length; i++) {
  22660. this.tracks[i].trim(0, this.duration);
  22661. }
  22662. return this;
  22663. }
  22664. validate() {
  22665. let valid = true;
  22666. for (let i = 0; i < this.tracks.length; i++) {
  22667. valid = valid && this.tracks[i].validate();
  22668. }
  22669. return valid;
  22670. }
  22671. optimize() {
  22672. for (let i = 0; i < this.tracks.length; i++) {
  22673. this.tracks[i].optimize();
  22674. }
  22675. return this;
  22676. }
  22677. clone() {
  22678. const tracks = [];
  22679. for (let i = 0; i < this.tracks.length; i++) {
  22680. tracks.push(this.tracks[i].clone());
  22681. }
  22682. return new this.constructor(this.name, this.duration, tracks, this.blendMode);
  22683. }
  22684. toJSON() {
  22685. return this.constructor.toJSON(this);
  22686. }
  22687. }
  22688. function getTrackTypeForValueTypeName(typeName) {
  22689. switch (typeName.toLowerCase()) {
  22690. case 'scalar':
  22691. case 'double':
  22692. case 'float':
  22693. case 'number':
  22694. case 'integer':
  22695. return NumberKeyframeTrack;
  22696. case 'vector':
  22697. case 'vector2':
  22698. case 'vector3':
  22699. case 'vector4':
  22700. return VectorKeyframeTrack;
  22701. case 'color':
  22702. return ColorKeyframeTrack;
  22703. case 'quaternion':
  22704. return QuaternionKeyframeTrack;
  22705. case 'bool':
  22706. case 'boolean':
  22707. return BooleanKeyframeTrack;
  22708. case 'string':
  22709. return StringKeyframeTrack;
  22710. }
  22711. throw new Error('THREE.KeyframeTrack: Unsupported typeName: ' + typeName);
  22712. }
  22713. function parseKeyframeTrack(json) {
  22714. if (json.type === undefined) {
  22715. throw new Error('THREE.KeyframeTrack: track type undefined, can not parse');
  22716. }
  22717. const trackType = getTrackTypeForValueTypeName(json.type);
  22718. if (json.times === undefined) {
  22719. const times = [],
  22720. values = [];
  22721. AnimationUtils.flattenJSON(json.keys, times, values, 'value');
  22722. json.times = times;
  22723. json.values = values;
  22724. } // derived classes can define a static parse method
  22725. if (trackType.parse !== undefined) {
  22726. return trackType.parse(json);
  22727. } else {
  22728. // by default, we assume a constructor compatible with the base
  22729. return new trackType(json.name, json.times, json.values, json.interpolation);
  22730. }
  22731. }
  22732. const Cache = {
  22733. enabled: false,
  22734. files: {},
  22735. add: function (key, file) {
  22736. if (this.enabled === false) return; // console.log( 'THREE.Cache', 'Adding key:', key );
  22737. this.files[key] = file;
  22738. },
  22739. get: function (key) {
  22740. if (this.enabled === false) return; // console.log( 'THREE.Cache', 'Checking key:', key );
  22741. return this.files[key];
  22742. },
  22743. remove: function (key) {
  22744. delete this.files[key];
  22745. },
  22746. clear: function () {
  22747. this.files = {};
  22748. }
  22749. };
  22750. class LoadingManager {
  22751. constructor(onLoad, onProgress, onError) {
  22752. const scope = this;
  22753. let isLoading = false;
  22754. let itemsLoaded = 0;
  22755. let itemsTotal = 0;
  22756. let urlModifier = undefined;
  22757. const handlers = []; // Refer to #5689 for the reason why we don't set .onStart
  22758. // in the constructor
  22759. this.onStart = undefined;
  22760. this.onLoad = onLoad;
  22761. this.onProgress = onProgress;
  22762. this.onError = onError;
  22763. this.itemStart = function (url) {
  22764. itemsTotal++;
  22765. if (isLoading === false) {
  22766. if (scope.onStart !== undefined) {
  22767. scope.onStart(url, itemsLoaded, itemsTotal);
  22768. }
  22769. }
  22770. isLoading = true;
  22771. };
  22772. this.itemEnd = function (url) {
  22773. itemsLoaded++;
  22774. if (scope.onProgress !== undefined) {
  22775. scope.onProgress(url, itemsLoaded, itemsTotal);
  22776. }
  22777. if (itemsLoaded === itemsTotal) {
  22778. isLoading = false;
  22779. if (scope.onLoad !== undefined) {
  22780. scope.onLoad();
  22781. }
  22782. }
  22783. };
  22784. this.itemError = function (url) {
  22785. if (scope.onError !== undefined) {
  22786. scope.onError(url);
  22787. }
  22788. };
  22789. this.resolveURL = function (url) {
  22790. if (urlModifier) {
  22791. return urlModifier(url);
  22792. }
  22793. return url;
  22794. };
  22795. this.setURLModifier = function (transform) {
  22796. urlModifier = transform;
  22797. return this;
  22798. };
  22799. this.addHandler = function (regex, loader) {
  22800. handlers.push(regex, loader);
  22801. return this;
  22802. };
  22803. this.removeHandler = function (regex) {
  22804. const index = handlers.indexOf(regex);
  22805. if (index !== -1) {
  22806. handlers.splice(index, 2);
  22807. }
  22808. return this;
  22809. };
  22810. this.getHandler = function (file) {
  22811. for (let i = 0, l = handlers.length; i < l; i += 2) {
  22812. const regex = handlers[i];
  22813. const loader = handlers[i + 1];
  22814. if (regex.global) regex.lastIndex = 0; // see #17920
  22815. if (regex.test(file)) {
  22816. return loader;
  22817. }
  22818. }
  22819. return null;
  22820. };
  22821. }
  22822. }
  22823. const DefaultLoadingManager = new LoadingManager();
  22824. class Loader {
  22825. constructor(manager) {
  22826. this.manager = manager !== undefined ? manager : DefaultLoadingManager;
  22827. this.crossOrigin = 'anonymous';
  22828. this.withCredentials = false;
  22829. this.path = '';
  22830. this.resourcePath = '';
  22831. this.requestHeader = {};
  22832. }
  22833. load() {}
  22834. loadAsync(url, onProgress) {
  22835. const scope = this;
  22836. return new Promise(function (resolve, reject) {
  22837. scope.load(url, resolve, onProgress, reject);
  22838. });
  22839. }
  22840. parse() {}
  22841. setCrossOrigin(crossOrigin) {
  22842. this.crossOrigin = crossOrigin;
  22843. return this;
  22844. }
  22845. setWithCredentials(value) {
  22846. this.withCredentials = value;
  22847. return this;
  22848. }
  22849. setPath(path) {
  22850. this.path = path;
  22851. return this;
  22852. }
  22853. setResourcePath(resourcePath) {
  22854. this.resourcePath = resourcePath;
  22855. return this;
  22856. }
  22857. setRequestHeader(requestHeader) {
  22858. this.requestHeader = requestHeader;
  22859. return this;
  22860. }
  22861. }
  22862. const loading = {};
  22863. class FileLoader extends Loader {
  22864. constructor(manager) {
  22865. super(manager);
  22866. }
  22867. load(url, onLoad, onProgress, onError) {
  22868. if (url === undefined) url = '';
  22869. if (this.path !== undefined) url = this.path + url;
  22870. url = this.manager.resolveURL(url);
  22871. const cached = Cache.get(url);
  22872. if (cached !== undefined) {
  22873. this.manager.itemStart(url);
  22874. setTimeout(() => {
  22875. if (onLoad) onLoad(cached);
  22876. this.manager.itemEnd(url);
  22877. }, 0);
  22878. return cached;
  22879. } // Check if request is duplicate
  22880. if (loading[url] !== undefined) {
  22881. loading[url].push({
  22882. onLoad: onLoad,
  22883. onProgress: onProgress,
  22884. onError: onError
  22885. });
  22886. return;
  22887. } // Initialise array for duplicate requests
  22888. loading[url] = [];
  22889. loading[url].push({
  22890. onLoad: onLoad,
  22891. onProgress: onProgress,
  22892. onError: onError
  22893. }); // create request
  22894. const req = new Request(url, {
  22895. headers: new Headers(this.requestHeader),
  22896. credentials: this.withCredentials ? 'include' : 'same-origin' // An abort controller could be added within a future PR
  22897. }); // record states ( avoid data race )
  22898. const mimeType = this.mimeType;
  22899. const responseType = this.responseType; // start the fetch
  22900. fetch(req).then(response => {
  22901. if (response.status === 200 || response.status === 0) {
  22902. // Some browsers return HTTP Status 0 when using non-http protocol
  22903. // e.g. 'file://' or 'data://'. Handle as success.
  22904. if (response.status === 0) {
  22905. console.warn('THREE.FileLoader: HTTP Status 0 received.');
  22906. } // Workaround: Checking if response.body === undefined for Alipay browser #23548
  22907. if (typeof ReadableStream === 'undefined' || response.body === undefined || response.body.getReader === undefined) {
  22908. return response;
  22909. }
  22910. const callbacks = loading[url];
  22911. const reader = response.body.getReader();
  22912. const contentLength = response.headers.get('Content-Length');
  22913. const total = contentLength ? parseInt(contentLength) : 0;
  22914. const lengthComputable = total !== 0;
  22915. let loaded = 0; // periodically read data into the new stream tracking while download progress
  22916. const stream = new ReadableStream({
  22917. start(controller) {
  22918. readData();
  22919. function readData() {
  22920. reader.read().then(({
  22921. done,
  22922. value
  22923. }) => {
  22924. if (done) {
  22925. controller.close();
  22926. } else {
  22927. loaded += value.byteLength;
  22928. const event = new ProgressEvent('progress', {
  22929. lengthComputable,
  22930. loaded,
  22931. total
  22932. });
  22933. for (let i = 0, il = callbacks.length; i < il; i++) {
  22934. const callback = callbacks[i];
  22935. if (callback.onProgress) callback.onProgress(event);
  22936. }
  22937. controller.enqueue(value);
  22938. readData();
  22939. }
  22940. });
  22941. }
  22942. }
  22943. });
  22944. return new Response(stream);
  22945. } else {
  22946. throw Error(`fetch for "${response.url}" responded with ${response.status}: ${response.statusText}`);
  22947. }
  22948. }).then(response => {
  22949. switch (responseType) {
  22950. case 'arraybuffer':
  22951. return response.arrayBuffer();
  22952. case 'blob':
  22953. return response.blob();
  22954. case 'document':
  22955. return response.text().then(text => {
  22956. const parser = new DOMParser();
  22957. return parser.parseFromString(text, mimeType);
  22958. });
  22959. case 'json':
  22960. return response.json();
  22961. default:
  22962. if (mimeType === undefined) {
  22963. return response.text();
  22964. } else {
  22965. // sniff encoding
  22966. const re = /charset="?([^;"\s]*)"?/i;
  22967. const exec = re.exec(mimeType);
  22968. const label = exec && exec[1] ? exec[1].toLowerCase() : undefined;
  22969. const decoder = new TextDecoder(label);
  22970. return response.arrayBuffer().then(ab => decoder.decode(ab));
  22971. }
  22972. }
  22973. }).then(data => {
  22974. // Add to cache only on HTTP success, so that we do not cache
  22975. // error response bodies as proper responses to requests.
  22976. Cache.add(url, data);
  22977. const callbacks = loading[url];
  22978. delete loading[url];
  22979. for (let i = 0, il = callbacks.length; i < il; i++) {
  22980. const callback = callbacks[i];
  22981. if (callback.onLoad) callback.onLoad(data);
  22982. }
  22983. }).catch(err => {
  22984. // Abort errors and other errors are handled the same
  22985. const callbacks = loading[url];
  22986. if (callbacks === undefined) {
  22987. // When onLoad was called and url was deleted in `loading`
  22988. this.manager.itemError(url);
  22989. throw err;
  22990. }
  22991. delete loading[url];
  22992. for (let i = 0, il = callbacks.length; i < il; i++) {
  22993. const callback = callbacks[i];
  22994. if (callback.onError) callback.onError(err);
  22995. }
  22996. this.manager.itemError(url);
  22997. }).finally(() => {
  22998. this.manager.itemEnd(url);
  22999. });
  23000. this.manager.itemStart(url);
  23001. }
  23002. setResponseType(value) {
  23003. this.responseType = value;
  23004. return this;
  23005. }
  23006. setMimeType(value) {
  23007. this.mimeType = value;
  23008. return this;
  23009. }
  23010. }
  23011. class AnimationLoader extends Loader {
  23012. constructor(manager) {
  23013. super(manager);
  23014. }
  23015. load(url, onLoad, onProgress, onError) {
  23016. const scope = this;
  23017. const loader = new FileLoader(this.manager);
  23018. loader.setPath(this.path);
  23019. loader.setRequestHeader(this.requestHeader);
  23020. loader.setWithCredentials(this.withCredentials);
  23021. loader.load(url, function (text) {
  23022. try {
  23023. onLoad(scope.parse(JSON.parse(text)));
  23024. } catch (e) {
  23025. if (onError) {
  23026. onError(e);
  23027. } else {
  23028. console.error(e);
  23029. }
  23030. scope.manager.itemError(url);
  23031. }
  23032. }, onProgress, onError);
  23033. }
  23034. parse(json) {
  23035. const animations = [];
  23036. for (let i = 0; i < json.length; i++) {
  23037. const clip = AnimationClip.parse(json[i]);
  23038. animations.push(clip);
  23039. }
  23040. return animations;
  23041. }
  23042. }
  23043. /**
  23044. * Abstract Base class to block based textures loader (dds, pvr, ...)
  23045. *
  23046. * Sub classes have to implement the parse() method which will be used in load().
  23047. */
  23048. class CompressedTextureLoader extends Loader {
  23049. constructor(manager) {
  23050. super(manager);
  23051. }
  23052. load(url, onLoad, onProgress, onError) {
  23053. const scope = this;
  23054. const images = [];
  23055. const texture = new CompressedTexture();
  23056. const loader = new FileLoader(this.manager);
  23057. loader.setPath(this.path);
  23058. loader.setResponseType('arraybuffer');
  23059. loader.setRequestHeader(this.requestHeader);
  23060. loader.setWithCredentials(scope.withCredentials);
  23061. let loaded = 0;
  23062. function loadTexture(i) {
  23063. loader.load(url[i], function (buffer) {
  23064. const texDatas = scope.parse(buffer, true);
  23065. images[i] = {
  23066. width: texDatas.width,
  23067. height: texDatas.height,
  23068. format: texDatas.format,
  23069. mipmaps: texDatas.mipmaps
  23070. };
  23071. loaded += 1;
  23072. if (loaded === 6) {
  23073. if (texDatas.mipmapCount === 1) texture.minFilter = LinearFilter;
  23074. texture.image = images;
  23075. texture.format = texDatas.format;
  23076. texture.needsUpdate = true;
  23077. if (onLoad) onLoad(texture);
  23078. }
  23079. }, onProgress, onError);
  23080. }
  23081. if (Array.isArray(url)) {
  23082. for (let i = 0, il = url.length; i < il; ++i) {
  23083. loadTexture(i);
  23084. }
  23085. } else {
  23086. // compressed cubemap texture stored in a single DDS file
  23087. loader.load(url, function (buffer) {
  23088. const texDatas = scope.parse(buffer, true);
  23089. if (texDatas.isCubemap) {
  23090. const faces = texDatas.mipmaps.length / texDatas.mipmapCount;
  23091. for (let f = 0; f < faces; f++) {
  23092. images[f] = {
  23093. mipmaps: []
  23094. };
  23095. for (let i = 0; i < texDatas.mipmapCount; i++) {
  23096. images[f].mipmaps.push(texDatas.mipmaps[f * texDatas.mipmapCount + i]);
  23097. images[f].format = texDatas.format;
  23098. images[f].width = texDatas.width;
  23099. images[f].height = texDatas.height;
  23100. }
  23101. }
  23102. texture.image = images;
  23103. } else {
  23104. texture.image.width = texDatas.width;
  23105. texture.image.height = texDatas.height;
  23106. texture.mipmaps = texDatas.mipmaps;
  23107. }
  23108. if (texDatas.mipmapCount === 1) {
  23109. texture.minFilter = LinearFilter;
  23110. }
  23111. texture.format = texDatas.format;
  23112. texture.needsUpdate = true;
  23113. if (onLoad) onLoad(texture);
  23114. }, onProgress, onError);
  23115. }
  23116. return texture;
  23117. }
  23118. }
  23119. class ImageLoader extends Loader {
  23120. constructor(manager) {
  23121. super(manager);
  23122. }
  23123. load(url, onLoad, onProgress, onError) {
  23124. if (this.path !== undefined) url = this.path + url;
  23125. url = this.manager.resolveURL(url);
  23126. const scope = this;
  23127. const cached = Cache.get(url);
  23128. if (cached !== undefined) {
  23129. scope.manager.itemStart(url);
  23130. setTimeout(function () {
  23131. if (onLoad) onLoad(cached);
  23132. scope.manager.itemEnd(url);
  23133. }, 0);
  23134. return cached;
  23135. }
  23136. const image = createElementNS('img');
  23137. function onImageLoad() {
  23138. removeEventListeners();
  23139. Cache.add(url, this);
  23140. if (onLoad) onLoad(this);
  23141. scope.manager.itemEnd(url);
  23142. }
  23143. function onImageError(event) {
  23144. removeEventListeners();
  23145. if (onError) onError(event);
  23146. scope.manager.itemError(url);
  23147. scope.manager.itemEnd(url);
  23148. }
  23149. function removeEventListeners() {
  23150. image.removeEventListener('load', onImageLoad, false);
  23151. image.removeEventListener('error', onImageError, false);
  23152. }
  23153. image.addEventListener('load', onImageLoad, false);
  23154. image.addEventListener('error', onImageError, false);
  23155. if (url.slice(0, 5) !== 'data:') {
  23156. if (this.crossOrigin !== undefined) image.crossOrigin = this.crossOrigin;
  23157. }
  23158. scope.manager.itemStart(url);
  23159. image.src = url;
  23160. return image;
  23161. }
  23162. }
  23163. class CubeTextureLoader extends Loader {
  23164. constructor(manager) {
  23165. super(manager);
  23166. }
  23167. load(urls, onLoad, onProgress, onError) {
  23168. const texture = new CubeTexture();
  23169. const loader = new ImageLoader(this.manager);
  23170. loader.setCrossOrigin(this.crossOrigin);
  23171. loader.setPath(this.path);
  23172. let loaded = 0;
  23173. function loadTexture(i) {
  23174. loader.load(urls[i], function (image) {
  23175. texture.images[i] = image;
  23176. loaded++;
  23177. if (loaded === 6) {
  23178. texture.needsUpdate = true;
  23179. if (onLoad) onLoad(texture);
  23180. }
  23181. }, undefined, onError);
  23182. }
  23183. for (let i = 0; i < urls.length; ++i) {
  23184. loadTexture(i);
  23185. }
  23186. return texture;
  23187. }
  23188. }
  23189. /**
  23190. * Abstract Base class to load generic binary textures formats (rgbe, hdr, ...)
  23191. *
  23192. * Sub classes have to implement the parse() method which will be used in load().
  23193. */
  23194. class DataTextureLoader extends Loader {
  23195. constructor(manager) {
  23196. super(manager);
  23197. }
  23198. load(url, onLoad, onProgress, onError) {
  23199. const scope = this;
  23200. const texture = new DataTexture();
  23201. const loader = new FileLoader(this.manager);
  23202. loader.setResponseType('arraybuffer');
  23203. loader.setRequestHeader(this.requestHeader);
  23204. loader.setPath(this.path);
  23205. loader.setWithCredentials(scope.withCredentials);
  23206. loader.load(url, function (buffer) {
  23207. const texData = scope.parse(buffer);
  23208. if (!texData) return;
  23209. if (texData.image !== undefined) {
  23210. texture.image = texData.image;
  23211. } else if (texData.data !== undefined) {
  23212. texture.image.width = texData.width;
  23213. texture.image.height = texData.height;
  23214. texture.image.data = texData.data;
  23215. }
  23216. texture.wrapS = texData.wrapS !== undefined ? texData.wrapS : ClampToEdgeWrapping;
  23217. texture.wrapT = texData.wrapT !== undefined ? texData.wrapT : ClampToEdgeWrapping;
  23218. texture.magFilter = texData.magFilter !== undefined ? texData.magFilter : LinearFilter;
  23219. texture.minFilter = texData.minFilter !== undefined ? texData.minFilter : LinearFilter;
  23220. texture.anisotropy = texData.anisotropy !== undefined ? texData.anisotropy : 1;
  23221. if (texData.encoding !== undefined) {
  23222. texture.encoding = texData.encoding;
  23223. }
  23224. if (texData.flipY !== undefined) {
  23225. texture.flipY = texData.flipY;
  23226. }
  23227. if (texData.format !== undefined) {
  23228. texture.format = texData.format;
  23229. }
  23230. if (texData.type !== undefined) {
  23231. texture.type = texData.type;
  23232. }
  23233. if (texData.mipmaps !== undefined) {
  23234. texture.mipmaps = texData.mipmaps;
  23235. texture.minFilter = LinearMipmapLinearFilter; // presumably...
  23236. }
  23237. if (texData.mipmapCount === 1) {
  23238. texture.minFilter = LinearFilter;
  23239. }
  23240. if (texData.generateMipmaps !== undefined) {
  23241. texture.generateMipmaps = texData.generateMipmaps;
  23242. }
  23243. texture.needsUpdate = true;
  23244. if (onLoad) onLoad(texture, texData);
  23245. }, onProgress, onError);
  23246. return texture;
  23247. }
  23248. }
  23249. class TextureLoader extends Loader {
  23250. constructor(manager) {
  23251. super(manager);
  23252. }
  23253. load(url, onLoad, onProgress, onError) {
  23254. const texture = new Texture();
  23255. const loader = new ImageLoader(this.manager);
  23256. loader.setCrossOrigin(this.crossOrigin);
  23257. loader.setPath(this.path);
  23258. loader.load(url, function (image) {
  23259. texture.image = image;
  23260. texture.needsUpdate = true;
  23261. if (onLoad !== undefined) {
  23262. onLoad(texture);
  23263. }
  23264. }, onProgress, onError);
  23265. return texture;
  23266. }
  23267. }
  23268. class Light extends Object3D {
  23269. constructor(color, intensity = 1) {
  23270. super();
  23271. this.isLight = true;
  23272. this.type = 'Light';
  23273. this.color = new Color(color);
  23274. this.intensity = intensity;
  23275. }
  23276. dispose() {// Empty here in base class; some subclasses override.
  23277. }
  23278. copy(source) {
  23279. super.copy(source);
  23280. this.color.copy(source.color);
  23281. this.intensity = source.intensity;
  23282. return this;
  23283. }
  23284. toJSON(meta) {
  23285. const data = super.toJSON(meta);
  23286. data.object.color = this.color.getHex();
  23287. data.object.intensity = this.intensity;
  23288. if (this.groundColor !== undefined) data.object.groundColor = this.groundColor.getHex();
  23289. if (this.distance !== undefined) data.object.distance = this.distance;
  23290. if (this.angle !== undefined) data.object.angle = this.angle;
  23291. if (this.decay !== undefined) data.object.decay = this.decay;
  23292. if (this.penumbra !== undefined) data.object.penumbra = this.penumbra;
  23293. if (this.shadow !== undefined) data.object.shadow = this.shadow.toJSON();
  23294. return data;
  23295. }
  23296. }
  23297. class HemisphereLight extends Light {
  23298. constructor(skyColor, groundColor, intensity) {
  23299. super(skyColor, intensity);
  23300. this.isHemisphereLight = true;
  23301. this.type = 'HemisphereLight';
  23302. this.position.copy(Object3D.DefaultUp);
  23303. this.updateMatrix();
  23304. this.groundColor = new Color(groundColor);
  23305. }
  23306. copy(source) {
  23307. super.copy(source);
  23308. this.groundColor.copy(source.groundColor);
  23309. return this;
  23310. }
  23311. }
  23312. const _projScreenMatrix$1 = /*@__PURE__*/new Matrix4();
  23313. const _lightPositionWorld$1 = /*@__PURE__*/new Vector3();
  23314. const _lookTarget$1 = /*@__PURE__*/new Vector3();
  23315. class LightShadow {
  23316. constructor(camera) {
  23317. this.camera = camera;
  23318. this.bias = 0;
  23319. this.normalBias = 0;
  23320. this.radius = 1;
  23321. this.blurSamples = 8;
  23322. this.mapSize = new Vector2(512, 512);
  23323. this.map = null;
  23324. this.mapPass = null;
  23325. this.matrix = new Matrix4();
  23326. this.autoUpdate = true;
  23327. this.needsUpdate = false;
  23328. this._frustum = new Frustum();
  23329. this._frameExtents = new Vector2(1, 1);
  23330. this._viewportCount = 1;
  23331. this._viewports = [new Vector4(0, 0, 1, 1)];
  23332. }
  23333. getViewportCount() {
  23334. return this._viewportCount;
  23335. }
  23336. getFrustum() {
  23337. return this._frustum;
  23338. }
  23339. updateMatrices(light) {
  23340. const shadowCamera = this.camera;
  23341. const shadowMatrix = this.matrix;
  23342. _lightPositionWorld$1.setFromMatrixPosition(light.matrixWorld);
  23343. shadowCamera.position.copy(_lightPositionWorld$1);
  23344. _lookTarget$1.setFromMatrixPosition(light.target.matrixWorld);
  23345. shadowCamera.lookAt(_lookTarget$1);
  23346. shadowCamera.updateMatrixWorld();
  23347. _projScreenMatrix$1.multiplyMatrices(shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse);
  23348. this._frustum.setFromProjectionMatrix(_projScreenMatrix$1);
  23349. 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);
  23350. shadowMatrix.multiply(shadowCamera.projectionMatrix);
  23351. shadowMatrix.multiply(shadowCamera.matrixWorldInverse);
  23352. }
  23353. getViewport(viewportIndex) {
  23354. return this._viewports[viewportIndex];
  23355. }
  23356. getFrameExtents() {
  23357. return this._frameExtents;
  23358. }
  23359. dispose() {
  23360. if (this.map) {
  23361. this.map.dispose();
  23362. }
  23363. if (this.mapPass) {
  23364. this.mapPass.dispose();
  23365. }
  23366. }
  23367. copy(source) {
  23368. this.camera = source.camera.clone();
  23369. this.bias = source.bias;
  23370. this.radius = source.radius;
  23371. this.mapSize.copy(source.mapSize);
  23372. return this;
  23373. }
  23374. clone() {
  23375. return new this.constructor().copy(this);
  23376. }
  23377. toJSON() {
  23378. const object = {};
  23379. if (this.bias !== 0) object.bias = this.bias;
  23380. if (this.normalBias !== 0) object.normalBias = this.normalBias;
  23381. if (this.radius !== 1) object.radius = this.radius;
  23382. if (this.mapSize.x !== 512 || this.mapSize.y !== 512) object.mapSize = this.mapSize.toArray();
  23383. object.camera = this.camera.toJSON(false).object;
  23384. delete object.camera.matrix;
  23385. return object;
  23386. }
  23387. }
  23388. class SpotLightShadow extends LightShadow {
  23389. constructor() {
  23390. super(new PerspectiveCamera(50, 1, 0.5, 500));
  23391. this.isSpotLightShadow = true;
  23392. this.focus = 1;
  23393. }
  23394. updateMatrices(light) {
  23395. const camera = this.camera;
  23396. const fov = RAD2DEG * 2 * light.angle * this.focus;
  23397. const aspect = this.mapSize.width / this.mapSize.height;
  23398. const far = light.distance || camera.far;
  23399. if (fov !== camera.fov || aspect !== camera.aspect || far !== camera.far) {
  23400. camera.fov = fov;
  23401. camera.aspect = aspect;
  23402. camera.far = far;
  23403. camera.updateProjectionMatrix();
  23404. }
  23405. super.updateMatrices(light);
  23406. }
  23407. copy(source) {
  23408. super.copy(source);
  23409. this.focus = source.focus;
  23410. return this;
  23411. }
  23412. }
  23413. class SpotLight extends Light {
  23414. constructor(color, intensity, distance = 0, angle = Math.PI / 3, penumbra = 0, decay = 1) {
  23415. super(color, intensity);
  23416. this.isSpotLight = true;
  23417. this.type = 'SpotLight';
  23418. this.position.copy(Object3D.DefaultUp);
  23419. this.updateMatrix();
  23420. this.target = new Object3D();
  23421. this.distance = distance;
  23422. this.angle = angle;
  23423. this.penumbra = penumbra;
  23424. this.decay = decay; // for physically correct lights, should be 2.
  23425. this.shadow = new SpotLightShadow();
  23426. }
  23427. get power() {
  23428. // compute the light's luminous power (in lumens) from its intensity (in candela)
  23429. // by convention for a spotlight, luminous power (lm) = π * luminous intensity (cd)
  23430. return this.intensity * Math.PI;
  23431. }
  23432. set power(power) {
  23433. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  23434. this.intensity = power / Math.PI;
  23435. }
  23436. dispose() {
  23437. this.shadow.dispose();
  23438. }
  23439. copy(source) {
  23440. super.copy(source);
  23441. this.distance = source.distance;
  23442. this.angle = source.angle;
  23443. this.penumbra = source.penumbra;
  23444. this.decay = source.decay;
  23445. this.target = source.target.clone();
  23446. this.shadow = source.shadow.clone();
  23447. return this;
  23448. }
  23449. }
  23450. const _projScreenMatrix = /*@__PURE__*/new Matrix4();
  23451. const _lightPositionWorld = /*@__PURE__*/new Vector3();
  23452. const _lookTarget = /*@__PURE__*/new Vector3();
  23453. class PointLightShadow extends LightShadow {
  23454. constructor() {
  23455. super(new PerspectiveCamera(90, 1, 0.5, 500));
  23456. this.isPointLightShadow = true;
  23457. this._frameExtents = new Vector2(4, 2);
  23458. this._viewportCount = 6;
  23459. this._viewports = [// These viewports map a cube-map onto a 2D texture with the
  23460. // following orientation:
  23461. //
  23462. // xzXZ
  23463. // y Y
  23464. //
  23465. // X - Positive x direction
  23466. // x - Negative x direction
  23467. // Y - Positive y direction
  23468. // y - Negative y direction
  23469. // Z - Positive z direction
  23470. // z - Negative z direction
  23471. // positive X
  23472. new Vector4(2, 1, 1, 1), // negative X
  23473. new Vector4(0, 1, 1, 1), // positive Z
  23474. new Vector4(3, 1, 1, 1), // negative Z
  23475. new Vector4(1, 1, 1, 1), // positive Y
  23476. new Vector4(3, 0, 1, 1), // negative Y
  23477. new Vector4(1, 0, 1, 1)];
  23478. 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)];
  23479. 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)];
  23480. }
  23481. updateMatrices(light, viewportIndex = 0) {
  23482. const camera = this.camera;
  23483. const shadowMatrix = this.matrix;
  23484. const far = light.distance || camera.far;
  23485. if (far !== camera.far) {
  23486. camera.far = far;
  23487. camera.updateProjectionMatrix();
  23488. }
  23489. _lightPositionWorld.setFromMatrixPosition(light.matrixWorld);
  23490. camera.position.copy(_lightPositionWorld);
  23491. _lookTarget.copy(camera.position);
  23492. _lookTarget.add(this._cubeDirections[viewportIndex]);
  23493. camera.up.copy(this._cubeUps[viewportIndex]);
  23494. camera.lookAt(_lookTarget);
  23495. camera.updateMatrixWorld();
  23496. shadowMatrix.makeTranslation(-_lightPositionWorld.x, -_lightPositionWorld.y, -_lightPositionWorld.z);
  23497. _projScreenMatrix.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse);
  23498. this._frustum.setFromProjectionMatrix(_projScreenMatrix);
  23499. }
  23500. }
  23501. class PointLight extends Light {
  23502. constructor(color, intensity, distance = 0, decay = 1) {
  23503. super(color, intensity);
  23504. this.isPointLight = true;
  23505. this.type = 'PointLight';
  23506. this.distance = distance;
  23507. this.decay = decay; // for physically correct lights, should be 2.
  23508. this.shadow = new PointLightShadow();
  23509. }
  23510. get power() {
  23511. // compute the light's luminous power (in lumens) from its intensity (in candela)
  23512. // for an isotropic light source, luminous power (lm) = 4 π luminous intensity (cd)
  23513. return this.intensity * 4 * Math.PI;
  23514. }
  23515. set power(power) {
  23516. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  23517. this.intensity = power / (4 * Math.PI);
  23518. }
  23519. dispose() {
  23520. this.shadow.dispose();
  23521. }
  23522. copy(source) {
  23523. super.copy(source);
  23524. this.distance = source.distance;
  23525. this.decay = source.decay;
  23526. this.shadow = source.shadow.clone();
  23527. return this;
  23528. }
  23529. }
  23530. class DirectionalLightShadow extends LightShadow {
  23531. constructor() {
  23532. super(new OrthographicCamera(-5, 5, 5, -5, 0.5, 500));
  23533. this.isDirectionalLightShadow = true;
  23534. }
  23535. }
  23536. class DirectionalLight extends Light {
  23537. constructor(color, intensity) {
  23538. super(color, intensity);
  23539. this.isDirectionalLight = true;
  23540. this.type = 'DirectionalLight';
  23541. this.position.copy(Object3D.DefaultUp);
  23542. this.updateMatrix();
  23543. this.target = new Object3D();
  23544. this.shadow = new DirectionalLightShadow();
  23545. }
  23546. dispose() {
  23547. this.shadow.dispose();
  23548. }
  23549. copy(source) {
  23550. super.copy(source);
  23551. this.target = source.target.clone();
  23552. this.shadow = source.shadow.clone();
  23553. return this;
  23554. }
  23555. }
  23556. class AmbientLight extends Light {
  23557. constructor(color, intensity) {
  23558. super(color, intensity);
  23559. this.isAmbientLight = true;
  23560. this.type = 'AmbientLight';
  23561. }
  23562. }
  23563. class RectAreaLight extends Light {
  23564. constructor(color, intensity, width = 10, height = 10) {
  23565. super(color, intensity);
  23566. this.isRectAreaLight = true;
  23567. this.type = 'RectAreaLight';
  23568. this.width = width;
  23569. this.height = height;
  23570. }
  23571. get power() {
  23572. // compute the light's luminous power (in lumens) from its intensity (in nits)
  23573. return this.intensity * this.width * this.height * Math.PI;
  23574. }
  23575. set power(power) {
  23576. // set the light's intensity (in nits) from the desired luminous power (in lumens)
  23577. this.intensity = power / (this.width * this.height * Math.PI);
  23578. }
  23579. copy(source) {
  23580. super.copy(source);
  23581. this.width = source.width;
  23582. this.height = source.height;
  23583. return this;
  23584. }
  23585. toJSON(meta) {
  23586. const data = super.toJSON(meta);
  23587. data.object.width = this.width;
  23588. data.object.height = this.height;
  23589. return data;
  23590. }
  23591. }
  23592. /**
  23593. * Primary reference:
  23594. * https://graphics.stanford.edu/papers/envmap/envmap.pdf
  23595. *
  23596. * Secondary reference:
  23597. * https://www.ppsloan.org/publications/StupidSH36.pdf
  23598. */
  23599. // 3-band SH defined by 9 coefficients
  23600. class SphericalHarmonics3 {
  23601. constructor() {
  23602. this.isSphericalHarmonics3 = true;
  23603. this.coefficients = [];
  23604. for (let i = 0; i < 9; i++) {
  23605. this.coefficients.push(new Vector3());
  23606. }
  23607. }
  23608. set(coefficients) {
  23609. for (let i = 0; i < 9; i++) {
  23610. this.coefficients[i].copy(coefficients[i]);
  23611. }
  23612. return this;
  23613. }
  23614. zero() {
  23615. for (let i = 0; i < 9; i++) {
  23616. this.coefficients[i].set(0, 0, 0);
  23617. }
  23618. return this;
  23619. } // get the radiance in the direction of the normal
  23620. // target is a Vector3
  23621. getAt(normal, target) {
  23622. // normal is assumed to be unit length
  23623. const x = normal.x,
  23624. y = normal.y,
  23625. z = normal.z;
  23626. const coeff = this.coefficients; // band 0
  23627. target.copy(coeff[0]).multiplyScalar(0.282095); // band 1
  23628. target.addScaledVector(coeff[1], 0.488603 * y);
  23629. target.addScaledVector(coeff[2], 0.488603 * z);
  23630. target.addScaledVector(coeff[3], 0.488603 * x); // band 2
  23631. target.addScaledVector(coeff[4], 1.092548 * (x * y));
  23632. target.addScaledVector(coeff[5], 1.092548 * (y * z));
  23633. target.addScaledVector(coeff[6], 0.315392 * (3.0 * z * z - 1.0));
  23634. target.addScaledVector(coeff[7], 1.092548 * (x * z));
  23635. target.addScaledVector(coeff[8], 0.546274 * (x * x - y * y));
  23636. return target;
  23637. } // get the irradiance (radiance convolved with cosine lobe) in the direction of the normal
  23638. // target is a Vector3
  23639. // https://graphics.stanford.edu/papers/envmap/envmap.pdf
  23640. getIrradianceAt(normal, target) {
  23641. // normal is assumed to be unit length
  23642. const x = normal.x,
  23643. y = normal.y,
  23644. z = normal.z;
  23645. const coeff = this.coefficients; // band 0
  23646. target.copy(coeff[0]).multiplyScalar(0.886227); // π * 0.282095
  23647. // band 1
  23648. target.addScaledVector(coeff[1], 2.0 * 0.511664 * y); // ( 2 * π / 3 ) * 0.488603
  23649. target.addScaledVector(coeff[2], 2.0 * 0.511664 * z);
  23650. target.addScaledVector(coeff[3], 2.0 * 0.511664 * x); // band 2
  23651. target.addScaledVector(coeff[4], 2.0 * 0.429043 * x * y); // ( π / 4 ) * 1.092548
  23652. target.addScaledVector(coeff[5], 2.0 * 0.429043 * y * z);
  23653. target.addScaledVector(coeff[6], 0.743125 * z * z - 0.247708); // ( π / 4 ) * 0.315392 * 3
  23654. target.addScaledVector(coeff[7], 2.0 * 0.429043 * x * z);
  23655. target.addScaledVector(coeff[8], 0.429043 * (x * x - y * y)); // ( π / 4 ) * 0.546274
  23656. return target;
  23657. }
  23658. add(sh) {
  23659. for (let i = 0; i < 9; i++) {
  23660. this.coefficients[i].add(sh.coefficients[i]);
  23661. }
  23662. return this;
  23663. }
  23664. addScaledSH(sh, s) {
  23665. for (let i = 0; i < 9; i++) {
  23666. this.coefficients[i].addScaledVector(sh.coefficients[i], s);
  23667. }
  23668. return this;
  23669. }
  23670. scale(s) {
  23671. for (let i = 0; i < 9; i++) {
  23672. this.coefficients[i].multiplyScalar(s);
  23673. }
  23674. return this;
  23675. }
  23676. lerp(sh, alpha) {
  23677. for (let i = 0; i < 9; i++) {
  23678. this.coefficients[i].lerp(sh.coefficients[i], alpha);
  23679. }
  23680. return this;
  23681. }
  23682. equals(sh) {
  23683. for (let i = 0; i < 9; i++) {
  23684. if (!this.coefficients[i].equals(sh.coefficients[i])) {
  23685. return false;
  23686. }
  23687. }
  23688. return true;
  23689. }
  23690. copy(sh) {
  23691. return this.set(sh.coefficients);
  23692. }
  23693. clone() {
  23694. return new this.constructor().copy(this);
  23695. }
  23696. fromArray(array, offset = 0) {
  23697. const coefficients = this.coefficients;
  23698. for (let i = 0; i < 9; i++) {
  23699. coefficients[i].fromArray(array, offset + i * 3);
  23700. }
  23701. return this;
  23702. }
  23703. toArray(array = [], offset = 0) {
  23704. const coefficients = this.coefficients;
  23705. for (let i = 0; i < 9; i++) {
  23706. coefficients[i].toArray(array, offset + i * 3);
  23707. }
  23708. return array;
  23709. } // evaluate the basis functions
  23710. // shBasis is an Array[ 9 ]
  23711. static getBasisAt(normal, shBasis) {
  23712. // normal is assumed to be unit length
  23713. const x = normal.x,
  23714. y = normal.y,
  23715. z = normal.z; // band 0
  23716. shBasis[0] = 0.282095; // band 1
  23717. shBasis[1] = 0.488603 * y;
  23718. shBasis[2] = 0.488603 * z;
  23719. shBasis[3] = 0.488603 * x; // band 2
  23720. shBasis[4] = 1.092548 * x * y;
  23721. shBasis[5] = 1.092548 * y * z;
  23722. shBasis[6] = 0.315392 * (3 * z * z - 1);
  23723. shBasis[7] = 1.092548 * x * z;
  23724. shBasis[8] = 0.546274 * (x * x - y * y);
  23725. }
  23726. }
  23727. class LightProbe extends Light {
  23728. constructor(sh = new SphericalHarmonics3(), intensity = 1) {
  23729. super(undefined, intensity);
  23730. this.isLightProbe = true;
  23731. this.sh = sh;
  23732. }
  23733. copy(source) {
  23734. super.copy(source);
  23735. this.sh.copy(source.sh);
  23736. return this;
  23737. }
  23738. fromJSON(json) {
  23739. this.intensity = json.intensity; // TODO: Move this bit to Light.fromJSON();
  23740. this.sh.fromArray(json.sh);
  23741. return this;
  23742. }
  23743. toJSON(meta) {
  23744. const data = super.toJSON(meta);
  23745. data.object.sh = this.sh.toArray();
  23746. return data;
  23747. }
  23748. }
  23749. class MaterialLoader extends Loader {
  23750. constructor(manager) {
  23751. super(manager);
  23752. this.textures = {};
  23753. }
  23754. load(url, onLoad, onProgress, onError) {
  23755. const scope = this;
  23756. const loader = new FileLoader(scope.manager);
  23757. loader.setPath(scope.path);
  23758. loader.setRequestHeader(scope.requestHeader);
  23759. loader.setWithCredentials(scope.withCredentials);
  23760. loader.load(url, function (text) {
  23761. try {
  23762. onLoad(scope.parse(JSON.parse(text)));
  23763. } catch (e) {
  23764. if (onError) {
  23765. onError(e);
  23766. } else {
  23767. console.error(e);
  23768. }
  23769. scope.manager.itemError(url);
  23770. }
  23771. }, onProgress, onError);
  23772. }
  23773. parse(json) {
  23774. const textures = this.textures;
  23775. function getTexture(name) {
  23776. if (textures[name] === undefined) {
  23777. console.warn('THREE.MaterialLoader: Undefined texture', name);
  23778. }
  23779. return textures[name];
  23780. }
  23781. const material = Material.fromType(json.type);
  23782. if (json.uuid !== undefined) material.uuid = json.uuid;
  23783. if (json.name !== undefined) material.name = json.name;
  23784. if (json.color !== undefined && material.color !== undefined) material.color.setHex(json.color);
  23785. if (json.roughness !== undefined) material.roughness = json.roughness;
  23786. if (json.metalness !== undefined) material.metalness = json.metalness;
  23787. if (json.sheen !== undefined) material.sheen = json.sheen;
  23788. if (json.sheenColor !== undefined) material.sheenColor = new Color().setHex(json.sheenColor);
  23789. if (json.sheenRoughness !== undefined) material.sheenRoughness = json.sheenRoughness;
  23790. if (json.emissive !== undefined && material.emissive !== undefined) material.emissive.setHex(json.emissive);
  23791. if (json.specular !== undefined && material.specular !== undefined) material.specular.setHex(json.specular);
  23792. if (json.specularIntensity !== undefined) material.specularIntensity = json.specularIntensity;
  23793. if (json.specularColor !== undefined && material.specularColor !== undefined) material.specularColor.setHex(json.specularColor);
  23794. if (json.shininess !== undefined) material.shininess = json.shininess;
  23795. if (json.clearcoat !== undefined) material.clearcoat = json.clearcoat;
  23796. if (json.clearcoatRoughness !== undefined) material.clearcoatRoughness = json.clearcoatRoughness;
  23797. if (json.transmission !== undefined) material.transmission = json.transmission;
  23798. if (json.thickness !== undefined) material.thickness = json.thickness;
  23799. if (json.attenuationDistance !== undefined) material.attenuationDistance = json.attenuationDistance;
  23800. if (json.attenuationColor !== undefined && material.attenuationColor !== undefined) material.attenuationColor.setHex(json.attenuationColor);
  23801. if (json.fog !== undefined) material.fog = json.fog;
  23802. if (json.flatShading !== undefined) material.flatShading = json.flatShading;
  23803. if (json.blending !== undefined) material.blending = json.blending;
  23804. if (json.combine !== undefined) material.combine = json.combine;
  23805. if (json.side !== undefined) material.side = json.side;
  23806. if (json.shadowSide !== undefined) material.shadowSide = json.shadowSide;
  23807. if (json.opacity !== undefined) material.opacity = json.opacity;
  23808. if (json.transparent !== undefined) material.transparent = json.transparent;
  23809. if (json.alphaTest !== undefined) material.alphaTest = json.alphaTest;
  23810. if (json.depthTest !== undefined) material.depthTest = json.depthTest;
  23811. if (json.depthWrite !== undefined) material.depthWrite = json.depthWrite;
  23812. if (json.colorWrite !== undefined) material.colorWrite = json.colorWrite;
  23813. if (json.stencilWrite !== undefined) material.stencilWrite = json.stencilWrite;
  23814. if (json.stencilWriteMask !== undefined) material.stencilWriteMask = json.stencilWriteMask;
  23815. if (json.stencilFunc !== undefined) material.stencilFunc = json.stencilFunc;
  23816. if (json.stencilRef !== undefined) material.stencilRef = json.stencilRef;
  23817. if (json.stencilFuncMask !== undefined) material.stencilFuncMask = json.stencilFuncMask;
  23818. if (json.stencilFail !== undefined) material.stencilFail = json.stencilFail;
  23819. if (json.stencilZFail !== undefined) material.stencilZFail = json.stencilZFail;
  23820. if (json.stencilZPass !== undefined) material.stencilZPass = json.stencilZPass;
  23821. if (json.wireframe !== undefined) material.wireframe = json.wireframe;
  23822. if (json.wireframeLinewidth !== undefined) material.wireframeLinewidth = json.wireframeLinewidth;
  23823. if (json.wireframeLinecap !== undefined) material.wireframeLinecap = json.wireframeLinecap;
  23824. if (json.wireframeLinejoin !== undefined) material.wireframeLinejoin = json.wireframeLinejoin;
  23825. if (json.rotation !== undefined) material.rotation = json.rotation;
  23826. if (json.linewidth !== 1) material.linewidth = json.linewidth;
  23827. if (json.dashSize !== undefined) material.dashSize = json.dashSize;
  23828. if (json.gapSize !== undefined) material.gapSize = json.gapSize;
  23829. if (json.scale !== undefined) material.scale = json.scale;
  23830. if (json.polygonOffset !== undefined) material.polygonOffset = json.polygonOffset;
  23831. if (json.polygonOffsetFactor !== undefined) material.polygonOffsetFactor = json.polygonOffsetFactor;
  23832. if (json.polygonOffsetUnits !== undefined) material.polygonOffsetUnits = json.polygonOffsetUnits;
  23833. if (json.dithering !== undefined) material.dithering = json.dithering;
  23834. if (json.alphaToCoverage !== undefined) material.alphaToCoverage = json.alphaToCoverage;
  23835. if (json.premultipliedAlpha !== undefined) material.premultipliedAlpha = json.premultipliedAlpha;
  23836. if (json.visible !== undefined) material.visible = json.visible;
  23837. if (json.toneMapped !== undefined) material.toneMapped = json.toneMapped;
  23838. if (json.userData !== undefined) material.userData = json.userData;
  23839. if (json.vertexColors !== undefined) {
  23840. if (typeof json.vertexColors === 'number') {
  23841. material.vertexColors = json.vertexColors > 0 ? true : false;
  23842. } else {
  23843. material.vertexColors = json.vertexColors;
  23844. }
  23845. } // Shader Material
  23846. if (json.uniforms !== undefined) {
  23847. for (const name in json.uniforms) {
  23848. const uniform = json.uniforms[name];
  23849. material.uniforms[name] = {};
  23850. switch (uniform.type) {
  23851. case 't':
  23852. material.uniforms[name].value = getTexture(uniform.value);
  23853. break;
  23854. case 'c':
  23855. material.uniforms[name].value = new Color().setHex(uniform.value);
  23856. break;
  23857. case 'v2':
  23858. material.uniforms[name].value = new Vector2().fromArray(uniform.value);
  23859. break;
  23860. case 'v3':
  23861. material.uniforms[name].value = new Vector3().fromArray(uniform.value);
  23862. break;
  23863. case 'v4':
  23864. material.uniforms[name].value = new Vector4().fromArray(uniform.value);
  23865. break;
  23866. case 'm3':
  23867. material.uniforms[name].value = new Matrix3().fromArray(uniform.value);
  23868. break;
  23869. case 'm4':
  23870. material.uniforms[name].value = new Matrix4().fromArray(uniform.value);
  23871. break;
  23872. default:
  23873. material.uniforms[name].value = uniform.value;
  23874. }
  23875. }
  23876. }
  23877. if (json.defines !== undefined) material.defines = json.defines;
  23878. if (json.vertexShader !== undefined) material.vertexShader = json.vertexShader;
  23879. if (json.fragmentShader !== undefined) material.fragmentShader = json.fragmentShader;
  23880. if (json.extensions !== undefined) {
  23881. for (const key in json.extensions) {
  23882. material.extensions[key] = json.extensions[key];
  23883. }
  23884. } // Deprecated
  23885. if (json.shading !== undefined) material.flatShading = json.shading === 1; // THREE.FlatShading
  23886. // for PointsMaterial
  23887. if (json.size !== undefined) material.size = json.size;
  23888. if (json.sizeAttenuation !== undefined) material.sizeAttenuation = json.sizeAttenuation; // maps
  23889. if (json.map !== undefined) material.map = getTexture(json.map);
  23890. if (json.matcap !== undefined) material.matcap = getTexture(json.matcap);
  23891. if (json.alphaMap !== undefined) material.alphaMap = getTexture(json.alphaMap);
  23892. if (json.bumpMap !== undefined) material.bumpMap = getTexture(json.bumpMap);
  23893. if (json.bumpScale !== undefined) material.bumpScale = json.bumpScale;
  23894. if (json.normalMap !== undefined) material.normalMap = getTexture(json.normalMap);
  23895. if (json.normalMapType !== undefined) material.normalMapType = json.normalMapType;
  23896. if (json.normalScale !== undefined) {
  23897. let normalScale = json.normalScale;
  23898. if (Array.isArray(normalScale) === false) {
  23899. // Blender exporter used to export a scalar. See #7459
  23900. normalScale = [normalScale, normalScale];
  23901. }
  23902. material.normalScale = new Vector2().fromArray(normalScale);
  23903. }
  23904. if (json.displacementMap !== undefined) material.displacementMap = getTexture(json.displacementMap);
  23905. if (json.displacementScale !== undefined) material.displacementScale = json.displacementScale;
  23906. if (json.displacementBias !== undefined) material.displacementBias = json.displacementBias;
  23907. if (json.roughnessMap !== undefined) material.roughnessMap = getTexture(json.roughnessMap);
  23908. if (json.metalnessMap !== undefined) material.metalnessMap = getTexture(json.metalnessMap);
  23909. if (json.emissiveMap !== undefined) material.emissiveMap = getTexture(json.emissiveMap);
  23910. if (json.emissiveIntensity !== undefined) material.emissiveIntensity = json.emissiveIntensity;
  23911. if (json.specularMap !== undefined) material.specularMap = getTexture(json.specularMap);
  23912. if (json.specularIntensityMap !== undefined) material.specularIntensityMap = getTexture(json.specularIntensityMap);
  23913. if (json.specularColorMap !== undefined) material.specularColorMap = getTexture(json.specularColorMap);
  23914. if (json.envMap !== undefined) material.envMap = getTexture(json.envMap);
  23915. if (json.envMapIntensity !== undefined) material.envMapIntensity = json.envMapIntensity;
  23916. if (json.reflectivity !== undefined) material.reflectivity = json.reflectivity;
  23917. if (json.refractionRatio !== undefined) material.refractionRatio = json.refractionRatio;
  23918. if (json.lightMap !== undefined) material.lightMap = getTexture(json.lightMap);
  23919. if (json.lightMapIntensity !== undefined) material.lightMapIntensity = json.lightMapIntensity;
  23920. if (json.aoMap !== undefined) material.aoMap = getTexture(json.aoMap);
  23921. if (json.aoMapIntensity !== undefined) material.aoMapIntensity = json.aoMapIntensity;
  23922. if (json.gradientMap !== undefined) material.gradientMap = getTexture(json.gradientMap);
  23923. if (json.clearcoatMap !== undefined) material.clearcoatMap = getTexture(json.clearcoatMap);
  23924. if (json.clearcoatRoughnessMap !== undefined) material.clearcoatRoughnessMap = getTexture(json.clearcoatRoughnessMap);
  23925. if (json.clearcoatNormalMap !== undefined) material.clearcoatNormalMap = getTexture(json.clearcoatNormalMap);
  23926. if (json.clearcoatNormalScale !== undefined) material.clearcoatNormalScale = new Vector2().fromArray(json.clearcoatNormalScale);
  23927. if (json.transmissionMap !== undefined) material.transmissionMap = getTexture(json.transmissionMap);
  23928. if (json.thicknessMap !== undefined) material.thicknessMap = getTexture(json.thicknessMap);
  23929. if (json.sheenColorMap !== undefined) material.sheenColorMap = getTexture(json.sheenColorMap);
  23930. if (json.sheenRoughnessMap !== undefined) material.sheenRoughnessMap = getTexture(json.sheenRoughnessMap);
  23931. return material;
  23932. }
  23933. setTextures(value) {
  23934. this.textures = value;
  23935. return this;
  23936. }
  23937. }
  23938. class LoaderUtils {
  23939. static decodeText(array) {
  23940. if (typeof TextDecoder !== 'undefined') {
  23941. return new TextDecoder().decode(array);
  23942. } // Avoid the String.fromCharCode.apply(null, array) shortcut, which
  23943. // throws a "maximum call stack size exceeded" error for large arrays.
  23944. let s = '';
  23945. for (let i = 0, il = array.length; i < il; i++) {
  23946. // Implicitly assumes little-endian.
  23947. s += String.fromCharCode(array[i]);
  23948. }
  23949. try {
  23950. // merges multi-byte utf-8 characters.
  23951. return decodeURIComponent(escape(s));
  23952. } catch (e) {
  23953. // see #16358
  23954. return s;
  23955. }
  23956. }
  23957. static extractUrlBase(url) {
  23958. const index = url.lastIndexOf('/');
  23959. if (index === -1) return './';
  23960. return url.slice(0, index + 1);
  23961. }
  23962. static resolveURL(url, path) {
  23963. // Invalid URL
  23964. if (typeof url !== 'string' || url === '') return ''; // Host Relative URL
  23965. if (/^https?:\/\//i.test(path) && /^\//.test(url)) {
  23966. path = path.replace(/(^https?:\/\/[^\/]+).*/i, '$1');
  23967. } // Absolute URL http://,https://,//
  23968. if (/^(https?:)?\/\//i.test(url)) return url; // Data URI
  23969. if (/^data:.*,.*$/i.test(url)) return url; // Blob URL
  23970. if (/^blob:.*$/i.test(url)) return url; // Relative URL
  23971. return path + url;
  23972. }
  23973. }
  23974. class InstancedBufferGeometry extends BufferGeometry {
  23975. constructor() {
  23976. super();
  23977. this.isInstancedBufferGeometry = true;
  23978. this.type = 'InstancedBufferGeometry';
  23979. this.instanceCount = Infinity;
  23980. }
  23981. copy(source) {
  23982. super.copy(source);
  23983. this.instanceCount = source.instanceCount;
  23984. return this;
  23985. }
  23986. clone() {
  23987. return new this.constructor().copy(this);
  23988. }
  23989. toJSON() {
  23990. const data = super.toJSON(this);
  23991. data.instanceCount = this.instanceCount;
  23992. data.isInstancedBufferGeometry = true;
  23993. return data;
  23994. }
  23995. }
  23996. class BufferGeometryLoader extends Loader {
  23997. constructor(manager) {
  23998. super(manager);
  23999. }
  24000. load(url, onLoad, onProgress, onError) {
  24001. const scope = this;
  24002. const loader = new FileLoader(scope.manager);
  24003. loader.setPath(scope.path);
  24004. loader.setRequestHeader(scope.requestHeader);
  24005. loader.setWithCredentials(scope.withCredentials);
  24006. loader.load(url, function (text) {
  24007. try {
  24008. onLoad(scope.parse(JSON.parse(text)));
  24009. } catch (e) {
  24010. if (onError) {
  24011. onError(e);
  24012. } else {
  24013. console.error(e);
  24014. }
  24015. scope.manager.itemError(url);
  24016. }
  24017. }, onProgress, onError);
  24018. }
  24019. parse(json) {
  24020. const interleavedBufferMap = {};
  24021. const arrayBufferMap = {};
  24022. function getInterleavedBuffer(json, uuid) {
  24023. if (interleavedBufferMap[uuid] !== undefined) return interleavedBufferMap[uuid];
  24024. const interleavedBuffers = json.interleavedBuffers;
  24025. const interleavedBuffer = interleavedBuffers[uuid];
  24026. const buffer = getArrayBuffer(json, interleavedBuffer.buffer);
  24027. const array = getTypedArray(interleavedBuffer.type, buffer);
  24028. const ib = new InterleavedBuffer(array, interleavedBuffer.stride);
  24029. ib.uuid = interleavedBuffer.uuid;
  24030. interleavedBufferMap[uuid] = ib;
  24031. return ib;
  24032. }
  24033. function getArrayBuffer(json, uuid) {
  24034. if (arrayBufferMap[uuid] !== undefined) return arrayBufferMap[uuid];
  24035. const arrayBuffers = json.arrayBuffers;
  24036. const arrayBuffer = arrayBuffers[uuid];
  24037. const ab = new Uint32Array(arrayBuffer).buffer;
  24038. arrayBufferMap[uuid] = ab;
  24039. return ab;
  24040. }
  24041. const geometry = json.isInstancedBufferGeometry ? new InstancedBufferGeometry() : new BufferGeometry();
  24042. const index = json.data.index;
  24043. if (index !== undefined) {
  24044. const typedArray = getTypedArray(index.type, index.array);
  24045. geometry.setIndex(new BufferAttribute(typedArray, 1));
  24046. }
  24047. const attributes = json.data.attributes;
  24048. for (const key in attributes) {
  24049. const attribute = attributes[key];
  24050. let bufferAttribute;
  24051. if (attribute.isInterleavedBufferAttribute) {
  24052. const interleavedBuffer = getInterleavedBuffer(json.data, attribute.data);
  24053. bufferAttribute = new InterleavedBufferAttribute(interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized);
  24054. } else {
  24055. const typedArray = getTypedArray(attribute.type, attribute.array);
  24056. const bufferAttributeConstr = attribute.isInstancedBufferAttribute ? InstancedBufferAttribute : BufferAttribute;
  24057. bufferAttribute = new bufferAttributeConstr(typedArray, attribute.itemSize, attribute.normalized);
  24058. }
  24059. if (attribute.name !== undefined) bufferAttribute.name = attribute.name;
  24060. if (attribute.usage !== undefined) bufferAttribute.setUsage(attribute.usage);
  24061. if (attribute.updateRange !== undefined) {
  24062. bufferAttribute.updateRange.offset = attribute.updateRange.offset;
  24063. bufferAttribute.updateRange.count = attribute.updateRange.count;
  24064. }
  24065. geometry.setAttribute(key, bufferAttribute);
  24066. }
  24067. const morphAttributes = json.data.morphAttributes;
  24068. if (morphAttributes) {
  24069. for (const key in morphAttributes) {
  24070. const attributeArray = morphAttributes[key];
  24071. const array = [];
  24072. for (let i = 0, il = attributeArray.length; i < il; i++) {
  24073. const attribute = attributeArray[i];
  24074. let bufferAttribute;
  24075. if (attribute.isInterleavedBufferAttribute) {
  24076. const interleavedBuffer = getInterleavedBuffer(json.data, attribute.data);
  24077. bufferAttribute = new InterleavedBufferAttribute(interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized);
  24078. } else {
  24079. const typedArray = getTypedArray(attribute.type, attribute.array);
  24080. bufferAttribute = new BufferAttribute(typedArray, attribute.itemSize, attribute.normalized);
  24081. }
  24082. if (attribute.name !== undefined) bufferAttribute.name = attribute.name;
  24083. array.push(bufferAttribute);
  24084. }
  24085. geometry.morphAttributes[key] = array;
  24086. }
  24087. }
  24088. const morphTargetsRelative = json.data.morphTargetsRelative;
  24089. if (morphTargetsRelative) {
  24090. geometry.morphTargetsRelative = true;
  24091. }
  24092. const groups = json.data.groups || json.data.drawcalls || json.data.offsets;
  24093. if (groups !== undefined) {
  24094. for (let i = 0, n = groups.length; i !== n; ++i) {
  24095. const group = groups[i];
  24096. geometry.addGroup(group.start, group.count, group.materialIndex);
  24097. }
  24098. }
  24099. const boundingSphere = json.data.boundingSphere;
  24100. if (boundingSphere !== undefined) {
  24101. const center = new Vector3();
  24102. if (boundingSphere.center !== undefined) {
  24103. center.fromArray(boundingSphere.center);
  24104. }
  24105. geometry.boundingSphere = new Sphere(center, boundingSphere.radius);
  24106. }
  24107. if (json.name) geometry.name = json.name;
  24108. if (json.userData) geometry.userData = json.userData;
  24109. return geometry;
  24110. }
  24111. }
  24112. class ObjectLoader extends Loader {
  24113. constructor(manager) {
  24114. super(manager);
  24115. }
  24116. load(url, onLoad, onProgress, onError) {
  24117. const scope = this;
  24118. const path = this.path === '' ? LoaderUtils.extractUrlBase(url) : this.path;
  24119. this.resourcePath = this.resourcePath || path;
  24120. const loader = new FileLoader(this.manager);
  24121. loader.setPath(this.path);
  24122. loader.setRequestHeader(this.requestHeader);
  24123. loader.setWithCredentials(this.withCredentials);
  24124. loader.load(url, function (text) {
  24125. let json = null;
  24126. try {
  24127. json = JSON.parse(text);
  24128. } catch (error) {
  24129. if (onError !== undefined) onError(error);
  24130. console.error('THREE:ObjectLoader: Can\'t parse ' + url + '.', error.message);
  24131. return;
  24132. }
  24133. const metadata = json.metadata;
  24134. if (metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry') {
  24135. console.error('THREE.ObjectLoader: Can\'t load ' + url);
  24136. return;
  24137. }
  24138. scope.parse(json, onLoad);
  24139. }, onProgress, onError);
  24140. }
  24141. async loadAsync(url, onProgress) {
  24142. const scope = this;
  24143. const path = this.path === '' ? LoaderUtils.extractUrlBase(url) : this.path;
  24144. this.resourcePath = this.resourcePath || path;
  24145. const loader = new FileLoader(this.manager);
  24146. loader.setPath(this.path);
  24147. loader.setRequestHeader(this.requestHeader);
  24148. loader.setWithCredentials(this.withCredentials);
  24149. const text = await loader.loadAsync(url, onProgress);
  24150. const json = JSON.parse(text);
  24151. const metadata = json.metadata;
  24152. if (metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry') {
  24153. throw new Error('THREE.ObjectLoader: Can\'t load ' + url);
  24154. }
  24155. return await scope.parseAsync(json);
  24156. }
  24157. parse(json, onLoad) {
  24158. const animations = this.parseAnimations(json.animations);
  24159. const shapes = this.parseShapes(json.shapes);
  24160. const geometries = this.parseGeometries(json.geometries, shapes);
  24161. const images = this.parseImages(json.images, function () {
  24162. if (onLoad !== undefined) onLoad(object);
  24163. });
  24164. const textures = this.parseTextures(json.textures, images);
  24165. const materials = this.parseMaterials(json.materials, textures);
  24166. const object = this.parseObject(json.object, geometries, materials, textures, animations);
  24167. const skeletons = this.parseSkeletons(json.skeletons, object);
  24168. this.bindSkeletons(object, skeletons); //
  24169. if (onLoad !== undefined) {
  24170. let hasImages = false;
  24171. for (const uuid in images) {
  24172. if (images[uuid].data instanceof HTMLImageElement) {
  24173. hasImages = true;
  24174. break;
  24175. }
  24176. }
  24177. if (hasImages === false) onLoad(object);
  24178. }
  24179. return object;
  24180. }
  24181. async parseAsync(json) {
  24182. const animations = this.parseAnimations(json.animations);
  24183. const shapes = this.parseShapes(json.shapes);
  24184. const geometries = this.parseGeometries(json.geometries, shapes);
  24185. const images = await this.parseImagesAsync(json.images);
  24186. const textures = this.parseTextures(json.textures, images);
  24187. const materials = this.parseMaterials(json.materials, textures);
  24188. const object = this.parseObject(json.object, geometries, materials, textures, animations);
  24189. const skeletons = this.parseSkeletons(json.skeletons, object);
  24190. this.bindSkeletons(object, skeletons);
  24191. return object;
  24192. }
  24193. parseShapes(json) {
  24194. const shapes = {};
  24195. if (json !== undefined) {
  24196. for (let i = 0, l = json.length; i < l; i++) {
  24197. const shape = new Shape().fromJSON(json[i]);
  24198. shapes[shape.uuid] = shape;
  24199. }
  24200. }
  24201. return shapes;
  24202. }
  24203. parseSkeletons(json, object) {
  24204. const skeletons = {};
  24205. const bones = {}; // generate bone lookup table
  24206. object.traverse(function (child) {
  24207. if (child.isBone) bones[child.uuid] = child;
  24208. }); // create skeletons
  24209. if (json !== undefined) {
  24210. for (let i = 0, l = json.length; i < l; i++) {
  24211. const skeleton = new Skeleton().fromJSON(json[i], bones);
  24212. skeletons[skeleton.uuid] = skeleton;
  24213. }
  24214. }
  24215. return skeletons;
  24216. }
  24217. parseGeometries(json, shapes) {
  24218. const geometries = {};
  24219. if (json !== undefined) {
  24220. const bufferGeometryLoader = new BufferGeometryLoader();
  24221. for (let i = 0, l = json.length; i < l; i++) {
  24222. let geometry;
  24223. const data = json[i];
  24224. switch (data.type) {
  24225. case 'BufferGeometry':
  24226. case 'InstancedBufferGeometry':
  24227. geometry = bufferGeometryLoader.parse(data);
  24228. break;
  24229. case 'Geometry':
  24230. console.error('THREE.ObjectLoader: The legacy Geometry type is no longer supported.');
  24231. break;
  24232. default:
  24233. if (data.type in Geometries) {
  24234. geometry = Geometries[data.type].fromJSON(data, shapes);
  24235. } else {
  24236. console.warn(`THREE.ObjectLoader: Unsupported geometry type "${data.type}"`);
  24237. }
  24238. }
  24239. geometry.uuid = data.uuid;
  24240. if (data.name !== undefined) geometry.name = data.name;
  24241. if (geometry.isBufferGeometry === true && data.userData !== undefined) geometry.userData = data.userData;
  24242. geometries[data.uuid] = geometry;
  24243. }
  24244. }
  24245. return geometries;
  24246. }
  24247. parseMaterials(json, textures) {
  24248. const cache = {}; // MultiMaterial
  24249. const materials = {};
  24250. if (json !== undefined) {
  24251. const loader = new MaterialLoader();
  24252. loader.setTextures(textures);
  24253. for (let i = 0, l = json.length; i < l; i++) {
  24254. const data = json[i];
  24255. if (data.type === 'MultiMaterial') {
  24256. // Deprecated
  24257. const array = [];
  24258. for (let j = 0; j < data.materials.length; j++) {
  24259. const material = data.materials[j];
  24260. if (cache[material.uuid] === undefined) {
  24261. cache[material.uuid] = loader.parse(material);
  24262. }
  24263. array.push(cache[material.uuid]);
  24264. }
  24265. materials[data.uuid] = array;
  24266. } else {
  24267. if (cache[data.uuid] === undefined) {
  24268. cache[data.uuid] = loader.parse(data);
  24269. }
  24270. materials[data.uuid] = cache[data.uuid];
  24271. }
  24272. }
  24273. }
  24274. return materials;
  24275. }
  24276. parseAnimations(json) {
  24277. const animations = {};
  24278. if (json !== undefined) {
  24279. for (let i = 0; i < json.length; i++) {
  24280. const data = json[i];
  24281. const clip = AnimationClip.parse(data);
  24282. animations[clip.uuid] = clip;
  24283. }
  24284. }
  24285. return animations;
  24286. }
  24287. parseImages(json, onLoad) {
  24288. const scope = this;
  24289. const images = {};
  24290. let loader;
  24291. function loadImage(url) {
  24292. scope.manager.itemStart(url);
  24293. return loader.load(url, function () {
  24294. scope.manager.itemEnd(url);
  24295. }, undefined, function () {
  24296. scope.manager.itemError(url);
  24297. scope.manager.itemEnd(url);
  24298. });
  24299. }
  24300. function deserializeImage(image) {
  24301. if (typeof image === 'string') {
  24302. const url = image;
  24303. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test(url) ? url : scope.resourcePath + url;
  24304. return loadImage(path);
  24305. } else {
  24306. if (image.data) {
  24307. return {
  24308. data: getTypedArray(image.type, image.data),
  24309. width: image.width,
  24310. height: image.height
  24311. };
  24312. } else {
  24313. return null;
  24314. }
  24315. }
  24316. }
  24317. if (json !== undefined && json.length > 0) {
  24318. const manager = new LoadingManager(onLoad);
  24319. loader = new ImageLoader(manager);
  24320. loader.setCrossOrigin(this.crossOrigin);
  24321. for (let i = 0, il = json.length; i < il; i++) {
  24322. const image = json[i];
  24323. const url = image.url;
  24324. if (Array.isArray(url)) {
  24325. // load array of images e.g CubeTexture
  24326. const imageArray = [];
  24327. for (let j = 0, jl = url.length; j < jl; j++) {
  24328. const currentUrl = url[j];
  24329. const deserializedImage = deserializeImage(currentUrl);
  24330. if (deserializedImage !== null) {
  24331. if (deserializedImage instanceof HTMLImageElement) {
  24332. imageArray.push(deserializedImage);
  24333. } else {
  24334. // special case: handle array of data textures for cube textures
  24335. imageArray.push(new DataTexture(deserializedImage.data, deserializedImage.width, deserializedImage.height));
  24336. }
  24337. }
  24338. }
  24339. images[image.uuid] = new Source(imageArray);
  24340. } else {
  24341. // load single image
  24342. const deserializedImage = deserializeImage(image.url);
  24343. images[image.uuid] = new Source(deserializedImage);
  24344. }
  24345. }
  24346. }
  24347. return images;
  24348. }
  24349. async parseImagesAsync(json) {
  24350. const scope = this;
  24351. const images = {};
  24352. let loader;
  24353. async function deserializeImage(image) {
  24354. if (typeof image === 'string') {
  24355. const url = image;
  24356. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test(url) ? url : scope.resourcePath + url;
  24357. return await loader.loadAsync(path);
  24358. } else {
  24359. if (image.data) {
  24360. return {
  24361. data: getTypedArray(image.type, image.data),
  24362. width: image.width,
  24363. height: image.height
  24364. };
  24365. } else {
  24366. return null;
  24367. }
  24368. }
  24369. }
  24370. if (json !== undefined && json.length > 0) {
  24371. loader = new ImageLoader(this.manager);
  24372. loader.setCrossOrigin(this.crossOrigin);
  24373. for (let i = 0, il = json.length; i < il; i++) {
  24374. const image = json[i];
  24375. const url = image.url;
  24376. if (Array.isArray(url)) {
  24377. // load array of images e.g CubeTexture
  24378. const imageArray = [];
  24379. for (let j = 0, jl = url.length; j < jl; j++) {
  24380. const currentUrl = url[j];
  24381. const deserializedImage = await deserializeImage(currentUrl);
  24382. if (deserializedImage !== null) {
  24383. if (deserializedImage instanceof HTMLImageElement) {
  24384. imageArray.push(deserializedImage);
  24385. } else {
  24386. // special case: handle array of data textures for cube textures
  24387. imageArray.push(new DataTexture(deserializedImage.data, deserializedImage.width, deserializedImage.height));
  24388. }
  24389. }
  24390. }
  24391. images[image.uuid] = new Source(imageArray);
  24392. } else {
  24393. // load single image
  24394. const deserializedImage = await deserializeImage(image.url);
  24395. images[image.uuid] = new Source(deserializedImage);
  24396. }
  24397. }
  24398. }
  24399. return images;
  24400. }
  24401. parseTextures(json, images) {
  24402. function parseConstant(value, type) {
  24403. if (typeof value === 'number') return value;
  24404. console.warn('THREE.ObjectLoader.parseTexture: Constant should be in numeric form.', value);
  24405. return type[value];
  24406. }
  24407. const textures = {};
  24408. if (json !== undefined) {
  24409. for (let i = 0, l = json.length; i < l; i++) {
  24410. const data = json[i];
  24411. if (data.image === undefined) {
  24412. console.warn('THREE.ObjectLoader: No "image" specified for', data.uuid);
  24413. }
  24414. if (images[data.image] === undefined) {
  24415. console.warn('THREE.ObjectLoader: Undefined image', data.image);
  24416. }
  24417. const source = images[data.image];
  24418. const image = source.data;
  24419. let texture;
  24420. if (Array.isArray(image)) {
  24421. texture = new CubeTexture();
  24422. if (image.length === 6) texture.needsUpdate = true;
  24423. } else {
  24424. if (image && image.data) {
  24425. texture = new DataTexture();
  24426. } else {
  24427. texture = new Texture();
  24428. }
  24429. if (image) texture.needsUpdate = true; // textures can have undefined image data
  24430. }
  24431. texture.source = source;
  24432. texture.uuid = data.uuid;
  24433. if (data.name !== undefined) texture.name = data.name;
  24434. if (data.mapping !== undefined) texture.mapping = parseConstant(data.mapping, TEXTURE_MAPPING);
  24435. if (data.offset !== undefined) texture.offset.fromArray(data.offset);
  24436. if (data.repeat !== undefined) texture.repeat.fromArray(data.repeat);
  24437. if (data.center !== undefined) texture.center.fromArray(data.center);
  24438. if (data.rotation !== undefined) texture.rotation = data.rotation;
  24439. if (data.wrap !== undefined) {
  24440. texture.wrapS = parseConstant(data.wrap[0], TEXTURE_WRAPPING);
  24441. texture.wrapT = parseConstant(data.wrap[1], TEXTURE_WRAPPING);
  24442. }
  24443. if (data.format !== undefined) texture.format = data.format;
  24444. if (data.type !== undefined) texture.type = data.type;
  24445. if (data.encoding !== undefined) texture.encoding = data.encoding;
  24446. if (data.minFilter !== undefined) texture.minFilter = parseConstant(data.minFilter, TEXTURE_FILTER);
  24447. if (data.magFilter !== undefined) texture.magFilter = parseConstant(data.magFilter, TEXTURE_FILTER);
  24448. if (data.anisotropy !== undefined) texture.anisotropy = data.anisotropy;
  24449. if (data.flipY !== undefined) texture.flipY = data.flipY;
  24450. if (data.premultiplyAlpha !== undefined) texture.premultiplyAlpha = data.premultiplyAlpha;
  24451. if (data.unpackAlignment !== undefined) texture.unpackAlignment = data.unpackAlignment;
  24452. if (data.userData !== undefined) texture.userData = data.userData;
  24453. textures[data.uuid] = texture;
  24454. }
  24455. }
  24456. return textures;
  24457. }
  24458. parseObject(data, geometries, materials, textures, animations) {
  24459. let object;
  24460. function getGeometry(name) {
  24461. if (geometries[name] === undefined) {
  24462. console.warn('THREE.ObjectLoader: Undefined geometry', name);
  24463. }
  24464. return geometries[name];
  24465. }
  24466. function getMaterial(name) {
  24467. if (name === undefined) return undefined;
  24468. if (Array.isArray(name)) {
  24469. const array = [];
  24470. for (let i = 0, l = name.length; i < l; i++) {
  24471. const uuid = name[i];
  24472. if (materials[uuid] === undefined) {
  24473. console.warn('THREE.ObjectLoader: Undefined material', uuid);
  24474. }
  24475. array.push(materials[uuid]);
  24476. }
  24477. return array;
  24478. }
  24479. if (materials[name] === undefined) {
  24480. console.warn('THREE.ObjectLoader: Undefined material', name);
  24481. }
  24482. return materials[name];
  24483. }
  24484. function getTexture(uuid) {
  24485. if (textures[uuid] === undefined) {
  24486. console.warn('THREE.ObjectLoader: Undefined texture', uuid);
  24487. }
  24488. return textures[uuid];
  24489. }
  24490. let geometry, material;
  24491. switch (data.type) {
  24492. case 'Scene':
  24493. object = new Scene();
  24494. if (data.background !== undefined) {
  24495. if (Number.isInteger(data.background)) {
  24496. object.background = new Color(data.background);
  24497. } else {
  24498. object.background = getTexture(data.background);
  24499. }
  24500. }
  24501. if (data.environment !== undefined) {
  24502. object.environment = getTexture(data.environment);
  24503. }
  24504. if (data.fog !== undefined) {
  24505. if (data.fog.type === 'Fog') {
  24506. object.fog = new Fog(data.fog.color, data.fog.near, data.fog.far);
  24507. } else if (data.fog.type === 'FogExp2') {
  24508. object.fog = new FogExp2(data.fog.color, data.fog.density);
  24509. }
  24510. }
  24511. break;
  24512. case 'PerspectiveCamera':
  24513. object = new PerspectiveCamera(data.fov, data.aspect, data.near, data.far);
  24514. if (data.focus !== undefined) object.focus = data.focus;
  24515. if (data.zoom !== undefined) object.zoom = data.zoom;
  24516. if (data.filmGauge !== undefined) object.filmGauge = data.filmGauge;
  24517. if (data.filmOffset !== undefined) object.filmOffset = data.filmOffset;
  24518. if (data.view !== undefined) object.view = Object.assign({}, data.view);
  24519. break;
  24520. case 'OrthographicCamera':
  24521. object = new OrthographicCamera(data.left, data.right, data.top, data.bottom, data.near, data.far);
  24522. if (data.zoom !== undefined) object.zoom = data.zoom;
  24523. if (data.view !== undefined) object.view = Object.assign({}, data.view);
  24524. break;
  24525. case 'AmbientLight':
  24526. object = new AmbientLight(data.color, data.intensity);
  24527. break;
  24528. case 'DirectionalLight':
  24529. object = new DirectionalLight(data.color, data.intensity);
  24530. break;
  24531. case 'PointLight':
  24532. object = new PointLight(data.color, data.intensity, data.distance, data.decay);
  24533. break;
  24534. case 'RectAreaLight':
  24535. object = new RectAreaLight(data.color, data.intensity, data.width, data.height);
  24536. break;
  24537. case 'SpotLight':
  24538. object = new SpotLight(data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay);
  24539. break;
  24540. case 'HemisphereLight':
  24541. object = new HemisphereLight(data.color, data.groundColor, data.intensity);
  24542. break;
  24543. case 'LightProbe':
  24544. object = new LightProbe().fromJSON(data);
  24545. break;
  24546. case 'SkinnedMesh':
  24547. geometry = getGeometry(data.geometry);
  24548. material = getMaterial(data.material);
  24549. object = new SkinnedMesh(geometry, material);
  24550. if (data.bindMode !== undefined) object.bindMode = data.bindMode;
  24551. if (data.bindMatrix !== undefined) object.bindMatrix.fromArray(data.bindMatrix);
  24552. if (data.skeleton !== undefined) object.skeleton = data.skeleton;
  24553. break;
  24554. case 'Mesh':
  24555. geometry = getGeometry(data.geometry);
  24556. material = getMaterial(data.material);
  24557. object = new Mesh(geometry, material);
  24558. break;
  24559. case 'InstancedMesh':
  24560. geometry = getGeometry(data.geometry);
  24561. material = getMaterial(data.material);
  24562. const count = data.count;
  24563. const instanceMatrix = data.instanceMatrix;
  24564. const instanceColor = data.instanceColor;
  24565. object = new InstancedMesh(geometry, material, count);
  24566. object.instanceMatrix = new InstancedBufferAttribute(new Float32Array(instanceMatrix.array), 16);
  24567. if (instanceColor !== undefined) object.instanceColor = new InstancedBufferAttribute(new Float32Array(instanceColor.array), instanceColor.itemSize);
  24568. break;
  24569. case 'LOD':
  24570. object = new LOD();
  24571. break;
  24572. case 'Line':
  24573. object = new Line(getGeometry(data.geometry), getMaterial(data.material));
  24574. break;
  24575. case 'LineLoop':
  24576. object = new LineLoop(getGeometry(data.geometry), getMaterial(data.material));
  24577. break;
  24578. case 'LineSegments':
  24579. object = new LineSegments(getGeometry(data.geometry), getMaterial(data.material));
  24580. break;
  24581. case 'PointCloud':
  24582. case 'Points':
  24583. object = new Points(getGeometry(data.geometry), getMaterial(data.material));
  24584. break;
  24585. case 'Sprite':
  24586. object = new Sprite(getMaterial(data.material));
  24587. break;
  24588. case 'Group':
  24589. object = new Group();
  24590. break;
  24591. case 'Bone':
  24592. object = new Bone();
  24593. break;
  24594. default:
  24595. object = new Object3D();
  24596. }
  24597. object.uuid = data.uuid;
  24598. if (data.name !== undefined) object.name = data.name;
  24599. if (data.matrix !== undefined) {
  24600. object.matrix.fromArray(data.matrix);
  24601. if (data.matrixAutoUpdate !== undefined) object.matrixAutoUpdate = data.matrixAutoUpdate;
  24602. if (object.matrixAutoUpdate) object.matrix.decompose(object.position, object.quaternion, object.scale);
  24603. } else {
  24604. if (data.position !== undefined) object.position.fromArray(data.position);
  24605. if (data.rotation !== undefined) object.rotation.fromArray(data.rotation);
  24606. if (data.quaternion !== undefined) object.quaternion.fromArray(data.quaternion);
  24607. if (data.scale !== undefined) object.scale.fromArray(data.scale);
  24608. }
  24609. if (data.castShadow !== undefined) object.castShadow = data.castShadow;
  24610. if (data.receiveShadow !== undefined) object.receiveShadow = data.receiveShadow;
  24611. if (data.shadow) {
  24612. if (data.shadow.bias !== undefined) object.shadow.bias = data.shadow.bias;
  24613. if (data.shadow.normalBias !== undefined) object.shadow.normalBias = data.shadow.normalBias;
  24614. if (data.shadow.radius !== undefined) object.shadow.radius = data.shadow.radius;
  24615. if (data.shadow.mapSize !== undefined) object.shadow.mapSize.fromArray(data.shadow.mapSize);
  24616. if (data.shadow.camera !== undefined) object.shadow.camera = this.parseObject(data.shadow.camera);
  24617. }
  24618. if (data.visible !== undefined) object.visible = data.visible;
  24619. if (data.frustumCulled !== undefined) object.frustumCulled = data.frustumCulled;
  24620. if (data.renderOrder !== undefined) object.renderOrder = data.renderOrder;
  24621. if (data.userData !== undefined) object.userData = data.userData;
  24622. if (data.layers !== undefined) object.layers.mask = data.layers;
  24623. if (data.children !== undefined) {
  24624. const children = data.children;
  24625. for (let i = 0; i < children.length; i++) {
  24626. object.add(this.parseObject(children[i], geometries, materials, textures, animations));
  24627. }
  24628. }
  24629. if (data.animations !== undefined) {
  24630. const objectAnimations = data.animations;
  24631. for (let i = 0; i < objectAnimations.length; i++) {
  24632. const uuid = objectAnimations[i];
  24633. object.animations.push(animations[uuid]);
  24634. }
  24635. }
  24636. if (data.type === 'LOD') {
  24637. if (data.autoUpdate !== undefined) object.autoUpdate = data.autoUpdate;
  24638. const levels = data.levels;
  24639. for (let l = 0; l < levels.length; l++) {
  24640. const level = levels[l];
  24641. const child = object.getObjectByProperty('uuid', level.object);
  24642. if (child !== undefined) {
  24643. object.addLevel(child, level.distance);
  24644. }
  24645. }
  24646. }
  24647. return object;
  24648. }
  24649. bindSkeletons(object, skeletons) {
  24650. if (Object.keys(skeletons).length === 0) return;
  24651. object.traverse(function (child) {
  24652. if (child.isSkinnedMesh === true && child.skeleton !== undefined) {
  24653. const skeleton = skeletons[child.skeleton];
  24654. if (skeleton === undefined) {
  24655. console.warn('THREE.ObjectLoader: No skeleton found with UUID:', child.skeleton);
  24656. } else {
  24657. child.bind(skeleton, child.bindMatrix);
  24658. }
  24659. }
  24660. });
  24661. }
  24662. /* DEPRECATED */
  24663. setTexturePath(value) {
  24664. console.warn('THREE.ObjectLoader: .setTexturePath() has been renamed to .setResourcePath().');
  24665. return this.setResourcePath(value);
  24666. }
  24667. }
  24668. const TEXTURE_MAPPING = {
  24669. UVMapping: UVMapping,
  24670. CubeReflectionMapping: CubeReflectionMapping,
  24671. CubeRefractionMapping: CubeRefractionMapping,
  24672. EquirectangularReflectionMapping: EquirectangularReflectionMapping,
  24673. EquirectangularRefractionMapping: EquirectangularRefractionMapping,
  24674. CubeUVReflectionMapping: CubeUVReflectionMapping
  24675. };
  24676. const TEXTURE_WRAPPING = {
  24677. RepeatWrapping: RepeatWrapping,
  24678. ClampToEdgeWrapping: ClampToEdgeWrapping,
  24679. MirroredRepeatWrapping: MirroredRepeatWrapping
  24680. };
  24681. const TEXTURE_FILTER = {
  24682. NearestFilter: NearestFilter,
  24683. NearestMipmapNearestFilter: NearestMipmapNearestFilter,
  24684. NearestMipmapLinearFilter: NearestMipmapLinearFilter,
  24685. LinearFilter: LinearFilter,
  24686. LinearMipmapNearestFilter: LinearMipmapNearestFilter,
  24687. LinearMipmapLinearFilter: LinearMipmapLinearFilter
  24688. };
  24689. class ImageBitmapLoader extends Loader {
  24690. constructor(manager) {
  24691. super(manager);
  24692. this.isImageBitmapLoader = true;
  24693. if (typeof createImageBitmap === 'undefined') {
  24694. console.warn('THREE.ImageBitmapLoader: createImageBitmap() not supported.');
  24695. }
  24696. if (typeof fetch === 'undefined') {
  24697. console.warn('THREE.ImageBitmapLoader: fetch() not supported.');
  24698. }
  24699. this.options = {
  24700. premultiplyAlpha: 'none'
  24701. };
  24702. }
  24703. setOptions(options) {
  24704. this.options = options;
  24705. return this;
  24706. }
  24707. load(url, onLoad, onProgress, onError) {
  24708. if (url === undefined) url = '';
  24709. if (this.path !== undefined) url = this.path + url;
  24710. url = this.manager.resolveURL(url);
  24711. const scope = this;
  24712. const cached = Cache.get(url);
  24713. if (cached !== undefined) {
  24714. scope.manager.itemStart(url);
  24715. setTimeout(function () {
  24716. if (onLoad) onLoad(cached);
  24717. scope.manager.itemEnd(url);
  24718. }, 0);
  24719. return cached;
  24720. }
  24721. const fetchOptions = {};
  24722. fetchOptions.credentials = this.crossOrigin === 'anonymous' ? 'same-origin' : 'include';
  24723. fetchOptions.headers = this.requestHeader;
  24724. fetch(url, fetchOptions).then(function (res) {
  24725. return res.blob();
  24726. }).then(function (blob) {
  24727. return createImageBitmap(blob, Object.assign(scope.options, {
  24728. colorSpaceConversion: 'none'
  24729. }));
  24730. }).then(function (imageBitmap) {
  24731. Cache.add(url, imageBitmap);
  24732. if (onLoad) onLoad(imageBitmap);
  24733. scope.manager.itemEnd(url);
  24734. }).catch(function (e) {
  24735. if (onError) onError(e);
  24736. scope.manager.itemError(url);
  24737. scope.manager.itemEnd(url);
  24738. });
  24739. scope.manager.itemStart(url);
  24740. }
  24741. }
  24742. let _context;
  24743. const AudioContext = {
  24744. getContext: function () {
  24745. if (_context === undefined) {
  24746. _context = new (window.AudioContext || window.webkitAudioContext)();
  24747. }
  24748. return _context;
  24749. },
  24750. setContext: function (value) {
  24751. _context = value;
  24752. }
  24753. };
  24754. class AudioLoader extends Loader {
  24755. constructor(manager) {
  24756. super(manager);
  24757. }
  24758. load(url, onLoad, onProgress, onError) {
  24759. const scope = this;
  24760. const loader = new FileLoader(this.manager);
  24761. loader.setResponseType('arraybuffer');
  24762. loader.setPath(this.path);
  24763. loader.setRequestHeader(this.requestHeader);
  24764. loader.setWithCredentials(this.withCredentials);
  24765. loader.load(url, function (buffer) {
  24766. try {
  24767. // Create a copy of the buffer. The `decodeAudioData` method
  24768. // detaches the buffer when complete, preventing reuse.
  24769. const bufferCopy = buffer.slice(0);
  24770. const context = AudioContext.getContext();
  24771. context.decodeAudioData(bufferCopy, function (audioBuffer) {
  24772. onLoad(audioBuffer);
  24773. });
  24774. } catch (e) {
  24775. if (onError) {
  24776. onError(e);
  24777. } else {
  24778. console.error(e);
  24779. }
  24780. scope.manager.itemError(url);
  24781. }
  24782. }, onProgress, onError);
  24783. }
  24784. }
  24785. class HemisphereLightProbe extends LightProbe {
  24786. constructor(skyColor, groundColor, intensity = 1) {
  24787. super(undefined, intensity);
  24788. this.isHemisphereLightProbe = true;
  24789. const color1 = new Color().set(skyColor);
  24790. const color2 = new Color().set(groundColor);
  24791. const sky = new Vector3(color1.r, color1.g, color1.b);
  24792. const ground = new Vector3(color2.r, color2.g, color2.b); // without extra factor of PI in the shader, should = 1 / Math.sqrt( Math.PI );
  24793. const c0 = Math.sqrt(Math.PI);
  24794. const c1 = c0 * Math.sqrt(0.75);
  24795. this.sh.coefficients[0].copy(sky).add(ground).multiplyScalar(c0);
  24796. this.sh.coefficients[1].copy(sky).sub(ground).multiplyScalar(c1);
  24797. }
  24798. }
  24799. class AmbientLightProbe extends LightProbe {
  24800. constructor(color, intensity = 1) {
  24801. super(undefined, intensity);
  24802. this.isAmbientLightProbe = true;
  24803. const color1 = new Color().set(color); // without extra factor of PI in the shader, would be 2 / Math.sqrt( Math.PI );
  24804. this.sh.coefficients[0].set(color1.r, color1.g, color1.b).multiplyScalar(2 * Math.sqrt(Math.PI));
  24805. }
  24806. }
  24807. const _eyeRight = /*@__PURE__*/new Matrix4();
  24808. const _eyeLeft = /*@__PURE__*/new Matrix4();
  24809. const _projectionMatrix = /*@__PURE__*/new Matrix4();
  24810. class StereoCamera {
  24811. constructor() {
  24812. this.type = 'StereoCamera';
  24813. this.aspect = 1;
  24814. this.eyeSep = 0.064;
  24815. this.cameraL = new PerspectiveCamera();
  24816. this.cameraL.layers.enable(1);
  24817. this.cameraL.matrixAutoUpdate = false;
  24818. this.cameraR = new PerspectiveCamera();
  24819. this.cameraR.layers.enable(2);
  24820. this.cameraR.matrixAutoUpdate = false;
  24821. this._cache = {
  24822. focus: null,
  24823. fov: null,
  24824. aspect: null,
  24825. near: null,
  24826. far: null,
  24827. zoom: null,
  24828. eyeSep: null
  24829. };
  24830. }
  24831. update(camera) {
  24832. const cache = this._cache;
  24833. 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;
  24834. if (needsUpdate) {
  24835. cache.focus = camera.focus;
  24836. cache.fov = camera.fov;
  24837. cache.aspect = camera.aspect * this.aspect;
  24838. cache.near = camera.near;
  24839. cache.far = camera.far;
  24840. cache.zoom = camera.zoom;
  24841. cache.eyeSep = this.eyeSep; // Off-axis stereoscopic effect based on
  24842. // http://paulbourke.net/stereographics/stereorender/
  24843. _projectionMatrix.copy(camera.projectionMatrix);
  24844. const eyeSepHalf = cache.eyeSep / 2;
  24845. const eyeSepOnProjection = eyeSepHalf * cache.near / cache.focus;
  24846. const ymax = cache.near * Math.tan(DEG2RAD * cache.fov * 0.5) / cache.zoom;
  24847. let xmin, xmax; // translate xOffset
  24848. _eyeLeft.elements[12] = -eyeSepHalf;
  24849. _eyeRight.elements[12] = eyeSepHalf; // for left eye
  24850. xmin = -ymax * cache.aspect + eyeSepOnProjection;
  24851. xmax = ymax * cache.aspect + eyeSepOnProjection;
  24852. _projectionMatrix.elements[0] = 2 * cache.near / (xmax - xmin);
  24853. _projectionMatrix.elements[8] = (xmax + xmin) / (xmax - xmin);
  24854. this.cameraL.projectionMatrix.copy(_projectionMatrix); // for right eye
  24855. xmin = -ymax * cache.aspect - eyeSepOnProjection;
  24856. xmax = ymax * cache.aspect - eyeSepOnProjection;
  24857. _projectionMatrix.elements[0] = 2 * cache.near / (xmax - xmin);
  24858. _projectionMatrix.elements[8] = (xmax + xmin) / (xmax - xmin);
  24859. this.cameraR.projectionMatrix.copy(_projectionMatrix);
  24860. }
  24861. this.cameraL.matrixWorld.copy(camera.matrixWorld).multiply(_eyeLeft);
  24862. this.cameraR.matrixWorld.copy(camera.matrixWorld).multiply(_eyeRight);
  24863. }
  24864. }
  24865. class Clock {
  24866. constructor(autoStart = true) {
  24867. this.autoStart = autoStart;
  24868. this.startTime = 0;
  24869. this.oldTime = 0;
  24870. this.elapsedTime = 0;
  24871. this.running = false;
  24872. }
  24873. start() {
  24874. this.startTime = now();
  24875. this.oldTime = this.startTime;
  24876. this.elapsedTime = 0;
  24877. this.running = true;
  24878. }
  24879. stop() {
  24880. this.getElapsedTime();
  24881. this.running = false;
  24882. this.autoStart = false;
  24883. }
  24884. getElapsedTime() {
  24885. this.getDelta();
  24886. return this.elapsedTime;
  24887. }
  24888. getDelta() {
  24889. let diff = 0;
  24890. if (this.autoStart && !this.running) {
  24891. this.start();
  24892. return 0;
  24893. }
  24894. if (this.running) {
  24895. const newTime = now();
  24896. diff = (newTime - this.oldTime) / 1000;
  24897. this.oldTime = newTime;
  24898. this.elapsedTime += diff;
  24899. }
  24900. return diff;
  24901. }
  24902. }
  24903. function now() {
  24904. return (typeof performance === 'undefined' ? Date : performance).now(); // see #10732
  24905. }
  24906. const _position$1 = /*@__PURE__*/new Vector3();
  24907. const _quaternion$1 = /*@__PURE__*/new Quaternion();
  24908. const _scale$1 = /*@__PURE__*/new Vector3();
  24909. const _orientation$1 = /*@__PURE__*/new Vector3();
  24910. class AudioListener extends Object3D {
  24911. constructor() {
  24912. super();
  24913. this.type = 'AudioListener';
  24914. this.context = AudioContext.getContext();
  24915. this.gain = this.context.createGain();
  24916. this.gain.connect(this.context.destination);
  24917. this.filter = null;
  24918. this.timeDelta = 0; // private
  24919. this._clock = new Clock();
  24920. }
  24921. getInput() {
  24922. return this.gain;
  24923. }
  24924. removeFilter() {
  24925. if (this.filter !== null) {
  24926. this.gain.disconnect(this.filter);
  24927. this.filter.disconnect(this.context.destination);
  24928. this.gain.connect(this.context.destination);
  24929. this.filter = null;
  24930. }
  24931. return this;
  24932. }
  24933. getFilter() {
  24934. return this.filter;
  24935. }
  24936. setFilter(value) {
  24937. if (this.filter !== null) {
  24938. this.gain.disconnect(this.filter);
  24939. this.filter.disconnect(this.context.destination);
  24940. } else {
  24941. this.gain.disconnect(this.context.destination);
  24942. }
  24943. this.filter = value;
  24944. this.gain.connect(this.filter);
  24945. this.filter.connect(this.context.destination);
  24946. return this;
  24947. }
  24948. getMasterVolume() {
  24949. return this.gain.gain.value;
  24950. }
  24951. setMasterVolume(value) {
  24952. this.gain.gain.setTargetAtTime(value, this.context.currentTime, 0.01);
  24953. return this;
  24954. }
  24955. updateMatrixWorld(force) {
  24956. super.updateMatrixWorld(force);
  24957. const listener = this.context.listener;
  24958. const up = this.up;
  24959. this.timeDelta = this._clock.getDelta();
  24960. this.matrixWorld.decompose(_position$1, _quaternion$1, _scale$1);
  24961. _orientation$1.set(0, 0, -1).applyQuaternion(_quaternion$1);
  24962. if (listener.positionX) {
  24963. // code path for Chrome (see #14393)
  24964. const endTime = this.context.currentTime + this.timeDelta;
  24965. listener.positionX.linearRampToValueAtTime(_position$1.x, endTime);
  24966. listener.positionY.linearRampToValueAtTime(_position$1.y, endTime);
  24967. listener.positionZ.linearRampToValueAtTime(_position$1.z, endTime);
  24968. listener.forwardX.linearRampToValueAtTime(_orientation$1.x, endTime);
  24969. listener.forwardY.linearRampToValueAtTime(_orientation$1.y, endTime);
  24970. listener.forwardZ.linearRampToValueAtTime(_orientation$1.z, endTime);
  24971. listener.upX.linearRampToValueAtTime(up.x, endTime);
  24972. listener.upY.linearRampToValueAtTime(up.y, endTime);
  24973. listener.upZ.linearRampToValueAtTime(up.z, endTime);
  24974. } else {
  24975. listener.setPosition(_position$1.x, _position$1.y, _position$1.z);
  24976. listener.setOrientation(_orientation$1.x, _orientation$1.y, _orientation$1.z, up.x, up.y, up.z);
  24977. }
  24978. }
  24979. }
  24980. class Audio extends Object3D {
  24981. constructor(listener) {
  24982. super();
  24983. this.type = 'Audio';
  24984. this.listener = listener;
  24985. this.context = listener.context;
  24986. this.gain = this.context.createGain();
  24987. this.gain.connect(listener.getInput());
  24988. this.autoplay = false;
  24989. this.buffer = null;
  24990. this.detune = 0;
  24991. this.loop = false;
  24992. this.loopStart = 0;
  24993. this.loopEnd = 0;
  24994. this.offset = 0;
  24995. this.duration = undefined;
  24996. this.playbackRate = 1;
  24997. this.isPlaying = false;
  24998. this.hasPlaybackControl = true;
  24999. this.source = null;
  25000. this.sourceType = 'empty';
  25001. this._startedAt = 0;
  25002. this._progress = 0;
  25003. this._connected = false;
  25004. this.filters = [];
  25005. }
  25006. getOutput() {
  25007. return this.gain;
  25008. }
  25009. setNodeSource(audioNode) {
  25010. this.hasPlaybackControl = false;
  25011. this.sourceType = 'audioNode';
  25012. this.source = audioNode;
  25013. this.connect();
  25014. return this;
  25015. }
  25016. setMediaElementSource(mediaElement) {
  25017. this.hasPlaybackControl = false;
  25018. this.sourceType = 'mediaNode';
  25019. this.source = this.context.createMediaElementSource(mediaElement);
  25020. this.connect();
  25021. return this;
  25022. }
  25023. setMediaStreamSource(mediaStream) {
  25024. this.hasPlaybackControl = false;
  25025. this.sourceType = 'mediaStreamNode';
  25026. this.source = this.context.createMediaStreamSource(mediaStream);
  25027. this.connect();
  25028. return this;
  25029. }
  25030. setBuffer(audioBuffer) {
  25031. this.buffer = audioBuffer;
  25032. this.sourceType = 'buffer';
  25033. if (this.autoplay) this.play();
  25034. return this;
  25035. }
  25036. play(delay = 0) {
  25037. if (this.isPlaying === true) {
  25038. console.warn('THREE.Audio: Audio is already playing.');
  25039. return;
  25040. }
  25041. if (this.hasPlaybackControl === false) {
  25042. console.warn('THREE.Audio: this Audio has no playback control.');
  25043. return;
  25044. }
  25045. this._startedAt = this.context.currentTime + delay;
  25046. const source = this.context.createBufferSource();
  25047. source.buffer = this.buffer;
  25048. source.loop = this.loop;
  25049. source.loopStart = this.loopStart;
  25050. source.loopEnd = this.loopEnd;
  25051. source.onended = this.onEnded.bind(this);
  25052. source.start(this._startedAt, this._progress + this.offset, this.duration);
  25053. this.isPlaying = true;
  25054. this.source = source;
  25055. this.setDetune(this.detune);
  25056. this.setPlaybackRate(this.playbackRate);
  25057. return this.connect();
  25058. }
  25059. pause() {
  25060. if (this.hasPlaybackControl === false) {
  25061. console.warn('THREE.Audio: this Audio has no playback control.');
  25062. return;
  25063. }
  25064. if (this.isPlaying === true) {
  25065. // update current progress
  25066. this._progress += Math.max(this.context.currentTime - this._startedAt, 0) * this.playbackRate;
  25067. if (this.loop === true) {
  25068. // ensure _progress does not exceed duration with looped audios
  25069. this._progress = this._progress % (this.duration || this.buffer.duration);
  25070. }
  25071. this.source.stop();
  25072. this.source.onended = null;
  25073. this.isPlaying = false;
  25074. }
  25075. return this;
  25076. }
  25077. stop() {
  25078. if (this.hasPlaybackControl === false) {
  25079. console.warn('THREE.Audio: this Audio has no playback control.');
  25080. return;
  25081. }
  25082. this._progress = 0;
  25083. this.source.stop();
  25084. this.source.onended = null;
  25085. this.isPlaying = false;
  25086. return this;
  25087. }
  25088. connect() {
  25089. if (this.filters.length > 0) {
  25090. this.source.connect(this.filters[0]);
  25091. for (let i = 1, l = this.filters.length; i < l; i++) {
  25092. this.filters[i - 1].connect(this.filters[i]);
  25093. }
  25094. this.filters[this.filters.length - 1].connect(this.getOutput());
  25095. } else {
  25096. this.source.connect(this.getOutput());
  25097. }
  25098. this._connected = true;
  25099. return this;
  25100. }
  25101. disconnect() {
  25102. if (this.filters.length > 0) {
  25103. this.source.disconnect(this.filters[0]);
  25104. for (let i = 1, l = this.filters.length; i < l; i++) {
  25105. this.filters[i - 1].disconnect(this.filters[i]);
  25106. }
  25107. this.filters[this.filters.length - 1].disconnect(this.getOutput());
  25108. } else {
  25109. this.source.disconnect(this.getOutput());
  25110. }
  25111. this._connected = false;
  25112. return this;
  25113. }
  25114. getFilters() {
  25115. return this.filters;
  25116. }
  25117. setFilters(value) {
  25118. if (!value) value = [];
  25119. if (this._connected === true) {
  25120. this.disconnect();
  25121. this.filters = value.slice();
  25122. this.connect();
  25123. } else {
  25124. this.filters = value.slice();
  25125. }
  25126. return this;
  25127. }
  25128. setDetune(value) {
  25129. this.detune = value;
  25130. if (this.source.detune === undefined) return; // only set detune when available
  25131. if (this.isPlaying === true) {
  25132. this.source.detune.setTargetAtTime(this.detune, this.context.currentTime, 0.01);
  25133. }
  25134. return this;
  25135. }
  25136. getDetune() {
  25137. return this.detune;
  25138. }
  25139. getFilter() {
  25140. return this.getFilters()[0];
  25141. }
  25142. setFilter(filter) {
  25143. return this.setFilters(filter ? [filter] : []);
  25144. }
  25145. setPlaybackRate(value) {
  25146. if (this.hasPlaybackControl === false) {
  25147. console.warn('THREE.Audio: this Audio has no playback control.');
  25148. return;
  25149. }
  25150. this.playbackRate = value;
  25151. if (this.isPlaying === true) {
  25152. this.source.playbackRate.setTargetAtTime(this.playbackRate, this.context.currentTime, 0.01);
  25153. }
  25154. return this;
  25155. }
  25156. getPlaybackRate() {
  25157. return this.playbackRate;
  25158. }
  25159. onEnded() {
  25160. this.isPlaying = false;
  25161. }
  25162. getLoop() {
  25163. if (this.hasPlaybackControl === false) {
  25164. console.warn('THREE.Audio: this Audio has no playback control.');
  25165. return false;
  25166. }
  25167. return this.loop;
  25168. }
  25169. setLoop(value) {
  25170. if (this.hasPlaybackControl === false) {
  25171. console.warn('THREE.Audio: this Audio has no playback control.');
  25172. return;
  25173. }
  25174. this.loop = value;
  25175. if (this.isPlaying === true) {
  25176. this.source.loop = this.loop;
  25177. }
  25178. return this;
  25179. }
  25180. setLoopStart(value) {
  25181. this.loopStart = value;
  25182. return this;
  25183. }
  25184. setLoopEnd(value) {
  25185. this.loopEnd = value;
  25186. return this;
  25187. }
  25188. getVolume() {
  25189. return this.gain.gain.value;
  25190. }
  25191. setVolume(value) {
  25192. this.gain.gain.setTargetAtTime(value, this.context.currentTime, 0.01);
  25193. return this;
  25194. }
  25195. }
  25196. const _position = /*@__PURE__*/new Vector3();
  25197. const _quaternion = /*@__PURE__*/new Quaternion();
  25198. const _scale = /*@__PURE__*/new Vector3();
  25199. const _orientation = /*@__PURE__*/new Vector3();
  25200. class PositionalAudio extends Audio {
  25201. constructor(listener) {
  25202. super(listener);
  25203. this.panner = this.context.createPanner();
  25204. this.panner.panningModel = 'HRTF';
  25205. this.panner.connect(this.gain);
  25206. }
  25207. disconnect() {
  25208. super.disconnect();
  25209. this.panner.disconnect(this.gain);
  25210. }
  25211. getOutput() {
  25212. return this.panner;
  25213. }
  25214. getRefDistance() {
  25215. return this.panner.refDistance;
  25216. }
  25217. setRefDistance(value) {
  25218. this.panner.refDistance = value;
  25219. return this;
  25220. }
  25221. getRolloffFactor() {
  25222. return this.panner.rolloffFactor;
  25223. }
  25224. setRolloffFactor(value) {
  25225. this.panner.rolloffFactor = value;
  25226. return this;
  25227. }
  25228. getDistanceModel() {
  25229. return this.panner.distanceModel;
  25230. }
  25231. setDistanceModel(value) {
  25232. this.panner.distanceModel = value;
  25233. return this;
  25234. }
  25235. getMaxDistance() {
  25236. return this.panner.maxDistance;
  25237. }
  25238. setMaxDistance(value) {
  25239. this.panner.maxDistance = value;
  25240. return this;
  25241. }
  25242. setDirectionalCone(coneInnerAngle, coneOuterAngle, coneOuterGain) {
  25243. this.panner.coneInnerAngle = coneInnerAngle;
  25244. this.panner.coneOuterAngle = coneOuterAngle;
  25245. this.panner.coneOuterGain = coneOuterGain;
  25246. return this;
  25247. }
  25248. updateMatrixWorld(force) {
  25249. super.updateMatrixWorld(force);
  25250. if (this.hasPlaybackControl === true && this.isPlaying === false) return;
  25251. this.matrixWorld.decompose(_position, _quaternion, _scale);
  25252. _orientation.set(0, 0, 1).applyQuaternion(_quaternion);
  25253. const panner = this.panner;
  25254. if (panner.positionX) {
  25255. // code path for Chrome and Firefox (see #14393)
  25256. const endTime = this.context.currentTime + this.listener.timeDelta;
  25257. panner.positionX.linearRampToValueAtTime(_position.x, endTime);
  25258. panner.positionY.linearRampToValueAtTime(_position.y, endTime);
  25259. panner.positionZ.linearRampToValueAtTime(_position.z, endTime);
  25260. panner.orientationX.linearRampToValueAtTime(_orientation.x, endTime);
  25261. panner.orientationY.linearRampToValueAtTime(_orientation.y, endTime);
  25262. panner.orientationZ.linearRampToValueAtTime(_orientation.z, endTime);
  25263. } else {
  25264. panner.setPosition(_position.x, _position.y, _position.z);
  25265. panner.setOrientation(_orientation.x, _orientation.y, _orientation.z);
  25266. }
  25267. }
  25268. }
  25269. class AudioAnalyser {
  25270. constructor(audio, fftSize = 2048) {
  25271. this.analyser = audio.context.createAnalyser();
  25272. this.analyser.fftSize = fftSize;
  25273. this.data = new Uint8Array(this.analyser.frequencyBinCount);
  25274. audio.getOutput().connect(this.analyser);
  25275. }
  25276. getFrequencyData() {
  25277. this.analyser.getByteFrequencyData(this.data);
  25278. return this.data;
  25279. }
  25280. getAverageFrequency() {
  25281. let value = 0;
  25282. const data = this.getFrequencyData();
  25283. for (let i = 0; i < data.length; i++) {
  25284. value += data[i];
  25285. }
  25286. return value / data.length;
  25287. }
  25288. }
  25289. class PropertyMixer {
  25290. constructor(binding, typeName, valueSize) {
  25291. this.binding = binding;
  25292. this.valueSize = valueSize;
  25293. let mixFunction, mixFunctionAdditive, setIdentity; // buffer layout: [ incoming | accu0 | accu1 | orig | addAccu | (optional work) ]
  25294. //
  25295. // interpolators can use .buffer as their .result
  25296. // the data then goes to 'incoming'
  25297. //
  25298. // 'accu0' and 'accu1' are used frame-interleaved for
  25299. // the cumulative result and are compared to detect
  25300. // changes
  25301. //
  25302. // 'orig' stores the original state of the property
  25303. //
  25304. // 'add' is used for additive cumulative results
  25305. //
  25306. // 'work' is optional and is only present for quaternion types. It is used
  25307. // to store intermediate quaternion multiplication results
  25308. switch (typeName) {
  25309. case 'quaternion':
  25310. mixFunction = this._slerp;
  25311. mixFunctionAdditive = this._slerpAdditive;
  25312. setIdentity = this._setAdditiveIdentityQuaternion;
  25313. this.buffer = new Float64Array(valueSize * 6);
  25314. this._workIndex = 5;
  25315. break;
  25316. case 'string':
  25317. case 'bool':
  25318. mixFunction = this._select; // Use the regular mix function and for additive on these types,
  25319. // additive is not relevant for non-numeric types
  25320. mixFunctionAdditive = this._select;
  25321. setIdentity = this._setAdditiveIdentityOther;
  25322. this.buffer = new Array(valueSize * 5);
  25323. break;
  25324. default:
  25325. mixFunction = this._lerp;
  25326. mixFunctionAdditive = this._lerpAdditive;
  25327. setIdentity = this._setAdditiveIdentityNumeric;
  25328. this.buffer = new Float64Array(valueSize * 5);
  25329. }
  25330. this._mixBufferRegion = mixFunction;
  25331. this._mixBufferRegionAdditive = mixFunctionAdditive;
  25332. this._setIdentity = setIdentity;
  25333. this._origIndex = 3;
  25334. this._addIndex = 4;
  25335. this.cumulativeWeight = 0;
  25336. this.cumulativeWeightAdditive = 0;
  25337. this.useCount = 0;
  25338. this.referenceCount = 0;
  25339. } // accumulate data in the 'incoming' region into 'accu<i>'
  25340. accumulate(accuIndex, weight) {
  25341. // note: happily accumulating nothing when weight = 0, the caller knows
  25342. // the weight and shouldn't have made the call in the first place
  25343. const buffer = this.buffer,
  25344. stride = this.valueSize,
  25345. offset = accuIndex * stride + stride;
  25346. let currentWeight = this.cumulativeWeight;
  25347. if (currentWeight === 0) {
  25348. // accuN := incoming * weight
  25349. for (let i = 0; i !== stride; ++i) {
  25350. buffer[offset + i] = buffer[i];
  25351. }
  25352. currentWeight = weight;
  25353. } else {
  25354. // accuN := accuN + incoming * weight
  25355. currentWeight += weight;
  25356. const mix = weight / currentWeight;
  25357. this._mixBufferRegion(buffer, offset, 0, mix, stride);
  25358. }
  25359. this.cumulativeWeight = currentWeight;
  25360. } // accumulate data in the 'incoming' region into 'add'
  25361. accumulateAdditive(weight) {
  25362. const buffer = this.buffer,
  25363. stride = this.valueSize,
  25364. offset = stride * this._addIndex;
  25365. if (this.cumulativeWeightAdditive === 0) {
  25366. // add = identity
  25367. this._setIdentity();
  25368. } // add := add + incoming * weight
  25369. this._mixBufferRegionAdditive(buffer, offset, 0, weight, stride);
  25370. this.cumulativeWeightAdditive += weight;
  25371. } // apply the state of 'accu<i>' to the binding when accus differ
  25372. apply(accuIndex) {
  25373. const stride = this.valueSize,
  25374. buffer = this.buffer,
  25375. offset = accuIndex * stride + stride,
  25376. weight = this.cumulativeWeight,
  25377. weightAdditive = this.cumulativeWeightAdditive,
  25378. binding = this.binding;
  25379. this.cumulativeWeight = 0;
  25380. this.cumulativeWeightAdditive = 0;
  25381. if (weight < 1) {
  25382. // accuN := accuN + original * ( 1 - cumulativeWeight )
  25383. const originalValueOffset = stride * this._origIndex;
  25384. this._mixBufferRegion(buffer, offset, originalValueOffset, 1 - weight, stride);
  25385. }
  25386. if (weightAdditive > 0) {
  25387. // accuN := accuN + additive accuN
  25388. this._mixBufferRegionAdditive(buffer, offset, this._addIndex * stride, 1, stride);
  25389. }
  25390. for (let i = stride, e = stride + stride; i !== e; ++i) {
  25391. if (buffer[i] !== buffer[i + stride]) {
  25392. // value has changed -> update scene graph
  25393. binding.setValue(buffer, offset);
  25394. break;
  25395. }
  25396. }
  25397. } // remember the state of the bound property and copy it to both accus
  25398. saveOriginalState() {
  25399. const binding = this.binding;
  25400. const buffer = this.buffer,
  25401. stride = this.valueSize,
  25402. originalValueOffset = stride * this._origIndex;
  25403. binding.getValue(buffer, originalValueOffset); // accu[0..1] := orig -- initially detect changes against the original
  25404. for (let i = stride, e = originalValueOffset; i !== e; ++i) {
  25405. buffer[i] = buffer[originalValueOffset + i % stride];
  25406. } // Add to identity for additive
  25407. this._setIdentity();
  25408. this.cumulativeWeight = 0;
  25409. this.cumulativeWeightAdditive = 0;
  25410. } // apply the state previously taken via 'saveOriginalState' to the binding
  25411. restoreOriginalState() {
  25412. const originalValueOffset = this.valueSize * 3;
  25413. this.binding.setValue(this.buffer, originalValueOffset);
  25414. }
  25415. _setAdditiveIdentityNumeric() {
  25416. const startIndex = this._addIndex * this.valueSize;
  25417. const endIndex = startIndex + this.valueSize;
  25418. for (let i = startIndex; i < endIndex; i++) {
  25419. this.buffer[i] = 0;
  25420. }
  25421. }
  25422. _setAdditiveIdentityQuaternion() {
  25423. this._setAdditiveIdentityNumeric();
  25424. this.buffer[this._addIndex * this.valueSize + 3] = 1;
  25425. }
  25426. _setAdditiveIdentityOther() {
  25427. const startIndex = this._origIndex * this.valueSize;
  25428. const targetIndex = this._addIndex * this.valueSize;
  25429. for (let i = 0; i < this.valueSize; i++) {
  25430. this.buffer[targetIndex + i] = this.buffer[startIndex + i];
  25431. }
  25432. } // mix functions
  25433. _select(buffer, dstOffset, srcOffset, t, stride) {
  25434. if (t >= 0.5) {
  25435. for (let i = 0; i !== stride; ++i) {
  25436. buffer[dstOffset + i] = buffer[srcOffset + i];
  25437. }
  25438. }
  25439. }
  25440. _slerp(buffer, dstOffset, srcOffset, t) {
  25441. Quaternion.slerpFlat(buffer, dstOffset, buffer, dstOffset, buffer, srcOffset, t);
  25442. }
  25443. _slerpAdditive(buffer, dstOffset, srcOffset, t, stride) {
  25444. const workOffset = this._workIndex * stride; // Store result in intermediate buffer offset
  25445. Quaternion.multiplyQuaternionsFlat(buffer, workOffset, buffer, dstOffset, buffer, srcOffset); // Slerp to the intermediate result
  25446. Quaternion.slerpFlat(buffer, dstOffset, buffer, dstOffset, buffer, workOffset, t);
  25447. }
  25448. _lerp(buffer, dstOffset, srcOffset, t, stride) {
  25449. const s = 1 - t;
  25450. for (let i = 0; i !== stride; ++i) {
  25451. const j = dstOffset + i;
  25452. buffer[j] = buffer[j] * s + buffer[srcOffset + i] * t;
  25453. }
  25454. }
  25455. _lerpAdditive(buffer, dstOffset, srcOffset, t, stride) {
  25456. for (let i = 0; i !== stride; ++i) {
  25457. const j = dstOffset + i;
  25458. buffer[j] = buffer[j] + buffer[srcOffset + i] * t;
  25459. }
  25460. }
  25461. }
  25462. // Characters [].:/ are reserved for track binding syntax.
  25463. const _RESERVED_CHARS_RE = '\\[\\]\\.:\\/';
  25464. const _reservedRe = new RegExp('[' + _RESERVED_CHARS_RE + ']', 'g'); // Attempts to allow node names from any language. ES5's `\w` regexp matches
  25465. // only latin characters, and the unicode \p{L} is not yet supported. So
  25466. // instead, we exclude reserved characters and match everything else.
  25467. const _wordChar = '[^' + _RESERVED_CHARS_RE + ']';
  25468. const _wordCharOrDot = '[^' + _RESERVED_CHARS_RE.replace('\\.', '') + ']'; // Parent directories, delimited by '/' or ':'. Currently unused, but must
  25469. // be matched to parse the rest of the track name.
  25470. const _directoryRe = /((?:WC+[\/:])*)/.source.replace('WC', _wordChar); // Target node. May contain word characters (a-zA-Z0-9_) and '.' or '-'.
  25471. const _nodeRe = /(WCOD+)?/.source.replace('WCOD', _wordCharOrDot); // Object on target node, and accessor. May not contain reserved
  25472. // characters. Accessor may contain any character except closing bracket.
  25473. const _objectRe = /(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace('WC', _wordChar); // Property and accessor. May not contain reserved characters. Accessor may
  25474. // contain any non-bracket characters.
  25475. const _propertyRe = /\.(WC+)(?:\[(.+)\])?/.source.replace('WC', _wordChar);
  25476. const _trackRe = new RegExp('' + '^' + _directoryRe + _nodeRe + _objectRe + _propertyRe + '$');
  25477. const _supportedObjectNames = ['material', 'materials', 'bones'];
  25478. class Composite {
  25479. constructor(targetGroup, path, optionalParsedPath) {
  25480. const parsedPath = optionalParsedPath || PropertyBinding.parseTrackName(path);
  25481. this._targetGroup = targetGroup;
  25482. this._bindings = targetGroup.subscribe_(path, parsedPath);
  25483. }
  25484. getValue(array, offset) {
  25485. this.bind(); // bind all binding
  25486. const firstValidIndex = this._targetGroup.nCachedObjects_,
  25487. binding = this._bindings[firstValidIndex]; // and only call .getValue on the first
  25488. if (binding !== undefined) binding.getValue(array, offset);
  25489. }
  25490. setValue(array, offset) {
  25491. const bindings = this._bindings;
  25492. for (let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++i) {
  25493. bindings[i].setValue(array, offset);
  25494. }
  25495. }
  25496. bind() {
  25497. const bindings = this._bindings;
  25498. for (let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++i) {
  25499. bindings[i].bind();
  25500. }
  25501. }
  25502. unbind() {
  25503. const bindings = this._bindings;
  25504. for (let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++i) {
  25505. bindings[i].unbind();
  25506. }
  25507. }
  25508. } // Note: This class uses a State pattern on a per-method basis:
  25509. // 'bind' sets 'this.getValue' / 'setValue' and shadows the
  25510. // prototype version of these methods with one that represents
  25511. // the bound state. When the property is not found, the methods
  25512. // become no-ops.
  25513. class PropertyBinding {
  25514. constructor(rootNode, path, parsedPath) {
  25515. this.path = path;
  25516. this.parsedPath = parsedPath || PropertyBinding.parseTrackName(path);
  25517. this.node = PropertyBinding.findNode(rootNode, this.parsedPath.nodeName) || rootNode;
  25518. this.rootNode = rootNode; // initial state of these methods that calls 'bind'
  25519. this.getValue = this._getValue_unbound;
  25520. this.setValue = this._setValue_unbound;
  25521. }
  25522. static create(root, path, parsedPath) {
  25523. if (!(root && root.isAnimationObjectGroup)) {
  25524. return new PropertyBinding(root, path, parsedPath);
  25525. } else {
  25526. return new PropertyBinding.Composite(root, path, parsedPath);
  25527. }
  25528. }
  25529. /**
  25530. * Replaces spaces with underscores and removes unsupported characters from
  25531. * node names, to ensure compatibility with parseTrackName().
  25532. *
  25533. * @param {string} name Node name to be sanitized.
  25534. * @return {string}
  25535. */
  25536. static sanitizeNodeName(name) {
  25537. return name.replace(/\s/g, '_').replace(_reservedRe, '');
  25538. }
  25539. static parseTrackName(trackName) {
  25540. const matches = _trackRe.exec(trackName);
  25541. if (matches === null) {
  25542. throw new Error('PropertyBinding: Cannot parse trackName: ' + trackName);
  25543. }
  25544. const results = {
  25545. // directoryName: matches[ 1 ], // (tschw) currently unused
  25546. nodeName: matches[2],
  25547. objectName: matches[3],
  25548. objectIndex: matches[4],
  25549. propertyName: matches[5],
  25550. // required
  25551. propertyIndex: matches[6]
  25552. };
  25553. const lastDot = results.nodeName && results.nodeName.lastIndexOf('.');
  25554. if (lastDot !== undefined && lastDot !== -1) {
  25555. const objectName = results.nodeName.substring(lastDot + 1); // Object names must be checked against an allowlist. Otherwise, there
  25556. // is no way to parse 'foo.bar.baz': 'baz' must be a property, but
  25557. // 'bar' could be the objectName, or part of a nodeName (which can
  25558. // include '.' characters).
  25559. if (_supportedObjectNames.indexOf(objectName) !== -1) {
  25560. results.nodeName = results.nodeName.substring(0, lastDot);
  25561. results.objectName = objectName;
  25562. }
  25563. }
  25564. if (results.propertyName === null || results.propertyName.length === 0) {
  25565. throw new Error('PropertyBinding: can not parse propertyName from trackName: ' + trackName);
  25566. }
  25567. return results;
  25568. }
  25569. static findNode(root, nodeName) {
  25570. if (nodeName === undefined || nodeName === '' || nodeName === '.' || nodeName === -1 || nodeName === root.name || nodeName === root.uuid) {
  25571. return root;
  25572. } // search into skeleton bones.
  25573. if (root.skeleton) {
  25574. const bone = root.skeleton.getBoneByName(nodeName);
  25575. if (bone !== undefined) {
  25576. return bone;
  25577. }
  25578. } // search into node subtree.
  25579. if (root.children) {
  25580. const searchNodeSubtree = function (children) {
  25581. for (let i = 0; i < children.length; i++) {
  25582. const childNode = children[i];
  25583. if (childNode.name === nodeName || childNode.uuid === nodeName) {
  25584. return childNode;
  25585. }
  25586. const result = searchNodeSubtree(childNode.children);
  25587. if (result) return result;
  25588. }
  25589. return null;
  25590. };
  25591. const subTreeNode = searchNodeSubtree(root.children);
  25592. if (subTreeNode) {
  25593. return subTreeNode;
  25594. }
  25595. }
  25596. return null;
  25597. } // these are used to "bind" a nonexistent property
  25598. _getValue_unavailable() {}
  25599. _setValue_unavailable() {} // Getters
  25600. _getValue_direct(buffer, offset) {
  25601. buffer[offset] = this.targetObject[this.propertyName];
  25602. }
  25603. _getValue_array(buffer, offset) {
  25604. const source = this.resolvedProperty;
  25605. for (let i = 0, n = source.length; i !== n; ++i) {
  25606. buffer[offset++] = source[i];
  25607. }
  25608. }
  25609. _getValue_arrayElement(buffer, offset) {
  25610. buffer[offset] = this.resolvedProperty[this.propertyIndex];
  25611. }
  25612. _getValue_toArray(buffer, offset) {
  25613. this.resolvedProperty.toArray(buffer, offset);
  25614. } // Direct
  25615. _setValue_direct(buffer, offset) {
  25616. this.targetObject[this.propertyName] = buffer[offset];
  25617. }
  25618. _setValue_direct_setNeedsUpdate(buffer, offset) {
  25619. this.targetObject[this.propertyName] = buffer[offset];
  25620. this.targetObject.needsUpdate = true;
  25621. }
  25622. _setValue_direct_setMatrixWorldNeedsUpdate(buffer, offset) {
  25623. this.targetObject[this.propertyName] = buffer[offset];
  25624. this.targetObject.matrixWorldNeedsUpdate = true;
  25625. } // EntireArray
  25626. _setValue_array(buffer, offset) {
  25627. const dest = this.resolvedProperty;
  25628. for (let i = 0, n = dest.length; i !== n; ++i) {
  25629. dest[i] = buffer[offset++];
  25630. }
  25631. }
  25632. _setValue_array_setNeedsUpdate(buffer, offset) {
  25633. const dest = this.resolvedProperty;
  25634. for (let i = 0, n = dest.length; i !== n; ++i) {
  25635. dest[i] = buffer[offset++];
  25636. }
  25637. this.targetObject.needsUpdate = true;
  25638. }
  25639. _setValue_array_setMatrixWorldNeedsUpdate(buffer, offset) {
  25640. const dest = this.resolvedProperty;
  25641. for (let i = 0, n = dest.length; i !== n; ++i) {
  25642. dest[i] = buffer[offset++];
  25643. }
  25644. this.targetObject.matrixWorldNeedsUpdate = true;
  25645. } // ArrayElement
  25646. _setValue_arrayElement(buffer, offset) {
  25647. this.resolvedProperty[this.propertyIndex] = buffer[offset];
  25648. }
  25649. _setValue_arrayElement_setNeedsUpdate(buffer, offset) {
  25650. this.resolvedProperty[this.propertyIndex] = buffer[offset];
  25651. this.targetObject.needsUpdate = true;
  25652. }
  25653. _setValue_arrayElement_setMatrixWorldNeedsUpdate(buffer, offset) {
  25654. this.resolvedProperty[this.propertyIndex] = buffer[offset];
  25655. this.targetObject.matrixWorldNeedsUpdate = true;
  25656. } // HasToFromArray
  25657. _setValue_fromArray(buffer, offset) {
  25658. this.resolvedProperty.fromArray(buffer, offset);
  25659. }
  25660. _setValue_fromArray_setNeedsUpdate(buffer, offset) {
  25661. this.resolvedProperty.fromArray(buffer, offset);
  25662. this.targetObject.needsUpdate = true;
  25663. }
  25664. _setValue_fromArray_setMatrixWorldNeedsUpdate(buffer, offset) {
  25665. this.resolvedProperty.fromArray(buffer, offset);
  25666. this.targetObject.matrixWorldNeedsUpdate = true;
  25667. }
  25668. _getValue_unbound(targetArray, offset) {
  25669. this.bind();
  25670. this.getValue(targetArray, offset);
  25671. }
  25672. _setValue_unbound(sourceArray, offset) {
  25673. this.bind();
  25674. this.setValue(sourceArray, offset);
  25675. } // create getter / setter pair for a property in the scene graph
  25676. bind() {
  25677. let targetObject = this.node;
  25678. const parsedPath = this.parsedPath;
  25679. const objectName = parsedPath.objectName;
  25680. const propertyName = parsedPath.propertyName;
  25681. let propertyIndex = parsedPath.propertyIndex;
  25682. if (!targetObject) {
  25683. targetObject = PropertyBinding.findNode(this.rootNode, parsedPath.nodeName) || this.rootNode;
  25684. this.node = targetObject;
  25685. } // set fail state so we can just 'return' on error
  25686. this.getValue = this._getValue_unavailable;
  25687. this.setValue = this._setValue_unavailable; // ensure there is a value node
  25688. if (!targetObject) {
  25689. console.error('THREE.PropertyBinding: Trying to update node for track: ' + this.path + ' but it wasn\'t found.');
  25690. return;
  25691. }
  25692. if (objectName) {
  25693. let objectIndex = parsedPath.objectIndex; // special cases were we need to reach deeper into the hierarchy to get the face materials....
  25694. switch (objectName) {
  25695. case 'materials':
  25696. if (!targetObject.material) {
  25697. console.error('THREE.PropertyBinding: Can not bind to material as node does not have a material.', this);
  25698. return;
  25699. }
  25700. if (!targetObject.material.materials) {
  25701. console.error('THREE.PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.', this);
  25702. return;
  25703. }
  25704. targetObject = targetObject.material.materials;
  25705. break;
  25706. case 'bones':
  25707. if (!targetObject.skeleton) {
  25708. console.error('THREE.PropertyBinding: Can not bind to bones as node does not have a skeleton.', this);
  25709. return;
  25710. } // potential future optimization: skip this if propertyIndex is already an integer
  25711. // and convert the integer string to a true integer.
  25712. targetObject = targetObject.skeleton.bones; // support resolving morphTarget names into indices.
  25713. for (let i = 0; i < targetObject.length; i++) {
  25714. if (targetObject[i].name === objectIndex) {
  25715. objectIndex = i;
  25716. break;
  25717. }
  25718. }
  25719. break;
  25720. default:
  25721. if (targetObject[objectName] === undefined) {
  25722. console.error('THREE.PropertyBinding: Can not bind to objectName of node undefined.', this);
  25723. return;
  25724. }
  25725. targetObject = targetObject[objectName];
  25726. }
  25727. if (objectIndex !== undefined) {
  25728. if (targetObject[objectIndex] === undefined) {
  25729. console.error('THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.', this, targetObject);
  25730. return;
  25731. }
  25732. targetObject = targetObject[objectIndex];
  25733. }
  25734. } // resolve property
  25735. const nodeProperty = targetObject[propertyName];
  25736. if (nodeProperty === undefined) {
  25737. const nodeName = parsedPath.nodeName;
  25738. console.error('THREE.PropertyBinding: Trying to update property for track: ' + nodeName + '.' + propertyName + ' but it wasn\'t found.', targetObject);
  25739. return;
  25740. } // determine versioning scheme
  25741. let versioning = this.Versioning.None;
  25742. this.targetObject = targetObject;
  25743. if (targetObject.needsUpdate !== undefined) {
  25744. // material
  25745. versioning = this.Versioning.NeedsUpdate;
  25746. } else if (targetObject.matrixWorldNeedsUpdate !== undefined) {
  25747. // node transform
  25748. versioning = this.Versioning.MatrixWorldNeedsUpdate;
  25749. } // determine how the property gets bound
  25750. let bindingType = this.BindingType.Direct;
  25751. if (propertyIndex !== undefined) {
  25752. // access a sub element of the property array (only primitives are supported right now)
  25753. if (propertyName === 'morphTargetInfluences') {
  25754. // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer.
  25755. // support resolving morphTarget names into indices.
  25756. if (!targetObject.geometry) {
  25757. console.error('THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.', this);
  25758. return;
  25759. }
  25760. if (targetObject.geometry.isBufferGeometry) {
  25761. if (!targetObject.geometry.morphAttributes) {
  25762. console.error('THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.', this);
  25763. return;
  25764. }
  25765. if (targetObject.morphTargetDictionary[propertyIndex] !== undefined) {
  25766. propertyIndex = targetObject.morphTargetDictionary[propertyIndex];
  25767. }
  25768. } else {
  25769. console.error('THREE.PropertyBinding: Can not bind to morphTargetInfluences on THREE.Geometry. Use THREE.BufferGeometry instead.', this);
  25770. return;
  25771. }
  25772. }
  25773. bindingType = this.BindingType.ArrayElement;
  25774. this.resolvedProperty = nodeProperty;
  25775. this.propertyIndex = propertyIndex;
  25776. } else if (nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined) {
  25777. // must use copy for Object3D.Euler/Quaternion
  25778. bindingType = this.BindingType.HasFromToArray;
  25779. this.resolvedProperty = nodeProperty;
  25780. } else if (Array.isArray(nodeProperty)) {
  25781. bindingType = this.BindingType.EntireArray;
  25782. this.resolvedProperty = nodeProperty;
  25783. } else {
  25784. this.propertyName = propertyName;
  25785. } // select getter / setter
  25786. this.getValue = this.GetterByBindingType[bindingType];
  25787. this.setValue = this.SetterByBindingTypeAndVersioning[bindingType][versioning];
  25788. }
  25789. unbind() {
  25790. this.node = null; // back to the prototype version of getValue / setValue
  25791. // note: avoiding to mutate the shape of 'this' via 'delete'
  25792. this.getValue = this._getValue_unbound;
  25793. this.setValue = this._setValue_unbound;
  25794. }
  25795. }
  25796. PropertyBinding.Composite = Composite;
  25797. PropertyBinding.prototype.BindingType = {
  25798. Direct: 0,
  25799. EntireArray: 1,
  25800. ArrayElement: 2,
  25801. HasFromToArray: 3
  25802. };
  25803. PropertyBinding.prototype.Versioning = {
  25804. None: 0,
  25805. NeedsUpdate: 1,
  25806. MatrixWorldNeedsUpdate: 2
  25807. };
  25808. PropertyBinding.prototype.GetterByBindingType = [PropertyBinding.prototype._getValue_direct, PropertyBinding.prototype._getValue_array, PropertyBinding.prototype._getValue_arrayElement, PropertyBinding.prototype._getValue_toArray];
  25809. PropertyBinding.prototype.SetterByBindingTypeAndVersioning = [[// Direct
  25810. PropertyBinding.prototype._setValue_direct, PropertyBinding.prototype._setValue_direct_setNeedsUpdate, PropertyBinding.prototype._setValue_direct_setMatrixWorldNeedsUpdate], [// EntireArray
  25811. PropertyBinding.prototype._setValue_array, PropertyBinding.prototype._setValue_array_setNeedsUpdate, PropertyBinding.prototype._setValue_array_setMatrixWorldNeedsUpdate], [// ArrayElement
  25812. PropertyBinding.prototype._setValue_arrayElement, PropertyBinding.prototype._setValue_arrayElement_setNeedsUpdate, PropertyBinding.prototype._setValue_arrayElement_setMatrixWorldNeedsUpdate], [// HasToFromArray
  25813. PropertyBinding.prototype._setValue_fromArray, PropertyBinding.prototype._setValue_fromArray_setNeedsUpdate, PropertyBinding.prototype._setValue_fromArray_setMatrixWorldNeedsUpdate]];
  25814. /**
  25815. *
  25816. * A group of objects that receives a shared animation state.
  25817. *
  25818. * Usage:
  25819. *
  25820. * - Add objects you would otherwise pass as 'root' to the
  25821. * constructor or the .clipAction method of AnimationMixer.
  25822. *
  25823. * - Instead pass this object as 'root'.
  25824. *
  25825. * - You can also add and remove objects later when the mixer
  25826. * is running.
  25827. *
  25828. * Note:
  25829. *
  25830. * Objects of this class appear as one object to the mixer,
  25831. * so cache control of the individual objects must be done
  25832. * on the group.
  25833. *
  25834. * Limitation:
  25835. *
  25836. * - The animated properties must be compatible among the
  25837. * all objects in the group.
  25838. *
  25839. * - A single property can either be controlled through a
  25840. * target group or directly, but not both.
  25841. */
  25842. class AnimationObjectGroup {
  25843. constructor() {
  25844. this.isAnimationObjectGroup = true;
  25845. this.uuid = generateUUID(); // cached objects followed by the active ones
  25846. this._objects = Array.prototype.slice.call(arguments);
  25847. this.nCachedObjects_ = 0; // threshold
  25848. // note: read by PropertyBinding.Composite
  25849. const indices = {};
  25850. this._indicesByUUID = indices; // for bookkeeping
  25851. for (let i = 0, n = arguments.length; i !== n; ++i) {
  25852. indices[arguments[i].uuid] = i;
  25853. }
  25854. this._paths = []; // inside: string
  25855. this._parsedPaths = []; // inside: { we don't care, here }
  25856. this._bindings = []; // inside: Array< PropertyBinding >
  25857. this._bindingsIndicesByPath = {}; // inside: indices in these arrays
  25858. const scope = this;
  25859. this.stats = {
  25860. objects: {
  25861. get total() {
  25862. return scope._objects.length;
  25863. },
  25864. get inUse() {
  25865. return this.total - scope.nCachedObjects_;
  25866. }
  25867. },
  25868. get bindingsPerObject() {
  25869. return scope._bindings.length;
  25870. }
  25871. };
  25872. }
  25873. add() {
  25874. const objects = this._objects,
  25875. indicesByUUID = this._indicesByUUID,
  25876. paths = this._paths,
  25877. parsedPaths = this._parsedPaths,
  25878. bindings = this._bindings,
  25879. nBindings = bindings.length;
  25880. let knownObject = undefined,
  25881. nObjects = objects.length,
  25882. nCachedObjects = this.nCachedObjects_;
  25883. for (let i = 0, n = arguments.length; i !== n; ++i) {
  25884. const object = arguments[i],
  25885. uuid = object.uuid;
  25886. let index = indicesByUUID[uuid];
  25887. if (index === undefined) {
  25888. // unknown object -> add it to the ACTIVE region
  25889. index = nObjects++;
  25890. indicesByUUID[uuid] = index;
  25891. objects.push(object); // accounting is done, now do the same for all bindings
  25892. for (let j = 0, m = nBindings; j !== m; ++j) {
  25893. bindings[j].push(new PropertyBinding(object, paths[j], parsedPaths[j]));
  25894. }
  25895. } else if (index < nCachedObjects) {
  25896. knownObject = objects[index]; // move existing object to the ACTIVE region
  25897. const firstActiveIndex = --nCachedObjects,
  25898. lastCachedObject = objects[firstActiveIndex];
  25899. indicesByUUID[lastCachedObject.uuid] = index;
  25900. objects[index] = lastCachedObject;
  25901. indicesByUUID[uuid] = firstActiveIndex;
  25902. objects[firstActiveIndex] = object; // accounting is done, now do the same for all bindings
  25903. for (let j = 0, m = nBindings; j !== m; ++j) {
  25904. const bindingsForPath = bindings[j],
  25905. lastCached = bindingsForPath[firstActiveIndex];
  25906. let binding = bindingsForPath[index];
  25907. bindingsForPath[index] = lastCached;
  25908. if (binding === undefined) {
  25909. // since we do not bother to create new bindings
  25910. // for objects that are cached, the binding may
  25911. // or may not exist
  25912. binding = new PropertyBinding(object, paths[j], parsedPaths[j]);
  25913. }
  25914. bindingsForPath[firstActiveIndex] = binding;
  25915. }
  25916. } else if (objects[index] !== knownObject) {
  25917. console.error('THREE.AnimationObjectGroup: Different objects with the same UUID ' + 'detected. Clean the caches or recreate your infrastructure when reloading scenes.');
  25918. } // else the object is already where we want it to be
  25919. } // for arguments
  25920. this.nCachedObjects_ = nCachedObjects;
  25921. }
  25922. remove() {
  25923. const objects = this._objects,
  25924. indicesByUUID = this._indicesByUUID,
  25925. bindings = this._bindings,
  25926. nBindings = bindings.length;
  25927. let nCachedObjects = this.nCachedObjects_;
  25928. for (let i = 0, n = arguments.length; i !== n; ++i) {
  25929. const object = arguments[i],
  25930. uuid = object.uuid,
  25931. index = indicesByUUID[uuid];
  25932. if (index !== undefined && index >= nCachedObjects) {
  25933. // move existing object into the CACHED region
  25934. const lastCachedIndex = nCachedObjects++,
  25935. firstActiveObject = objects[lastCachedIndex];
  25936. indicesByUUID[firstActiveObject.uuid] = index;
  25937. objects[index] = firstActiveObject;
  25938. indicesByUUID[uuid] = lastCachedIndex;
  25939. objects[lastCachedIndex] = object; // accounting is done, now do the same for all bindings
  25940. for (let j = 0, m = nBindings; j !== m; ++j) {
  25941. const bindingsForPath = bindings[j],
  25942. firstActive = bindingsForPath[lastCachedIndex],
  25943. binding = bindingsForPath[index];
  25944. bindingsForPath[index] = firstActive;
  25945. bindingsForPath[lastCachedIndex] = binding;
  25946. }
  25947. }
  25948. } // for arguments
  25949. this.nCachedObjects_ = nCachedObjects;
  25950. } // remove & forget
  25951. uncache() {
  25952. const objects = this._objects,
  25953. indicesByUUID = this._indicesByUUID,
  25954. bindings = this._bindings,
  25955. nBindings = bindings.length;
  25956. let nCachedObjects = this.nCachedObjects_,
  25957. nObjects = objects.length;
  25958. for (let i = 0, n = arguments.length; i !== n; ++i) {
  25959. const object = arguments[i],
  25960. uuid = object.uuid,
  25961. index = indicesByUUID[uuid];
  25962. if (index !== undefined) {
  25963. delete indicesByUUID[uuid];
  25964. if (index < nCachedObjects) {
  25965. // object is cached, shrink the CACHED region
  25966. const firstActiveIndex = --nCachedObjects,
  25967. lastCachedObject = objects[firstActiveIndex],
  25968. lastIndex = --nObjects,
  25969. lastObject = objects[lastIndex]; // last cached object takes this object's place
  25970. indicesByUUID[lastCachedObject.uuid] = index;
  25971. objects[index] = lastCachedObject; // last object goes to the activated slot and pop
  25972. indicesByUUID[lastObject.uuid] = firstActiveIndex;
  25973. objects[firstActiveIndex] = lastObject;
  25974. objects.pop(); // accounting is done, now do the same for all bindings
  25975. for (let j = 0, m = nBindings; j !== m; ++j) {
  25976. const bindingsForPath = bindings[j],
  25977. lastCached = bindingsForPath[firstActiveIndex],
  25978. last = bindingsForPath[lastIndex];
  25979. bindingsForPath[index] = lastCached;
  25980. bindingsForPath[firstActiveIndex] = last;
  25981. bindingsForPath.pop();
  25982. }
  25983. } else {
  25984. // object is active, just swap with the last and pop
  25985. const lastIndex = --nObjects,
  25986. lastObject = objects[lastIndex];
  25987. if (lastIndex > 0) {
  25988. indicesByUUID[lastObject.uuid] = index;
  25989. }
  25990. objects[index] = lastObject;
  25991. objects.pop(); // accounting is done, now do the same for all bindings
  25992. for (let j = 0, m = nBindings; j !== m; ++j) {
  25993. const bindingsForPath = bindings[j];
  25994. bindingsForPath[index] = bindingsForPath[lastIndex];
  25995. bindingsForPath.pop();
  25996. }
  25997. } // cached or active
  25998. } // if object is known
  25999. } // for arguments
  26000. this.nCachedObjects_ = nCachedObjects;
  26001. } // Internal interface used by befriended PropertyBinding.Composite:
  26002. subscribe_(path, parsedPath) {
  26003. // returns an array of bindings for the given path that is changed
  26004. // according to the contained objects in the group
  26005. const indicesByPath = this._bindingsIndicesByPath;
  26006. let index = indicesByPath[path];
  26007. const bindings = this._bindings;
  26008. if (index !== undefined) return bindings[index];
  26009. const paths = this._paths,
  26010. parsedPaths = this._parsedPaths,
  26011. objects = this._objects,
  26012. nObjects = objects.length,
  26013. nCachedObjects = this.nCachedObjects_,
  26014. bindingsForPath = new Array(nObjects);
  26015. index = bindings.length;
  26016. indicesByPath[path] = index;
  26017. paths.push(path);
  26018. parsedPaths.push(parsedPath);
  26019. bindings.push(bindingsForPath);
  26020. for (let i = nCachedObjects, n = objects.length; i !== n; ++i) {
  26021. const object = objects[i];
  26022. bindingsForPath[i] = new PropertyBinding(object, path, parsedPath);
  26023. }
  26024. return bindingsForPath;
  26025. }
  26026. unsubscribe_(path) {
  26027. // tells the group to forget about a property path and no longer
  26028. // update the array previously obtained with 'subscribe_'
  26029. const indicesByPath = this._bindingsIndicesByPath,
  26030. index = indicesByPath[path];
  26031. if (index !== undefined) {
  26032. const paths = this._paths,
  26033. parsedPaths = this._parsedPaths,
  26034. bindings = this._bindings,
  26035. lastBindingsIndex = bindings.length - 1,
  26036. lastBindings = bindings[lastBindingsIndex],
  26037. lastBindingsPath = path[lastBindingsIndex];
  26038. indicesByPath[lastBindingsPath] = index;
  26039. bindings[index] = lastBindings;
  26040. bindings.pop();
  26041. parsedPaths[index] = parsedPaths[lastBindingsIndex];
  26042. parsedPaths.pop();
  26043. paths[index] = paths[lastBindingsIndex];
  26044. paths.pop();
  26045. }
  26046. }
  26047. }
  26048. class AnimationAction {
  26049. constructor(mixer, clip, localRoot = null, blendMode = clip.blendMode) {
  26050. this._mixer = mixer;
  26051. this._clip = clip;
  26052. this._localRoot = localRoot;
  26053. this.blendMode = blendMode;
  26054. const tracks = clip.tracks,
  26055. nTracks = tracks.length,
  26056. interpolants = new Array(nTracks);
  26057. const interpolantSettings = {
  26058. endingStart: ZeroCurvatureEnding,
  26059. endingEnd: ZeroCurvatureEnding
  26060. };
  26061. for (let i = 0; i !== nTracks; ++i) {
  26062. const interpolant = tracks[i].createInterpolant(null);
  26063. interpolants[i] = interpolant;
  26064. interpolant.settings = interpolantSettings;
  26065. }
  26066. this._interpolantSettings = interpolantSettings;
  26067. this._interpolants = interpolants; // bound by the mixer
  26068. // inside: PropertyMixer (managed by the mixer)
  26069. this._propertyBindings = new Array(nTracks);
  26070. this._cacheIndex = null; // for the memory manager
  26071. this._byClipCacheIndex = null; // for the memory manager
  26072. this._timeScaleInterpolant = null;
  26073. this._weightInterpolant = null;
  26074. this.loop = LoopRepeat;
  26075. this._loopCount = -1; // global mixer time when the action is to be started
  26076. // it's set back to 'null' upon start of the action
  26077. this._startTime = null; // scaled local time of the action
  26078. // gets clamped or wrapped to 0..clip.duration according to loop
  26079. this.time = 0;
  26080. this.timeScale = 1;
  26081. this._effectiveTimeScale = 1;
  26082. this.weight = 1;
  26083. this._effectiveWeight = 1;
  26084. this.repetitions = Infinity; // no. of repetitions when looping
  26085. this.paused = false; // true -> zero effective time scale
  26086. this.enabled = true; // false -> zero effective weight
  26087. this.clampWhenFinished = false; // keep feeding the last frame?
  26088. this.zeroSlopeAtStart = true; // for smooth interpolation w/o separate
  26089. this.zeroSlopeAtEnd = true; // clips for start, loop and end
  26090. } // State & Scheduling
  26091. play() {
  26092. this._mixer._activateAction(this);
  26093. return this;
  26094. }
  26095. stop() {
  26096. this._mixer._deactivateAction(this);
  26097. return this.reset();
  26098. }
  26099. reset() {
  26100. this.paused = false;
  26101. this.enabled = true;
  26102. this.time = 0; // restart clip
  26103. this._loopCount = -1; // forget previous loops
  26104. this._startTime = null; // forget scheduling
  26105. return this.stopFading().stopWarping();
  26106. }
  26107. isRunning() {
  26108. return this.enabled && !this.paused && this.timeScale !== 0 && this._startTime === null && this._mixer._isActiveAction(this);
  26109. } // return true when play has been called
  26110. isScheduled() {
  26111. return this._mixer._isActiveAction(this);
  26112. }
  26113. startAt(time) {
  26114. this._startTime = time;
  26115. return this;
  26116. }
  26117. setLoop(mode, repetitions) {
  26118. this.loop = mode;
  26119. this.repetitions = repetitions;
  26120. return this;
  26121. } // Weight
  26122. // set the weight stopping any scheduled fading
  26123. // although .enabled = false yields an effective weight of zero, this
  26124. // method does *not* change .enabled, because it would be confusing
  26125. setEffectiveWeight(weight) {
  26126. this.weight = weight; // note: same logic as when updated at runtime
  26127. this._effectiveWeight = this.enabled ? weight : 0;
  26128. return this.stopFading();
  26129. } // return the weight considering fading and .enabled
  26130. getEffectiveWeight() {
  26131. return this._effectiveWeight;
  26132. }
  26133. fadeIn(duration) {
  26134. return this._scheduleFading(duration, 0, 1);
  26135. }
  26136. fadeOut(duration) {
  26137. return this._scheduleFading(duration, 1, 0);
  26138. }
  26139. crossFadeFrom(fadeOutAction, duration, warp) {
  26140. fadeOutAction.fadeOut(duration);
  26141. this.fadeIn(duration);
  26142. if (warp) {
  26143. const fadeInDuration = this._clip.duration,
  26144. fadeOutDuration = fadeOutAction._clip.duration,
  26145. startEndRatio = fadeOutDuration / fadeInDuration,
  26146. endStartRatio = fadeInDuration / fadeOutDuration;
  26147. fadeOutAction.warp(1.0, startEndRatio, duration);
  26148. this.warp(endStartRatio, 1.0, duration);
  26149. }
  26150. return this;
  26151. }
  26152. crossFadeTo(fadeInAction, duration, warp) {
  26153. return fadeInAction.crossFadeFrom(this, duration, warp);
  26154. }
  26155. stopFading() {
  26156. const weightInterpolant = this._weightInterpolant;
  26157. if (weightInterpolant !== null) {
  26158. this._weightInterpolant = null;
  26159. this._mixer._takeBackControlInterpolant(weightInterpolant);
  26160. }
  26161. return this;
  26162. } // Time Scale Control
  26163. // set the time scale stopping any scheduled warping
  26164. // although .paused = true yields an effective time scale of zero, this
  26165. // method does *not* change .paused, because it would be confusing
  26166. setEffectiveTimeScale(timeScale) {
  26167. this.timeScale = timeScale;
  26168. this._effectiveTimeScale = this.paused ? 0 : timeScale;
  26169. return this.stopWarping();
  26170. } // return the time scale considering warping and .paused
  26171. getEffectiveTimeScale() {
  26172. return this._effectiveTimeScale;
  26173. }
  26174. setDuration(duration) {
  26175. this.timeScale = this._clip.duration / duration;
  26176. return this.stopWarping();
  26177. }
  26178. syncWith(action) {
  26179. this.time = action.time;
  26180. this.timeScale = action.timeScale;
  26181. return this.stopWarping();
  26182. }
  26183. halt(duration) {
  26184. return this.warp(this._effectiveTimeScale, 0, duration);
  26185. }
  26186. warp(startTimeScale, endTimeScale, duration) {
  26187. const mixer = this._mixer,
  26188. now = mixer.time,
  26189. timeScale = this.timeScale;
  26190. let interpolant = this._timeScaleInterpolant;
  26191. if (interpolant === null) {
  26192. interpolant = mixer._lendControlInterpolant();
  26193. this._timeScaleInterpolant = interpolant;
  26194. }
  26195. const times = interpolant.parameterPositions,
  26196. values = interpolant.sampleValues;
  26197. times[0] = now;
  26198. times[1] = now + duration;
  26199. values[0] = startTimeScale / timeScale;
  26200. values[1] = endTimeScale / timeScale;
  26201. return this;
  26202. }
  26203. stopWarping() {
  26204. const timeScaleInterpolant = this._timeScaleInterpolant;
  26205. if (timeScaleInterpolant !== null) {
  26206. this._timeScaleInterpolant = null;
  26207. this._mixer._takeBackControlInterpolant(timeScaleInterpolant);
  26208. }
  26209. return this;
  26210. } // Object Accessors
  26211. getMixer() {
  26212. return this._mixer;
  26213. }
  26214. getClip() {
  26215. return this._clip;
  26216. }
  26217. getRoot() {
  26218. return this._localRoot || this._mixer._root;
  26219. } // Interna
  26220. _update(time, deltaTime, timeDirection, accuIndex) {
  26221. // called by the mixer
  26222. if (!this.enabled) {
  26223. // call ._updateWeight() to update ._effectiveWeight
  26224. this._updateWeight(time);
  26225. return;
  26226. }
  26227. const startTime = this._startTime;
  26228. if (startTime !== null) {
  26229. // check for scheduled start of action
  26230. const timeRunning = (time - startTime) * timeDirection;
  26231. if (timeRunning < 0 || timeDirection === 0) {
  26232. return; // yet to come / don't decide when delta = 0
  26233. } // start
  26234. this._startTime = null; // unschedule
  26235. deltaTime = timeDirection * timeRunning;
  26236. } // apply time scale and advance time
  26237. deltaTime *= this._updateTimeScale(time);
  26238. const clipTime = this._updateTime(deltaTime); // note: _updateTime may disable the action resulting in
  26239. // an effective weight of 0
  26240. const weight = this._updateWeight(time);
  26241. if (weight > 0) {
  26242. const interpolants = this._interpolants;
  26243. const propertyMixers = this._propertyBindings;
  26244. switch (this.blendMode) {
  26245. case AdditiveAnimationBlendMode:
  26246. for (let j = 0, m = interpolants.length; j !== m; ++j) {
  26247. interpolants[j].evaluate(clipTime);
  26248. propertyMixers[j].accumulateAdditive(weight);
  26249. }
  26250. break;
  26251. case NormalAnimationBlendMode:
  26252. default:
  26253. for (let j = 0, m = interpolants.length; j !== m; ++j) {
  26254. interpolants[j].evaluate(clipTime);
  26255. propertyMixers[j].accumulate(accuIndex, weight);
  26256. }
  26257. }
  26258. }
  26259. }
  26260. _updateWeight(time) {
  26261. let weight = 0;
  26262. if (this.enabled) {
  26263. weight = this.weight;
  26264. const interpolant = this._weightInterpolant;
  26265. if (interpolant !== null) {
  26266. const interpolantValue = interpolant.evaluate(time)[0];
  26267. weight *= interpolantValue;
  26268. if (time > interpolant.parameterPositions[1]) {
  26269. this.stopFading();
  26270. if (interpolantValue === 0) {
  26271. // faded out, disable
  26272. this.enabled = false;
  26273. }
  26274. }
  26275. }
  26276. }
  26277. this._effectiveWeight = weight;
  26278. return weight;
  26279. }
  26280. _updateTimeScale(time) {
  26281. let timeScale = 0;
  26282. if (!this.paused) {
  26283. timeScale = this.timeScale;
  26284. const interpolant = this._timeScaleInterpolant;
  26285. if (interpolant !== null) {
  26286. const interpolantValue = interpolant.evaluate(time)[0];
  26287. timeScale *= interpolantValue;
  26288. if (time > interpolant.parameterPositions[1]) {
  26289. this.stopWarping();
  26290. if (timeScale === 0) {
  26291. // motion has halted, pause
  26292. this.paused = true;
  26293. } else {
  26294. // warp done - apply final time scale
  26295. this.timeScale = timeScale;
  26296. }
  26297. }
  26298. }
  26299. }
  26300. this._effectiveTimeScale = timeScale;
  26301. return timeScale;
  26302. }
  26303. _updateTime(deltaTime) {
  26304. const duration = this._clip.duration;
  26305. const loop = this.loop;
  26306. let time = this.time + deltaTime;
  26307. let loopCount = this._loopCount;
  26308. const pingPong = loop === LoopPingPong;
  26309. if (deltaTime === 0) {
  26310. if (loopCount === -1) return time;
  26311. return pingPong && (loopCount & 1) === 1 ? duration - time : time;
  26312. }
  26313. if (loop === LoopOnce) {
  26314. if (loopCount === -1) {
  26315. // just started
  26316. this._loopCount = 0;
  26317. this._setEndings(true, true, false);
  26318. }
  26319. handle_stop: {
  26320. if (time >= duration) {
  26321. time = duration;
  26322. } else if (time < 0) {
  26323. time = 0;
  26324. } else {
  26325. this.time = time;
  26326. break handle_stop;
  26327. }
  26328. if (this.clampWhenFinished) this.paused = true;else this.enabled = false;
  26329. this.time = time;
  26330. this._mixer.dispatchEvent({
  26331. type: 'finished',
  26332. action: this,
  26333. direction: deltaTime < 0 ? -1 : 1
  26334. });
  26335. }
  26336. } else {
  26337. // repetitive Repeat or PingPong
  26338. if (loopCount === -1) {
  26339. // just started
  26340. if (deltaTime >= 0) {
  26341. loopCount = 0;
  26342. this._setEndings(true, this.repetitions === 0, pingPong);
  26343. } else {
  26344. // when looping in reverse direction, the initial
  26345. // transition through zero counts as a repetition,
  26346. // so leave loopCount at -1
  26347. this._setEndings(this.repetitions === 0, true, pingPong);
  26348. }
  26349. }
  26350. if (time >= duration || time < 0) {
  26351. // wrap around
  26352. const loopDelta = Math.floor(time / duration); // signed
  26353. time -= duration * loopDelta;
  26354. loopCount += Math.abs(loopDelta);
  26355. const pending = this.repetitions - loopCount;
  26356. if (pending <= 0) {
  26357. // have to stop (switch state, clamp time, fire event)
  26358. if (this.clampWhenFinished) this.paused = true;else this.enabled = false;
  26359. time = deltaTime > 0 ? duration : 0;
  26360. this.time = time;
  26361. this._mixer.dispatchEvent({
  26362. type: 'finished',
  26363. action: this,
  26364. direction: deltaTime > 0 ? 1 : -1
  26365. });
  26366. } else {
  26367. // keep running
  26368. if (pending === 1) {
  26369. // entering the last round
  26370. const atStart = deltaTime < 0;
  26371. this._setEndings(atStart, !atStart, pingPong);
  26372. } else {
  26373. this._setEndings(false, false, pingPong);
  26374. }
  26375. this._loopCount = loopCount;
  26376. this.time = time;
  26377. this._mixer.dispatchEvent({
  26378. type: 'loop',
  26379. action: this,
  26380. loopDelta: loopDelta
  26381. });
  26382. }
  26383. } else {
  26384. this.time = time;
  26385. }
  26386. if (pingPong && (loopCount & 1) === 1) {
  26387. // invert time for the "pong round"
  26388. return duration - time;
  26389. }
  26390. }
  26391. return time;
  26392. }
  26393. _setEndings(atStart, atEnd, pingPong) {
  26394. const settings = this._interpolantSettings;
  26395. if (pingPong) {
  26396. settings.endingStart = ZeroSlopeEnding;
  26397. settings.endingEnd = ZeroSlopeEnding;
  26398. } else {
  26399. // assuming for LoopOnce atStart == atEnd == true
  26400. if (atStart) {
  26401. settings.endingStart = this.zeroSlopeAtStart ? ZeroSlopeEnding : ZeroCurvatureEnding;
  26402. } else {
  26403. settings.endingStart = WrapAroundEnding;
  26404. }
  26405. if (atEnd) {
  26406. settings.endingEnd = this.zeroSlopeAtEnd ? ZeroSlopeEnding : ZeroCurvatureEnding;
  26407. } else {
  26408. settings.endingEnd = WrapAroundEnding;
  26409. }
  26410. }
  26411. }
  26412. _scheduleFading(duration, weightNow, weightThen) {
  26413. const mixer = this._mixer,
  26414. now = mixer.time;
  26415. let interpolant = this._weightInterpolant;
  26416. if (interpolant === null) {
  26417. interpolant = mixer._lendControlInterpolant();
  26418. this._weightInterpolant = interpolant;
  26419. }
  26420. const times = interpolant.parameterPositions,
  26421. values = interpolant.sampleValues;
  26422. times[0] = now;
  26423. values[0] = weightNow;
  26424. times[1] = now + duration;
  26425. values[1] = weightThen;
  26426. return this;
  26427. }
  26428. }
  26429. const _controlInterpolantsResultBuffer = /*@__PURE__*/new Float32Array(1);
  26430. class AnimationMixer extends EventDispatcher {
  26431. constructor(root) {
  26432. super();
  26433. this._root = root;
  26434. this._initMemoryManager();
  26435. this._accuIndex = 0;
  26436. this.time = 0;
  26437. this.timeScale = 1.0;
  26438. }
  26439. _bindAction(action, prototypeAction) {
  26440. const root = action._localRoot || this._root,
  26441. tracks = action._clip.tracks,
  26442. nTracks = tracks.length,
  26443. bindings = action._propertyBindings,
  26444. interpolants = action._interpolants,
  26445. rootUuid = root.uuid,
  26446. bindingsByRoot = this._bindingsByRootAndName;
  26447. let bindingsByName = bindingsByRoot[rootUuid];
  26448. if (bindingsByName === undefined) {
  26449. bindingsByName = {};
  26450. bindingsByRoot[rootUuid] = bindingsByName;
  26451. }
  26452. for (let i = 0; i !== nTracks; ++i) {
  26453. const track = tracks[i],
  26454. trackName = track.name;
  26455. let binding = bindingsByName[trackName];
  26456. if (binding !== undefined) {
  26457. ++binding.referenceCount;
  26458. bindings[i] = binding;
  26459. } else {
  26460. binding = bindings[i];
  26461. if (binding !== undefined) {
  26462. // existing binding, make sure the cache knows
  26463. if (binding._cacheIndex === null) {
  26464. ++binding.referenceCount;
  26465. this._addInactiveBinding(binding, rootUuid, trackName);
  26466. }
  26467. continue;
  26468. }
  26469. const path = prototypeAction && prototypeAction._propertyBindings[i].binding.parsedPath;
  26470. binding = new PropertyMixer(PropertyBinding.create(root, trackName, path), track.ValueTypeName, track.getValueSize());
  26471. ++binding.referenceCount;
  26472. this._addInactiveBinding(binding, rootUuid, trackName);
  26473. bindings[i] = binding;
  26474. }
  26475. interpolants[i].resultBuffer = binding.buffer;
  26476. }
  26477. }
  26478. _activateAction(action) {
  26479. if (!this._isActiveAction(action)) {
  26480. if (action._cacheIndex === null) {
  26481. // this action has been forgotten by the cache, but the user
  26482. // appears to be still using it -> rebind
  26483. const rootUuid = (action._localRoot || this._root).uuid,
  26484. clipUuid = action._clip.uuid,
  26485. actionsForClip = this._actionsByClip[clipUuid];
  26486. this._bindAction(action, actionsForClip && actionsForClip.knownActions[0]);
  26487. this._addInactiveAction(action, clipUuid, rootUuid);
  26488. }
  26489. const bindings = action._propertyBindings; // increment reference counts / sort out state
  26490. for (let i = 0, n = bindings.length; i !== n; ++i) {
  26491. const binding = bindings[i];
  26492. if (binding.useCount++ === 0) {
  26493. this._lendBinding(binding);
  26494. binding.saveOriginalState();
  26495. }
  26496. }
  26497. this._lendAction(action);
  26498. }
  26499. }
  26500. _deactivateAction(action) {
  26501. if (this._isActiveAction(action)) {
  26502. const bindings = action._propertyBindings; // decrement reference counts / sort out state
  26503. for (let i = 0, n = bindings.length; i !== n; ++i) {
  26504. const binding = bindings[i];
  26505. if (--binding.useCount === 0) {
  26506. binding.restoreOriginalState();
  26507. this._takeBackBinding(binding);
  26508. }
  26509. }
  26510. this._takeBackAction(action);
  26511. }
  26512. } // Memory manager
  26513. _initMemoryManager() {
  26514. this._actions = []; // 'nActiveActions' followed by inactive ones
  26515. this._nActiveActions = 0;
  26516. this._actionsByClip = {}; // inside:
  26517. // {
  26518. // knownActions: Array< AnimationAction > - used as prototypes
  26519. // actionByRoot: AnimationAction - lookup
  26520. // }
  26521. this._bindings = []; // 'nActiveBindings' followed by inactive ones
  26522. this._nActiveBindings = 0;
  26523. this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer >
  26524. this._controlInterpolants = []; // same game as above
  26525. this._nActiveControlInterpolants = 0;
  26526. const scope = this;
  26527. this.stats = {
  26528. actions: {
  26529. get total() {
  26530. return scope._actions.length;
  26531. },
  26532. get inUse() {
  26533. return scope._nActiveActions;
  26534. }
  26535. },
  26536. bindings: {
  26537. get total() {
  26538. return scope._bindings.length;
  26539. },
  26540. get inUse() {
  26541. return scope._nActiveBindings;
  26542. }
  26543. },
  26544. controlInterpolants: {
  26545. get total() {
  26546. return scope._controlInterpolants.length;
  26547. },
  26548. get inUse() {
  26549. return scope._nActiveControlInterpolants;
  26550. }
  26551. }
  26552. };
  26553. } // Memory management for AnimationAction objects
  26554. _isActiveAction(action) {
  26555. const index = action._cacheIndex;
  26556. return index !== null && index < this._nActiveActions;
  26557. }
  26558. _addInactiveAction(action, clipUuid, rootUuid) {
  26559. const actions = this._actions,
  26560. actionsByClip = this._actionsByClip;
  26561. let actionsForClip = actionsByClip[clipUuid];
  26562. if (actionsForClip === undefined) {
  26563. actionsForClip = {
  26564. knownActions: [action],
  26565. actionByRoot: {}
  26566. };
  26567. action._byClipCacheIndex = 0;
  26568. actionsByClip[clipUuid] = actionsForClip;
  26569. } else {
  26570. const knownActions = actionsForClip.knownActions;
  26571. action._byClipCacheIndex = knownActions.length;
  26572. knownActions.push(action);
  26573. }
  26574. action._cacheIndex = actions.length;
  26575. actions.push(action);
  26576. actionsForClip.actionByRoot[rootUuid] = action;
  26577. }
  26578. _removeInactiveAction(action) {
  26579. const actions = this._actions,
  26580. lastInactiveAction = actions[actions.length - 1],
  26581. cacheIndex = action._cacheIndex;
  26582. lastInactiveAction._cacheIndex = cacheIndex;
  26583. actions[cacheIndex] = lastInactiveAction;
  26584. actions.pop();
  26585. action._cacheIndex = null;
  26586. const clipUuid = action._clip.uuid,
  26587. actionsByClip = this._actionsByClip,
  26588. actionsForClip = actionsByClip[clipUuid],
  26589. knownActionsForClip = actionsForClip.knownActions,
  26590. lastKnownAction = knownActionsForClip[knownActionsForClip.length - 1],
  26591. byClipCacheIndex = action._byClipCacheIndex;
  26592. lastKnownAction._byClipCacheIndex = byClipCacheIndex;
  26593. knownActionsForClip[byClipCacheIndex] = lastKnownAction;
  26594. knownActionsForClip.pop();
  26595. action._byClipCacheIndex = null;
  26596. const actionByRoot = actionsForClip.actionByRoot,
  26597. rootUuid = (action._localRoot || this._root).uuid;
  26598. delete actionByRoot[rootUuid];
  26599. if (knownActionsForClip.length === 0) {
  26600. delete actionsByClip[clipUuid];
  26601. }
  26602. this._removeInactiveBindingsForAction(action);
  26603. }
  26604. _removeInactiveBindingsForAction(action) {
  26605. const bindings = action._propertyBindings;
  26606. for (let i = 0, n = bindings.length; i !== n; ++i) {
  26607. const binding = bindings[i];
  26608. if (--binding.referenceCount === 0) {
  26609. this._removeInactiveBinding(binding);
  26610. }
  26611. }
  26612. }
  26613. _lendAction(action) {
  26614. // [ active actions | inactive actions ]
  26615. // [ active actions >| inactive actions ]
  26616. // s a
  26617. // <-swap->
  26618. // a s
  26619. const actions = this._actions,
  26620. prevIndex = action._cacheIndex,
  26621. lastActiveIndex = this._nActiveActions++,
  26622. firstInactiveAction = actions[lastActiveIndex];
  26623. action._cacheIndex = lastActiveIndex;
  26624. actions[lastActiveIndex] = action;
  26625. firstInactiveAction._cacheIndex = prevIndex;
  26626. actions[prevIndex] = firstInactiveAction;
  26627. }
  26628. _takeBackAction(action) {
  26629. // [ active actions | inactive actions ]
  26630. // [ active actions |< inactive actions ]
  26631. // a s
  26632. // <-swap->
  26633. // s a
  26634. const actions = this._actions,
  26635. prevIndex = action._cacheIndex,
  26636. firstInactiveIndex = --this._nActiveActions,
  26637. lastActiveAction = actions[firstInactiveIndex];
  26638. action._cacheIndex = firstInactiveIndex;
  26639. actions[firstInactiveIndex] = action;
  26640. lastActiveAction._cacheIndex = prevIndex;
  26641. actions[prevIndex] = lastActiveAction;
  26642. } // Memory management for PropertyMixer objects
  26643. _addInactiveBinding(binding, rootUuid, trackName) {
  26644. const bindingsByRoot = this._bindingsByRootAndName,
  26645. bindings = this._bindings;
  26646. let bindingByName = bindingsByRoot[rootUuid];
  26647. if (bindingByName === undefined) {
  26648. bindingByName = {};
  26649. bindingsByRoot[rootUuid] = bindingByName;
  26650. }
  26651. bindingByName[trackName] = binding;
  26652. binding._cacheIndex = bindings.length;
  26653. bindings.push(binding);
  26654. }
  26655. _removeInactiveBinding(binding) {
  26656. const bindings = this._bindings,
  26657. propBinding = binding.binding,
  26658. rootUuid = propBinding.rootNode.uuid,
  26659. trackName = propBinding.path,
  26660. bindingsByRoot = this._bindingsByRootAndName,
  26661. bindingByName = bindingsByRoot[rootUuid],
  26662. lastInactiveBinding = bindings[bindings.length - 1],
  26663. cacheIndex = binding._cacheIndex;
  26664. lastInactiveBinding._cacheIndex = cacheIndex;
  26665. bindings[cacheIndex] = lastInactiveBinding;
  26666. bindings.pop();
  26667. delete bindingByName[trackName];
  26668. if (Object.keys(bindingByName).length === 0) {
  26669. delete bindingsByRoot[rootUuid];
  26670. }
  26671. }
  26672. _lendBinding(binding) {
  26673. const bindings = this._bindings,
  26674. prevIndex = binding._cacheIndex,
  26675. lastActiveIndex = this._nActiveBindings++,
  26676. firstInactiveBinding = bindings[lastActiveIndex];
  26677. binding._cacheIndex = lastActiveIndex;
  26678. bindings[lastActiveIndex] = binding;
  26679. firstInactiveBinding._cacheIndex = prevIndex;
  26680. bindings[prevIndex] = firstInactiveBinding;
  26681. }
  26682. _takeBackBinding(binding) {
  26683. const bindings = this._bindings,
  26684. prevIndex = binding._cacheIndex,
  26685. firstInactiveIndex = --this._nActiveBindings,
  26686. lastActiveBinding = bindings[firstInactiveIndex];
  26687. binding._cacheIndex = firstInactiveIndex;
  26688. bindings[firstInactiveIndex] = binding;
  26689. lastActiveBinding._cacheIndex = prevIndex;
  26690. bindings[prevIndex] = lastActiveBinding;
  26691. } // Memory management of Interpolants for weight and time scale
  26692. _lendControlInterpolant() {
  26693. const interpolants = this._controlInterpolants,
  26694. lastActiveIndex = this._nActiveControlInterpolants++;
  26695. let interpolant = interpolants[lastActiveIndex];
  26696. if (interpolant === undefined) {
  26697. interpolant = new LinearInterpolant(new Float32Array(2), new Float32Array(2), 1, _controlInterpolantsResultBuffer);
  26698. interpolant.__cacheIndex = lastActiveIndex;
  26699. interpolants[lastActiveIndex] = interpolant;
  26700. }
  26701. return interpolant;
  26702. }
  26703. _takeBackControlInterpolant(interpolant) {
  26704. const interpolants = this._controlInterpolants,
  26705. prevIndex = interpolant.__cacheIndex,
  26706. firstInactiveIndex = --this._nActiveControlInterpolants,
  26707. lastActiveInterpolant = interpolants[firstInactiveIndex];
  26708. interpolant.__cacheIndex = firstInactiveIndex;
  26709. interpolants[firstInactiveIndex] = interpolant;
  26710. lastActiveInterpolant.__cacheIndex = prevIndex;
  26711. interpolants[prevIndex] = lastActiveInterpolant;
  26712. } // return an action for a clip optionally using a custom root target
  26713. // object (this method allocates a lot of dynamic memory in case a
  26714. // previously unknown clip/root combination is specified)
  26715. clipAction(clip, optionalRoot, blendMode) {
  26716. const root = optionalRoot || this._root,
  26717. rootUuid = root.uuid;
  26718. let clipObject = typeof clip === 'string' ? AnimationClip.findByName(root, clip) : clip;
  26719. const clipUuid = clipObject !== null ? clipObject.uuid : clip;
  26720. const actionsForClip = this._actionsByClip[clipUuid];
  26721. let prototypeAction = null;
  26722. if (blendMode === undefined) {
  26723. if (clipObject !== null) {
  26724. blendMode = clipObject.blendMode;
  26725. } else {
  26726. blendMode = NormalAnimationBlendMode;
  26727. }
  26728. }
  26729. if (actionsForClip !== undefined) {
  26730. const existingAction = actionsForClip.actionByRoot[rootUuid];
  26731. if (existingAction !== undefined && existingAction.blendMode === blendMode) {
  26732. return existingAction;
  26733. } // we know the clip, so we don't have to parse all
  26734. // the bindings again but can just copy
  26735. prototypeAction = actionsForClip.knownActions[0]; // also, take the clip from the prototype action
  26736. if (clipObject === null) clipObject = prototypeAction._clip;
  26737. } // clip must be known when specified via string
  26738. if (clipObject === null) return null; // allocate all resources required to run it
  26739. const newAction = new AnimationAction(this, clipObject, optionalRoot, blendMode);
  26740. this._bindAction(newAction, prototypeAction); // and make the action known to the memory manager
  26741. this._addInactiveAction(newAction, clipUuid, rootUuid);
  26742. return newAction;
  26743. } // get an existing action
  26744. existingAction(clip, optionalRoot) {
  26745. const root = optionalRoot || this._root,
  26746. rootUuid = root.uuid,
  26747. clipObject = typeof clip === 'string' ? AnimationClip.findByName(root, clip) : clip,
  26748. clipUuid = clipObject ? clipObject.uuid : clip,
  26749. actionsForClip = this._actionsByClip[clipUuid];
  26750. if (actionsForClip !== undefined) {
  26751. return actionsForClip.actionByRoot[rootUuid] || null;
  26752. }
  26753. return null;
  26754. } // deactivates all previously scheduled actions
  26755. stopAllAction() {
  26756. const actions = this._actions,
  26757. nActions = this._nActiveActions;
  26758. for (let i = nActions - 1; i >= 0; --i) {
  26759. actions[i].stop();
  26760. }
  26761. return this;
  26762. } // advance the time and update apply the animation
  26763. update(deltaTime) {
  26764. deltaTime *= this.timeScale;
  26765. const actions = this._actions,
  26766. nActions = this._nActiveActions,
  26767. time = this.time += deltaTime,
  26768. timeDirection = Math.sign(deltaTime),
  26769. accuIndex = this._accuIndex ^= 1; // run active actions
  26770. for (let i = 0; i !== nActions; ++i) {
  26771. const action = actions[i];
  26772. action._update(time, deltaTime, timeDirection, accuIndex);
  26773. } // update scene graph
  26774. const bindings = this._bindings,
  26775. nBindings = this._nActiveBindings;
  26776. for (let i = 0; i !== nBindings; ++i) {
  26777. bindings[i].apply(accuIndex);
  26778. }
  26779. return this;
  26780. } // Allows you to seek to a specific time in an animation.
  26781. setTime(timeInSeconds) {
  26782. this.time = 0; // Zero out time attribute for AnimationMixer object;
  26783. for (let i = 0; i < this._actions.length; i++) {
  26784. this._actions[i].time = 0; // Zero out time attribute for all associated AnimationAction objects.
  26785. }
  26786. return this.update(timeInSeconds); // Update used to set exact time. Returns "this" AnimationMixer object.
  26787. } // return this mixer's root target object
  26788. getRoot() {
  26789. return this._root;
  26790. } // free all resources specific to a particular clip
  26791. uncacheClip(clip) {
  26792. const actions = this._actions,
  26793. clipUuid = clip.uuid,
  26794. actionsByClip = this._actionsByClip,
  26795. actionsForClip = actionsByClip[clipUuid];
  26796. if (actionsForClip !== undefined) {
  26797. // note: just calling _removeInactiveAction would mess up the
  26798. // iteration state and also require updating the state we can
  26799. // just throw away
  26800. const actionsToRemove = actionsForClip.knownActions;
  26801. for (let i = 0, n = actionsToRemove.length; i !== n; ++i) {
  26802. const action = actionsToRemove[i];
  26803. this._deactivateAction(action);
  26804. const cacheIndex = action._cacheIndex,
  26805. lastInactiveAction = actions[actions.length - 1];
  26806. action._cacheIndex = null;
  26807. action._byClipCacheIndex = null;
  26808. lastInactiveAction._cacheIndex = cacheIndex;
  26809. actions[cacheIndex] = lastInactiveAction;
  26810. actions.pop();
  26811. this._removeInactiveBindingsForAction(action);
  26812. }
  26813. delete actionsByClip[clipUuid];
  26814. }
  26815. } // free all resources specific to a particular root target object
  26816. uncacheRoot(root) {
  26817. const rootUuid = root.uuid,
  26818. actionsByClip = this._actionsByClip;
  26819. for (const clipUuid in actionsByClip) {
  26820. const actionByRoot = actionsByClip[clipUuid].actionByRoot,
  26821. action = actionByRoot[rootUuid];
  26822. if (action !== undefined) {
  26823. this._deactivateAction(action);
  26824. this._removeInactiveAction(action);
  26825. }
  26826. }
  26827. const bindingsByRoot = this._bindingsByRootAndName,
  26828. bindingByName = bindingsByRoot[rootUuid];
  26829. if (bindingByName !== undefined) {
  26830. for (const trackName in bindingByName) {
  26831. const binding = bindingByName[trackName];
  26832. binding.restoreOriginalState();
  26833. this._removeInactiveBinding(binding);
  26834. }
  26835. }
  26836. } // remove a targeted clip from the cache
  26837. uncacheAction(clip, optionalRoot) {
  26838. const action = this.existingAction(clip, optionalRoot);
  26839. if (action !== null) {
  26840. this._deactivateAction(action);
  26841. this._removeInactiveAction(action);
  26842. }
  26843. }
  26844. }
  26845. class Uniform {
  26846. constructor(value) {
  26847. if (typeof value === 'string') {
  26848. console.warn('THREE.Uniform: Type parameter is no longer needed.');
  26849. value = arguments[1];
  26850. }
  26851. this.value = value;
  26852. }
  26853. clone() {
  26854. return new Uniform(this.value.clone === undefined ? this.value : this.value.clone());
  26855. }
  26856. }
  26857. class InstancedInterleavedBuffer extends InterleavedBuffer {
  26858. constructor(array, stride, meshPerAttribute = 1) {
  26859. super(array, stride);
  26860. this.isInstancedInterleavedBuffer = true;
  26861. this.meshPerAttribute = meshPerAttribute;
  26862. }
  26863. copy(source) {
  26864. super.copy(source);
  26865. this.meshPerAttribute = source.meshPerAttribute;
  26866. return this;
  26867. }
  26868. clone(data) {
  26869. const ib = super.clone(data);
  26870. ib.meshPerAttribute = this.meshPerAttribute;
  26871. return ib;
  26872. }
  26873. toJSON(data) {
  26874. const json = super.toJSON(data);
  26875. json.isInstancedInterleavedBuffer = true;
  26876. json.meshPerAttribute = this.meshPerAttribute;
  26877. return json;
  26878. }
  26879. }
  26880. class GLBufferAttribute {
  26881. constructor(buffer, type, itemSize, elementSize, count) {
  26882. this.isGLBufferAttribute = true;
  26883. this.buffer = buffer;
  26884. this.type = type;
  26885. this.itemSize = itemSize;
  26886. this.elementSize = elementSize;
  26887. this.count = count;
  26888. this.version = 0;
  26889. }
  26890. set needsUpdate(value) {
  26891. if (value === true) this.version++;
  26892. }
  26893. setBuffer(buffer) {
  26894. this.buffer = buffer;
  26895. return this;
  26896. }
  26897. setType(type, elementSize) {
  26898. this.type = type;
  26899. this.elementSize = elementSize;
  26900. return this;
  26901. }
  26902. setItemSize(itemSize) {
  26903. this.itemSize = itemSize;
  26904. return this;
  26905. }
  26906. setCount(count) {
  26907. this.count = count;
  26908. return this;
  26909. }
  26910. }
  26911. class Raycaster {
  26912. constructor(origin, direction, near = 0, far = Infinity) {
  26913. this.ray = new Ray(origin, direction); // direction is assumed to be normalized (for accurate distance calculations)
  26914. this.near = near;
  26915. this.far = far;
  26916. this.camera = null;
  26917. this.layers = new Layers();
  26918. this.params = {
  26919. Mesh: {},
  26920. Line: {
  26921. threshold: 1
  26922. },
  26923. LOD: {},
  26924. Points: {
  26925. threshold: 1
  26926. },
  26927. Sprite: {}
  26928. };
  26929. }
  26930. set(origin, direction) {
  26931. // direction is assumed to be normalized (for accurate distance calculations)
  26932. this.ray.set(origin, direction);
  26933. }
  26934. setFromCamera(coords, camera) {
  26935. if (camera.isPerspectiveCamera) {
  26936. this.ray.origin.setFromMatrixPosition(camera.matrixWorld);
  26937. this.ray.direction.set(coords.x, coords.y, 0.5).unproject(camera).sub(this.ray.origin).normalize();
  26938. this.camera = camera;
  26939. } else if (camera.isOrthographicCamera) {
  26940. this.ray.origin.set(coords.x, coords.y, (camera.near + camera.far) / (camera.near - camera.far)).unproject(camera); // set origin in plane of camera
  26941. this.ray.direction.set(0, 0, -1).transformDirection(camera.matrixWorld);
  26942. this.camera = camera;
  26943. } else {
  26944. console.error('THREE.Raycaster: Unsupported camera type: ' + camera.type);
  26945. }
  26946. }
  26947. intersectObject(object, recursive = true, intersects = []) {
  26948. intersectObject(object, this, intersects, recursive);
  26949. intersects.sort(ascSort);
  26950. return intersects;
  26951. }
  26952. intersectObjects(objects, recursive = true, intersects = []) {
  26953. for (let i = 0, l = objects.length; i < l; i++) {
  26954. intersectObject(objects[i], this, intersects, recursive);
  26955. }
  26956. intersects.sort(ascSort);
  26957. return intersects;
  26958. }
  26959. }
  26960. function ascSort(a, b) {
  26961. return a.distance - b.distance;
  26962. }
  26963. function intersectObject(object, raycaster, intersects, recursive) {
  26964. if (object.layers.test(raycaster.layers)) {
  26965. object.raycast(raycaster, intersects);
  26966. }
  26967. if (recursive === true) {
  26968. const children = object.children;
  26969. for (let i = 0, l = children.length; i < l; i++) {
  26970. intersectObject(children[i], raycaster, intersects, true);
  26971. }
  26972. }
  26973. }
  26974. /**
  26975. * Ref: https://en.wikipedia.org/wiki/Spherical_coordinate_system
  26976. *
  26977. * The polar angle (phi) is measured from the positive y-axis. The positive y-axis is up.
  26978. * The azimuthal angle (theta) is measured from the positive z-axis.
  26979. */
  26980. class Spherical {
  26981. constructor(radius = 1, phi = 0, theta = 0) {
  26982. this.radius = radius;
  26983. this.phi = phi; // polar angle
  26984. this.theta = theta; // azimuthal angle
  26985. return this;
  26986. }
  26987. set(radius, phi, theta) {
  26988. this.radius = radius;
  26989. this.phi = phi;
  26990. this.theta = theta;
  26991. return this;
  26992. }
  26993. copy(other) {
  26994. this.radius = other.radius;
  26995. this.phi = other.phi;
  26996. this.theta = other.theta;
  26997. return this;
  26998. } // restrict phi to be between EPS and PI-EPS
  26999. makeSafe() {
  27000. const EPS = 0.000001;
  27001. this.phi = Math.max(EPS, Math.min(Math.PI - EPS, this.phi));
  27002. return this;
  27003. }
  27004. setFromVector3(v) {
  27005. return this.setFromCartesianCoords(v.x, v.y, v.z);
  27006. }
  27007. setFromCartesianCoords(x, y, z) {
  27008. this.radius = Math.sqrt(x * x + y * y + z * z);
  27009. if (this.radius === 0) {
  27010. this.theta = 0;
  27011. this.phi = 0;
  27012. } else {
  27013. this.theta = Math.atan2(x, z);
  27014. this.phi = Math.acos(clamp(y / this.radius, -1, 1));
  27015. }
  27016. return this;
  27017. }
  27018. clone() {
  27019. return new this.constructor().copy(this);
  27020. }
  27021. }
  27022. /**
  27023. * Ref: https://en.wikipedia.org/wiki/Cylindrical_coordinate_system
  27024. */
  27025. class Cylindrical {
  27026. constructor(radius = 1, theta = 0, y = 0) {
  27027. this.radius = radius; // distance from the origin to a point in the x-z plane
  27028. this.theta = theta; // counterclockwise angle in the x-z plane measured in radians from the positive z-axis
  27029. this.y = y; // height above the x-z plane
  27030. return this;
  27031. }
  27032. set(radius, theta, y) {
  27033. this.radius = radius;
  27034. this.theta = theta;
  27035. this.y = y;
  27036. return this;
  27037. }
  27038. copy(other) {
  27039. this.radius = other.radius;
  27040. this.theta = other.theta;
  27041. this.y = other.y;
  27042. return this;
  27043. }
  27044. setFromVector3(v) {
  27045. return this.setFromCartesianCoords(v.x, v.y, v.z);
  27046. }
  27047. setFromCartesianCoords(x, y, z) {
  27048. this.radius = Math.sqrt(x * x + z * z);
  27049. this.theta = Math.atan2(x, z);
  27050. this.y = y;
  27051. return this;
  27052. }
  27053. clone() {
  27054. return new this.constructor().copy(this);
  27055. }
  27056. }
  27057. const _vector$4 = /*@__PURE__*/new Vector2();
  27058. class Box2 {
  27059. constructor(min = new Vector2(+Infinity, +Infinity), max = new Vector2(-Infinity, -Infinity)) {
  27060. this.isBox2 = true;
  27061. this.min = min;
  27062. this.max = max;
  27063. }
  27064. set(min, max) {
  27065. this.min.copy(min);
  27066. this.max.copy(max);
  27067. return this;
  27068. }
  27069. setFromPoints(points) {
  27070. this.makeEmpty();
  27071. for (let i = 0, il = points.length; i < il; i++) {
  27072. this.expandByPoint(points[i]);
  27073. }
  27074. return this;
  27075. }
  27076. setFromCenterAndSize(center, size) {
  27077. const halfSize = _vector$4.copy(size).multiplyScalar(0.5);
  27078. this.min.copy(center).sub(halfSize);
  27079. this.max.copy(center).add(halfSize);
  27080. return this;
  27081. }
  27082. clone() {
  27083. return new this.constructor().copy(this);
  27084. }
  27085. copy(box) {
  27086. this.min.copy(box.min);
  27087. this.max.copy(box.max);
  27088. return this;
  27089. }
  27090. makeEmpty() {
  27091. this.min.x = this.min.y = +Infinity;
  27092. this.max.x = this.max.y = -Infinity;
  27093. return this;
  27094. }
  27095. isEmpty() {
  27096. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  27097. return this.max.x < this.min.x || this.max.y < this.min.y;
  27098. }
  27099. getCenter(target) {
  27100. return this.isEmpty() ? target.set(0, 0) : target.addVectors(this.min, this.max).multiplyScalar(0.5);
  27101. }
  27102. getSize(target) {
  27103. return this.isEmpty() ? target.set(0, 0) : target.subVectors(this.max, this.min);
  27104. }
  27105. expandByPoint(point) {
  27106. this.min.min(point);
  27107. this.max.max(point);
  27108. return this;
  27109. }
  27110. expandByVector(vector) {
  27111. this.min.sub(vector);
  27112. this.max.add(vector);
  27113. return this;
  27114. }
  27115. expandByScalar(scalar) {
  27116. this.min.addScalar(-scalar);
  27117. this.max.addScalar(scalar);
  27118. return this;
  27119. }
  27120. containsPoint(point) {
  27121. return point.x < this.min.x || point.x > this.max.x || point.y < this.min.y || point.y > this.max.y ? false : true;
  27122. }
  27123. containsBox(box) {
  27124. 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;
  27125. }
  27126. getParameter(point, target) {
  27127. // This can potentially have a divide by zero if the box
  27128. // has a size dimension of 0.
  27129. 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));
  27130. }
  27131. intersectsBox(box) {
  27132. // using 4 splitting planes to rule out intersections
  27133. 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;
  27134. }
  27135. clampPoint(point, target) {
  27136. return target.copy(point).clamp(this.min, this.max);
  27137. }
  27138. distanceToPoint(point) {
  27139. const clampedPoint = _vector$4.copy(point).clamp(this.min, this.max);
  27140. return clampedPoint.sub(point).length();
  27141. }
  27142. intersect(box) {
  27143. this.min.max(box.min);
  27144. this.max.min(box.max);
  27145. return this;
  27146. }
  27147. union(box) {
  27148. this.min.min(box.min);
  27149. this.max.max(box.max);
  27150. return this;
  27151. }
  27152. translate(offset) {
  27153. this.min.add(offset);
  27154. this.max.add(offset);
  27155. return this;
  27156. }
  27157. equals(box) {
  27158. return box.min.equals(this.min) && box.max.equals(this.max);
  27159. }
  27160. }
  27161. const _startP = /*@__PURE__*/new Vector3();
  27162. const _startEnd = /*@__PURE__*/new Vector3();
  27163. class Line3 {
  27164. constructor(start = new Vector3(), end = new Vector3()) {
  27165. this.start = start;
  27166. this.end = end;
  27167. }
  27168. set(start, end) {
  27169. this.start.copy(start);
  27170. this.end.copy(end);
  27171. return this;
  27172. }
  27173. copy(line) {
  27174. this.start.copy(line.start);
  27175. this.end.copy(line.end);
  27176. return this;
  27177. }
  27178. getCenter(target) {
  27179. return target.addVectors(this.start, this.end).multiplyScalar(0.5);
  27180. }
  27181. delta(target) {
  27182. return target.subVectors(this.end, this.start);
  27183. }
  27184. distanceSq() {
  27185. return this.start.distanceToSquared(this.end);
  27186. }
  27187. distance() {
  27188. return this.start.distanceTo(this.end);
  27189. }
  27190. at(t, target) {
  27191. return this.delta(target).multiplyScalar(t).add(this.start);
  27192. }
  27193. closestPointToPointParameter(point, clampToLine) {
  27194. _startP.subVectors(point, this.start);
  27195. _startEnd.subVectors(this.end, this.start);
  27196. const startEnd2 = _startEnd.dot(_startEnd);
  27197. const startEnd_startP = _startEnd.dot(_startP);
  27198. let t = startEnd_startP / startEnd2;
  27199. if (clampToLine) {
  27200. t = clamp(t, 0, 1);
  27201. }
  27202. return t;
  27203. }
  27204. closestPointToPoint(point, clampToLine, target) {
  27205. const t = this.closestPointToPointParameter(point, clampToLine);
  27206. return this.delta(target).multiplyScalar(t).add(this.start);
  27207. }
  27208. applyMatrix4(matrix) {
  27209. this.start.applyMatrix4(matrix);
  27210. this.end.applyMatrix4(matrix);
  27211. return this;
  27212. }
  27213. equals(line) {
  27214. return line.start.equals(this.start) && line.end.equals(this.end);
  27215. }
  27216. clone() {
  27217. return new this.constructor().copy(this);
  27218. }
  27219. }
  27220. const _vector$3 = /*@__PURE__*/new Vector3();
  27221. class SpotLightHelper extends Object3D {
  27222. constructor(light, color) {
  27223. super();
  27224. this.light = light;
  27225. this.light.updateMatrixWorld();
  27226. this.matrix = light.matrixWorld;
  27227. this.matrixAutoUpdate = false;
  27228. this.color = color;
  27229. const geometry = new BufferGeometry();
  27230. 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];
  27231. for (let i = 0, j = 1, l = 32; i < l; i++, j++) {
  27232. const p1 = i / l * Math.PI * 2;
  27233. const p2 = j / l * Math.PI * 2;
  27234. positions.push(Math.cos(p1), Math.sin(p1), 1, Math.cos(p2), Math.sin(p2), 1);
  27235. }
  27236. geometry.setAttribute('position', new Float32BufferAttribute(positions, 3));
  27237. const material = new LineBasicMaterial({
  27238. fog: false,
  27239. toneMapped: false
  27240. });
  27241. this.cone = new LineSegments(geometry, material);
  27242. this.add(this.cone);
  27243. this.update();
  27244. }
  27245. dispose() {
  27246. this.cone.geometry.dispose();
  27247. this.cone.material.dispose();
  27248. }
  27249. update() {
  27250. this.light.updateMatrixWorld();
  27251. const coneLength = this.light.distance ? this.light.distance : 1000;
  27252. const coneWidth = coneLength * Math.tan(this.light.angle);
  27253. this.cone.scale.set(coneWidth, coneWidth, coneLength);
  27254. _vector$3.setFromMatrixPosition(this.light.target.matrixWorld);
  27255. this.cone.lookAt(_vector$3);
  27256. if (this.color !== undefined) {
  27257. this.cone.material.color.set(this.color);
  27258. } else {
  27259. this.cone.material.color.copy(this.light.color);
  27260. }
  27261. }
  27262. }
  27263. const _vector$2 = /*@__PURE__*/new Vector3();
  27264. const _boneMatrix = /*@__PURE__*/new Matrix4();
  27265. const _matrixWorldInv = /*@__PURE__*/new Matrix4();
  27266. class SkeletonHelper extends LineSegments {
  27267. constructor(object) {
  27268. const bones = getBoneList(object);
  27269. const geometry = new BufferGeometry();
  27270. const vertices = [];
  27271. const colors = [];
  27272. const color1 = new Color(0, 0, 1);
  27273. const color2 = new Color(0, 1, 0);
  27274. for (let i = 0; i < bones.length; i++) {
  27275. const bone = bones[i];
  27276. if (bone.parent && bone.parent.isBone) {
  27277. vertices.push(0, 0, 0);
  27278. vertices.push(0, 0, 0);
  27279. colors.push(color1.r, color1.g, color1.b);
  27280. colors.push(color2.r, color2.g, color2.b);
  27281. }
  27282. }
  27283. geometry.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  27284. geometry.setAttribute('color', new Float32BufferAttribute(colors, 3));
  27285. const material = new LineBasicMaterial({
  27286. vertexColors: true,
  27287. depthTest: false,
  27288. depthWrite: false,
  27289. toneMapped: false,
  27290. transparent: true
  27291. });
  27292. super(geometry, material);
  27293. this.isSkeletonHelper = true;
  27294. this.type = 'SkeletonHelper';
  27295. this.root = object;
  27296. this.bones = bones;
  27297. this.matrix = object.matrixWorld;
  27298. this.matrixAutoUpdate = false;
  27299. }
  27300. updateMatrixWorld(force) {
  27301. const bones = this.bones;
  27302. const geometry = this.geometry;
  27303. const position = geometry.getAttribute('position');
  27304. _matrixWorldInv.copy(this.root.matrixWorld).invert();
  27305. for (let i = 0, j = 0; i < bones.length; i++) {
  27306. const bone = bones[i];
  27307. if (bone.parent && bone.parent.isBone) {
  27308. _boneMatrix.multiplyMatrices(_matrixWorldInv, bone.matrixWorld);
  27309. _vector$2.setFromMatrixPosition(_boneMatrix);
  27310. position.setXYZ(j, _vector$2.x, _vector$2.y, _vector$2.z);
  27311. _boneMatrix.multiplyMatrices(_matrixWorldInv, bone.parent.matrixWorld);
  27312. _vector$2.setFromMatrixPosition(_boneMatrix);
  27313. position.setXYZ(j + 1, _vector$2.x, _vector$2.y, _vector$2.z);
  27314. j += 2;
  27315. }
  27316. }
  27317. geometry.getAttribute('position').needsUpdate = true;
  27318. super.updateMatrixWorld(force);
  27319. }
  27320. }
  27321. function getBoneList(object) {
  27322. const boneList = [];
  27323. if (object.isBone === true) {
  27324. boneList.push(object);
  27325. }
  27326. for (let i = 0; i < object.children.length; i++) {
  27327. boneList.push.apply(boneList, getBoneList(object.children[i]));
  27328. }
  27329. return boneList;
  27330. }
  27331. class PointLightHelper extends Mesh {
  27332. constructor(light, sphereSize, color) {
  27333. const geometry = new SphereGeometry(sphereSize, 4, 2);
  27334. const material = new MeshBasicMaterial({
  27335. wireframe: true,
  27336. fog: false,
  27337. toneMapped: false
  27338. });
  27339. super(geometry, material);
  27340. this.light = light;
  27341. this.light.updateMatrixWorld();
  27342. this.color = color;
  27343. this.type = 'PointLightHelper';
  27344. this.matrix = this.light.matrixWorld;
  27345. this.matrixAutoUpdate = false;
  27346. this.update();
  27347. /*
  27348. // TODO: delete this comment?
  27349. const distanceGeometry = new THREE.IcosahedronGeometry( 1, 2 );
  27350. const distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  27351. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  27352. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  27353. const d = light.distance;
  27354. if ( d === 0.0 ) {
  27355. this.lightDistance.visible = false;
  27356. } else {
  27357. this.lightDistance.scale.set( d, d, d );
  27358. }
  27359. this.add( this.lightDistance );
  27360. */
  27361. }
  27362. dispose() {
  27363. this.geometry.dispose();
  27364. this.material.dispose();
  27365. }
  27366. update() {
  27367. if (this.color !== undefined) {
  27368. this.material.color.set(this.color);
  27369. } else {
  27370. this.material.color.copy(this.light.color);
  27371. }
  27372. /*
  27373. const d = this.light.distance;
  27374. if ( d === 0.0 ) {
  27375. this.lightDistance.visible = false;
  27376. } else {
  27377. this.lightDistance.visible = true;
  27378. this.lightDistance.scale.set( d, d, d );
  27379. }
  27380. */
  27381. }
  27382. }
  27383. const _vector$1 = /*@__PURE__*/new Vector3();
  27384. const _color1 = /*@__PURE__*/new Color();
  27385. const _color2 = /*@__PURE__*/new Color();
  27386. class HemisphereLightHelper extends Object3D {
  27387. constructor(light, size, color) {
  27388. super();
  27389. this.light = light;
  27390. this.light.updateMatrixWorld();
  27391. this.matrix = light.matrixWorld;
  27392. this.matrixAutoUpdate = false;
  27393. this.color = color;
  27394. const geometry = new OctahedronGeometry(size);
  27395. geometry.rotateY(Math.PI * 0.5);
  27396. this.material = new MeshBasicMaterial({
  27397. wireframe: true,
  27398. fog: false,
  27399. toneMapped: false
  27400. });
  27401. if (this.color === undefined) this.material.vertexColors = true;
  27402. const position = geometry.getAttribute('position');
  27403. const colors = new Float32Array(position.count * 3);
  27404. geometry.setAttribute('color', new BufferAttribute(colors, 3));
  27405. this.add(new Mesh(geometry, this.material));
  27406. this.update();
  27407. }
  27408. dispose() {
  27409. this.children[0].geometry.dispose();
  27410. this.children[0].material.dispose();
  27411. }
  27412. update() {
  27413. const mesh = this.children[0];
  27414. if (this.color !== undefined) {
  27415. this.material.color.set(this.color);
  27416. } else {
  27417. const colors = mesh.geometry.getAttribute('color');
  27418. _color1.copy(this.light.color);
  27419. _color2.copy(this.light.groundColor);
  27420. for (let i = 0, l = colors.count; i < l; i++) {
  27421. const color = i < l / 2 ? _color1 : _color2;
  27422. colors.setXYZ(i, color.r, color.g, color.b);
  27423. }
  27424. colors.needsUpdate = true;
  27425. }
  27426. mesh.lookAt(_vector$1.setFromMatrixPosition(this.light.matrixWorld).negate());
  27427. }
  27428. }
  27429. class GridHelper extends LineSegments {
  27430. constructor(size = 10, divisions = 10, color1 = 0x444444, color2 = 0x888888) {
  27431. color1 = new Color(color1);
  27432. color2 = new Color(color2);
  27433. const center = divisions / 2;
  27434. const step = size / divisions;
  27435. const halfSize = size / 2;
  27436. const vertices = [],
  27437. colors = [];
  27438. for (let i = 0, j = 0, k = -halfSize; i <= divisions; i++, k += step) {
  27439. vertices.push(-halfSize, 0, k, halfSize, 0, k);
  27440. vertices.push(k, 0, -halfSize, k, 0, halfSize);
  27441. const color = i === center ? color1 : color2;
  27442. color.toArray(colors, j);
  27443. j += 3;
  27444. color.toArray(colors, j);
  27445. j += 3;
  27446. color.toArray(colors, j);
  27447. j += 3;
  27448. color.toArray(colors, j);
  27449. j += 3;
  27450. }
  27451. const geometry = new BufferGeometry();
  27452. geometry.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  27453. geometry.setAttribute('color', new Float32BufferAttribute(colors, 3));
  27454. const material = new LineBasicMaterial({
  27455. vertexColors: true,
  27456. toneMapped: false
  27457. });
  27458. super(geometry, material);
  27459. this.type = 'GridHelper';
  27460. }
  27461. }
  27462. class PolarGridHelper extends LineSegments {
  27463. constructor(radius = 10, radials = 16, circles = 8, divisions = 64, color1 = 0x444444, color2 = 0x888888) {
  27464. color1 = new Color(color1);
  27465. color2 = new Color(color2);
  27466. const vertices = [];
  27467. const colors = []; // create the radials
  27468. for (let i = 0; i <= radials; i++) {
  27469. const v = i / radials * (Math.PI * 2);
  27470. const x = Math.sin(v) * radius;
  27471. const z = Math.cos(v) * radius;
  27472. vertices.push(0, 0, 0);
  27473. vertices.push(x, 0, z);
  27474. const color = i & 1 ? color1 : color2;
  27475. colors.push(color.r, color.g, color.b);
  27476. colors.push(color.r, color.g, color.b);
  27477. } // create the circles
  27478. for (let i = 0; i <= circles; i++) {
  27479. const color = i & 1 ? color1 : color2;
  27480. const r = radius - radius / circles * i;
  27481. for (let j = 0; j < divisions; j++) {
  27482. // first vertex
  27483. let v = j / divisions * (Math.PI * 2);
  27484. let x = Math.sin(v) * r;
  27485. let z = Math.cos(v) * r;
  27486. vertices.push(x, 0, z);
  27487. colors.push(color.r, color.g, color.b); // second vertex
  27488. v = (j + 1) / divisions * (Math.PI * 2);
  27489. x = Math.sin(v) * r;
  27490. z = Math.cos(v) * r;
  27491. vertices.push(x, 0, z);
  27492. colors.push(color.r, color.g, color.b);
  27493. }
  27494. }
  27495. const geometry = new BufferGeometry();
  27496. geometry.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  27497. geometry.setAttribute('color', new Float32BufferAttribute(colors, 3));
  27498. const material = new LineBasicMaterial({
  27499. vertexColors: true,
  27500. toneMapped: false
  27501. });
  27502. super(geometry, material);
  27503. this.type = 'PolarGridHelper';
  27504. }
  27505. }
  27506. const _v1 = /*@__PURE__*/new Vector3();
  27507. const _v2 = /*@__PURE__*/new Vector3();
  27508. const _v3 = /*@__PURE__*/new Vector3();
  27509. class DirectionalLightHelper extends Object3D {
  27510. constructor(light, size, color) {
  27511. super();
  27512. this.light = light;
  27513. this.light.updateMatrixWorld();
  27514. this.matrix = light.matrixWorld;
  27515. this.matrixAutoUpdate = false;
  27516. this.color = color;
  27517. if (size === undefined) size = 1;
  27518. let geometry = new BufferGeometry();
  27519. geometry.setAttribute('position', new Float32BufferAttribute([-size, size, 0, size, size, 0, size, -size, 0, -size, -size, 0, -size, size, 0], 3));
  27520. const material = new LineBasicMaterial({
  27521. fog: false,
  27522. toneMapped: false
  27523. });
  27524. this.lightPlane = new Line(geometry, material);
  27525. this.add(this.lightPlane);
  27526. geometry = new BufferGeometry();
  27527. geometry.setAttribute('position', new Float32BufferAttribute([0, 0, 0, 0, 0, 1], 3));
  27528. this.targetLine = new Line(geometry, material);
  27529. this.add(this.targetLine);
  27530. this.update();
  27531. }
  27532. dispose() {
  27533. this.lightPlane.geometry.dispose();
  27534. this.lightPlane.material.dispose();
  27535. this.targetLine.geometry.dispose();
  27536. this.targetLine.material.dispose();
  27537. }
  27538. update() {
  27539. _v1.setFromMatrixPosition(this.light.matrixWorld);
  27540. _v2.setFromMatrixPosition(this.light.target.matrixWorld);
  27541. _v3.subVectors(_v2, _v1);
  27542. this.lightPlane.lookAt(_v2);
  27543. if (this.color !== undefined) {
  27544. this.lightPlane.material.color.set(this.color);
  27545. this.targetLine.material.color.set(this.color);
  27546. } else {
  27547. this.lightPlane.material.color.copy(this.light.color);
  27548. this.targetLine.material.color.copy(this.light.color);
  27549. }
  27550. this.targetLine.lookAt(_v2);
  27551. this.targetLine.scale.z = _v3.length();
  27552. }
  27553. }
  27554. const _vector = /*@__PURE__*/new Vector3();
  27555. const _camera = /*@__PURE__*/new Camera();
  27556. /**
  27557. * - shows frustum, line of sight and up of the camera
  27558. * - suitable for fast updates
  27559. * - based on frustum visualization in lightgl.js shadowmap example
  27560. * https://github.com/evanw/lightgl.js/blob/master/tests/shadowmap.html
  27561. */
  27562. class CameraHelper extends LineSegments {
  27563. constructor(camera) {
  27564. const geometry = new BufferGeometry();
  27565. const material = new LineBasicMaterial({
  27566. color: 0xffffff,
  27567. vertexColors: true,
  27568. toneMapped: false
  27569. });
  27570. const vertices = [];
  27571. const colors = [];
  27572. const pointMap = {}; // colors
  27573. const colorFrustum = new Color(0xffaa00);
  27574. const colorCone = new Color(0xff0000);
  27575. const colorUp = new Color(0x00aaff);
  27576. const colorTarget = new Color(0xffffff);
  27577. const colorCross = new Color(0x333333); // near
  27578. addLine('n1', 'n2', colorFrustum);
  27579. addLine('n2', 'n4', colorFrustum);
  27580. addLine('n4', 'n3', colorFrustum);
  27581. addLine('n3', 'n1', colorFrustum); // far
  27582. addLine('f1', 'f2', colorFrustum);
  27583. addLine('f2', 'f4', colorFrustum);
  27584. addLine('f4', 'f3', colorFrustum);
  27585. addLine('f3', 'f1', colorFrustum); // sides
  27586. addLine('n1', 'f1', colorFrustum);
  27587. addLine('n2', 'f2', colorFrustum);
  27588. addLine('n3', 'f3', colorFrustum);
  27589. addLine('n4', 'f4', colorFrustum); // cone
  27590. addLine('p', 'n1', colorCone);
  27591. addLine('p', 'n2', colorCone);
  27592. addLine('p', 'n3', colorCone);
  27593. addLine('p', 'n4', colorCone); // up
  27594. addLine('u1', 'u2', colorUp);
  27595. addLine('u2', 'u3', colorUp);
  27596. addLine('u3', 'u1', colorUp); // target
  27597. addLine('c', 't', colorTarget);
  27598. addLine('p', 'c', colorCross); // cross
  27599. addLine('cn1', 'cn2', colorCross);
  27600. addLine('cn3', 'cn4', colorCross);
  27601. addLine('cf1', 'cf2', colorCross);
  27602. addLine('cf3', 'cf4', colorCross);
  27603. function addLine(a, b, color) {
  27604. addPoint(a, color);
  27605. addPoint(b, color);
  27606. }
  27607. function addPoint(id, color) {
  27608. vertices.push(0, 0, 0);
  27609. colors.push(color.r, color.g, color.b);
  27610. if (pointMap[id] === undefined) {
  27611. pointMap[id] = [];
  27612. }
  27613. pointMap[id].push(vertices.length / 3 - 1);
  27614. }
  27615. geometry.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  27616. geometry.setAttribute('color', new Float32BufferAttribute(colors, 3));
  27617. super(geometry, material);
  27618. this.type = 'CameraHelper';
  27619. this.camera = camera;
  27620. if (this.camera.updateProjectionMatrix) this.camera.updateProjectionMatrix();
  27621. this.matrix = camera.matrixWorld;
  27622. this.matrixAutoUpdate = false;
  27623. this.pointMap = pointMap;
  27624. this.update();
  27625. }
  27626. update() {
  27627. const geometry = this.geometry;
  27628. const pointMap = this.pointMap;
  27629. const w = 1,
  27630. h = 1; // we need just camera projection matrix inverse
  27631. // world matrix must be identity
  27632. _camera.projectionMatrixInverse.copy(this.camera.projectionMatrixInverse); // center / target
  27633. setPoint('c', pointMap, geometry, _camera, 0, 0, -1);
  27634. setPoint('t', pointMap, geometry, _camera, 0, 0, 1); // near
  27635. setPoint('n1', pointMap, geometry, _camera, -w, -h, -1);
  27636. setPoint('n2', pointMap, geometry, _camera, w, -h, -1);
  27637. setPoint('n3', pointMap, geometry, _camera, -w, h, -1);
  27638. setPoint('n4', pointMap, geometry, _camera, w, h, -1); // far
  27639. setPoint('f1', pointMap, geometry, _camera, -w, -h, 1);
  27640. setPoint('f2', pointMap, geometry, _camera, w, -h, 1);
  27641. setPoint('f3', pointMap, geometry, _camera, -w, h, 1);
  27642. setPoint('f4', pointMap, geometry, _camera, w, h, 1); // up
  27643. setPoint('u1', pointMap, geometry, _camera, w * 0.7, h * 1.1, -1);
  27644. setPoint('u2', pointMap, geometry, _camera, -w * 0.7, h * 1.1, -1);
  27645. setPoint('u3', pointMap, geometry, _camera, 0, h * 2, -1); // cross
  27646. setPoint('cf1', pointMap, geometry, _camera, -w, 0, 1);
  27647. setPoint('cf2', pointMap, geometry, _camera, w, 0, 1);
  27648. setPoint('cf3', pointMap, geometry, _camera, 0, -h, 1);
  27649. setPoint('cf4', pointMap, geometry, _camera, 0, h, 1);
  27650. setPoint('cn1', pointMap, geometry, _camera, -w, 0, -1);
  27651. setPoint('cn2', pointMap, geometry, _camera, w, 0, -1);
  27652. setPoint('cn3', pointMap, geometry, _camera, 0, -h, -1);
  27653. setPoint('cn4', pointMap, geometry, _camera, 0, h, -1);
  27654. geometry.getAttribute('position').needsUpdate = true;
  27655. }
  27656. dispose() {
  27657. this.geometry.dispose();
  27658. this.material.dispose();
  27659. }
  27660. }
  27661. function setPoint(point, pointMap, geometry, camera, x, y, z) {
  27662. _vector.set(x, y, z).unproject(camera);
  27663. const points = pointMap[point];
  27664. if (points !== undefined) {
  27665. const position = geometry.getAttribute('position');
  27666. for (let i = 0, l = points.length; i < l; i++) {
  27667. position.setXYZ(points[i], _vector.x, _vector.y, _vector.z);
  27668. }
  27669. }
  27670. }
  27671. const _box = /*@__PURE__*/new Box3();
  27672. class BoxHelper extends LineSegments {
  27673. constructor(object, color = 0xffff00) {
  27674. 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]);
  27675. const positions = new Float32Array(8 * 3);
  27676. const geometry = new BufferGeometry();
  27677. geometry.setIndex(new BufferAttribute(indices, 1));
  27678. geometry.setAttribute('position', new BufferAttribute(positions, 3));
  27679. super(geometry, new LineBasicMaterial({
  27680. color: color,
  27681. toneMapped: false
  27682. }));
  27683. this.object = object;
  27684. this.type = 'BoxHelper';
  27685. this.matrixAutoUpdate = false;
  27686. this.update();
  27687. }
  27688. update(object) {
  27689. if (object !== undefined) {
  27690. console.warn('THREE.BoxHelper: .update() has no longer arguments.');
  27691. }
  27692. if (this.object !== undefined) {
  27693. _box.setFromObject(this.object);
  27694. }
  27695. if (_box.isEmpty()) return;
  27696. const min = _box.min;
  27697. const max = _box.max;
  27698. /*
  27699. 5____4
  27700. 1/___0/|
  27701. | 6__|_7
  27702. 2/___3/
  27703. 0: max.x, max.y, max.z
  27704. 1: min.x, max.y, max.z
  27705. 2: min.x, min.y, max.z
  27706. 3: max.x, min.y, max.z
  27707. 4: max.x, max.y, min.z
  27708. 5: min.x, max.y, min.z
  27709. 6: min.x, min.y, min.z
  27710. 7: max.x, min.y, min.z
  27711. */
  27712. const position = this.geometry.attributes.position;
  27713. const array = position.array;
  27714. array[0] = max.x;
  27715. array[1] = max.y;
  27716. array[2] = max.z;
  27717. array[3] = min.x;
  27718. array[4] = max.y;
  27719. array[5] = max.z;
  27720. array[6] = min.x;
  27721. array[7] = min.y;
  27722. array[8] = max.z;
  27723. array[9] = max.x;
  27724. array[10] = min.y;
  27725. array[11] = max.z;
  27726. array[12] = max.x;
  27727. array[13] = max.y;
  27728. array[14] = min.z;
  27729. array[15] = min.x;
  27730. array[16] = max.y;
  27731. array[17] = min.z;
  27732. array[18] = min.x;
  27733. array[19] = min.y;
  27734. array[20] = min.z;
  27735. array[21] = max.x;
  27736. array[22] = min.y;
  27737. array[23] = min.z;
  27738. position.needsUpdate = true;
  27739. this.geometry.computeBoundingSphere();
  27740. }
  27741. setFromObject(object) {
  27742. this.object = object;
  27743. this.update();
  27744. return this;
  27745. }
  27746. copy(source) {
  27747. LineSegments.prototype.copy.call(this, source);
  27748. this.object = source.object;
  27749. return this;
  27750. }
  27751. }
  27752. class Box3Helper extends LineSegments {
  27753. constructor(box, color = 0xffff00) {
  27754. 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]);
  27755. 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];
  27756. const geometry = new BufferGeometry();
  27757. geometry.setIndex(new BufferAttribute(indices, 1));
  27758. geometry.setAttribute('position', new Float32BufferAttribute(positions, 3));
  27759. super(geometry, new LineBasicMaterial({
  27760. color: color,
  27761. toneMapped: false
  27762. }));
  27763. this.box = box;
  27764. this.type = 'Box3Helper';
  27765. this.geometry.computeBoundingSphere();
  27766. }
  27767. updateMatrixWorld(force) {
  27768. const box = this.box;
  27769. if (box.isEmpty()) return;
  27770. box.getCenter(this.position);
  27771. box.getSize(this.scale);
  27772. this.scale.multiplyScalar(0.5);
  27773. super.updateMatrixWorld(force);
  27774. }
  27775. }
  27776. class PlaneHelper extends Line {
  27777. constructor(plane, size = 1, hex = 0xffff00) {
  27778. const color = hex;
  27779. 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];
  27780. const geometry = new BufferGeometry();
  27781. geometry.setAttribute('position', new Float32BufferAttribute(positions, 3));
  27782. geometry.computeBoundingSphere();
  27783. super(geometry, new LineBasicMaterial({
  27784. color: color,
  27785. toneMapped: false
  27786. }));
  27787. this.type = 'PlaneHelper';
  27788. this.plane = plane;
  27789. this.size = size;
  27790. const positions2 = [1, 1, 1, -1, 1, 1, -1, -1, 1, 1, 1, 1, -1, -1, 1, 1, -1, 1];
  27791. const geometry2 = new BufferGeometry();
  27792. geometry2.setAttribute('position', new Float32BufferAttribute(positions2, 3));
  27793. geometry2.computeBoundingSphere();
  27794. this.add(new Mesh(geometry2, new MeshBasicMaterial({
  27795. color: color,
  27796. opacity: 0.2,
  27797. transparent: true,
  27798. depthWrite: false,
  27799. toneMapped: false
  27800. })));
  27801. }
  27802. updateMatrixWorld(force) {
  27803. let scale = -this.plane.constant;
  27804. if (Math.abs(scale) < 1e-8) scale = 1e-8; // sign does not matter
  27805. this.scale.set(0.5 * this.size, 0.5 * this.size, scale);
  27806. this.children[0].material.side = scale < 0 ? BackSide : FrontSide; // renderer flips side when determinant < 0; flipping not wanted here
  27807. this.lookAt(this.plane.normal);
  27808. super.updateMatrixWorld(force);
  27809. }
  27810. }
  27811. const _axis = /*@__PURE__*/new Vector3();
  27812. let _lineGeometry, _coneGeometry;
  27813. class ArrowHelper extends Object3D {
  27814. // dir is assumed to be normalized
  27815. constructor(dir = new Vector3(0, 0, 1), origin = new Vector3(0, 0, 0), length = 1, color = 0xffff00, headLength = length * 0.2, headWidth = headLength * 0.2) {
  27816. super();
  27817. this.type = 'ArrowHelper';
  27818. if (_lineGeometry === undefined) {
  27819. _lineGeometry = new BufferGeometry();
  27820. _lineGeometry.setAttribute('position', new Float32BufferAttribute([0, 0, 0, 0, 1, 0], 3));
  27821. _coneGeometry = new CylinderGeometry(0, 0.5, 1, 5, 1);
  27822. _coneGeometry.translate(0, -0.5, 0);
  27823. }
  27824. this.position.copy(origin);
  27825. this.line = new Line(_lineGeometry, new LineBasicMaterial({
  27826. color: color,
  27827. toneMapped: false
  27828. }));
  27829. this.line.matrixAutoUpdate = false;
  27830. this.add(this.line);
  27831. this.cone = new Mesh(_coneGeometry, new MeshBasicMaterial({
  27832. color: color,
  27833. toneMapped: false
  27834. }));
  27835. this.cone.matrixAutoUpdate = false;
  27836. this.add(this.cone);
  27837. this.setDirection(dir);
  27838. this.setLength(length, headLength, headWidth);
  27839. }
  27840. setDirection(dir) {
  27841. // dir is assumed to be normalized
  27842. if (dir.y > 0.99999) {
  27843. this.quaternion.set(0, 0, 0, 1);
  27844. } else if (dir.y < -0.99999) {
  27845. this.quaternion.set(1, 0, 0, 0);
  27846. } else {
  27847. _axis.set(dir.z, 0, -dir.x).normalize();
  27848. const radians = Math.acos(dir.y);
  27849. this.quaternion.setFromAxisAngle(_axis, radians);
  27850. }
  27851. }
  27852. setLength(length, headLength = length * 0.2, headWidth = headLength * 0.2) {
  27853. this.line.scale.set(1, Math.max(0.0001, length - headLength), 1); // see #17458
  27854. this.line.updateMatrix();
  27855. this.cone.scale.set(headWidth, headLength, headWidth);
  27856. this.cone.position.y = length;
  27857. this.cone.updateMatrix();
  27858. }
  27859. setColor(color) {
  27860. this.line.material.color.set(color);
  27861. this.cone.material.color.set(color);
  27862. }
  27863. copy(source) {
  27864. super.copy(source, false);
  27865. this.line.copy(source.line);
  27866. this.cone.copy(source.cone);
  27867. return this;
  27868. }
  27869. }
  27870. class AxesHelper extends LineSegments {
  27871. constructor(size = 1) {
  27872. const vertices = [0, 0, 0, size, 0, 0, 0, 0, 0, 0, size, 0, 0, 0, 0, 0, 0, size];
  27873. const colors = [1, 0, 0, 1, 0.6, 0, 0, 1, 0, 0.6, 1, 0, 0, 0, 1, 0, 0.6, 1];
  27874. const geometry = new BufferGeometry();
  27875. geometry.setAttribute('position', new Float32BufferAttribute(vertices, 3));
  27876. geometry.setAttribute('color', new Float32BufferAttribute(colors, 3));
  27877. const material = new LineBasicMaterial({
  27878. vertexColors: true,
  27879. toneMapped: false
  27880. });
  27881. super(geometry, material);
  27882. this.type = 'AxesHelper';
  27883. }
  27884. setColors(xAxisColor, yAxisColor, zAxisColor) {
  27885. const color = new Color();
  27886. const array = this.geometry.attributes.color.array;
  27887. color.set(xAxisColor);
  27888. color.toArray(array, 0);
  27889. color.toArray(array, 3);
  27890. color.set(yAxisColor);
  27891. color.toArray(array, 6);
  27892. color.toArray(array, 9);
  27893. color.set(zAxisColor);
  27894. color.toArray(array, 12);
  27895. color.toArray(array, 15);
  27896. this.geometry.attributes.color.needsUpdate = true;
  27897. return this;
  27898. }
  27899. dispose() {
  27900. this.geometry.dispose();
  27901. this.material.dispose();
  27902. }
  27903. }
  27904. class ShapePath {
  27905. constructor() {
  27906. this.type = 'ShapePath';
  27907. this.color = new Color();
  27908. this.subPaths = [];
  27909. this.currentPath = null;
  27910. }
  27911. moveTo(x, y) {
  27912. this.currentPath = new Path();
  27913. this.subPaths.push(this.currentPath);
  27914. this.currentPath.moveTo(x, y);
  27915. return this;
  27916. }
  27917. lineTo(x, y) {
  27918. this.currentPath.lineTo(x, y);
  27919. return this;
  27920. }
  27921. quadraticCurveTo(aCPx, aCPy, aX, aY) {
  27922. this.currentPath.quadraticCurveTo(aCPx, aCPy, aX, aY);
  27923. return this;
  27924. }
  27925. bezierCurveTo(aCP1x, aCP1y, aCP2x, aCP2y, aX, aY) {
  27926. this.currentPath.bezierCurveTo(aCP1x, aCP1y, aCP2x, aCP2y, aX, aY);
  27927. return this;
  27928. }
  27929. splineThru(pts) {
  27930. this.currentPath.splineThru(pts);
  27931. return this;
  27932. }
  27933. toShapes(isCCW, noHoles) {
  27934. function toShapesNoHoles(inSubpaths) {
  27935. const shapes = [];
  27936. for (let i = 0, l = inSubpaths.length; i < l; i++) {
  27937. const tmpPath = inSubpaths[i];
  27938. const tmpShape = new Shape();
  27939. tmpShape.curves = tmpPath.curves;
  27940. shapes.push(tmpShape);
  27941. }
  27942. return shapes;
  27943. }
  27944. function isPointInsidePolygon(inPt, inPolygon) {
  27945. const polyLen = inPolygon.length; // inPt on polygon contour => immediate success or
  27946. // toggling of inside/outside at every single! intersection point of an edge
  27947. // with the horizontal line through inPt, left of inPt
  27948. // not counting lowerY endpoints of edges and whole edges on that line
  27949. let inside = false;
  27950. for (let p = polyLen - 1, q = 0; q < polyLen; p = q++) {
  27951. let edgeLowPt = inPolygon[p];
  27952. let edgeHighPt = inPolygon[q];
  27953. let edgeDx = edgeHighPt.x - edgeLowPt.x;
  27954. let edgeDy = edgeHighPt.y - edgeLowPt.y;
  27955. if (Math.abs(edgeDy) > Number.EPSILON) {
  27956. // not parallel
  27957. if (edgeDy < 0) {
  27958. edgeLowPt = inPolygon[q];
  27959. edgeDx = -edgeDx;
  27960. edgeHighPt = inPolygon[p];
  27961. edgeDy = -edgeDy;
  27962. }
  27963. if (inPt.y < edgeLowPt.y || inPt.y > edgeHighPt.y) continue;
  27964. if (inPt.y === edgeLowPt.y) {
  27965. if (inPt.x === edgeLowPt.x) return true; // inPt is on contour ?
  27966. // continue; // no intersection or edgeLowPt => doesn't count !!!
  27967. } else {
  27968. const perpEdge = edgeDy * (inPt.x - edgeLowPt.x) - edgeDx * (inPt.y - edgeLowPt.y);
  27969. if (perpEdge === 0) return true; // inPt is on contour ?
  27970. if (perpEdge < 0) continue;
  27971. inside = !inside; // true intersection left of inPt
  27972. }
  27973. } else {
  27974. // parallel or collinear
  27975. if (inPt.y !== edgeLowPt.y) continue; // parallel
  27976. // edge lies on the same horizontal line as inPt
  27977. if (edgeHighPt.x <= inPt.x && inPt.x <= edgeLowPt.x || edgeLowPt.x <= inPt.x && inPt.x <= edgeHighPt.x) return true; // inPt: Point on contour !
  27978. // continue;
  27979. }
  27980. }
  27981. return inside;
  27982. }
  27983. const isClockWise = ShapeUtils.isClockWise;
  27984. const subPaths = this.subPaths;
  27985. if (subPaths.length === 0) return [];
  27986. if (noHoles === true) return toShapesNoHoles(subPaths);
  27987. let solid, tmpPath, tmpShape;
  27988. const shapes = [];
  27989. if (subPaths.length === 1) {
  27990. tmpPath = subPaths[0];
  27991. tmpShape = new Shape();
  27992. tmpShape.curves = tmpPath.curves;
  27993. shapes.push(tmpShape);
  27994. return shapes;
  27995. }
  27996. let holesFirst = !isClockWise(subPaths[0].getPoints());
  27997. holesFirst = isCCW ? !holesFirst : holesFirst; // console.log("Holes first", holesFirst);
  27998. const betterShapeHoles = [];
  27999. const newShapes = [];
  28000. let newShapeHoles = [];
  28001. let mainIdx = 0;
  28002. let tmpPoints;
  28003. newShapes[mainIdx] = undefined;
  28004. newShapeHoles[mainIdx] = [];
  28005. for (let i = 0, l = subPaths.length; i < l; i++) {
  28006. tmpPath = subPaths[i];
  28007. tmpPoints = tmpPath.getPoints();
  28008. solid = isClockWise(tmpPoints);
  28009. solid = isCCW ? !solid : solid;
  28010. if (solid) {
  28011. if (!holesFirst && newShapes[mainIdx]) mainIdx++;
  28012. newShapes[mainIdx] = {
  28013. s: new Shape(),
  28014. p: tmpPoints
  28015. };
  28016. newShapes[mainIdx].s.curves = tmpPath.curves;
  28017. if (holesFirst) mainIdx++;
  28018. newShapeHoles[mainIdx] = []; //console.log('cw', i);
  28019. } else {
  28020. newShapeHoles[mainIdx].push({
  28021. h: tmpPath,
  28022. p: tmpPoints[0]
  28023. }); //console.log('ccw', i);
  28024. }
  28025. } // only Holes? -> probably all Shapes with wrong orientation
  28026. if (!newShapes[0]) return toShapesNoHoles(subPaths);
  28027. if (newShapes.length > 1) {
  28028. let ambiguous = false;
  28029. let toChange = 0;
  28030. for (let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx++) {
  28031. betterShapeHoles[sIdx] = [];
  28032. }
  28033. for (let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx++) {
  28034. const sho = newShapeHoles[sIdx];
  28035. for (let hIdx = 0; hIdx < sho.length; hIdx++) {
  28036. const ho = sho[hIdx];
  28037. let hole_unassigned = true;
  28038. for (let s2Idx = 0; s2Idx < newShapes.length; s2Idx++) {
  28039. if (isPointInsidePolygon(ho.p, newShapes[s2Idx].p)) {
  28040. if (sIdx !== s2Idx) toChange++;
  28041. if (hole_unassigned) {
  28042. hole_unassigned = false;
  28043. betterShapeHoles[s2Idx].push(ho);
  28044. } else {
  28045. ambiguous = true;
  28046. }
  28047. }
  28048. }
  28049. if (hole_unassigned) {
  28050. betterShapeHoles[sIdx].push(ho);
  28051. }
  28052. }
  28053. }
  28054. if (toChange > 0 && ambiguous === false) {
  28055. newShapeHoles = betterShapeHoles;
  28056. }
  28057. }
  28058. let tmpHoles;
  28059. for (let i = 0, il = newShapes.length; i < il; i++) {
  28060. tmpShape = newShapes[i].s;
  28061. shapes.push(tmpShape);
  28062. tmpHoles = newShapeHoles[i];
  28063. for (let j = 0, jl = tmpHoles.length; j < jl; j++) {
  28064. tmpShape.holes.push(tmpHoles[j].h);
  28065. }
  28066. } //console.log("shape", shapes);
  28067. return shapes;
  28068. }
  28069. }
  28070. class DataUtils {
  28071. // float32 to float16
  28072. static toHalfFloat(val) {
  28073. if (Math.abs(val) > 65504) console.warn('THREE.DataUtils.toHalfFloat(): Value out of range.');
  28074. val = clamp(val, -65504, 65504);
  28075. _floatView[0] = val;
  28076. const f = _uint32View[0];
  28077. const e = f >> 23 & 0x1ff;
  28078. return _baseTable[e] + ((f & 0x007fffff) >> _shiftTable[e]);
  28079. } // float16 to float32
  28080. static fromHalfFloat(val) {
  28081. const m = val >> 10;
  28082. _uint32View[0] = _mantissaTable[_offsetTable[m] + (val & 0x3ff)] + _exponentTable[m];
  28083. return _floatView[0];
  28084. }
  28085. } // float32 to float16 helpers
  28086. const _buffer = new ArrayBuffer(4);
  28087. const _floatView = new Float32Array(_buffer);
  28088. const _uint32View = new Uint32Array(_buffer);
  28089. const _baseTable = new Uint32Array(512);
  28090. const _shiftTable = new Uint32Array(512);
  28091. for (let i = 0; i < 256; ++i) {
  28092. const e = i - 127; // very small number (0, -0)
  28093. if (e < -27) {
  28094. _baseTable[i] = 0x0000;
  28095. _baseTable[i | 0x100] = 0x8000;
  28096. _shiftTable[i] = 24;
  28097. _shiftTable[i | 0x100] = 24; // small number (denorm)
  28098. } else if (e < -14) {
  28099. _baseTable[i] = 0x0400 >> -e - 14;
  28100. _baseTable[i | 0x100] = 0x0400 >> -e - 14 | 0x8000;
  28101. _shiftTable[i] = -e - 1;
  28102. _shiftTable[i | 0x100] = -e - 1; // normal number
  28103. } else if (e <= 15) {
  28104. _baseTable[i] = e + 15 << 10;
  28105. _baseTable[i | 0x100] = e + 15 << 10 | 0x8000;
  28106. _shiftTable[i] = 13;
  28107. _shiftTable[i | 0x100] = 13; // large number (Infinity, -Infinity)
  28108. } else if (e < 128) {
  28109. _baseTable[i] = 0x7c00;
  28110. _baseTable[i | 0x100] = 0xfc00;
  28111. _shiftTable[i] = 24;
  28112. _shiftTable[i | 0x100] = 24; // stay (NaN, Infinity, -Infinity)
  28113. } else {
  28114. _baseTable[i] = 0x7c00;
  28115. _baseTable[i | 0x100] = 0xfc00;
  28116. _shiftTable[i] = 13;
  28117. _shiftTable[i | 0x100] = 13;
  28118. }
  28119. } // float16 to float32 helpers
  28120. const _mantissaTable = new Uint32Array(2048);
  28121. const _exponentTable = new Uint32Array(64);
  28122. const _offsetTable = new Uint32Array(64);
  28123. for (let i = 1; i < 1024; ++i) {
  28124. let m = i << 13; // zero pad mantissa bits
  28125. let e = 0; // zero exponent
  28126. // normalized
  28127. while ((m & 0x00800000) === 0) {
  28128. m <<= 1;
  28129. e -= 0x00800000; // decrement exponent
  28130. }
  28131. m &= ~0x00800000; // clear leading 1 bit
  28132. e += 0x38800000; // adjust bias
  28133. _mantissaTable[i] = m | e;
  28134. }
  28135. for (let i = 1024; i < 2048; ++i) {
  28136. _mantissaTable[i] = 0x38000000 + (i - 1024 << 13);
  28137. }
  28138. for (let i = 1; i < 31; ++i) {
  28139. _exponentTable[i] = i << 23;
  28140. }
  28141. _exponentTable[31] = 0x47800000;
  28142. _exponentTable[32] = 0x80000000;
  28143. for (let i = 33; i < 63; ++i) {
  28144. _exponentTable[i] = 0x80000000 + (i - 32 << 23);
  28145. }
  28146. _exponentTable[63] = 0xc7800000;
  28147. for (let i = 1; i < 64; ++i) {
  28148. if (i !== 32) {
  28149. _offsetTable[i] = 1024;
  28150. }
  28151. }
  28152. class ParametricGeometry extends BufferGeometry {
  28153. constructor() {
  28154. console.error('THREE.ParametricGeometry has been moved to /examples/jsm/geometries/ParametricGeometry.js');
  28155. super();
  28156. }
  28157. } // r133, eb58ff153119090d3bbb24474ea0ffc40c70dc92
  28158. class TextGeometry extends BufferGeometry {
  28159. constructor() {
  28160. console.error('THREE.TextGeometry has been moved to /examples/jsm/geometries/TextGeometry.js');
  28161. super();
  28162. }
  28163. } // r133, eb58ff153119090d3bbb24474ea0ffc40c70dc92
  28164. function FontLoader() {
  28165. console.error('THREE.FontLoader has been moved to /examples/jsm/loaders/FontLoader.js');
  28166. } // r133, eb58ff153119090d3bbb24474ea0ffc40c70dc92
  28167. function Font() {
  28168. console.error('THREE.Font has been moved to /examples/jsm/loaders/FontLoader.js');
  28169. } // r134, d65e0af06644fe5a84a6fc0e372f4318f95a04c0
  28170. function ImmediateRenderObject() {
  28171. console.error('THREE.ImmediateRenderObject has been removed.');
  28172. } // r138, 48b05d3500acc084df50be9b4c90781ad9b8cb17
  28173. class WebGLMultisampleRenderTarget extends WebGLRenderTarget {
  28174. constructor(width, height, options) {
  28175. console.error('THREE.WebGLMultisampleRenderTarget has been removed. Use a normal render target and set the "samples" property to greater 0 to enable multisampling.');
  28176. super(width, height, options);
  28177. this.samples = 4;
  28178. }
  28179. } // r138, f9cd9cab03b7b64244e304900a3a2eeaa3a588ce
  28180. class DataTexture2DArray extends DataArrayTexture {
  28181. constructor(data, width, height, depth) {
  28182. console.warn('THREE.DataTexture2DArray has been renamed to DataArrayTexture.');
  28183. super(data, width, height, depth);
  28184. }
  28185. } // r138, f9cd9cab03b7b64244e304900a3a2eeaa3a588ce
  28186. class DataTexture3D extends Data3DTexture {
  28187. constructor(data, width, height, depth) {
  28188. console.warn('THREE.DataTexture3D has been renamed to Data3DTexture.');
  28189. super(data, width, height, depth);
  28190. }
  28191. }
  28192. if (typeof __THREE_DEVTOOLS__ !== 'undefined') {
  28193. __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent('register', {
  28194. detail: {
  28195. revision: REVISION
  28196. }
  28197. }));
  28198. }
  28199. if (typeof window !== 'undefined') {
  28200. if (window.__THREE__) {
  28201. console.warn('WARNING: Multiple instances of Three.js being imported.');
  28202. } else {
  28203. window.__THREE__ = REVISION;
  28204. }
  28205. }
  28206. exports.ACESFilmicToneMapping = ACESFilmicToneMapping;
  28207. exports.AddEquation = AddEquation;
  28208. exports.AddOperation = AddOperation;
  28209. exports.AdditiveAnimationBlendMode = AdditiveAnimationBlendMode;
  28210. exports.AdditiveBlending = AdditiveBlending;
  28211. exports.AlphaFormat = AlphaFormat;
  28212. exports.AlwaysDepth = AlwaysDepth;
  28213. exports.AlwaysStencilFunc = AlwaysStencilFunc;
  28214. exports.AmbientLight = AmbientLight;
  28215. exports.AmbientLightProbe = AmbientLightProbe;
  28216. exports.AnimationClip = AnimationClip;
  28217. exports.AnimationLoader = AnimationLoader;
  28218. exports.AnimationMixer = AnimationMixer;
  28219. exports.AnimationObjectGroup = AnimationObjectGroup;
  28220. exports.AnimationUtils = AnimationUtils;
  28221. exports.ArcCurve = ArcCurve;
  28222. exports.ArrayCamera = ArrayCamera;
  28223. exports.ArrowHelper = ArrowHelper;
  28224. exports.Audio = Audio;
  28225. exports.AudioAnalyser = AudioAnalyser;
  28226. exports.AudioContext = AudioContext;
  28227. exports.AudioListener = AudioListener;
  28228. exports.AudioLoader = AudioLoader;
  28229. exports.AxesHelper = AxesHelper;
  28230. exports.BackSide = BackSide;
  28231. exports.BasicDepthPacking = BasicDepthPacking;
  28232. exports.BasicShadowMap = BasicShadowMap;
  28233. exports.Bone = Bone;
  28234. exports.BooleanKeyframeTrack = BooleanKeyframeTrack;
  28235. exports.Box2 = Box2;
  28236. exports.Box3 = Box3;
  28237. exports.Box3Helper = Box3Helper;
  28238. exports.BoxBufferGeometry = BoxGeometry;
  28239. exports.BoxGeometry = BoxGeometry;
  28240. exports.BoxHelper = BoxHelper;
  28241. exports.BufferAttribute = BufferAttribute;
  28242. exports.BufferGeometry = BufferGeometry;
  28243. exports.BufferGeometryLoader = BufferGeometryLoader;
  28244. exports.ByteType = ByteType;
  28245. exports.Cache = Cache;
  28246. exports.Camera = Camera;
  28247. exports.CameraHelper = CameraHelper;
  28248. exports.CanvasTexture = CanvasTexture;
  28249. exports.CapsuleBufferGeometry = CapsuleGeometry;
  28250. exports.CapsuleGeometry = CapsuleGeometry;
  28251. exports.CatmullRomCurve3 = CatmullRomCurve3;
  28252. exports.CineonToneMapping = CineonToneMapping;
  28253. exports.CircleBufferGeometry = CircleGeometry;
  28254. exports.CircleGeometry = CircleGeometry;
  28255. exports.ClampToEdgeWrapping = ClampToEdgeWrapping;
  28256. exports.Clock = Clock;
  28257. exports.Color = Color;
  28258. exports.ColorKeyframeTrack = ColorKeyframeTrack;
  28259. exports.ColorManagement = ColorManagement;
  28260. exports.CompressedTexture = CompressedTexture;
  28261. exports.CompressedTextureLoader = CompressedTextureLoader;
  28262. exports.ConeBufferGeometry = ConeGeometry;
  28263. exports.ConeGeometry = ConeGeometry;
  28264. exports.CubeCamera = CubeCamera;
  28265. exports.CubeReflectionMapping = CubeReflectionMapping;
  28266. exports.CubeRefractionMapping = CubeRefractionMapping;
  28267. exports.CubeTexture = CubeTexture;
  28268. exports.CubeTextureLoader = CubeTextureLoader;
  28269. exports.CubeUVReflectionMapping = CubeUVReflectionMapping;
  28270. exports.CubicBezierCurve = CubicBezierCurve;
  28271. exports.CubicBezierCurve3 = CubicBezierCurve3;
  28272. exports.CubicInterpolant = CubicInterpolant;
  28273. exports.CullFaceBack = CullFaceBack;
  28274. exports.CullFaceFront = CullFaceFront;
  28275. exports.CullFaceFrontBack = CullFaceFrontBack;
  28276. exports.CullFaceNone = CullFaceNone;
  28277. exports.Curve = Curve;
  28278. exports.CurvePath = CurvePath;
  28279. exports.CustomBlending = CustomBlending;
  28280. exports.CustomToneMapping = CustomToneMapping;
  28281. exports.CylinderBufferGeometry = CylinderGeometry;
  28282. exports.CylinderGeometry = CylinderGeometry;
  28283. exports.Cylindrical = Cylindrical;
  28284. exports.Data3DTexture = Data3DTexture;
  28285. exports.DataArrayTexture = DataArrayTexture;
  28286. exports.DataTexture = DataTexture;
  28287. exports.DataTexture2DArray = DataTexture2DArray;
  28288. exports.DataTexture3D = DataTexture3D;
  28289. exports.DataTextureLoader = DataTextureLoader;
  28290. exports.DataUtils = DataUtils;
  28291. exports.DecrementStencilOp = DecrementStencilOp;
  28292. exports.DecrementWrapStencilOp = DecrementWrapStencilOp;
  28293. exports.DefaultLoadingManager = DefaultLoadingManager;
  28294. exports.DepthFormat = DepthFormat;
  28295. exports.DepthStencilFormat = DepthStencilFormat;
  28296. exports.DepthTexture = DepthTexture;
  28297. exports.DirectionalLight = DirectionalLight;
  28298. exports.DirectionalLightHelper = DirectionalLightHelper;
  28299. exports.DiscreteInterpolant = DiscreteInterpolant;
  28300. exports.DodecahedronBufferGeometry = DodecahedronGeometry;
  28301. exports.DodecahedronGeometry = DodecahedronGeometry;
  28302. exports.DoubleSide = DoubleSide;
  28303. exports.DstAlphaFactor = DstAlphaFactor;
  28304. exports.DstColorFactor = DstColorFactor;
  28305. exports.DynamicCopyUsage = DynamicCopyUsage;
  28306. exports.DynamicDrawUsage = DynamicDrawUsage;
  28307. exports.DynamicReadUsage = DynamicReadUsage;
  28308. exports.EdgesGeometry = EdgesGeometry;
  28309. exports.EllipseCurve = EllipseCurve;
  28310. exports.EqualDepth = EqualDepth;
  28311. exports.EqualStencilFunc = EqualStencilFunc;
  28312. exports.EquirectangularReflectionMapping = EquirectangularReflectionMapping;
  28313. exports.EquirectangularRefractionMapping = EquirectangularRefractionMapping;
  28314. exports.Euler = Euler;
  28315. exports.EventDispatcher = EventDispatcher;
  28316. exports.ExtrudeBufferGeometry = ExtrudeGeometry;
  28317. exports.ExtrudeGeometry = ExtrudeGeometry;
  28318. exports.FileLoader = FileLoader;
  28319. exports.FlatShading = FlatShading;
  28320. exports.Float16BufferAttribute = Float16BufferAttribute;
  28321. exports.Float32BufferAttribute = Float32BufferAttribute;
  28322. exports.Float64BufferAttribute = Float64BufferAttribute;
  28323. exports.FloatType = FloatType;
  28324. exports.Fog = Fog;
  28325. exports.FogExp2 = FogExp2;
  28326. exports.Font = Font;
  28327. exports.FontLoader = FontLoader;
  28328. exports.FramebufferTexture = FramebufferTexture;
  28329. exports.FrontSide = FrontSide;
  28330. exports.Frustum = Frustum;
  28331. exports.GLBufferAttribute = GLBufferAttribute;
  28332. exports.GLSL1 = GLSL1;
  28333. exports.GLSL3 = GLSL3;
  28334. exports.GreaterDepth = GreaterDepth;
  28335. exports.GreaterEqualDepth = GreaterEqualDepth;
  28336. exports.GreaterEqualStencilFunc = GreaterEqualStencilFunc;
  28337. exports.GreaterStencilFunc = GreaterStencilFunc;
  28338. exports.GridHelper = GridHelper;
  28339. exports.Group = Group;
  28340. exports.HalfFloatType = HalfFloatType;
  28341. exports.HemisphereLight = HemisphereLight;
  28342. exports.HemisphereLightHelper = HemisphereLightHelper;
  28343. exports.HemisphereLightProbe = HemisphereLightProbe;
  28344. exports.IcosahedronBufferGeometry = IcosahedronGeometry;
  28345. exports.IcosahedronGeometry = IcosahedronGeometry;
  28346. exports.ImageBitmapLoader = ImageBitmapLoader;
  28347. exports.ImageLoader = ImageLoader;
  28348. exports.ImageUtils = ImageUtils;
  28349. exports.ImmediateRenderObject = ImmediateRenderObject;
  28350. exports.IncrementStencilOp = IncrementStencilOp;
  28351. exports.IncrementWrapStencilOp = IncrementWrapStencilOp;
  28352. exports.InstancedBufferAttribute = InstancedBufferAttribute;
  28353. exports.InstancedBufferGeometry = InstancedBufferGeometry;
  28354. exports.InstancedInterleavedBuffer = InstancedInterleavedBuffer;
  28355. exports.InstancedMesh = InstancedMesh;
  28356. exports.Int16BufferAttribute = Int16BufferAttribute;
  28357. exports.Int32BufferAttribute = Int32BufferAttribute;
  28358. exports.Int8BufferAttribute = Int8BufferAttribute;
  28359. exports.IntType = IntType;
  28360. exports.InterleavedBuffer = InterleavedBuffer;
  28361. exports.InterleavedBufferAttribute = InterleavedBufferAttribute;
  28362. exports.Interpolant = Interpolant;
  28363. exports.InterpolateDiscrete = InterpolateDiscrete;
  28364. exports.InterpolateLinear = InterpolateLinear;
  28365. exports.InterpolateSmooth = InterpolateSmooth;
  28366. exports.InvertStencilOp = InvertStencilOp;
  28367. exports.KeepStencilOp = KeepStencilOp;
  28368. exports.KeyframeTrack = KeyframeTrack;
  28369. exports.LOD = LOD;
  28370. exports.LatheBufferGeometry = LatheGeometry;
  28371. exports.LatheGeometry = LatheGeometry;
  28372. exports.Layers = Layers;
  28373. exports.LessDepth = LessDepth;
  28374. exports.LessEqualDepth = LessEqualDepth;
  28375. exports.LessEqualStencilFunc = LessEqualStencilFunc;
  28376. exports.LessStencilFunc = LessStencilFunc;
  28377. exports.Light = Light;
  28378. exports.LightProbe = LightProbe;
  28379. exports.Line = Line;
  28380. exports.Line3 = Line3;
  28381. exports.LineBasicMaterial = LineBasicMaterial;
  28382. exports.LineCurve = LineCurve;
  28383. exports.LineCurve3 = LineCurve3;
  28384. exports.LineDashedMaterial = LineDashedMaterial;
  28385. exports.LineLoop = LineLoop;
  28386. exports.LineSegments = LineSegments;
  28387. exports.LinearEncoding = LinearEncoding;
  28388. exports.LinearFilter = LinearFilter;
  28389. exports.LinearInterpolant = LinearInterpolant;
  28390. exports.LinearMipMapLinearFilter = LinearMipMapLinearFilter;
  28391. exports.LinearMipMapNearestFilter = LinearMipMapNearestFilter;
  28392. exports.LinearMipmapLinearFilter = LinearMipmapLinearFilter;
  28393. exports.LinearMipmapNearestFilter = LinearMipmapNearestFilter;
  28394. exports.LinearSRGBColorSpace = LinearSRGBColorSpace;
  28395. exports.LinearToneMapping = LinearToneMapping;
  28396. exports.Loader = Loader;
  28397. exports.LoaderUtils = LoaderUtils;
  28398. exports.LoadingManager = LoadingManager;
  28399. exports.LoopOnce = LoopOnce;
  28400. exports.LoopPingPong = LoopPingPong;
  28401. exports.LoopRepeat = LoopRepeat;
  28402. exports.LuminanceAlphaFormat = LuminanceAlphaFormat;
  28403. exports.LuminanceFormat = LuminanceFormat;
  28404. exports.MOUSE = MOUSE;
  28405. exports.Material = Material;
  28406. exports.MaterialLoader = MaterialLoader;
  28407. exports.MathUtils = MathUtils;
  28408. exports.Matrix3 = Matrix3;
  28409. exports.Matrix4 = Matrix4;
  28410. exports.MaxEquation = MaxEquation;
  28411. exports.Mesh = Mesh;
  28412. exports.MeshBasicMaterial = MeshBasicMaterial;
  28413. exports.MeshDepthMaterial = MeshDepthMaterial;
  28414. exports.MeshDistanceMaterial = MeshDistanceMaterial;
  28415. exports.MeshLambertMaterial = MeshLambertMaterial;
  28416. exports.MeshMatcapMaterial = MeshMatcapMaterial;
  28417. exports.MeshNormalMaterial = MeshNormalMaterial;
  28418. exports.MeshPhongMaterial = MeshPhongMaterial;
  28419. exports.MeshPhysicalMaterial = MeshPhysicalMaterial;
  28420. exports.MeshStandardMaterial = MeshStandardMaterial;
  28421. exports.MeshToonMaterial = MeshToonMaterial;
  28422. exports.MinEquation = MinEquation;
  28423. exports.MirroredRepeatWrapping = MirroredRepeatWrapping;
  28424. exports.MixOperation = MixOperation;
  28425. exports.MultiplyBlending = MultiplyBlending;
  28426. exports.MultiplyOperation = MultiplyOperation;
  28427. exports.NearestFilter = NearestFilter;
  28428. exports.NearestMipMapLinearFilter = NearestMipMapLinearFilter;
  28429. exports.NearestMipMapNearestFilter = NearestMipMapNearestFilter;
  28430. exports.NearestMipmapLinearFilter = NearestMipmapLinearFilter;
  28431. exports.NearestMipmapNearestFilter = NearestMipmapNearestFilter;
  28432. exports.NeverDepth = NeverDepth;
  28433. exports.NeverStencilFunc = NeverStencilFunc;
  28434. exports.NoBlending = NoBlending;
  28435. exports.NoColorSpace = NoColorSpace;
  28436. exports.NoToneMapping = NoToneMapping;
  28437. exports.NormalAnimationBlendMode = NormalAnimationBlendMode;
  28438. exports.NormalBlending = NormalBlending;
  28439. exports.NotEqualDepth = NotEqualDepth;
  28440. exports.NotEqualStencilFunc = NotEqualStencilFunc;
  28441. exports.NumberKeyframeTrack = NumberKeyframeTrack;
  28442. exports.Object3D = Object3D;
  28443. exports.ObjectLoader = ObjectLoader;
  28444. exports.ObjectSpaceNormalMap = ObjectSpaceNormalMap;
  28445. exports.OctahedronBufferGeometry = OctahedronGeometry;
  28446. exports.OctahedronGeometry = OctahedronGeometry;
  28447. exports.OneFactor = OneFactor;
  28448. exports.OneMinusDstAlphaFactor = OneMinusDstAlphaFactor;
  28449. exports.OneMinusDstColorFactor = OneMinusDstColorFactor;
  28450. exports.OneMinusSrcAlphaFactor = OneMinusSrcAlphaFactor;
  28451. exports.OneMinusSrcColorFactor = OneMinusSrcColorFactor;
  28452. exports.OrthographicCamera = OrthographicCamera;
  28453. exports.PCFShadowMap = PCFShadowMap;
  28454. exports.PCFSoftShadowMap = PCFSoftShadowMap;
  28455. exports.PMREMGenerator = PMREMGenerator;
  28456. exports.ParametricGeometry = ParametricGeometry;
  28457. exports.Path = Path;
  28458. exports.PerspectiveCamera = PerspectiveCamera;
  28459. exports.Plane = Plane;
  28460. exports.PlaneBufferGeometry = PlaneGeometry;
  28461. exports.PlaneGeometry = PlaneGeometry;
  28462. exports.PlaneHelper = PlaneHelper;
  28463. exports.PointLight = PointLight;
  28464. exports.PointLightHelper = PointLightHelper;
  28465. exports.Points = Points;
  28466. exports.PointsMaterial = PointsMaterial;
  28467. exports.PolarGridHelper = PolarGridHelper;
  28468. exports.PolyhedronBufferGeometry = PolyhedronGeometry;
  28469. exports.PolyhedronGeometry = PolyhedronGeometry;
  28470. exports.PositionalAudio = PositionalAudio;
  28471. exports.PropertyBinding = PropertyBinding;
  28472. exports.PropertyMixer = PropertyMixer;
  28473. exports.QuadraticBezierCurve = QuadraticBezierCurve;
  28474. exports.QuadraticBezierCurve3 = QuadraticBezierCurve3;
  28475. exports.Quaternion = Quaternion;
  28476. exports.QuaternionKeyframeTrack = QuaternionKeyframeTrack;
  28477. exports.QuaternionLinearInterpolant = QuaternionLinearInterpolant;
  28478. exports.REVISION = REVISION;
  28479. exports.RGBADepthPacking = RGBADepthPacking;
  28480. exports.RGBAFormat = RGBAFormat;
  28481. exports.RGBAIntegerFormat = RGBAIntegerFormat;
  28482. exports.RGBA_ASTC_10x10_Format = RGBA_ASTC_10x10_Format;
  28483. exports.RGBA_ASTC_10x5_Format = RGBA_ASTC_10x5_Format;
  28484. exports.RGBA_ASTC_10x6_Format = RGBA_ASTC_10x6_Format;
  28485. exports.RGBA_ASTC_10x8_Format = RGBA_ASTC_10x8_Format;
  28486. exports.RGBA_ASTC_12x10_Format = RGBA_ASTC_12x10_Format;
  28487. exports.RGBA_ASTC_12x12_Format = RGBA_ASTC_12x12_Format;
  28488. exports.RGBA_ASTC_4x4_Format = RGBA_ASTC_4x4_Format;
  28489. exports.RGBA_ASTC_5x4_Format = RGBA_ASTC_5x4_Format;
  28490. exports.RGBA_ASTC_5x5_Format = RGBA_ASTC_5x5_Format;
  28491. exports.RGBA_ASTC_6x5_Format = RGBA_ASTC_6x5_Format;
  28492. exports.RGBA_ASTC_6x6_Format = RGBA_ASTC_6x6_Format;
  28493. exports.RGBA_ASTC_8x5_Format = RGBA_ASTC_8x5_Format;
  28494. exports.RGBA_ASTC_8x6_Format = RGBA_ASTC_8x6_Format;
  28495. exports.RGBA_ASTC_8x8_Format = RGBA_ASTC_8x8_Format;
  28496. exports.RGBA_BPTC_Format = RGBA_BPTC_Format;
  28497. exports.RGBA_ETC2_EAC_Format = RGBA_ETC2_EAC_Format;
  28498. exports.RGBA_PVRTC_2BPPV1_Format = RGBA_PVRTC_2BPPV1_Format;
  28499. exports.RGBA_PVRTC_4BPPV1_Format = RGBA_PVRTC_4BPPV1_Format;
  28500. exports.RGBA_S3TC_DXT1_Format = RGBA_S3TC_DXT1_Format;
  28501. exports.RGBA_S3TC_DXT3_Format = RGBA_S3TC_DXT3_Format;
  28502. exports.RGBA_S3TC_DXT5_Format = RGBA_S3TC_DXT5_Format;
  28503. exports.RGBFormat = RGBFormat;
  28504. exports.RGB_ETC1_Format = RGB_ETC1_Format;
  28505. exports.RGB_ETC2_Format = RGB_ETC2_Format;
  28506. exports.RGB_PVRTC_2BPPV1_Format = RGB_PVRTC_2BPPV1_Format;
  28507. exports.RGB_PVRTC_4BPPV1_Format = RGB_PVRTC_4BPPV1_Format;
  28508. exports.RGB_S3TC_DXT1_Format = RGB_S3TC_DXT1_Format;
  28509. exports.RGFormat = RGFormat;
  28510. exports.RGIntegerFormat = RGIntegerFormat;
  28511. exports.RawShaderMaterial = RawShaderMaterial;
  28512. exports.Ray = Ray;
  28513. exports.Raycaster = Raycaster;
  28514. exports.RectAreaLight = RectAreaLight;
  28515. exports.RedFormat = RedFormat;
  28516. exports.RedIntegerFormat = RedIntegerFormat;
  28517. exports.ReinhardToneMapping = ReinhardToneMapping;
  28518. exports.RepeatWrapping = RepeatWrapping;
  28519. exports.ReplaceStencilOp = ReplaceStencilOp;
  28520. exports.ReverseSubtractEquation = ReverseSubtractEquation;
  28521. exports.RingBufferGeometry = RingGeometry;
  28522. exports.RingGeometry = RingGeometry;
  28523. exports.SRGBColorSpace = SRGBColorSpace;
  28524. exports.Scene = Scene;
  28525. exports.ShaderChunk = ShaderChunk;
  28526. exports.ShaderLib = ShaderLib;
  28527. exports.ShaderMaterial = ShaderMaterial;
  28528. exports.ShadowMaterial = ShadowMaterial;
  28529. exports.Shape = Shape;
  28530. exports.ShapeBufferGeometry = ShapeGeometry;
  28531. exports.ShapeGeometry = ShapeGeometry;
  28532. exports.ShapePath = ShapePath;
  28533. exports.ShapeUtils = ShapeUtils;
  28534. exports.ShortType = ShortType;
  28535. exports.Skeleton = Skeleton;
  28536. exports.SkeletonHelper = SkeletonHelper;
  28537. exports.SkinnedMesh = SkinnedMesh;
  28538. exports.SmoothShading = SmoothShading;
  28539. exports.Source = Source;
  28540. exports.Sphere = Sphere;
  28541. exports.SphereBufferGeometry = SphereGeometry;
  28542. exports.SphereGeometry = SphereGeometry;
  28543. exports.Spherical = Spherical;
  28544. exports.SphericalHarmonics3 = SphericalHarmonics3;
  28545. exports.SplineCurve = SplineCurve;
  28546. exports.SpotLight = SpotLight;
  28547. exports.SpotLightHelper = SpotLightHelper;
  28548. exports.Sprite = Sprite;
  28549. exports.SpriteMaterial = SpriteMaterial;
  28550. exports.SrcAlphaFactor = SrcAlphaFactor;
  28551. exports.SrcAlphaSaturateFactor = SrcAlphaSaturateFactor;
  28552. exports.SrcColorFactor = SrcColorFactor;
  28553. exports.StaticCopyUsage = StaticCopyUsage;
  28554. exports.StaticDrawUsage = StaticDrawUsage;
  28555. exports.StaticReadUsage = StaticReadUsage;
  28556. exports.StereoCamera = StereoCamera;
  28557. exports.StreamCopyUsage = StreamCopyUsage;
  28558. exports.StreamDrawUsage = StreamDrawUsage;
  28559. exports.StreamReadUsage = StreamReadUsage;
  28560. exports.StringKeyframeTrack = StringKeyframeTrack;
  28561. exports.SubtractEquation = SubtractEquation;
  28562. exports.SubtractiveBlending = SubtractiveBlending;
  28563. exports.TOUCH = TOUCH;
  28564. exports.TangentSpaceNormalMap = TangentSpaceNormalMap;
  28565. exports.TetrahedronBufferGeometry = TetrahedronGeometry;
  28566. exports.TetrahedronGeometry = TetrahedronGeometry;
  28567. exports.TextGeometry = TextGeometry;
  28568. exports.Texture = Texture;
  28569. exports.TextureLoader = TextureLoader;
  28570. exports.TorusBufferGeometry = TorusGeometry;
  28571. exports.TorusGeometry = TorusGeometry;
  28572. exports.TorusKnotBufferGeometry = TorusKnotGeometry;
  28573. exports.TorusKnotGeometry = TorusKnotGeometry;
  28574. exports.Triangle = Triangle;
  28575. exports.TriangleFanDrawMode = TriangleFanDrawMode;
  28576. exports.TriangleStripDrawMode = TriangleStripDrawMode;
  28577. exports.TrianglesDrawMode = TrianglesDrawMode;
  28578. exports.TubeBufferGeometry = TubeGeometry;
  28579. exports.TubeGeometry = TubeGeometry;
  28580. exports.UVMapping = UVMapping;
  28581. exports.Uint16BufferAttribute = Uint16BufferAttribute;
  28582. exports.Uint32BufferAttribute = Uint32BufferAttribute;
  28583. exports.Uint8BufferAttribute = Uint8BufferAttribute;
  28584. exports.Uint8ClampedBufferAttribute = Uint8ClampedBufferAttribute;
  28585. exports.Uniform = Uniform;
  28586. exports.UniformsLib = UniformsLib;
  28587. exports.UniformsUtils = UniformsUtils;
  28588. exports.UnsignedByteType = UnsignedByteType;
  28589. exports.UnsignedInt248Type = UnsignedInt248Type;
  28590. exports.UnsignedIntType = UnsignedIntType;
  28591. exports.UnsignedShort4444Type = UnsignedShort4444Type;
  28592. exports.UnsignedShort5551Type = UnsignedShort5551Type;
  28593. exports.UnsignedShortType = UnsignedShortType;
  28594. exports.VSMShadowMap = VSMShadowMap;
  28595. exports.Vector2 = Vector2;
  28596. exports.Vector3 = Vector3;
  28597. exports.Vector4 = Vector4;
  28598. exports.VectorKeyframeTrack = VectorKeyframeTrack;
  28599. exports.VideoTexture = VideoTexture;
  28600. exports.WebGL1Renderer = WebGL1Renderer;
  28601. exports.WebGL3DRenderTarget = WebGL3DRenderTarget;
  28602. exports.WebGLArrayRenderTarget = WebGLArrayRenderTarget;
  28603. exports.WebGLCubeRenderTarget = WebGLCubeRenderTarget;
  28604. exports.WebGLMultipleRenderTargets = WebGLMultipleRenderTargets;
  28605. exports.WebGLMultisampleRenderTarget = WebGLMultisampleRenderTarget;
  28606. exports.WebGLRenderTarget = WebGLRenderTarget;
  28607. exports.WebGLRenderer = WebGLRenderer;
  28608. exports.WebGLUtils = WebGLUtils;
  28609. exports.WireframeGeometry = WireframeGeometry;
  28610. exports.WrapAroundEnding = WrapAroundEnding;
  28611. exports.ZeroCurvatureEnding = ZeroCurvatureEnding;
  28612. exports.ZeroFactor = ZeroFactor;
  28613. exports.ZeroSlopeEnding = ZeroSlopeEnding;
  28614. exports.ZeroStencilOp = ZeroStencilOp;
  28615. exports._SRGBAFormat = _SRGBAFormat;
  28616. exports.sRGBEncoding = sRGBEncoding;
  28617. Object.defineProperty(exports, '__esModule', { value: true });
  28618. }));
粤ICP备19079148号