2
0

three.cjs 1.2 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447374483744937450374513745237453374543745537456374573745837459374603746137462374633746437465374663746737468374693747037471374723747337474374753747637477374783747937480374813748237483374843748537486374873748837489374903749137492374933749437495374963749737498374993750037501375023750337504375053750637507375083750937510375113751237513375143751537516375173751837519375203752137522375233752437525375263752737528375293753037531375323753337534375353753637537375383753937540375413754237543375443754537546375473754837549375503755137552375533755437555375563755737558375593756037561375623756337564375653756637567375683756937570375713757237573375743757537576375773757837579375803758137582375833758437585375863758737588375893759037591375923759337594375953759637597375983759937600376013760237603376043760537606376073760837609376103761137612376133761437615376163761737618376193762037621376223762337624376253762637627376283762937630376313763237633376343763537636376373763837639376403764137642376433764437645376463764737648376493765037651376523765337654376553765637657376583765937660376613766237663376643766537666376673766837669376703767137672376733767437675376763767737678376793768037681376823768337684376853768637687376883768937690376913769237693376943769537696376973769837699377003770137702377033770437705377063770737708377093771037711377123771337714377153771637717377183771937720377213772237723377243772537726377273772837729377303773137732377333773437735377363773737738377393774037741377423774337744377453774637747377483774937750377513775237753377543775537756377573775837759377603776137762377633776437765377663776737768377693777037771377723777337774377753777637777377783777937780377813778237783377843778537786377873778837789377903779137792377933779437795377963779737798377993780037801378023780337804378053780637807378083780937810378113781237813378143781537816378173781837819378203782137822378233782437825378263782737828378293783037831378323783337834378353783637837378383783937840378413784237843378443784537846378473784837849378503785137852378533785437855378563785737858378593786037861378623786337864378653786637867378683786937870378713787237873378743787537876378773787837879378803788137882378833788437885378863788737888378893789037891378923789337894378953789637897378983789937900379013790237903379043790537906379073790837909379103791137912379133791437915379163791737918379193792037921379223792337924379253792637927379283792937930379313793237933379343793537936379373793837939379403794137942379433794437945379463794737948379493795037951379523795337954379553795637957379583795937960379613796237963379643796537966379673796837969379703797137972379733797437975379763797737978379793798037981379823798337984379853798637987379883798937990379913799237993379943799537996379973799837999380003800138002380033800438005380063800738008380093801038011380123801338014380153801638017380183801938020380213802238023380243802538026380273802838029380303803138032380333803438035380363803738038380393804038041380423804338044380453804638047380483804938050380513805238053380543805538056380573805838059380603806138062380633806438065380663806738068380693807038071380723807338074380753807638077380783807938080380813808238083380843808538086380873808838089380903809138092380933809438095380963809738098380993810038101381023810338104381053810638107381083810938110381113811238113381143811538116381173811838119381203812138122381233812438125381263812738128381293813038131381323813338134381353813638137381383813938140381413814238143381443814538146381473814838149381503815138152381533815438155381563815738158381593816038161381623816338164381653816638167381683816938170381713817238173381743817538176381773817838179381803818138182381833818438185381863818738188381893819038191381923819338194381953819638197381983819938200382013820238203382043820538206382073820838209382103821138212382133821438215382163821738218382193822038221382223822338224382253822638227382283822938230382313823238233382343823538236382373823838239382403824138242382433824438245382463824738248382493825038251382523825338254382553825638257382583825938260382613826238263382643826538266382673826838269382703827138272382733827438275382763827738278382793828038281382823828338284382853828638287382883828938290382913829238293382943829538296382973829838299383003830138302383033830438305383063830738308383093831038311383123831338314383153831638317383183831938320383213832238323383243832538326383273832838329383303833138332383333833438335383363833738338383393834038341383423834338344383453834638347383483834938350383513835238353383543835538356383573835838359383603836138362383633836438365383663836738368383693837038371383723837338374383753837638377383783837938380383813838238383383843838538386383873838838389383903839138392383933839438395383963839738398383993840038401384023840338404384053840638407384083840938410384113841238413384143841538416384173841838419384203842138422384233842438425384263842738428384293843038431384323843338434384353843638437384383843938440384413844238443384443844538446384473844838449384503845138452384533845438455384563845738458384593846038461384623846338464384653846638467384683846938470384713847238473384743847538476384773847838479384803848138482384833848438485384863848738488384893849038491384923849338494384953849638497384983849938500385013850238503385043850538506385073850838509385103851138512385133851438515385163851738518385193852038521385223852338524385253852638527385283852938530385313853238533385343853538536385373853838539385403854138542385433854438545385463854738548385493855038551385523855338554385553855638557385583855938560385613856238563385643856538566385673856838569385703857138572385733857438575385763857738578385793858038581385823858338584385853858638587385883858938590385913859238593385943859538596385973859838599386003860138602386033860438605386063860738608386093861038611386123861338614386153861638617386183861938620386213862238623386243862538626386273862838629386303863138632386333863438635386363863738638386393864038641386423864338644386453864638647386483864938650386513865238653386543865538656386573865838659386603866138662386633866438665386663866738668386693867038671386723867338674386753867638677386783867938680386813868238683386843868538686386873868838689386903869138692386933869438695386963869738698386993870038701387023870338704387053870638707387083870938710387113871238713387143871538716387173871838719387203872138722387233872438725387263872738728387293873038731387323873338734387353873638737387383873938740387413874238743387443874538746387473874838749387503875138752387533875438755387563875738758387593876038761387623876338764387653876638767387683876938770387713877238773387743877538776387773877838779387803878138782387833878438785387863878738788387893879038791387923879338794387953879638797387983879938800388013880238803388043880538806388073880838809388103881138812388133881438815388163881738818388193882038821388223882338824388253882638827388283882938830388313883238833388343883538836388373883838839388403884138842388433884438845388463884738848388493885038851388523885338854388553885638857388583885938860388613886238863388643886538866388673886838869388703887138872388733887438875388763887738878388793888038881388823888338884388853888638887388883888938890388913889238893388943889538896388973889838899389003890138902389033890438905389063890738908389093891038911389123891338914389153891638917389183891938920389213892238923389243892538926389273892838929389303893138932389333893438935389363893738938389393894038941389423894338944389453894638947389483894938950389513895238953389543895538956389573895838959389603896138962389633896438965389663896738968389693897038971389723897338974389753897638977389783897938980389813898238983389843898538986389873898838989389903899138992389933899438995389963899738998389993900039001390023900339004390053900639007390083900939010390113901239013390143901539016390173901839019390203902139022390233902439025390263902739028390293903039031390323903339034390353903639037390383903939040390413904239043390443904539046390473904839049390503905139052390533905439055390563905739058390593906039061390623906339064390653906639067390683906939070390713907239073390743907539076390773907839079390803908139082390833908439085390863908739088390893909039091390923909339094390953909639097390983909939100391013910239103391043910539106391073910839109391103911139112391133911439115391163911739118391193912039121391223912339124391253912639127391283912939130391313913239133391343913539136391373913839139391403914139142391433914439145391463914739148391493915039151391523915339154391553915639157391583915939160391613916239163391643916539166391673916839169391703917139172391733917439175391763917739178391793918039181391823918339184391853918639187391883918939190391913919239193391943919539196391973919839199392003920139202392033920439205392063920739208392093921039211392123921339214392153921639217392183921939220392213922239223392243922539226392273922839229392303923139232392333923439235392363923739238392393924039241392423924339244392453924639247392483924939250392513925239253392543925539256392573925839259392603926139262392633926439265392663926739268392693927039271392723927339274392753927639277392783927939280392813928239283392843928539286392873928839289392903929139292392933929439295392963929739298392993930039301393023930339304393053930639307393083930939310393113931239313393143931539316393173931839319393203932139322393233932439325393263932739328393293933039331393323933339334393353933639337393383933939340393413934239343393443934539346393473934839349393503935139352393533935439355393563935739358393593936039361393623936339364393653936639367393683936939370393713937239373393743937539376393773937839379393803938139382393833938439385393863938739388393893939039391393923939339394393953939639397393983939939400394013940239403394043940539406394073940839409394103941139412394133941439415394163941739418394193942039421394223942339424394253942639427394283942939430394313943239433394343943539436394373943839439394403944139442394433944439445394463944739448394493945039451394523945339454394553945639457394583945939460394613946239463394643946539466394673946839469394703947139472394733947439475394763947739478394793948039481394823948339484394853948639487394883948939490394913949239493394943949539496394973949839499395003950139502395033950439505395063950739508395093951039511395123951339514395153951639517395183951939520395213952239523395243952539526395273952839529395303953139532395333953439535395363953739538395393954039541395423954339544395453954639547395483954939550395513955239553395543955539556395573955839559395603956139562395633956439565395663956739568395693957039571395723957339574395753957639577395783957939580395813958239583395843958539586395873958839589395903959139592395933959439595395963959739598395993960039601396023960339604396053960639607396083960939610396113961239613396143961539616396173961839619396203962139622396233962439625396263962739628396293963039631396323963339634396353963639637396383963939640396413964239643396443964539646396473964839649396503965139652396533965439655396563965739658396593966039661396623966339664396653966639667396683966939670396713967239673396743967539676396773967839679396803968139682396833968439685396863968739688396893969039691396923969339694396953969639697396983969939700397013970239703397043970539706397073970839709397103971139712397133971439715397163971739718397193972039721397223972339724397253972639727397283972939730397313973239733397343973539736397373973839739397403974139742397433974439745397463974739748397493975039751397523975339754397553975639757397583975939760397613976239763397643976539766397673976839769397703977139772397733977439775397763977739778397793978039781397823978339784397853978639787397883978939790397913979239793397943979539796397973979839799398003980139802398033980439805398063980739808398093981039811398123981339814398153981639817398183981939820398213982239823398243982539826398273982839829398303983139832398333983439835398363983739838398393984039841398423984339844398453984639847398483984939850398513985239853398543985539856398573985839859398603986139862398633986439865398663986739868398693987039871398723987339874398753987639877398783987939880398813988239883398843988539886398873988839889398903989139892398933989439895398963989739898398993990039901399023990339904399053990639907399083990939910399113991239913399143991539916399173991839919399203992139922399233992439925399263992739928399293993039931399323993339934399353993639937399383993939940399413994239943399443994539946399473994839949399503995139952399533995439955399563995739958399593996039961399623996339964399653996639967399683996939970399713997239973399743997539976399773997839979399803998139982399833998439985399863998739988399893999039991399923999339994399953999639997399983999940000400014000240003400044000540006400074000840009400104001140012400134001440015400164001740018400194002040021400224002340024400254002640027400284002940030400314003240033400344003540036400374003840039400404004140042400434004440045400464004740048400494005040051400524005340054400554005640057400584005940060400614006240063400644006540066400674006840069400704007140072400734007440075400764007740078400794008040081400824008340084400854008640087400884008940090400914009240093400944009540096400974009840099401004010140102401034010440105401064010740108401094011040111401124011340114401154011640117401184011940120401214012240123401244012540126401274012840129401304013140132401334013440135401364013740138401394014040141401424014340144401454014640147401484014940150401514015240153401544015540156401574015840159401604016140162401634016440165401664016740168401694017040171401724017340174401754017640177401784017940180401814018240183401844018540186401874018840189401904019140192401934019440195401964019740198401994020040201402024020340204402054020640207402084020940210402114021240213402144021540216402174021840219402204022140222402234022440225402264022740228402294023040231402324023340234402354023640237402384023940240402414024240243402444024540246402474024840249402504025140252402534025440255402564025740258402594026040261402624026340264402654026640267402684026940270402714027240273402744027540276402774027840279402804028140282402834028440285402864028740288402894029040291402924029340294402954029640297402984029940300403014030240303403044030540306403074030840309403104031140312403134031440315403164031740318403194032040321403224032340324403254032640327403284032940330403314033240333403344033540336403374033840339403404034140342403434034440345403464034740348403494035040351403524035340354403554035640357403584035940360403614036240363403644036540366403674036840369403704037140372403734037440375403764037740378403794038040381403824038340384403854038640387403884038940390403914039240393403944039540396403974039840399404004040140402404034040440405404064040740408404094041040411404124041340414404154041640417404184041940420404214042240423404244042540426404274042840429404304043140432404334043440435404364043740438404394044040441404424044340444404454044640447404484044940450404514045240453404544045540456404574045840459404604046140462404634046440465404664046740468404694047040471404724047340474404754047640477404784047940480404814048240483404844048540486404874048840489404904049140492404934049440495404964049740498404994050040501405024050340504405054050640507405084050940510405114051240513405144051540516405174051840519405204052140522405234052440525405264052740528405294053040531405324053340534405354053640537405384053940540405414054240543405444054540546405474054840549405504055140552405534055440555405564055740558405594056040561405624056340564405654056640567405684056940570405714057240573405744057540576405774057840579405804058140582405834058440585405864058740588405894059040591405924059340594405954059640597405984059940600406014060240603406044060540606406074060840609406104061140612406134061440615406164061740618406194062040621406224062340624406254062640627406284062940630406314063240633406344063540636406374063840639406404064140642406434064440645406464064740648406494065040651406524065340654406554065640657406584065940660406614066240663406644066540666406674066840669406704067140672406734067440675406764067740678406794068040681406824068340684406854068640687406884068940690406914069240693406944069540696406974069840699407004070140702407034070440705407064070740708407094071040711407124071340714407154071640717407184071940720407214072240723407244072540726407274072840729407304073140732407334073440735407364073740738407394074040741407424074340744407454074640747407484074940750407514075240753407544075540756407574075840759407604076140762407634076440765407664076740768407694077040771407724077340774407754077640777407784077940780407814078240783407844078540786407874078840789407904079140792407934079440795407964079740798407994080040801408024080340804408054080640807408084080940810408114081240813408144081540816408174081840819408204082140822408234082440825408264082740828408294083040831408324083340834408354083640837408384083940840408414084240843408444084540846408474084840849408504085140852408534085440855408564085740858408594086040861408624086340864408654086640867408684086940870408714087240873408744087540876408774087840879408804088140882408834088440885408864088740888408894089040891408924089340894408954089640897408984089940900409014090240903409044090540906409074090840909409104091140912409134091440915409164091740918409194092040921409224092340924409254092640927409284092940930409314093240933409344093540936409374093840939409404094140942409434094440945409464094740948409494095040951409524095340954409554095640957409584095940960409614096240963409644096540966409674096840969409704097140972409734097440975409764097740978409794098040981409824098340984409854098640987409884098940990409914099240993409944099540996409974099840999410004100141002410034100441005410064100741008410094101041011410124101341014410154101641017410184101941020410214102241023410244102541026410274102841029410304103141032410334103441035410364103741038410394104041041410424104341044410454104641047410484104941050410514105241053410544105541056410574105841059410604106141062410634106441065410664106741068410694107041071410724107341074410754107641077410784107941080410814108241083410844108541086410874108841089410904109141092410934109441095410964109741098410994110041101411024110341104411054110641107411084110941110411114111241113411144111541116411174111841119411204112141122411234112441125411264112741128411294113041131411324113341134411354113641137411384113941140411414114241143411444114541146411474114841149411504115141152411534115441155411564115741158411594116041161411624116341164411654116641167411684116941170411714117241173411744117541176411774117841179411804118141182411834118441185411864118741188411894119041191411924119341194411954119641197411984119941200412014120241203412044120541206412074120841209412104121141212412134121441215412164121741218412194122041221412224122341224412254122641227412284122941230412314123241233412344123541236412374123841239412404124141242412434124441245412464124741248412494125041251412524125341254412554125641257412584125941260412614126241263412644126541266412674126841269412704127141272412734127441275412764127741278412794128041281412824128341284412854128641287412884128941290412914129241293412944129541296412974129841299413004130141302413034130441305413064130741308413094131041311413124131341314413154131641317413184131941320413214132241323413244132541326413274132841329413304133141332413334133441335413364133741338413394134041341413424134341344413454134641347413484134941350413514135241353413544135541356413574135841359413604136141362413634136441365413664136741368413694137041371413724137341374413754137641377413784137941380413814138241383413844138541386413874138841389413904139141392413934139441395413964139741398413994140041401414024140341404414054140641407414084140941410414114141241413414144141541416414174141841419414204142141422414234142441425414264142741428414294143041431414324143341434414354143641437414384143941440414414144241443414444144541446414474144841449414504145141452414534145441455414564145741458414594146041461414624146341464414654146641467414684146941470414714147241473414744147541476414774147841479414804148141482414834148441485414864148741488414894149041491414924149341494414954149641497414984149941500415014150241503415044150541506415074150841509415104151141512415134151441515415164151741518415194152041521415224152341524415254152641527415284152941530415314153241533415344153541536415374153841539415404154141542415434154441545415464154741548415494155041551415524155341554415554155641557415584155941560415614156241563415644156541566415674156841569415704157141572415734157441575415764157741578415794158041581415824158341584415854158641587415884158941590415914159241593415944159541596415974159841599416004160141602416034160441605416064160741608416094161041611416124161341614416154161641617416184161941620416214162241623416244162541626416274162841629416304163141632416334163441635416364163741638416394164041641416424164341644416454164641647416484164941650416514165241653416544165541656416574165841659416604166141662416634166441665416664166741668416694167041671416724167341674416754167641677416784167941680416814168241683416844168541686416874168841689416904169141692416934169441695416964169741698416994170041701417024170341704417054170641707417084170941710417114171241713417144171541716417174171841719417204172141722417234172441725417264172741728417294173041731417324173341734417354173641737417384173941740417414174241743417444174541746417474174841749417504175141752417534175441755417564175741758417594176041761417624176341764417654176641767417684176941770417714177241773417744177541776417774177841779417804178141782417834178441785417864178741788417894179041791417924179341794417954179641797417984179941800418014180241803418044180541806418074180841809418104181141812418134181441815418164181741818418194182041821418224182341824418254182641827418284182941830418314183241833418344183541836418374183841839418404184141842418434184441845418464184741848418494185041851418524185341854418554185641857418584185941860418614186241863418644186541866418674186841869418704187141872418734187441875418764187741878418794188041881418824188341884418854188641887418884188941890418914189241893418944189541896418974189841899419004190141902419034190441905419064190741908419094191041911419124191341914419154191641917419184191941920419214192241923419244192541926419274192841929419304193141932419334193441935419364193741938419394194041941419424194341944419454194641947419484194941950419514195241953419544195541956419574195841959419604196141962419634196441965419664196741968419694197041971419724197341974419754197641977419784197941980419814198241983419844198541986419874198841989419904199141992419934199441995419964199741998419994200042001420024200342004420054200642007420084200942010420114201242013420144201542016420174201842019420204202142022420234202442025420264202742028420294203042031420324203342034420354203642037420384203942040420414204242043420444204542046420474204842049420504205142052420534205442055420564205742058420594206042061420624206342064420654206642067420684206942070420714207242073420744207542076420774207842079420804208142082420834208442085420864208742088420894209042091420924209342094420954209642097420984209942100421014210242103421044210542106421074210842109421104211142112421134211442115421164211742118421194212042121421224212342124421254212642127421284212942130421314213242133421344213542136421374213842139421404214142142421434214442145421464214742148421494215042151421524215342154421554215642157421584215942160421614216242163421644216542166421674216842169421704217142172421734217442175421764217742178421794218042181421824218342184421854218642187421884218942190421914219242193421944219542196421974219842199422004220142202422034220442205422064220742208422094221042211422124221342214422154221642217422184221942220422214222242223422244222542226422274222842229422304223142232422334223442235422364223742238422394224042241422424224342244422454224642247422484224942250422514225242253422544225542256422574225842259422604226142262422634226442265422664226742268422694227042271422724227342274422754227642277422784227942280422814228242283422844228542286422874228842289422904229142292422934229442295422964229742298422994230042301423024230342304423054230642307423084230942310423114231242313423144231542316423174231842319423204232142322423234232442325423264232742328423294233042331423324233342334423354233642337423384233942340423414234242343423444234542346423474234842349423504235142352423534235442355423564235742358423594236042361423624236342364423654236642367423684236942370423714237242373423744237542376423774237842379423804238142382423834238442385423864238742388423894239042391423924239342394423954239642397423984239942400424014240242403424044240542406424074240842409424104241142412424134241442415424164241742418424194242042421424224242342424424254242642427424284242942430424314243242433424344243542436424374243842439424404244142442424434244442445424464244742448424494245042451424524245342454424554245642457424584245942460424614246242463424644246542466424674246842469424704247142472424734247442475424764247742478424794248042481424824248342484424854248642487424884248942490424914249242493424944249542496424974249842499425004250142502425034250442505425064250742508425094251042511425124251342514425154251642517425184251942520425214252242523425244252542526425274252842529425304253142532425334253442535425364253742538425394254042541425424254342544425454254642547425484254942550425514255242553425544255542556425574255842559425604256142562425634256442565425664256742568425694257042571425724257342574425754257642577425784257942580425814258242583425844258542586425874258842589425904259142592425934259442595425964259742598425994260042601426024260342604426054260642607426084260942610426114261242613426144261542616426174261842619426204262142622426234262442625426264262742628426294263042631426324263342634426354263642637426384263942640426414264242643426444264542646426474264842649426504265142652426534265442655426564265742658426594266042661426624266342664426654266642667426684266942670426714267242673426744267542676426774267842679426804268142682426834268442685426864268742688426894269042691426924269342694426954269642697426984269942700427014270242703427044270542706427074270842709427104271142712427134271442715427164271742718427194272042721427224272342724427254272642727427284272942730427314273242733427344273542736427374273842739427404274142742427434274442745427464274742748427494275042751427524275342754427554275642757427584275942760427614276242763427644276542766427674276842769427704277142772427734277442775427764277742778427794278042781427824278342784427854278642787427884278942790427914279242793427944279542796427974279842799428004280142802428034280442805428064280742808428094281042811428124281342814428154281642817428184281942820428214282242823428244282542826428274282842829428304283142832428334283442835428364283742838428394284042841428424284342844428454284642847428484284942850428514285242853428544285542856428574285842859428604286142862428634286442865428664286742868428694287042871428724287342874428754287642877428784287942880428814288242883428844288542886428874288842889428904289142892428934289442895428964289742898428994290042901429024290342904429054290642907429084290942910429114291242913429144291542916429174291842919429204292142922429234292442925429264292742928429294293042931429324293342934429354293642937429384293942940429414294242943429444294542946429474294842949429504295142952429534295442955429564295742958429594296042961429624296342964429654296642967429684296942970429714297242973429744297542976429774297842979429804298142982429834298442985429864298742988429894299042991429924299342994429954299642997429984299943000430014300243003430044300543006430074300843009430104301143012430134301443015430164301743018430194302043021430224302343024430254302643027430284302943030430314303243033430344303543036430374303843039430404304143042430434304443045430464304743048430494305043051430524305343054430554305643057430584305943060430614306243063430644306543066430674306843069430704307143072430734307443075430764307743078430794308043081430824308343084430854308643087430884308943090430914309243093430944309543096430974309843099431004310143102431034310443105431064310743108431094311043111431124311343114431154311643117431184311943120431214312243123431244312543126431274312843129431304313143132431334313443135431364313743138431394314043141431424314343144431454314643147431484314943150431514315243153431544315543156431574315843159431604316143162431634316443165431664316743168431694317043171431724317343174431754317643177431784317943180431814318243183431844318543186431874318843189431904319143192431934319443195431964319743198431994320043201432024320343204432054320643207432084320943210432114321243213432144321543216432174321843219432204322143222432234322443225432264322743228432294323043231432324323343234432354323643237432384323943240432414324243243432444324543246432474324843249432504325143252432534325443255432564325743258432594326043261432624326343264432654326643267432684326943270432714327243273432744327543276432774327843279432804328143282432834328443285432864328743288432894329043291432924329343294432954329643297432984329943300433014330243303433044330543306433074330843309433104331143312433134331443315433164331743318433194332043321433224332343324433254332643327433284332943330433314333243333433344333543336433374333843339433404334143342433434334443345433464334743348433494335043351433524335343354433554335643357433584335943360433614336243363433644336543366433674336843369433704337143372433734337443375433764337743378433794338043381433824338343384433854338643387433884338943390433914339243393433944339543396433974339843399434004340143402434034340443405434064340743408434094341043411434124341343414434154341643417434184341943420434214342243423434244342543426434274342843429434304343143432434334343443435434364343743438434394344043441434424344343444434454344643447434484344943450434514345243453434544345543456434574345843459434604346143462434634346443465434664346743468434694347043471434724347343474434754347643477434784347943480434814348243483434844348543486434874348843489434904349143492434934349443495434964349743498434994350043501435024350343504435054350643507435084350943510435114351243513435144351543516435174351843519435204352143522435234352443525435264352743528435294353043531435324353343534435354353643537435384353943540435414354243543435444354543546435474354843549435504355143552435534355443555435564355743558435594356043561435624356343564435654356643567435684356943570435714357243573435744357543576435774357843579435804358143582435834358443585435864358743588435894359043591435924359343594435954359643597435984359943600436014360243603436044360543606436074360843609436104361143612436134361443615436164361743618436194362043621436224362343624436254362643627436284362943630436314363243633436344363543636436374363843639436404364143642436434364443645436464364743648436494365043651436524365343654436554365643657436584365943660436614366243663436644366543666436674366843669436704367143672436734367443675436764367743678436794368043681436824368343684436854368643687436884368943690436914369243693436944369543696436974369843699437004370143702437034370443705437064370743708437094371043711437124371343714437154371643717437184371943720437214372243723437244372543726437274372843729437304373143732437334373443735437364373743738437394374043741437424374343744437454374643747437484374943750437514375243753437544375543756437574375843759437604376143762437634376443765437664376743768437694377043771437724377343774437754377643777437784377943780437814378243783437844378543786437874378843789437904379143792437934379443795437964379743798437994380043801438024380343804438054380643807438084380943810438114381243813438144381543816438174381843819438204382143822438234382443825438264382743828438294383043831438324383343834438354383643837438384383943840438414384243843438444384543846438474384843849438504385143852438534385443855438564385743858438594386043861438624386343864438654386643867438684386943870438714387243873438744387543876438774387843879438804388143882438834388443885438864388743888438894389043891438924389343894438954389643897438984389943900439014390243903439044390543906439074390843909439104391143912439134391443915439164391743918439194392043921439224392343924439254392643927439284392943930439314393243933439344393543936439374393843939439404394143942439434394443945439464394743948439494395043951439524395343954439554395643957439584395943960439614396243963439644396543966439674396843969439704397143972439734397443975439764397743978439794398043981439824398343984439854398643987439884398943990439914399243993439944399543996439974399843999440004400144002440034400444005440064400744008440094401044011440124401344014440154401644017440184401944020440214402244023440244402544026440274402844029440304403144032440334403444035440364403744038440394404044041440424404344044440454404644047440484404944050440514405244053440544405544056440574405844059440604406144062440634406444065440664406744068440694407044071440724407344074440754407644077440784407944080440814408244083440844408544086440874408844089440904409144092440934409444095440964409744098440994410044101441024410344104441054410644107441084410944110441114411244113441144411544116441174411844119441204412144122441234412444125441264412744128441294413044131441324413344134441354413644137441384413944140441414414244143441444414544146441474414844149441504415144152441534415444155441564415744158441594416044161441624416344164441654416644167441684416944170441714417244173441744417544176441774417844179441804418144182441834418444185441864418744188441894419044191441924419344194441954419644197441984419944200442014420244203442044420544206442074420844209442104421144212442134421444215442164421744218442194422044221442224422344224442254422644227442284422944230442314423244233442344423544236442374423844239442404424144242442434424444245442464424744248442494425044251442524425344254442554425644257442584425944260442614426244263442644426544266442674426844269442704427144272442734427444275442764427744278442794428044281442824428344284442854428644287442884428944290442914429244293442944429544296442974429844299443004430144302443034430444305443064430744308443094431044311443124431344314443154431644317443184431944320443214432244323443244432544326443274432844329443304433144332443334433444335443364433744338443394434044341443424434344344443454434644347443484434944350443514435244353443544435544356443574435844359443604436144362443634436444365443664436744368443694437044371443724437344374443754437644377443784437944380443814438244383443844438544386443874438844389443904439144392443934439444395443964439744398443994440044401444024440344404444054440644407444084440944410444114441244413444144441544416444174441844419444204442144422444234442444425444264442744428444294443044431444324443344434444354443644437444384443944440444414444244443444444444544446444474444844449444504445144452444534445444455444564445744458444594446044461444624446344464444654446644467444684446944470444714447244473444744447544476444774447844479444804448144482444834448444485444864448744488444894449044491444924449344494444954449644497444984449944500445014450244503445044450544506445074450844509445104451144512445134451444515445164451744518445194452044521445224452344524445254452644527445284452944530445314453244533445344453544536445374453844539445404454144542445434454444545445464454744548445494455044551445524455344554445554455644557445584455944560445614456244563445644456544566445674456844569445704457144572445734457444575445764457744578445794458044581445824458344584445854458644587445884458944590445914459244593445944459544596445974459844599446004460144602446034460444605446064460744608446094461044611446124461344614446154461644617446184461944620446214462244623446244462544626446274462844629446304463144632446334463444635446364463744638446394464044641446424464344644446454464644647446484464944650446514465244653446544465544656446574465844659446604466144662446634466444665446664466744668446694467044671446724467344674446754467644677446784467944680446814468244683446844468544686446874468844689446904469144692446934469444695446964469744698446994470044701447024470344704447054470644707447084470944710447114471244713447144471544716447174471844719447204472144722447234472444725447264472744728447294473044731447324473344734447354473644737447384473944740447414474244743447444474544746447474474844749447504475144752447534475444755447564475744758447594476044761447624476344764447654476644767447684476944770447714477244773447744477544776447774477844779447804478144782447834478444785447864478744788447894479044791447924479344794447954479644797447984479944800448014480244803448044480544806448074480844809448104481144812448134481444815448164481744818448194482044821448224482344824448254482644827448284482944830448314483244833448344483544836448374483844839448404484144842448434484444845448464484744848448494485044851448524485344854448554485644857448584485944860448614486244863448644486544866448674486844869448704487144872448734487444875448764487744878448794488044881448824488344884448854488644887448884488944890448914489244893448944489544896448974489844899449004490144902449034490444905449064490744908449094491044911449124491344914449154491644917449184491944920449214492244923449244492544926449274492844929449304493144932449334493444935449364493744938449394494044941449424494344944449454494644947449484494944950449514495244953449544495544956449574495844959449604496144962449634496444965449664496744968449694497044971449724497344974449754497644977449784497944980449814498244983449844498544986449874498844989449904499144992449934499444995449964499744998449994500045001450024500345004450054500645007450084500945010450114501245013450144501545016450174501845019450204502145022450234502445025450264502745028450294503045031450324503345034450354503645037450384503945040450414504245043450444504545046450474504845049450504505145052450534505445055450564505745058450594506045061450624506345064450654506645067450684506945070450714507245073450744507545076450774507845079450804508145082450834508445085450864508745088450894509045091450924509345094450954509645097450984509945100451014510245103451044510545106451074510845109451104511145112451134511445115451164511745118451194512045121451224512345124451254512645127451284512945130451314513245133451344513545136451374513845139451404514145142451434514445145451464514745148451494515045151451524515345154451554515645157451584515945160451614516245163451644516545166451674516845169451704517145172451734517445175451764517745178451794518045181451824518345184451854518645187451884518945190451914519245193451944519545196451974519845199452004520145202452034520445205452064520745208452094521045211452124521345214452154521645217452184521945220452214522245223452244522545226452274522845229452304523145232452334523445235452364523745238452394524045241452424524345244452454524645247452484524945250452514525245253452544525545256452574525845259452604526145262452634526445265452664526745268452694527045271452724527345274452754527645277452784527945280452814528245283452844528545286452874528845289452904529145292452934529445295452964529745298452994530045301453024530345304453054530645307453084530945310453114531245313453144531545316453174531845319453204532145322453234532445325453264532745328453294533045331453324533345334453354533645337453384533945340453414534245343453444534545346453474534845349453504535145352453534535445355453564535745358453594536045361453624536345364453654536645367453684536945370453714537245373453744537545376453774537845379453804538145382453834538445385453864538745388453894539045391453924539345394453954539645397453984539945400454014540245403454044540545406454074540845409454104541145412454134541445415454164541745418454194542045421454224542345424454254542645427454284542945430454314543245433454344543545436454374543845439454404544145442454434544445445454464544745448454494545045451454524545345454454554545645457454584545945460454614546245463454644546545466454674546845469454704547145472454734547445475454764547745478454794548045481454824548345484454854548645487454884548945490454914549245493454944549545496454974549845499455004550145502455034550445505455064550745508455094551045511455124551345514455154551645517455184551945520455214552245523455244552545526455274552845529455304553145532455334553445535455364553745538455394554045541455424554345544455454554645547455484554945550455514555245553455544555545556455574555845559455604556145562455634556445565455664556745568455694557045571455724557345574455754557645577455784557945580455814558245583455844558545586455874558845589455904559145592455934559445595455964559745598455994560045601456024560345604456054560645607456084560945610456114561245613456144561545616456174561845619456204562145622456234562445625456264562745628456294563045631456324563345634456354563645637456384563945640456414564245643456444564545646456474564845649456504565145652456534565445655456564565745658456594566045661456624566345664456654566645667456684566945670456714567245673456744567545676456774567845679456804568145682456834568445685456864568745688456894569045691456924569345694456954569645697456984569945700457014570245703457044570545706457074570845709457104571145712457134571445715457164571745718457194572045721457224572345724457254572645727457284572945730457314573245733457344573545736457374573845739457404574145742457434574445745457464574745748457494575045751457524575345754457554575645757457584575945760457614576245763457644576545766457674576845769457704577145772457734577445775457764577745778457794578045781457824578345784457854578645787457884578945790457914579245793457944579545796457974579845799458004580145802458034580445805458064580745808458094581045811458124581345814458154581645817458184581945820458214582245823458244582545826458274582845829458304583145832458334583445835458364583745838458394584045841458424584345844458454584645847458484584945850458514585245853458544585545856458574585845859458604586145862458634586445865458664586745868458694587045871458724587345874458754587645877458784587945880458814588245883458844588545886458874588845889458904589145892458934589445895458964589745898458994590045901459024590345904459054590645907459084590945910459114591245913459144591545916459174591845919459204592145922459234592445925459264592745928459294593045931459324593345934459354593645937459384593945940459414594245943459444594545946459474594845949459504595145952459534595445955459564595745958459594596045961459624596345964459654596645967459684596945970459714597245973459744597545976459774597845979459804598145982459834598445985459864598745988459894599045991459924599345994459954599645997459984599946000460014600246003460044600546006460074600846009460104601146012460134601446015460164601746018460194602046021460224602346024460254602646027460284602946030460314603246033460344603546036460374603846039460404604146042460434604446045460464604746048460494605046051460524605346054460554605646057460584605946060460614606246063460644606546066460674606846069460704607146072460734607446075460764607746078460794608046081460824608346084460854608646087460884608946090460914609246093460944609546096460974609846099461004610146102461034610446105461064610746108461094611046111461124611346114461154611646117461184611946120461214612246123461244612546126461274612846129461304613146132461334613446135461364613746138461394614046141461424614346144461454614646147461484614946150461514615246153461544615546156461574615846159461604616146162461634616446165461664616746168461694617046171461724617346174461754617646177461784617946180461814618246183461844618546186461874618846189461904619146192461934619446195461964619746198461994620046201462024620346204462054620646207462084620946210462114621246213462144621546216462174621846219462204622146222462234622446225462264622746228462294623046231462324623346234462354623646237462384623946240462414624246243462444624546246462474624846249462504625146252462534625446255462564625746258462594626046261462624626346264462654626646267462684626946270462714627246273462744627546276462774627846279462804628146282462834628446285462864628746288462894629046291462924629346294462954629646297462984629946300463014630246303463044630546306463074630846309463104631146312463134631446315463164631746318463194632046321463224632346324463254632646327463284632946330463314633246333463344633546336463374633846339463404634146342463434634446345463464634746348463494635046351463524635346354463554635646357463584635946360463614636246363463644636546366463674636846369463704637146372463734637446375463764637746378463794638046381463824638346384463854638646387463884638946390463914639246393463944639546396463974639846399464004640146402464034640446405464064640746408464094641046411464124641346414464154641646417464184641946420464214642246423464244642546426464274642846429464304643146432464334643446435464364643746438464394644046441464424644346444464454644646447464484644946450464514645246453464544645546456464574645846459464604646146462464634646446465464664646746468464694647046471464724647346474464754647646477464784647946480464814648246483464844648546486464874648846489464904649146492464934649446495464964649746498464994650046501465024650346504465054650646507465084650946510465114651246513465144651546516465174651846519465204652146522465234652446525465264652746528465294653046531465324653346534465354653646537465384653946540465414654246543465444654546546465474654846549465504655146552465534655446555465564655746558465594656046561465624656346564465654656646567465684656946570465714657246573465744657546576465774657846579465804658146582465834658446585465864658746588465894659046591465924659346594465954659646597465984659946600466014660246603466044660546606466074660846609466104661146612466134661446615466164661746618466194662046621466224662346624466254662646627466284662946630466314663246633466344663546636466374663846639466404664146642466434664446645466464664746648466494665046651466524665346654466554665646657466584665946660466614666246663466644666546666466674666846669466704667146672466734667446675466764667746678466794668046681466824668346684466854668646687466884668946690466914669246693466944669546696466974669846699467004670146702467034670446705467064670746708467094671046711467124671346714467154671646717467184671946720467214672246723467244672546726467274672846729467304673146732467334673446735467364673746738467394674046741467424674346744467454674646747467484674946750467514675246753467544675546756467574675846759467604676146762467634676446765467664676746768467694677046771467724677346774467754677646777467784677946780467814678246783467844678546786467874678846789467904679146792467934679446795467964679746798467994680046801468024680346804468054680646807468084680946810468114681246813468144681546816468174681846819468204682146822468234682446825468264682746828468294683046831468324683346834468354683646837468384683946840468414684246843468444684546846468474684846849468504685146852468534685446855468564685746858468594686046861468624686346864468654686646867468684686946870468714687246873468744687546876468774687846879468804688146882468834688446885468864688746888468894689046891468924689346894468954689646897468984689946900469014690246903469044690546906469074690846909469104691146912469134691446915469164691746918469194692046921469224692346924469254692646927469284692946930469314693246933469344693546936469374693846939469404694146942469434694446945469464694746948469494695046951469524695346954469554695646957469584695946960469614696246963469644696546966469674696846969469704697146972469734697446975469764697746978469794698046981469824698346984469854698646987469884698946990469914699246993469944699546996469974699846999470004700147002470034700447005470064700747008470094701047011470124701347014470154701647017470184701947020470214702247023470244702547026470274702847029470304703147032470334703447035470364703747038470394704047041470424704347044470454704647047470484704947050470514705247053470544705547056470574705847059470604706147062470634706447065470664706747068470694707047071470724707347074470754707647077470784707947080470814708247083470844708547086470874708847089470904709147092470934709447095470964709747098470994710047101471024710347104471054710647107471084710947110471114711247113471144711547116471174711847119471204712147122471234712447125471264712747128471294713047131471324713347134471354713647137471384713947140471414714247143471444714547146471474714847149471504715147152471534715447155471564715747158471594716047161471624716347164471654716647167471684716947170471714717247173471744717547176471774717847179471804718147182471834718447185471864718747188471894719047191471924719347194471954719647197471984719947200472014720247203472044720547206472074720847209472104721147212472134721447215472164721747218472194722047221472224722347224472254722647227472284722947230472314723247233472344723547236472374723847239472404724147242472434724447245472464724747248472494725047251472524725347254472554725647257472584725947260472614726247263472644726547266472674726847269472704727147272472734727447275472764727747278472794728047281472824728347284472854728647287472884728947290472914729247293472944729547296472974729847299473004730147302473034730447305473064730747308473094731047311473124731347314473154731647317473184731947320473214732247323473244732547326473274732847329473304733147332473334733447335473364733747338473394734047341473424734347344473454734647347473484734947350473514735247353473544735547356473574735847359473604736147362473634736447365473664736747368473694737047371473724737347374473754737647377473784737947380473814738247383473844738547386473874738847389473904739147392473934739447395473964739747398473994740047401474024740347404474054740647407474084740947410474114741247413474144741547416474174741847419474204742147422474234742447425474264742747428474294743047431474324743347434474354743647437474384743947440474414744247443474444744547446474474744847449474504745147452474534745447455474564745747458474594746047461474624746347464474654746647467474684746947470474714747247473474744747547476474774747847479474804748147482474834748447485474864748747488474894749047491474924749347494474954749647497474984749947500475014750247503475044750547506475074750847509475104751147512475134751447515475164751747518475194752047521475224752347524475254752647527475284752947530475314753247533475344753547536475374753847539475404754147542475434754447545475464754747548475494755047551475524755347554475554755647557475584755947560475614756247563475644756547566475674756847569475704757147572475734757447575475764757747578475794758047581475824758347584475854758647587475884758947590475914759247593475944759547596475974759847599476004760147602476034760447605476064760747608476094761047611476124761347614476154761647617476184761947620476214762247623476244762547626476274762847629476304763147632476334763447635476364763747638476394764047641476424764347644476454764647647476484764947650476514765247653476544765547656476574765847659476604766147662476634766447665476664766747668476694767047671476724767347674476754767647677476784767947680476814768247683476844768547686476874768847689476904769147692476934769447695476964769747698476994770047701477024770347704477054770647707477084770947710477114771247713477144771547716477174771847719477204772147722477234772447725477264772747728477294773047731477324773347734477354773647737477384773947740477414774247743477444774547746477474774847749477504775147752477534775447755477564775747758477594776047761477624776347764477654776647767477684776947770477714777247773477744777547776477774777847779477804778147782477834778447785477864778747788477894779047791477924779347794477954779647797477984779947800478014780247803478044780547806478074780847809478104781147812478134781447815478164781747818478194782047821478224782347824478254782647827478284782947830478314783247833478344783547836478374783847839478404784147842478434784447845478464784747848478494785047851478524785347854478554785647857478584785947860478614786247863478644786547866478674786847869478704787147872478734787447875478764787747878478794788047881478824788347884478854788647887478884788947890478914789247893478944789547896478974789847899479004790147902479034790447905479064790747908479094791047911479124791347914479154791647917479184791947920479214792247923479244792547926479274792847929479304793147932479334793447935479364793747938479394794047941479424794347944479454794647947479484794947950479514795247953479544795547956479574795847959479604796147962479634796447965479664796747968479694797047971479724797347974479754797647977479784797947980479814798247983479844798547986479874798847989479904799147992479934799447995479964799747998479994800048001480024800348004480054800648007480084800948010480114801248013480144801548016480174801848019480204802148022480234802448025480264802748028480294803048031480324803348034480354803648037480384803948040480414804248043480444804548046480474804848049480504805148052480534805448055480564805748058480594806048061480624806348064480654806648067480684806948070480714807248073480744807548076480774807848079480804808148082480834808448085480864808748088480894809048091480924809348094480954809648097480984809948100481014810248103481044810548106481074810848109481104811148112481134811448115481164811748118481194812048121481224812348124481254812648127481284812948130481314813248133481344813548136481374813848139481404814148142481434814448145481464814748148481494815048151481524815348154481554815648157481584815948160481614816248163481644816548166481674816848169481704817148172481734817448175481764817748178481794818048181481824818348184481854818648187481884818948190481914819248193481944819548196481974819848199482004820148202482034820448205482064820748208482094821048211482124821348214482154821648217482184821948220482214822248223482244822548226482274822848229482304823148232482334823448235482364823748238482394824048241482424824348244482454824648247482484824948250482514825248253482544825548256482574825848259482604826148262482634826448265482664826748268482694827048271482724827348274482754827648277482784827948280482814828248283482844828548286482874828848289482904829148292482934829448295482964829748298482994830048301483024830348304483054830648307483084830948310483114831248313483144831548316483174831848319483204832148322483234832448325483264832748328483294833048331483324833348334483354833648337483384833948340483414834248343483444834548346483474834848349483504835148352483534835448355483564835748358483594836048361483624836348364483654836648367483684836948370483714837248373483744837548376483774837848379483804838148382483834838448385483864838748388483894839048391483924839348394483954839648397483984839948400484014840248403484044840548406484074840848409484104841148412484134841448415484164841748418484194842048421484224842348424484254842648427484284842948430484314843248433484344843548436484374843848439484404844148442484434844448445484464844748448484494845048451484524845348454484554845648457484584845948460484614846248463484644846548466484674846848469484704847148472484734847448475484764847748478484794848048481484824848348484484854848648487484884848948490484914849248493484944849548496484974849848499485004850148502485034850448505485064850748508485094851048511485124851348514485154851648517485184851948520485214852248523485244852548526485274852848529485304853148532485334853448535485364853748538485394854048541485424854348544485454854648547485484854948550485514855248553485544855548556485574855848559485604856148562485634856448565485664856748568485694857048571485724857348574485754857648577485784857948580485814858248583485844858548586485874858848589485904859148592485934859448595485964859748598485994860048601486024860348604486054860648607486084860948610486114861248613486144861548616486174861848619486204862148622486234862448625486264862748628486294863048631486324863348634486354863648637486384863948640486414864248643486444864548646486474864848649486504865148652486534865448655486564865748658486594866048661486624866348664486654866648667486684866948670486714867248673486744867548676486774867848679486804868148682486834868448685486864868748688486894869048691486924869348694486954869648697486984869948700487014870248703487044870548706487074870848709487104871148712487134871448715487164871748718487194872048721487224872348724487254872648727487284872948730487314873248733487344873548736487374873848739487404874148742487434874448745487464874748748487494875048751487524875348754487554875648757487584875948760487614876248763487644876548766487674876848769487704877148772487734877448775487764877748778487794878048781487824878348784487854878648787487884878948790487914879248793487944879548796487974879848799488004880148802488034880448805488064880748808488094881048811488124881348814488154881648817488184881948820488214882248823488244882548826488274882848829488304883148832488334883448835488364883748838488394884048841488424884348844488454884648847488484884948850488514885248853488544885548856488574885848859488604886148862488634886448865488664886748868488694887048871488724887348874488754887648877488784887948880488814888248883488844888548886488874888848889488904889148892488934889448895488964889748898488994890048901489024890348904489054890648907489084890948910489114891248913489144891548916489174891848919489204892148922489234892448925489264892748928489294893048931489324893348934489354893648937489384893948940489414894248943489444894548946489474894848949489504895148952489534895448955489564895748958489594896048961489624896348964489654896648967489684896948970489714897248973489744897548976489774897848979489804898148982489834898448985489864898748988489894899048991489924899348994489954899648997489984899949000490014900249003490044900549006490074900849009490104901149012490134901449015490164901749018490194902049021490224902349024490254902649027490284902949030490314903249033490344903549036490374903849039490404904149042490434904449045490464904749048490494905049051490524905349054490554905649057490584905949060490614906249063490644906549066490674906849069490704907149072490734907449075490764907749078490794908049081490824908349084490854908649087490884908949090490914909249093490944909549096490974909849099491004910149102491034910449105491064910749108491094911049111491124911349114491154911649117491184911949120491214912249123491244912549126491274912849129491304913149132491334913449135491364913749138491394914049141491424914349144491454914649147491484914949150491514915249153491544915549156491574915849159491604916149162491634916449165491664916749168491694917049171491724917349174491754917649177491784917949180491814918249183491844918549186491874918849189491904919149192491934919449195491964919749198491994920049201492024920349204492054920649207492084920949210492114921249213492144921549216492174921849219492204922149222492234922449225492264922749228492294923049231492324923349234492354923649237492384923949240492414924249243492444924549246492474924849249492504925149252492534925449255492564925749258492594926049261492624926349264492654926649267492684926949270492714927249273492744927549276492774927849279492804928149282492834928449285492864928749288492894929049291492924929349294492954929649297492984929949300493014930249303493044930549306493074930849309493104931149312493134931449315493164931749318493194932049321493224932349324493254932649327493284932949330493314933249333493344933549336493374933849339493404934149342493434934449345493464934749348493494935049351493524935349354493554935649357493584935949360493614936249363493644936549366493674936849369493704937149372493734937449375493764937749378493794938049381493824938349384493854938649387493884938949390493914939249393493944939549396493974939849399494004940149402494034940449405494064940749408494094941049411494124941349414494154941649417494184941949420494214942249423494244942549426494274942849429494304943149432494334943449435494364943749438494394944049441494424944349444494454944649447494484944949450494514945249453494544945549456494574945849459494604946149462494634946449465494664946749468494694947049471494724947349474494754947649477494784947949480494814948249483494844948549486494874948849489494904949149492494934949449495494964949749498494994950049501495024950349504495054950649507495084950949510495114951249513495144951549516495174951849519495204952149522495234952449525495264952749528495294953049531495324953349534495354953649537495384953949540495414954249543495444954549546495474954849549495504955149552495534955449555495564955749558495594956049561495624956349564495654956649567495684956949570495714957249573495744957549576495774957849579495804958149582495834958449585495864958749588495894959049591495924959349594495954959649597495984959949600496014960249603496044960549606496074960849609496104961149612496134961449615496164961749618496194962049621496224962349624496254962649627496284962949630496314963249633496344963549636496374963849639496404964149642496434964449645496464964749648496494965049651496524965349654496554965649657496584965949660496614966249663496644966549666496674966849669496704967149672496734967449675496764967749678496794968049681496824968349684496854968649687496884968949690496914969249693496944969549696496974969849699497004970149702497034970449705497064970749708497094971049711497124971349714497154971649717497184971949720497214972249723497244972549726497274972849729497304973149732497334973449735497364973749738497394974049741497424974349744497454974649747497484974949750497514975249753497544975549756497574975849759497604976149762497634976449765497664976749768497694977049771497724977349774497754977649777497784977949780497814978249783497844978549786497874978849789497904979149792497934979449795497964979749798497994980049801498024980349804498054980649807498084980949810498114981249813498144981549816498174981849819498204982149822498234982449825498264982749828498294983049831498324983349834498354983649837498384983949840498414984249843498444984549846498474984849849498504985149852498534985449855498564985749858498594986049861498624986349864498654986649867498684986949870498714987249873498744987549876498774987849879498804988149882498834988449885498864988749888498894989049891498924989349894498954989649897498984989949900499014990249903499044990549906499074990849909499104991149912499134991449915499164991749918499194992049921499224992349924499254992649927499284992949930499314993249933499344993549936499374993849939499404994149942499434994449945499464994749948499494995049951499524995349954499554995649957499584995949960499614996249963499644996549966499674996849969499704997149972499734997449975499764997749978499794998049981499824998349984499854998649987499884998949990499914999249993499944999549996499974999849999500005000150002500035000450005500065000750008500095001050011500125001350014500155001650017500185001950020500215002250023500245002550026500275002850029500305003150032500335003450035500365003750038500395004050041500425004350044500455004650047500485004950050500515005250053500545005550056500575005850059500605006150062500635006450065500665006750068500695007050071500725007350074500755007650077500785007950080500815008250083500845008550086500875008850089500905009150092500935009450095500965009750098500995010050101501025010350104501055010650107501085010950110501115011250113501145011550116501175011850119501205012150122501235012450125501265012750128501295013050131501325013350134501355013650137501385013950140501415014250143501445014550146501475014850149501505015150152501535015450155501565015750158501595016050161501625016350164501655016650167501685016950170501715017250173501745017550176501775017850179501805018150182501835018450185501865018750188501895019050191501925019350194501955019650197501985019950200502015020250203502045020550206502075020850209502105021150212502135021450215502165021750218502195022050221502225022350224502255022650227502285022950230502315023250233502345023550236502375023850239502405024150242502435024450245502465024750248502495025050251502525025350254502555025650257502585025950260502615026250263502645026550266502675026850269502705027150272502735027450275502765027750278502795028050281502825028350284502855028650287502885028950290502915029250293502945029550296502975029850299503005030150302503035030450305503065030750308503095031050311503125031350314503155031650317503185031950320503215032250323503245032550326503275032850329503305033150332503335033450335503365033750338503395034050341503425034350344503455034650347503485034950350503515035250353503545035550356503575035850359503605036150362503635036450365503665036750368503695037050371503725037350374503755037650377503785037950380503815038250383503845038550386503875038850389503905039150392503935039450395503965039750398503995040050401504025040350404504055040650407504085040950410504115041250413504145041550416504175041850419504205042150422504235042450425504265042750428504295043050431504325043350434504355043650437504385043950440504415044250443504445044550446504475044850449504505045150452504535045450455504565045750458504595046050461504625046350464504655046650467504685046950470504715047250473504745047550476504775047850479504805048150482504835048450485504865048750488504895049050491504925049350494504955049650497504985049950500505015050250503505045050550506505075050850509505105051150512505135051450515505165051750518505195052050521505225052350524505255052650527505285052950530505315053250533505345053550536505375053850539505405054150542505435054450545505465054750548505495055050551505525055350554505555055650557505585055950560505615056250563505645056550566505675056850569505705057150572505735057450575505765057750578505795058050581505825058350584505855058650587505885058950590505915059250593505945059550596505975059850599506005060150602506035060450605506065060750608506095061050611506125061350614506155061650617506185061950620506215062250623506245062550626506275062850629506305063150632506335063450635506365063750638506395064050641506425064350644506455064650647506485064950650506515065250653506545065550656506575065850659506605066150662506635066450665506665066750668506695067050671506725067350674506755067650677506785067950680506815068250683506845068550686506875068850689506905069150692506935069450695506965069750698506995070050701507025070350704507055070650707507085070950710507115071250713507145071550716507175071850719507205072150722507235072450725507265072750728507295073050731507325073350734507355073650737507385073950740507415074250743507445074550746507475074850749507505075150752507535075450755507565075750758507595076050761507625076350764507655076650767507685076950770507715077250773507745077550776507775077850779507805078150782507835078450785507865078750788507895079050791507925079350794507955079650797507985079950800508015080250803508045080550806508075080850809508105081150812508135081450815508165081750818508195082050821508225082350824508255082650827508285082950830508315083250833508345083550836508375083850839508405084150842508435084450845508465084750848508495085050851508525085350854508555085650857508585085950860508615086250863508645086550866508675086850869508705087150872508735087450875508765087750878508795088050881508825088350884508855088650887508885088950890508915089250893508945089550896508975089850899509005090150902509035090450905509065090750908509095091050911509125091350914509155091650917509185091950920509215092250923509245092550926509275092850929509305093150932509335093450935509365093750938509395094050941509425094350944509455094650947509485094950950509515095250953509545095550956509575095850959509605096150962509635096450965509665096750968509695097050971509725097350974509755097650977509785097950980509815098250983509845098550986509875098850989509905099150992509935099450995509965099750998509995100051001510025100351004510055100651007510085100951010510115101251013510145101551016510175101851019510205102151022510235102451025510265102751028510295103051031510325103351034510355103651037510385103951040510415104251043510445104551046510475104851049510505105151052510535105451055510565105751058510595106051061510625106351064510655106651067510685106951070510715107251073510745107551076510775107851079510805108151082510835108451085510865108751088510895109051091510925109351094510955109651097510985109951100511015110251103511045110551106511075110851109511105111151112511135111451115511165111751118511195112051121511225112351124511255112651127511285112951130511315113251133511345113551136511375113851139511405114151142511435114451145511465114751148511495115051151511525115351154511555115651157511585115951160511615116251163511645116551166511675116851169511705117151172511735117451175511765117751178511795118051181511825118351184511855118651187511885118951190511915119251193511945119551196511975119851199512005120151202512035120451205512065120751208512095121051211512125121351214512155121651217512185121951220512215122251223512245122551226512275122851229512305123151232512335123451235512365123751238512395124051241512425124351244512455124651247512485124951250512515125251253512545125551256512575125851259512605126151262512635126451265512665126751268512695127051271512725127351274512755127651277512785127951280512815128251283512845128551286512875128851289512905129151292512935129451295512965129751298512995130051301513025130351304513055130651307513085130951310513115131251313513145131551316513175131851319513205132151322513235132451325513265132751328513295133051331513325133351334513355133651337513385133951340513415134251343513445134551346513475134851349513505135151352513535135451355513565135751358513595136051361513625136351364513655136651367513685136951370513715137251373513745137551376513775137851379513805138151382513835138451385513865138751388513895139051391513925139351394513955139651397513985139951400514015140251403514045140551406514075140851409514105141151412514135141451415514165141751418514195142051421514225142351424514255142651427514285142951430514315143251433514345143551436514375143851439514405144151442514435144451445514465144751448514495145051451514525145351454514555145651457514585145951460514615146251463514645146551466514675146851469514705147151472514735147451475514765147751478514795148051481514825148351484514855148651487514885148951490514915149251493514945149551496514975149851499515005150151502515035150451505515065150751508515095151051511515125151351514515155151651517515185151951520515215152251523515245152551526515275152851529515305153151532515335153451535515365153751538515395154051541515425154351544515455154651547515485154951550515515155251553515545155551556515575155851559515605156151562515635156451565515665156751568515695157051571515725157351574515755157651577515785157951580515815158251583515845158551586515875158851589515905159151592515935159451595515965159751598515995160051601516025160351604516055160651607516085160951610516115161251613516145161551616516175161851619516205162151622516235162451625516265162751628516295163051631516325163351634516355163651637516385163951640516415164251643516445164551646516475164851649516505165151652516535165451655516565165751658516595166051661516625166351664516655166651667516685166951670516715167251673516745167551676516775167851679516805168151682516835168451685516865168751688516895169051691516925169351694516955169651697516985169951700517015170251703517045170551706517075170851709517105171151712517135171451715517165171751718517195172051721517225172351724517255172651727517285172951730517315173251733517345173551736517375173851739517405174151742517435174451745517465174751748517495175051751517525175351754517555175651757517585175951760517615176251763517645176551766517675176851769517705177151772517735177451775517765177751778517795178051781517825178351784517855178651787517885178951790517915179251793517945179551796517975179851799518005180151802518035180451805518065180751808518095181051811518125181351814518155181651817518185181951820518215182251823518245182551826518275182851829518305183151832518335183451835518365183751838518395184051841518425184351844518455184651847518485184951850518515185251853518545185551856518575185851859518605186151862518635186451865518665186751868518695187051871518725187351874518755187651877518785187951880518815188251883518845188551886518875188851889518905189151892518935189451895518965189751898518995190051901519025190351904519055190651907519085190951910519115191251913519145191551916519175191851919519205192151922519235192451925519265192751928519295193051931519325193351934519355193651937519385193951940519415194251943519445194551946519475194851949519505195151952519535195451955519565195751958519595196051961519625196351964519655196651967519685196951970519715197251973519745197551976519775197851979519805198151982519835198451985519865198751988519895199051991519925199351994519955199651997519985199952000520015200252003520045200552006520075200852009520105201152012520135201452015520165201752018520195202052021520225202352024520255202652027520285202952030520315203252033520345203552036520375203852039520405204152042520435204452045520465204752048520495205052051520525205352054520555205652057520585205952060520615206252063520645206552066520675206852069520705207152072520735207452075520765207752078520795208052081520825208352084520855208652087520885208952090520915209252093520945209552096520975209852099521005210152102521035210452105521065210752108521095211052111521125211352114521155211652117521185211952120521215212252123521245212552126521275212852129521305213152132521335213452135521365213752138521395214052141521425214352144521455214652147521485214952150521515215252153521545215552156521575215852159521605216152162521635216452165521665216752168521695217052171521725217352174521755217652177521785217952180521815218252183521845218552186521875218852189521905219152192521935219452195521965219752198521995220052201522025220352204522055220652207522085220952210522115221252213522145221552216522175221852219522205222152222522235222452225522265222752228522295223052231522325223352234522355223652237522385223952240522415224252243522445224552246522475224852249522505225152252522535225452255522565225752258522595226052261522625226352264522655226652267522685226952270522715227252273522745227552276522775227852279522805228152282522835228452285522865228752288522895229052291522925229352294522955229652297522985229952300523015230252303523045230552306523075230852309523105231152312523135231452315523165231752318523195232052321523225232352324523255232652327523285232952330523315233252333523345233552336523375233852339523405234152342523435234452345523465234752348523495235052351523525235352354523555235652357523585235952360523615236252363523645236552366523675236852369523705237152372523735237452375523765237752378523795238052381523825238352384523855238652387523885238952390523915239252393523945239552396523975239852399524005240152402524035240452405524065240752408524095241052411524125241352414524155241652417524185241952420524215242252423524245242552426524275242852429524305243152432524335243452435524365243752438524395244052441524425244352444524455244652447524485244952450524515245252453524545245552456524575245852459524605246152462524635246452465524665246752468524695247052471524725247352474524755247652477524785247952480524815248252483524845248552486524875248852489524905249152492524935249452495524965249752498524995250052501525025250352504525055250652507525085250952510525115251252513525145251552516525175251852519525205252152522525235252452525525265252752528525295253052531525325253352534525355253652537525385253952540525415254252543525445254552546525475254852549525505255152552525535255452555525565255752558525595256052561525625256352564525655256652567525685256952570525715257252573525745257552576525775257852579525805258152582525835258452585525865258752588525895259052591525925259352594525955259652597525985259952600526015260252603526045260552606526075260852609526105261152612526135261452615526165261752618526195262052621526225262352624526255262652627526285262952630526315263252633526345263552636526375263852639526405264152642526435264452645526465264752648526495265052651526525265352654526555265652657526585265952660526615266252663526645266552666526675266852669526705267152672526735267452675526765267752678526795268052681526825268352684526855268652687526885268952690526915269252693526945269552696526975269852699527005270152702527035270452705527065270752708527095271052711527125271352714527155271652717527185271952720527215272252723527245272552726527275272852729527305273152732527335273452735527365273752738527395274052741527425274352744527455274652747527485274952750527515275252753527545275552756527575275852759527605276152762527635276452765527665276752768527695277052771527725277352774527755277652777527785277952780527815278252783527845278552786527875278852789527905279152792527935279452795527965279752798527995280052801528025280352804528055280652807528085280952810528115281252813528145281552816528175281852819528205282152822528235282452825528265282752828528295283052831528325283352834528355283652837528385283952840528415284252843528445284552846528475284852849528505285152852528535285452855528565285752858528595286052861528625286352864528655286652867528685286952870528715287252873528745287552876528775287852879528805288152882528835288452885528865288752888528895289052891528925289352894528955289652897528985289952900529015290252903529045290552906529075290852909529105291152912529135291452915529165291752918529195292052921529225292352924529255292652927529285292952930529315293252933529345293552936529375293852939529405294152942529435294452945529465294752948529495295052951529525295352954529555295652957529585295952960529615296252963529645296552966529675296852969529705297152972529735297452975529765297752978529795298052981529825298352984529855298652987529885298952990529915299252993529945299552996529975299852999530005300153002530035300453005530065300753008530095301053011530125301353014530155301653017530185301953020530215302253023530245302553026530275302853029530305303153032530335303453035530365303753038530395304053041530425304353044530455304653047530485304953050530515305253053530545305553056530575305853059530605306153062530635306453065530665306753068530695307053071530725307353074530755307653077530785307953080530815308253083530845308553086530875308853089530905309153092530935309453095530965309753098530995310053101531025310353104531055310653107531085310953110531115311253113531145311553116531175311853119531205312153122531235312453125531265312753128531295313053131531325313353134531355313653137531385313953140531415314253143531445314553146531475314853149531505315153152531535315453155531565315753158531595316053161531625316353164531655316653167531685316953170531715317253173531745317553176531775317853179531805318153182531835318453185531865318753188531895319053191531925319353194531955319653197531985319953200532015320253203532045320553206532075320853209532105321153212532135321453215532165321753218532195322053221532225322353224532255322653227532285322953230532315323253233532345323553236532375323853239532405324153242532435324453245532465324753248532495325053251532525325353254532555325653257532585325953260532615326253263532645326553266532675326853269532705327153272532735327453275532765327753278532795328053281532825328353284532855328653287532885328953290532915329253293532945329553296532975329853299533005330153302533035330453305533065330753308533095331053311533125331353314533155331653317533185331953320533215332253323533245332553326533275332853329533305333153332533335333453335533365333753338533395334053341533425334353344533455334653347533485334953350533515335253353533545335553356533575335853359533605336153362533635336453365533665336753368533695337053371533725337353374533755337653377533785337953380533815338253383533845338553386533875338853389533905339153392533935339453395533965339753398533995340053401534025340353404534055340653407534085340953410534115341253413534145341553416534175341853419534205342153422534235342453425534265342753428534295343053431534325343353434534355343653437534385343953440534415344253443534445344553446534475344853449534505345153452534535345453455534565345753458534595346053461534625346353464534655346653467534685346953470534715347253473534745347553476534775347853479534805348153482534835348453485534865348753488534895349053491534925349353494534955349653497534985349953500535015350253503535045350553506535075350853509535105351153512535135351453515535165351753518535195352053521535225352353524535255352653527535285352953530535315353253533535345353553536535375353853539535405354153542535435354453545535465354753548535495355053551535525355353554535555355653557535585355953560535615356253563535645356553566535675356853569535705357153572535735357453575535765357753578535795358053581535825358353584535855358653587535885358953590535915359253593535945359553596535975359853599536005360153602536035360453605536065360753608536095361053611536125361353614536155361653617536185361953620536215362253623536245362553626536275362853629536305363153632536335363453635536365363753638536395364053641536425364353644536455364653647536485364953650536515365253653536545365553656536575365853659536605366153662536635366453665536665366753668536695367053671536725367353674536755367653677536785367953680536815368253683536845368553686536875368853689536905369153692536935369453695536965369753698536995370053701537025370353704
  1. /**
  2. * @license
  3. * Copyright 2010-2023 Three.js Authors
  4. * SPDX-License-Identifier: MIT
  5. */
  6. 'use strict';
  7. const REVISION = '162dev';
  8. const MOUSE = { LEFT: 0, MIDDLE: 1, RIGHT: 2, ROTATE: 0, DOLLY: 1, PAN: 2 };
  9. const TOUCH = { ROTATE: 0, PAN: 1, DOLLY_PAN: 2, DOLLY_ROTATE: 3 };
  10. const CullFaceNone = 0;
  11. const CullFaceBack = 1;
  12. const CullFaceFront = 2;
  13. const CullFaceFrontBack = 3;
  14. const BasicShadowMap = 0;
  15. const PCFShadowMap = 1;
  16. const PCFSoftShadowMap = 2;
  17. const VSMShadowMap = 3;
  18. const FrontSide = 0;
  19. const BackSide = 1;
  20. const DoubleSide = 2;
  21. const NoBlending = 0;
  22. const NormalBlending = 1;
  23. const AdditiveBlending = 2;
  24. const SubtractiveBlending = 3;
  25. const MultiplyBlending = 4;
  26. const CustomBlending = 5;
  27. const AddEquation = 100;
  28. const SubtractEquation = 101;
  29. const ReverseSubtractEquation = 102;
  30. const MinEquation = 103;
  31. const MaxEquation = 104;
  32. const ZeroFactor = 200;
  33. const OneFactor = 201;
  34. const SrcColorFactor = 202;
  35. const OneMinusSrcColorFactor = 203;
  36. const SrcAlphaFactor = 204;
  37. const OneMinusSrcAlphaFactor = 205;
  38. const DstAlphaFactor = 206;
  39. const OneMinusDstAlphaFactor = 207;
  40. const DstColorFactor = 208;
  41. const OneMinusDstColorFactor = 209;
  42. const SrcAlphaSaturateFactor = 210;
  43. const ConstantColorFactor = 211;
  44. const OneMinusConstantColorFactor = 212;
  45. const ConstantAlphaFactor = 213;
  46. const OneMinusConstantAlphaFactor = 214;
  47. const NeverDepth = 0;
  48. const AlwaysDepth = 1;
  49. const LessDepth = 2;
  50. const LessEqualDepth = 3;
  51. const EqualDepth = 4;
  52. const GreaterEqualDepth = 5;
  53. const GreaterDepth = 6;
  54. const NotEqualDepth = 7;
  55. const MultiplyOperation = 0;
  56. const MixOperation = 1;
  57. const AddOperation = 2;
  58. const NoToneMapping = 0;
  59. const LinearToneMapping = 1;
  60. const ReinhardToneMapping = 2;
  61. const CineonToneMapping = 3;
  62. const ACESFilmicToneMapping = 4;
  63. const CustomToneMapping = 5;
  64. const AgXToneMapping = 6;
  65. const NeutralToneMapping = 7;
  66. const AttachedBindMode = 'attached';
  67. const DetachedBindMode = 'detached';
  68. const UVMapping = 300;
  69. const CubeReflectionMapping = 301;
  70. const CubeRefractionMapping = 302;
  71. const EquirectangularReflectionMapping = 303;
  72. const EquirectangularRefractionMapping = 304;
  73. const CubeUVReflectionMapping = 306;
  74. const RepeatWrapping = 1000;
  75. const ClampToEdgeWrapping = 1001;
  76. const MirroredRepeatWrapping = 1002;
  77. const NearestFilter = 1003;
  78. const NearestMipmapNearestFilter = 1004;
  79. const NearestMipMapNearestFilter = 1004;
  80. const NearestMipmapLinearFilter = 1005;
  81. const NearestMipMapLinearFilter = 1005;
  82. const LinearFilter = 1006;
  83. const LinearMipmapNearestFilter = 1007;
  84. const LinearMipMapNearestFilter = 1007;
  85. const LinearMipmapLinearFilter = 1008;
  86. const LinearMipMapLinearFilter = 1008;
  87. const UnsignedByteType = 1009;
  88. const ByteType = 1010;
  89. const ShortType = 1011;
  90. const UnsignedShortType = 1012;
  91. const IntType = 1013;
  92. const UnsignedIntType = 1014;
  93. const FloatType = 1015;
  94. const HalfFloatType = 1016;
  95. const UnsignedShort4444Type = 1017;
  96. const UnsignedShort5551Type = 1018;
  97. const UnsignedInt248Type = 1020;
  98. const AlphaFormat = 1021;
  99. const RGBAFormat = 1023;
  100. const LuminanceFormat = 1024;
  101. const LuminanceAlphaFormat = 1025;
  102. const DepthFormat = 1026;
  103. const DepthStencilFormat = 1027;
  104. const RedFormat = 1028;
  105. const RedIntegerFormat = 1029;
  106. const RGFormat = 1030;
  107. const RGIntegerFormat = 1031;
  108. const RGBAIntegerFormat = 1033;
  109. const RGB_S3TC_DXT1_Format = 33776;
  110. const RGBA_S3TC_DXT1_Format = 33777;
  111. const RGBA_S3TC_DXT3_Format = 33778;
  112. const RGBA_S3TC_DXT5_Format = 33779;
  113. const RGB_PVRTC_4BPPV1_Format = 35840;
  114. const RGB_PVRTC_2BPPV1_Format = 35841;
  115. const RGBA_PVRTC_4BPPV1_Format = 35842;
  116. const RGBA_PVRTC_2BPPV1_Format = 35843;
  117. const RGB_ETC1_Format = 36196;
  118. const RGB_ETC2_Format = 37492;
  119. const RGBA_ETC2_EAC_Format = 37496;
  120. const RGBA_ASTC_4x4_Format = 37808;
  121. const RGBA_ASTC_5x4_Format = 37809;
  122. const RGBA_ASTC_5x5_Format = 37810;
  123. const RGBA_ASTC_6x5_Format = 37811;
  124. const RGBA_ASTC_6x6_Format = 37812;
  125. const RGBA_ASTC_8x5_Format = 37813;
  126. const RGBA_ASTC_8x6_Format = 37814;
  127. const RGBA_ASTC_8x8_Format = 37815;
  128. const RGBA_ASTC_10x5_Format = 37816;
  129. const RGBA_ASTC_10x6_Format = 37817;
  130. const RGBA_ASTC_10x8_Format = 37818;
  131. const RGBA_ASTC_10x10_Format = 37819;
  132. const RGBA_ASTC_12x10_Format = 37820;
  133. const RGBA_ASTC_12x12_Format = 37821;
  134. const RGBA_BPTC_Format = 36492;
  135. const RGB_BPTC_SIGNED_Format = 36494;
  136. const RGB_BPTC_UNSIGNED_Format = 36495;
  137. const RED_RGTC1_Format = 36283;
  138. const SIGNED_RED_RGTC1_Format = 36284;
  139. const RED_GREEN_RGTC2_Format = 36285;
  140. const SIGNED_RED_GREEN_RGTC2_Format = 36286;
  141. const LoopOnce = 2200;
  142. const LoopRepeat = 2201;
  143. const LoopPingPong = 2202;
  144. const InterpolateDiscrete = 2300;
  145. const InterpolateLinear = 2301;
  146. const InterpolateSmooth = 2302;
  147. const ZeroCurvatureEnding = 2400;
  148. const ZeroSlopeEnding = 2401;
  149. const WrapAroundEnding = 2402;
  150. const NormalAnimationBlendMode = 2500;
  151. const AdditiveAnimationBlendMode = 2501;
  152. const TrianglesDrawMode = 0;
  153. const TriangleStripDrawMode = 1;
  154. const TriangleFanDrawMode = 2;
  155. const BasicDepthPacking = 3200;
  156. const RGBADepthPacking = 3201;
  157. const TangentSpaceNormalMap = 0;
  158. const ObjectSpaceNormalMap = 1;
  159. // Color space string identifiers, matching CSS Color Module Level 4 and WebGPU names where available.
  160. const NoColorSpace = '';
  161. const SRGBColorSpace = 'srgb';
  162. const LinearSRGBColorSpace = 'srgb-linear';
  163. const DisplayP3ColorSpace = 'display-p3';
  164. const LinearDisplayP3ColorSpace = 'display-p3-linear';
  165. const LinearTransfer = 'linear';
  166. const SRGBTransfer = 'srgb';
  167. const Rec709Primaries = 'rec709';
  168. const P3Primaries = 'p3';
  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 NeverCompare = 512;
  186. const LessCompare = 513;
  187. const EqualCompare = 514;
  188. const LessEqualCompare = 515;
  189. const GreaterCompare = 516;
  190. const NotEqualCompare = 517;
  191. const GreaterEqualCompare = 518;
  192. const AlwaysCompare = 519;
  193. const StaticDrawUsage = 35044;
  194. const DynamicDrawUsage = 35048;
  195. const StreamDrawUsage = 35040;
  196. const StaticReadUsage = 35045;
  197. const DynamicReadUsage = 35049;
  198. const StreamReadUsage = 35041;
  199. const StaticCopyUsage = 35046;
  200. const DynamicCopyUsage = 35050;
  201. const StreamCopyUsage = 35042;
  202. const GLSL1 = '100';
  203. const GLSL3 = '300 es';
  204. const _SRGBAFormat = 1035; // fallback for WebGL 1
  205. const WebGLCoordinateSystem = 2000;
  206. const WebGPUCoordinateSystem = 2001;
  207. /**
  208. * https://github.com/mrdoob/eventdispatcher.js/
  209. */
  210. class EventDispatcher {
  211. addEventListener( type, listener ) {
  212. if ( this._listeners === undefined ) this._listeners = {};
  213. const listeners = this._listeners;
  214. if ( listeners[ type ] === undefined ) {
  215. listeners[ type ] = [];
  216. }
  217. if ( listeners[ type ].indexOf( listener ) === - 1 ) {
  218. listeners[ type ].push( listener );
  219. }
  220. }
  221. hasEventListener( type, listener ) {
  222. if ( this._listeners === undefined ) return false;
  223. const listeners = this._listeners;
  224. return listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== - 1;
  225. }
  226. removeEventListener( type, listener ) {
  227. if ( this._listeners === undefined ) return;
  228. const listeners = this._listeners;
  229. const listenerArray = listeners[ type ];
  230. if ( listenerArray !== undefined ) {
  231. const index = listenerArray.indexOf( listener );
  232. if ( index !== - 1 ) {
  233. listenerArray.splice( index, 1 );
  234. }
  235. }
  236. }
  237. dispatchEvent( event ) {
  238. if ( this._listeners === undefined ) return;
  239. const listeners = this._listeners;
  240. const listenerArray = listeners[ event.type ];
  241. if ( listenerArray !== undefined ) {
  242. event.target = this;
  243. // Make a copy, in case listeners are removed while iterating.
  244. const array = listenerArray.slice( 0 );
  245. for ( let i = 0, l = array.length; i < l; i ++ ) {
  246. array[ i ].call( this, event );
  247. }
  248. event.target = null;
  249. }
  250. }
  251. }
  252. const _lut = [ '00', '01', '02', '03', '04', '05', '06', '07', '08', '09', '0a', '0b', '0c', '0d', '0e', '0f', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '1a', '1b', '1c', '1d', '1e', '1f', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '2a', '2b', '2c', '2d', '2e', '2f', '30', '31', '32', '33', '34', '35', '36', '37', '38', '39', '3a', '3b', '3c', '3d', '3e', '3f', '40', '41', '42', '43', '44', '45', '46', '47', '48', '49', '4a', '4b', '4c', '4d', '4e', '4f', '50', '51', '52', '53', '54', '55', '56', '57', '58', '59', '5a', '5b', '5c', '5d', '5e', '5f', '60', '61', '62', '63', '64', '65', '66', '67', '68', '69', '6a', '6b', '6c', '6d', '6e', '6f', '70', '71', '72', '73', '74', '75', '76', '77', '78', '79', '7a', '7b', '7c', '7d', '7e', '7f', '80', '81', '82', '83', '84', '85', '86', '87', '88', '89', '8a', '8b', '8c', '8d', '8e', '8f', '90', '91', '92', '93', '94', '95', '96', '97', '98', '99', '9a', '9b', '9c', '9d', '9e', '9f', 'a0', 'a1', 'a2', 'a3', 'a4', 'a5', 'a6', 'a7', 'a8', 'a9', 'aa', 'ab', 'ac', 'ad', 'ae', 'af', 'b0', 'b1', 'b2', 'b3', 'b4', 'b5', 'b6', 'b7', 'b8', 'b9', 'ba', 'bb', 'bc', 'bd', 'be', 'bf', 'c0', 'c1', 'c2', 'c3', 'c4', 'c5', 'c6', 'c7', 'c8', 'c9', 'ca', 'cb', 'cc', 'cd', 'ce', 'cf', 'd0', 'd1', 'd2', 'd3', 'd4', 'd5', 'd6', 'd7', 'd8', 'd9', 'da', 'db', 'dc', 'dd', 'de', 'df', 'e0', 'e1', 'e2', 'e3', 'e4', 'e5', 'e6', 'e7', 'e8', 'e9', 'ea', 'eb', 'ec', 'ed', 'ee', 'ef', 'f0', 'f1', 'f2', 'f3', 'f4', 'f5', 'f6', 'f7', 'f8', 'f9', 'fa', 'fb', 'fc', 'fd', 'fe', 'ff' ];
  253. let _seed = 1234567;
  254. const DEG2RAD = Math.PI / 180;
  255. const RAD2DEG = 180 / Math.PI;
  256. // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/21963136#21963136
  257. function generateUUID() {
  258. const d0 = Math.random() * 0xffffffff | 0;
  259. const d1 = Math.random() * 0xffffffff | 0;
  260. const d2 = Math.random() * 0xffffffff | 0;
  261. const d3 = Math.random() * 0xffffffff | 0;
  262. const uuid = _lut[ d0 & 0xff ] + _lut[ d0 >> 8 & 0xff ] + _lut[ d0 >> 16 & 0xff ] + _lut[ d0 >> 24 & 0xff ] + '-' +
  263. _lut[ d1 & 0xff ] + _lut[ d1 >> 8 & 0xff ] + '-' + _lut[ d1 >> 16 & 0x0f | 0x40 ] + _lut[ d1 >> 24 & 0xff ] + '-' +
  264. _lut[ d2 & 0x3f | 0x80 ] + _lut[ d2 >> 8 & 0xff ] + '-' + _lut[ d2 >> 16 & 0xff ] + _lut[ d2 >> 24 & 0xff ] +
  265. _lut[ d3 & 0xff ] + _lut[ d3 >> 8 & 0xff ] + _lut[ d3 >> 16 & 0xff ] + _lut[ d3 >> 24 & 0xff ];
  266. // .toLowerCase() here flattens concatenated strings to save heap memory space.
  267. return uuid.toLowerCase();
  268. }
  269. function clamp( value, min, max ) {
  270. return Math.max( min, Math.min( max, value ) );
  271. }
  272. // compute euclidean modulo of m % n
  273. // https://en.wikipedia.org/wiki/Modulo_operation
  274. function euclideanModulo( n, m ) {
  275. return ( ( n % m ) + m ) % m;
  276. }
  277. // Linear mapping from range <a1, a2> to range <b1, b2>
  278. function mapLinear( x, a1, a2, b1, b2 ) {
  279. return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
  280. }
  281. // https://www.gamedev.net/tutorials/programming/general-and-gameplay-programming/inverse-lerp-a-super-useful-yet-often-overlooked-function-r5230/
  282. function inverseLerp( x, y, value ) {
  283. if ( x !== y ) {
  284. return ( value - x ) / ( y - x );
  285. } else {
  286. return 0;
  287. }
  288. }
  289. // https://en.wikipedia.org/wiki/Linear_interpolation
  290. function lerp( x, y, t ) {
  291. return ( 1 - t ) * x + t * y;
  292. }
  293. // http://www.rorydriscoll.com/2016/03/07/frame-rate-independent-damping-using-lerp/
  294. function damp( x, y, lambda, dt ) {
  295. return lerp( x, y, 1 - Math.exp( - lambda * dt ) );
  296. }
  297. // https://www.desmos.com/calculator/vcsjnyz7x4
  298. function pingpong( x, length = 1 ) {
  299. return length - Math.abs( euclideanModulo( x, length * 2 ) - length );
  300. }
  301. // http://en.wikipedia.org/wiki/Smoothstep
  302. function smoothstep( x, min, max ) {
  303. if ( x <= min ) return 0;
  304. if ( x >= max ) return 1;
  305. x = ( x - min ) / ( max - min );
  306. return x * x * ( 3 - 2 * x );
  307. }
  308. function smootherstep( x, min, max ) {
  309. if ( x <= min ) return 0;
  310. if ( x >= max ) return 1;
  311. x = ( x - min ) / ( max - min );
  312. return x * x * x * ( x * ( x * 6 - 15 ) + 10 );
  313. }
  314. // Random integer from <low, high> interval
  315. function randInt( low, high ) {
  316. return low + Math.floor( Math.random() * ( high - low + 1 ) );
  317. }
  318. // Random float from <low, high> interval
  319. function randFloat( low, high ) {
  320. return low + Math.random() * ( high - low );
  321. }
  322. // Random float from <-range/2, range/2> interval
  323. function randFloatSpread( range ) {
  324. return range * ( 0.5 - Math.random() );
  325. }
  326. // Deterministic pseudo-random float in the interval [ 0, 1 ]
  327. function seededRandom( s ) {
  328. if ( s !== undefined ) _seed = s;
  329. // Mulberry32 generator
  330. let t = _seed += 0x6D2B79F5;
  331. t = Math.imul( t ^ t >>> 15, t | 1 );
  332. t ^= t + Math.imul( t ^ t >>> 7, t | 61 );
  333. return ( ( t ^ t >>> 14 ) >>> 0 ) / 4294967296;
  334. }
  335. function degToRad( degrees ) {
  336. return degrees * DEG2RAD;
  337. }
  338. function radToDeg( radians ) {
  339. return radians * RAD2DEG;
  340. }
  341. function isPowerOfTwo( value ) {
  342. return ( value & ( value - 1 ) ) === 0 && value !== 0;
  343. }
  344. function ceilPowerOfTwo( value ) {
  345. return Math.pow( 2, Math.ceil( Math.log( value ) / Math.LN2 ) );
  346. }
  347. function floorPowerOfTwo( value ) {
  348. return Math.pow( 2, Math.floor( Math.log( value ) / Math.LN2 ) );
  349. }
  350. function setQuaternionFromProperEuler( q, a, b, c, order ) {
  351. // Intrinsic Proper Euler Angles - see https://en.wikipedia.org/wiki/Euler_angles
  352. // rotations are applied to the axes in the order specified by 'order'
  353. // rotation by angle 'a' is applied first, then by angle 'b', then by angle 'c'
  354. // angles are in radians
  355. const cos = Math.cos;
  356. const sin = Math.sin;
  357. const c2 = cos( b / 2 );
  358. const s2 = sin( b / 2 );
  359. const c13 = cos( ( a + c ) / 2 );
  360. const s13 = sin( ( a + c ) / 2 );
  361. const c1_3 = cos( ( a - c ) / 2 );
  362. const s1_3 = sin( ( a - c ) / 2 );
  363. const c3_1 = cos( ( c - a ) / 2 );
  364. const s3_1 = sin( ( c - a ) / 2 );
  365. switch ( order ) {
  366. case 'XYX':
  367. q.set( c2 * s13, s2 * c1_3, s2 * s1_3, c2 * c13 );
  368. break;
  369. case 'YZY':
  370. q.set( s2 * s1_3, c2 * s13, s2 * c1_3, c2 * c13 );
  371. break;
  372. case 'ZXZ':
  373. q.set( s2 * c1_3, s2 * s1_3, c2 * s13, c2 * c13 );
  374. break;
  375. case 'XZX':
  376. q.set( c2 * s13, s2 * s3_1, s2 * c3_1, c2 * c13 );
  377. break;
  378. case 'YXY':
  379. q.set( s2 * c3_1, c2 * s13, s2 * s3_1, c2 * c13 );
  380. break;
  381. case 'ZYZ':
  382. q.set( s2 * s3_1, s2 * c3_1, c2 * s13, c2 * c13 );
  383. break;
  384. default:
  385. console.warn( 'THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: ' + order );
  386. }
  387. }
  388. function denormalize( value, array ) {
  389. switch ( array.constructor ) {
  390. case Float32Array:
  391. return value;
  392. case Uint32Array:
  393. return value / 4294967295.0;
  394. case Uint16Array:
  395. return value / 65535.0;
  396. case Uint8Array:
  397. return value / 255.0;
  398. case Int32Array:
  399. return Math.max( value / 2147483647.0, - 1.0 );
  400. case Int16Array:
  401. return Math.max( value / 32767.0, - 1.0 );
  402. case Int8Array:
  403. return Math.max( value / 127.0, - 1.0 );
  404. default:
  405. throw new Error( 'Invalid component type.' );
  406. }
  407. }
  408. function normalize( value, array ) {
  409. switch ( array.constructor ) {
  410. case Float32Array:
  411. return value;
  412. case Uint32Array:
  413. return Math.round( value * 4294967295.0 );
  414. case Uint16Array:
  415. return Math.round( value * 65535.0 );
  416. case Uint8Array:
  417. return Math.round( value * 255.0 );
  418. case Int32Array:
  419. return Math.round( value * 2147483647.0 );
  420. case Int16Array:
  421. return Math.round( value * 32767.0 );
  422. case Int8Array:
  423. return Math.round( value * 127.0 );
  424. default:
  425. throw new Error( 'Invalid component type.' );
  426. }
  427. }
  428. const MathUtils = {
  429. DEG2RAD: DEG2RAD,
  430. RAD2DEG: RAD2DEG,
  431. generateUUID: generateUUID,
  432. clamp: clamp,
  433. euclideanModulo: euclideanModulo,
  434. mapLinear: mapLinear,
  435. inverseLerp: inverseLerp,
  436. lerp: lerp,
  437. damp: damp,
  438. pingpong: pingpong,
  439. smoothstep: smoothstep,
  440. smootherstep: smootherstep,
  441. randInt: randInt,
  442. randFloat: randFloat,
  443. randFloatSpread: randFloatSpread,
  444. seededRandom: seededRandom,
  445. degToRad: degToRad,
  446. radToDeg: radToDeg,
  447. isPowerOfTwo: isPowerOfTwo,
  448. ceilPowerOfTwo: ceilPowerOfTwo,
  449. floorPowerOfTwo: floorPowerOfTwo,
  450. setQuaternionFromProperEuler: setQuaternionFromProperEuler,
  451. normalize: normalize,
  452. denormalize: denormalize
  453. };
  454. class Vector2 {
  455. constructor( x = 0, y = 0 ) {
  456. Vector2.prototype.isVector2 = true;
  457. this.x = x;
  458. this.y = y;
  459. }
  460. get width() {
  461. return this.x;
  462. }
  463. set width( value ) {
  464. this.x = value;
  465. }
  466. get height() {
  467. return this.y;
  468. }
  469. set height( value ) {
  470. this.y = value;
  471. }
  472. set( x, y ) {
  473. this.x = x;
  474. this.y = y;
  475. return this;
  476. }
  477. setScalar( scalar ) {
  478. this.x = scalar;
  479. this.y = scalar;
  480. return this;
  481. }
  482. setX( x ) {
  483. this.x = x;
  484. return this;
  485. }
  486. setY( y ) {
  487. this.y = y;
  488. return this;
  489. }
  490. setComponent( index, value ) {
  491. switch ( index ) {
  492. case 0: this.x = value; break;
  493. case 1: this.y = value; break;
  494. default: throw new Error( 'index is out of range: ' + index );
  495. }
  496. return this;
  497. }
  498. getComponent( index ) {
  499. switch ( index ) {
  500. case 0: return this.x;
  501. case 1: return this.y;
  502. default: throw new Error( 'index is out of range: ' + index );
  503. }
  504. }
  505. clone() {
  506. return new this.constructor( this.x, this.y );
  507. }
  508. copy( v ) {
  509. this.x = v.x;
  510. this.y = v.y;
  511. return this;
  512. }
  513. add( v ) {
  514. this.x += v.x;
  515. this.y += v.y;
  516. return this;
  517. }
  518. addScalar( s ) {
  519. this.x += s;
  520. this.y += s;
  521. return this;
  522. }
  523. addVectors( a, b ) {
  524. this.x = a.x + b.x;
  525. this.y = a.y + b.y;
  526. return this;
  527. }
  528. addScaledVector( v, s ) {
  529. this.x += v.x * s;
  530. this.y += v.y * s;
  531. return this;
  532. }
  533. sub( v ) {
  534. this.x -= v.x;
  535. this.y -= v.y;
  536. return this;
  537. }
  538. subScalar( s ) {
  539. this.x -= s;
  540. this.y -= s;
  541. return this;
  542. }
  543. subVectors( a, b ) {
  544. this.x = a.x - b.x;
  545. this.y = a.y - b.y;
  546. return this;
  547. }
  548. multiply( v ) {
  549. this.x *= v.x;
  550. this.y *= v.y;
  551. return this;
  552. }
  553. multiplyScalar( scalar ) {
  554. this.x *= scalar;
  555. this.y *= scalar;
  556. return this;
  557. }
  558. divide( v ) {
  559. this.x /= v.x;
  560. this.y /= v.y;
  561. return this;
  562. }
  563. divideScalar( scalar ) {
  564. return this.multiplyScalar( 1 / scalar );
  565. }
  566. applyMatrix3( m ) {
  567. const x = this.x, y = this.y;
  568. const e = m.elements;
  569. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ];
  570. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ];
  571. return this;
  572. }
  573. min( v ) {
  574. this.x = Math.min( this.x, v.x );
  575. this.y = Math.min( this.y, v.y );
  576. return this;
  577. }
  578. max( v ) {
  579. this.x = Math.max( this.x, v.x );
  580. this.y = Math.max( this.y, v.y );
  581. return this;
  582. }
  583. clamp( min, max ) {
  584. // assumes min < max, componentwise
  585. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  586. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  587. return this;
  588. }
  589. clampScalar( minVal, maxVal ) {
  590. this.x = Math.max( minVal, Math.min( maxVal, this.x ) );
  591. this.y = Math.max( minVal, Math.min( maxVal, this.y ) );
  592. return this;
  593. }
  594. clampLength( min, max ) {
  595. const length = this.length();
  596. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  597. }
  598. floor() {
  599. this.x = Math.floor( this.x );
  600. this.y = Math.floor( this.y );
  601. return this;
  602. }
  603. ceil() {
  604. this.x = Math.ceil( this.x );
  605. this.y = Math.ceil( this.y );
  606. return this;
  607. }
  608. round() {
  609. this.x = Math.round( this.x );
  610. this.y = Math.round( this.y );
  611. return this;
  612. }
  613. roundToZero() {
  614. this.x = Math.trunc( this.x );
  615. this.y = Math.trunc( this.y );
  616. return this;
  617. }
  618. negate() {
  619. this.x = - this.x;
  620. this.y = - this.y;
  621. return this;
  622. }
  623. dot( v ) {
  624. return this.x * v.x + this.y * v.y;
  625. }
  626. cross( v ) {
  627. return this.x * v.y - this.y * v.x;
  628. }
  629. lengthSq() {
  630. return this.x * this.x + this.y * this.y;
  631. }
  632. length() {
  633. return Math.sqrt( this.x * this.x + this.y * this.y );
  634. }
  635. manhattanLength() {
  636. return Math.abs( this.x ) + Math.abs( this.y );
  637. }
  638. normalize() {
  639. return this.divideScalar( this.length() || 1 );
  640. }
  641. angle() {
  642. // computes the angle in radians with respect to the positive x-axis
  643. const angle = Math.atan2( - this.y, - this.x ) + Math.PI;
  644. return angle;
  645. }
  646. angleTo( v ) {
  647. const denominator = Math.sqrt( this.lengthSq() * v.lengthSq() );
  648. if ( denominator === 0 ) return Math.PI / 2;
  649. const theta = this.dot( v ) / denominator;
  650. // clamp, to handle numerical problems
  651. return Math.acos( clamp( theta, - 1, 1 ) );
  652. }
  653. distanceTo( v ) {
  654. return Math.sqrt( this.distanceToSquared( v ) );
  655. }
  656. distanceToSquared( v ) {
  657. const dx = this.x - v.x, dy = this.y - v.y;
  658. return dx * dx + dy * dy;
  659. }
  660. manhattanDistanceTo( v ) {
  661. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y );
  662. }
  663. setLength( length ) {
  664. return this.normalize().multiplyScalar( length );
  665. }
  666. lerp( v, alpha ) {
  667. this.x += ( v.x - this.x ) * alpha;
  668. this.y += ( v.y - this.y ) * alpha;
  669. return this;
  670. }
  671. lerpVectors( v1, v2, alpha ) {
  672. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  673. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  674. return this;
  675. }
  676. equals( v ) {
  677. return ( ( v.x === this.x ) && ( v.y === this.y ) );
  678. }
  679. fromArray( array, offset = 0 ) {
  680. this.x = array[ offset ];
  681. this.y = array[ offset + 1 ];
  682. return this;
  683. }
  684. toArray( array = [], offset = 0 ) {
  685. array[ offset ] = this.x;
  686. array[ offset + 1 ] = this.y;
  687. return array;
  688. }
  689. fromBufferAttribute( attribute, index ) {
  690. this.x = attribute.getX( index );
  691. this.y = attribute.getY( index );
  692. return this;
  693. }
  694. rotateAround( center, angle ) {
  695. const c = Math.cos( angle ), s = Math.sin( angle );
  696. const x = this.x - center.x;
  697. const y = this.y - center.y;
  698. this.x = x * c - y * s + center.x;
  699. this.y = x * s + y * c + center.y;
  700. return this;
  701. }
  702. random() {
  703. this.x = Math.random();
  704. this.y = Math.random();
  705. return this;
  706. }
  707. *[ Symbol.iterator ]() {
  708. yield this.x;
  709. yield this.y;
  710. }
  711. }
  712. class Matrix3 {
  713. constructor( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  714. Matrix3.prototype.isMatrix3 = true;
  715. this.elements = [
  716. 1, 0, 0,
  717. 0, 1, 0,
  718. 0, 0, 1
  719. ];
  720. if ( n11 !== undefined ) {
  721. this.set( n11, n12, n13, n21, n22, n23, n31, n32, n33 );
  722. }
  723. }
  724. set( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  725. const te = this.elements;
  726. te[ 0 ] = n11; te[ 1 ] = n21; te[ 2 ] = n31;
  727. te[ 3 ] = n12; te[ 4 ] = n22; te[ 5 ] = n32;
  728. te[ 6 ] = n13; te[ 7 ] = n23; te[ 8 ] = n33;
  729. return this;
  730. }
  731. identity() {
  732. this.set(
  733. 1, 0, 0,
  734. 0, 1, 0,
  735. 0, 0, 1
  736. );
  737. return this;
  738. }
  739. copy( m ) {
  740. const te = this.elements;
  741. const me = m.elements;
  742. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ];
  743. te[ 3 ] = me[ 3 ]; te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ];
  744. te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ]; te[ 8 ] = me[ 8 ];
  745. return this;
  746. }
  747. extractBasis( xAxis, yAxis, zAxis ) {
  748. xAxis.setFromMatrix3Column( this, 0 );
  749. yAxis.setFromMatrix3Column( this, 1 );
  750. zAxis.setFromMatrix3Column( this, 2 );
  751. return this;
  752. }
  753. setFromMatrix4( m ) {
  754. const me = m.elements;
  755. this.set(
  756. me[ 0 ], me[ 4 ], me[ 8 ],
  757. me[ 1 ], me[ 5 ], me[ 9 ],
  758. me[ 2 ], me[ 6 ], me[ 10 ]
  759. );
  760. return this;
  761. }
  762. multiply( m ) {
  763. return this.multiplyMatrices( this, m );
  764. }
  765. premultiply( m ) {
  766. return this.multiplyMatrices( m, this );
  767. }
  768. multiplyMatrices( a, b ) {
  769. const ae = a.elements;
  770. const be = b.elements;
  771. const te = this.elements;
  772. const a11 = ae[ 0 ], a12 = ae[ 3 ], a13 = ae[ 6 ];
  773. const a21 = ae[ 1 ], a22 = ae[ 4 ], a23 = ae[ 7 ];
  774. const a31 = ae[ 2 ], a32 = ae[ 5 ], a33 = ae[ 8 ];
  775. const b11 = be[ 0 ], b12 = be[ 3 ], b13 = be[ 6 ];
  776. const b21 = be[ 1 ], b22 = be[ 4 ], b23 = be[ 7 ];
  777. const b31 = be[ 2 ], b32 = be[ 5 ], b33 = be[ 8 ];
  778. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31;
  779. te[ 3 ] = a11 * b12 + a12 * b22 + a13 * b32;
  780. te[ 6 ] = a11 * b13 + a12 * b23 + a13 * b33;
  781. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31;
  782. te[ 4 ] = a21 * b12 + a22 * b22 + a23 * b32;
  783. te[ 7 ] = a21 * b13 + a22 * b23 + a23 * b33;
  784. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31;
  785. te[ 5 ] = a31 * b12 + a32 * b22 + a33 * b32;
  786. te[ 8 ] = a31 * b13 + a32 * b23 + a33 * b33;
  787. return this;
  788. }
  789. multiplyScalar( s ) {
  790. const te = this.elements;
  791. te[ 0 ] *= s; te[ 3 ] *= s; te[ 6 ] *= s;
  792. te[ 1 ] *= s; te[ 4 ] *= s; te[ 7 ] *= s;
  793. te[ 2 ] *= s; te[ 5 ] *= s; te[ 8 ] *= s;
  794. return this;
  795. }
  796. determinant() {
  797. const te = this.elements;
  798. const a = te[ 0 ], b = te[ 1 ], c = te[ 2 ],
  799. d = te[ 3 ], e = te[ 4 ], f = te[ 5 ],
  800. g = te[ 6 ], h = te[ 7 ], i = te[ 8 ];
  801. return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g;
  802. }
  803. invert() {
  804. const te = this.elements,
  805. n11 = te[ 0 ], n21 = te[ 1 ], n31 = te[ 2 ],
  806. n12 = te[ 3 ], n22 = te[ 4 ], n32 = te[ 5 ],
  807. n13 = te[ 6 ], n23 = te[ 7 ], n33 = te[ 8 ],
  808. t11 = n33 * n22 - n32 * n23,
  809. t12 = n32 * n13 - n33 * n12,
  810. t13 = n23 * n12 - n22 * n13,
  811. det = n11 * t11 + n21 * t12 + n31 * t13;
  812. if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0 );
  813. const detInv = 1 / det;
  814. te[ 0 ] = t11 * detInv;
  815. te[ 1 ] = ( n31 * n23 - n33 * n21 ) * detInv;
  816. te[ 2 ] = ( n32 * n21 - n31 * n22 ) * detInv;
  817. te[ 3 ] = t12 * detInv;
  818. te[ 4 ] = ( n33 * n11 - n31 * n13 ) * detInv;
  819. te[ 5 ] = ( n31 * n12 - n32 * n11 ) * detInv;
  820. te[ 6 ] = t13 * detInv;
  821. te[ 7 ] = ( n21 * n13 - n23 * n11 ) * detInv;
  822. te[ 8 ] = ( n22 * n11 - n21 * n12 ) * detInv;
  823. return this;
  824. }
  825. transpose() {
  826. let tmp;
  827. const m = this.elements;
  828. tmp = m[ 1 ]; m[ 1 ] = m[ 3 ]; m[ 3 ] = tmp;
  829. tmp = m[ 2 ]; m[ 2 ] = m[ 6 ]; m[ 6 ] = tmp;
  830. tmp = m[ 5 ]; m[ 5 ] = m[ 7 ]; m[ 7 ] = tmp;
  831. return this;
  832. }
  833. getNormalMatrix( matrix4 ) {
  834. return this.setFromMatrix4( matrix4 ).invert().transpose();
  835. }
  836. transposeIntoArray( r ) {
  837. const m = this.elements;
  838. r[ 0 ] = m[ 0 ];
  839. r[ 1 ] = m[ 3 ];
  840. r[ 2 ] = m[ 6 ];
  841. r[ 3 ] = m[ 1 ];
  842. r[ 4 ] = m[ 4 ];
  843. r[ 5 ] = m[ 7 ];
  844. r[ 6 ] = m[ 2 ];
  845. r[ 7 ] = m[ 5 ];
  846. r[ 8 ] = m[ 8 ];
  847. return this;
  848. }
  849. setUvTransform( tx, ty, sx, sy, rotation, cx, cy ) {
  850. const c = Math.cos( rotation );
  851. const s = Math.sin( rotation );
  852. this.set(
  853. sx * c, sx * s, - sx * ( c * cx + s * cy ) + cx + tx,
  854. - sy * s, sy * c, - sy * ( - s * cx + c * cy ) + cy + ty,
  855. 0, 0, 1
  856. );
  857. return this;
  858. }
  859. //
  860. scale( sx, sy ) {
  861. this.premultiply( _m3.makeScale( sx, sy ) );
  862. return this;
  863. }
  864. rotate( theta ) {
  865. this.premultiply( _m3.makeRotation( - theta ) );
  866. return this;
  867. }
  868. translate( tx, ty ) {
  869. this.premultiply( _m3.makeTranslation( tx, ty ) );
  870. return this;
  871. }
  872. // for 2D Transforms
  873. makeTranslation( x, y ) {
  874. if ( x.isVector2 ) {
  875. this.set(
  876. 1, 0, x.x,
  877. 0, 1, x.y,
  878. 0, 0, 1
  879. );
  880. } else {
  881. this.set(
  882. 1, 0, x,
  883. 0, 1, y,
  884. 0, 0, 1
  885. );
  886. }
  887. return this;
  888. }
  889. makeRotation( theta ) {
  890. // counterclockwise
  891. const c = Math.cos( theta );
  892. const s = Math.sin( theta );
  893. this.set(
  894. c, - s, 0,
  895. s, c, 0,
  896. 0, 0, 1
  897. );
  898. return this;
  899. }
  900. makeScale( x, y ) {
  901. this.set(
  902. x, 0, 0,
  903. 0, y, 0,
  904. 0, 0, 1
  905. );
  906. return this;
  907. }
  908. //
  909. equals( matrix ) {
  910. const te = this.elements;
  911. const me = matrix.elements;
  912. for ( let i = 0; i < 9; i ++ ) {
  913. if ( te[ i ] !== me[ i ] ) return false;
  914. }
  915. return true;
  916. }
  917. fromArray( array, offset = 0 ) {
  918. for ( let i = 0; i < 9; i ++ ) {
  919. this.elements[ i ] = array[ i + offset ];
  920. }
  921. return this;
  922. }
  923. toArray( array = [], offset = 0 ) {
  924. const te = this.elements;
  925. array[ offset ] = te[ 0 ];
  926. array[ offset + 1 ] = te[ 1 ];
  927. array[ offset + 2 ] = te[ 2 ];
  928. array[ offset + 3 ] = te[ 3 ];
  929. array[ offset + 4 ] = te[ 4 ];
  930. array[ offset + 5 ] = te[ 5 ];
  931. array[ offset + 6 ] = te[ 6 ];
  932. array[ offset + 7 ] = te[ 7 ];
  933. array[ offset + 8 ] = te[ 8 ];
  934. return array;
  935. }
  936. clone() {
  937. return new this.constructor().fromArray( this.elements );
  938. }
  939. }
  940. const _m3 = /*@__PURE__*/ new Matrix3();
  941. function arrayNeedsUint32( array ) {
  942. // assumes larger values usually on last
  943. for ( let i = array.length - 1; i >= 0; -- i ) {
  944. if ( array[ i ] >= 65535 ) return true; // account for PRIMITIVE_RESTART_FIXED_INDEX, #24565
  945. }
  946. return false;
  947. }
  948. const TYPED_ARRAYS = {
  949. Int8Array: Int8Array,
  950. Uint8Array: Uint8Array,
  951. Uint8ClampedArray: Uint8ClampedArray,
  952. Int16Array: Int16Array,
  953. Uint16Array: Uint16Array,
  954. Int32Array: Int32Array,
  955. Uint32Array: Uint32Array,
  956. Float32Array: Float32Array,
  957. Float64Array: Float64Array
  958. };
  959. function getTypedArray( type, buffer ) {
  960. return new TYPED_ARRAYS[ type ]( buffer );
  961. }
  962. function createElementNS( name ) {
  963. return document.createElementNS( 'http://www.w3.org/1999/xhtml', name );
  964. }
  965. function createCanvasElement() {
  966. const canvas = createElementNS( 'canvas' );
  967. canvas.style.display = 'block';
  968. return canvas;
  969. }
  970. const _cache = {};
  971. function warnOnce( message ) {
  972. if ( message in _cache ) return;
  973. _cache[ message ] = true;
  974. console.warn( message );
  975. }
  976. /**
  977. * Matrices converting P3 <-> Rec. 709 primaries, without gamut mapping
  978. * or clipping. Based on W3C specifications for sRGB and Display P3,
  979. * and ICC specifications for the D50 connection space. Values in/out
  980. * are _linear_ sRGB and _linear_ Display P3.
  981. *
  982. * Note that both sRGB and Display P3 use the sRGB transfer functions.
  983. *
  984. * Reference:
  985. * - http://www.russellcottrell.com/photo/matrixCalculator.htm
  986. */
  987. const LINEAR_SRGB_TO_LINEAR_DISPLAY_P3 = /*@__PURE__*/ new Matrix3().set(
  988. 0.8224621, 0.177538, 0.0,
  989. 0.0331941, 0.9668058, 0.0,
  990. 0.0170827, 0.0723974, 0.9105199,
  991. );
  992. const LINEAR_DISPLAY_P3_TO_LINEAR_SRGB = /*@__PURE__*/ new Matrix3().set(
  993. 1.2249401, - 0.2249404, 0.0,
  994. - 0.0420569, 1.0420571, 0.0,
  995. - 0.0196376, - 0.0786361, 1.0982735
  996. );
  997. /**
  998. * Defines supported color spaces by transfer function and primaries,
  999. * and provides conversions to/from the Linear-sRGB reference space.
  1000. */
  1001. const COLOR_SPACES = {
  1002. [ LinearSRGBColorSpace ]: {
  1003. transfer: LinearTransfer,
  1004. primaries: Rec709Primaries,
  1005. toReference: ( color ) => color,
  1006. fromReference: ( color ) => color,
  1007. },
  1008. [ SRGBColorSpace ]: {
  1009. transfer: SRGBTransfer,
  1010. primaries: Rec709Primaries,
  1011. toReference: ( color ) => color.convertSRGBToLinear(),
  1012. fromReference: ( color ) => color.convertLinearToSRGB(),
  1013. },
  1014. [ LinearDisplayP3ColorSpace ]: {
  1015. transfer: LinearTransfer,
  1016. primaries: P3Primaries,
  1017. toReference: ( color ) => color.applyMatrix3( LINEAR_DISPLAY_P3_TO_LINEAR_SRGB ),
  1018. fromReference: ( color ) => color.applyMatrix3( LINEAR_SRGB_TO_LINEAR_DISPLAY_P3 ),
  1019. },
  1020. [ DisplayP3ColorSpace ]: {
  1021. transfer: SRGBTransfer,
  1022. primaries: P3Primaries,
  1023. toReference: ( color ) => color.convertSRGBToLinear().applyMatrix3( LINEAR_DISPLAY_P3_TO_LINEAR_SRGB ),
  1024. fromReference: ( color ) => color.applyMatrix3( LINEAR_SRGB_TO_LINEAR_DISPLAY_P3 ).convertLinearToSRGB(),
  1025. },
  1026. };
  1027. const SUPPORTED_WORKING_COLOR_SPACES = new Set( [ LinearSRGBColorSpace, LinearDisplayP3ColorSpace ] );
  1028. const ColorManagement = {
  1029. enabled: true,
  1030. _workingColorSpace: LinearSRGBColorSpace,
  1031. get workingColorSpace() {
  1032. return this._workingColorSpace;
  1033. },
  1034. set workingColorSpace( colorSpace ) {
  1035. if ( ! SUPPORTED_WORKING_COLOR_SPACES.has( colorSpace ) ) {
  1036. throw new Error( `Unsupported working color space, "${ colorSpace }".` );
  1037. }
  1038. this._workingColorSpace = colorSpace;
  1039. },
  1040. convert: function ( color, sourceColorSpace, targetColorSpace ) {
  1041. if ( this.enabled === false || sourceColorSpace === targetColorSpace || ! sourceColorSpace || ! targetColorSpace ) {
  1042. return color;
  1043. }
  1044. const sourceToReference = COLOR_SPACES[ sourceColorSpace ].toReference;
  1045. const targetFromReference = COLOR_SPACES[ targetColorSpace ].fromReference;
  1046. return targetFromReference( sourceToReference( color ) );
  1047. },
  1048. fromWorkingColorSpace: function ( color, targetColorSpace ) {
  1049. return this.convert( color, this._workingColorSpace, targetColorSpace );
  1050. },
  1051. toWorkingColorSpace: function ( color, sourceColorSpace ) {
  1052. return this.convert( color, sourceColorSpace, this._workingColorSpace );
  1053. },
  1054. getPrimaries: function ( colorSpace ) {
  1055. return COLOR_SPACES[ colorSpace ].primaries;
  1056. },
  1057. getTransfer: function ( colorSpace ) {
  1058. if ( colorSpace === NoColorSpace ) return LinearTransfer;
  1059. return COLOR_SPACES[ colorSpace ].transfer;
  1060. },
  1061. };
  1062. function SRGBToLinear( c ) {
  1063. return ( c < 0.04045 ) ? c * 0.0773993808 : Math.pow( c * 0.9478672986 + 0.0521327014, 2.4 );
  1064. }
  1065. function LinearToSRGB( c ) {
  1066. return ( c < 0.0031308 ) ? c * 12.92 : 1.055 * ( Math.pow( c, 0.41666 ) ) - 0.055;
  1067. }
  1068. let _canvas;
  1069. class ImageUtils {
  1070. static getDataURL( image ) {
  1071. if ( /^data:/i.test( image.src ) ) {
  1072. return image.src;
  1073. }
  1074. if ( typeof HTMLCanvasElement === 'undefined' ) {
  1075. return image.src;
  1076. }
  1077. let canvas;
  1078. if ( image instanceof HTMLCanvasElement ) {
  1079. canvas = image;
  1080. } else {
  1081. if ( _canvas === undefined ) _canvas = createElementNS( 'canvas' );
  1082. _canvas.width = image.width;
  1083. _canvas.height = image.height;
  1084. const context = _canvas.getContext( '2d' );
  1085. if ( image instanceof ImageData ) {
  1086. context.putImageData( image, 0, 0 );
  1087. } else {
  1088. context.drawImage( image, 0, 0, image.width, image.height );
  1089. }
  1090. canvas = _canvas;
  1091. }
  1092. if ( canvas.width > 2048 || canvas.height > 2048 ) {
  1093. console.warn( 'THREE.ImageUtils.getDataURL: Image converted to jpg for performance reasons', image );
  1094. return canvas.toDataURL( 'image/jpeg', 0.6 );
  1095. } else {
  1096. return canvas.toDataURL( 'image/png' );
  1097. }
  1098. }
  1099. static sRGBToLinear( image ) {
  1100. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  1101. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  1102. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  1103. const canvas = createElementNS( 'canvas' );
  1104. canvas.width = image.width;
  1105. canvas.height = image.height;
  1106. const context = canvas.getContext( '2d' );
  1107. context.drawImage( image, 0, 0, image.width, image.height );
  1108. const imageData = context.getImageData( 0, 0, image.width, image.height );
  1109. const data = imageData.data;
  1110. for ( let i = 0; i < data.length; i ++ ) {
  1111. data[ i ] = SRGBToLinear( data[ i ] / 255 ) * 255;
  1112. }
  1113. context.putImageData( imageData, 0, 0 );
  1114. return canvas;
  1115. } else if ( image.data ) {
  1116. const data = image.data.slice( 0 );
  1117. for ( let i = 0; i < data.length; i ++ ) {
  1118. if ( data instanceof Uint8Array || data instanceof Uint8ClampedArray ) {
  1119. data[ i ] = Math.floor( SRGBToLinear( data[ i ] / 255 ) * 255 );
  1120. } else {
  1121. // assuming float
  1122. data[ i ] = SRGBToLinear( data[ i ] );
  1123. }
  1124. }
  1125. return {
  1126. data: data,
  1127. width: image.width,
  1128. height: image.height
  1129. };
  1130. } else {
  1131. console.warn( 'THREE.ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied.' );
  1132. return image;
  1133. }
  1134. }
  1135. }
  1136. let _sourceId = 0;
  1137. class Source {
  1138. constructor( data = null ) {
  1139. this.isSource = true;
  1140. Object.defineProperty( this, 'id', { value: _sourceId ++ } );
  1141. this.uuid = generateUUID();
  1142. this.data = data;
  1143. this.dataReady = true;
  1144. this.version = 0;
  1145. }
  1146. set needsUpdate( value ) {
  1147. if ( value === true ) this.version ++;
  1148. }
  1149. toJSON( meta ) {
  1150. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  1151. if ( ! isRootObject && meta.images[ this.uuid ] !== undefined ) {
  1152. return meta.images[ this.uuid ];
  1153. }
  1154. const output = {
  1155. uuid: this.uuid,
  1156. url: ''
  1157. };
  1158. const data = this.data;
  1159. if ( data !== null ) {
  1160. let url;
  1161. if ( Array.isArray( data ) ) {
  1162. // cube texture
  1163. url = [];
  1164. for ( let i = 0, l = data.length; i < l; i ++ ) {
  1165. if ( data[ i ].isDataTexture ) {
  1166. url.push( serializeImage( data[ i ].image ) );
  1167. } else {
  1168. url.push( serializeImage( data[ i ] ) );
  1169. }
  1170. }
  1171. } else {
  1172. // texture
  1173. url = serializeImage( data );
  1174. }
  1175. output.url = url;
  1176. }
  1177. if ( ! isRootObject ) {
  1178. meta.images[ this.uuid ] = output;
  1179. }
  1180. return output;
  1181. }
  1182. }
  1183. function serializeImage( image ) {
  1184. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  1185. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  1186. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  1187. // default images
  1188. return ImageUtils.getDataURL( image );
  1189. } else {
  1190. if ( image.data ) {
  1191. // images of DataTexture
  1192. return {
  1193. data: Array.from( image.data ),
  1194. width: image.width,
  1195. height: image.height,
  1196. type: image.data.constructor.name
  1197. };
  1198. } else {
  1199. console.warn( 'THREE.Texture: Unable to serialize Texture.' );
  1200. return {};
  1201. }
  1202. }
  1203. }
  1204. let _textureId = 0;
  1205. class Texture extends EventDispatcher {
  1206. constructor( image = Texture.DEFAULT_IMAGE, mapping = Texture.DEFAULT_MAPPING, wrapS = ClampToEdgeWrapping, wrapT = ClampToEdgeWrapping, magFilter = LinearFilter, minFilter = LinearMipmapLinearFilter, format = RGBAFormat, type = UnsignedByteType, anisotropy = Texture.DEFAULT_ANISOTROPY, colorSpace = NoColorSpace ) {
  1207. super();
  1208. this.isTexture = true;
  1209. Object.defineProperty( this, 'id', { value: _textureId ++ } );
  1210. this.uuid = generateUUID();
  1211. this.name = '';
  1212. this.source = new Source( image );
  1213. this.mipmaps = [];
  1214. this.mapping = mapping;
  1215. this.channel = 0;
  1216. this.wrapS = wrapS;
  1217. this.wrapT = wrapT;
  1218. this.magFilter = magFilter;
  1219. this.minFilter = minFilter;
  1220. this.anisotropy = anisotropy;
  1221. this.format = format;
  1222. this.internalFormat = null;
  1223. this.type = type;
  1224. this.offset = new Vector2( 0, 0 );
  1225. this.repeat = new Vector2( 1, 1 );
  1226. this.center = new Vector2( 0, 0 );
  1227. this.rotation = 0;
  1228. this.matrixAutoUpdate = true;
  1229. this.matrix = new Matrix3();
  1230. this.generateMipmaps = true;
  1231. this.premultiplyAlpha = false;
  1232. this.flipY = true;
  1233. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  1234. this.colorSpace = colorSpace;
  1235. this.userData = {};
  1236. this.version = 0;
  1237. this.onUpdate = null;
  1238. this.isRenderTargetTexture = false; // indicates whether a texture belongs to a render target or not
  1239. this.needsPMREMUpdate = false; // indicates whether this texture should be processed by PMREMGenerator or not (only relevant for render target textures)
  1240. }
  1241. get image() {
  1242. return this.source.data;
  1243. }
  1244. set image( value = null ) {
  1245. this.source.data = value;
  1246. }
  1247. updateMatrix() {
  1248. this.matrix.setUvTransform( this.offset.x, this.offset.y, this.repeat.x, this.repeat.y, this.rotation, this.center.x, this.center.y );
  1249. }
  1250. clone() {
  1251. return new this.constructor().copy( this );
  1252. }
  1253. copy( source ) {
  1254. this.name = source.name;
  1255. this.source = source.source;
  1256. this.mipmaps = source.mipmaps.slice( 0 );
  1257. this.mapping = source.mapping;
  1258. this.channel = source.channel;
  1259. this.wrapS = source.wrapS;
  1260. this.wrapT = source.wrapT;
  1261. this.magFilter = source.magFilter;
  1262. this.minFilter = source.minFilter;
  1263. this.anisotropy = source.anisotropy;
  1264. this.format = source.format;
  1265. this.internalFormat = source.internalFormat;
  1266. this.type = source.type;
  1267. this.offset.copy( source.offset );
  1268. this.repeat.copy( source.repeat );
  1269. this.center.copy( source.center );
  1270. this.rotation = source.rotation;
  1271. this.matrixAutoUpdate = source.matrixAutoUpdate;
  1272. this.matrix.copy( source.matrix );
  1273. this.generateMipmaps = source.generateMipmaps;
  1274. this.premultiplyAlpha = source.premultiplyAlpha;
  1275. this.flipY = source.flipY;
  1276. this.unpackAlignment = source.unpackAlignment;
  1277. this.colorSpace = source.colorSpace;
  1278. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  1279. this.needsUpdate = true;
  1280. return this;
  1281. }
  1282. toJSON( meta ) {
  1283. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  1284. if ( ! isRootObject && meta.textures[ this.uuid ] !== undefined ) {
  1285. return meta.textures[ this.uuid ];
  1286. }
  1287. const output = {
  1288. metadata: {
  1289. version: 4.6,
  1290. type: 'Texture',
  1291. generator: 'Texture.toJSON'
  1292. },
  1293. uuid: this.uuid,
  1294. name: this.name,
  1295. image: this.source.toJSON( meta ).uuid,
  1296. mapping: this.mapping,
  1297. channel: this.channel,
  1298. repeat: [ this.repeat.x, this.repeat.y ],
  1299. offset: [ this.offset.x, this.offset.y ],
  1300. center: [ this.center.x, this.center.y ],
  1301. rotation: this.rotation,
  1302. wrap: [ this.wrapS, this.wrapT ],
  1303. format: this.format,
  1304. internalFormat: this.internalFormat,
  1305. type: this.type,
  1306. colorSpace: this.colorSpace,
  1307. minFilter: this.minFilter,
  1308. magFilter: this.magFilter,
  1309. anisotropy: this.anisotropy,
  1310. flipY: this.flipY,
  1311. generateMipmaps: this.generateMipmaps,
  1312. premultiplyAlpha: this.premultiplyAlpha,
  1313. unpackAlignment: this.unpackAlignment
  1314. };
  1315. if ( Object.keys( this.userData ).length > 0 ) output.userData = this.userData;
  1316. if ( ! isRootObject ) {
  1317. meta.textures[ this.uuid ] = output;
  1318. }
  1319. return output;
  1320. }
  1321. dispose() {
  1322. this.dispatchEvent( { type: 'dispose' } );
  1323. }
  1324. transformUv( uv ) {
  1325. if ( this.mapping !== UVMapping ) return uv;
  1326. uv.applyMatrix3( this.matrix );
  1327. if ( uv.x < 0 || uv.x > 1 ) {
  1328. switch ( this.wrapS ) {
  1329. case RepeatWrapping:
  1330. uv.x = uv.x - Math.floor( uv.x );
  1331. break;
  1332. case ClampToEdgeWrapping:
  1333. uv.x = uv.x < 0 ? 0 : 1;
  1334. break;
  1335. case MirroredRepeatWrapping:
  1336. if ( Math.abs( Math.floor( uv.x ) % 2 ) === 1 ) {
  1337. uv.x = Math.ceil( uv.x ) - uv.x;
  1338. } else {
  1339. uv.x = uv.x - Math.floor( uv.x );
  1340. }
  1341. break;
  1342. }
  1343. }
  1344. if ( uv.y < 0 || uv.y > 1 ) {
  1345. switch ( this.wrapT ) {
  1346. case RepeatWrapping:
  1347. uv.y = uv.y - Math.floor( uv.y );
  1348. break;
  1349. case ClampToEdgeWrapping:
  1350. uv.y = uv.y < 0 ? 0 : 1;
  1351. break;
  1352. case MirroredRepeatWrapping:
  1353. if ( Math.abs( Math.floor( uv.y ) % 2 ) === 1 ) {
  1354. uv.y = Math.ceil( uv.y ) - uv.y;
  1355. } else {
  1356. uv.y = uv.y - Math.floor( uv.y );
  1357. }
  1358. break;
  1359. }
  1360. }
  1361. if ( this.flipY ) {
  1362. uv.y = 1 - uv.y;
  1363. }
  1364. return uv;
  1365. }
  1366. set needsUpdate( value ) {
  1367. if ( value === true ) {
  1368. this.version ++;
  1369. this.source.needsUpdate = true;
  1370. }
  1371. }
  1372. }
  1373. Texture.DEFAULT_IMAGE = null;
  1374. Texture.DEFAULT_MAPPING = UVMapping;
  1375. Texture.DEFAULT_ANISOTROPY = 1;
  1376. class Vector4 {
  1377. constructor( x = 0, y = 0, z = 0, w = 1 ) {
  1378. Vector4.prototype.isVector4 = true;
  1379. this.x = x;
  1380. this.y = y;
  1381. this.z = z;
  1382. this.w = w;
  1383. }
  1384. get width() {
  1385. return this.z;
  1386. }
  1387. set width( value ) {
  1388. this.z = value;
  1389. }
  1390. get height() {
  1391. return this.w;
  1392. }
  1393. set height( value ) {
  1394. this.w = value;
  1395. }
  1396. set( x, y, z, w ) {
  1397. this.x = x;
  1398. this.y = y;
  1399. this.z = z;
  1400. this.w = w;
  1401. return this;
  1402. }
  1403. setScalar( scalar ) {
  1404. this.x = scalar;
  1405. this.y = scalar;
  1406. this.z = scalar;
  1407. this.w = scalar;
  1408. return this;
  1409. }
  1410. setX( x ) {
  1411. this.x = x;
  1412. return this;
  1413. }
  1414. setY( y ) {
  1415. this.y = y;
  1416. return this;
  1417. }
  1418. setZ( z ) {
  1419. this.z = z;
  1420. return this;
  1421. }
  1422. setW( w ) {
  1423. this.w = w;
  1424. return this;
  1425. }
  1426. setComponent( index, value ) {
  1427. switch ( index ) {
  1428. case 0: this.x = value; break;
  1429. case 1: this.y = value; break;
  1430. case 2: this.z = value; break;
  1431. case 3: this.w = value; break;
  1432. default: throw new Error( 'index is out of range: ' + index );
  1433. }
  1434. return this;
  1435. }
  1436. getComponent( index ) {
  1437. switch ( index ) {
  1438. case 0: return this.x;
  1439. case 1: return this.y;
  1440. case 2: return this.z;
  1441. case 3: return this.w;
  1442. default: throw new Error( 'index is out of range: ' + index );
  1443. }
  1444. }
  1445. clone() {
  1446. return new this.constructor( this.x, this.y, this.z, this.w );
  1447. }
  1448. copy( v ) {
  1449. this.x = v.x;
  1450. this.y = v.y;
  1451. this.z = v.z;
  1452. this.w = ( v.w !== undefined ) ? v.w : 1;
  1453. return this;
  1454. }
  1455. add( v ) {
  1456. this.x += v.x;
  1457. this.y += v.y;
  1458. this.z += v.z;
  1459. this.w += v.w;
  1460. return this;
  1461. }
  1462. addScalar( s ) {
  1463. this.x += s;
  1464. this.y += s;
  1465. this.z += s;
  1466. this.w += s;
  1467. return this;
  1468. }
  1469. addVectors( a, b ) {
  1470. this.x = a.x + b.x;
  1471. this.y = a.y + b.y;
  1472. this.z = a.z + b.z;
  1473. this.w = a.w + b.w;
  1474. return this;
  1475. }
  1476. addScaledVector( v, s ) {
  1477. this.x += v.x * s;
  1478. this.y += v.y * s;
  1479. this.z += v.z * s;
  1480. this.w += v.w * s;
  1481. return this;
  1482. }
  1483. sub( v ) {
  1484. this.x -= v.x;
  1485. this.y -= v.y;
  1486. this.z -= v.z;
  1487. this.w -= v.w;
  1488. return this;
  1489. }
  1490. subScalar( s ) {
  1491. this.x -= s;
  1492. this.y -= s;
  1493. this.z -= s;
  1494. this.w -= s;
  1495. return this;
  1496. }
  1497. subVectors( a, b ) {
  1498. this.x = a.x - b.x;
  1499. this.y = a.y - b.y;
  1500. this.z = a.z - b.z;
  1501. this.w = a.w - b.w;
  1502. return this;
  1503. }
  1504. multiply( v ) {
  1505. this.x *= v.x;
  1506. this.y *= v.y;
  1507. this.z *= v.z;
  1508. this.w *= v.w;
  1509. return this;
  1510. }
  1511. multiplyScalar( scalar ) {
  1512. this.x *= scalar;
  1513. this.y *= scalar;
  1514. this.z *= scalar;
  1515. this.w *= scalar;
  1516. return this;
  1517. }
  1518. applyMatrix4( m ) {
  1519. const x = this.x, y = this.y, z = this.z, w = this.w;
  1520. const e = m.elements;
  1521. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] * w;
  1522. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] * w;
  1523. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] * w;
  1524. this.w = e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] * w;
  1525. return this;
  1526. }
  1527. divideScalar( scalar ) {
  1528. return this.multiplyScalar( 1 / scalar );
  1529. }
  1530. setAxisAngleFromQuaternion( q ) {
  1531. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  1532. // q is assumed to be normalized
  1533. this.w = 2 * Math.acos( q.w );
  1534. const s = Math.sqrt( 1 - q.w * q.w );
  1535. if ( s < 0.0001 ) {
  1536. this.x = 1;
  1537. this.y = 0;
  1538. this.z = 0;
  1539. } else {
  1540. this.x = q.x / s;
  1541. this.y = q.y / s;
  1542. this.z = q.z / s;
  1543. }
  1544. return this;
  1545. }
  1546. setAxisAngleFromRotationMatrix( m ) {
  1547. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  1548. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1549. let angle, x, y, z; // variables for result
  1550. const epsilon = 0.01, // margin to allow for rounding errors
  1551. epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees
  1552. te = m.elements,
  1553. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  1554. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  1555. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  1556. if ( ( Math.abs( m12 - m21 ) < epsilon ) &&
  1557. ( Math.abs( m13 - m31 ) < epsilon ) &&
  1558. ( Math.abs( m23 - m32 ) < epsilon ) ) {
  1559. // singularity found
  1560. // first check for identity matrix which must have +1 for all terms
  1561. // in leading diagonal and zero in other terms
  1562. if ( ( Math.abs( m12 + m21 ) < epsilon2 ) &&
  1563. ( Math.abs( m13 + m31 ) < epsilon2 ) &&
  1564. ( Math.abs( m23 + m32 ) < epsilon2 ) &&
  1565. ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) {
  1566. // this singularity is identity matrix so angle = 0
  1567. this.set( 1, 0, 0, 0 );
  1568. return this; // zero angle, arbitrary axis
  1569. }
  1570. // otherwise this singularity is angle = 180
  1571. angle = Math.PI;
  1572. const xx = ( m11 + 1 ) / 2;
  1573. const yy = ( m22 + 1 ) / 2;
  1574. const zz = ( m33 + 1 ) / 2;
  1575. const xy = ( m12 + m21 ) / 4;
  1576. const xz = ( m13 + m31 ) / 4;
  1577. const yz = ( m23 + m32 ) / 4;
  1578. if ( ( xx > yy ) && ( xx > zz ) ) {
  1579. // m11 is the largest diagonal term
  1580. if ( xx < epsilon ) {
  1581. x = 0;
  1582. y = 0.707106781;
  1583. z = 0.707106781;
  1584. } else {
  1585. x = Math.sqrt( xx );
  1586. y = xy / x;
  1587. z = xz / x;
  1588. }
  1589. } else if ( yy > zz ) {
  1590. // m22 is the largest diagonal term
  1591. if ( yy < epsilon ) {
  1592. x = 0.707106781;
  1593. y = 0;
  1594. z = 0.707106781;
  1595. } else {
  1596. y = Math.sqrt( yy );
  1597. x = xy / y;
  1598. z = yz / y;
  1599. }
  1600. } else {
  1601. // m33 is the largest diagonal term so base result on this
  1602. if ( zz < epsilon ) {
  1603. x = 0.707106781;
  1604. y = 0.707106781;
  1605. z = 0;
  1606. } else {
  1607. z = Math.sqrt( zz );
  1608. x = xz / z;
  1609. y = yz / z;
  1610. }
  1611. }
  1612. this.set( x, y, z, angle );
  1613. return this; // return 180 deg rotation
  1614. }
  1615. // as we have reached here there are no singularities so we can handle normally
  1616. let s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 ) +
  1617. ( m13 - m31 ) * ( m13 - m31 ) +
  1618. ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize
  1619. if ( Math.abs( s ) < 0.001 ) s = 1;
  1620. // prevent divide by zero, should not happen if matrix is orthogonal and should be
  1621. // caught by singularity test above, but I've left it in just in case
  1622. this.x = ( m32 - m23 ) / s;
  1623. this.y = ( m13 - m31 ) / s;
  1624. this.z = ( m21 - m12 ) / s;
  1625. this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 );
  1626. return this;
  1627. }
  1628. min( v ) {
  1629. this.x = Math.min( this.x, v.x );
  1630. this.y = Math.min( this.y, v.y );
  1631. this.z = Math.min( this.z, v.z );
  1632. this.w = Math.min( this.w, v.w );
  1633. return this;
  1634. }
  1635. max( v ) {
  1636. this.x = Math.max( this.x, v.x );
  1637. this.y = Math.max( this.y, v.y );
  1638. this.z = Math.max( this.z, v.z );
  1639. this.w = Math.max( this.w, v.w );
  1640. return this;
  1641. }
  1642. clamp( min, max ) {
  1643. // assumes min < max, componentwise
  1644. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  1645. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  1646. this.z = Math.max( min.z, Math.min( max.z, this.z ) );
  1647. this.w = Math.max( min.w, Math.min( max.w, this.w ) );
  1648. return this;
  1649. }
  1650. clampScalar( minVal, maxVal ) {
  1651. this.x = Math.max( minVal, Math.min( maxVal, this.x ) );
  1652. this.y = Math.max( minVal, Math.min( maxVal, this.y ) );
  1653. this.z = Math.max( minVal, Math.min( maxVal, this.z ) );
  1654. this.w = Math.max( minVal, Math.min( maxVal, this.w ) );
  1655. return this;
  1656. }
  1657. clampLength( min, max ) {
  1658. const length = this.length();
  1659. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  1660. }
  1661. floor() {
  1662. this.x = Math.floor( this.x );
  1663. this.y = Math.floor( this.y );
  1664. this.z = Math.floor( this.z );
  1665. this.w = Math.floor( this.w );
  1666. return this;
  1667. }
  1668. ceil() {
  1669. this.x = Math.ceil( this.x );
  1670. this.y = Math.ceil( this.y );
  1671. this.z = Math.ceil( this.z );
  1672. this.w = Math.ceil( this.w );
  1673. return this;
  1674. }
  1675. round() {
  1676. this.x = Math.round( this.x );
  1677. this.y = Math.round( this.y );
  1678. this.z = Math.round( this.z );
  1679. this.w = Math.round( this.w );
  1680. return this;
  1681. }
  1682. roundToZero() {
  1683. this.x = Math.trunc( this.x );
  1684. this.y = Math.trunc( this.y );
  1685. this.z = Math.trunc( this.z );
  1686. this.w = Math.trunc( this.w );
  1687. return this;
  1688. }
  1689. negate() {
  1690. this.x = - this.x;
  1691. this.y = - this.y;
  1692. this.z = - this.z;
  1693. this.w = - this.w;
  1694. return this;
  1695. }
  1696. dot( v ) {
  1697. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  1698. }
  1699. lengthSq() {
  1700. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  1701. }
  1702. length() {
  1703. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  1704. }
  1705. manhattanLength() {
  1706. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w );
  1707. }
  1708. normalize() {
  1709. return this.divideScalar( this.length() || 1 );
  1710. }
  1711. setLength( length ) {
  1712. return this.normalize().multiplyScalar( length );
  1713. }
  1714. lerp( v, alpha ) {
  1715. this.x += ( v.x - this.x ) * alpha;
  1716. this.y += ( v.y - this.y ) * alpha;
  1717. this.z += ( v.z - this.z ) * alpha;
  1718. this.w += ( v.w - this.w ) * alpha;
  1719. return this;
  1720. }
  1721. lerpVectors( v1, v2, alpha ) {
  1722. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  1723. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  1724. this.z = v1.z + ( v2.z - v1.z ) * alpha;
  1725. this.w = v1.w + ( v2.w - v1.w ) * alpha;
  1726. return this;
  1727. }
  1728. equals( v ) {
  1729. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );
  1730. }
  1731. fromArray( array, offset = 0 ) {
  1732. this.x = array[ offset ];
  1733. this.y = array[ offset + 1 ];
  1734. this.z = array[ offset + 2 ];
  1735. this.w = array[ offset + 3 ];
  1736. return this;
  1737. }
  1738. toArray( array = [], offset = 0 ) {
  1739. array[ offset ] = this.x;
  1740. array[ offset + 1 ] = this.y;
  1741. array[ offset + 2 ] = this.z;
  1742. array[ offset + 3 ] = this.w;
  1743. return array;
  1744. }
  1745. fromBufferAttribute( attribute, index ) {
  1746. this.x = attribute.getX( index );
  1747. this.y = attribute.getY( index );
  1748. this.z = attribute.getZ( index );
  1749. this.w = attribute.getW( index );
  1750. return this;
  1751. }
  1752. random() {
  1753. this.x = Math.random();
  1754. this.y = Math.random();
  1755. this.z = Math.random();
  1756. this.w = Math.random();
  1757. return this;
  1758. }
  1759. *[ Symbol.iterator ]() {
  1760. yield this.x;
  1761. yield this.y;
  1762. yield this.z;
  1763. yield this.w;
  1764. }
  1765. }
  1766. /*
  1767. In options, we can specify:
  1768. * Texture parameters for an auto-generated target texture
  1769. * depthBuffer/stencilBuffer: Booleans to indicate if we should generate these buffers
  1770. */
  1771. class RenderTarget extends EventDispatcher {
  1772. constructor( width = 1, height = 1, options = {} ) {
  1773. super();
  1774. this.isRenderTarget = true;
  1775. this.width = width;
  1776. this.height = height;
  1777. this.depth = 1;
  1778. this.scissor = new Vector4( 0, 0, width, height );
  1779. this.scissorTest = false;
  1780. this.viewport = new Vector4( 0, 0, width, height );
  1781. const image = { width: width, height: height, depth: 1 };
  1782. options = Object.assign( {
  1783. generateMipmaps: false,
  1784. internalFormat: null,
  1785. minFilter: LinearFilter,
  1786. depthBuffer: true,
  1787. stencilBuffer: false,
  1788. depthTexture: null,
  1789. samples: 0,
  1790. count: 1
  1791. }, options );
  1792. const texture = new Texture( image, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.colorSpace );
  1793. texture.flipY = false;
  1794. texture.generateMipmaps = options.generateMipmaps;
  1795. texture.internalFormat = options.internalFormat;
  1796. this.textures = [];
  1797. const count = options.count;
  1798. for ( let i = 0; i < count; i ++ ) {
  1799. this.textures[ i ] = texture.clone();
  1800. this.textures[ i ].isRenderTargetTexture = true;
  1801. }
  1802. this.depthBuffer = options.depthBuffer;
  1803. this.stencilBuffer = options.stencilBuffer;
  1804. this.depthTexture = options.depthTexture;
  1805. this.samples = options.samples;
  1806. }
  1807. get texture() {
  1808. return this.textures[ 0 ];
  1809. }
  1810. set texture( value ) {
  1811. this.textures[ 0 ] = value;
  1812. }
  1813. setSize( width, height, depth = 1 ) {
  1814. if ( this.width !== width || this.height !== height || this.depth !== depth ) {
  1815. this.width = width;
  1816. this.height = height;
  1817. this.depth = depth;
  1818. for ( let i = 0, il = this.textures.length; i < il; i ++ ) {
  1819. this.textures[ i ].image.width = width;
  1820. this.textures[ i ].image.height = height;
  1821. this.textures[ i ].image.depth = depth;
  1822. }
  1823. this.dispose();
  1824. }
  1825. this.viewport.set( 0, 0, width, height );
  1826. this.scissor.set( 0, 0, width, height );
  1827. }
  1828. clone() {
  1829. return new this.constructor().copy( this );
  1830. }
  1831. copy( source ) {
  1832. this.width = source.width;
  1833. this.height = source.height;
  1834. this.depth = source.depth;
  1835. this.scissor.copy( source.scissor );
  1836. this.scissorTest = source.scissorTest;
  1837. this.viewport.copy( source.viewport );
  1838. this.textures.length = 0;
  1839. for ( let i = 0, il = source.textures.length; i < il; i ++ ) {
  1840. this.textures[ i ] = source.textures[ i ].clone();
  1841. this.textures[ i ].isRenderTargetTexture = true;
  1842. }
  1843. // ensure image object is not shared, see #20328
  1844. const image = Object.assign( {}, source.texture.image );
  1845. this.texture.source = new Source( image );
  1846. this.depthBuffer = source.depthBuffer;
  1847. this.stencilBuffer = source.stencilBuffer;
  1848. if ( source.depthTexture !== null ) this.depthTexture = source.depthTexture.clone();
  1849. this.samples = source.samples;
  1850. return this;
  1851. }
  1852. dispose() {
  1853. this.dispatchEvent( { type: 'dispose' } );
  1854. }
  1855. }
  1856. class WebGLRenderTarget extends RenderTarget {
  1857. constructor( width = 1, height = 1, options = {} ) {
  1858. super( width, height, options );
  1859. this.isWebGLRenderTarget = true;
  1860. }
  1861. }
  1862. class DataArrayTexture extends Texture {
  1863. constructor( data = null, width = 1, height = 1, depth = 1 ) {
  1864. super( null );
  1865. this.isDataArrayTexture = true;
  1866. this.image = { data, width, height, depth };
  1867. this.magFilter = NearestFilter;
  1868. this.minFilter = NearestFilter;
  1869. this.wrapR = ClampToEdgeWrapping;
  1870. this.generateMipmaps = false;
  1871. this.flipY = false;
  1872. this.unpackAlignment = 1;
  1873. }
  1874. }
  1875. class WebGLArrayRenderTarget extends WebGLRenderTarget {
  1876. constructor( width = 1, height = 1, depth = 1, options = {} ) {
  1877. super( width, height, options );
  1878. this.isWebGLArrayRenderTarget = true;
  1879. this.depth = depth;
  1880. this.texture = new DataArrayTexture( null, width, height, depth );
  1881. this.texture.isRenderTargetTexture = true;
  1882. }
  1883. }
  1884. class Data3DTexture extends Texture {
  1885. constructor( data = null, width = 1, height = 1, depth = 1 ) {
  1886. // We're going to add .setXXX() methods for setting properties later.
  1887. // Users can still set in DataTexture3D directly.
  1888. //
  1889. // const texture = new THREE.DataTexture3D( data, width, height, depth );
  1890. // texture.anisotropy = 16;
  1891. //
  1892. // See #14839
  1893. super( null );
  1894. this.isData3DTexture = true;
  1895. this.image = { data, width, height, depth };
  1896. this.magFilter = NearestFilter;
  1897. this.minFilter = NearestFilter;
  1898. this.wrapR = ClampToEdgeWrapping;
  1899. this.generateMipmaps = false;
  1900. this.flipY = false;
  1901. this.unpackAlignment = 1;
  1902. }
  1903. }
  1904. class WebGL3DRenderTarget extends WebGLRenderTarget {
  1905. constructor( width = 1, height = 1, depth = 1, options = {} ) {
  1906. super( width, height, options );
  1907. this.isWebGL3DRenderTarget = true;
  1908. this.depth = depth;
  1909. this.texture = new Data3DTexture( null, width, height, depth );
  1910. this.texture.isRenderTargetTexture = true;
  1911. }
  1912. }
  1913. class Quaternion {
  1914. constructor( x = 0, y = 0, z = 0, w = 1 ) {
  1915. this.isQuaternion = true;
  1916. this._x = x;
  1917. this._y = y;
  1918. this._z = z;
  1919. this._w = w;
  1920. }
  1921. static slerpFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t ) {
  1922. // fuzz-free, array-based Quaternion SLERP operation
  1923. let x0 = src0[ srcOffset0 + 0 ],
  1924. y0 = src0[ srcOffset0 + 1 ],
  1925. z0 = src0[ srcOffset0 + 2 ],
  1926. w0 = src0[ srcOffset0 + 3 ];
  1927. const x1 = src1[ srcOffset1 + 0 ],
  1928. y1 = src1[ srcOffset1 + 1 ],
  1929. z1 = src1[ srcOffset1 + 2 ],
  1930. w1 = src1[ srcOffset1 + 3 ];
  1931. if ( t === 0 ) {
  1932. dst[ dstOffset + 0 ] = x0;
  1933. dst[ dstOffset + 1 ] = y0;
  1934. dst[ dstOffset + 2 ] = z0;
  1935. dst[ dstOffset + 3 ] = w0;
  1936. return;
  1937. }
  1938. if ( t === 1 ) {
  1939. dst[ dstOffset + 0 ] = x1;
  1940. dst[ dstOffset + 1 ] = y1;
  1941. dst[ dstOffset + 2 ] = z1;
  1942. dst[ dstOffset + 3 ] = w1;
  1943. return;
  1944. }
  1945. if ( w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1 ) {
  1946. let s = 1 - t;
  1947. const cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1,
  1948. dir = ( cos >= 0 ? 1 : - 1 ),
  1949. sqrSin = 1 - cos * cos;
  1950. // Skip the Slerp for tiny steps to avoid numeric problems:
  1951. if ( sqrSin > Number.EPSILON ) {
  1952. const sin = Math.sqrt( sqrSin ),
  1953. len = Math.atan2( sin, cos * dir );
  1954. s = Math.sin( s * len ) / sin;
  1955. t = Math.sin( t * len ) / sin;
  1956. }
  1957. const tDir = t * dir;
  1958. x0 = x0 * s + x1 * tDir;
  1959. y0 = y0 * s + y1 * tDir;
  1960. z0 = z0 * s + z1 * tDir;
  1961. w0 = w0 * s + w1 * tDir;
  1962. // Normalize in case we just did a lerp:
  1963. if ( s === 1 - t ) {
  1964. const f = 1 / Math.sqrt( x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0 );
  1965. x0 *= f;
  1966. y0 *= f;
  1967. z0 *= f;
  1968. w0 *= f;
  1969. }
  1970. }
  1971. dst[ dstOffset ] = x0;
  1972. dst[ dstOffset + 1 ] = y0;
  1973. dst[ dstOffset + 2 ] = z0;
  1974. dst[ dstOffset + 3 ] = w0;
  1975. }
  1976. static multiplyQuaternionsFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1 ) {
  1977. const x0 = src0[ srcOffset0 ];
  1978. const y0 = src0[ srcOffset0 + 1 ];
  1979. const z0 = src0[ srcOffset0 + 2 ];
  1980. const w0 = src0[ srcOffset0 + 3 ];
  1981. const x1 = src1[ srcOffset1 ];
  1982. const y1 = src1[ srcOffset1 + 1 ];
  1983. const z1 = src1[ srcOffset1 + 2 ];
  1984. const w1 = src1[ srcOffset1 + 3 ];
  1985. dst[ dstOffset ] = x0 * w1 + w0 * x1 + y0 * z1 - z0 * y1;
  1986. dst[ dstOffset + 1 ] = y0 * w1 + w0 * y1 + z0 * x1 - x0 * z1;
  1987. dst[ dstOffset + 2 ] = z0 * w1 + w0 * z1 + x0 * y1 - y0 * x1;
  1988. dst[ dstOffset + 3 ] = w0 * w1 - x0 * x1 - y0 * y1 - z0 * z1;
  1989. return dst;
  1990. }
  1991. get x() {
  1992. return this._x;
  1993. }
  1994. set x( value ) {
  1995. this._x = value;
  1996. this._onChangeCallback();
  1997. }
  1998. get y() {
  1999. return this._y;
  2000. }
  2001. set y( value ) {
  2002. this._y = value;
  2003. this._onChangeCallback();
  2004. }
  2005. get z() {
  2006. return this._z;
  2007. }
  2008. set z( value ) {
  2009. this._z = value;
  2010. this._onChangeCallback();
  2011. }
  2012. get w() {
  2013. return this._w;
  2014. }
  2015. set w( value ) {
  2016. this._w = value;
  2017. this._onChangeCallback();
  2018. }
  2019. set( x, y, z, w ) {
  2020. this._x = x;
  2021. this._y = y;
  2022. this._z = z;
  2023. this._w = w;
  2024. this._onChangeCallback();
  2025. return this;
  2026. }
  2027. clone() {
  2028. return new this.constructor( this._x, this._y, this._z, this._w );
  2029. }
  2030. copy( quaternion ) {
  2031. this._x = quaternion.x;
  2032. this._y = quaternion.y;
  2033. this._z = quaternion.z;
  2034. this._w = quaternion.w;
  2035. this._onChangeCallback();
  2036. return this;
  2037. }
  2038. setFromEuler( euler, update = true ) {
  2039. const x = euler._x, y = euler._y, z = euler._z, order = euler._order;
  2040. // http://www.mathworks.com/matlabcentral/fileexchange/
  2041. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  2042. // content/SpinCalc.m
  2043. const cos = Math.cos;
  2044. const sin = Math.sin;
  2045. const c1 = cos( x / 2 );
  2046. const c2 = cos( y / 2 );
  2047. const c3 = cos( z / 2 );
  2048. const s1 = sin( x / 2 );
  2049. const s2 = sin( y / 2 );
  2050. const s3 = sin( z / 2 );
  2051. switch ( order ) {
  2052. case 'XYZ':
  2053. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  2054. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  2055. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  2056. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  2057. break;
  2058. case 'YXZ':
  2059. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  2060. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  2061. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  2062. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  2063. break;
  2064. case 'ZXY':
  2065. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  2066. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  2067. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  2068. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  2069. break;
  2070. case 'ZYX':
  2071. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  2072. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  2073. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  2074. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  2075. break;
  2076. case 'YZX':
  2077. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  2078. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  2079. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  2080. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  2081. break;
  2082. case 'XZY':
  2083. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  2084. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  2085. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  2086. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  2087. break;
  2088. default:
  2089. console.warn( 'THREE.Quaternion: .setFromEuler() encountered an unknown order: ' + order );
  2090. }
  2091. if ( update === true ) this._onChangeCallback();
  2092. return this;
  2093. }
  2094. setFromAxisAngle( axis, angle ) {
  2095. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  2096. // assumes axis is normalized
  2097. const halfAngle = angle / 2, s = Math.sin( halfAngle );
  2098. this._x = axis.x * s;
  2099. this._y = axis.y * s;
  2100. this._z = axis.z * s;
  2101. this._w = Math.cos( halfAngle );
  2102. this._onChangeCallback();
  2103. return this;
  2104. }
  2105. setFromRotationMatrix( m ) {
  2106. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  2107. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  2108. const te = m.elements,
  2109. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  2110. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  2111. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ],
  2112. trace = m11 + m22 + m33;
  2113. if ( trace > 0 ) {
  2114. const s = 0.5 / Math.sqrt( trace + 1.0 );
  2115. this._w = 0.25 / s;
  2116. this._x = ( m32 - m23 ) * s;
  2117. this._y = ( m13 - m31 ) * s;
  2118. this._z = ( m21 - m12 ) * s;
  2119. } else if ( m11 > m22 && m11 > m33 ) {
  2120. const s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );
  2121. this._w = ( m32 - m23 ) / s;
  2122. this._x = 0.25 * s;
  2123. this._y = ( m12 + m21 ) / s;
  2124. this._z = ( m13 + m31 ) / s;
  2125. } else if ( m22 > m33 ) {
  2126. const s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );
  2127. this._w = ( m13 - m31 ) / s;
  2128. this._x = ( m12 + m21 ) / s;
  2129. this._y = 0.25 * s;
  2130. this._z = ( m23 + m32 ) / s;
  2131. } else {
  2132. const s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );
  2133. this._w = ( m21 - m12 ) / s;
  2134. this._x = ( m13 + m31 ) / s;
  2135. this._y = ( m23 + m32 ) / s;
  2136. this._z = 0.25 * s;
  2137. }
  2138. this._onChangeCallback();
  2139. return this;
  2140. }
  2141. setFromUnitVectors( vFrom, vTo ) {
  2142. // assumes direction vectors vFrom and vTo are normalized
  2143. let r = vFrom.dot( vTo ) + 1;
  2144. if ( r < Number.EPSILON ) {
  2145. // vFrom and vTo point in opposite directions
  2146. r = 0;
  2147. if ( Math.abs( vFrom.x ) > Math.abs( vFrom.z ) ) {
  2148. this._x = - vFrom.y;
  2149. this._y = vFrom.x;
  2150. this._z = 0;
  2151. this._w = r;
  2152. } else {
  2153. this._x = 0;
  2154. this._y = - vFrom.z;
  2155. this._z = vFrom.y;
  2156. this._w = r;
  2157. }
  2158. } else {
  2159. // crossVectors( vFrom, vTo ); // inlined to avoid cyclic dependency on Vector3
  2160. this._x = vFrom.y * vTo.z - vFrom.z * vTo.y;
  2161. this._y = vFrom.z * vTo.x - vFrom.x * vTo.z;
  2162. this._z = vFrom.x * vTo.y - vFrom.y * vTo.x;
  2163. this._w = r;
  2164. }
  2165. return this.normalize();
  2166. }
  2167. angleTo( q ) {
  2168. return 2 * Math.acos( Math.abs( clamp( this.dot( q ), - 1, 1 ) ) );
  2169. }
  2170. rotateTowards( q, step ) {
  2171. const angle = this.angleTo( q );
  2172. if ( angle === 0 ) return this;
  2173. const t = Math.min( 1, step / angle );
  2174. this.slerp( q, t );
  2175. return this;
  2176. }
  2177. identity() {
  2178. return this.set( 0, 0, 0, 1 );
  2179. }
  2180. invert() {
  2181. // quaternion is assumed to have unit length
  2182. return this.conjugate();
  2183. }
  2184. conjugate() {
  2185. this._x *= - 1;
  2186. this._y *= - 1;
  2187. this._z *= - 1;
  2188. this._onChangeCallback();
  2189. return this;
  2190. }
  2191. dot( v ) {
  2192. return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w;
  2193. }
  2194. lengthSq() {
  2195. return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  2196. }
  2197. length() {
  2198. return Math.sqrt( this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w );
  2199. }
  2200. normalize() {
  2201. let l = this.length();
  2202. if ( l === 0 ) {
  2203. this._x = 0;
  2204. this._y = 0;
  2205. this._z = 0;
  2206. this._w = 1;
  2207. } else {
  2208. l = 1 / l;
  2209. this._x = this._x * l;
  2210. this._y = this._y * l;
  2211. this._z = this._z * l;
  2212. this._w = this._w * l;
  2213. }
  2214. this._onChangeCallback();
  2215. return this;
  2216. }
  2217. multiply( q ) {
  2218. return this.multiplyQuaternions( this, q );
  2219. }
  2220. premultiply( q ) {
  2221. return this.multiplyQuaternions( q, this );
  2222. }
  2223. multiplyQuaternions( a, b ) {
  2224. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  2225. const qax = a._x, qay = a._y, qaz = a._z, qaw = a._w;
  2226. const qbx = b._x, qby = b._y, qbz = b._z, qbw = b._w;
  2227. this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  2228. this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  2229. this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  2230. this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  2231. this._onChangeCallback();
  2232. return this;
  2233. }
  2234. slerp( qb, t ) {
  2235. if ( t === 0 ) return this;
  2236. if ( t === 1 ) return this.copy( qb );
  2237. const x = this._x, y = this._y, z = this._z, w = this._w;
  2238. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  2239. let cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z;
  2240. if ( cosHalfTheta < 0 ) {
  2241. this._w = - qb._w;
  2242. this._x = - qb._x;
  2243. this._y = - qb._y;
  2244. this._z = - qb._z;
  2245. cosHalfTheta = - cosHalfTheta;
  2246. } else {
  2247. this.copy( qb );
  2248. }
  2249. if ( cosHalfTheta >= 1.0 ) {
  2250. this._w = w;
  2251. this._x = x;
  2252. this._y = y;
  2253. this._z = z;
  2254. return this;
  2255. }
  2256. const sqrSinHalfTheta = 1.0 - cosHalfTheta * cosHalfTheta;
  2257. if ( sqrSinHalfTheta <= Number.EPSILON ) {
  2258. const s = 1 - t;
  2259. this._w = s * w + t * this._w;
  2260. this._x = s * x + t * this._x;
  2261. this._y = s * y + t * this._y;
  2262. this._z = s * z + t * this._z;
  2263. this.normalize(); // normalize calls _onChangeCallback()
  2264. return this;
  2265. }
  2266. const sinHalfTheta = Math.sqrt( sqrSinHalfTheta );
  2267. const halfTheta = Math.atan2( sinHalfTheta, cosHalfTheta );
  2268. const ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta,
  2269. ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  2270. this._w = ( w * ratioA + this._w * ratioB );
  2271. this._x = ( x * ratioA + this._x * ratioB );
  2272. this._y = ( y * ratioA + this._y * ratioB );
  2273. this._z = ( z * ratioA + this._z * ratioB );
  2274. this._onChangeCallback();
  2275. return this;
  2276. }
  2277. slerpQuaternions( qa, qb, t ) {
  2278. return this.copy( qa ).slerp( qb, t );
  2279. }
  2280. random() {
  2281. // sets this quaternion to a uniform random unit quaternnion
  2282. // Ken Shoemake
  2283. // Uniform random rotations
  2284. // D. Kirk, editor, Graphics Gems III, pages 124-132. Academic Press, New York, 1992.
  2285. const theta1 = 2 * Math.PI * Math.random();
  2286. const theta2 = 2 * Math.PI * Math.random();
  2287. const x0 = Math.random();
  2288. const r1 = Math.sqrt( 1 - x0 );
  2289. const r2 = Math.sqrt( x0 );
  2290. return this.set(
  2291. r1 * Math.sin( theta1 ),
  2292. r1 * Math.cos( theta1 ),
  2293. r2 * Math.sin( theta2 ),
  2294. r2 * Math.cos( theta2 ),
  2295. );
  2296. }
  2297. equals( quaternion ) {
  2298. return ( quaternion._x === this._x ) && ( quaternion._y === this._y ) && ( quaternion._z === this._z ) && ( quaternion._w === this._w );
  2299. }
  2300. fromArray( array, offset = 0 ) {
  2301. this._x = array[ offset ];
  2302. this._y = array[ offset + 1 ];
  2303. this._z = array[ offset + 2 ];
  2304. this._w = array[ offset + 3 ];
  2305. this._onChangeCallback();
  2306. return this;
  2307. }
  2308. toArray( array = [], offset = 0 ) {
  2309. array[ offset ] = this._x;
  2310. array[ offset + 1 ] = this._y;
  2311. array[ offset + 2 ] = this._z;
  2312. array[ offset + 3 ] = this._w;
  2313. return array;
  2314. }
  2315. fromBufferAttribute( attribute, index ) {
  2316. this._x = attribute.getX( index );
  2317. this._y = attribute.getY( index );
  2318. this._z = attribute.getZ( index );
  2319. this._w = attribute.getW( index );
  2320. this._onChangeCallback();
  2321. return this;
  2322. }
  2323. toJSON() {
  2324. return this.toArray();
  2325. }
  2326. _onChange( callback ) {
  2327. this._onChangeCallback = callback;
  2328. return this;
  2329. }
  2330. _onChangeCallback() {}
  2331. *[ Symbol.iterator ]() {
  2332. yield this._x;
  2333. yield this._y;
  2334. yield this._z;
  2335. yield this._w;
  2336. }
  2337. }
  2338. class Vector3 {
  2339. constructor( x = 0, y = 0, z = 0 ) {
  2340. Vector3.prototype.isVector3 = true;
  2341. this.x = x;
  2342. this.y = y;
  2343. this.z = z;
  2344. }
  2345. set( x, y, z ) {
  2346. if ( z === undefined ) z = this.z; // sprite.scale.set(x,y)
  2347. this.x = x;
  2348. this.y = y;
  2349. this.z = z;
  2350. return this;
  2351. }
  2352. setScalar( scalar ) {
  2353. this.x = scalar;
  2354. this.y = scalar;
  2355. this.z = scalar;
  2356. return this;
  2357. }
  2358. setX( x ) {
  2359. this.x = x;
  2360. return this;
  2361. }
  2362. setY( y ) {
  2363. this.y = y;
  2364. return this;
  2365. }
  2366. setZ( z ) {
  2367. this.z = z;
  2368. return this;
  2369. }
  2370. setComponent( index, value ) {
  2371. switch ( index ) {
  2372. case 0: this.x = value; break;
  2373. case 1: this.y = value; break;
  2374. case 2: this.z = value; break;
  2375. default: throw new Error( 'index is out of range: ' + index );
  2376. }
  2377. return this;
  2378. }
  2379. getComponent( index ) {
  2380. switch ( index ) {
  2381. case 0: return this.x;
  2382. case 1: return this.y;
  2383. case 2: return this.z;
  2384. default: throw new Error( 'index is out of range: ' + index );
  2385. }
  2386. }
  2387. clone() {
  2388. return new this.constructor( this.x, this.y, this.z );
  2389. }
  2390. copy( v ) {
  2391. this.x = v.x;
  2392. this.y = v.y;
  2393. this.z = v.z;
  2394. return this;
  2395. }
  2396. add( v ) {
  2397. this.x += v.x;
  2398. this.y += v.y;
  2399. this.z += v.z;
  2400. return this;
  2401. }
  2402. addScalar( s ) {
  2403. this.x += s;
  2404. this.y += s;
  2405. this.z += s;
  2406. return this;
  2407. }
  2408. addVectors( a, b ) {
  2409. this.x = a.x + b.x;
  2410. this.y = a.y + b.y;
  2411. this.z = a.z + b.z;
  2412. return this;
  2413. }
  2414. addScaledVector( v, s ) {
  2415. this.x += v.x * s;
  2416. this.y += v.y * s;
  2417. this.z += v.z * s;
  2418. return this;
  2419. }
  2420. sub( v ) {
  2421. this.x -= v.x;
  2422. this.y -= v.y;
  2423. this.z -= v.z;
  2424. return this;
  2425. }
  2426. subScalar( s ) {
  2427. this.x -= s;
  2428. this.y -= s;
  2429. this.z -= s;
  2430. return this;
  2431. }
  2432. subVectors( a, b ) {
  2433. this.x = a.x - b.x;
  2434. this.y = a.y - b.y;
  2435. this.z = a.z - b.z;
  2436. return this;
  2437. }
  2438. multiply( v ) {
  2439. this.x *= v.x;
  2440. this.y *= v.y;
  2441. this.z *= v.z;
  2442. return this;
  2443. }
  2444. multiplyScalar( scalar ) {
  2445. this.x *= scalar;
  2446. this.y *= scalar;
  2447. this.z *= scalar;
  2448. return this;
  2449. }
  2450. multiplyVectors( a, b ) {
  2451. this.x = a.x * b.x;
  2452. this.y = a.y * b.y;
  2453. this.z = a.z * b.z;
  2454. return this;
  2455. }
  2456. applyEuler( euler ) {
  2457. return this.applyQuaternion( _quaternion$4.setFromEuler( euler ) );
  2458. }
  2459. applyAxisAngle( axis, angle ) {
  2460. return this.applyQuaternion( _quaternion$4.setFromAxisAngle( axis, angle ) );
  2461. }
  2462. applyMatrix3( m ) {
  2463. const x = this.x, y = this.y, z = this.z;
  2464. const e = m.elements;
  2465. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ] * z;
  2466. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ] * z;
  2467. this.z = e[ 2 ] * x + e[ 5 ] * y + e[ 8 ] * z;
  2468. return this;
  2469. }
  2470. applyNormalMatrix( m ) {
  2471. return this.applyMatrix3( m ).normalize();
  2472. }
  2473. applyMatrix4( m ) {
  2474. const x = this.x, y = this.y, z = this.z;
  2475. const e = m.elements;
  2476. const w = 1 / ( e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] );
  2477. this.x = ( e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] ) * w;
  2478. this.y = ( e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] ) * w;
  2479. this.z = ( e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] ) * w;
  2480. return this;
  2481. }
  2482. applyQuaternion( q ) {
  2483. // quaternion q is assumed to have unit length
  2484. const vx = this.x, vy = this.y, vz = this.z;
  2485. const qx = q.x, qy = q.y, qz = q.z, qw = q.w;
  2486. // t = 2 * cross( q.xyz, v );
  2487. const tx = 2 * ( qy * vz - qz * vy );
  2488. const ty = 2 * ( qz * vx - qx * vz );
  2489. const tz = 2 * ( qx * vy - qy * vx );
  2490. // v + q.w * t + cross( q.xyz, t );
  2491. this.x = vx + qw * tx + qy * tz - qz * ty;
  2492. this.y = vy + qw * ty + qz * tx - qx * tz;
  2493. this.z = vz + qw * tz + qx * ty - qy * tx;
  2494. return this;
  2495. }
  2496. project( camera ) {
  2497. return this.applyMatrix4( camera.matrixWorldInverse ).applyMatrix4( camera.projectionMatrix );
  2498. }
  2499. unproject( camera ) {
  2500. return this.applyMatrix4( camera.projectionMatrixInverse ).applyMatrix4( camera.matrixWorld );
  2501. }
  2502. transformDirection( m ) {
  2503. // input: THREE.Matrix4 affine matrix
  2504. // vector interpreted as a direction
  2505. const x = this.x, y = this.y, z = this.z;
  2506. const e = m.elements;
  2507. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z;
  2508. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z;
  2509. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z;
  2510. return this.normalize();
  2511. }
  2512. divide( v ) {
  2513. this.x /= v.x;
  2514. this.y /= v.y;
  2515. this.z /= v.z;
  2516. return this;
  2517. }
  2518. divideScalar( scalar ) {
  2519. return this.multiplyScalar( 1 / scalar );
  2520. }
  2521. min( v ) {
  2522. this.x = Math.min( this.x, v.x );
  2523. this.y = Math.min( this.y, v.y );
  2524. this.z = Math.min( this.z, v.z );
  2525. return this;
  2526. }
  2527. max( v ) {
  2528. this.x = Math.max( this.x, v.x );
  2529. this.y = Math.max( this.y, v.y );
  2530. this.z = Math.max( this.z, v.z );
  2531. return this;
  2532. }
  2533. clamp( min, max ) {
  2534. // assumes min < max, componentwise
  2535. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  2536. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  2537. this.z = Math.max( min.z, Math.min( max.z, this.z ) );
  2538. return this;
  2539. }
  2540. clampScalar( minVal, maxVal ) {
  2541. this.x = Math.max( minVal, Math.min( maxVal, this.x ) );
  2542. this.y = Math.max( minVal, Math.min( maxVal, this.y ) );
  2543. this.z = Math.max( minVal, Math.min( maxVal, this.z ) );
  2544. return this;
  2545. }
  2546. clampLength( min, max ) {
  2547. const length = this.length();
  2548. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  2549. }
  2550. floor() {
  2551. this.x = Math.floor( this.x );
  2552. this.y = Math.floor( this.y );
  2553. this.z = Math.floor( this.z );
  2554. return this;
  2555. }
  2556. ceil() {
  2557. this.x = Math.ceil( this.x );
  2558. this.y = Math.ceil( this.y );
  2559. this.z = Math.ceil( this.z );
  2560. return this;
  2561. }
  2562. round() {
  2563. this.x = Math.round( this.x );
  2564. this.y = Math.round( this.y );
  2565. this.z = Math.round( this.z );
  2566. return this;
  2567. }
  2568. roundToZero() {
  2569. this.x = Math.trunc( this.x );
  2570. this.y = Math.trunc( this.y );
  2571. this.z = Math.trunc( this.z );
  2572. return this;
  2573. }
  2574. negate() {
  2575. this.x = - this.x;
  2576. this.y = - this.y;
  2577. this.z = - this.z;
  2578. return this;
  2579. }
  2580. dot( v ) {
  2581. return this.x * v.x + this.y * v.y + this.z * v.z;
  2582. }
  2583. // TODO lengthSquared?
  2584. lengthSq() {
  2585. return this.x * this.x + this.y * this.y + this.z * this.z;
  2586. }
  2587. length() {
  2588. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z );
  2589. }
  2590. manhattanLength() {
  2591. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );
  2592. }
  2593. normalize() {
  2594. return this.divideScalar( this.length() || 1 );
  2595. }
  2596. setLength( length ) {
  2597. return this.normalize().multiplyScalar( length );
  2598. }
  2599. lerp( v, alpha ) {
  2600. this.x += ( v.x - this.x ) * alpha;
  2601. this.y += ( v.y - this.y ) * alpha;
  2602. this.z += ( v.z - this.z ) * alpha;
  2603. return this;
  2604. }
  2605. lerpVectors( v1, v2, alpha ) {
  2606. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  2607. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  2608. this.z = v1.z + ( v2.z - v1.z ) * alpha;
  2609. return this;
  2610. }
  2611. cross( v ) {
  2612. return this.crossVectors( this, v );
  2613. }
  2614. crossVectors( a, b ) {
  2615. const ax = a.x, ay = a.y, az = a.z;
  2616. const bx = b.x, by = b.y, bz = b.z;
  2617. this.x = ay * bz - az * by;
  2618. this.y = az * bx - ax * bz;
  2619. this.z = ax * by - ay * bx;
  2620. return this;
  2621. }
  2622. projectOnVector( v ) {
  2623. const denominator = v.lengthSq();
  2624. if ( denominator === 0 ) return this.set( 0, 0, 0 );
  2625. const scalar = v.dot( this ) / denominator;
  2626. return this.copy( v ).multiplyScalar( scalar );
  2627. }
  2628. projectOnPlane( planeNormal ) {
  2629. _vector$c.copy( this ).projectOnVector( planeNormal );
  2630. return this.sub( _vector$c );
  2631. }
  2632. reflect( normal ) {
  2633. // reflect incident vector off plane orthogonal to normal
  2634. // normal is assumed to have unit length
  2635. return this.sub( _vector$c.copy( normal ).multiplyScalar( 2 * this.dot( normal ) ) );
  2636. }
  2637. angleTo( v ) {
  2638. const denominator = Math.sqrt( this.lengthSq() * v.lengthSq() );
  2639. if ( denominator === 0 ) return Math.PI / 2;
  2640. const theta = this.dot( v ) / denominator;
  2641. // clamp, to handle numerical problems
  2642. return Math.acos( clamp( theta, - 1, 1 ) );
  2643. }
  2644. distanceTo( v ) {
  2645. return Math.sqrt( this.distanceToSquared( v ) );
  2646. }
  2647. distanceToSquared( v ) {
  2648. const dx = this.x - v.x, dy = this.y - v.y, dz = this.z - v.z;
  2649. return dx * dx + dy * dy + dz * dz;
  2650. }
  2651. manhattanDistanceTo( v ) {
  2652. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y ) + Math.abs( this.z - v.z );
  2653. }
  2654. setFromSpherical( s ) {
  2655. return this.setFromSphericalCoords( s.radius, s.phi, s.theta );
  2656. }
  2657. setFromSphericalCoords( radius, phi, theta ) {
  2658. const sinPhiRadius = Math.sin( phi ) * radius;
  2659. this.x = sinPhiRadius * Math.sin( theta );
  2660. this.y = Math.cos( phi ) * radius;
  2661. this.z = sinPhiRadius * Math.cos( theta );
  2662. return this;
  2663. }
  2664. setFromCylindrical( c ) {
  2665. return this.setFromCylindricalCoords( c.radius, c.theta, c.y );
  2666. }
  2667. setFromCylindricalCoords( radius, theta, y ) {
  2668. this.x = radius * Math.sin( theta );
  2669. this.y = y;
  2670. this.z = radius * Math.cos( theta );
  2671. return this;
  2672. }
  2673. setFromMatrixPosition( m ) {
  2674. const e = m.elements;
  2675. this.x = e[ 12 ];
  2676. this.y = e[ 13 ];
  2677. this.z = e[ 14 ];
  2678. return this;
  2679. }
  2680. setFromMatrixScale( m ) {
  2681. const sx = this.setFromMatrixColumn( m, 0 ).length();
  2682. const sy = this.setFromMatrixColumn( m, 1 ).length();
  2683. const sz = this.setFromMatrixColumn( m, 2 ).length();
  2684. this.x = sx;
  2685. this.y = sy;
  2686. this.z = sz;
  2687. return this;
  2688. }
  2689. setFromMatrixColumn( m, index ) {
  2690. return this.fromArray( m.elements, index * 4 );
  2691. }
  2692. setFromMatrix3Column( m, index ) {
  2693. return this.fromArray( m.elements, index * 3 );
  2694. }
  2695. setFromEuler( e ) {
  2696. this.x = e._x;
  2697. this.y = e._y;
  2698. this.z = e._z;
  2699. return this;
  2700. }
  2701. setFromColor( c ) {
  2702. this.x = c.r;
  2703. this.y = c.g;
  2704. this.z = c.b;
  2705. return this;
  2706. }
  2707. equals( v ) {
  2708. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
  2709. }
  2710. fromArray( array, offset = 0 ) {
  2711. this.x = array[ offset ];
  2712. this.y = array[ offset + 1 ];
  2713. this.z = array[ offset + 2 ];
  2714. return this;
  2715. }
  2716. toArray( array = [], offset = 0 ) {
  2717. array[ offset ] = this.x;
  2718. array[ offset + 1 ] = this.y;
  2719. array[ offset + 2 ] = this.z;
  2720. return array;
  2721. }
  2722. fromBufferAttribute( attribute, index ) {
  2723. this.x = attribute.getX( index );
  2724. this.y = attribute.getY( index );
  2725. this.z = attribute.getZ( index );
  2726. return this;
  2727. }
  2728. random() {
  2729. this.x = Math.random();
  2730. this.y = Math.random();
  2731. this.z = Math.random();
  2732. return this;
  2733. }
  2734. randomDirection() {
  2735. // https://mathworld.wolfram.com/SpherePointPicking.html
  2736. const theta = Math.random() * Math.PI * 2;
  2737. const u = Math.random() * 2 - 1;
  2738. const c = Math.sqrt( 1 - u * u );
  2739. this.x = c * Math.cos( theta );
  2740. this.y = u;
  2741. this.z = c * Math.sin( theta );
  2742. return this;
  2743. }
  2744. *[ Symbol.iterator ]() {
  2745. yield this.x;
  2746. yield this.y;
  2747. yield this.z;
  2748. }
  2749. }
  2750. const _vector$c = /*@__PURE__*/ new Vector3();
  2751. const _quaternion$4 = /*@__PURE__*/ new Quaternion();
  2752. class Box3 {
  2753. constructor( min = new Vector3( + Infinity, + Infinity, + Infinity ), max = new Vector3( - Infinity, - Infinity, - Infinity ) ) {
  2754. this.isBox3 = true;
  2755. this.min = min;
  2756. this.max = max;
  2757. }
  2758. set( min, max ) {
  2759. this.min.copy( min );
  2760. this.max.copy( max );
  2761. return this;
  2762. }
  2763. setFromArray( array ) {
  2764. this.makeEmpty();
  2765. for ( let i = 0, il = array.length; i < il; i += 3 ) {
  2766. this.expandByPoint( _vector$b.fromArray( array, i ) );
  2767. }
  2768. return this;
  2769. }
  2770. setFromBufferAttribute( attribute ) {
  2771. this.makeEmpty();
  2772. for ( let i = 0, il = attribute.count; i < il; i ++ ) {
  2773. this.expandByPoint( _vector$b.fromBufferAttribute( attribute, i ) );
  2774. }
  2775. return this;
  2776. }
  2777. setFromPoints( points ) {
  2778. this.makeEmpty();
  2779. for ( let i = 0, il = points.length; i < il; i ++ ) {
  2780. this.expandByPoint( points[ i ] );
  2781. }
  2782. return this;
  2783. }
  2784. setFromCenterAndSize( center, size ) {
  2785. const halfSize = _vector$b.copy( size ).multiplyScalar( 0.5 );
  2786. this.min.copy( center ).sub( halfSize );
  2787. this.max.copy( center ).add( halfSize );
  2788. return this;
  2789. }
  2790. setFromObject( object, precise = false ) {
  2791. this.makeEmpty();
  2792. return this.expandByObject( object, precise );
  2793. }
  2794. clone() {
  2795. return new this.constructor().copy( this );
  2796. }
  2797. copy( box ) {
  2798. this.min.copy( box.min );
  2799. this.max.copy( box.max );
  2800. return this;
  2801. }
  2802. makeEmpty() {
  2803. this.min.x = this.min.y = this.min.z = + Infinity;
  2804. this.max.x = this.max.y = this.max.z = - Infinity;
  2805. return this;
  2806. }
  2807. isEmpty() {
  2808. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  2809. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z );
  2810. }
  2811. getCenter( target ) {
  2812. return this.isEmpty() ? target.set( 0, 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  2813. }
  2814. getSize( target ) {
  2815. return this.isEmpty() ? target.set( 0, 0, 0 ) : target.subVectors( this.max, this.min );
  2816. }
  2817. expandByPoint( point ) {
  2818. this.min.min( point );
  2819. this.max.max( point );
  2820. return this;
  2821. }
  2822. expandByVector( vector ) {
  2823. this.min.sub( vector );
  2824. this.max.add( vector );
  2825. return this;
  2826. }
  2827. expandByScalar( scalar ) {
  2828. this.min.addScalar( - scalar );
  2829. this.max.addScalar( scalar );
  2830. return this;
  2831. }
  2832. expandByObject( object, precise = false ) {
  2833. // Computes the world-axis-aligned bounding box of an object (including its children),
  2834. // accounting for both the object's, and children's, world transforms
  2835. object.updateWorldMatrix( false, false );
  2836. const geometry = object.geometry;
  2837. if ( geometry !== undefined ) {
  2838. const positionAttribute = geometry.getAttribute( 'position' );
  2839. // precise AABB computation based on vertex data requires at least a position attribute.
  2840. // instancing isn't supported so far and uses the normal (conservative) code path.
  2841. if ( precise === true && positionAttribute !== undefined && object.isInstancedMesh !== true ) {
  2842. for ( let i = 0, l = positionAttribute.count; i < l; i ++ ) {
  2843. if ( object.isMesh === true ) {
  2844. object.getVertexPosition( i, _vector$b );
  2845. } else {
  2846. _vector$b.fromBufferAttribute( positionAttribute, i );
  2847. }
  2848. _vector$b.applyMatrix4( object.matrixWorld );
  2849. this.expandByPoint( _vector$b );
  2850. }
  2851. } else {
  2852. if ( object.boundingBox !== undefined ) {
  2853. // object-level bounding box
  2854. if ( object.boundingBox === null ) {
  2855. object.computeBoundingBox();
  2856. }
  2857. _box$4.copy( object.boundingBox );
  2858. } else {
  2859. // geometry-level bounding box
  2860. if ( geometry.boundingBox === null ) {
  2861. geometry.computeBoundingBox();
  2862. }
  2863. _box$4.copy( geometry.boundingBox );
  2864. }
  2865. _box$4.applyMatrix4( object.matrixWorld );
  2866. this.union( _box$4 );
  2867. }
  2868. }
  2869. const children = object.children;
  2870. for ( let i = 0, l = children.length; i < l; i ++ ) {
  2871. this.expandByObject( children[ i ], precise );
  2872. }
  2873. return this;
  2874. }
  2875. containsPoint( point ) {
  2876. return point.x < this.min.x || point.x > this.max.x ||
  2877. point.y < this.min.y || point.y > this.max.y ||
  2878. point.z < this.min.z || point.z > this.max.z ? false : true;
  2879. }
  2880. containsBox( box ) {
  2881. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  2882. this.min.y <= box.min.y && box.max.y <= this.max.y &&
  2883. this.min.z <= box.min.z && box.max.z <= this.max.z;
  2884. }
  2885. getParameter( point, target ) {
  2886. // This can potentially have a divide by zero if the box
  2887. // has a size dimension of 0.
  2888. return target.set(
  2889. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  2890. ( point.y - this.min.y ) / ( this.max.y - this.min.y ),
  2891. ( point.z - this.min.z ) / ( this.max.z - this.min.z )
  2892. );
  2893. }
  2894. intersectsBox( box ) {
  2895. // using 6 splitting planes to rule out intersections.
  2896. return box.max.x < this.min.x || box.min.x > this.max.x ||
  2897. box.max.y < this.min.y || box.min.y > this.max.y ||
  2898. box.max.z < this.min.z || box.min.z > this.max.z ? false : true;
  2899. }
  2900. intersectsSphere( sphere ) {
  2901. // Find the point on the AABB closest to the sphere center.
  2902. this.clampPoint( sphere.center, _vector$b );
  2903. // If that point is inside the sphere, the AABB and sphere intersect.
  2904. return _vector$b.distanceToSquared( sphere.center ) <= ( sphere.radius * sphere.radius );
  2905. }
  2906. intersectsPlane( plane ) {
  2907. // We compute the minimum and maximum dot product values. If those values
  2908. // are on the same side (back or front) of the plane, then there is no intersection.
  2909. let min, max;
  2910. if ( plane.normal.x > 0 ) {
  2911. min = plane.normal.x * this.min.x;
  2912. max = plane.normal.x * this.max.x;
  2913. } else {
  2914. min = plane.normal.x * this.max.x;
  2915. max = plane.normal.x * this.min.x;
  2916. }
  2917. if ( plane.normal.y > 0 ) {
  2918. min += plane.normal.y * this.min.y;
  2919. max += plane.normal.y * this.max.y;
  2920. } else {
  2921. min += plane.normal.y * this.max.y;
  2922. max += plane.normal.y * this.min.y;
  2923. }
  2924. if ( plane.normal.z > 0 ) {
  2925. min += plane.normal.z * this.min.z;
  2926. max += plane.normal.z * this.max.z;
  2927. } else {
  2928. min += plane.normal.z * this.max.z;
  2929. max += plane.normal.z * this.min.z;
  2930. }
  2931. return ( min <= - plane.constant && max >= - plane.constant );
  2932. }
  2933. intersectsTriangle( triangle ) {
  2934. if ( this.isEmpty() ) {
  2935. return false;
  2936. }
  2937. // compute box center and extents
  2938. this.getCenter( _center );
  2939. _extents.subVectors( this.max, _center );
  2940. // translate triangle to aabb origin
  2941. _v0$2.subVectors( triangle.a, _center );
  2942. _v1$7.subVectors( triangle.b, _center );
  2943. _v2$4.subVectors( triangle.c, _center );
  2944. // compute edge vectors for triangle
  2945. _f0.subVectors( _v1$7, _v0$2 );
  2946. _f1.subVectors( _v2$4, _v1$7 );
  2947. _f2.subVectors( _v0$2, _v2$4 );
  2948. // test against axes that are given by cross product combinations of the edges of the triangle and the edges of the aabb
  2949. // 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
  2950. // axis_ij = u_i x f_j (u0, u1, u2 = face normals of aabb = x,y,z axes vectors since aabb is axis aligned)
  2951. let axes = [
  2952. 0, - _f0.z, _f0.y, 0, - _f1.z, _f1.y, 0, - _f2.z, _f2.y,
  2953. _f0.z, 0, - _f0.x, _f1.z, 0, - _f1.x, _f2.z, 0, - _f2.x,
  2954. - _f0.y, _f0.x, 0, - _f1.y, _f1.x, 0, - _f2.y, _f2.x, 0
  2955. ];
  2956. if ( ! satForAxes( axes, _v0$2, _v1$7, _v2$4, _extents ) ) {
  2957. return false;
  2958. }
  2959. // test 3 face normals from the aabb
  2960. axes = [ 1, 0, 0, 0, 1, 0, 0, 0, 1 ];
  2961. if ( ! satForAxes( axes, _v0$2, _v1$7, _v2$4, _extents ) ) {
  2962. return false;
  2963. }
  2964. // finally testing the face normal of the triangle
  2965. // use already existing triangle edge vectors here
  2966. _triangleNormal.crossVectors( _f0, _f1 );
  2967. axes = [ _triangleNormal.x, _triangleNormal.y, _triangleNormal.z ];
  2968. return satForAxes( axes, _v0$2, _v1$7, _v2$4, _extents );
  2969. }
  2970. clampPoint( point, target ) {
  2971. return target.copy( point ).clamp( this.min, this.max );
  2972. }
  2973. distanceToPoint( point ) {
  2974. return this.clampPoint( point, _vector$b ).distanceTo( point );
  2975. }
  2976. getBoundingSphere( target ) {
  2977. if ( this.isEmpty() ) {
  2978. target.makeEmpty();
  2979. } else {
  2980. this.getCenter( target.center );
  2981. target.radius = this.getSize( _vector$b ).length() * 0.5;
  2982. }
  2983. return target;
  2984. }
  2985. intersect( box ) {
  2986. this.min.max( box.min );
  2987. this.max.min( box.max );
  2988. // 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.
  2989. if ( this.isEmpty() ) this.makeEmpty();
  2990. return this;
  2991. }
  2992. union( box ) {
  2993. this.min.min( box.min );
  2994. this.max.max( box.max );
  2995. return this;
  2996. }
  2997. applyMatrix4( matrix ) {
  2998. // transform of empty box is an empty box.
  2999. if ( this.isEmpty() ) return this;
  3000. // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  3001. _points[ 0 ].set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 000
  3002. _points[ 1 ].set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 001
  3003. _points[ 2 ].set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 010
  3004. _points[ 3 ].set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 011
  3005. _points[ 4 ].set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 100
  3006. _points[ 5 ].set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 101
  3007. _points[ 6 ].set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 110
  3008. _points[ 7 ].set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 111
  3009. this.setFromPoints( _points );
  3010. return this;
  3011. }
  3012. translate( offset ) {
  3013. this.min.add( offset );
  3014. this.max.add( offset );
  3015. return this;
  3016. }
  3017. equals( box ) {
  3018. return box.min.equals( this.min ) && box.max.equals( this.max );
  3019. }
  3020. }
  3021. const _points = [
  3022. /*@__PURE__*/ new Vector3(),
  3023. /*@__PURE__*/ new Vector3(),
  3024. /*@__PURE__*/ new Vector3(),
  3025. /*@__PURE__*/ new Vector3(),
  3026. /*@__PURE__*/ new Vector3(),
  3027. /*@__PURE__*/ new Vector3(),
  3028. /*@__PURE__*/ new Vector3(),
  3029. /*@__PURE__*/ new Vector3()
  3030. ];
  3031. const _vector$b = /*@__PURE__*/ new Vector3();
  3032. const _box$4 = /*@__PURE__*/ new Box3();
  3033. // triangle centered vertices
  3034. const _v0$2 = /*@__PURE__*/ new Vector3();
  3035. const _v1$7 = /*@__PURE__*/ new Vector3();
  3036. const _v2$4 = /*@__PURE__*/ new Vector3();
  3037. // triangle edge vectors
  3038. const _f0 = /*@__PURE__*/ new Vector3();
  3039. const _f1 = /*@__PURE__*/ new Vector3();
  3040. const _f2 = /*@__PURE__*/ new Vector3();
  3041. const _center = /*@__PURE__*/ new Vector3();
  3042. const _extents = /*@__PURE__*/ new Vector3();
  3043. const _triangleNormal = /*@__PURE__*/ new Vector3();
  3044. const _testAxis = /*@__PURE__*/ new Vector3();
  3045. function satForAxes( axes, v0, v1, v2, extents ) {
  3046. for ( let i = 0, j = axes.length - 3; i <= j; i += 3 ) {
  3047. _testAxis.fromArray( axes, i );
  3048. // project the aabb onto the separating axis
  3049. const r = extents.x * Math.abs( _testAxis.x ) + extents.y * Math.abs( _testAxis.y ) + extents.z * Math.abs( _testAxis.z );
  3050. // project all 3 vertices of the triangle onto the separating axis
  3051. const p0 = v0.dot( _testAxis );
  3052. const p1 = v1.dot( _testAxis );
  3053. const p2 = v2.dot( _testAxis );
  3054. // actual test, basically see if either of the most extreme of the triangle points intersects r
  3055. if ( Math.max( - Math.max( p0, p1, p2 ), Math.min( p0, p1, p2 ) ) > r ) {
  3056. // points of the projected triangle are outside the projected half-length of the aabb
  3057. // the axis is separating and we can exit
  3058. return false;
  3059. }
  3060. }
  3061. return true;
  3062. }
  3063. const _box$3 = /*@__PURE__*/ new Box3();
  3064. const _v1$6 = /*@__PURE__*/ new Vector3();
  3065. const _v2$3 = /*@__PURE__*/ new Vector3();
  3066. class Sphere {
  3067. constructor( center = new Vector3(), radius = - 1 ) {
  3068. this.isSphere = true;
  3069. this.center = center;
  3070. this.radius = radius;
  3071. }
  3072. set( center, radius ) {
  3073. this.center.copy( center );
  3074. this.radius = radius;
  3075. return this;
  3076. }
  3077. setFromPoints( points, optionalCenter ) {
  3078. const center = this.center;
  3079. if ( optionalCenter !== undefined ) {
  3080. center.copy( optionalCenter );
  3081. } else {
  3082. _box$3.setFromPoints( points ).getCenter( center );
  3083. }
  3084. let maxRadiusSq = 0;
  3085. for ( let i = 0, il = points.length; i < il; i ++ ) {
  3086. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( points[ i ] ) );
  3087. }
  3088. this.radius = Math.sqrt( maxRadiusSq );
  3089. return this;
  3090. }
  3091. copy( sphere ) {
  3092. this.center.copy( sphere.center );
  3093. this.radius = sphere.radius;
  3094. return this;
  3095. }
  3096. isEmpty() {
  3097. return ( this.radius < 0 );
  3098. }
  3099. makeEmpty() {
  3100. this.center.set( 0, 0, 0 );
  3101. this.radius = - 1;
  3102. return this;
  3103. }
  3104. containsPoint( point ) {
  3105. return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) );
  3106. }
  3107. distanceToPoint( point ) {
  3108. return ( point.distanceTo( this.center ) - this.radius );
  3109. }
  3110. intersectsSphere( sphere ) {
  3111. const radiusSum = this.radius + sphere.radius;
  3112. return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum );
  3113. }
  3114. intersectsBox( box ) {
  3115. return box.intersectsSphere( this );
  3116. }
  3117. intersectsPlane( plane ) {
  3118. return Math.abs( plane.distanceToPoint( this.center ) ) <= this.radius;
  3119. }
  3120. clampPoint( point, target ) {
  3121. const deltaLengthSq = this.center.distanceToSquared( point );
  3122. target.copy( point );
  3123. if ( deltaLengthSq > ( this.radius * this.radius ) ) {
  3124. target.sub( this.center ).normalize();
  3125. target.multiplyScalar( this.radius ).add( this.center );
  3126. }
  3127. return target;
  3128. }
  3129. getBoundingBox( target ) {
  3130. if ( this.isEmpty() ) {
  3131. // Empty sphere produces empty bounding box
  3132. target.makeEmpty();
  3133. return target;
  3134. }
  3135. target.set( this.center, this.center );
  3136. target.expandByScalar( this.radius );
  3137. return target;
  3138. }
  3139. applyMatrix4( matrix ) {
  3140. this.center.applyMatrix4( matrix );
  3141. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  3142. return this;
  3143. }
  3144. translate( offset ) {
  3145. this.center.add( offset );
  3146. return this;
  3147. }
  3148. expandByPoint( point ) {
  3149. if ( this.isEmpty() ) {
  3150. this.center.copy( point );
  3151. this.radius = 0;
  3152. return this;
  3153. }
  3154. _v1$6.subVectors( point, this.center );
  3155. const lengthSq = _v1$6.lengthSq();
  3156. if ( lengthSq > ( this.radius * this.radius ) ) {
  3157. // calculate the minimal sphere
  3158. const length = Math.sqrt( lengthSq );
  3159. const delta = ( length - this.radius ) * 0.5;
  3160. this.center.addScaledVector( _v1$6, delta / length );
  3161. this.radius += delta;
  3162. }
  3163. return this;
  3164. }
  3165. union( sphere ) {
  3166. if ( sphere.isEmpty() ) {
  3167. return this;
  3168. }
  3169. if ( this.isEmpty() ) {
  3170. this.copy( sphere );
  3171. return this;
  3172. }
  3173. if ( this.center.equals( sphere.center ) === true ) {
  3174. this.radius = Math.max( this.radius, sphere.radius );
  3175. } else {
  3176. _v2$3.subVectors( sphere.center, this.center ).setLength( sphere.radius );
  3177. this.expandByPoint( _v1$6.copy( sphere.center ).add( _v2$3 ) );
  3178. this.expandByPoint( _v1$6.copy( sphere.center ).sub( _v2$3 ) );
  3179. }
  3180. return this;
  3181. }
  3182. equals( sphere ) {
  3183. return sphere.center.equals( this.center ) && ( sphere.radius === this.radius );
  3184. }
  3185. clone() {
  3186. return new this.constructor().copy( this );
  3187. }
  3188. }
  3189. const _vector$a = /*@__PURE__*/ new Vector3();
  3190. const _segCenter = /*@__PURE__*/ new Vector3();
  3191. const _segDir = /*@__PURE__*/ new Vector3();
  3192. const _diff = /*@__PURE__*/ new Vector3();
  3193. const _edge1 = /*@__PURE__*/ new Vector3();
  3194. const _edge2 = /*@__PURE__*/ new Vector3();
  3195. const _normal$1 = /*@__PURE__*/ new Vector3();
  3196. class Ray {
  3197. constructor( origin = new Vector3(), direction = new Vector3( 0, 0, - 1 ) ) {
  3198. this.origin = origin;
  3199. this.direction = direction;
  3200. }
  3201. set( origin, direction ) {
  3202. this.origin.copy( origin );
  3203. this.direction.copy( direction );
  3204. return this;
  3205. }
  3206. copy( ray ) {
  3207. this.origin.copy( ray.origin );
  3208. this.direction.copy( ray.direction );
  3209. return this;
  3210. }
  3211. at( t, target ) {
  3212. return target.copy( this.origin ).addScaledVector( this.direction, t );
  3213. }
  3214. lookAt( v ) {
  3215. this.direction.copy( v ).sub( this.origin ).normalize();
  3216. return this;
  3217. }
  3218. recast( t ) {
  3219. this.origin.copy( this.at( t, _vector$a ) );
  3220. return this;
  3221. }
  3222. closestPointToPoint( point, target ) {
  3223. target.subVectors( point, this.origin );
  3224. const directionDistance = target.dot( this.direction );
  3225. if ( directionDistance < 0 ) {
  3226. return target.copy( this.origin );
  3227. }
  3228. return target.copy( this.origin ).addScaledVector( this.direction, directionDistance );
  3229. }
  3230. distanceToPoint( point ) {
  3231. return Math.sqrt( this.distanceSqToPoint( point ) );
  3232. }
  3233. distanceSqToPoint( point ) {
  3234. const directionDistance = _vector$a.subVectors( point, this.origin ).dot( this.direction );
  3235. // point behind the ray
  3236. if ( directionDistance < 0 ) {
  3237. return this.origin.distanceToSquared( point );
  3238. }
  3239. _vector$a.copy( this.origin ).addScaledVector( this.direction, directionDistance );
  3240. return _vector$a.distanceToSquared( point );
  3241. }
  3242. distanceSqToSegment( v0, v1, optionalPointOnRay, optionalPointOnSegment ) {
  3243. // from https://github.com/pmjoniak/GeometricTools/blob/master/GTEngine/Include/Mathematics/GteDistRaySegment.h
  3244. // It returns the min distance between the ray and the segment
  3245. // defined by v0 and v1
  3246. // It can also set two optional targets :
  3247. // - The closest point on the ray
  3248. // - The closest point on the segment
  3249. _segCenter.copy( v0 ).add( v1 ).multiplyScalar( 0.5 );
  3250. _segDir.copy( v1 ).sub( v0 ).normalize();
  3251. _diff.copy( this.origin ).sub( _segCenter );
  3252. const segExtent = v0.distanceTo( v1 ) * 0.5;
  3253. const a01 = - this.direction.dot( _segDir );
  3254. const b0 = _diff.dot( this.direction );
  3255. const b1 = - _diff.dot( _segDir );
  3256. const c = _diff.lengthSq();
  3257. const det = Math.abs( 1 - a01 * a01 );
  3258. let s0, s1, sqrDist, extDet;
  3259. if ( det > 0 ) {
  3260. // The ray and segment are not parallel.
  3261. s0 = a01 * b1 - b0;
  3262. s1 = a01 * b0 - b1;
  3263. extDet = segExtent * det;
  3264. if ( s0 >= 0 ) {
  3265. if ( s1 >= - extDet ) {
  3266. if ( s1 <= extDet ) {
  3267. // region 0
  3268. // Minimum at interior points of ray and segment.
  3269. const invDet = 1 / det;
  3270. s0 *= invDet;
  3271. s1 *= invDet;
  3272. sqrDist = s0 * ( s0 + a01 * s1 + 2 * b0 ) + s1 * ( a01 * s0 + s1 + 2 * b1 ) + c;
  3273. } else {
  3274. // region 1
  3275. s1 = segExtent;
  3276. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3277. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3278. }
  3279. } else {
  3280. // region 5
  3281. s1 = - segExtent;
  3282. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3283. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3284. }
  3285. } else {
  3286. if ( s1 <= - extDet ) {
  3287. // region 4
  3288. s0 = Math.max( 0, - ( - a01 * segExtent + b0 ) );
  3289. s1 = ( s0 > 0 ) ? - segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3290. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3291. } else if ( s1 <= extDet ) {
  3292. // region 3
  3293. s0 = 0;
  3294. s1 = Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3295. sqrDist = s1 * ( s1 + 2 * b1 ) + c;
  3296. } else {
  3297. // region 2
  3298. s0 = Math.max( 0, - ( a01 * segExtent + b0 ) );
  3299. s1 = ( s0 > 0 ) ? segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3300. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3301. }
  3302. }
  3303. } else {
  3304. // Ray and segment are parallel.
  3305. s1 = ( a01 > 0 ) ? - segExtent : segExtent;
  3306. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3307. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3308. }
  3309. if ( optionalPointOnRay ) {
  3310. optionalPointOnRay.copy( this.origin ).addScaledVector( this.direction, s0 );
  3311. }
  3312. if ( optionalPointOnSegment ) {
  3313. optionalPointOnSegment.copy( _segCenter ).addScaledVector( _segDir, s1 );
  3314. }
  3315. return sqrDist;
  3316. }
  3317. intersectSphere( sphere, target ) {
  3318. _vector$a.subVectors( sphere.center, this.origin );
  3319. const tca = _vector$a.dot( this.direction );
  3320. const d2 = _vector$a.dot( _vector$a ) - tca * tca;
  3321. const radius2 = sphere.radius * sphere.radius;
  3322. if ( d2 > radius2 ) return null;
  3323. const thc = Math.sqrt( radius2 - d2 );
  3324. // t0 = first intersect point - entrance on front of sphere
  3325. const t0 = tca - thc;
  3326. // t1 = second intersect point - exit point on back of sphere
  3327. const t1 = tca + thc;
  3328. // test to see if t1 is behind the ray - if so, return null
  3329. if ( t1 < 0 ) return null;
  3330. // test to see if t0 is behind the ray:
  3331. // if it is, the ray is inside the sphere, so return the second exit point scaled by t1,
  3332. // in order to always return an intersect point that is in front of the ray.
  3333. if ( t0 < 0 ) return this.at( t1, target );
  3334. // else t0 is in front of the ray, so return the first collision point scaled by t0
  3335. return this.at( t0, target );
  3336. }
  3337. intersectsSphere( sphere ) {
  3338. return this.distanceSqToPoint( sphere.center ) <= ( sphere.radius * sphere.radius );
  3339. }
  3340. distanceToPlane( plane ) {
  3341. const denominator = plane.normal.dot( this.direction );
  3342. if ( denominator === 0 ) {
  3343. // line is coplanar, return origin
  3344. if ( plane.distanceToPoint( this.origin ) === 0 ) {
  3345. return 0;
  3346. }
  3347. // Null is preferable to undefined since undefined means.... it is undefined
  3348. return null;
  3349. }
  3350. const t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator;
  3351. // Return if the ray never intersects the plane
  3352. return t >= 0 ? t : null;
  3353. }
  3354. intersectPlane( plane, target ) {
  3355. const t = this.distanceToPlane( plane );
  3356. if ( t === null ) {
  3357. return null;
  3358. }
  3359. return this.at( t, target );
  3360. }
  3361. intersectsPlane( plane ) {
  3362. // check if the ray lies on the plane first
  3363. const distToPoint = plane.distanceToPoint( this.origin );
  3364. if ( distToPoint === 0 ) {
  3365. return true;
  3366. }
  3367. const denominator = plane.normal.dot( this.direction );
  3368. if ( denominator * distToPoint < 0 ) {
  3369. return true;
  3370. }
  3371. // ray origin is behind the plane (and is pointing behind it)
  3372. return false;
  3373. }
  3374. intersectBox( box, target ) {
  3375. let tmin, tmax, tymin, tymax, tzmin, tzmax;
  3376. const invdirx = 1 / this.direction.x,
  3377. invdiry = 1 / this.direction.y,
  3378. invdirz = 1 / this.direction.z;
  3379. const origin = this.origin;
  3380. if ( invdirx >= 0 ) {
  3381. tmin = ( box.min.x - origin.x ) * invdirx;
  3382. tmax = ( box.max.x - origin.x ) * invdirx;
  3383. } else {
  3384. tmin = ( box.max.x - origin.x ) * invdirx;
  3385. tmax = ( box.min.x - origin.x ) * invdirx;
  3386. }
  3387. if ( invdiry >= 0 ) {
  3388. tymin = ( box.min.y - origin.y ) * invdiry;
  3389. tymax = ( box.max.y - origin.y ) * invdiry;
  3390. } else {
  3391. tymin = ( box.max.y - origin.y ) * invdiry;
  3392. tymax = ( box.min.y - origin.y ) * invdiry;
  3393. }
  3394. if ( ( tmin > tymax ) || ( tymin > tmax ) ) return null;
  3395. if ( tymin > tmin || isNaN( tmin ) ) tmin = tymin;
  3396. if ( tymax < tmax || isNaN( tmax ) ) tmax = tymax;
  3397. if ( invdirz >= 0 ) {
  3398. tzmin = ( box.min.z - origin.z ) * invdirz;
  3399. tzmax = ( box.max.z - origin.z ) * invdirz;
  3400. } else {
  3401. tzmin = ( box.max.z - origin.z ) * invdirz;
  3402. tzmax = ( box.min.z - origin.z ) * invdirz;
  3403. }
  3404. if ( ( tmin > tzmax ) || ( tzmin > tmax ) ) return null;
  3405. if ( tzmin > tmin || tmin !== tmin ) tmin = tzmin;
  3406. if ( tzmax < tmax || tmax !== tmax ) tmax = tzmax;
  3407. //return point closest to the ray (positive side)
  3408. if ( tmax < 0 ) return null;
  3409. return this.at( tmin >= 0 ? tmin : tmax, target );
  3410. }
  3411. intersectsBox( box ) {
  3412. return this.intersectBox( box, _vector$a ) !== null;
  3413. }
  3414. intersectTriangle( a, b, c, backfaceCulling, target ) {
  3415. // Compute the offset origin, edges, and normal.
  3416. // from https://github.com/pmjoniak/GeometricTools/blob/master/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h
  3417. _edge1.subVectors( b, a );
  3418. _edge2.subVectors( c, a );
  3419. _normal$1.crossVectors( _edge1, _edge2 );
  3420. // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  3421. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  3422. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  3423. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  3424. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  3425. let DdN = this.direction.dot( _normal$1 );
  3426. let sign;
  3427. if ( DdN > 0 ) {
  3428. if ( backfaceCulling ) return null;
  3429. sign = 1;
  3430. } else if ( DdN < 0 ) {
  3431. sign = - 1;
  3432. DdN = - DdN;
  3433. } else {
  3434. return null;
  3435. }
  3436. _diff.subVectors( this.origin, a );
  3437. const DdQxE2 = sign * this.direction.dot( _edge2.crossVectors( _diff, _edge2 ) );
  3438. // b1 < 0, no intersection
  3439. if ( DdQxE2 < 0 ) {
  3440. return null;
  3441. }
  3442. const DdE1xQ = sign * this.direction.dot( _edge1.cross( _diff ) );
  3443. // b2 < 0, no intersection
  3444. if ( DdE1xQ < 0 ) {
  3445. return null;
  3446. }
  3447. // b1+b2 > 1, no intersection
  3448. if ( DdQxE2 + DdE1xQ > DdN ) {
  3449. return null;
  3450. }
  3451. // Line intersects triangle, check if ray does.
  3452. const QdN = - sign * _diff.dot( _normal$1 );
  3453. // t < 0, no intersection
  3454. if ( QdN < 0 ) {
  3455. return null;
  3456. }
  3457. // Ray intersects triangle.
  3458. return this.at( QdN / DdN, target );
  3459. }
  3460. applyMatrix4( matrix4 ) {
  3461. this.origin.applyMatrix4( matrix4 );
  3462. this.direction.transformDirection( matrix4 );
  3463. return this;
  3464. }
  3465. equals( ray ) {
  3466. return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction );
  3467. }
  3468. clone() {
  3469. return new this.constructor().copy( this );
  3470. }
  3471. }
  3472. class Matrix4 {
  3473. constructor( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  3474. Matrix4.prototype.isMatrix4 = true;
  3475. this.elements = [
  3476. 1, 0, 0, 0,
  3477. 0, 1, 0, 0,
  3478. 0, 0, 1, 0,
  3479. 0, 0, 0, 1
  3480. ];
  3481. if ( n11 !== undefined ) {
  3482. this.set( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 );
  3483. }
  3484. }
  3485. set( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  3486. const te = this.elements;
  3487. te[ 0 ] = n11; te[ 4 ] = n12; te[ 8 ] = n13; te[ 12 ] = n14;
  3488. te[ 1 ] = n21; te[ 5 ] = n22; te[ 9 ] = n23; te[ 13 ] = n24;
  3489. te[ 2 ] = n31; te[ 6 ] = n32; te[ 10 ] = n33; te[ 14 ] = n34;
  3490. te[ 3 ] = n41; te[ 7 ] = n42; te[ 11 ] = n43; te[ 15 ] = n44;
  3491. return this;
  3492. }
  3493. identity() {
  3494. this.set(
  3495. 1, 0, 0, 0,
  3496. 0, 1, 0, 0,
  3497. 0, 0, 1, 0,
  3498. 0, 0, 0, 1
  3499. );
  3500. return this;
  3501. }
  3502. clone() {
  3503. return new Matrix4().fromArray( this.elements );
  3504. }
  3505. copy( m ) {
  3506. const te = this.elements;
  3507. const me = m.elements;
  3508. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ]; te[ 3 ] = me[ 3 ];
  3509. te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ]; te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ];
  3510. te[ 8 ] = me[ 8 ]; te[ 9 ] = me[ 9 ]; te[ 10 ] = me[ 10 ]; te[ 11 ] = me[ 11 ];
  3511. te[ 12 ] = me[ 12 ]; te[ 13 ] = me[ 13 ]; te[ 14 ] = me[ 14 ]; te[ 15 ] = me[ 15 ];
  3512. return this;
  3513. }
  3514. copyPosition( m ) {
  3515. const te = this.elements, me = m.elements;
  3516. te[ 12 ] = me[ 12 ];
  3517. te[ 13 ] = me[ 13 ];
  3518. te[ 14 ] = me[ 14 ];
  3519. return this;
  3520. }
  3521. setFromMatrix3( m ) {
  3522. const me = m.elements;
  3523. this.set(
  3524. me[ 0 ], me[ 3 ], me[ 6 ], 0,
  3525. me[ 1 ], me[ 4 ], me[ 7 ], 0,
  3526. me[ 2 ], me[ 5 ], me[ 8 ], 0,
  3527. 0, 0, 0, 1
  3528. );
  3529. return this;
  3530. }
  3531. extractBasis( xAxis, yAxis, zAxis ) {
  3532. xAxis.setFromMatrixColumn( this, 0 );
  3533. yAxis.setFromMatrixColumn( this, 1 );
  3534. zAxis.setFromMatrixColumn( this, 2 );
  3535. return this;
  3536. }
  3537. makeBasis( xAxis, yAxis, zAxis ) {
  3538. this.set(
  3539. xAxis.x, yAxis.x, zAxis.x, 0,
  3540. xAxis.y, yAxis.y, zAxis.y, 0,
  3541. xAxis.z, yAxis.z, zAxis.z, 0,
  3542. 0, 0, 0, 1
  3543. );
  3544. return this;
  3545. }
  3546. extractRotation( m ) {
  3547. // this method does not support reflection matrices
  3548. const te = this.elements;
  3549. const me = m.elements;
  3550. const scaleX = 1 / _v1$5.setFromMatrixColumn( m, 0 ).length();
  3551. const scaleY = 1 / _v1$5.setFromMatrixColumn( m, 1 ).length();
  3552. const scaleZ = 1 / _v1$5.setFromMatrixColumn( m, 2 ).length();
  3553. te[ 0 ] = me[ 0 ] * scaleX;
  3554. te[ 1 ] = me[ 1 ] * scaleX;
  3555. te[ 2 ] = me[ 2 ] * scaleX;
  3556. te[ 3 ] = 0;
  3557. te[ 4 ] = me[ 4 ] * scaleY;
  3558. te[ 5 ] = me[ 5 ] * scaleY;
  3559. te[ 6 ] = me[ 6 ] * scaleY;
  3560. te[ 7 ] = 0;
  3561. te[ 8 ] = me[ 8 ] * scaleZ;
  3562. te[ 9 ] = me[ 9 ] * scaleZ;
  3563. te[ 10 ] = me[ 10 ] * scaleZ;
  3564. te[ 11 ] = 0;
  3565. te[ 12 ] = 0;
  3566. te[ 13 ] = 0;
  3567. te[ 14 ] = 0;
  3568. te[ 15 ] = 1;
  3569. return this;
  3570. }
  3571. makeRotationFromEuler( euler ) {
  3572. const te = this.elements;
  3573. const x = euler.x, y = euler.y, z = euler.z;
  3574. const a = Math.cos( x ), b = Math.sin( x );
  3575. const c = Math.cos( y ), d = Math.sin( y );
  3576. const e = Math.cos( z ), f = Math.sin( z );
  3577. if ( euler.order === 'XYZ' ) {
  3578. const ae = a * e, af = a * f, be = b * e, bf = b * f;
  3579. te[ 0 ] = c * e;
  3580. te[ 4 ] = - c * f;
  3581. te[ 8 ] = d;
  3582. te[ 1 ] = af + be * d;
  3583. te[ 5 ] = ae - bf * d;
  3584. te[ 9 ] = - b * c;
  3585. te[ 2 ] = bf - ae * d;
  3586. te[ 6 ] = be + af * d;
  3587. te[ 10 ] = a * c;
  3588. } else if ( euler.order === 'YXZ' ) {
  3589. const ce = c * e, cf = c * f, de = d * e, df = d * f;
  3590. te[ 0 ] = ce + df * b;
  3591. te[ 4 ] = de * b - cf;
  3592. te[ 8 ] = a * d;
  3593. te[ 1 ] = a * f;
  3594. te[ 5 ] = a * e;
  3595. te[ 9 ] = - b;
  3596. te[ 2 ] = cf * b - de;
  3597. te[ 6 ] = df + ce * b;
  3598. te[ 10 ] = a * c;
  3599. } else if ( euler.order === 'ZXY' ) {
  3600. const ce = c * e, cf = c * f, de = d * e, df = d * f;
  3601. te[ 0 ] = ce - df * b;
  3602. te[ 4 ] = - a * f;
  3603. te[ 8 ] = de + cf * b;
  3604. te[ 1 ] = cf + de * b;
  3605. te[ 5 ] = a * e;
  3606. te[ 9 ] = df - ce * b;
  3607. te[ 2 ] = - a * d;
  3608. te[ 6 ] = b;
  3609. te[ 10 ] = a * c;
  3610. } else if ( euler.order === 'ZYX' ) {
  3611. const ae = a * e, af = a * f, be = b * e, bf = b * f;
  3612. te[ 0 ] = c * e;
  3613. te[ 4 ] = be * d - af;
  3614. te[ 8 ] = ae * d + bf;
  3615. te[ 1 ] = c * f;
  3616. te[ 5 ] = bf * d + ae;
  3617. te[ 9 ] = af * d - be;
  3618. te[ 2 ] = - d;
  3619. te[ 6 ] = b * c;
  3620. te[ 10 ] = a * c;
  3621. } else if ( euler.order === 'YZX' ) {
  3622. const ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  3623. te[ 0 ] = c * e;
  3624. te[ 4 ] = bd - ac * f;
  3625. te[ 8 ] = bc * f + ad;
  3626. te[ 1 ] = f;
  3627. te[ 5 ] = a * e;
  3628. te[ 9 ] = - b * e;
  3629. te[ 2 ] = - d * e;
  3630. te[ 6 ] = ad * f + bc;
  3631. te[ 10 ] = ac - bd * f;
  3632. } else if ( euler.order === 'XZY' ) {
  3633. const ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  3634. te[ 0 ] = c * e;
  3635. te[ 4 ] = - f;
  3636. te[ 8 ] = d * e;
  3637. te[ 1 ] = ac * f + bd;
  3638. te[ 5 ] = a * e;
  3639. te[ 9 ] = ad * f - bc;
  3640. te[ 2 ] = bc * f - ad;
  3641. te[ 6 ] = b * e;
  3642. te[ 10 ] = bd * f + ac;
  3643. }
  3644. // bottom row
  3645. te[ 3 ] = 0;
  3646. te[ 7 ] = 0;
  3647. te[ 11 ] = 0;
  3648. // last column
  3649. te[ 12 ] = 0;
  3650. te[ 13 ] = 0;
  3651. te[ 14 ] = 0;
  3652. te[ 15 ] = 1;
  3653. return this;
  3654. }
  3655. makeRotationFromQuaternion( q ) {
  3656. return this.compose( _zero, q, _one );
  3657. }
  3658. lookAt( eye, target, up ) {
  3659. const te = this.elements;
  3660. _z.subVectors( eye, target );
  3661. if ( _z.lengthSq() === 0 ) {
  3662. // eye and target are in the same position
  3663. _z.z = 1;
  3664. }
  3665. _z.normalize();
  3666. _x.crossVectors( up, _z );
  3667. if ( _x.lengthSq() === 0 ) {
  3668. // up and z are parallel
  3669. if ( Math.abs( up.z ) === 1 ) {
  3670. _z.x += 0.0001;
  3671. } else {
  3672. _z.z += 0.0001;
  3673. }
  3674. _z.normalize();
  3675. _x.crossVectors( up, _z );
  3676. }
  3677. _x.normalize();
  3678. _y.crossVectors( _z, _x );
  3679. te[ 0 ] = _x.x; te[ 4 ] = _y.x; te[ 8 ] = _z.x;
  3680. te[ 1 ] = _x.y; te[ 5 ] = _y.y; te[ 9 ] = _z.y;
  3681. te[ 2 ] = _x.z; te[ 6 ] = _y.z; te[ 10 ] = _z.z;
  3682. return this;
  3683. }
  3684. multiply( m ) {
  3685. return this.multiplyMatrices( this, m );
  3686. }
  3687. premultiply( m ) {
  3688. return this.multiplyMatrices( m, this );
  3689. }
  3690. multiplyMatrices( a, b ) {
  3691. const ae = a.elements;
  3692. const be = b.elements;
  3693. const te = this.elements;
  3694. const a11 = ae[ 0 ], a12 = ae[ 4 ], a13 = ae[ 8 ], a14 = ae[ 12 ];
  3695. const a21 = ae[ 1 ], a22 = ae[ 5 ], a23 = ae[ 9 ], a24 = ae[ 13 ];
  3696. const a31 = ae[ 2 ], a32 = ae[ 6 ], a33 = ae[ 10 ], a34 = ae[ 14 ];
  3697. const a41 = ae[ 3 ], a42 = ae[ 7 ], a43 = ae[ 11 ], a44 = ae[ 15 ];
  3698. const b11 = be[ 0 ], b12 = be[ 4 ], b13 = be[ 8 ], b14 = be[ 12 ];
  3699. const b21 = be[ 1 ], b22 = be[ 5 ], b23 = be[ 9 ], b24 = be[ 13 ];
  3700. const b31 = be[ 2 ], b32 = be[ 6 ], b33 = be[ 10 ], b34 = be[ 14 ];
  3701. const b41 = be[ 3 ], b42 = be[ 7 ], b43 = be[ 11 ], b44 = be[ 15 ];
  3702. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  3703. te[ 4 ] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  3704. te[ 8 ] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  3705. te[ 12 ] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  3706. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  3707. te[ 5 ] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  3708. te[ 9 ] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  3709. te[ 13 ] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  3710. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  3711. te[ 6 ] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  3712. te[ 10 ] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  3713. te[ 14 ] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  3714. te[ 3 ] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  3715. te[ 7 ] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  3716. te[ 11 ] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  3717. te[ 15 ] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  3718. return this;
  3719. }
  3720. multiplyScalar( s ) {
  3721. const te = this.elements;
  3722. te[ 0 ] *= s; te[ 4 ] *= s; te[ 8 ] *= s; te[ 12 ] *= s;
  3723. te[ 1 ] *= s; te[ 5 ] *= s; te[ 9 ] *= s; te[ 13 ] *= s;
  3724. te[ 2 ] *= s; te[ 6 ] *= s; te[ 10 ] *= s; te[ 14 ] *= s;
  3725. te[ 3 ] *= s; te[ 7 ] *= s; te[ 11 ] *= s; te[ 15 ] *= s;
  3726. return this;
  3727. }
  3728. determinant() {
  3729. const te = this.elements;
  3730. const n11 = te[ 0 ], n12 = te[ 4 ], n13 = te[ 8 ], n14 = te[ 12 ];
  3731. const n21 = te[ 1 ], n22 = te[ 5 ], n23 = te[ 9 ], n24 = te[ 13 ];
  3732. const n31 = te[ 2 ], n32 = te[ 6 ], n33 = te[ 10 ], n34 = te[ 14 ];
  3733. const n41 = te[ 3 ], n42 = te[ 7 ], n43 = te[ 11 ], n44 = te[ 15 ];
  3734. //TODO: make this more efficient
  3735. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  3736. return (
  3737. n41 * (
  3738. + n14 * n23 * n32
  3739. - n13 * n24 * n32
  3740. - n14 * n22 * n33
  3741. + n12 * n24 * n33
  3742. + n13 * n22 * n34
  3743. - n12 * n23 * n34
  3744. ) +
  3745. n42 * (
  3746. + n11 * n23 * n34
  3747. - n11 * n24 * n33
  3748. + n14 * n21 * n33
  3749. - n13 * n21 * n34
  3750. + n13 * n24 * n31
  3751. - n14 * n23 * n31
  3752. ) +
  3753. n43 * (
  3754. + n11 * n24 * n32
  3755. - n11 * n22 * n34
  3756. - n14 * n21 * n32
  3757. + n12 * n21 * n34
  3758. + n14 * n22 * n31
  3759. - n12 * n24 * n31
  3760. ) +
  3761. n44 * (
  3762. - n13 * n22 * n31
  3763. - n11 * n23 * n32
  3764. + n11 * n22 * n33
  3765. + n13 * n21 * n32
  3766. - n12 * n21 * n33
  3767. + n12 * n23 * n31
  3768. )
  3769. );
  3770. }
  3771. transpose() {
  3772. const te = this.elements;
  3773. let tmp;
  3774. tmp = te[ 1 ]; te[ 1 ] = te[ 4 ]; te[ 4 ] = tmp;
  3775. tmp = te[ 2 ]; te[ 2 ] = te[ 8 ]; te[ 8 ] = tmp;
  3776. tmp = te[ 6 ]; te[ 6 ] = te[ 9 ]; te[ 9 ] = tmp;
  3777. tmp = te[ 3 ]; te[ 3 ] = te[ 12 ]; te[ 12 ] = tmp;
  3778. tmp = te[ 7 ]; te[ 7 ] = te[ 13 ]; te[ 13 ] = tmp;
  3779. tmp = te[ 11 ]; te[ 11 ] = te[ 14 ]; te[ 14 ] = tmp;
  3780. return this;
  3781. }
  3782. setPosition( x, y, z ) {
  3783. const te = this.elements;
  3784. if ( x.isVector3 ) {
  3785. te[ 12 ] = x.x;
  3786. te[ 13 ] = x.y;
  3787. te[ 14 ] = x.z;
  3788. } else {
  3789. te[ 12 ] = x;
  3790. te[ 13 ] = y;
  3791. te[ 14 ] = z;
  3792. }
  3793. return this;
  3794. }
  3795. invert() {
  3796. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  3797. const te = this.elements,
  3798. n11 = te[ 0 ], n21 = te[ 1 ], n31 = te[ 2 ], n41 = te[ 3 ],
  3799. n12 = te[ 4 ], n22 = te[ 5 ], n32 = te[ 6 ], n42 = te[ 7 ],
  3800. n13 = te[ 8 ], n23 = te[ 9 ], n33 = te[ 10 ], n43 = te[ 11 ],
  3801. n14 = te[ 12 ], n24 = te[ 13 ], n34 = te[ 14 ], n44 = te[ 15 ],
  3802. t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44,
  3803. t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44,
  3804. t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44,
  3805. t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34;
  3806. const det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14;
  3807. if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 );
  3808. const detInv = 1 / det;
  3809. te[ 0 ] = t11 * detInv;
  3810. te[ 1 ] = ( n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44 ) * detInv;
  3811. te[ 2 ] = ( n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44 ) * detInv;
  3812. te[ 3 ] = ( n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43 ) * detInv;
  3813. te[ 4 ] = t12 * detInv;
  3814. te[ 5 ] = ( n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44 ) * detInv;
  3815. te[ 6 ] = ( n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44 ) * detInv;
  3816. te[ 7 ] = ( n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43 ) * detInv;
  3817. te[ 8 ] = t13 * detInv;
  3818. te[ 9 ] = ( n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44 ) * detInv;
  3819. te[ 10 ] = ( n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44 ) * detInv;
  3820. te[ 11 ] = ( n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43 ) * detInv;
  3821. te[ 12 ] = t14 * detInv;
  3822. te[ 13 ] = ( n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34 ) * detInv;
  3823. te[ 14 ] = ( n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34 ) * detInv;
  3824. te[ 15 ] = ( n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33 ) * detInv;
  3825. return this;
  3826. }
  3827. scale( v ) {
  3828. const te = this.elements;
  3829. const x = v.x, y = v.y, z = v.z;
  3830. te[ 0 ] *= x; te[ 4 ] *= y; te[ 8 ] *= z;
  3831. te[ 1 ] *= x; te[ 5 ] *= y; te[ 9 ] *= z;
  3832. te[ 2 ] *= x; te[ 6 ] *= y; te[ 10 ] *= z;
  3833. te[ 3 ] *= x; te[ 7 ] *= y; te[ 11 ] *= z;
  3834. return this;
  3835. }
  3836. getMaxScaleOnAxis() {
  3837. const te = this.elements;
  3838. const scaleXSq = te[ 0 ] * te[ 0 ] + te[ 1 ] * te[ 1 ] + te[ 2 ] * te[ 2 ];
  3839. const scaleYSq = te[ 4 ] * te[ 4 ] + te[ 5 ] * te[ 5 ] + te[ 6 ] * te[ 6 ];
  3840. const scaleZSq = te[ 8 ] * te[ 8 ] + te[ 9 ] * te[ 9 ] + te[ 10 ] * te[ 10 ];
  3841. return Math.sqrt( Math.max( scaleXSq, scaleYSq, scaleZSq ) );
  3842. }
  3843. makeTranslation( x, y, z ) {
  3844. if ( x.isVector3 ) {
  3845. this.set(
  3846. 1, 0, 0, x.x,
  3847. 0, 1, 0, x.y,
  3848. 0, 0, 1, x.z,
  3849. 0, 0, 0, 1
  3850. );
  3851. } else {
  3852. this.set(
  3853. 1, 0, 0, x,
  3854. 0, 1, 0, y,
  3855. 0, 0, 1, z,
  3856. 0, 0, 0, 1
  3857. );
  3858. }
  3859. return this;
  3860. }
  3861. makeRotationX( theta ) {
  3862. const c = Math.cos( theta ), s = Math.sin( theta );
  3863. this.set(
  3864. 1, 0, 0, 0,
  3865. 0, c, - s, 0,
  3866. 0, s, c, 0,
  3867. 0, 0, 0, 1
  3868. );
  3869. return this;
  3870. }
  3871. makeRotationY( theta ) {
  3872. const c = Math.cos( theta ), s = Math.sin( theta );
  3873. this.set(
  3874. c, 0, s, 0,
  3875. 0, 1, 0, 0,
  3876. - s, 0, c, 0,
  3877. 0, 0, 0, 1
  3878. );
  3879. return this;
  3880. }
  3881. makeRotationZ( theta ) {
  3882. const c = Math.cos( theta ), s = Math.sin( theta );
  3883. this.set(
  3884. c, - s, 0, 0,
  3885. s, c, 0, 0,
  3886. 0, 0, 1, 0,
  3887. 0, 0, 0, 1
  3888. );
  3889. return this;
  3890. }
  3891. makeRotationAxis( axis, angle ) {
  3892. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  3893. const c = Math.cos( angle );
  3894. const s = Math.sin( angle );
  3895. const t = 1 - c;
  3896. const x = axis.x, y = axis.y, z = axis.z;
  3897. const tx = t * x, ty = t * y;
  3898. this.set(
  3899. tx * x + c, tx * y - s * z, tx * z + s * y, 0,
  3900. tx * y + s * z, ty * y + c, ty * z - s * x, 0,
  3901. tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
  3902. 0, 0, 0, 1
  3903. );
  3904. return this;
  3905. }
  3906. makeScale( x, y, z ) {
  3907. this.set(
  3908. x, 0, 0, 0,
  3909. 0, y, 0, 0,
  3910. 0, 0, z, 0,
  3911. 0, 0, 0, 1
  3912. );
  3913. return this;
  3914. }
  3915. makeShear( xy, xz, yx, yz, zx, zy ) {
  3916. this.set(
  3917. 1, yx, zx, 0,
  3918. xy, 1, zy, 0,
  3919. xz, yz, 1, 0,
  3920. 0, 0, 0, 1
  3921. );
  3922. return this;
  3923. }
  3924. compose( position, quaternion, scale ) {
  3925. const te = this.elements;
  3926. const x = quaternion._x, y = quaternion._y, z = quaternion._z, w = quaternion._w;
  3927. const x2 = x + x, y2 = y + y, z2 = z + z;
  3928. const xx = x * x2, xy = x * y2, xz = x * z2;
  3929. const yy = y * y2, yz = y * z2, zz = z * z2;
  3930. const wx = w * x2, wy = w * y2, wz = w * z2;
  3931. const sx = scale.x, sy = scale.y, sz = scale.z;
  3932. te[ 0 ] = ( 1 - ( yy + zz ) ) * sx;
  3933. te[ 1 ] = ( xy + wz ) * sx;
  3934. te[ 2 ] = ( xz - wy ) * sx;
  3935. te[ 3 ] = 0;
  3936. te[ 4 ] = ( xy - wz ) * sy;
  3937. te[ 5 ] = ( 1 - ( xx + zz ) ) * sy;
  3938. te[ 6 ] = ( yz + wx ) * sy;
  3939. te[ 7 ] = 0;
  3940. te[ 8 ] = ( xz + wy ) * sz;
  3941. te[ 9 ] = ( yz - wx ) * sz;
  3942. te[ 10 ] = ( 1 - ( xx + yy ) ) * sz;
  3943. te[ 11 ] = 0;
  3944. te[ 12 ] = position.x;
  3945. te[ 13 ] = position.y;
  3946. te[ 14 ] = position.z;
  3947. te[ 15 ] = 1;
  3948. return this;
  3949. }
  3950. decompose( position, quaternion, scale ) {
  3951. const te = this.elements;
  3952. let sx = _v1$5.set( te[ 0 ], te[ 1 ], te[ 2 ] ).length();
  3953. const sy = _v1$5.set( te[ 4 ], te[ 5 ], te[ 6 ] ).length();
  3954. const sz = _v1$5.set( te[ 8 ], te[ 9 ], te[ 10 ] ).length();
  3955. // if determine is negative, we need to invert one scale
  3956. const det = this.determinant();
  3957. if ( det < 0 ) sx = - sx;
  3958. position.x = te[ 12 ];
  3959. position.y = te[ 13 ];
  3960. position.z = te[ 14 ];
  3961. // scale the rotation part
  3962. _m1$2.copy( this );
  3963. const invSX = 1 / sx;
  3964. const invSY = 1 / sy;
  3965. const invSZ = 1 / sz;
  3966. _m1$2.elements[ 0 ] *= invSX;
  3967. _m1$2.elements[ 1 ] *= invSX;
  3968. _m1$2.elements[ 2 ] *= invSX;
  3969. _m1$2.elements[ 4 ] *= invSY;
  3970. _m1$2.elements[ 5 ] *= invSY;
  3971. _m1$2.elements[ 6 ] *= invSY;
  3972. _m1$2.elements[ 8 ] *= invSZ;
  3973. _m1$2.elements[ 9 ] *= invSZ;
  3974. _m1$2.elements[ 10 ] *= invSZ;
  3975. quaternion.setFromRotationMatrix( _m1$2 );
  3976. scale.x = sx;
  3977. scale.y = sy;
  3978. scale.z = sz;
  3979. return this;
  3980. }
  3981. makePerspective( left, right, top, bottom, near, far, coordinateSystem = WebGLCoordinateSystem ) {
  3982. const te = this.elements;
  3983. const x = 2 * near / ( right - left );
  3984. const y = 2 * near / ( top - bottom );
  3985. const a = ( right + left ) / ( right - left );
  3986. const b = ( top + bottom ) / ( top - bottom );
  3987. let c, d;
  3988. if ( coordinateSystem === WebGLCoordinateSystem ) {
  3989. c = - ( far + near ) / ( far - near );
  3990. d = ( - 2 * far * near ) / ( far - near );
  3991. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  3992. c = - far / ( far - near );
  3993. d = ( - far * near ) / ( far - near );
  3994. } else {
  3995. throw new Error( 'THREE.Matrix4.makePerspective(): Invalid coordinate system: ' + coordinateSystem );
  3996. }
  3997. te[ 0 ] = x; te[ 4 ] = 0; te[ 8 ] = a; te[ 12 ] = 0;
  3998. te[ 1 ] = 0; te[ 5 ] = y; te[ 9 ] = b; te[ 13 ] = 0;
  3999. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = c; te[ 14 ] = d;
  4000. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = - 1; te[ 15 ] = 0;
  4001. return this;
  4002. }
  4003. makeOrthographic( left, right, top, bottom, near, far, coordinateSystem = WebGLCoordinateSystem ) {
  4004. const te = this.elements;
  4005. const w = 1.0 / ( right - left );
  4006. const h = 1.0 / ( top - bottom );
  4007. const p = 1.0 / ( far - near );
  4008. const x = ( right + left ) * w;
  4009. const y = ( top + bottom ) * h;
  4010. let z, zInv;
  4011. if ( coordinateSystem === WebGLCoordinateSystem ) {
  4012. z = ( far + near ) * p;
  4013. zInv = - 2 * p;
  4014. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  4015. z = near * p;
  4016. zInv = - 1 * p;
  4017. } else {
  4018. throw new Error( 'THREE.Matrix4.makeOrthographic(): Invalid coordinate system: ' + coordinateSystem );
  4019. }
  4020. te[ 0 ] = 2 * w; te[ 4 ] = 0; te[ 8 ] = 0; te[ 12 ] = - x;
  4021. te[ 1 ] = 0; te[ 5 ] = 2 * h; te[ 9 ] = 0; te[ 13 ] = - y;
  4022. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = zInv; te[ 14 ] = - z;
  4023. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = 0; te[ 15 ] = 1;
  4024. return this;
  4025. }
  4026. equals( matrix ) {
  4027. const te = this.elements;
  4028. const me = matrix.elements;
  4029. for ( let i = 0; i < 16; i ++ ) {
  4030. if ( te[ i ] !== me[ i ] ) return false;
  4031. }
  4032. return true;
  4033. }
  4034. fromArray( array, offset = 0 ) {
  4035. for ( let i = 0; i < 16; i ++ ) {
  4036. this.elements[ i ] = array[ i + offset ];
  4037. }
  4038. return this;
  4039. }
  4040. toArray( array = [], offset = 0 ) {
  4041. const te = this.elements;
  4042. array[ offset ] = te[ 0 ];
  4043. array[ offset + 1 ] = te[ 1 ];
  4044. array[ offset + 2 ] = te[ 2 ];
  4045. array[ offset + 3 ] = te[ 3 ];
  4046. array[ offset + 4 ] = te[ 4 ];
  4047. array[ offset + 5 ] = te[ 5 ];
  4048. array[ offset + 6 ] = te[ 6 ];
  4049. array[ offset + 7 ] = te[ 7 ];
  4050. array[ offset + 8 ] = te[ 8 ];
  4051. array[ offset + 9 ] = te[ 9 ];
  4052. array[ offset + 10 ] = te[ 10 ];
  4053. array[ offset + 11 ] = te[ 11 ];
  4054. array[ offset + 12 ] = te[ 12 ];
  4055. array[ offset + 13 ] = te[ 13 ];
  4056. array[ offset + 14 ] = te[ 14 ];
  4057. array[ offset + 15 ] = te[ 15 ];
  4058. return array;
  4059. }
  4060. }
  4061. const _v1$5 = /*@__PURE__*/ new Vector3();
  4062. const _m1$2 = /*@__PURE__*/ new Matrix4();
  4063. const _zero = /*@__PURE__*/ new Vector3( 0, 0, 0 );
  4064. const _one = /*@__PURE__*/ new Vector3( 1, 1, 1 );
  4065. const _x = /*@__PURE__*/ new Vector3();
  4066. const _y = /*@__PURE__*/ new Vector3();
  4067. const _z = /*@__PURE__*/ new Vector3();
  4068. const _matrix$1 = /*@__PURE__*/ new Matrix4();
  4069. const _quaternion$3 = /*@__PURE__*/ new Quaternion();
  4070. class Euler {
  4071. constructor( x = 0, y = 0, z = 0, order = Euler.DEFAULT_ORDER ) {
  4072. this.isEuler = true;
  4073. this._x = x;
  4074. this._y = y;
  4075. this._z = z;
  4076. this._order = order;
  4077. }
  4078. get x() {
  4079. return this._x;
  4080. }
  4081. set x( value ) {
  4082. this._x = value;
  4083. this._onChangeCallback();
  4084. }
  4085. get y() {
  4086. return this._y;
  4087. }
  4088. set y( value ) {
  4089. this._y = value;
  4090. this._onChangeCallback();
  4091. }
  4092. get z() {
  4093. return this._z;
  4094. }
  4095. set z( value ) {
  4096. this._z = value;
  4097. this._onChangeCallback();
  4098. }
  4099. get order() {
  4100. return this._order;
  4101. }
  4102. set order( value ) {
  4103. this._order = value;
  4104. this._onChangeCallback();
  4105. }
  4106. set( x, y, z, order = this._order ) {
  4107. this._x = x;
  4108. this._y = y;
  4109. this._z = z;
  4110. this._order = order;
  4111. this._onChangeCallback();
  4112. return this;
  4113. }
  4114. clone() {
  4115. return new this.constructor( this._x, this._y, this._z, this._order );
  4116. }
  4117. copy( euler ) {
  4118. this._x = euler._x;
  4119. this._y = euler._y;
  4120. this._z = euler._z;
  4121. this._order = euler._order;
  4122. this._onChangeCallback();
  4123. return this;
  4124. }
  4125. setFromRotationMatrix( m, order = this._order, update = true ) {
  4126. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  4127. const te = m.elements;
  4128. const m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ];
  4129. const m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ];
  4130. const m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  4131. switch ( order ) {
  4132. case 'XYZ':
  4133. this._y = Math.asin( clamp( m13, - 1, 1 ) );
  4134. if ( Math.abs( m13 ) < 0.9999999 ) {
  4135. this._x = Math.atan2( - m23, m33 );
  4136. this._z = Math.atan2( - m12, m11 );
  4137. } else {
  4138. this._x = Math.atan2( m32, m22 );
  4139. this._z = 0;
  4140. }
  4141. break;
  4142. case 'YXZ':
  4143. this._x = Math.asin( - clamp( m23, - 1, 1 ) );
  4144. if ( Math.abs( m23 ) < 0.9999999 ) {
  4145. this._y = Math.atan2( m13, m33 );
  4146. this._z = Math.atan2( m21, m22 );
  4147. } else {
  4148. this._y = Math.atan2( - m31, m11 );
  4149. this._z = 0;
  4150. }
  4151. break;
  4152. case 'ZXY':
  4153. this._x = Math.asin( clamp( m32, - 1, 1 ) );
  4154. if ( Math.abs( m32 ) < 0.9999999 ) {
  4155. this._y = Math.atan2( - m31, m33 );
  4156. this._z = Math.atan2( - m12, m22 );
  4157. } else {
  4158. this._y = 0;
  4159. this._z = Math.atan2( m21, m11 );
  4160. }
  4161. break;
  4162. case 'ZYX':
  4163. this._y = Math.asin( - clamp( m31, - 1, 1 ) );
  4164. if ( Math.abs( m31 ) < 0.9999999 ) {
  4165. this._x = Math.atan2( m32, m33 );
  4166. this._z = Math.atan2( m21, m11 );
  4167. } else {
  4168. this._x = 0;
  4169. this._z = Math.atan2( - m12, m22 );
  4170. }
  4171. break;
  4172. case 'YZX':
  4173. this._z = Math.asin( clamp( m21, - 1, 1 ) );
  4174. if ( Math.abs( m21 ) < 0.9999999 ) {
  4175. this._x = Math.atan2( - m23, m22 );
  4176. this._y = Math.atan2( - m31, m11 );
  4177. } else {
  4178. this._x = 0;
  4179. this._y = Math.atan2( m13, m33 );
  4180. }
  4181. break;
  4182. case 'XZY':
  4183. this._z = Math.asin( - clamp( m12, - 1, 1 ) );
  4184. if ( Math.abs( m12 ) < 0.9999999 ) {
  4185. this._x = Math.atan2( m32, m22 );
  4186. this._y = Math.atan2( m13, m11 );
  4187. } else {
  4188. this._x = Math.atan2( - m23, m33 );
  4189. this._y = 0;
  4190. }
  4191. break;
  4192. default:
  4193. console.warn( 'THREE.Euler: .setFromRotationMatrix() encountered an unknown order: ' + order );
  4194. }
  4195. this._order = order;
  4196. if ( update === true ) this._onChangeCallback();
  4197. return this;
  4198. }
  4199. setFromQuaternion( q, order, update ) {
  4200. _matrix$1.makeRotationFromQuaternion( q );
  4201. return this.setFromRotationMatrix( _matrix$1, order, update );
  4202. }
  4203. setFromVector3( v, order = this._order ) {
  4204. return this.set( v.x, v.y, v.z, order );
  4205. }
  4206. reorder( newOrder ) {
  4207. // WARNING: this discards revolution information -bhouston
  4208. _quaternion$3.setFromEuler( this );
  4209. return this.setFromQuaternion( _quaternion$3, newOrder );
  4210. }
  4211. equals( euler ) {
  4212. return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order );
  4213. }
  4214. fromArray( array ) {
  4215. this._x = array[ 0 ];
  4216. this._y = array[ 1 ];
  4217. this._z = array[ 2 ];
  4218. if ( array[ 3 ] !== undefined ) this._order = array[ 3 ];
  4219. this._onChangeCallback();
  4220. return this;
  4221. }
  4222. toArray( array = [], offset = 0 ) {
  4223. array[ offset ] = this._x;
  4224. array[ offset + 1 ] = this._y;
  4225. array[ offset + 2 ] = this._z;
  4226. array[ offset + 3 ] = this._order;
  4227. return array;
  4228. }
  4229. _onChange( callback ) {
  4230. this._onChangeCallback = callback;
  4231. return this;
  4232. }
  4233. _onChangeCallback() {}
  4234. *[ Symbol.iterator ]() {
  4235. yield this._x;
  4236. yield this._y;
  4237. yield this._z;
  4238. yield this._order;
  4239. }
  4240. }
  4241. Euler.DEFAULT_ORDER = 'XYZ';
  4242. class Layers {
  4243. constructor() {
  4244. this.mask = 1 | 0;
  4245. }
  4246. set( channel ) {
  4247. this.mask = ( 1 << channel | 0 ) >>> 0;
  4248. }
  4249. enable( channel ) {
  4250. this.mask |= 1 << channel | 0;
  4251. }
  4252. enableAll() {
  4253. this.mask = 0xffffffff | 0;
  4254. }
  4255. toggle( channel ) {
  4256. this.mask ^= 1 << channel | 0;
  4257. }
  4258. disable( channel ) {
  4259. this.mask &= ~ ( 1 << channel | 0 );
  4260. }
  4261. disableAll() {
  4262. this.mask = 0;
  4263. }
  4264. test( layers ) {
  4265. return ( this.mask & layers.mask ) !== 0;
  4266. }
  4267. isEnabled( channel ) {
  4268. return ( this.mask & ( 1 << channel | 0 ) ) !== 0;
  4269. }
  4270. }
  4271. let _object3DId = 0;
  4272. const _v1$4 = /*@__PURE__*/ new Vector3();
  4273. const _q1 = /*@__PURE__*/ new Quaternion();
  4274. const _m1$1 = /*@__PURE__*/ new Matrix4();
  4275. const _target = /*@__PURE__*/ new Vector3();
  4276. const _position$3 = /*@__PURE__*/ new Vector3();
  4277. const _scale$2 = /*@__PURE__*/ new Vector3();
  4278. const _quaternion$2 = /*@__PURE__*/ new Quaternion();
  4279. const _xAxis = /*@__PURE__*/ new Vector3( 1, 0, 0 );
  4280. const _yAxis = /*@__PURE__*/ new Vector3( 0, 1, 0 );
  4281. const _zAxis = /*@__PURE__*/ new Vector3( 0, 0, 1 );
  4282. const _addedEvent = { type: 'added' };
  4283. const _removedEvent = { type: 'removed' };
  4284. class Object3D extends EventDispatcher {
  4285. constructor() {
  4286. super();
  4287. this.isObject3D = true;
  4288. Object.defineProperty( this, 'id', { value: _object3DId ++ } );
  4289. this.uuid = generateUUID();
  4290. this.name = '';
  4291. this.type = 'Object3D';
  4292. this.parent = null;
  4293. this.children = [];
  4294. this.up = Object3D.DEFAULT_UP.clone();
  4295. const position = new Vector3();
  4296. const rotation = new Euler();
  4297. const quaternion = new Quaternion();
  4298. const scale = new Vector3( 1, 1, 1 );
  4299. function onRotationChange() {
  4300. quaternion.setFromEuler( rotation, false );
  4301. }
  4302. function onQuaternionChange() {
  4303. rotation.setFromQuaternion( quaternion, undefined, false );
  4304. }
  4305. rotation._onChange( onRotationChange );
  4306. quaternion._onChange( onQuaternionChange );
  4307. Object.defineProperties( this, {
  4308. position: {
  4309. configurable: true,
  4310. enumerable: true,
  4311. value: position
  4312. },
  4313. rotation: {
  4314. configurable: true,
  4315. enumerable: true,
  4316. value: rotation
  4317. },
  4318. quaternion: {
  4319. configurable: true,
  4320. enumerable: true,
  4321. value: quaternion
  4322. },
  4323. scale: {
  4324. configurable: true,
  4325. enumerable: true,
  4326. value: scale
  4327. },
  4328. modelViewMatrix: {
  4329. value: new Matrix4()
  4330. },
  4331. normalMatrix: {
  4332. value: new Matrix3()
  4333. }
  4334. } );
  4335. this.matrix = new Matrix4();
  4336. this.matrixWorld = new Matrix4();
  4337. this.matrixAutoUpdate = Object3D.DEFAULT_MATRIX_AUTO_UPDATE;
  4338. this.matrixWorldAutoUpdate = Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE; // checked by the renderer
  4339. this.matrixWorldNeedsUpdate = false;
  4340. this.layers = new Layers();
  4341. this.visible = true;
  4342. this.castShadow = false;
  4343. this.receiveShadow = false;
  4344. this.frustumCulled = true;
  4345. this.renderOrder = 0;
  4346. this.animations = [];
  4347. this.userData = {};
  4348. }
  4349. onBeforeShadow( /* renderer, object, camera, shadowCamera, geometry, depthMaterial, group */ ) {}
  4350. onAfterShadow( /* renderer, object, camera, shadowCamera, geometry, depthMaterial, group */ ) {}
  4351. onBeforeRender( /* renderer, scene, camera, geometry, material, group */ ) {}
  4352. onAfterRender( /* renderer, scene, camera, geometry, material, group */ ) {}
  4353. applyMatrix4( matrix ) {
  4354. if ( this.matrixAutoUpdate ) this.updateMatrix();
  4355. this.matrix.premultiply( matrix );
  4356. this.matrix.decompose( this.position, this.quaternion, this.scale );
  4357. }
  4358. applyQuaternion( q ) {
  4359. this.quaternion.premultiply( q );
  4360. return this;
  4361. }
  4362. setRotationFromAxisAngle( axis, angle ) {
  4363. // assumes axis is normalized
  4364. this.quaternion.setFromAxisAngle( axis, angle );
  4365. }
  4366. setRotationFromEuler( euler ) {
  4367. this.quaternion.setFromEuler( euler, true );
  4368. }
  4369. setRotationFromMatrix( m ) {
  4370. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  4371. this.quaternion.setFromRotationMatrix( m );
  4372. }
  4373. setRotationFromQuaternion( q ) {
  4374. // assumes q is normalized
  4375. this.quaternion.copy( q );
  4376. }
  4377. rotateOnAxis( axis, angle ) {
  4378. // rotate object on axis in object space
  4379. // axis is assumed to be normalized
  4380. _q1.setFromAxisAngle( axis, angle );
  4381. this.quaternion.multiply( _q1 );
  4382. return this;
  4383. }
  4384. rotateOnWorldAxis( axis, angle ) {
  4385. // rotate object on axis in world space
  4386. // axis is assumed to be normalized
  4387. // method assumes no rotated parent
  4388. _q1.setFromAxisAngle( axis, angle );
  4389. this.quaternion.premultiply( _q1 );
  4390. return this;
  4391. }
  4392. rotateX( angle ) {
  4393. return this.rotateOnAxis( _xAxis, angle );
  4394. }
  4395. rotateY( angle ) {
  4396. return this.rotateOnAxis( _yAxis, angle );
  4397. }
  4398. rotateZ( angle ) {
  4399. return this.rotateOnAxis( _zAxis, angle );
  4400. }
  4401. translateOnAxis( axis, distance ) {
  4402. // translate object by distance along axis in object space
  4403. // axis is assumed to be normalized
  4404. _v1$4.copy( axis ).applyQuaternion( this.quaternion );
  4405. this.position.add( _v1$4.multiplyScalar( distance ) );
  4406. return this;
  4407. }
  4408. translateX( distance ) {
  4409. return this.translateOnAxis( _xAxis, distance );
  4410. }
  4411. translateY( distance ) {
  4412. return this.translateOnAxis( _yAxis, distance );
  4413. }
  4414. translateZ( distance ) {
  4415. return this.translateOnAxis( _zAxis, distance );
  4416. }
  4417. localToWorld( vector ) {
  4418. this.updateWorldMatrix( true, false );
  4419. return vector.applyMatrix4( this.matrixWorld );
  4420. }
  4421. worldToLocal( vector ) {
  4422. this.updateWorldMatrix( true, false );
  4423. return vector.applyMatrix4( _m1$1.copy( this.matrixWorld ).invert() );
  4424. }
  4425. lookAt( x, y, z ) {
  4426. // This method does not support objects having non-uniformly-scaled parent(s)
  4427. if ( x.isVector3 ) {
  4428. _target.copy( x );
  4429. } else {
  4430. _target.set( x, y, z );
  4431. }
  4432. const parent = this.parent;
  4433. this.updateWorldMatrix( true, false );
  4434. _position$3.setFromMatrixPosition( this.matrixWorld );
  4435. if ( this.isCamera || this.isLight ) {
  4436. _m1$1.lookAt( _position$3, _target, this.up );
  4437. } else {
  4438. _m1$1.lookAt( _target, _position$3, this.up );
  4439. }
  4440. this.quaternion.setFromRotationMatrix( _m1$1 );
  4441. if ( parent ) {
  4442. _m1$1.extractRotation( parent.matrixWorld );
  4443. _q1.setFromRotationMatrix( _m1$1 );
  4444. this.quaternion.premultiply( _q1.invert() );
  4445. }
  4446. }
  4447. add( object ) {
  4448. if ( arguments.length > 1 ) {
  4449. for ( let i = 0; i < arguments.length; i ++ ) {
  4450. this.add( arguments[ i ] );
  4451. }
  4452. return this;
  4453. }
  4454. if ( object === this ) {
  4455. console.error( 'THREE.Object3D.add: object can\'t be added as a child of itself.', object );
  4456. return this;
  4457. }
  4458. if ( object && object.isObject3D ) {
  4459. if ( object.parent !== null ) {
  4460. object.parent.remove( object );
  4461. }
  4462. object.parent = this;
  4463. this.children.push( object );
  4464. object.dispatchEvent( _addedEvent );
  4465. } else {
  4466. console.error( 'THREE.Object3D.add: object not an instance of THREE.Object3D.', object );
  4467. }
  4468. return this;
  4469. }
  4470. remove( object ) {
  4471. if ( arguments.length > 1 ) {
  4472. for ( let i = 0; i < arguments.length; i ++ ) {
  4473. this.remove( arguments[ i ] );
  4474. }
  4475. return this;
  4476. }
  4477. const index = this.children.indexOf( object );
  4478. if ( index !== - 1 ) {
  4479. object.parent = null;
  4480. this.children.splice( index, 1 );
  4481. object.dispatchEvent( _removedEvent );
  4482. }
  4483. return this;
  4484. }
  4485. removeFromParent() {
  4486. const parent = this.parent;
  4487. if ( parent !== null ) {
  4488. parent.remove( this );
  4489. }
  4490. return this;
  4491. }
  4492. clear() {
  4493. return this.remove( ... this.children );
  4494. }
  4495. attach( object ) {
  4496. // adds object as a child of this, while maintaining the object's world transform
  4497. // Note: This method does not support scene graphs having non-uniformly-scaled nodes(s)
  4498. this.updateWorldMatrix( true, false );
  4499. _m1$1.copy( this.matrixWorld ).invert();
  4500. if ( object.parent !== null ) {
  4501. object.parent.updateWorldMatrix( true, false );
  4502. _m1$1.multiply( object.parent.matrixWorld );
  4503. }
  4504. object.applyMatrix4( _m1$1 );
  4505. this.add( object );
  4506. object.updateWorldMatrix( false, true );
  4507. return this;
  4508. }
  4509. getObjectById( id ) {
  4510. return this.getObjectByProperty( 'id', id );
  4511. }
  4512. getObjectByName( name ) {
  4513. return this.getObjectByProperty( 'name', name );
  4514. }
  4515. getObjectByProperty( name, value ) {
  4516. if ( this[ name ] === value ) return this;
  4517. for ( let i = 0, l = this.children.length; i < l; i ++ ) {
  4518. const child = this.children[ i ];
  4519. const object = child.getObjectByProperty( name, value );
  4520. if ( object !== undefined ) {
  4521. return object;
  4522. }
  4523. }
  4524. return undefined;
  4525. }
  4526. getObjectsByProperty( name, value, result = [] ) {
  4527. if ( this[ name ] === value ) result.push( this );
  4528. const children = this.children;
  4529. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4530. children[ i ].getObjectsByProperty( name, value, result );
  4531. }
  4532. return result;
  4533. }
  4534. getWorldPosition( target ) {
  4535. this.updateWorldMatrix( true, false );
  4536. return target.setFromMatrixPosition( this.matrixWorld );
  4537. }
  4538. getWorldQuaternion( target ) {
  4539. this.updateWorldMatrix( true, false );
  4540. this.matrixWorld.decompose( _position$3, target, _scale$2 );
  4541. return target;
  4542. }
  4543. getWorldScale( target ) {
  4544. this.updateWorldMatrix( true, false );
  4545. this.matrixWorld.decompose( _position$3, _quaternion$2, target );
  4546. return target;
  4547. }
  4548. getWorldDirection( target ) {
  4549. this.updateWorldMatrix( true, false );
  4550. const e = this.matrixWorld.elements;
  4551. return target.set( e[ 8 ], e[ 9 ], e[ 10 ] ).normalize();
  4552. }
  4553. raycast( /* raycaster, intersects */ ) {}
  4554. traverse( callback ) {
  4555. callback( this );
  4556. const children = this.children;
  4557. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4558. children[ i ].traverse( callback );
  4559. }
  4560. }
  4561. traverseVisible( callback ) {
  4562. if ( this.visible === false ) return;
  4563. callback( this );
  4564. const children = this.children;
  4565. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4566. children[ i ].traverseVisible( callback );
  4567. }
  4568. }
  4569. traverseAncestors( callback ) {
  4570. const parent = this.parent;
  4571. if ( parent !== null ) {
  4572. callback( parent );
  4573. parent.traverseAncestors( callback );
  4574. }
  4575. }
  4576. updateMatrix() {
  4577. this.matrix.compose( this.position, this.quaternion, this.scale );
  4578. this.matrixWorldNeedsUpdate = true;
  4579. }
  4580. updateMatrixWorld( force ) {
  4581. if ( this.matrixAutoUpdate ) this.updateMatrix();
  4582. if ( this.matrixWorldNeedsUpdate || force ) {
  4583. if ( this.parent === null ) {
  4584. this.matrixWorld.copy( this.matrix );
  4585. } else {
  4586. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  4587. }
  4588. this.matrixWorldNeedsUpdate = false;
  4589. force = true;
  4590. }
  4591. // update children
  4592. const children = this.children;
  4593. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4594. const child = children[ i ];
  4595. if ( child.matrixWorldAutoUpdate === true || force === true ) {
  4596. child.updateMatrixWorld( force );
  4597. }
  4598. }
  4599. }
  4600. updateWorldMatrix( updateParents, updateChildren ) {
  4601. const parent = this.parent;
  4602. if ( updateParents === true && parent !== null && parent.matrixWorldAutoUpdate === true ) {
  4603. parent.updateWorldMatrix( true, false );
  4604. }
  4605. if ( this.matrixAutoUpdate ) this.updateMatrix();
  4606. if ( this.parent === null ) {
  4607. this.matrixWorld.copy( this.matrix );
  4608. } else {
  4609. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  4610. }
  4611. // update children
  4612. if ( updateChildren === true ) {
  4613. const children = this.children;
  4614. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4615. const child = children[ i ];
  4616. if ( child.matrixWorldAutoUpdate === true ) {
  4617. child.updateWorldMatrix( false, true );
  4618. }
  4619. }
  4620. }
  4621. }
  4622. toJSON( meta ) {
  4623. // meta is a string when called from JSON.stringify
  4624. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  4625. const output = {};
  4626. // meta is a hash used to collect geometries, materials.
  4627. // not providing it implies that this is the root object
  4628. // being serialized.
  4629. if ( isRootObject ) {
  4630. // initialize meta obj
  4631. meta = {
  4632. geometries: {},
  4633. materials: {},
  4634. textures: {},
  4635. images: {},
  4636. shapes: {},
  4637. skeletons: {},
  4638. animations: {},
  4639. nodes: {}
  4640. };
  4641. output.metadata = {
  4642. version: 4.6,
  4643. type: 'Object',
  4644. generator: 'Object3D.toJSON'
  4645. };
  4646. }
  4647. // standard Object3D serialization
  4648. const object = {};
  4649. object.uuid = this.uuid;
  4650. object.type = this.type;
  4651. if ( this.name !== '' ) object.name = this.name;
  4652. if ( this.castShadow === true ) object.castShadow = true;
  4653. if ( this.receiveShadow === true ) object.receiveShadow = true;
  4654. if ( this.visible === false ) object.visible = false;
  4655. if ( this.frustumCulled === false ) object.frustumCulled = false;
  4656. if ( this.renderOrder !== 0 ) object.renderOrder = this.renderOrder;
  4657. if ( Object.keys( this.userData ).length > 0 ) object.userData = this.userData;
  4658. object.layers = this.layers.mask;
  4659. object.matrix = this.matrix.toArray();
  4660. object.up = this.up.toArray();
  4661. if ( this.matrixAutoUpdate === false ) object.matrixAutoUpdate = false;
  4662. // object specific properties
  4663. if ( this.isInstancedMesh ) {
  4664. object.type = 'InstancedMesh';
  4665. object.count = this.count;
  4666. object.instanceMatrix = this.instanceMatrix.toJSON();
  4667. if ( this.instanceColor !== null ) object.instanceColor = this.instanceColor.toJSON();
  4668. }
  4669. if ( this.isBatchedMesh ) {
  4670. object.type = 'BatchedMesh';
  4671. object.perObjectFrustumCulled = this.perObjectFrustumCulled;
  4672. object.sortObjects = this.sortObjects;
  4673. object.drawRanges = this._drawRanges;
  4674. object.reservedRanges = this._reservedRanges;
  4675. object.visibility = this._visibility;
  4676. object.active = this._active;
  4677. object.bounds = this._bounds.map( bound => ( {
  4678. boxInitialized: bound.boxInitialized,
  4679. boxMin: bound.box.min.toArray(),
  4680. boxMax: bound.box.max.toArray(),
  4681. sphereInitialized: bound.sphereInitialized,
  4682. sphereRadius: bound.sphere.radius,
  4683. sphereCenter: bound.sphere.center.toArray()
  4684. } ) );
  4685. object.maxGeometryCount = this._maxGeometryCount;
  4686. object.maxVertexCount = this._maxVertexCount;
  4687. object.maxIndexCount = this._maxIndexCount;
  4688. object.geometryInitialized = this._geometryInitialized;
  4689. object.geometryCount = this._geometryCount;
  4690. object.matricesTexture = this._matricesTexture.toJSON( meta );
  4691. if ( this.boundingSphere !== null ) {
  4692. object.boundingSphere = {
  4693. center: object.boundingSphere.center.toArray(),
  4694. radius: object.boundingSphere.radius
  4695. };
  4696. }
  4697. if ( this.boundingBox !== null ) {
  4698. object.boundingBox = {
  4699. min: object.boundingBox.min.toArray(),
  4700. max: object.boundingBox.max.toArray()
  4701. };
  4702. }
  4703. }
  4704. //
  4705. function serialize( library, element ) {
  4706. if ( library[ element.uuid ] === undefined ) {
  4707. library[ element.uuid ] = element.toJSON( meta );
  4708. }
  4709. return element.uuid;
  4710. }
  4711. if ( this.isScene ) {
  4712. if ( this.background ) {
  4713. if ( this.background.isColor ) {
  4714. object.background = this.background.toJSON();
  4715. } else if ( this.background.isTexture ) {
  4716. object.background = this.background.toJSON( meta ).uuid;
  4717. }
  4718. }
  4719. if ( this.environment && this.environment.isTexture && this.environment.isRenderTargetTexture !== true ) {
  4720. object.environment = this.environment.toJSON( meta ).uuid;
  4721. }
  4722. } else if ( this.isMesh || this.isLine || this.isPoints ) {
  4723. object.geometry = serialize( meta.geometries, this.geometry );
  4724. const parameters = this.geometry.parameters;
  4725. if ( parameters !== undefined && parameters.shapes !== undefined ) {
  4726. const shapes = parameters.shapes;
  4727. if ( Array.isArray( shapes ) ) {
  4728. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  4729. const shape = shapes[ i ];
  4730. serialize( meta.shapes, shape );
  4731. }
  4732. } else {
  4733. serialize( meta.shapes, shapes );
  4734. }
  4735. }
  4736. }
  4737. if ( this.isSkinnedMesh ) {
  4738. object.bindMode = this.bindMode;
  4739. object.bindMatrix = this.bindMatrix.toArray();
  4740. if ( this.skeleton !== undefined ) {
  4741. serialize( meta.skeletons, this.skeleton );
  4742. object.skeleton = this.skeleton.uuid;
  4743. }
  4744. }
  4745. if ( this.material !== undefined ) {
  4746. if ( Array.isArray( this.material ) ) {
  4747. const uuids = [];
  4748. for ( let i = 0, l = this.material.length; i < l; i ++ ) {
  4749. uuids.push( serialize( meta.materials, this.material[ i ] ) );
  4750. }
  4751. object.material = uuids;
  4752. } else {
  4753. object.material = serialize( meta.materials, this.material );
  4754. }
  4755. }
  4756. //
  4757. if ( this.children.length > 0 ) {
  4758. object.children = [];
  4759. for ( let i = 0; i < this.children.length; i ++ ) {
  4760. object.children.push( this.children[ i ].toJSON( meta ).object );
  4761. }
  4762. }
  4763. //
  4764. if ( this.animations.length > 0 ) {
  4765. object.animations = [];
  4766. for ( let i = 0; i < this.animations.length; i ++ ) {
  4767. const animation = this.animations[ i ];
  4768. object.animations.push( serialize( meta.animations, animation ) );
  4769. }
  4770. }
  4771. if ( isRootObject ) {
  4772. const geometries = extractFromCache( meta.geometries );
  4773. const materials = extractFromCache( meta.materials );
  4774. const textures = extractFromCache( meta.textures );
  4775. const images = extractFromCache( meta.images );
  4776. const shapes = extractFromCache( meta.shapes );
  4777. const skeletons = extractFromCache( meta.skeletons );
  4778. const animations = extractFromCache( meta.animations );
  4779. const nodes = extractFromCache( meta.nodes );
  4780. if ( geometries.length > 0 ) output.geometries = geometries;
  4781. if ( materials.length > 0 ) output.materials = materials;
  4782. if ( textures.length > 0 ) output.textures = textures;
  4783. if ( images.length > 0 ) output.images = images;
  4784. if ( shapes.length > 0 ) output.shapes = shapes;
  4785. if ( skeletons.length > 0 ) output.skeletons = skeletons;
  4786. if ( animations.length > 0 ) output.animations = animations;
  4787. if ( nodes.length > 0 ) output.nodes = nodes;
  4788. }
  4789. output.object = object;
  4790. return output;
  4791. // extract data from the cache hash
  4792. // remove metadata on each item
  4793. // and return as array
  4794. function extractFromCache( cache ) {
  4795. const values = [];
  4796. for ( const key in cache ) {
  4797. const data = cache[ key ];
  4798. delete data.metadata;
  4799. values.push( data );
  4800. }
  4801. return values;
  4802. }
  4803. }
  4804. clone( recursive ) {
  4805. return new this.constructor().copy( this, recursive );
  4806. }
  4807. copy( source, recursive = true ) {
  4808. this.name = source.name;
  4809. this.up.copy( source.up );
  4810. this.position.copy( source.position );
  4811. this.rotation.order = source.rotation.order;
  4812. this.quaternion.copy( source.quaternion );
  4813. this.scale.copy( source.scale );
  4814. this.matrix.copy( source.matrix );
  4815. this.matrixWorld.copy( source.matrixWorld );
  4816. this.matrixAutoUpdate = source.matrixAutoUpdate;
  4817. this.matrixWorldAutoUpdate = source.matrixWorldAutoUpdate;
  4818. this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;
  4819. this.layers.mask = source.layers.mask;
  4820. this.visible = source.visible;
  4821. this.castShadow = source.castShadow;
  4822. this.receiveShadow = source.receiveShadow;
  4823. this.frustumCulled = source.frustumCulled;
  4824. this.renderOrder = source.renderOrder;
  4825. this.animations = source.animations.slice();
  4826. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  4827. if ( recursive === true ) {
  4828. for ( let i = 0; i < source.children.length; i ++ ) {
  4829. const child = source.children[ i ];
  4830. this.add( child.clone() );
  4831. }
  4832. }
  4833. return this;
  4834. }
  4835. }
  4836. Object3D.DEFAULT_UP = /*@__PURE__*/ new Vector3( 0, 1, 0 );
  4837. Object3D.DEFAULT_MATRIX_AUTO_UPDATE = true;
  4838. Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE = true;
  4839. const _v0$1 = /*@__PURE__*/ new Vector3();
  4840. const _v1$3 = /*@__PURE__*/ new Vector3();
  4841. const _v2$2 = /*@__PURE__*/ new Vector3();
  4842. const _v3$2 = /*@__PURE__*/ new Vector3();
  4843. const _vab = /*@__PURE__*/ new Vector3();
  4844. const _vac = /*@__PURE__*/ new Vector3();
  4845. const _vbc = /*@__PURE__*/ new Vector3();
  4846. const _vap = /*@__PURE__*/ new Vector3();
  4847. const _vbp = /*@__PURE__*/ new Vector3();
  4848. const _vcp = /*@__PURE__*/ new Vector3();
  4849. class Triangle {
  4850. constructor( a = new Vector3(), b = new Vector3(), c = new Vector3() ) {
  4851. this.a = a;
  4852. this.b = b;
  4853. this.c = c;
  4854. }
  4855. static getNormal( a, b, c, target ) {
  4856. target.subVectors( c, b );
  4857. _v0$1.subVectors( a, b );
  4858. target.cross( _v0$1 );
  4859. const targetLengthSq = target.lengthSq();
  4860. if ( targetLengthSq > 0 ) {
  4861. return target.multiplyScalar( 1 / Math.sqrt( targetLengthSq ) );
  4862. }
  4863. return target.set( 0, 0, 0 );
  4864. }
  4865. // static/instance method to calculate barycentric coordinates
  4866. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  4867. static getBarycoord( point, a, b, c, target ) {
  4868. _v0$1.subVectors( c, a );
  4869. _v1$3.subVectors( b, a );
  4870. _v2$2.subVectors( point, a );
  4871. const dot00 = _v0$1.dot( _v0$1 );
  4872. const dot01 = _v0$1.dot( _v1$3 );
  4873. const dot02 = _v0$1.dot( _v2$2 );
  4874. const dot11 = _v1$3.dot( _v1$3 );
  4875. const dot12 = _v1$3.dot( _v2$2 );
  4876. const denom = ( dot00 * dot11 - dot01 * dot01 );
  4877. // collinear or singular triangle
  4878. if ( denom === 0 ) {
  4879. target.set( 0, 0, 0 );
  4880. return null;
  4881. }
  4882. const invDenom = 1 / denom;
  4883. const u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  4884. const v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  4885. // barycentric coordinates must always sum to 1
  4886. return target.set( 1 - u - v, v, u );
  4887. }
  4888. static containsPoint( point, a, b, c ) {
  4889. // if the triangle is degenerate then we can't contain a point
  4890. if ( this.getBarycoord( point, a, b, c, _v3$2 ) === null ) {
  4891. return false;
  4892. }
  4893. return ( _v3$2.x >= 0 ) && ( _v3$2.y >= 0 ) && ( ( _v3$2.x + _v3$2.y ) <= 1 );
  4894. }
  4895. static getInterpolation( point, p1, p2, p3, v1, v2, v3, target ) {
  4896. if ( this.getBarycoord( point, p1, p2, p3, _v3$2 ) === null ) {
  4897. target.x = 0;
  4898. target.y = 0;
  4899. if ( 'z' in target ) target.z = 0;
  4900. if ( 'w' in target ) target.w = 0;
  4901. return null;
  4902. }
  4903. target.setScalar( 0 );
  4904. target.addScaledVector( v1, _v3$2.x );
  4905. target.addScaledVector( v2, _v3$2.y );
  4906. target.addScaledVector( v3, _v3$2.z );
  4907. return target;
  4908. }
  4909. static isFrontFacing( a, b, c, direction ) {
  4910. _v0$1.subVectors( c, b );
  4911. _v1$3.subVectors( a, b );
  4912. // strictly front facing
  4913. return ( _v0$1.cross( _v1$3 ).dot( direction ) < 0 ) ? true : false;
  4914. }
  4915. set( a, b, c ) {
  4916. this.a.copy( a );
  4917. this.b.copy( b );
  4918. this.c.copy( c );
  4919. return this;
  4920. }
  4921. setFromPointsAndIndices( points, i0, i1, i2 ) {
  4922. this.a.copy( points[ i0 ] );
  4923. this.b.copy( points[ i1 ] );
  4924. this.c.copy( points[ i2 ] );
  4925. return this;
  4926. }
  4927. setFromAttributeAndIndices( attribute, i0, i1, i2 ) {
  4928. this.a.fromBufferAttribute( attribute, i0 );
  4929. this.b.fromBufferAttribute( attribute, i1 );
  4930. this.c.fromBufferAttribute( attribute, i2 );
  4931. return this;
  4932. }
  4933. clone() {
  4934. return new this.constructor().copy( this );
  4935. }
  4936. copy( triangle ) {
  4937. this.a.copy( triangle.a );
  4938. this.b.copy( triangle.b );
  4939. this.c.copy( triangle.c );
  4940. return this;
  4941. }
  4942. getArea() {
  4943. _v0$1.subVectors( this.c, this.b );
  4944. _v1$3.subVectors( this.a, this.b );
  4945. return _v0$1.cross( _v1$3 ).length() * 0.5;
  4946. }
  4947. getMidpoint( target ) {
  4948. return target.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 );
  4949. }
  4950. getNormal( target ) {
  4951. return Triangle.getNormal( this.a, this.b, this.c, target );
  4952. }
  4953. getPlane( target ) {
  4954. return target.setFromCoplanarPoints( this.a, this.b, this.c );
  4955. }
  4956. getBarycoord( point, target ) {
  4957. return Triangle.getBarycoord( point, this.a, this.b, this.c, target );
  4958. }
  4959. getInterpolation( point, v1, v2, v3, target ) {
  4960. return Triangle.getInterpolation( point, this.a, this.b, this.c, v1, v2, v3, target );
  4961. }
  4962. containsPoint( point ) {
  4963. return Triangle.containsPoint( point, this.a, this.b, this.c );
  4964. }
  4965. isFrontFacing( direction ) {
  4966. return Triangle.isFrontFacing( this.a, this.b, this.c, direction );
  4967. }
  4968. intersectsBox( box ) {
  4969. return box.intersectsTriangle( this );
  4970. }
  4971. closestPointToPoint( p, target ) {
  4972. const a = this.a, b = this.b, c = this.c;
  4973. let v, w;
  4974. // algorithm thanks to Real-Time Collision Detection by Christer Ericson,
  4975. // published by Morgan Kaufmann Publishers, (c) 2005 Elsevier Inc.,
  4976. // under the accompanying license; see chapter 5.1.5 for detailed explanation.
  4977. // basically, we're distinguishing which of the voronoi regions of the triangle
  4978. // the point lies in with the minimum amount of redundant computation.
  4979. _vab.subVectors( b, a );
  4980. _vac.subVectors( c, a );
  4981. _vap.subVectors( p, a );
  4982. const d1 = _vab.dot( _vap );
  4983. const d2 = _vac.dot( _vap );
  4984. if ( d1 <= 0 && d2 <= 0 ) {
  4985. // vertex region of A; barycentric coords (1, 0, 0)
  4986. return target.copy( a );
  4987. }
  4988. _vbp.subVectors( p, b );
  4989. const d3 = _vab.dot( _vbp );
  4990. const d4 = _vac.dot( _vbp );
  4991. if ( d3 >= 0 && d4 <= d3 ) {
  4992. // vertex region of B; barycentric coords (0, 1, 0)
  4993. return target.copy( b );
  4994. }
  4995. const vc = d1 * d4 - d3 * d2;
  4996. if ( vc <= 0 && d1 >= 0 && d3 <= 0 ) {
  4997. v = d1 / ( d1 - d3 );
  4998. // edge region of AB; barycentric coords (1-v, v, 0)
  4999. return target.copy( a ).addScaledVector( _vab, v );
  5000. }
  5001. _vcp.subVectors( p, c );
  5002. const d5 = _vab.dot( _vcp );
  5003. const d6 = _vac.dot( _vcp );
  5004. if ( d6 >= 0 && d5 <= d6 ) {
  5005. // vertex region of C; barycentric coords (0, 0, 1)
  5006. return target.copy( c );
  5007. }
  5008. const vb = d5 * d2 - d1 * d6;
  5009. if ( vb <= 0 && d2 >= 0 && d6 <= 0 ) {
  5010. w = d2 / ( d2 - d6 );
  5011. // edge region of AC; barycentric coords (1-w, 0, w)
  5012. return target.copy( a ).addScaledVector( _vac, w );
  5013. }
  5014. const va = d3 * d6 - d5 * d4;
  5015. if ( va <= 0 && ( d4 - d3 ) >= 0 && ( d5 - d6 ) >= 0 ) {
  5016. _vbc.subVectors( c, b );
  5017. w = ( d4 - d3 ) / ( ( d4 - d3 ) + ( d5 - d6 ) );
  5018. // edge region of BC; barycentric coords (0, 1-w, w)
  5019. return target.copy( b ).addScaledVector( _vbc, w ); // edge region of BC
  5020. }
  5021. // face region
  5022. const denom = 1 / ( va + vb + vc );
  5023. // u = va * denom
  5024. v = vb * denom;
  5025. w = vc * denom;
  5026. return target.copy( a ).addScaledVector( _vab, v ).addScaledVector( _vac, w );
  5027. }
  5028. equals( triangle ) {
  5029. return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c );
  5030. }
  5031. }
  5032. const _colorKeywords = { 'aliceblue': 0xF0F8FF, 'antiquewhite': 0xFAEBD7, 'aqua': 0x00FFFF, 'aquamarine': 0x7FFFD4, 'azure': 0xF0FFFF,
  5033. 'beige': 0xF5F5DC, 'bisque': 0xFFE4C4, 'black': 0x000000, 'blanchedalmond': 0xFFEBCD, 'blue': 0x0000FF, 'blueviolet': 0x8A2BE2,
  5034. 'brown': 0xA52A2A, 'burlywood': 0xDEB887, 'cadetblue': 0x5F9EA0, 'chartreuse': 0x7FFF00, 'chocolate': 0xD2691E, 'coral': 0xFF7F50,
  5035. 'cornflowerblue': 0x6495ED, 'cornsilk': 0xFFF8DC, 'crimson': 0xDC143C, 'cyan': 0x00FFFF, 'darkblue': 0x00008B, 'darkcyan': 0x008B8B,
  5036. 'darkgoldenrod': 0xB8860B, 'darkgray': 0xA9A9A9, 'darkgreen': 0x006400, 'darkgrey': 0xA9A9A9, 'darkkhaki': 0xBDB76B, 'darkmagenta': 0x8B008B,
  5037. 'darkolivegreen': 0x556B2F, 'darkorange': 0xFF8C00, 'darkorchid': 0x9932CC, 'darkred': 0x8B0000, 'darksalmon': 0xE9967A, 'darkseagreen': 0x8FBC8F,
  5038. 'darkslateblue': 0x483D8B, 'darkslategray': 0x2F4F4F, 'darkslategrey': 0x2F4F4F, 'darkturquoise': 0x00CED1, 'darkviolet': 0x9400D3,
  5039. 'deeppink': 0xFF1493, 'deepskyblue': 0x00BFFF, 'dimgray': 0x696969, 'dimgrey': 0x696969, 'dodgerblue': 0x1E90FF, 'firebrick': 0xB22222,
  5040. 'floralwhite': 0xFFFAF0, 'forestgreen': 0x228B22, 'fuchsia': 0xFF00FF, 'gainsboro': 0xDCDCDC, 'ghostwhite': 0xF8F8FF, 'gold': 0xFFD700,
  5041. 'goldenrod': 0xDAA520, 'gray': 0x808080, 'green': 0x008000, 'greenyellow': 0xADFF2F, 'grey': 0x808080, 'honeydew': 0xF0FFF0, 'hotpink': 0xFF69B4,
  5042. 'indianred': 0xCD5C5C, 'indigo': 0x4B0082, 'ivory': 0xFFFFF0, 'khaki': 0xF0E68C, 'lavender': 0xE6E6FA, 'lavenderblush': 0xFFF0F5, 'lawngreen': 0x7CFC00,
  5043. 'lemonchiffon': 0xFFFACD, 'lightblue': 0xADD8E6, 'lightcoral': 0xF08080, 'lightcyan': 0xE0FFFF, 'lightgoldenrodyellow': 0xFAFAD2, 'lightgray': 0xD3D3D3,
  5044. 'lightgreen': 0x90EE90, 'lightgrey': 0xD3D3D3, 'lightpink': 0xFFB6C1, 'lightsalmon': 0xFFA07A, 'lightseagreen': 0x20B2AA, 'lightskyblue': 0x87CEFA,
  5045. 'lightslategray': 0x778899, 'lightslategrey': 0x778899, 'lightsteelblue': 0xB0C4DE, 'lightyellow': 0xFFFFE0, 'lime': 0x00FF00, 'limegreen': 0x32CD32,
  5046. 'linen': 0xFAF0E6, 'magenta': 0xFF00FF, 'maroon': 0x800000, 'mediumaquamarine': 0x66CDAA, 'mediumblue': 0x0000CD, 'mediumorchid': 0xBA55D3,
  5047. 'mediumpurple': 0x9370DB, 'mediumseagreen': 0x3CB371, 'mediumslateblue': 0x7B68EE, 'mediumspringgreen': 0x00FA9A, 'mediumturquoise': 0x48D1CC,
  5048. 'mediumvioletred': 0xC71585, 'midnightblue': 0x191970, 'mintcream': 0xF5FFFA, 'mistyrose': 0xFFE4E1, 'moccasin': 0xFFE4B5, 'navajowhite': 0xFFDEAD,
  5049. 'navy': 0x000080, 'oldlace': 0xFDF5E6, 'olive': 0x808000, 'olivedrab': 0x6B8E23, 'orange': 0xFFA500, 'orangered': 0xFF4500, 'orchid': 0xDA70D6,
  5050. 'palegoldenrod': 0xEEE8AA, 'palegreen': 0x98FB98, 'paleturquoise': 0xAFEEEE, 'palevioletred': 0xDB7093, 'papayawhip': 0xFFEFD5, 'peachpuff': 0xFFDAB9,
  5051. 'peru': 0xCD853F, 'pink': 0xFFC0CB, 'plum': 0xDDA0DD, 'powderblue': 0xB0E0E6, 'purple': 0x800080, 'rebeccapurple': 0x663399, 'red': 0xFF0000, 'rosybrown': 0xBC8F8F,
  5052. 'royalblue': 0x4169E1, 'saddlebrown': 0x8B4513, 'salmon': 0xFA8072, 'sandybrown': 0xF4A460, 'seagreen': 0x2E8B57, 'seashell': 0xFFF5EE,
  5053. 'sienna': 0xA0522D, 'silver': 0xC0C0C0, 'skyblue': 0x87CEEB, 'slateblue': 0x6A5ACD, 'slategray': 0x708090, 'slategrey': 0x708090, 'snow': 0xFFFAFA,
  5054. 'springgreen': 0x00FF7F, 'steelblue': 0x4682B4, 'tan': 0xD2B48C, 'teal': 0x008080, 'thistle': 0xD8BFD8, 'tomato': 0xFF6347, 'turquoise': 0x40E0D0,
  5055. 'violet': 0xEE82EE, 'wheat': 0xF5DEB3, 'white': 0xFFFFFF, 'whitesmoke': 0xF5F5F5, 'yellow': 0xFFFF00, 'yellowgreen': 0x9ACD32 };
  5056. const _hslA = { h: 0, s: 0, l: 0 };
  5057. const _hslB = { h: 0, s: 0, l: 0 };
  5058. function hue2rgb( p, q, t ) {
  5059. if ( t < 0 ) t += 1;
  5060. if ( t > 1 ) t -= 1;
  5061. if ( t < 1 / 6 ) return p + ( q - p ) * 6 * t;
  5062. if ( t < 1 / 2 ) return q;
  5063. if ( t < 2 / 3 ) return p + ( q - p ) * 6 * ( 2 / 3 - t );
  5064. return p;
  5065. }
  5066. class Color {
  5067. constructor( r, g, b ) {
  5068. this.isColor = true;
  5069. this.r = 1;
  5070. this.g = 1;
  5071. this.b = 1;
  5072. return this.set( r, g, b );
  5073. }
  5074. set( r, g, b ) {
  5075. if ( g === undefined && b === undefined ) {
  5076. // r is THREE.Color, hex or string
  5077. const value = r;
  5078. if ( value && value.isColor ) {
  5079. this.copy( value );
  5080. } else if ( typeof value === 'number' ) {
  5081. this.setHex( value );
  5082. } else if ( typeof value === 'string' ) {
  5083. this.setStyle( value );
  5084. }
  5085. } else {
  5086. this.setRGB( r, g, b );
  5087. }
  5088. return this;
  5089. }
  5090. setScalar( scalar ) {
  5091. this.r = scalar;
  5092. this.g = scalar;
  5093. this.b = scalar;
  5094. return this;
  5095. }
  5096. setHex( hex, colorSpace = SRGBColorSpace ) {
  5097. hex = Math.floor( hex );
  5098. this.r = ( hex >> 16 & 255 ) / 255;
  5099. this.g = ( hex >> 8 & 255 ) / 255;
  5100. this.b = ( hex & 255 ) / 255;
  5101. ColorManagement.toWorkingColorSpace( this, colorSpace );
  5102. return this;
  5103. }
  5104. setRGB( r, g, b, colorSpace = ColorManagement.workingColorSpace ) {
  5105. this.r = r;
  5106. this.g = g;
  5107. this.b = b;
  5108. ColorManagement.toWorkingColorSpace( this, colorSpace );
  5109. return this;
  5110. }
  5111. setHSL( h, s, l, colorSpace = ColorManagement.workingColorSpace ) {
  5112. // h,s,l ranges are in 0.0 - 1.0
  5113. h = euclideanModulo( h, 1 );
  5114. s = clamp( s, 0, 1 );
  5115. l = clamp( l, 0, 1 );
  5116. if ( s === 0 ) {
  5117. this.r = this.g = this.b = l;
  5118. } else {
  5119. const p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s );
  5120. const q = ( 2 * l ) - p;
  5121. this.r = hue2rgb( q, p, h + 1 / 3 );
  5122. this.g = hue2rgb( q, p, h );
  5123. this.b = hue2rgb( q, p, h - 1 / 3 );
  5124. }
  5125. ColorManagement.toWorkingColorSpace( this, colorSpace );
  5126. return this;
  5127. }
  5128. setStyle( style, colorSpace = SRGBColorSpace ) {
  5129. function handleAlpha( string ) {
  5130. if ( string === undefined ) return;
  5131. if ( parseFloat( string ) < 1 ) {
  5132. console.warn( 'THREE.Color: Alpha component of ' + style + ' will be ignored.' );
  5133. }
  5134. }
  5135. let m;
  5136. if ( m = /^(\w+)\(([^\)]*)\)/.exec( style ) ) {
  5137. // rgb / hsl
  5138. let color;
  5139. const name = m[ 1 ];
  5140. const components = m[ 2 ];
  5141. switch ( name ) {
  5142. case 'rgb':
  5143. case 'rgba':
  5144. if ( color = /^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  5145. // rgb(255,0,0) rgba(255,0,0,0.5)
  5146. handleAlpha( color[ 4 ] );
  5147. return this.setRGB(
  5148. Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255,
  5149. Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255,
  5150. Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255,
  5151. colorSpace
  5152. );
  5153. }
  5154. if ( color = /^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  5155. // rgb(100%,0%,0%) rgba(100%,0%,0%,0.5)
  5156. handleAlpha( color[ 4 ] );
  5157. return this.setRGB(
  5158. Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100,
  5159. Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100,
  5160. Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100,
  5161. colorSpace
  5162. );
  5163. }
  5164. break;
  5165. case 'hsl':
  5166. case 'hsla':
  5167. if ( color = /^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  5168. // hsl(120,50%,50%) hsla(120,50%,50%,0.5)
  5169. handleAlpha( color[ 4 ] );
  5170. return this.setHSL(
  5171. parseFloat( color[ 1 ] ) / 360,
  5172. parseFloat( color[ 2 ] ) / 100,
  5173. parseFloat( color[ 3 ] ) / 100,
  5174. colorSpace
  5175. );
  5176. }
  5177. break;
  5178. default:
  5179. console.warn( 'THREE.Color: Unknown color model ' + style );
  5180. }
  5181. } else if ( m = /^\#([A-Fa-f\d]+)$/.exec( style ) ) {
  5182. // hex color
  5183. const hex = m[ 1 ];
  5184. const size = hex.length;
  5185. if ( size === 3 ) {
  5186. // #ff0
  5187. return this.setRGB(
  5188. parseInt( hex.charAt( 0 ), 16 ) / 15,
  5189. parseInt( hex.charAt( 1 ), 16 ) / 15,
  5190. parseInt( hex.charAt( 2 ), 16 ) / 15,
  5191. colorSpace
  5192. );
  5193. } else if ( size === 6 ) {
  5194. // #ff0000
  5195. return this.setHex( parseInt( hex, 16 ), colorSpace );
  5196. } else {
  5197. console.warn( 'THREE.Color: Invalid hex color ' + style );
  5198. }
  5199. } else if ( style && style.length > 0 ) {
  5200. return this.setColorName( style, colorSpace );
  5201. }
  5202. return this;
  5203. }
  5204. setColorName( style, colorSpace = SRGBColorSpace ) {
  5205. // color keywords
  5206. const hex = _colorKeywords[ style.toLowerCase() ];
  5207. if ( hex !== undefined ) {
  5208. // red
  5209. this.setHex( hex, colorSpace );
  5210. } else {
  5211. // unknown color
  5212. console.warn( 'THREE.Color: Unknown color ' + style );
  5213. }
  5214. return this;
  5215. }
  5216. clone() {
  5217. return new this.constructor( this.r, this.g, this.b );
  5218. }
  5219. copy( color ) {
  5220. this.r = color.r;
  5221. this.g = color.g;
  5222. this.b = color.b;
  5223. return this;
  5224. }
  5225. copySRGBToLinear( color ) {
  5226. this.r = SRGBToLinear( color.r );
  5227. this.g = SRGBToLinear( color.g );
  5228. this.b = SRGBToLinear( color.b );
  5229. return this;
  5230. }
  5231. copyLinearToSRGB( color ) {
  5232. this.r = LinearToSRGB( color.r );
  5233. this.g = LinearToSRGB( color.g );
  5234. this.b = LinearToSRGB( color.b );
  5235. return this;
  5236. }
  5237. convertSRGBToLinear() {
  5238. this.copySRGBToLinear( this );
  5239. return this;
  5240. }
  5241. convertLinearToSRGB() {
  5242. this.copyLinearToSRGB( this );
  5243. return this;
  5244. }
  5245. getHex( colorSpace = SRGBColorSpace ) {
  5246. ColorManagement.fromWorkingColorSpace( _color.copy( this ), colorSpace );
  5247. return Math.round( clamp( _color.r * 255, 0, 255 ) ) * 65536 + Math.round( clamp( _color.g * 255, 0, 255 ) ) * 256 + Math.round( clamp( _color.b * 255, 0, 255 ) );
  5248. }
  5249. getHexString( colorSpace = SRGBColorSpace ) {
  5250. return ( '000000' + this.getHex( colorSpace ).toString( 16 ) ).slice( - 6 );
  5251. }
  5252. getHSL( target, colorSpace = ColorManagement.workingColorSpace ) {
  5253. // h,s,l ranges are in 0.0 - 1.0
  5254. ColorManagement.fromWorkingColorSpace( _color.copy( this ), colorSpace );
  5255. const r = _color.r, g = _color.g, b = _color.b;
  5256. const max = Math.max( r, g, b );
  5257. const min = Math.min( r, g, b );
  5258. let hue, saturation;
  5259. const lightness = ( min + max ) / 2.0;
  5260. if ( min === max ) {
  5261. hue = 0;
  5262. saturation = 0;
  5263. } else {
  5264. const delta = max - min;
  5265. saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min );
  5266. switch ( max ) {
  5267. case r: hue = ( g - b ) / delta + ( g < b ? 6 : 0 ); break;
  5268. case g: hue = ( b - r ) / delta + 2; break;
  5269. case b: hue = ( r - g ) / delta + 4; break;
  5270. }
  5271. hue /= 6;
  5272. }
  5273. target.h = hue;
  5274. target.s = saturation;
  5275. target.l = lightness;
  5276. return target;
  5277. }
  5278. getRGB( target, colorSpace = ColorManagement.workingColorSpace ) {
  5279. ColorManagement.fromWorkingColorSpace( _color.copy( this ), colorSpace );
  5280. target.r = _color.r;
  5281. target.g = _color.g;
  5282. target.b = _color.b;
  5283. return target;
  5284. }
  5285. getStyle( colorSpace = SRGBColorSpace ) {
  5286. ColorManagement.fromWorkingColorSpace( _color.copy( this ), colorSpace );
  5287. const r = _color.r, g = _color.g, b = _color.b;
  5288. if ( colorSpace !== SRGBColorSpace ) {
  5289. // Requires CSS Color Module Level 4 (https://www.w3.org/TR/css-color-4/).
  5290. return `color(${ colorSpace } ${ r.toFixed( 3 ) } ${ g.toFixed( 3 ) } ${ b.toFixed( 3 ) })`;
  5291. }
  5292. return `rgb(${ Math.round( r * 255 ) },${ Math.round( g * 255 ) },${ Math.round( b * 255 ) })`;
  5293. }
  5294. offsetHSL( h, s, l ) {
  5295. this.getHSL( _hslA );
  5296. return this.setHSL( _hslA.h + h, _hslA.s + s, _hslA.l + l );
  5297. }
  5298. add( color ) {
  5299. this.r += color.r;
  5300. this.g += color.g;
  5301. this.b += color.b;
  5302. return this;
  5303. }
  5304. addColors( color1, color2 ) {
  5305. this.r = color1.r + color2.r;
  5306. this.g = color1.g + color2.g;
  5307. this.b = color1.b + color2.b;
  5308. return this;
  5309. }
  5310. addScalar( s ) {
  5311. this.r += s;
  5312. this.g += s;
  5313. this.b += s;
  5314. return this;
  5315. }
  5316. sub( color ) {
  5317. this.r = Math.max( 0, this.r - color.r );
  5318. this.g = Math.max( 0, this.g - color.g );
  5319. this.b = Math.max( 0, this.b - color.b );
  5320. return this;
  5321. }
  5322. multiply( color ) {
  5323. this.r *= color.r;
  5324. this.g *= color.g;
  5325. this.b *= color.b;
  5326. return this;
  5327. }
  5328. multiplyScalar( s ) {
  5329. this.r *= s;
  5330. this.g *= s;
  5331. this.b *= s;
  5332. return this;
  5333. }
  5334. lerp( color, alpha ) {
  5335. this.r += ( color.r - this.r ) * alpha;
  5336. this.g += ( color.g - this.g ) * alpha;
  5337. this.b += ( color.b - this.b ) * alpha;
  5338. return this;
  5339. }
  5340. lerpColors( color1, color2, alpha ) {
  5341. this.r = color1.r + ( color2.r - color1.r ) * alpha;
  5342. this.g = color1.g + ( color2.g - color1.g ) * alpha;
  5343. this.b = color1.b + ( color2.b - color1.b ) * alpha;
  5344. return this;
  5345. }
  5346. lerpHSL( color, alpha ) {
  5347. this.getHSL( _hslA );
  5348. color.getHSL( _hslB );
  5349. const h = lerp( _hslA.h, _hslB.h, alpha );
  5350. const s = lerp( _hslA.s, _hslB.s, alpha );
  5351. const l = lerp( _hslA.l, _hslB.l, alpha );
  5352. this.setHSL( h, s, l );
  5353. return this;
  5354. }
  5355. setFromVector3( v ) {
  5356. this.r = v.x;
  5357. this.g = v.y;
  5358. this.b = v.z;
  5359. return this;
  5360. }
  5361. applyMatrix3( m ) {
  5362. const r = this.r, g = this.g, b = this.b;
  5363. const e = m.elements;
  5364. this.r = e[ 0 ] * r + e[ 3 ] * g + e[ 6 ] * b;
  5365. this.g = e[ 1 ] * r + e[ 4 ] * g + e[ 7 ] * b;
  5366. this.b = e[ 2 ] * r + e[ 5 ] * g + e[ 8 ] * b;
  5367. return this;
  5368. }
  5369. equals( c ) {
  5370. return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b );
  5371. }
  5372. fromArray( array, offset = 0 ) {
  5373. this.r = array[ offset ];
  5374. this.g = array[ offset + 1 ];
  5375. this.b = array[ offset + 2 ];
  5376. return this;
  5377. }
  5378. toArray( array = [], offset = 0 ) {
  5379. array[ offset ] = this.r;
  5380. array[ offset + 1 ] = this.g;
  5381. array[ offset + 2 ] = this.b;
  5382. return array;
  5383. }
  5384. fromBufferAttribute( attribute, index ) {
  5385. this.r = attribute.getX( index );
  5386. this.g = attribute.getY( index );
  5387. this.b = attribute.getZ( index );
  5388. return this;
  5389. }
  5390. toJSON() {
  5391. return this.getHex();
  5392. }
  5393. *[ Symbol.iterator ]() {
  5394. yield this.r;
  5395. yield this.g;
  5396. yield this.b;
  5397. }
  5398. }
  5399. const _color = /*@__PURE__*/ new Color();
  5400. Color.NAMES = _colorKeywords;
  5401. let _materialId = 0;
  5402. class Material extends EventDispatcher {
  5403. constructor() {
  5404. super();
  5405. this.isMaterial = true;
  5406. Object.defineProperty( this, 'id', { value: _materialId ++ } );
  5407. this.uuid = generateUUID();
  5408. this.name = '';
  5409. this.type = 'Material';
  5410. this.blending = NormalBlending;
  5411. this.side = FrontSide;
  5412. this.vertexColors = false;
  5413. this.opacity = 1;
  5414. this.transparent = false;
  5415. this.alphaHash = false;
  5416. this.blendSrc = SrcAlphaFactor;
  5417. this.blendDst = OneMinusSrcAlphaFactor;
  5418. this.blendEquation = AddEquation;
  5419. this.blendSrcAlpha = null;
  5420. this.blendDstAlpha = null;
  5421. this.blendEquationAlpha = null;
  5422. this.blendColor = new Color( 0, 0, 0 );
  5423. this.blendAlpha = 0;
  5424. this.depthFunc = LessEqualDepth;
  5425. this.depthTest = true;
  5426. this.depthWrite = true;
  5427. this.stencilWriteMask = 0xff;
  5428. this.stencilFunc = AlwaysStencilFunc;
  5429. this.stencilRef = 0;
  5430. this.stencilFuncMask = 0xff;
  5431. this.stencilFail = KeepStencilOp;
  5432. this.stencilZFail = KeepStencilOp;
  5433. this.stencilZPass = KeepStencilOp;
  5434. this.stencilWrite = false;
  5435. this.clippingPlanes = null;
  5436. this.clipIntersection = false;
  5437. this.clipShadows = false;
  5438. this.shadowSide = null;
  5439. this.colorWrite = true;
  5440. this.precision = null; // override the renderer's default precision for this material
  5441. this.polygonOffset = false;
  5442. this.polygonOffsetFactor = 0;
  5443. this.polygonOffsetUnits = 0;
  5444. this.dithering = false;
  5445. this.alphaToCoverage = false;
  5446. this.premultipliedAlpha = false;
  5447. this.forceSinglePass = false;
  5448. this.visible = true;
  5449. this.toneMapped = true;
  5450. this.userData = {};
  5451. this.version = 0;
  5452. this._alphaTest = 0;
  5453. }
  5454. get alphaTest() {
  5455. return this._alphaTest;
  5456. }
  5457. set alphaTest( value ) {
  5458. if ( this._alphaTest > 0 !== value > 0 ) {
  5459. this.version ++;
  5460. }
  5461. this._alphaTest = value;
  5462. }
  5463. onBuild( /* shaderobject, renderer */ ) {}
  5464. onBeforeRender( /* renderer, scene, camera, geometry, object, group */ ) {}
  5465. onBeforeCompile( /* shaderobject, renderer */ ) {}
  5466. customProgramCacheKey() {
  5467. return this.onBeforeCompile.toString();
  5468. }
  5469. setValues( values ) {
  5470. if ( values === undefined ) return;
  5471. for ( const key in values ) {
  5472. const newValue = values[ key ];
  5473. if ( newValue === undefined ) {
  5474. console.warn( `THREE.Material: parameter '${ key }' has value of undefined.` );
  5475. continue;
  5476. }
  5477. const currentValue = this[ key ];
  5478. if ( currentValue === undefined ) {
  5479. console.warn( `THREE.Material: '${ key }' is not a property of THREE.${ this.type }.` );
  5480. continue;
  5481. }
  5482. if ( currentValue && currentValue.isColor ) {
  5483. currentValue.set( newValue );
  5484. } else if ( ( currentValue && currentValue.isVector3 ) && ( newValue && newValue.isVector3 ) ) {
  5485. currentValue.copy( newValue );
  5486. } else {
  5487. this[ key ] = newValue;
  5488. }
  5489. }
  5490. }
  5491. toJSON( meta ) {
  5492. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  5493. if ( isRootObject ) {
  5494. meta = {
  5495. textures: {},
  5496. images: {}
  5497. };
  5498. }
  5499. const data = {
  5500. metadata: {
  5501. version: 4.6,
  5502. type: 'Material',
  5503. generator: 'Material.toJSON'
  5504. }
  5505. };
  5506. // standard Material serialization
  5507. data.uuid = this.uuid;
  5508. data.type = this.type;
  5509. if ( this.name !== '' ) data.name = this.name;
  5510. if ( this.color && this.color.isColor ) data.color = this.color.getHex();
  5511. if ( this.roughness !== undefined ) data.roughness = this.roughness;
  5512. if ( this.metalness !== undefined ) data.metalness = this.metalness;
  5513. if ( this.sheen !== undefined ) data.sheen = this.sheen;
  5514. if ( this.sheenColor && this.sheenColor.isColor ) data.sheenColor = this.sheenColor.getHex();
  5515. if ( this.sheenRoughness !== undefined ) data.sheenRoughness = this.sheenRoughness;
  5516. if ( this.emissive && this.emissive.isColor ) data.emissive = this.emissive.getHex();
  5517. if ( this.emissiveIntensity && this.emissiveIntensity !== 1 ) data.emissiveIntensity = this.emissiveIntensity;
  5518. if ( this.specular && this.specular.isColor ) data.specular = this.specular.getHex();
  5519. if ( this.specularIntensity !== undefined ) data.specularIntensity = this.specularIntensity;
  5520. if ( this.specularColor && this.specularColor.isColor ) data.specularColor = this.specularColor.getHex();
  5521. if ( this.shininess !== undefined ) data.shininess = this.shininess;
  5522. if ( this.clearcoat !== undefined ) data.clearcoat = this.clearcoat;
  5523. if ( this.clearcoatRoughness !== undefined ) data.clearcoatRoughness = this.clearcoatRoughness;
  5524. if ( this.clearcoatMap && this.clearcoatMap.isTexture ) {
  5525. data.clearcoatMap = this.clearcoatMap.toJSON( meta ).uuid;
  5526. }
  5527. if ( this.clearcoatRoughnessMap && this.clearcoatRoughnessMap.isTexture ) {
  5528. data.clearcoatRoughnessMap = this.clearcoatRoughnessMap.toJSON( meta ).uuid;
  5529. }
  5530. if ( this.clearcoatNormalMap && this.clearcoatNormalMap.isTexture ) {
  5531. data.clearcoatNormalMap = this.clearcoatNormalMap.toJSON( meta ).uuid;
  5532. data.clearcoatNormalScale = this.clearcoatNormalScale.toArray();
  5533. }
  5534. if ( this.iridescence !== undefined ) data.iridescence = this.iridescence;
  5535. if ( this.iridescenceIOR !== undefined ) data.iridescenceIOR = this.iridescenceIOR;
  5536. if ( this.iridescenceThicknessRange !== undefined ) data.iridescenceThicknessRange = this.iridescenceThicknessRange;
  5537. if ( this.iridescenceMap && this.iridescenceMap.isTexture ) {
  5538. data.iridescenceMap = this.iridescenceMap.toJSON( meta ).uuid;
  5539. }
  5540. if ( this.iridescenceThicknessMap && this.iridescenceThicknessMap.isTexture ) {
  5541. data.iridescenceThicknessMap = this.iridescenceThicknessMap.toJSON( meta ).uuid;
  5542. }
  5543. if ( this.anisotropy !== undefined ) data.anisotropy = this.anisotropy;
  5544. if ( this.anisotropyRotation !== undefined ) data.anisotropyRotation = this.anisotropyRotation;
  5545. if ( this.anisotropyMap && this.anisotropyMap.isTexture ) {
  5546. data.anisotropyMap = this.anisotropyMap.toJSON( meta ).uuid;
  5547. }
  5548. if ( this.map && this.map.isTexture ) data.map = this.map.toJSON( meta ).uuid;
  5549. if ( this.matcap && this.matcap.isTexture ) data.matcap = this.matcap.toJSON( meta ).uuid;
  5550. if ( this.alphaMap && this.alphaMap.isTexture ) data.alphaMap = this.alphaMap.toJSON( meta ).uuid;
  5551. if ( this.lightMap && this.lightMap.isTexture ) {
  5552. data.lightMap = this.lightMap.toJSON( meta ).uuid;
  5553. data.lightMapIntensity = this.lightMapIntensity;
  5554. }
  5555. if ( this.aoMap && this.aoMap.isTexture ) {
  5556. data.aoMap = this.aoMap.toJSON( meta ).uuid;
  5557. data.aoMapIntensity = this.aoMapIntensity;
  5558. }
  5559. if ( this.bumpMap && this.bumpMap.isTexture ) {
  5560. data.bumpMap = this.bumpMap.toJSON( meta ).uuid;
  5561. data.bumpScale = this.bumpScale;
  5562. }
  5563. if ( this.normalMap && this.normalMap.isTexture ) {
  5564. data.normalMap = this.normalMap.toJSON( meta ).uuid;
  5565. data.normalMapType = this.normalMapType;
  5566. data.normalScale = this.normalScale.toArray();
  5567. }
  5568. if ( this.displacementMap && this.displacementMap.isTexture ) {
  5569. data.displacementMap = this.displacementMap.toJSON( meta ).uuid;
  5570. data.displacementScale = this.displacementScale;
  5571. data.displacementBias = this.displacementBias;
  5572. }
  5573. if ( this.roughnessMap && this.roughnessMap.isTexture ) data.roughnessMap = this.roughnessMap.toJSON( meta ).uuid;
  5574. if ( this.metalnessMap && this.metalnessMap.isTexture ) data.metalnessMap = this.metalnessMap.toJSON( meta ).uuid;
  5575. if ( this.emissiveMap && this.emissiveMap.isTexture ) data.emissiveMap = this.emissiveMap.toJSON( meta ).uuid;
  5576. if ( this.specularMap && this.specularMap.isTexture ) data.specularMap = this.specularMap.toJSON( meta ).uuid;
  5577. if ( this.specularIntensityMap && this.specularIntensityMap.isTexture ) data.specularIntensityMap = this.specularIntensityMap.toJSON( meta ).uuid;
  5578. if ( this.specularColorMap && this.specularColorMap.isTexture ) data.specularColorMap = this.specularColorMap.toJSON( meta ).uuid;
  5579. if ( this.envMap && this.envMap.isTexture ) {
  5580. data.envMap = this.envMap.toJSON( meta ).uuid;
  5581. if ( this.combine !== undefined ) data.combine = this.combine;
  5582. }
  5583. if ( this.envMapIntensity !== undefined ) data.envMapIntensity = this.envMapIntensity;
  5584. if ( this.reflectivity !== undefined ) data.reflectivity = this.reflectivity;
  5585. if ( this.refractionRatio !== undefined ) data.refractionRatio = this.refractionRatio;
  5586. if ( this.gradientMap && this.gradientMap.isTexture ) {
  5587. data.gradientMap = this.gradientMap.toJSON( meta ).uuid;
  5588. }
  5589. if ( this.transmission !== undefined ) data.transmission = this.transmission;
  5590. if ( this.transmissionMap && this.transmissionMap.isTexture ) data.transmissionMap = this.transmissionMap.toJSON( meta ).uuid;
  5591. if ( this.thickness !== undefined ) data.thickness = this.thickness;
  5592. if ( this.thicknessMap && this.thicknessMap.isTexture ) data.thicknessMap = this.thicknessMap.toJSON( meta ).uuid;
  5593. if ( this.attenuationDistance !== undefined && this.attenuationDistance !== Infinity ) data.attenuationDistance = this.attenuationDistance;
  5594. if ( this.attenuationColor !== undefined ) data.attenuationColor = this.attenuationColor.getHex();
  5595. if ( this.size !== undefined ) data.size = this.size;
  5596. if ( this.shadowSide !== null ) data.shadowSide = this.shadowSide;
  5597. if ( this.sizeAttenuation !== undefined ) data.sizeAttenuation = this.sizeAttenuation;
  5598. if ( this.blending !== NormalBlending ) data.blending = this.blending;
  5599. if ( this.side !== FrontSide ) data.side = this.side;
  5600. if ( this.vertexColors === true ) data.vertexColors = true;
  5601. if ( this.opacity < 1 ) data.opacity = this.opacity;
  5602. if ( this.transparent === true ) data.transparent = true;
  5603. if ( this.blendSrc !== SrcAlphaFactor ) data.blendSrc = this.blendSrc;
  5604. if ( this.blendDst !== OneMinusSrcAlphaFactor ) data.blendDst = this.blendDst;
  5605. if ( this.blendEquation !== AddEquation ) data.blendEquation = this.blendEquation;
  5606. if ( this.blendSrcAlpha !== null ) data.blendSrcAlpha = this.blendSrcAlpha;
  5607. if ( this.blendDstAlpha !== null ) data.blendDstAlpha = this.blendDstAlpha;
  5608. if ( this.blendEquationAlpha !== null ) data.blendEquationAlpha = this.blendEquationAlpha;
  5609. if ( this.blendColor && this.blendColor.isColor ) data.blendColor = this.blendColor.getHex();
  5610. if ( this.blendAlpha !== 0 ) data.blendAlpha = this.blendAlpha;
  5611. if ( this.depthFunc !== LessEqualDepth ) data.depthFunc = this.depthFunc;
  5612. if ( this.depthTest === false ) data.depthTest = this.depthTest;
  5613. if ( this.depthWrite === false ) data.depthWrite = this.depthWrite;
  5614. if ( this.colorWrite === false ) data.colorWrite = this.colorWrite;
  5615. if ( this.stencilWriteMask !== 0xff ) data.stencilWriteMask = this.stencilWriteMask;
  5616. if ( this.stencilFunc !== AlwaysStencilFunc ) data.stencilFunc = this.stencilFunc;
  5617. if ( this.stencilRef !== 0 ) data.stencilRef = this.stencilRef;
  5618. if ( this.stencilFuncMask !== 0xff ) data.stencilFuncMask = this.stencilFuncMask;
  5619. if ( this.stencilFail !== KeepStencilOp ) data.stencilFail = this.stencilFail;
  5620. if ( this.stencilZFail !== KeepStencilOp ) data.stencilZFail = this.stencilZFail;
  5621. if ( this.stencilZPass !== KeepStencilOp ) data.stencilZPass = this.stencilZPass;
  5622. if ( this.stencilWrite === true ) data.stencilWrite = this.stencilWrite;
  5623. // rotation (SpriteMaterial)
  5624. if ( this.rotation !== undefined && this.rotation !== 0 ) data.rotation = this.rotation;
  5625. if ( this.polygonOffset === true ) data.polygonOffset = true;
  5626. if ( this.polygonOffsetFactor !== 0 ) data.polygonOffsetFactor = this.polygonOffsetFactor;
  5627. if ( this.polygonOffsetUnits !== 0 ) data.polygonOffsetUnits = this.polygonOffsetUnits;
  5628. if ( this.linewidth !== undefined && this.linewidth !== 1 ) data.linewidth = this.linewidth;
  5629. if ( this.dashSize !== undefined ) data.dashSize = this.dashSize;
  5630. if ( this.gapSize !== undefined ) data.gapSize = this.gapSize;
  5631. if ( this.scale !== undefined ) data.scale = this.scale;
  5632. if ( this.dithering === true ) data.dithering = true;
  5633. if ( this.alphaTest > 0 ) data.alphaTest = this.alphaTest;
  5634. if ( this.alphaHash === true ) data.alphaHash = true;
  5635. if ( this.alphaToCoverage === true ) data.alphaToCoverage = true;
  5636. if ( this.premultipliedAlpha === true ) data.premultipliedAlpha = true;
  5637. if ( this.forceSinglePass === true ) data.forceSinglePass = true;
  5638. if ( this.wireframe === true ) data.wireframe = true;
  5639. if ( this.wireframeLinewidth > 1 ) data.wireframeLinewidth = this.wireframeLinewidth;
  5640. if ( this.wireframeLinecap !== 'round' ) data.wireframeLinecap = this.wireframeLinecap;
  5641. if ( this.wireframeLinejoin !== 'round' ) data.wireframeLinejoin = this.wireframeLinejoin;
  5642. if ( this.flatShading === true ) data.flatShading = true;
  5643. if ( this.visible === false ) data.visible = false;
  5644. if ( this.toneMapped === false ) data.toneMapped = false;
  5645. if ( this.fog === false ) data.fog = false;
  5646. if ( Object.keys( this.userData ).length > 0 ) data.userData = this.userData;
  5647. // TODO: Copied from Object3D.toJSON
  5648. function extractFromCache( cache ) {
  5649. const values = [];
  5650. for ( const key in cache ) {
  5651. const data = cache[ key ];
  5652. delete data.metadata;
  5653. values.push( data );
  5654. }
  5655. return values;
  5656. }
  5657. if ( isRootObject ) {
  5658. const textures = extractFromCache( meta.textures );
  5659. const images = extractFromCache( meta.images );
  5660. if ( textures.length > 0 ) data.textures = textures;
  5661. if ( images.length > 0 ) data.images = images;
  5662. }
  5663. return data;
  5664. }
  5665. clone() {
  5666. return new this.constructor().copy( this );
  5667. }
  5668. copy( source ) {
  5669. this.name = source.name;
  5670. this.blending = source.blending;
  5671. this.side = source.side;
  5672. this.vertexColors = source.vertexColors;
  5673. this.opacity = source.opacity;
  5674. this.transparent = source.transparent;
  5675. this.blendSrc = source.blendSrc;
  5676. this.blendDst = source.blendDst;
  5677. this.blendEquation = source.blendEquation;
  5678. this.blendSrcAlpha = source.blendSrcAlpha;
  5679. this.blendDstAlpha = source.blendDstAlpha;
  5680. this.blendEquationAlpha = source.blendEquationAlpha;
  5681. this.blendColor.copy( source.blendColor );
  5682. this.blendAlpha = source.blendAlpha;
  5683. this.depthFunc = source.depthFunc;
  5684. this.depthTest = source.depthTest;
  5685. this.depthWrite = source.depthWrite;
  5686. this.stencilWriteMask = source.stencilWriteMask;
  5687. this.stencilFunc = source.stencilFunc;
  5688. this.stencilRef = source.stencilRef;
  5689. this.stencilFuncMask = source.stencilFuncMask;
  5690. this.stencilFail = source.stencilFail;
  5691. this.stencilZFail = source.stencilZFail;
  5692. this.stencilZPass = source.stencilZPass;
  5693. this.stencilWrite = source.stencilWrite;
  5694. const srcPlanes = source.clippingPlanes;
  5695. let dstPlanes = null;
  5696. if ( srcPlanes !== null ) {
  5697. const n = srcPlanes.length;
  5698. dstPlanes = new Array( n );
  5699. for ( let i = 0; i !== n; ++ i ) {
  5700. dstPlanes[ i ] = srcPlanes[ i ].clone();
  5701. }
  5702. }
  5703. this.clippingPlanes = dstPlanes;
  5704. this.clipIntersection = source.clipIntersection;
  5705. this.clipShadows = source.clipShadows;
  5706. this.shadowSide = source.shadowSide;
  5707. this.colorWrite = source.colorWrite;
  5708. this.precision = source.precision;
  5709. this.polygonOffset = source.polygonOffset;
  5710. this.polygonOffsetFactor = source.polygonOffsetFactor;
  5711. this.polygonOffsetUnits = source.polygonOffsetUnits;
  5712. this.dithering = source.dithering;
  5713. this.alphaTest = source.alphaTest;
  5714. this.alphaHash = source.alphaHash;
  5715. this.alphaToCoverage = source.alphaToCoverage;
  5716. this.premultipliedAlpha = source.premultipliedAlpha;
  5717. this.forceSinglePass = source.forceSinglePass;
  5718. this.visible = source.visible;
  5719. this.toneMapped = source.toneMapped;
  5720. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  5721. return this;
  5722. }
  5723. dispose() {
  5724. this.dispatchEvent( { type: 'dispose' } );
  5725. }
  5726. set needsUpdate( value ) {
  5727. if ( value === true ) this.version ++;
  5728. }
  5729. }
  5730. class MeshBasicMaterial extends Material {
  5731. constructor( parameters ) {
  5732. super();
  5733. this.isMeshBasicMaterial = true;
  5734. this.type = 'MeshBasicMaterial';
  5735. this.color = new Color( 0xffffff ); // emissive
  5736. this.map = null;
  5737. this.lightMap = null;
  5738. this.lightMapIntensity = 1.0;
  5739. this.aoMap = null;
  5740. this.aoMapIntensity = 1.0;
  5741. this.specularMap = null;
  5742. this.alphaMap = null;
  5743. this.envMap = null;
  5744. this.combine = MultiplyOperation;
  5745. this.reflectivity = 1;
  5746. this.refractionRatio = 0.98;
  5747. this.wireframe = false;
  5748. this.wireframeLinewidth = 1;
  5749. this.wireframeLinecap = 'round';
  5750. this.wireframeLinejoin = 'round';
  5751. this.fog = true;
  5752. this.setValues( parameters );
  5753. }
  5754. copy( source ) {
  5755. super.copy( source );
  5756. this.color.copy( source.color );
  5757. this.map = source.map;
  5758. this.lightMap = source.lightMap;
  5759. this.lightMapIntensity = source.lightMapIntensity;
  5760. this.aoMap = source.aoMap;
  5761. this.aoMapIntensity = source.aoMapIntensity;
  5762. this.specularMap = source.specularMap;
  5763. this.alphaMap = source.alphaMap;
  5764. this.envMap = source.envMap;
  5765. this.combine = source.combine;
  5766. this.reflectivity = source.reflectivity;
  5767. this.refractionRatio = source.refractionRatio;
  5768. this.wireframe = source.wireframe;
  5769. this.wireframeLinewidth = source.wireframeLinewidth;
  5770. this.wireframeLinecap = source.wireframeLinecap;
  5771. this.wireframeLinejoin = source.wireframeLinejoin;
  5772. this.fog = source.fog;
  5773. return this;
  5774. }
  5775. }
  5776. // Fast Half Float Conversions, http://www.fox-toolkit.org/ftp/fasthalffloatconversion.pdf
  5777. const _tables = /*@__PURE__*/ _generateTables();
  5778. function _generateTables() {
  5779. // float32 to float16 helpers
  5780. const buffer = new ArrayBuffer( 4 );
  5781. const floatView = new Float32Array( buffer );
  5782. const uint32View = new Uint32Array( buffer );
  5783. const baseTable = new Uint32Array( 512 );
  5784. const shiftTable = new Uint32Array( 512 );
  5785. for ( let i = 0; i < 256; ++ i ) {
  5786. const e = i - 127;
  5787. // very small number (0, -0)
  5788. if ( e < - 27 ) {
  5789. baseTable[ i ] = 0x0000;
  5790. baseTable[ i | 0x100 ] = 0x8000;
  5791. shiftTable[ i ] = 24;
  5792. shiftTable[ i | 0x100 ] = 24;
  5793. // small number (denorm)
  5794. } else if ( e < - 14 ) {
  5795. baseTable[ i ] = 0x0400 >> ( - e - 14 );
  5796. baseTable[ i | 0x100 ] = ( 0x0400 >> ( - e - 14 ) ) | 0x8000;
  5797. shiftTable[ i ] = - e - 1;
  5798. shiftTable[ i | 0x100 ] = - e - 1;
  5799. // normal number
  5800. } else if ( e <= 15 ) {
  5801. baseTable[ i ] = ( e + 15 ) << 10;
  5802. baseTable[ i | 0x100 ] = ( ( e + 15 ) << 10 ) | 0x8000;
  5803. shiftTable[ i ] = 13;
  5804. shiftTable[ i | 0x100 ] = 13;
  5805. // large number (Infinity, -Infinity)
  5806. } else if ( e < 128 ) {
  5807. baseTable[ i ] = 0x7c00;
  5808. baseTable[ i | 0x100 ] = 0xfc00;
  5809. shiftTable[ i ] = 24;
  5810. shiftTable[ i | 0x100 ] = 24;
  5811. // stay (NaN, Infinity, -Infinity)
  5812. } else {
  5813. baseTable[ i ] = 0x7c00;
  5814. baseTable[ i | 0x100 ] = 0xfc00;
  5815. shiftTable[ i ] = 13;
  5816. shiftTable[ i | 0x100 ] = 13;
  5817. }
  5818. }
  5819. // float16 to float32 helpers
  5820. const mantissaTable = new Uint32Array( 2048 );
  5821. const exponentTable = new Uint32Array( 64 );
  5822. const offsetTable = new Uint32Array( 64 );
  5823. for ( let i = 1; i < 1024; ++ i ) {
  5824. let m = i << 13; // zero pad mantissa bits
  5825. let e = 0; // zero exponent
  5826. // normalized
  5827. while ( ( m & 0x00800000 ) === 0 ) {
  5828. m <<= 1;
  5829. e -= 0x00800000; // decrement exponent
  5830. }
  5831. m &= ~ 0x00800000; // clear leading 1 bit
  5832. e += 0x38800000; // adjust bias
  5833. mantissaTable[ i ] = m | e;
  5834. }
  5835. for ( let i = 1024; i < 2048; ++ i ) {
  5836. mantissaTable[ i ] = 0x38000000 + ( ( i - 1024 ) << 13 );
  5837. }
  5838. for ( let i = 1; i < 31; ++ i ) {
  5839. exponentTable[ i ] = i << 23;
  5840. }
  5841. exponentTable[ 31 ] = 0x47800000;
  5842. exponentTable[ 32 ] = 0x80000000;
  5843. for ( let i = 33; i < 63; ++ i ) {
  5844. exponentTable[ i ] = 0x80000000 + ( ( i - 32 ) << 23 );
  5845. }
  5846. exponentTable[ 63 ] = 0xc7800000;
  5847. for ( let i = 1; i < 64; ++ i ) {
  5848. if ( i !== 32 ) {
  5849. offsetTable[ i ] = 1024;
  5850. }
  5851. }
  5852. return {
  5853. floatView: floatView,
  5854. uint32View: uint32View,
  5855. baseTable: baseTable,
  5856. shiftTable: shiftTable,
  5857. mantissaTable: mantissaTable,
  5858. exponentTable: exponentTable,
  5859. offsetTable: offsetTable
  5860. };
  5861. }
  5862. // float32 to float16
  5863. function toHalfFloat( val ) {
  5864. if ( Math.abs( val ) > 65504 ) console.warn( 'THREE.DataUtils.toHalfFloat(): Value out of range.' );
  5865. val = clamp( val, - 65504, 65504 );
  5866. _tables.floatView[ 0 ] = val;
  5867. const f = _tables.uint32View[ 0 ];
  5868. const e = ( f >> 23 ) & 0x1ff;
  5869. return _tables.baseTable[ e ] + ( ( f & 0x007fffff ) >> _tables.shiftTable[ e ] );
  5870. }
  5871. // float16 to float32
  5872. function fromHalfFloat( val ) {
  5873. const m = val >> 10;
  5874. _tables.uint32View[ 0 ] = _tables.mantissaTable[ _tables.offsetTable[ m ] + ( val & 0x3ff ) ] + _tables.exponentTable[ m ];
  5875. return _tables.floatView[ 0 ];
  5876. }
  5877. const DataUtils = {
  5878. toHalfFloat: toHalfFloat,
  5879. fromHalfFloat: fromHalfFloat,
  5880. };
  5881. const _vector$9 = /*@__PURE__*/ new Vector3();
  5882. const _vector2$1 = /*@__PURE__*/ new Vector2();
  5883. class BufferAttribute {
  5884. constructor( array, itemSize, normalized = false ) {
  5885. if ( Array.isArray( array ) ) {
  5886. throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' );
  5887. }
  5888. this.isBufferAttribute = true;
  5889. this.name = '';
  5890. this.array = array;
  5891. this.itemSize = itemSize;
  5892. this.count = array !== undefined ? array.length / itemSize : 0;
  5893. this.normalized = normalized;
  5894. this.usage = StaticDrawUsage;
  5895. this._updateRange = { offset: 0, count: - 1 };
  5896. this.updateRanges = [];
  5897. this.gpuType = FloatType;
  5898. this.version = 0;
  5899. }
  5900. onUploadCallback() {}
  5901. set needsUpdate( value ) {
  5902. if ( value === true ) this.version ++;
  5903. }
  5904. get updateRange() {
  5905. warnOnce( 'THREE.BufferAttribute: updateRange() is deprecated and will be removed in r169. Use addUpdateRange() instead.' ); // @deprecated, r159
  5906. return this._updateRange;
  5907. }
  5908. setUsage( value ) {
  5909. this.usage = value;
  5910. return this;
  5911. }
  5912. addUpdateRange( start, count ) {
  5913. this.updateRanges.push( { start, count } );
  5914. }
  5915. clearUpdateRanges() {
  5916. this.updateRanges.length = 0;
  5917. }
  5918. copy( source ) {
  5919. this.name = source.name;
  5920. this.array = new source.array.constructor( source.array );
  5921. this.itemSize = source.itemSize;
  5922. this.count = source.count;
  5923. this.normalized = source.normalized;
  5924. this.usage = source.usage;
  5925. this.gpuType = source.gpuType;
  5926. return this;
  5927. }
  5928. copyAt( index1, attribute, index2 ) {
  5929. index1 *= this.itemSize;
  5930. index2 *= attribute.itemSize;
  5931. for ( let i = 0, l = this.itemSize; i < l; i ++ ) {
  5932. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  5933. }
  5934. return this;
  5935. }
  5936. copyArray( array ) {
  5937. this.array.set( array );
  5938. return this;
  5939. }
  5940. applyMatrix3( m ) {
  5941. if ( this.itemSize === 2 ) {
  5942. for ( let i = 0, l = this.count; i < l; i ++ ) {
  5943. _vector2$1.fromBufferAttribute( this, i );
  5944. _vector2$1.applyMatrix3( m );
  5945. this.setXY( i, _vector2$1.x, _vector2$1.y );
  5946. }
  5947. } else if ( this.itemSize === 3 ) {
  5948. for ( let i = 0, l = this.count; i < l; i ++ ) {
  5949. _vector$9.fromBufferAttribute( this, i );
  5950. _vector$9.applyMatrix3( m );
  5951. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  5952. }
  5953. }
  5954. return this;
  5955. }
  5956. applyMatrix4( m ) {
  5957. for ( let i = 0, l = this.count; i < l; i ++ ) {
  5958. _vector$9.fromBufferAttribute( this, i );
  5959. _vector$9.applyMatrix4( m );
  5960. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  5961. }
  5962. return this;
  5963. }
  5964. applyNormalMatrix( m ) {
  5965. for ( let i = 0, l = this.count; i < l; i ++ ) {
  5966. _vector$9.fromBufferAttribute( this, i );
  5967. _vector$9.applyNormalMatrix( m );
  5968. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  5969. }
  5970. return this;
  5971. }
  5972. transformDirection( m ) {
  5973. for ( let i = 0, l = this.count; i < l; i ++ ) {
  5974. _vector$9.fromBufferAttribute( this, i );
  5975. _vector$9.transformDirection( m );
  5976. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  5977. }
  5978. return this;
  5979. }
  5980. set( value, offset = 0 ) {
  5981. // Matching BufferAttribute constructor, do not normalize the array.
  5982. this.array.set( value, offset );
  5983. return this;
  5984. }
  5985. getComponent( index, component ) {
  5986. let value = this.array[ index * this.itemSize + component ];
  5987. if ( this.normalized ) value = denormalize( value, this.array );
  5988. return value;
  5989. }
  5990. setComponent( index, component, value ) {
  5991. if ( this.normalized ) value = normalize( value, this.array );
  5992. this.array[ index * this.itemSize + component ] = value;
  5993. return this;
  5994. }
  5995. getX( index ) {
  5996. let x = this.array[ index * this.itemSize ];
  5997. if ( this.normalized ) x = denormalize( x, this.array );
  5998. return x;
  5999. }
  6000. setX( index, x ) {
  6001. if ( this.normalized ) x = normalize( x, this.array );
  6002. this.array[ index * this.itemSize ] = x;
  6003. return this;
  6004. }
  6005. getY( index ) {
  6006. let y = this.array[ index * this.itemSize + 1 ];
  6007. if ( this.normalized ) y = denormalize( y, this.array );
  6008. return y;
  6009. }
  6010. setY( index, y ) {
  6011. if ( this.normalized ) y = normalize( y, this.array );
  6012. this.array[ index * this.itemSize + 1 ] = y;
  6013. return this;
  6014. }
  6015. getZ( index ) {
  6016. let z = this.array[ index * this.itemSize + 2 ];
  6017. if ( this.normalized ) z = denormalize( z, this.array );
  6018. return z;
  6019. }
  6020. setZ( index, z ) {
  6021. if ( this.normalized ) z = normalize( z, this.array );
  6022. this.array[ index * this.itemSize + 2 ] = z;
  6023. return this;
  6024. }
  6025. getW( index ) {
  6026. let w = this.array[ index * this.itemSize + 3 ];
  6027. if ( this.normalized ) w = denormalize( w, this.array );
  6028. return w;
  6029. }
  6030. setW( index, w ) {
  6031. if ( this.normalized ) w = normalize( w, this.array );
  6032. this.array[ index * this.itemSize + 3 ] = w;
  6033. return this;
  6034. }
  6035. setXY( index, x, y ) {
  6036. index *= this.itemSize;
  6037. if ( this.normalized ) {
  6038. x = normalize( x, this.array );
  6039. y = normalize( y, this.array );
  6040. }
  6041. this.array[ index + 0 ] = x;
  6042. this.array[ index + 1 ] = y;
  6043. return this;
  6044. }
  6045. setXYZ( index, x, y, z ) {
  6046. index *= this.itemSize;
  6047. if ( this.normalized ) {
  6048. x = normalize( x, this.array );
  6049. y = normalize( y, this.array );
  6050. z = normalize( z, this.array );
  6051. }
  6052. this.array[ index + 0 ] = x;
  6053. this.array[ index + 1 ] = y;
  6054. this.array[ index + 2 ] = z;
  6055. return this;
  6056. }
  6057. setXYZW( index, x, y, z, w ) {
  6058. index *= this.itemSize;
  6059. if ( this.normalized ) {
  6060. x = normalize( x, this.array );
  6061. y = normalize( y, this.array );
  6062. z = normalize( z, this.array );
  6063. w = normalize( w, this.array );
  6064. }
  6065. this.array[ index + 0 ] = x;
  6066. this.array[ index + 1 ] = y;
  6067. this.array[ index + 2 ] = z;
  6068. this.array[ index + 3 ] = w;
  6069. return this;
  6070. }
  6071. onUpload( callback ) {
  6072. this.onUploadCallback = callback;
  6073. return this;
  6074. }
  6075. clone() {
  6076. return new this.constructor( this.array, this.itemSize ).copy( this );
  6077. }
  6078. toJSON() {
  6079. const data = {
  6080. itemSize: this.itemSize,
  6081. type: this.array.constructor.name,
  6082. array: Array.from( this.array ),
  6083. normalized: this.normalized
  6084. };
  6085. if ( this.name !== '' ) data.name = this.name;
  6086. if ( this.usage !== StaticDrawUsage ) data.usage = this.usage;
  6087. return data;
  6088. }
  6089. }
  6090. //
  6091. class Int8BufferAttribute extends BufferAttribute {
  6092. constructor( array, itemSize, normalized ) {
  6093. super( new Int8Array( array ), itemSize, normalized );
  6094. }
  6095. }
  6096. class Uint8BufferAttribute extends BufferAttribute {
  6097. constructor( array, itemSize, normalized ) {
  6098. super( new Uint8Array( array ), itemSize, normalized );
  6099. }
  6100. }
  6101. class Uint8ClampedBufferAttribute extends BufferAttribute {
  6102. constructor( array, itemSize, normalized ) {
  6103. super( new Uint8ClampedArray( array ), itemSize, normalized );
  6104. }
  6105. }
  6106. class Int16BufferAttribute extends BufferAttribute {
  6107. constructor( array, itemSize, normalized ) {
  6108. super( new Int16Array( array ), itemSize, normalized );
  6109. }
  6110. }
  6111. class Uint16BufferAttribute extends BufferAttribute {
  6112. constructor( array, itemSize, normalized ) {
  6113. super( new Uint16Array( array ), itemSize, normalized );
  6114. }
  6115. }
  6116. class Int32BufferAttribute extends BufferAttribute {
  6117. constructor( array, itemSize, normalized ) {
  6118. super( new Int32Array( array ), itemSize, normalized );
  6119. }
  6120. }
  6121. class Uint32BufferAttribute extends BufferAttribute {
  6122. constructor( array, itemSize, normalized ) {
  6123. super( new Uint32Array( array ), itemSize, normalized );
  6124. }
  6125. }
  6126. class Float16BufferAttribute extends BufferAttribute {
  6127. constructor( array, itemSize, normalized ) {
  6128. super( new Uint16Array( array ), itemSize, normalized );
  6129. this.isFloat16BufferAttribute = true;
  6130. }
  6131. getX( index ) {
  6132. let x = fromHalfFloat( this.array[ index * this.itemSize ] );
  6133. if ( this.normalized ) x = denormalize( x, this.array );
  6134. return x;
  6135. }
  6136. setX( index, x ) {
  6137. if ( this.normalized ) x = normalize( x, this.array );
  6138. this.array[ index * this.itemSize ] = toHalfFloat( x );
  6139. return this;
  6140. }
  6141. getY( index ) {
  6142. let y = fromHalfFloat( this.array[ index * this.itemSize + 1 ] );
  6143. if ( this.normalized ) y = denormalize( y, this.array );
  6144. return y;
  6145. }
  6146. setY( index, y ) {
  6147. if ( this.normalized ) y = normalize( y, this.array );
  6148. this.array[ index * this.itemSize + 1 ] = toHalfFloat( y );
  6149. return this;
  6150. }
  6151. getZ( index ) {
  6152. let z = fromHalfFloat( this.array[ index * this.itemSize + 2 ] );
  6153. if ( this.normalized ) z = denormalize( z, this.array );
  6154. return z;
  6155. }
  6156. setZ( index, z ) {
  6157. if ( this.normalized ) z = normalize( z, this.array );
  6158. this.array[ index * this.itemSize + 2 ] = toHalfFloat( z );
  6159. return this;
  6160. }
  6161. getW( index ) {
  6162. let w = fromHalfFloat( this.array[ index * this.itemSize + 3 ] );
  6163. if ( this.normalized ) w = denormalize( w, this.array );
  6164. return w;
  6165. }
  6166. setW( index, w ) {
  6167. if ( this.normalized ) w = normalize( w, this.array );
  6168. this.array[ index * this.itemSize + 3 ] = toHalfFloat( w );
  6169. return this;
  6170. }
  6171. setXY( index, x, y ) {
  6172. index *= this.itemSize;
  6173. if ( this.normalized ) {
  6174. x = normalize( x, this.array );
  6175. y = normalize( y, this.array );
  6176. }
  6177. this.array[ index + 0 ] = toHalfFloat( x );
  6178. this.array[ index + 1 ] = toHalfFloat( y );
  6179. return this;
  6180. }
  6181. setXYZ( index, x, y, z ) {
  6182. index *= this.itemSize;
  6183. if ( this.normalized ) {
  6184. x = normalize( x, this.array );
  6185. y = normalize( y, this.array );
  6186. z = normalize( z, this.array );
  6187. }
  6188. this.array[ index + 0 ] = toHalfFloat( x );
  6189. this.array[ index + 1 ] = toHalfFloat( y );
  6190. this.array[ index + 2 ] = toHalfFloat( z );
  6191. return this;
  6192. }
  6193. setXYZW( index, x, y, z, w ) {
  6194. index *= this.itemSize;
  6195. if ( this.normalized ) {
  6196. x = normalize( x, this.array );
  6197. y = normalize( y, this.array );
  6198. z = normalize( z, this.array );
  6199. w = normalize( w, this.array );
  6200. }
  6201. this.array[ index + 0 ] = toHalfFloat( x );
  6202. this.array[ index + 1 ] = toHalfFloat( y );
  6203. this.array[ index + 2 ] = toHalfFloat( z );
  6204. this.array[ index + 3 ] = toHalfFloat( w );
  6205. return this;
  6206. }
  6207. }
  6208. class Float32BufferAttribute extends BufferAttribute {
  6209. constructor( array, itemSize, normalized ) {
  6210. super( new Float32Array( array ), itemSize, normalized );
  6211. }
  6212. }
  6213. class Float64BufferAttribute extends BufferAttribute {
  6214. constructor( array, itemSize, normalized ) {
  6215. super( new Float64Array( array ), itemSize, normalized );
  6216. }
  6217. }
  6218. let _id$2 = 0;
  6219. const _m1 = /*@__PURE__*/ new Matrix4();
  6220. const _obj = /*@__PURE__*/ new Object3D();
  6221. const _offset = /*@__PURE__*/ new Vector3();
  6222. const _box$2 = /*@__PURE__*/ new Box3();
  6223. const _boxMorphTargets = /*@__PURE__*/ new Box3();
  6224. const _vector$8 = /*@__PURE__*/ new Vector3();
  6225. class BufferGeometry extends EventDispatcher {
  6226. constructor() {
  6227. super();
  6228. this.isBufferGeometry = true;
  6229. Object.defineProperty( this, 'id', { value: _id$2 ++ } );
  6230. this.uuid = generateUUID();
  6231. this.name = '';
  6232. this.type = 'BufferGeometry';
  6233. this.index = null;
  6234. this.attributes = {};
  6235. this.morphAttributes = {};
  6236. this.morphTargetsRelative = false;
  6237. this.groups = [];
  6238. this.boundingBox = null;
  6239. this.boundingSphere = null;
  6240. this.drawRange = { start: 0, count: Infinity };
  6241. this.userData = {};
  6242. }
  6243. getIndex() {
  6244. return this.index;
  6245. }
  6246. setIndex( index ) {
  6247. if ( Array.isArray( index ) ) {
  6248. this.index = new ( arrayNeedsUint32( index ) ? Uint32BufferAttribute : Uint16BufferAttribute )( index, 1 );
  6249. } else {
  6250. this.index = index;
  6251. }
  6252. return this;
  6253. }
  6254. getAttribute( name ) {
  6255. return this.attributes[ name ];
  6256. }
  6257. setAttribute( name, attribute ) {
  6258. this.attributes[ name ] = attribute;
  6259. return this;
  6260. }
  6261. deleteAttribute( name ) {
  6262. delete this.attributes[ name ];
  6263. return this;
  6264. }
  6265. hasAttribute( name ) {
  6266. return this.attributes[ name ] !== undefined;
  6267. }
  6268. addGroup( start, count, materialIndex = 0 ) {
  6269. this.groups.push( {
  6270. start: start,
  6271. count: count,
  6272. materialIndex: materialIndex
  6273. } );
  6274. }
  6275. clearGroups() {
  6276. this.groups = [];
  6277. }
  6278. setDrawRange( start, count ) {
  6279. this.drawRange.start = start;
  6280. this.drawRange.count = count;
  6281. }
  6282. applyMatrix4( matrix ) {
  6283. const position = this.attributes.position;
  6284. if ( position !== undefined ) {
  6285. position.applyMatrix4( matrix );
  6286. position.needsUpdate = true;
  6287. }
  6288. const normal = this.attributes.normal;
  6289. if ( normal !== undefined ) {
  6290. const normalMatrix = new Matrix3().getNormalMatrix( matrix );
  6291. normal.applyNormalMatrix( normalMatrix );
  6292. normal.needsUpdate = true;
  6293. }
  6294. const tangent = this.attributes.tangent;
  6295. if ( tangent !== undefined ) {
  6296. tangent.transformDirection( matrix );
  6297. tangent.needsUpdate = true;
  6298. }
  6299. if ( this.boundingBox !== null ) {
  6300. this.computeBoundingBox();
  6301. }
  6302. if ( this.boundingSphere !== null ) {
  6303. this.computeBoundingSphere();
  6304. }
  6305. return this;
  6306. }
  6307. applyQuaternion( q ) {
  6308. _m1.makeRotationFromQuaternion( q );
  6309. this.applyMatrix4( _m1 );
  6310. return this;
  6311. }
  6312. rotateX( angle ) {
  6313. // rotate geometry around world x-axis
  6314. _m1.makeRotationX( angle );
  6315. this.applyMatrix4( _m1 );
  6316. return this;
  6317. }
  6318. rotateY( angle ) {
  6319. // rotate geometry around world y-axis
  6320. _m1.makeRotationY( angle );
  6321. this.applyMatrix4( _m1 );
  6322. return this;
  6323. }
  6324. rotateZ( angle ) {
  6325. // rotate geometry around world z-axis
  6326. _m1.makeRotationZ( angle );
  6327. this.applyMatrix4( _m1 );
  6328. return this;
  6329. }
  6330. translate( x, y, z ) {
  6331. // translate geometry
  6332. _m1.makeTranslation( x, y, z );
  6333. this.applyMatrix4( _m1 );
  6334. return this;
  6335. }
  6336. scale( x, y, z ) {
  6337. // scale geometry
  6338. _m1.makeScale( x, y, z );
  6339. this.applyMatrix4( _m1 );
  6340. return this;
  6341. }
  6342. lookAt( vector ) {
  6343. _obj.lookAt( vector );
  6344. _obj.updateMatrix();
  6345. this.applyMatrix4( _obj.matrix );
  6346. return this;
  6347. }
  6348. center() {
  6349. this.computeBoundingBox();
  6350. this.boundingBox.getCenter( _offset ).negate();
  6351. this.translate( _offset.x, _offset.y, _offset.z );
  6352. return this;
  6353. }
  6354. setFromPoints( points ) {
  6355. const position = [];
  6356. for ( let i = 0, l = points.length; i < l; i ++ ) {
  6357. const point = points[ i ];
  6358. position.push( point.x, point.y, point.z || 0 );
  6359. }
  6360. this.setAttribute( 'position', new Float32BufferAttribute( position, 3 ) );
  6361. return this;
  6362. }
  6363. computeBoundingBox() {
  6364. if ( this.boundingBox === null ) {
  6365. this.boundingBox = new Box3();
  6366. }
  6367. const position = this.attributes.position;
  6368. const morphAttributesPosition = this.morphAttributes.position;
  6369. if ( position && position.isGLBufferAttribute ) {
  6370. console.error( 'THREE.BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box. Alternatively set "mesh.frustumCulled" to "false".', this );
  6371. this.boundingBox.set(
  6372. new Vector3( - Infinity, - Infinity, - Infinity ),
  6373. new Vector3( + Infinity, + Infinity, + Infinity )
  6374. );
  6375. return;
  6376. }
  6377. if ( position !== undefined ) {
  6378. this.boundingBox.setFromBufferAttribute( position );
  6379. // process morph attributes if present
  6380. if ( morphAttributesPosition ) {
  6381. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  6382. const morphAttribute = morphAttributesPosition[ i ];
  6383. _box$2.setFromBufferAttribute( morphAttribute );
  6384. if ( this.morphTargetsRelative ) {
  6385. _vector$8.addVectors( this.boundingBox.min, _box$2.min );
  6386. this.boundingBox.expandByPoint( _vector$8 );
  6387. _vector$8.addVectors( this.boundingBox.max, _box$2.max );
  6388. this.boundingBox.expandByPoint( _vector$8 );
  6389. } else {
  6390. this.boundingBox.expandByPoint( _box$2.min );
  6391. this.boundingBox.expandByPoint( _box$2.max );
  6392. }
  6393. }
  6394. }
  6395. } else {
  6396. this.boundingBox.makeEmpty();
  6397. }
  6398. if ( isNaN( this.boundingBox.min.x ) || isNaN( this.boundingBox.min.y ) || isNaN( this.boundingBox.min.z ) ) {
  6399. console.error( 'THREE.BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this );
  6400. }
  6401. }
  6402. computeBoundingSphere() {
  6403. if ( this.boundingSphere === null ) {
  6404. this.boundingSphere = new Sphere();
  6405. }
  6406. const position = this.attributes.position;
  6407. const morphAttributesPosition = this.morphAttributes.position;
  6408. if ( position && position.isGLBufferAttribute ) {
  6409. console.error( 'THREE.BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere. Alternatively set "mesh.frustumCulled" to "false".', this );
  6410. this.boundingSphere.set( new Vector3(), Infinity );
  6411. return;
  6412. }
  6413. if ( position ) {
  6414. // first, find the center of the bounding sphere
  6415. const center = this.boundingSphere.center;
  6416. _box$2.setFromBufferAttribute( position );
  6417. // process morph attributes if present
  6418. if ( morphAttributesPosition ) {
  6419. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  6420. const morphAttribute = morphAttributesPosition[ i ];
  6421. _boxMorphTargets.setFromBufferAttribute( morphAttribute );
  6422. if ( this.morphTargetsRelative ) {
  6423. _vector$8.addVectors( _box$2.min, _boxMorphTargets.min );
  6424. _box$2.expandByPoint( _vector$8 );
  6425. _vector$8.addVectors( _box$2.max, _boxMorphTargets.max );
  6426. _box$2.expandByPoint( _vector$8 );
  6427. } else {
  6428. _box$2.expandByPoint( _boxMorphTargets.min );
  6429. _box$2.expandByPoint( _boxMorphTargets.max );
  6430. }
  6431. }
  6432. }
  6433. _box$2.getCenter( center );
  6434. // second, try to find a boundingSphere with a radius smaller than the
  6435. // boundingSphere of the boundingBox: sqrt(3) smaller in the best case
  6436. let maxRadiusSq = 0;
  6437. for ( let i = 0, il = position.count; i < il; i ++ ) {
  6438. _vector$8.fromBufferAttribute( position, i );
  6439. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$8 ) );
  6440. }
  6441. // process morph attributes if present
  6442. if ( morphAttributesPosition ) {
  6443. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  6444. const morphAttribute = morphAttributesPosition[ i ];
  6445. const morphTargetsRelative = this.morphTargetsRelative;
  6446. for ( let j = 0, jl = morphAttribute.count; j < jl; j ++ ) {
  6447. _vector$8.fromBufferAttribute( morphAttribute, j );
  6448. if ( morphTargetsRelative ) {
  6449. _offset.fromBufferAttribute( position, j );
  6450. _vector$8.add( _offset );
  6451. }
  6452. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$8 ) );
  6453. }
  6454. }
  6455. }
  6456. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  6457. if ( isNaN( this.boundingSphere.radius ) ) {
  6458. console.error( 'THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this );
  6459. }
  6460. }
  6461. }
  6462. computeTangents() {
  6463. const index = this.index;
  6464. const attributes = this.attributes;
  6465. // based on http://www.terathon.com/code/tangent.html
  6466. // (per vertex tangents)
  6467. if ( index === null ||
  6468. attributes.position === undefined ||
  6469. attributes.normal === undefined ||
  6470. attributes.uv === undefined ) {
  6471. console.error( 'THREE.BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)' );
  6472. return;
  6473. }
  6474. const indices = index.array;
  6475. const positions = attributes.position.array;
  6476. const normals = attributes.normal.array;
  6477. const uvs = attributes.uv.array;
  6478. const nVertices = positions.length / 3;
  6479. if ( this.hasAttribute( 'tangent' ) === false ) {
  6480. this.setAttribute( 'tangent', new BufferAttribute( new Float32Array( 4 * nVertices ), 4 ) );
  6481. }
  6482. const tangents = this.getAttribute( 'tangent' ).array;
  6483. const tan1 = [], tan2 = [];
  6484. for ( let i = 0; i < nVertices; i ++ ) {
  6485. tan1[ i ] = new Vector3();
  6486. tan2[ i ] = new Vector3();
  6487. }
  6488. const vA = new Vector3(),
  6489. vB = new Vector3(),
  6490. vC = new Vector3(),
  6491. uvA = new Vector2(),
  6492. uvB = new Vector2(),
  6493. uvC = new Vector2(),
  6494. sdir = new Vector3(),
  6495. tdir = new Vector3();
  6496. function handleTriangle( a, b, c ) {
  6497. vA.fromArray( positions, a * 3 );
  6498. vB.fromArray( positions, b * 3 );
  6499. vC.fromArray( positions, c * 3 );
  6500. uvA.fromArray( uvs, a * 2 );
  6501. uvB.fromArray( uvs, b * 2 );
  6502. uvC.fromArray( uvs, c * 2 );
  6503. vB.sub( vA );
  6504. vC.sub( vA );
  6505. uvB.sub( uvA );
  6506. uvC.sub( uvA );
  6507. const r = 1.0 / ( uvB.x * uvC.y - uvC.x * uvB.y );
  6508. // silently ignore degenerate uv triangles having coincident or colinear vertices
  6509. if ( ! isFinite( r ) ) return;
  6510. sdir.copy( vB ).multiplyScalar( uvC.y ).addScaledVector( vC, - uvB.y ).multiplyScalar( r );
  6511. tdir.copy( vC ).multiplyScalar( uvB.x ).addScaledVector( vB, - uvC.x ).multiplyScalar( r );
  6512. tan1[ a ].add( sdir );
  6513. tan1[ b ].add( sdir );
  6514. tan1[ c ].add( sdir );
  6515. tan2[ a ].add( tdir );
  6516. tan2[ b ].add( tdir );
  6517. tan2[ c ].add( tdir );
  6518. }
  6519. let groups = this.groups;
  6520. if ( groups.length === 0 ) {
  6521. groups = [ {
  6522. start: 0,
  6523. count: indices.length
  6524. } ];
  6525. }
  6526. for ( let i = 0, il = groups.length; i < il; ++ i ) {
  6527. const group = groups[ i ];
  6528. const start = group.start;
  6529. const count = group.count;
  6530. for ( let j = start, jl = start + count; j < jl; j += 3 ) {
  6531. handleTriangle(
  6532. indices[ j + 0 ],
  6533. indices[ j + 1 ],
  6534. indices[ j + 2 ]
  6535. );
  6536. }
  6537. }
  6538. const tmp = new Vector3(), tmp2 = new Vector3();
  6539. const n = new Vector3(), n2 = new Vector3();
  6540. function handleVertex( v ) {
  6541. n.fromArray( normals, v * 3 );
  6542. n2.copy( n );
  6543. const t = tan1[ v ];
  6544. // Gram-Schmidt orthogonalize
  6545. tmp.copy( t );
  6546. tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize();
  6547. // Calculate handedness
  6548. tmp2.crossVectors( n2, t );
  6549. const test = tmp2.dot( tan2[ v ] );
  6550. const w = ( test < 0.0 ) ? - 1.0 : 1.0;
  6551. tangents[ v * 4 ] = tmp.x;
  6552. tangents[ v * 4 + 1 ] = tmp.y;
  6553. tangents[ v * 4 + 2 ] = tmp.z;
  6554. tangents[ v * 4 + 3 ] = w;
  6555. }
  6556. for ( let i = 0, il = groups.length; i < il; ++ i ) {
  6557. const group = groups[ i ];
  6558. const start = group.start;
  6559. const count = group.count;
  6560. for ( let j = start, jl = start + count; j < jl; j += 3 ) {
  6561. handleVertex( indices[ j + 0 ] );
  6562. handleVertex( indices[ j + 1 ] );
  6563. handleVertex( indices[ j + 2 ] );
  6564. }
  6565. }
  6566. }
  6567. computeVertexNormals() {
  6568. const index = this.index;
  6569. const positionAttribute = this.getAttribute( 'position' );
  6570. if ( positionAttribute !== undefined ) {
  6571. let normalAttribute = this.getAttribute( 'normal' );
  6572. if ( normalAttribute === undefined ) {
  6573. normalAttribute = new BufferAttribute( new Float32Array( positionAttribute.count * 3 ), 3 );
  6574. this.setAttribute( 'normal', normalAttribute );
  6575. } else {
  6576. // reset existing normals to zero
  6577. for ( let i = 0, il = normalAttribute.count; i < il; i ++ ) {
  6578. normalAttribute.setXYZ( i, 0, 0, 0 );
  6579. }
  6580. }
  6581. const pA = new Vector3(), pB = new Vector3(), pC = new Vector3();
  6582. const nA = new Vector3(), nB = new Vector3(), nC = new Vector3();
  6583. const cb = new Vector3(), ab = new Vector3();
  6584. // indexed elements
  6585. if ( index ) {
  6586. for ( let i = 0, il = index.count; i < il; i += 3 ) {
  6587. const vA = index.getX( i + 0 );
  6588. const vB = index.getX( i + 1 );
  6589. const vC = index.getX( i + 2 );
  6590. pA.fromBufferAttribute( positionAttribute, vA );
  6591. pB.fromBufferAttribute( positionAttribute, vB );
  6592. pC.fromBufferAttribute( positionAttribute, vC );
  6593. cb.subVectors( pC, pB );
  6594. ab.subVectors( pA, pB );
  6595. cb.cross( ab );
  6596. nA.fromBufferAttribute( normalAttribute, vA );
  6597. nB.fromBufferAttribute( normalAttribute, vB );
  6598. nC.fromBufferAttribute( normalAttribute, vC );
  6599. nA.add( cb );
  6600. nB.add( cb );
  6601. nC.add( cb );
  6602. normalAttribute.setXYZ( vA, nA.x, nA.y, nA.z );
  6603. normalAttribute.setXYZ( vB, nB.x, nB.y, nB.z );
  6604. normalAttribute.setXYZ( vC, nC.x, nC.y, nC.z );
  6605. }
  6606. } else {
  6607. // non-indexed elements (unconnected triangle soup)
  6608. for ( let i = 0, il = positionAttribute.count; i < il; i += 3 ) {
  6609. pA.fromBufferAttribute( positionAttribute, i + 0 );
  6610. pB.fromBufferAttribute( positionAttribute, i + 1 );
  6611. pC.fromBufferAttribute( positionAttribute, i + 2 );
  6612. cb.subVectors( pC, pB );
  6613. ab.subVectors( pA, pB );
  6614. cb.cross( ab );
  6615. normalAttribute.setXYZ( i + 0, cb.x, cb.y, cb.z );
  6616. normalAttribute.setXYZ( i + 1, cb.x, cb.y, cb.z );
  6617. normalAttribute.setXYZ( i + 2, cb.x, cb.y, cb.z );
  6618. }
  6619. }
  6620. this.normalizeNormals();
  6621. normalAttribute.needsUpdate = true;
  6622. }
  6623. }
  6624. normalizeNormals() {
  6625. const normals = this.attributes.normal;
  6626. for ( let i = 0, il = normals.count; i < il; i ++ ) {
  6627. _vector$8.fromBufferAttribute( normals, i );
  6628. _vector$8.normalize();
  6629. normals.setXYZ( i, _vector$8.x, _vector$8.y, _vector$8.z );
  6630. }
  6631. }
  6632. toNonIndexed() {
  6633. function convertBufferAttribute( attribute, indices ) {
  6634. const array = attribute.array;
  6635. const itemSize = attribute.itemSize;
  6636. const normalized = attribute.normalized;
  6637. const array2 = new array.constructor( indices.length * itemSize );
  6638. let index = 0, index2 = 0;
  6639. for ( let i = 0, l = indices.length; i < l; i ++ ) {
  6640. if ( attribute.isInterleavedBufferAttribute ) {
  6641. index = indices[ i ] * attribute.data.stride + attribute.offset;
  6642. } else {
  6643. index = indices[ i ] * itemSize;
  6644. }
  6645. for ( let j = 0; j < itemSize; j ++ ) {
  6646. array2[ index2 ++ ] = array[ index ++ ];
  6647. }
  6648. }
  6649. return new BufferAttribute( array2, itemSize, normalized );
  6650. }
  6651. //
  6652. if ( this.index === null ) {
  6653. console.warn( 'THREE.BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed.' );
  6654. return this;
  6655. }
  6656. const geometry2 = new BufferGeometry();
  6657. const indices = this.index.array;
  6658. const attributes = this.attributes;
  6659. // attributes
  6660. for ( const name in attributes ) {
  6661. const attribute = attributes[ name ];
  6662. const newAttribute = convertBufferAttribute( attribute, indices );
  6663. geometry2.setAttribute( name, newAttribute );
  6664. }
  6665. // morph attributes
  6666. const morphAttributes = this.morphAttributes;
  6667. for ( const name in morphAttributes ) {
  6668. const morphArray = [];
  6669. const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  6670. for ( let i = 0, il = morphAttribute.length; i < il; i ++ ) {
  6671. const attribute = morphAttribute[ i ];
  6672. const newAttribute = convertBufferAttribute( attribute, indices );
  6673. morphArray.push( newAttribute );
  6674. }
  6675. geometry2.morphAttributes[ name ] = morphArray;
  6676. }
  6677. geometry2.morphTargetsRelative = this.morphTargetsRelative;
  6678. // groups
  6679. const groups = this.groups;
  6680. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  6681. const group = groups[ i ];
  6682. geometry2.addGroup( group.start, group.count, group.materialIndex );
  6683. }
  6684. return geometry2;
  6685. }
  6686. toJSON() {
  6687. const data = {
  6688. metadata: {
  6689. version: 4.6,
  6690. type: 'BufferGeometry',
  6691. generator: 'BufferGeometry.toJSON'
  6692. }
  6693. };
  6694. // standard BufferGeometry serialization
  6695. data.uuid = this.uuid;
  6696. data.type = this.type;
  6697. if ( this.name !== '' ) data.name = this.name;
  6698. if ( Object.keys( this.userData ).length > 0 ) data.userData = this.userData;
  6699. if ( this.parameters !== undefined ) {
  6700. const parameters = this.parameters;
  6701. for ( const key in parameters ) {
  6702. if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ];
  6703. }
  6704. return data;
  6705. }
  6706. // for simplicity the code assumes attributes are not shared across geometries, see #15811
  6707. data.data = { attributes: {} };
  6708. const index = this.index;
  6709. if ( index !== null ) {
  6710. data.data.index = {
  6711. type: index.array.constructor.name,
  6712. array: Array.prototype.slice.call( index.array )
  6713. };
  6714. }
  6715. const attributes = this.attributes;
  6716. for ( const key in attributes ) {
  6717. const attribute = attributes[ key ];
  6718. data.data.attributes[ key ] = attribute.toJSON( data.data );
  6719. }
  6720. const morphAttributes = {};
  6721. let hasMorphAttributes = false;
  6722. for ( const key in this.morphAttributes ) {
  6723. const attributeArray = this.morphAttributes[ key ];
  6724. const array = [];
  6725. for ( let i = 0, il = attributeArray.length; i < il; i ++ ) {
  6726. const attribute = attributeArray[ i ];
  6727. array.push( attribute.toJSON( data.data ) );
  6728. }
  6729. if ( array.length > 0 ) {
  6730. morphAttributes[ key ] = array;
  6731. hasMorphAttributes = true;
  6732. }
  6733. }
  6734. if ( hasMorphAttributes ) {
  6735. data.data.morphAttributes = morphAttributes;
  6736. data.data.morphTargetsRelative = this.morphTargetsRelative;
  6737. }
  6738. const groups = this.groups;
  6739. if ( groups.length > 0 ) {
  6740. data.data.groups = JSON.parse( JSON.stringify( groups ) );
  6741. }
  6742. const boundingSphere = this.boundingSphere;
  6743. if ( boundingSphere !== null ) {
  6744. data.data.boundingSphere = {
  6745. center: boundingSphere.center.toArray(),
  6746. radius: boundingSphere.radius
  6747. };
  6748. }
  6749. return data;
  6750. }
  6751. clone() {
  6752. return new this.constructor().copy( this );
  6753. }
  6754. copy( source ) {
  6755. // reset
  6756. this.index = null;
  6757. this.attributes = {};
  6758. this.morphAttributes = {};
  6759. this.groups = [];
  6760. this.boundingBox = null;
  6761. this.boundingSphere = null;
  6762. // used for storing cloned, shared data
  6763. const data = {};
  6764. // name
  6765. this.name = source.name;
  6766. // index
  6767. const index = source.index;
  6768. if ( index !== null ) {
  6769. this.setIndex( index.clone( data ) );
  6770. }
  6771. // attributes
  6772. const attributes = source.attributes;
  6773. for ( const name in attributes ) {
  6774. const attribute = attributes[ name ];
  6775. this.setAttribute( name, attribute.clone( data ) );
  6776. }
  6777. // morph attributes
  6778. const morphAttributes = source.morphAttributes;
  6779. for ( const name in morphAttributes ) {
  6780. const array = [];
  6781. const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  6782. for ( let i = 0, l = morphAttribute.length; i < l; i ++ ) {
  6783. array.push( morphAttribute[ i ].clone( data ) );
  6784. }
  6785. this.morphAttributes[ name ] = array;
  6786. }
  6787. this.morphTargetsRelative = source.morphTargetsRelative;
  6788. // groups
  6789. const groups = source.groups;
  6790. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  6791. const group = groups[ i ];
  6792. this.addGroup( group.start, group.count, group.materialIndex );
  6793. }
  6794. // bounding box
  6795. const boundingBox = source.boundingBox;
  6796. if ( boundingBox !== null ) {
  6797. this.boundingBox = boundingBox.clone();
  6798. }
  6799. // bounding sphere
  6800. const boundingSphere = source.boundingSphere;
  6801. if ( boundingSphere !== null ) {
  6802. this.boundingSphere = boundingSphere.clone();
  6803. }
  6804. // draw range
  6805. this.drawRange.start = source.drawRange.start;
  6806. this.drawRange.count = source.drawRange.count;
  6807. // user data
  6808. this.userData = source.userData;
  6809. return this;
  6810. }
  6811. dispose() {
  6812. this.dispatchEvent( { type: 'dispose' } );
  6813. }
  6814. }
  6815. const _inverseMatrix$3 = /*@__PURE__*/ new Matrix4();
  6816. const _ray$3 = /*@__PURE__*/ new Ray();
  6817. const _sphere$6 = /*@__PURE__*/ new Sphere();
  6818. const _sphereHitAt = /*@__PURE__*/ new Vector3();
  6819. const _vA$1 = /*@__PURE__*/ new Vector3();
  6820. const _vB$1 = /*@__PURE__*/ new Vector3();
  6821. const _vC$1 = /*@__PURE__*/ new Vector3();
  6822. const _tempA = /*@__PURE__*/ new Vector3();
  6823. const _morphA = /*@__PURE__*/ new Vector3();
  6824. const _uvA$1 = /*@__PURE__*/ new Vector2();
  6825. const _uvB$1 = /*@__PURE__*/ new Vector2();
  6826. const _uvC$1 = /*@__PURE__*/ new Vector2();
  6827. const _normalA = /*@__PURE__*/ new Vector3();
  6828. const _normalB = /*@__PURE__*/ new Vector3();
  6829. const _normalC = /*@__PURE__*/ new Vector3();
  6830. const _intersectionPoint = /*@__PURE__*/ new Vector3();
  6831. const _intersectionPointWorld = /*@__PURE__*/ new Vector3();
  6832. class Mesh extends Object3D {
  6833. constructor( geometry = new BufferGeometry(), material = new MeshBasicMaterial() ) {
  6834. super();
  6835. this.isMesh = true;
  6836. this.type = 'Mesh';
  6837. this.geometry = geometry;
  6838. this.material = material;
  6839. this.updateMorphTargets();
  6840. }
  6841. copy( source, recursive ) {
  6842. super.copy( source, recursive );
  6843. if ( source.morphTargetInfluences !== undefined ) {
  6844. this.morphTargetInfluences = source.morphTargetInfluences.slice();
  6845. }
  6846. if ( source.morphTargetDictionary !== undefined ) {
  6847. this.morphTargetDictionary = Object.assign( {}, source.morphTargetDictionary );
  6848. }
  6849. this.material = Array.isArray( source.material ) ? source.material.slice() : source.material;
  6850. this.geometry = source.geometry;
  6851. return this;
  6852. }
  6853. updateMorphTargets() {
  6854. const geometry = this.geometry;
  6855. const morphAttributes = geometry.morphAttributes;
  6856. const keys = Object.keys( morphAttributes );
  6857. if ( keys.length > 0 ) {
  6858. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  6859. if ( morphAttribute !== undefined ) {
  6860. this.morphTargetInfluences = [];
  6861. this.morphTargetDictionary = {};
  6862. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  6863. const name = morphAttribute[ m ].name || String( m );
  6864. this.morphTargetInfluences.push( 0 );
  6865. this.morphTargetDictionary[ name ] = m;
  6866. }
  6867. }
  6868. }
  6869. }
  6870. getVertexPosition( index, target ) {
  6871. const geometry = this.geometry;
  6872. const position = geometry.attributes.position;
  6873. const morphPosition = geometry.morphAttributes.position;
  6874. const morphTargetsRelative = geometry.morphTargetsRelative;
  6875. target.fromBufferAttribute( position, index );
  6876. const morphInfluences = this.morphTargetInfluences;
  6877. if ( morphPosition && morphInfluences ) {
  6878. _morphA.set( 0, 0, 0 );
  6879. for ( let i = 0, il = morphPosition.length; i < il; i ++ ) {
  6880. const influence = morphInfluences[ i ];
  6881. const morphAttribute = morphPosition[ i ];
  6882. if ( influence === 0 ) continue;
  6883. _tempA.fromBufferAttribute( morphAttribute, index );
  6884. if ( morphTargetsRelative ) {
  6885. _morphA.addScaledVector( _tempA, influence );
  6886. } else {
  6887. _morphA.addScaledVector( _tempA.sub( target ), influence );
  6888. }
  6889. }
  6890. target.add( _morphA );
  6891. }
  6892. return target;
  6893. }
  6894. raycast( raycaster, intersects ) {
  6895. const geometry = this.geometry;
  6896. const material = this.material;
  6897. const matrixWorld = this.matrixWorld;
  6898. if ( material === undefined ) return;
  6899. // test with bounding sphere in world space
  6900. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  6901. _sphere$6.copy( geometry.boundingSphere );
  6902. _sphere$6.applyMatrix4( matrixWorld );
  6903. // check distance from ray origin to bounding sphere
  6904. _ray$3.copy( raycaster.ray ).recast( raycaster.near );
  6905. if ( _sphere$6.containsPoint( _ray$3.origin ) === false ) {
  6906. if ( _ray$3.intersectSphere( _sphere$6, _sphereHitAt ) === null ) return;
  6907. if ( _ray$3.origin.distanceToSquared( _sphereHitAt ) > ( raycaster.far - raycaster.near ) ** 2 ) return;
  6908. }
  6909. // convert ray to local space of mesh
  6910. _inverseMatrix$3.copy( matrixWorld ).invert();
  6911. _ray$3.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$3 );
  6912. // test with bounding box in local space
  6913. if ( geometry.boundingBox !== null ) {
  6914. if ( _ray$3.intersectsBox( geometry.boundingBox ) === false ) return;
  6915. }
  6916. // test for intersections with geometry
  6917. this._computeIntersections( raycaster, intersects, _ray$3 );
  6918. }
  6919. _computeIntersections( raycaster, intersects, rayLocalSpace ) {
  6920. let intersection;
  6921. const geometry = this.geometry;
  6922. const material = this.material;
  6923. const index = geometry.index;
  6924. const position = geometry.attributes.position;
  6925. const uv = geometry.attributes.uv;
  6926. const uv1 = geometry.attributes.uv1;
  6927. const normal = geometry.attributes.normal;
  6928. const groups = geometry.groups;
  6929. const drawRange = geometry.drawRange;
  6930. if ( index !== null ) {
  6931. // indexed buffer geometry
  6932. if ( Array.isArray( material ) ) {
  6933. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  6934. const group = groups[ i ];
  6935. const groupMaterial = material[ group.materialIndex ];
  6936. const start = Math.max( group.start, drawRange.start );
  6937. const end = Math.min( index.count, Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ) );
  6938. for ( let j = start, jl = end; j < jl; j += 3 ) {
  6939. const a = index.getX( j );
  6940. const b = index.getX( j + 1 );
  6941. const c = index.getX( j + 2 );
  6942. intersection = checkGeometryIntersection( this, groupMaterial, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  6943. if ( intersection ) {
  6944. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in indexed buffer semantics
  6945. intersection.face.materialIndex = group.materialIndex;
  6946. intersects.push( intersection );
  6947. }
  6948. }
  6949. }
  6950. } else {
  6951. const start = Math.max( 0, drawRange.start );
  6952. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  6953. for ( let i = start, il = end; i < il; i += 3 ) {
  6954. const a = index.getX( i );
  6955. const b = index.getX( i + 1 );
  6956. const c = index.getX( i + 2 );
  6957. intersection = checkGeometryIntersection( this, material, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  6958. if ( intersection ) {
  6959. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in indexed buffer semantics
  6960. intersects.push( intersection );
  6961. }
  6962. }
  6963. }
  6964. } else if ( position !== undefined ) {
  6965. // non-indexed buffer geometry
  6966. if ( Array.isArray( material ) ) {
  6967. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  6968. const group = groups[ i ];
  6969. const groupMaterial = material[ group.materialIndex ];
  6970. const start = Math.max( group.start, drawRange.start );
  6971. const end = Math.min( position.count, Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ) );
  6972. for ( let j = start, jl = end; j < jl; j += 3 ) {
  6973. const a = j;
  6974. const b = j + 1;
  6975. const c = j + 2;
  6976. intersection = checkGeometryIntersection( this, groupMaterial, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  6977. if ( intersection ) {
  6978. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in non-indexed buffer semantics
  6979. intersection.face.materialIndex = group.materialIndex;
  6980. intersects.push( intersection );
  6981. }
  6982. }
  6983. }
  6984. } else {
  6985. const start = Math.max( 0, drawRange.start );
  6986. const end = Math.min( position.count, ( drawRange.start + drawRange.count ) );
  6987. for ( let i = start, il = end; i < il; i += 3 ) {
  6988. const a = i;
  6989. const b = i + 1;
  6990. const c = i + 2;
  6991. intersection = checkGeometryIntersection( this, material, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  6992. if ( intersection ) {
  6993. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in non-indexed buffer semantics
  6994. intersects.push( intersection );
  6995. }
  6996. }
  6997. }
  6998. }
  6999. }
  7000. }
  7001. function checkIntersection( object, material, raycaster, ray, pA, pB, pC, point ) {
  7002. let intersect;
  7003. if ( material.side === BackSide ) {
  7004. intersect = ray.intersectTriangle( pC, pB, pA, true, point );
  7005. } else {
  7006. intersect = ray.intersectTriangle( pA, pB, pC, ( material.side === FrontSide ), point );
  7007. }
  7008. if ( intersect === null ) return null;
  7009. _intersectionPointWorld.copy( point );
  7010. _intersectionPointWorld.applyMatrix4( object.matrixWorld );
  7011. const distance = raycaster.ray.origin.distanceTo( _intersectionPointWorld );
  7012. if ( distance < raycaster.near || distance > raycaster.far ) return null;
  7013. return {
  7014. distance: distance,
  7015. point: _intersectionPointWorld.clone(),
  7016. object: object
  7017. };
  7018. }
  7019. function checkGeometryIntersection( object, material, raycaster, ray, uv, uv1, normal, a, b, c ) {
  7020. object.getVertexPosition( a, _vA$1 );
  7021. object.getVertexPosition( b, _vB$1 );
  7022. object.getVertexPosition( c, _vC$1 );
  7023. const intersection = checkIntersection( object, material, raycaster, ray, _vA$1, _vB$1, _vC$1, _intersectionPoint );
  7024. if ( intersection ) {
  7025. if ( uv ) {
  7026. _uvA$1.fromBufferAttribute( uv, a );
  7027. _uvB$1.fromBufferAttribute( uv, b );
  7028. _uvC$1.fromBufferAttribute( uv, c );
  7029. intersection.uv = Triangle.getInterpolation( _intersectionPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2() );
  7030. }
  7031. if ( uv1 ) {
  7032. _uvA$1.fromBufferAttribute( uv1, a );
  7033. _uvB$1.fromBufferAttribute( uv1, b );
  7034. _uvC$1.fromBufferAttribute( uv1, c );
  7035. intersection.uv1 = Triangle.getInterpolation( _intersectionPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2() );
  7036. }
  7037. if ( normal ) {
  7038. _normalA.fromBufferAttribute( normal, a );
  7039. _normalB.fromBufferAttribute( normal, b );
  7040. _normalC.fromBufferAttribute( normal, c );
  7041. intersection.normal = Triangle.getInterpolation( _intersectionPoint, _vA$1, _vB$1, _vC$1, _normalA, _normalB, _normalC, new Vector3() );
  7042. if ( intersection.normal.dot( ray.direction ) > 0 ) {
  7043. intersection.normal.multiplyScalar( - 1 );
  7044. }
  7045. }
  7046. const face = {
  7047. a: a,
  7048. b: b,
  7049. c: c,
  7050. normal: new Vector3(),
  7051. materialIndex: 0
  7052. };
  7053. Triangle.getNormal( _vA$1, _vB$1, _vC$1, face.normal );
  7054. intersection.face = face;
  7055. }
  7056. return intersection;
  7057. }
  7058. class BoxGeometry extends BufferGeometry {
  7059. constructor( width = 1, height = 1, depth = 1, widthSegments = 1, heightSegments = 1, depthSegments = 1 ) {
  7060. super();
  7061. this.type = 'BoxGeometry';
  7062. this.parameters = {
  7063. width: width,
  7064. height: height,
  7065. depth: depth,
  7066. widthSegments: widthSegments,
  7067. heightSegments: heightSegments,
  7068. depthSegments: depthSegments
  7069. };
  7070. const scope = this;
  7071. // segments
  7072. widthSegments = Math.floor( widthSegments );
  7073. heightSegments = Math.floor( heightSegments );
  7074. depthSegments = Math.floor( depthSegments );
  7075. // buffers
  7076. const indices = [];
  7077. const vertices = [];
  7078. const normals = [];
  7079. const uvs = [];
  7080. // helper variables
  7081. let numberOfVertices = 0;
  7082. let groupStart = 0;
  7083. // build each side of the box geometry
  7084. buildPlane( 'z', 'y', 'x', - 1, - 1, depth, height, width, depthSegments, heightSegments, 0 ); // px
  7085. buildPlane( 'z', 'y', 'x', 1, - 1, depth, height, - width, depthSegments, heightSegments, 1 ); // nx
  7086. buildPlane( 'x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2 ); // py
  7087. buildPlane( 'x', 'z', 'y', 1, - 1, width, depth, - height, widthSegments, depthSegments, 3 ); // ny
  7088. buildPlane( 'x', 'y', 'z', 1, - 1, width, height, depth, widthSegments, heightSegments, 4 ); // pz
  7089. buildPlane( 'x', 'y', 'z', - 1, - 1, width, height, - depth, widthSegments, heightSegments, 5 ); // nz
  7090. // build geometry
  7091. this.setIndex( indices );
  7092. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  7093. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  7094. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  7095. function buildPlane( u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex ) {
  7096. const segmentWidth = width / gridX;
  7097. const segmentHeight = height / gridY;
  7098. const widthHalf = width / 2;
  7099. const heightHalf = height / 2;
  7100. const depthHalf = depth / 2;
  7101. const gridX1 = gridX + 1;
  7102. const gridY1 = gridY + 1;
  7103. let vertexCounter = 0;
  7104. let groupCount = 0;
  7105. const vector = new Vector3();
  7106. // generate vertices, normals and uvs
  7107. for ( let iy = 0; iy < gridY1; iy ++ ) {
  7108. const y = iy * segmentHeight - heightHalf;
  7109. for ( let ix = 0; ix < gridX1; ix ++ ) {
  7110. const x = ix * segmentWidth - widthHalf;
  7111. // set values to correct vector component
  7112. vector[ u ] = x * udir;
  7113. vector[ v ] = y * vdir;
  7114. vector[ w ] = depthHalf;
  7115. // now apply vector to vertex buffer
  7116. vertices.push( vector.x, vector.y, vector.z );
  7117. // set values to correct vector component
  7118. vector[ u ] = 0;
  7119. vector[ v ] = 0;
  7120. vector[ w ] = depth > 0 ? 1 : - 1;
  7121. // now apply vector to normal buffer
  7122. normals.push( vector.x, vector.y, vector.z );
  7123. // uvs
  7124. uvs.push( ix / gridX );
  7125. uvs.push( 1 - ( iy / gridY ) );
  7126. // counters
  7127. vertexCounter += 1;
  7128. }
  7129. }
  7130. // indices
  7131. // 1. you need three indices to draw a single face
  7132. // 2. a single segment consists of two faces
  7133. // 3. so we need to generate six (2*3) indices per segment
  7134. for ( let iy = 0; iy < gridY; iy ++ ) {
  7135. for ( let ix = 0; ix < gridX; ix ++ ) {
  7136. const a = numberOfVertices + ix + gridX1 * iy;
  7137. const b = numberOfVertices + ix + gridX1 * ( iy + 1 );
  7138. const c = numberOfVertices + ( ix + 1 ) + gridX1 * ( iy + 1 );
  7139. const d = numberOfVertices + ( ix + 1 ) + gridX1 * iy;
  7140. // faces
  7141. indices.push( a, b, d );
  7142. indices.push( b, c, d );
  7143. // increase counter
  7144. groupCount += 6;
  7145. }
  7146. }
  7147. // add a group to the geometry. this will ensure multi material support
  7148. scope.addGroup( groupStart, groupCount, materialIndex );
  7149. // calculate new start value for groups
  7150. groupStart += groupCount;
  7151. // update total number of vertices
  7152. numberOfVertices += vertexCounter;
  7153. }
  7154. }
  7155. copy( source ) {
  7156. super.copy( source );
  7157. this.parameters = Object.assign( {}, source.parameters );
  7158. return this;
  7159. }
  7160. static fromJSON( data ) {
  7161. return new BoxGeometry( data.width, data.height, data.depth, data.widthSegments, data.heightSegments, data.depthSegments );
  7162. }
  7163. }
  7164. /**
  7165. * Uniform Utilities
  7166. */
  7167. function cloneUniforms( src ) {
  7168. const dst = {};
  7169. for ( const u in src ) {
  7170. dst[ u ] = {};
  7171. for ( const p in src[ u ] ) {
  7172. const property = src[ u ][ p ];
  7173. if ( property && ( property.isColor ||
  7174. property.isMatrix3 || property.isMatrix4 ||
  7175. property.isVector2 || property.isVector3 || property.isVector4 ||
  7176. property.isTexture || property.isQuaternion ) ) {
  7177. if ( property.isRenderTargetTexture ) {
  7178. console.warn( 'UniformsUtils: Textures of render targets cannot be cloned via cloneUniforms() or mergeUniforms().' );
  7179. dst[ u ][ p ] = null;
  7180. } else {
  7181. dst[ u ][ p ] = property.clone();
  7182. }
  7183. } else if ( Array.isArray( property ) ) {
  7184. dst[ u ][ p ] = property.slice();
  7185. } else {
  7186. dst[ u ][ p ] = property;
  7187. }
  7188. }
  7189. }
  7190. return dst;
  7191. }
  7192. function mergeUniforms( uniforms ) {
  7193. const merged = {};
  7194. for ( let u = 0; u < uniforms.length; u ++ ) {
  7195. const tmp = cloneUniforms( uniforms[ u ] );
  7196. for ( const p in tmp ) {
  7197. merged[ p ] = tmp[ p ];
  7198. }
  7199. }
  7200. return merged;
  7201. }
  7202. function cloneUniformsGroups( src ) {
  7203. const dst = [];
  7204. for ( let u = 0; u < src.length; u ++ ) {
  7205. dst.push( src[ u ].clone() );
  7206. }
  7207. return dst;
  7208. }
  7209. function getUnlitUniformColorSpace( renderer ) {
  7210. if ( renderer.getRenderTarget() === null ) {
  7211. // https://github.com/mrdoob/three.js/pull/23937#issuecomment-1111067398
  7212. return renderer.outputColorSpace;
  7213. }
  7214. return ColorManagement.workingColorSpace;
  7215. }
  7216. // Legacy
  7217. const UniformsUtils = { clone: cloneUniforms, merge: mergeUniforms };
  7218. var default_vertex = "void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}";
  7219. var default_fragment = "void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}";
  7220. class ShaderMaterial extends Material {
  7221. constructor( parameters ) {
  7222. super();
  7223. this.isShaderMaterial = true;
  7224. this.type = 'ShaderMaterial';
  7225. this.defines = {};
  7226. this.uniforms = {};
  7227. this.uniformsGroups = [];
  7228. this.vertexShader = default_vertex;
  7229. this.fragmentShader = default_fragment;
  7230. this.linewidth = 1;
  7231. this.wireframe = false;
  7232. this.wireframeLinewidth = 1;
  7233. this.fog = false; // set to use scene fog
  7234. this.lights = false; // set to use scene lights
  7235. this.clipping = false; // set to use user-defined clipping planes
  7236. this.forceSinglePass = true;
  7237. this.extensions = {
  7238. derivatives: false, // set to use derivatives
  7239. fragDepth: false, // set to use fragment depth values
  7240. drawBuffers: false, // set to use draw buffers
  7241. shaderTextureLOD: false, // set to use shader texture LOD
  7242. clipCullDistance: false, // set to use vertex shader clipping
  7243. multiDraw: false // set to use vertex shader multi_draw / enable gl_DrawID
  7244. };
  7245. // When rendered geometry doesn't include these attributes but the material does,
  7246. // use these default values in WebGL. This avoids errors when buffer data is missing.
  7247. this.defaultAttributeValues = {
  7248. 'color': [ 1, 1, 1 ],
  7249. 'uv': [ 0, 0 ],
  7250. 'uv1': [ 0, 0 ]
  7251. };
  7252. this.index0AttributeName = undefined;
  7253. this.uniformsNeedUpdate = false;
  7254. this.glslVersion = null;
  7255. if ( parameters !== undefined ) {
  7256. this.setValues( parameters );
  7257. }
  7258. }
  7259. copy( source ) {
  7260. super.copy( source );
  7261. this.fragmentShader = source.fragmentShader;
  7262. this.vertexShader = source.vertexShader;
  7263. this.uniforms = cloneUniforms( source.uniforms );
  7264. this.uniformsGroups = cloneUniformsGroups( source.uniformsGroups );
  7265. this.defines = Object.assign( {}, source.defines );
  7266. this.wireframe = source.wireframe;
  7267. this.wireframeLinewidth = source.wireframeLinewidth;
  7268. this.fog = source.fog;
  7269. this.lights = source.lights;
  7270. this.clipping = source.clipping;
  7271. this.extensions = Object.assign( {}, source.extensions );
  7272. this.glslVersion = source.glslVersion;
  7273. return this;
  7274. }
  7275. toJSON( meta ) {
  7276. const data = super.toJSON( meta );
  7277. data.glslVersion = this.glslVersion;
  7278. data.uniforms = {};
  7279. for ( const name in this.uniforms ) {
  7280. const uniform = this.uniforms[ name ];
  7281. const value = uniform.value;
  7282. if ( value && value.isTexture ) {
  7283. data.uniforms[ name ] = {
  7284. type: 't',
  7285. value: value.toJSON( meta ).uuid
  7286. };
  7287. } else if ( value && value.isColor ) {
  7288. data.uniforms[ name ] = {
  7289. type: 'c',
  7290. value: value.getHex()
  7291. };
  7292. } else if ( value && value.isVector2 ) {
  7293. data.uniforms[ name ] = {
  7294. type: 'v2',
  7295. value: value.toArray()
  7296. };
  7297. } else if ( value && value.isVector3 ) {
  7298. data.uniforms[ name ] = {
  7299. type: 'v3',
  7300. value: value.toArray()
  7301. };
  7302. } else if ( value && value.isVector4 ) {
  7303. data.uniforms[ name ] = {
  7304. type: 'v4',
  7305. value: value.toArray()
  7306. };
  7307. } else if ( value && value.isMatrix3 ) {
  7308. data.uniforms[ name ] = {
  7309. type: 'm3',
  7310. value: value.toArray()
  7311. };
  7312. } else if ( value && value.isMatrix4 ) {
  7313. data.uniforms[ name ] = {
  7314. type: 'm4',
  7315. value: value.toArray()
  7316. };
  7317. } else {
  7318. data.uniforms[ name ] = {
  7319. value: value
  7320. };
  7321. // note: the array variants v2v, v3v, v4v, m4v and tv are not supported so far
  7322. }
  7323. }
  7324. if ( Object.keys( this.defines ).length > 0 ) data.defines = this.defines;
  7325. data.vertexShader = this.vertexShader;
  7326. data.fragmentShader = this.fragmentShader;
  7327. data.lights = this.lights;
  7328. data.clipping = this.clipping;
  7329. const extensions = {};
  7330. for ( const key in this.extensions ) {
  7331. if ( this.extensions[ key ] === true ) extensions[ key ] = true;
  7332. }
  7333. if ( Object.keys( extensions ).length > 0 ) data.extensions = extensions;
  7334. return data;
  7335. }
  7336. }
  7337. class Camera extends Object3D {
  7338. constructor() {
  7339. super();
  7340. this.isCamera = true;
  7341. this.type = 'Camera';
  7342. this.matrixWorldInverse = new Matrix4();
  7343. this.projectionMatrix = new Matrix4();
  7344. this.projectionMatrixInverse = new Matrix4();
  7345. this.coordinateSystem = WebGLCoordinateSystem;
  7346. }
  7347. copy( source, recursive ) {
  7348. super.copy( source, recursive );
  7349. this.matrixWorldInverse.copy( source.matrixWorldInverse );
  7350. this.projectionMatrix.copy( source.projectionMatrix );
  7351. this.projectionMatrixInverse.copy( source.projectionMatrixInverse );
  7352. this.coordinateSystem = source.coordinateSystem;
  7353. return this;
  7354. }
  7355. getWorldDirection( target ) {
  7356. return super.getWorldDirection( target ).negate();
  7357. }
  7358. updateMatrixWorld( force ) {
  7359. super.updateMatrixWorld( force );
  7360. this.matrixWorldInverse.copy( this.matrixWorld ).invert();
  7361. }
  7362. updateWorldMatrix( updateParents, updateChildren ) {
  7363. super.updateWorldMatrix( updateParents, updateChildren );
  7364. this.matrixWorldInverse.copy( this.matrixWorld ).invert();
  7365. }
  7366. clone() {
  7367. return new this.constructor().copy( this );
  7368. }
  7369. }
  7370. const _v3$1 = /*@__PURE__*/ new Vector3();
  7371. const _minTarget = /*@__PURE__*/ new Vector2();
  7372. const _maxTarget = /*@__PURE__*/ new Vector2();
  7373. class PerspectiveCamera extends Camera {
  7374. constructor( fov = 50, aspect = 1, near = 0.1, far = 2000 ) {
  7375. super();
  7376. this.isPerspectiveCamera = true;
  7377. this.type = 'PerspectiveCamera';
  7378. this.fov = fov;
  7379. this.zoom = 1;
  7380. this.near = near;
  7381. this.far = far;
  7382. this.focus = 10;
  7383. this.aspect = aspect;
  7384. this.view = null;
  7385. this.filmGauge = 35; // width of the film (default in millimeters)
  7386. this.filmOffset = 0; // horizontal film offset (same unit as gauge)
  7387. this.updateProjectionMatrix();
  7388. }
  7389. copy( source, recursive ) {
  7390. super.copy( source, recursive );
  7391. this.fov = source.fov;
  7392. this.zoom = source.zoom;
  7393. this.near = source.near;
  7394. this.far = source.far;
  7395. this.focus = source.focus;
  7396. this.aspect = source.aspect;
  7397. this.view = source.view === null ? null : Object.assign( {}, source.view );
  7398. this.filmGauge = source.filmGauge;
  7399. this.filmOffset = source.filmOffset;
  7400. return this;
  7401. }
  7402. /**
  7403. * Sets the FOV by focal length in respect to the current .filmGauge.
  7404. *
  7405. * The default film gauge is 35, so that the focal length can be specified for
  7406. * a 35mm (full frame) camera.
  7407. *
  7408. * Values for focal length and film gauge must have the same unit.
  7409. */
  7410. setFocalLength( focalLength ) {
  7411. /** see {@link http://www.bobatkins.com/photography/technical/field_of_view.html} */
  7412. const vExtentSlope = 0.5 * this.getFilmHeight() / focalLength;
  7413. this.fov = RAD2DEG * 2 * Math.atan( vExtentSlope );
  7414. this.updateProjectionMatrix();
  7415. }
  7416. /**
  7417. * Calculates the focal length from the current .fov and .filmGauge.
  7418. */
  7419. getFocalLength() {
  7420. const vExtentSlope = Math.tan( DEG2RAD * 0.5 * this.fov );
  7421. return 0.5 * this.getFilmHeight() / vExtentSlope;
  7422. }
  7423. getEffectiveFOV() {
  7424. return RAD2DEG * 2 * Math.atan(
  7425. Math.tan( DEG2RAD * 0.5 * this.fov ) / this.zoom );
  7426. }
  7427. getFilmWidth() {
  7428. // film not completely covered in portrait format (aspect < 1)
  7429. return this.filmGauge * Math.min( this.aspect, 1 );
  7430. }
  7431. getFilmHeight() {
  7432. // film not completely covered in landscape format (aspect > 1)
  7433. return this.filmGauge / Math.max( this.aspect, 1 );
  7434. }
  7435. /**
  7436. * Computes the 2D bounds of the camera's viewable rectangle at a given distance along the viewing direction.
  7437. * Sets minTarget and maxTarget to the coordinates of the lower-left and upper-right corners of the view rectangle.
  7438. */
  7439. getViewBounds( distance, minTarget, maxTarget ) {
  7440. _v3$1.set( - 1, - 1, 0.5 ).applyMatrix4( this.projectionMatrixInverse );
  7441. minTarget.set( _v3$1.x, _v3$1.y ).multiplyScalar( - distance / _v3$1.z );
  7442. _v3$1.set( 1, 1, 0.5 ).applyMatrix4( this.projectionMatrixInverse );
  7443. maxTarget.set( _v3$1.x, _v3$1.y ).multiplyScalar( - distance / _v3$1.z );
  7444. }
  7445. /**
  7446. * Computes the width and height of the camera's viewable rectangle at a given distance along the viewing direction.
  7447. * Copies the result into the target Vector2, where x is width and y is height.
  7448. */
  7449. getViewSize( distance, target ) {
  7450. this.getViewBounds( distance, _minTarget, _maxTarget );
  7451. return target.subVectors( _maxTarget, _minTarget );
  7452. }
  7453. /**
  7454. * Sets an offset in a larger frustum. This is useful for multi-window or
  7455. * multi-monitor/multi-machine setups.
  7456. *
  7457. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  7458. * the monitors are in grid like this
  7459. *
  7460. * +---+---+---+
  7461. * | A | B | C |
  7462. * +---+---+---+
  7463. * | D | E | F |
  7464. * +---+---+---+
  7465. *
  7466. * then for each monitor you would call it like this
  7467. *
  7468. * const w = 1920;
  7469. * const h = 1080;
  7470. * const fullWidth = w * 3;
  7471. * const fullHeight = h * 2;
  7472. *
  7473. * --A--
  7474. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  7475. * --B--
  7476. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  7477. * --C--
  7478. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  7479. * --D--
  7480. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  7481. * --E--
  7482. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  7483. * --F--
  7484. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  7485. *
  7486. * Note there is no reason monitors have to be the same size or in a grid.
  7487. */
  7488. setViewOffset( fullWidth, fullHeight, x, y, width, height ) {
  7489. this.aspect = fullWidth / fullHeight;
  7490. if ( this.view === null ) {
  7491. this.view = {
  7492. enabled: true,
  7493. fullWidth: 1,
  7494. fullHeight: 1,
  7495. offsetX: 0,
  7496. offsetY: 0,
  7497. width: 1,
  7498. height: 1
  7499. };
  7500. }
  7501. this.view.enabled = true;
  7502. this.view.fullWidth = fullWidth;
  7503. this.view.fullHeight = fullHeight;
  7504. this.view.offsetX = x;
  7505. this.view.offsetY = y;
  7506. this.view.width = width;
  7507. this.view.height = height;
  7508. this.updateProjectionMatrix();
  7509. }
  7510. clearViewOffset() {
  7511. if ( this.view !== null ) {
  7512. this.view.enabled = false;
  7513. }
  7514. this.updateProjectionMatrix();
  7515. }
  7516. updateProjectionMatrix() {
  7517. const near = this.near;
  7518. let top = near * Math.tan( DEG2RAD * 0.5 * this.fov ) / this.zoom;
  7519. let height = 2 * top;
  7520. let width = this.aspect * height;
  7521. let left = - 0.5 * width;
  7522. const view = this.view;
  7523. if ( this.view !== null && this.view.enabled ) {
  7524. const fullWidth = view.fullWidth,
  7525. fullHeight = view.fullHeight;
  7526. left += view.offsetX * width / fullWidth;
  7527. top -= view.offsetY * height / fullHeight;
  7528. width *= view.width / fullWidth;
  7529. height *= view.height / fullHeight;
  7530. }
  7531. const skew = this.filmOffset;
  7532. if ( skew !== 0 ) left += near * skew / this.getFilmWidth();
  7533. this.projectionMatrix.makePerspective( left, left + width, top, top - height, near, this.far, this.coordinateSystem );
  7534. this.projectionMatrixInverse.copy( this.projectionMatrix ).invert();
  7535. }
  7536. toJSON( meta ) {
  7537. const data = super.toJSON( meta );
  7538. data.object.fov = this.fov;
  7539. data.object.zoom = this.zoom;
  7540. data.object.near = this.near;
  7541. data.object.far = this.far;
  7542. data.object.focus = this.focus;
  7543. data.object.aspect = this.aspect;
  7544. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  7545. data.object.filmGauge = this.filmGauge;
  7546. data.object.filmOffset = this.filmOffset;
  7547. return data;
  7548. }
  7549. }
  7550. const fov = - 90; // negative fov is not an error
  7551. const aspect = 1;
  7552. class CubeCamera extends Object3D {
  7553. constructor( near, far, renderTarget ) {
  7554. super();
  7555. this.type = 'CubeCamera';
  7556. this.renderTarget = renderTarget;
  7557. this.coordinateSystem = null;
  7558. this.activeMipmapLevel = 0;
  7559. const cameraPX = new PerspectiveCamera( fov, aspect, near, far );
  7560. cameraPX.layers = this.layers;
  7561. this.add( cameraPX );
  7562. const cameraNX = new PerspectiveCamera( fov, aspect, near, far );
  7563. cameraNX.layers = this.layers;
  7564. this.add( cameraNX );
  7565. const cameraPY = new PerspectiveCamera( fov, aspect, near, far );
  7566. cameraPY.layers = this.layers;
  7567. this.add( cameraPY );
  7568. const cameraNY = new PerspectiveCamera( fov, aspect, near, far );
  7569. cameraNY.layers = this.layers;
  7570. this.add( cameraNY );
  7571. const cameraPZ = new PerspectiveCamera( fov, aspect, near, far );
  7572. cameraPZ.layers = this.layers;
  7573. this.add( cameraPZ );
  7574. const cameraNZ = new PerspectiveCamera( fov, aspect, near, far );
  7575. cameraNZ.layers = this.layers;
  7576. this.add( cameraNZ );
  7577. }
  7578. updateCoordinateSystem() {
  7579. const coordinateSystem = this.coordinateSystem;
  7580. const cameras = this.children.concat();
  7581. const [ cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ ] = cameras;
  7582. for ( const camera of cameras ) this.remove( camera );
  7583. if ( coordinateSystem === WebGLCoordinateSystem ) {
  7584. cameraPX.up.set( 0, 1, 0 );
  7585. cameraPX.lookAt( 1, 0, 0 );
  7586. cameraNX.up.set( 0, 1, 0 );
  7587. cameraNX.lookAt( - 1, 0, 0 );
  7588. cameraPY.up.set( 0, 0, - 1 );
  7589. cameraPY.lookAt( 0, 1, 0 );
  7590. cameraNY.up.set( 0, 0, 1 );
  7591. cameraNY.lookAt( 0, - 1, 0 );
  7592. cameraPZ.up.set( 0, 1, 0 );
  7593. cameraPZ.lookAt( 0, 0, 1 );
  7594. cameraNZ.up.set( 0, 1, 0 );
  7595. cameraNZ.lookAt( 0, 0, - 1 );
  7596. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  7597. cameraPX.up.set( 0, - 1, 0 );
  7598. cameraPX.lookAt( - 1, 0, 0 );
  7599. cameraNX.up.set( 0, - 1, 0 );
  7600. cameraNX.lookAt( 1, 0, 0 );
  7601. cameraPY.up.set( 0, 0, 1 );
  7602. cameraPY.lookAt( 0, 1, 0 );
  7603. cameraNY.up.set( 0, 0, - 1 );
  7604. cameraNY.lookAt( 0, - 1, 0 );
  7605. cameraPZ.up.set( 0, - 1, 0 );
  7606. cameraPZ.lookAt( 0, 0, 1 );
  7607. cameraNZ.up.set( 0, - 1, 0 );
  7608. cameraNZ.lookAt( 0, 0, - 1 );
  7609. } else {
  7610. throw new Error( 'THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: ' + coordinateSystem );
  7611. }
  7612. for ( const camera of cameras ) {
  7613. this.add( camera );
  7614. camera.updateMatrixWorld();
  7615. }
  7616. }
  7617. update( renderer, scene ) {
  7618. if ( this.parent === null ) this.updateMatrixWorld();
  7619. const { renderTarget, activeMipmapLevel } = this;
  7620. if ( this.coordinateSystem !== renderer.coordinateSystem ) {
  7621. this.coordinateSystem = renderer.coordinateSystem;
  7622. this.updateCoordinateSystem();
  7623. }
  7624. const [ cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ ] = this.children;
  7625. const currentRenderTarget = renderer.getRenderTarget();
  7626. const currentActiveCubeFace = renderer.getActiveCubeFace();
  7627. const currentActiveMipmapLevel = renderer.getActiveMipmapLevel();
  7628. const currentXrEnabled = renderer.xr.enabled;
  7629. renderer.xr.enabled = false;
  7630. const generateMipmaps = renderTarget.texture.generateMipmaps;
  7631. renderTarget.texture.generateMipmaps = false;
  7632. renderer.setRenderTarget( renderTarget, 0, activeMipmapLevel );
  7633. renderer.render( scene, cameraPX );
  7634. renderer.setRenderTarget( renderTarget, 1, activeMipmapLevel );
  7635. renderer.render( scene, cameraNX );
  7636. renderer.setRenderTarget( renderTarget, 2, activeMipmapLevel );
  7637. renderer.render( scene, cameraPY );
  7638. renderer.setRenderTarget( renderTarget, 3, activeMipmapLevel );
  7639. renderer.render( scene, cameraNY );
  7640. renderer.setRenderTarget( renderTarget, 4, activeMipmapLevel );
  7641. renderer.render( scene, cameraPZ );
  7642. // mipmaps are generated during the last call of render()
  7643. // at this point, all sides of the cube render target are defined
  7644. renderTarget.texture.generateMipmaps = generateMipmaps;
  7645. renderer.setRenderTarget( renderTarget, 5, activeMipmapLevel );
  7646. renderer.render( scene, cameraNZ );
  7647. renderer.setRenderTarget( currentRenderTarget, currentActiveCubeFace, currentActiveMipmapLevel );
  7648. renderer.xr.enabled = currentXrEnabled;
  7649. renderTarget.texture.needsPMREMUpdate = true;
  7650. }
  7651. }
  7652. class CubeTexture extends Texture {
  7653. constructor( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace ) {
  7654. images = images !== undefined ? images : [];
  7655. mapping = mapping !== undefined ? mapping : CubeReflectionMapping;
  7656. super( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace );
  7657. this.isCubeTexture = true;
  7658. this.flipY = false;
  7659. }
  7660. get images() {
  7661. return this.image;
  7662. }
  7663. set images( value ) {
  7664. this.image = value;
  7665. }
  7666. }
  7667. class WebGLCubeRenderTarget extends WebGLRenderTarget {
  7668. constructor( size = 1, options = {} ) {
  7669. super( size, size, options );
  7670. this.isWebGLCubeRenderTarget = true;
  7671. const image = { width: size, height: size, depth: 1 };
  7672. const images = [ image, image, image, image, image, image ];
  7673. this.texture = new CubeTexture( images, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.colorSpace );
  7674. // By convention -- likely based on the RenderMan spec from the 1990's -- cube maps are specified by WebGL (and three.js)
  7675. // in a coordinate system in which positive-x is to the right when looking up the positive-z axis -- in other words,
  7676. // in a left-handed coordinate system. By continuing this convention, preexisting cube maps continued to render correctly.
  7677. // three.js uses a right-handed coordinate system. So environment maps used in three.js appear to have px and nx swapped
  7678. // and the flag isRenderTargetTexture controls this conversion. The flip is not required when using WebGLCubeRenderTarget.texture
  7679. // as a cube texture (this is detected when isRenderTargetTexture is set to true for cube textures).
  7680. this.texture.isRenderTargetTexture = true;
  7681. this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false;
  7682. this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter;
  7683. }
  7684. fromEquirectangularTexture( renderer, texture ) {
  7685. this.texture.type = texture.type;
  7686. this.texture.colorSpace = texture.colorSpace;
  7687. this.texture.generateMipmaps = texture.generateMipmaps;
  7688. this.texture.minFilter = texture.minFilter;
  7689. this.texture.magFilter = texture.magFilter;
  7690. const shader = {
  7691. uniforms: {
  7692. tEquirect: { value: null },
  7693. },
  7694. vertexShader: /* glsl */`
  7695. varying vec3 vWorldDirection;
  7696. vec3 transformDirection( in vec3 dir, in mat4 matrix ) {
  7697. return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );
  7698. }
  7699. void main() {
  7700. vWorldDirection = transformDirection( position, modelMatrix );
  7701. #include <begin_vertex>
  7702. #include <project_vertex>
  7703. }
  7704. `,
  7705. fragmentShader: /* glsl */`
  7706. uniform sampler2D tEquirect;
  7707. varying vec3 vWorldDirection;
  7708. #include <common>
  7709. void main() {
  7710. vec3 direction = normalize( vWorldDirection );
  7711. vec2 sampleUV = equirectUv( direction );
  7712. gl_FragColor = texture2D( tEquirect, sampleUV );
  7713. }
  7714. `
  7715. };
  7716. const geometry = new BoxGeometry( 5, 5, 5 );
  7717. const material = new ShaderMaterial( {
  7718. name: 'CubemapFromEquirect',
  7719. uniforms: cloneUniforms( shader.uniforms ),
  7720. vertexShader: shader.vertexShader,
  7721. fragmentShader: shader.fragmentShader,
  7722. side: BackSide,
  7723. blending: NoBlending
  7724. } );
  7725. material.uniforms.tEquirect.value = texture;
  7726. const mesh = new Mesh( geometry, material );
  7727. const currentMinFilter = texture.minFilter;
  7728. // Avoid blurred poles
  7729. if ( texture.minFilter === LinearMipmapLinearFilter ) texture.minFilter = LinearFilter;
  7730. const camera = new CubeCamera( 1, 10, this );
  7731. camera.update( renderer, mesh );
  7732. texture.minFilter = currentMinFilter;
  7733. mesh.geometry.dispose();
  7734. mesh.material.dispose();
  7735. return this;
  7736. }
  7737. clear( renderer, color, depth, stencil ) {
  7738. const currentRenderTarget = renderer.getRenderTarget();
  7739. for ( let i = 0; i < 6; i ++ ) {
  7740. renderer.setRenderTarget( this, i );
  7741. renderer.clear( color, depth, stencil );
  7742. }
  7743. renderer.setRenderTarget( currentRenderTarget );
  7744. }
  7745. }
  7746. const _vector1 = /*@__PURE__*/ new Vector3();
  7747. const _vector2 = /*@__PURE__*/ new Vector3();
  7748. const _normalMatrix = /*@__PURE__*/ new Matrix3();
  7749. class Plane {
  7750. constructor( normal = new Vector3( 1, 0, 0 ), constant = 0 ) {
  7751. this.isPlane = true;
  7752. // normal is assumed to be normalized
  7753. this.normal = normal;
  7754. this.constant = constant;
  7755. }
  7756. set( normal, constant ) {
  7757. this.normal.copy( normal );
  7758. this.constant = constant;
  7759. return this;
  7760. }
  7761. setComponents( x, y, z, w ) {
  7762. this.normal.set( x, y, z );
  7763. this.constant = w;
  7764. return this;
  7765. }
  7766. setFromNormalAndCoplanarPoint( normal, point ) {
  7767. this.normal.copy( normal );
  7768. this.constant = - point.dot( this.normal );
  7769. return this;
  7770. }
  7771. setFromCoplanarPoints( a, b, c ) {
  7772. const normal = _vector1.subVectors( c, b ).cross( _vector2.subVectors( a, b ) ).normalize();
  7773. // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  7774. this.setFromNormalAndCoplanarPoint( normal, a );
  7775. return this;
  7776. }
  7777. copy( plane ) {
  7778. this.normal.copy( plane.normal );
  7779. this.constant = plane.constant;
  7780. return this;
  7781. }
  7782. normalize() {
  7783. // Note: will lead to a divide by zero if the plane is invalid.
  7784. const inverseNormalLength = 1.0 / this.normal.length();
  7785. this.normal.multiplyScalar( inverseNormalLength );
  7786. this.constant *= inverseNormalLength;
  7787. return this;
  7788. }
  7789. negate() {
  7790. this.constant *= - 1;
  7791. this.normal.negate();
  7792. return this;
  7793. }
  7794. distanceToPoint( point ) {
  7795. return this.normal.dot( point ) + this.constant;
  7796. }
  7797. distanceToSphere( sphere ) {
  7798. return this.distanceToPoint( sphere.center ) - sphere.radius;
  7799. }
  7800. projectPoint( point, target ) {
  7801. return target.copy( point ).addScaledVector( this.normal, - this.distanceToPoint( point ) );
  7802. }
  7803. intersectLine( line, target ) {
  7804. const direction = line.delta( _vector1 );
  7805. const denominator = this.normal.dot( direction );
  7806. if ( denominator === 0 ) {
  7807. // line is coplanar, return origin
  7808. if ( this.distanceToPoint( line.start ) === 0 ) {
  7809. return target.copy( line.start );
  7810. }
  7811. // Unsure if this is the correct method to handle this case.
  7812. return null;
  7813. }
  7814. const t = - ( line.start.dot( this.normal ) + this.constant ) / denominator;
  7815. if ( t < 0 || t > 1 ) {
  7816. return null;
  7817. }
  7818. return target.copy( line.start ).addScaledVector( direction, t );
  7819. }
  7820. intersectsLine( line ) {
  7821. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  7822. const startSign = this.distanceToPoint( line.start );
  7823. const endSign = this.distanceToPoint( line.end );
  7824. return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 );
  7825. }
  7826. intersectsBox( box ) {
  7827. return box.intersectsPlane( this );
  7828. }
  7829. intersectsSphere( sphere ) {
  7830. return sphere.intersectsPlane( this );
  7831. }
  7832. coplanarPoint( target ) {
  7833. return target.copy( this.normal ).multiplyScalar( - this.constant );
  7834. }
  7835. applyMatrix4( matrix, optionalNormalMatrix ) {
  7836. const normalMatrix = optionalNormalMatrix || _normalMatrix.getNormalMatrix( matrix );
  7837. const referencePoint = this.coplanarPoint( _vector1 ).applyMatrix4( matrix );
  7838. const normal = this.normal.applyMatrix3( normalMatrix ).normalize();
  7839. this.constant = - referencePoint.dot( normal );
  7840. return this;
  7841. }
  7842. translate( offset ) {
  7843. this.constant -= offset.dot( this.normal );
  7844. return this;
  7845. }
  7846. equals( plane ) {
  7847. return plane.normal.equals( this.normal ) && ( plane.constant === this.constant );
  7848. }
  7849. clone() {
  7850. return new this.constructor().copy( this );
  7851. }
  7852. }
  7853. const _sphere$5 = /*@__PURE__*/ new Sphere();
  7854. const _vector$7 = /*@__PURE__*/ new Vector3();
  7855. class Frustum {
  7856. constructor( p0 = new Plane(), p1 = new Plane(), p2 = new Plane(), p3 = new Plane(), p4 = new Plane(), p5 = new Plane() ) {
  7857. this.planes = [ p0, p1, p2, p3, p4, p5 ];
  7858. }
  7859. set( p0, p1, p2, p3, p4, p5 ) {
  7860. const planes = this.planes;
  7861. planes[ 0 ].copy( p0 );
  7862. planes[ 1 ].copy( p1 );
  7863. planes[ 2 ].copy( p2 );
  7864. planes[ 3 ].copy( p3 );
  7865. planes[ 4 ].copy( p4 );
  7866. planes[ 5 ].copy( p5 );
  7867. return this;
  7868. }
  7869. copy( frustum ) {
  7870. const planes = this.planes;
  7871. for ( let i = 0; i < 6; i ++ ) {
  7872. planes[ i ].copy( frustum.planes[ i ] );
  7873. }
  7874. return this;
  7875. }
  7876. setFromProjectionMatrix( m, coordinateSystem = WebGLCoordinateSystem ) {
  7877. const planes = this.planes;
  7878. const me = m.elements;
  7879. const me0 = me[ 0 ], me1 = me[ 1 ], me2 = me[ 2 ], me3 = me[ 3 ];
  7880. const me4 = me[ 4 ], me5 = me[ 5 ], me6 = me[ 6 ], me7 = me[ 7 ];
  7881. const me8 = me[ 8 ], me9 = me[ 9 ], me10 = me[ 10 ], me11 = me[ 11 ];
  7882. const me12 = me[ 12 ], me13 = me[ 13 ], me14 = me[ 14 ], me15 = me[ 15 ];
  7883. planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize();
  7884. planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize();
  7885. planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize();
  7886. planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize();
  7887. planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize();
  7888. if ( coordinateSystem === WebGLCoordinateSystem ) {
  7889. planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize();
  7890. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  7891. planes[ 5 ].setComponents( me2, me6, me10, me14 ).normalize();
  7892. } else {
  7893. throw new Error( 'THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: ' + coordinateSystem );
  7894. }
  7895. return this;
  7896. }
  7897. intersectsObject( object ) {
  7898. if ( object.boundingSphere !== undefined ) {
  7899. if ( object.boundingSphere === null ) object.computeBoundingSphere();
  7900. _sphere$5.copy( object.boundingSphere ).applyMatrix4( object.matrixWorld );
  7901. } else {
  7902. const geometry = object.geometry;
  7903. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  7904. _sphere$5.copy( geometry.boundingSphere ).applyMatrix4( object.matrixWorld );
  7905. }
  7906. return this.intersectsSphere( _sphere$5 );
  7907. }
  7908. intersectsSprite( sprite ) {
  7909. _sphere$5.center.set( 0, 0, 0 );
  7910. _sphere$5.radius = 0.7071067811865476;
  7911. _sphere$5.applyMatrix4( sprite.matrixWorld );
  7912. return this.intersectsSphere( _sphere$5 );
  7913. }
  7914. intersectsSphere( sphere ) {
  7915. const planes = this.planes;
  7916. const center = sphere.center;
  7917. const negRadius = - sphere.radius;
  7918. for ( let i = 0; i < 6; i ++ ) {
  7919. const distance = planes[ i ].distanceToPoint( center );
  7920. if ( distance < negRadius ) {
  7921. return false;
  7922. }
  7923. }
  7924. return true;
  7925. }
  7926. intersectsBox( box ) {
  7927. const planes = this.planes;
  7928. for ( let i = 0; i < 6; i ++ ) {
  7929. const plane = planes[ i ];
  7930. // corner at max distance
  7931. _vector$7.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  7932. _vector$7.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  7933. _vector$7.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  7934. if ( plane.distanceToPoint( _vector$7 ) < 0 ) {
  7935. return false;
  7936. }
  7937. }
  7938. return true;
  7939. }
  7940. containsPoint( point ) {
  7941. const planes = this.planes;
  7942. for ( let i = 0; i < 6; i ++ ) {
  7943. if ( planes[ i ].distanceToPoint( point ) < 0 ) {
  7944. return false;
  7945. }
  7946. }
  7947. return true;
  7948. }
  7949. clone() {
  7950. return new this.constructor().copy( this );
  7951. }
  7952. }
  7953. function WebGLAnimation() {
  7954. let context = null;
  7955. let isAnimating = false;
  7956. let animationLoop = null;
  7957. let requestId = null;
  7958. function onAnimationFrame( time, frame ) {
  7959. animationLoop( time, frame );
  7960. requestId = context.requestAnimationFrame( onAnimationFrame );
  7961. }
  7962. return {
  7963. start: function () {
  7964. if ( isAnimating === true ) return;
  7965. if ( animationLoop === null ) return;
  7966. requestId = context.requestAnimationFrame( onAnimationFrame );
  7967. isAnimating = true;
  7968. },
  7969. stop: function () {
  7970. context.cancelAnimationFrame( requestId );
  7971. isAnimating = false;
  7972. },
  7973. setAnimationLoop: function ( callback ) {
  7974. animationLoop = callback;
  7975. },
  7976. setContext: function ( value ) {
  7977. context = value;
  7978. }
  7979. };
  7980. }
  7981. function WebGLAttributes( gl, capabilities ) {
  7982. const isWebGL2 = capabilities.isWebGL2;
  7983. const buffers = new WeakMap();
  7984. function createBuffer( attribute, bufferType ) {
  7985. const array = attribute.array;
  7986. const usage = attribute.usage;
  7987. const size = array.byteLength;
  7988. const buffer = gl.createBuffer();
  7989. gl.bindBuffer( bufferType, buffer );
  7990. gl.bufferData( bufferType, array, usage );
  7991. attribute.onUploadCallback();
  7992. let type;
  7993. if ( array instanceof Float32Array ) {
  7994. type = gl.FLOAT;
  7995. } else if ( array instanceof Uint16Array ) {
  7996. if ( attribute.isFloat16BufferAttribute ) {
  7997. if ( isWebGL2 ) {
  7998. type = gl.HALF_FLOAT;
  7999. } else {
  8000. throw new Error( 'THREE.WebGLAttributes: Usage of Float16BufferAttribute requires WebGL2.' );
  8001. }
  8002. } else {
  8003. type = gl.UNSIGNED_SHORT;
  8004. }
  8005. } else if ( array instanceof Int16Array ) {
  8006. type = gl.SHORT;
  8007. } else if ( array instanceof Uint32Array ) {
  8008. type = gl.UNSIGNED_INT;
  8009. } else if ( array instanceof Int32Array ) {
  8010. type = gl.INT;
  8011. } else if ( array instanceof Int8Array ) {
  8012. type = gl.BYTE;
  8013. } else if ( array instanceof Uint8Array ) {
  8014. type = gl.UNSIGNED_BYTE;
  8015. } else if ( array instanceof Uint8ClampedArray ) {
  8016. type = gl.UNSIGNED_BYTE;
  8017. } else {
  8018. throw new Error( 'THREE.WebGLAttributes: Unsupported buffer data format: ' + array );
  8019. }
  8020. return {
  8021. buffer: buffer,
  8022. type: type,
  8023. bytesPerElement: array.BYTES_PER_ELEMENT,
  8024. version: attribute.version,
  8025. size: size
  8026. };
  8027. }
  8028. function updateBuffer( buffer, attribute, bufferType ) {
  8029. const array = attribute.array;
  8030. const updateRange = attribute._updateRange; // @deprecated, r159
  8031. const updateRanges = attribute.updateRanges;
  8032. gl.bindBuffer( bufferType, buffer );
  8033. if ( updateRange.count === - 1 && updateRanges.length === 0 ) {
  8034. // Not using update ranges
  8035. gl.bufferSubData( bufferType, 0, array );
  8036. }
  8037. if ( updateRanges.length !== 0 ) {
  8038. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  8039. const range = updateRanges[ i ];
  8040. if ( isWebGL2 ) {
  8041. gl.bufferSubData( bufferType, range.start * array.BYTES_PER_ELEMENT,
  8042. array, range.start, range.count );
  8043. } else {
  8044. gl.bufferSubData( bufferType, range.start * array.BYTES_PER_ELEMENT,
  8045. array.subarray( range.start, range.start + range.count ) );
  8046. }
  8047. }
  8048. attribute.clearUpdateRanges();
  8049. }
  8050. // @deprecated, r159
  8051. if ( updateRange.count !== - 1 ) {
  8052. if ( isWebGL2 ) {
  8053. gl.bufferSubData( bufferType, updateRange.offset * array.BYTES_PER_ELEMENT,
  8054. array, updateRange.offset, updateRange.count );
  8055. } else {
  8056. gl.bufferSubData( bufferType, updateRange.offset * array.BYTES_PER_ELEMENT,
  8057. array.subarray( updateRange.offset, updateRange.offset + updateRange.count ) );
  8058. }
  8059. updateRange.count = - 1; // reset range
  8060. }
  8061. attribute.onUploadCallback();
  8062. }
  8063. //
  8064. function get( attribute ) {
  8065. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  8066. return buffers.get( attribute );
  8067. }
  8068. function remove( attribute ) {
  8069. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  8070. const data = buffers.get( attribute );
  8071. if ( data ) {
  8072. gl.deleteBuffer( data.buffer );
  8073. buffers.delete( attribute );
  8074. }
  8075. }
  8076. function update( attribute, bufferType ) {
  8077. if ( attribute.isGLBufferAttribute ) {
  8078. const cached = buffers.get( attribute );
  8079. if ( ! cached || cached.version < attribute.version ) {
  8080. buffers.set( attribute, {
  8081. buffer: attribute.buffer,
  8082. type: attribute.type,
  8083. bytesPerElement: attribute.elementSize,
  8084. version: attribute.version
  8085. } );
  8086. }
  8087. return;
  8088. }
  8089. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  8090. const data = buffers.get( attribute );
  8091. if ( data === undefined ) {
  8092. buffers.set( attribute, createBuffer( attribute, bufferType ) );
  8093. } else if ( data.version < attribute.version ) {
  8094. if ( data.size !== attribute.array.byteLength ) {
  8095. throw new Error( 'THREE.WebGLAttributes: The size of the buffer attribute\'s array buffer does not match the original size. Resizing buffer attributes is not supported.' );
  8096. }
  8097. updateBuffer( data.buffer, attribute, bufferType );
  8098. data.version = attribute.version;
  8099. }
  8100. }
  8101. return {
  8102. get: get,
  8103. remove: remove,
  8104. update: update
  8105. };
  8106. }
  8107. class PlaneGeometry extends BufferGeometry {
  8108. constructor( width = 1, height = 1, widthSegments = 1, heightSegments = 1 ) {
  8109. super();
  8110. this.type = 'PlaneGeometry';
  8111. this.parameters = {
  8112. width: width,
  8113. height: height,
  8114. widthSegments: widthSegments,
  8115. heightSegments: heightSegments
  8116. };
  8117. const width_half = width / 2;
  8118. const height_half = height / 2;
  8119. const gridX = Math.floor( widthSegments );
  8120. const gridY = Math.floor( heightSegments );
  8121. const gridX1 = gridX + 1;
  8122. const gridY1 = gridY + 1;
  8123. const segment_width = width / gridX;
  8124. const segment_height = height / gridY;
  8125. //
  8126. const indices = [];
  8127. const vertices = [];
  8128. const normals = [];
  8129. const uvs = [];
  8130. for ( let iy = 0; iy < gridY1; iy ++ ) {
  8131. const y = iy * segment_height - height_half;
  8132. for ( let ix = 0; ix < gridX1; ix ++ ) {
  8133. const x = ix * segment_width - width_half;
  8134. vertices.push( x, - y, 0 );
  8135. normals.push( 0, 0, 1 );
  8136. uvs.push( ix / gridX );
  8137. uvs.push( 1 - ( iy / gridY ) );
  8138. }
  8139. }
  8140. for ( let iy = 0; iy < gridY; iy ++ ) {
  8141. for ( let ix = 0; ix < gridX; ix ++ ) {
  8142. const a = ix + gridX1 * iy;
  8143. const b = ix + gridX1 * ( iy + 1 );
  8144. const c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  8145. const d = ( ix + 1 ) + gridX1 * iy;
  8146. indices.push( a, b, d );
  8147. indices.push( b, c, d );
  8148. }
  8149. }
  8150. this.setIndex( indices );
  8151. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  8152. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  8153. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  8154. }
  8155. copy( source ) {
  8156. super.copy( source );
  8157. this.parameters = Object.assign( {}, source.parameters );
  8158. return this;
  8159. }
  8160. static fromJSON( data ) {
  8161. return new PlaneGeometry( data.width, data.height, data.widthSegments, data.heightSegments );
  8162. }
  8163. }
  8164. var alphahash_fragment = "#ifdef USE_ALPHAHASH\n\tif ( diffuseColor.a < getAlphaHashThreshold( vPosition ) ) discard;\n#endif";
  8165. var alphahash_pars_fragment = "#ifdef USE_ALPHAHASH\n\tconst float ALPHA_HASH_SCALE = 0.05;\n\tfloat hash2D( vec2 value ) {\n\t\treturn fract( 1.0e4 * sin( 17.0 * value.x + 0.1 * value.y ) * ( 0.1 + abs( sin( 13.0 * value.y + value.x ) ) ) );\n\t}\n\tfloat hash3D( vec3 value ) {\n\t\treturn hash2D( vec2( hash2D( value.xy ), value.z ) );\n\t}\n\tfloat getAlphaHashThreshold( vec3 position ) {\n\t\tfloat maxDeriv = max(\n\t\t\tlength( dFdx( position.xyz ) ),\n\t\t\tlength( dFdy( position.xyz ) )\n\t\t);\n\t\tfloat pixScale = 1.0 / ( ALPHA_HASH_SCALE * maxDeriv );\n\t\tvec2 pixScales = vec2(\n\t\t\texp2( floor( log2( pixScale ) ) ),\n\t\t\texp2( ceil( log2( pixScale ) ) )\n\t\t);\n\t\tvec2 alpha = vec2(\n\t\t\thash3D( floor( pixScales.x * position.xyz ) ),\n\t\t\thash3D( floor( pixScales.y * position.xyz ) )\n\t\t);\n\t\tfloat lerpFactor = fract( log2( pixScale ) );\n\t\tfloat x = ( 1.0 - lerpFactor ) * alpha.x + lerpFactor * alpha.y;\n\t\tfloat a = min( lerpFactor, 1.0 - lerpFactor );\n\t\tvec3 cases = vec3(\n\t\t\tx * x / ( 2.0 * a * ( 1.0 - a ) ),\n\t\t\t( x - 0.5 * a ) / ( 1.0 - a ),\n\t\t\t1.0 - ( ( 1.0 - x ) * ( 1.0 - x ) / ( 2.0 * a * ( 1.0 - a ) ) )\n\t\t);\n\t\tfloat threshold = ( x < ( 1.0 - a ) )\n\t\t\t? ( ( x < a ) ? cases.x : cases.y )\n\t\t\t: cases.z;\n\t\treturn clamp( threshold , 1.0e-6, 1.0 );\n\t}\n#endif";
  8166. var alphamap_fragment = "#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, vAlphaMapUv ).g;\n#endif";
  8167. var alphamap_pars_fragment = "#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif";
  8168. var alphatest_fragment = "#ifdef USE_ALPHATEST\n\t#ifdef ALPHA_TO_COVERAGE\n\tdiffuseColor.a = smoothstep( alphaTest, alphaTest + fwidth( diffuseColor.a ), diffuseColor.a );\n\tif ( diffuseColor.a == 0.0 ) discard;\n\t#else\n\tif ( diffuseColor.a < alphaTest ) discard;\n\t#endif\n#endif";
  8169. var alphatest_pars_fragment = "#ifdef USE_ALPHATEST\n\tuniform float alphaTest;\n#endif";
  8170. var aomap_fragment = "#ifdef USE_AOMAP\n\tfloat ambientOcclusion = ( texture2D( aoMap, vAoMapUv ).r - 1.0 ) * aoMapIntensity + 1.0;\n\treflectedLight.indirectDiffuse *= ambientOcclusion;\n\t#if defined( USE_CLEARCOAT ) \n\t\tclearcoatSpecularIndirect *= ambientOcclusion;\n\t#endif\n\t#if defined( USE_SHEEN ) \n\t\tsheenSpecularIndirect *= ambientOcclusion;\n\t#endif\n\t#if defined( USE_ENVMAP ) && defined( STANDARD )\n\t\tfloat dotNV = saturate( dot( geometryNormal, geometryViewDir ) );\n\t\treflectedLight.indirectSpecular *= computeSpecularOcclusion( dotNV, ambientOcclusion, material.roughness );\n\t#endif\n#endif";
  8171. var aomap_pars_fragment = "#ifdef USE_AOMAP\n\tuniform sampler2D aoMap;\n\tuniform float aoMapIntensity;\n#endif";
  8172. var batching_pars_vertex = "#ifdef USE_BATCHING\n\tattribute float batchId;\n\tuniform highp sampler2D batchingTexture;\n\tmat4 getBatchingMatrix( const in float i ) {\n\t\tint size = textureSize( batchingTexture, 0 ).x;\n\t\tint j = int( i ) * 4;\n\t\tint x = j % size;\n\t\tint y = j / size;\n\t\tvec4 v1 = texelFetch( batchingTexture, ivec2( x, y ), 0 );\n\t\tvec4 v2 = texelFetch( batchingTexture, ivec2( x + 1, y ), 0 );\n\t\tvec4 v3 = texelFetch( batchingTexture, ivec2( x + 2, y ), 0 );\n\t\tvec4 v4 = texelFetch( batchingTexture, ivec2( x + 3, y ), 0 );\n\t\treturn mat4( v1, v2, v3, v4 );\n\t}\n#endif";
  8173. var batching_vertex = "#ifdef USE_BATCHING\n\tmat4 batchingMatrix = getBatchingMatrix( batchId );\n#endif";
  8174. var begin_vertex = "vec3 transformed = vec3( position );\n#ifdef USE_ALPHAHASH\n\tvPosition = vec3( position );\n#endif";
  8175. var beginnormal_vertex = "vec3 objectNormal = vec3( normal );\n#ifdef USE_TANGENT\n\tvec3 objectTangent = vec3( tangent.xyz );\n#endif";
  8176. var bsdfs = "float 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} // validated";
  8177. var iridescence_fragment = "#ifdef USE_IRIDESCENCE\n\tconst mat3 XYZ_TO_REC709 = mat3(\n\t\t 3.2404542, -0.9692660, 0.0556434,\n\t\t-1.5371385, 1.8760108, -0.2040259,\n\t\t-0.4985314, 0.0415560, 1.0572252\n\t);\n\tvec3 Fresnel0ToIor( vec3 fresnel0 ) {\n\t\tvec3 sqrtF0 = sqrt( fresnel0 );\n\t\treturn ( vec3( 1.0 ) + sqrtF0 ) / ( vec3( 1.0 ) - sqrtF0 );\n\t}\n\tvec3 IorToFresnel0( vec3 transmittedIor, float incidentIor ) {\n\t\treturn pow2( ( transmittedIor - vec3( incidentIor ) ) / ( transmittedIor + vec3( incidentIor ) ) );\n\t}\n\tfloat IorToFresnel0( float transmittedIor, float incidentIor ) {\n\t\treturn pow2( ( transmittedIor - incidentIor ) / ( transmittedIor + incidentIor ));\n\t}\n\tvec3 evalSensitivity( float OPD, vec3 shift ) {\n\t\tfloat phase = 2.0 * PI * OPD * 1.0e-9;\n\t\tvec3 val = vec3( 5.4856e-13, 4.4201e-13, 5.2481e-13 );\n\t\tvec3 pos = vec3( 1.6810e+06, 1.7953e+06, 2.2084e+06 );\n\t\tvec3 var = vec3( 4.3278e+09, 9.3046e+09, 6.6121e+09 );\n\t\tvec3 xyz = val * sqrt( 2.0 * PI * var ) * cos( pos * phase + shift ) * exp( - pow2( phase ) * var );\n\t\txyz.x += 9.7470e-14 * sqrt( 2.0 * PI * 4.5282e+09 ) * cos( 2.2399e+06 * phase + shift[ 0 ] ) * exp( - 4.5282e+09 * pow2( phase ) );\n\t\txyz /= 1.0685e-7;\n\t\tvec3 rgb = XYZ_TO_REC709 * xyz;\n\t\treturn rgb;\n\t}\n\tvec3 evalIridescence( float outsideIOR, float eta2, float cosTheta1, float thinFilmThickness, vec3 baseF0 ) {\n\t\tvec3 I;\n\t\tfloat iridescenceIOR = mix( outsideIOR, eta2, smoothstep( 0.0, 0.03, thinFilmThickness ) );\n\t\tfloat sinTheta2Sq = pow2( outsideIOR / iridescenceIOR ) * ( 1.0 - pow2( cosTheta1 ) );\n\t\tfloat cosTheta2Sq = 1.0 - sinTheta2Sq;\n\t\tif ( cosTheta2Sq < 0.0 ) {\n\t\t\treturn vec3( 1.0 );\n\t\t}\n\t\tfloat cosTheta2 = sqrt( cosTheta2Sq );\n\t\tfloat R0 = IorToFresnel0( iridescenceIOR, outsideIOR );\n\t\tfloat R12 = F_Schlick( R0, 1.0, cosTheta1 );\n\t\tfloat T121 = 1.0 - R12;\n\t\tfloat phi12 = 0.0;\n\t\tif ( iridescenceIOR < outsideIOR ) phi12 = PI;\n\t\tfloat phi21 = PI - phi12;\n\t\tvec3 baseIOR = Fresnel0ToIor( clamp( baseF0, 0.0, 0.9999 ) );\t\tvec3 R1 = IorToFresnel0( baseIOR, iridescenceIOR );\n\t\tvec3 R23 = F_Schlick( R1, 1.0, cosTheta2 );\n\t\tvec3 phi23 = vec3( 0.0 );\n\t\tif ( baseIOR[ 0 ] < iridescenceIOR ) phi23[ 0 ] = PI;\n\t\tif ( baseIOR[ 1 ] < iridescenceIOR ) phi23[ 1 ] = PI;\n\t\tif ( baseIOR[ 2 ] < iridescenceIOR ) phi23[ 2 ] = PI;\n\t\tfloat OPD = 2.0 * iridescenceIOR * thinFilmThickness * cosTheta2;\n\t\tvec3 phi = vec3( phi21 ) + phi23;\n\t\tvec3 R123 = clamp( R12 * R23, 1e-5, 0.9999 );\n\t\tvec3 r123 = sqrt( R123 );\n\t\tvec3 Rs = pow2( T121 ) * R23 / ( vec3( 1.0 ) - R123 );\n\t\tvec3 C0 = R12 + Rs;\n\t\tI = C0;\n\t\tvec3 Cm = Rs - T121;\n\t\tfor ( int m = 1; m <= 2; ++ m ) {\n\t\t\tCm *= r123;\n\t\t\tvec3 Sm = 2.0 * evalSensitivity( float( m ) * OPD, float( m ) * phi );\n\t\t\tI += Cm * Sm;\n\t\t}\n\t\treturn max( I, vec3( 0.0 ) );\n\t}\n#endif";
  8178. var bumpmap_pars_fragment = "#ifdef USE_BUMPMAP\n\tuniform sampler2D bumpMap;\n\tuniform float bumpScale;\n\tvec2 dHdxy_fwd() {\n\t\tvec2 dSTdx = dFdx( vBumpMapUv );\n\t\tvec2 dSTdy = dFdy( vBumpMapUv );\n\t\tfloat Hll = bumpScale * texture2D( bumpMap, vBumpMapUv ).x;\n\t\tfloat dBx = bumpScale * texture2D( bumpMap, vBumpMapUv + dSTdx ).x - Hll;\n\t\tfloat dBy = bumpScale * texture2D( bumpMap, vBumpMapUv + 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 = normalize( dFdx( surf_pos.xyz ) );\n\t\tvec3 vSigmaY = normalize( dFdy( surf_pos.xyz ) );\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";
  8179. var clipping_planes_fragment = "#if NUM_CLIPPING_PLANES > 0\n\tvec4 plane;\n\t#ifdef ALPHA_TO_COVERAGE\n\t\tfloat distanceToPlane, distanceGradient;\n\t\tfloat clipOpacity = 1.0;\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) {\n\t\t\tplane = clippingPlanes[ i ];\n\t\t\tdistanceToPlane = - dot( vClipPosition, plane.xyz ) + plane.w;\n\t\t\tdistanceGradient = fwidth( distanceToPlane ) / 2.0;\n\t\t\tclipOpacity *= smoothstep( - distanceGradient, distanceGradient, distanceToPlane );\n\t\t\tif ( clipOpacity == 0.0 ) discard;\n\t\t}\n\t\t#pragma unroll_loop_end\n\t\t#if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES\n\t\t\tfloat unionClipOpacity = 1.0;\n\t\t\t#pragma unroll_loop_start\n\t\t\tfor ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) {\n\t\t\t\tplane = clippingPlanes[ i ];\n\t\t\t\tdistanceToPlane = - dot( vClipPosition, plane.xyz ) + plane.w;\n\t\t\t\tdistanceGradient = fwidth( distanceToPlane ) / 2.0;\n\t\t\t\tunionClipOpacity *= 1.0 - smoothstep( - distanceGradient, distanceGradient, distanceToPlane );\n\t\t\t}\n\t\t\t#pragma unroll_loop_end\n\t\t\tclipOpacity *= 1.0 - unionClipOpacity;\n\t\t#endif\n\t\tdiffuseColor.a *= clipOpacity;\n\t\tif ( diffuseColor.a == 0.0 ) discard;\n\t#else\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) {\n\t\t\tplane = clippingPlanes[ i ];\n\t\t\tif ( dot( vClipPosition, plane.xyz ) > plane.w ) discard;\n\t\t}\n\t\t#pragma unroll_loop_end\n\t\t#if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES\n\t\t\tbool clipped = true;\n\t\t\t#pragma unroll_loop_start\n\t\t\tfor ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) {\n\t\t\t\tplane = clippingPlanes[ i ];\n\t\t\t\tclipped = ( dot( vClipPosition, plane.xyz ) > plane.w ) && clipped;\n\t\t\t}\n\t\t\t#pragma unroll_loop_end\n\t\t\tif ( clipped ) discard;\n\t\t#endif\n\t#endif\n#endif";
  8180. var clipping_planes_pars_fragment = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n\tuniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];\n#endif";
  8181. var clipping_planes_pars_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n#endif";
  8182. var clipping_planes_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvClipPosition = - mvPosition.xyz;\n#endif";
  8183. var color_fragment = "#if defined( USE_COLOR_ALPHA )\n\tdiffuseColor *= vColor;\n#elif defined( USE_COLOR )\n\tdiffuseColor.rgb *= vColor;\n#endif";
  8184. var color_pars_fragment = "#if defined( USE_COLOR_ALPHA )\n\tvarying vec4 vColor;\n#elif defined( USE_COLOR )\n\tvarying vec3 vColor;\n#endif";
  8185. 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";
  8186. 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";
  8187. 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; }\nvec3 pow2( const in vec3 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 v ) { return dot( v, vec3( 0.3333333 ) ); }\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};\n#ifdef USE_ALPHAHASH\n\tvarying vec3 vPosition;\n#endif\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 luminance( const in vec3 rgb ) {\n\tconst vec3 weights = vec3( 0.2126729, 0.7151522, 0.0721750 );\n\treturn dot( weights, 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}\nvec3 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 F_Schlick( const in float 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} // validated";
  8188. 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\thighp vec2 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 cubeUV_r0 1.0\n\t#define cubeUV_m0 - 2.0\n\t#define cubeUV_r1 0.8\n\t#define cubeUV_m1 - 1.0\n\t#define cubeUV_r4 0.4\n\t#define cubeUV_m4 2.0\n\t#define cubeUV_r5 0.305\n\t#define cubeUV_m5 3.0\n\t#define cubeUV_r6 0.21\n\t#define cubeUV_m6 4.0\n\tfloat roughnessToMip( float roughness ) {\n\t\tfloat mip = 0.0;\n\t\tif ( roughness >= cubeUV_r1 ) {\n\t\t\tmip = ( cubeUV_r0 - roughness ) * ( cubeUV_m1 - cubeUV_m0 ) / ( cubeUV_r0 - cubeUV_r1 ) + cubeUV_m0;\n\t\t} else if ( roughness >= cubeUV_r4 ) {\n\t\t\tmip = ( cubeUV_r1 - roughness ) * ( cubeUV_m4 - cubeUV_m1 ) / ( cubeUV_r1 - cubeUV_r4 ) + cubeUV_m1;\n\t\t} else if ( roughness >= cubeUV_r5 ) {\n\t\t\tmip = ( cubeUV_r4 - roughness ) * ( cubeUV_m5 - cubeUV_m4 ) / ( cubeUV_r4 - cubeUV_r5 ) + cubeUV_m4;\n\t\t} else if ( roughness >= cubeUV_r6 ) {\n\t\t\tmip = ( cubeUV_r5 - roughness ) * ( cubeUV_m6 - cubeUV_m5 ) / ( cubeUV_r5 - cubeUV_r6 ) + cubeUV_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 ), cubeUV_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";
  8189. var defaultnormal_vertex = "vec3 transformedNormal = objectNormal;\n#ifdef USE_TANGENT\n\tvec3 transformedTangent = objectTangent;\n#endif\n#ifdef USE_BATCHING\n\tmat3 bm = mat3( batchingMatrix );\n\ttransformedNormal /= vec3( dot( bm[ 0 ], bm[ 0 ] ), dot( bm[ 1 ], bm[ 1 ] ), dot( bm[ 2 ], bm[ 2 ] ) );\n\ttransformedNormal = bm * transformedNormal;\n\t#ifdef USE_TANGENT\n\t\ttransformedTangent = bm * transformedTangent;\n\t#endif\n#endif\n#ifdef USE_INSTANCING\n\tmat3 im = mat3( instanceMatrix );\n\ttransformedNormal /= vec3( dot( im[ 0 ], im[ 0 ] ), dot( im[ 1 ], im[ 1 ] ), dot( im[ 2 ], im[ 2 ] ) );\n\ttransformedNormal = im * transformedNormal;\n\t#ifdef USE_TANGENT\n\t\ttransformedTangent = im * transformedTangent;\n\t#endif\n#endif\ntransformedNormal = normalMatrix * transformedNormal;\n#ifdef FLIP_SIDED\n\ttransformedNormal = - transformedNormal;\n#endif\n#ifdef USE_TANGENT\n\ttransformedTangent = ( modelViewMatrix * vec4( transformedTangent, 0.0 ) ).xyz;\n\t#ifdef FLIP_SIDED\n\t\ttransformedTangent = - transformedTangent;\n\t#endif\n#endif";
  8190. var displacementmap_pars_vertex = "#ifdef USE_DISPLACEMENTMAP\n\tuniform sampler2D displacementMap;\n\tuniform float displacementScale;\n\tuniform float displacementBias;\n#endif";
  8191. var displacementmap_vertex = "#ifdef USE_DISPLACEMENTMAP\n\ttransformed += normalize( objectNormal ) * ( texture2D( displacementMap, vDisplacementMapUv ).x * displacementScale + displacementBias );\n#endif";
  8192. var emissivemap_fragment = "#ifdef USE_EMISSIVEMAP\n\tvec4 emissiveColor = texture2D( emissiveMap, vEmissiveMapUv );\n\ttotalEmissiveRadiance *= emissiveColor.rgb;\n#endif";
  8193. var emissivemap_pars_fragment = "#ifdef USE_EMISSIVEMAP\n\tuniform sampler2D emissiveMap;\n#endif";
  8194. var colorspace_fragment = "gl_FragColor = linearToOutputTexel( gl_FragColor );";
  8195. var colorspace_pars_fragment = "\nconst mat3 LINEAR_SRGB_TO_LINEAR_DISPLAY_P3 = mat3(\n\tvec3( 0.8224621, 0.177538, 0.0 ),\n\tvec3( 0.0331941, 0.9668058, 0.0 ),\n\tvec3( 0.0170827, 0.0723974, 0.9105199 )\n);\nconst mat3 LINEAR_DISPLAY_P3_TO_LINEAR_SRGB = mat3(\n\tvec3( 1.2249401, - 0.2249404, 0.0 ),\n\tvec3( - 0.0420569, 1.0420571, 0.0 ),\n\tvec3( - 0.0196376, - 0.0786361, 1.0982735 )\n);\nvec4 LinearSRGBToLinearDisplayP3( in vec4 value ) {\n\treturn vec4( value.rgb * LINEAR_SRGB_TO_LINEAR_DISPLAY_P3, value.a );\n}\nvec4 LinearDisplayP3ToLinearSRGB( in vec4 value ) {\n\treturn vec4( value.rgb * LINEAR_DISPLAY_P3_TO_LINEAR_SRGB, value.a );\n}\nvec4 LinearTransferOETF( in vec4 value ) {\n\treturn value;\n}\nvec4 sRGBTransferOETF( in vec4 value ) {\n\treturn vec4( mix( pow( value.rgb, vec3( 0.41666 ) ) * 1.055 - vec3( 0.055 ), value.rgb * 12.92, vec3( lessThanEqual( value.rgb, vec3( 0.0031308 ) ) ) ), value.a );\n}\nvec4 LinearToLinear( in vec4 value ) {\n\treturn value;\n}\nvec4 LinearTosRGB( in vec4 value ) {\n\treturn sRGBTransferOETF( value );\n}";
  8196. 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#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";
  8197. 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";
  8198. var envmap_pars_fragment = "#ifdef USE_ENVMAP\n\tuniform float reflectivity;\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT )\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";
  8199. var envmap_pars_vertex = "#ifdef USE_ENVMAP\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT )\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";
  8200. 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";
  8201. var fog_vertex = "#ifdef USE_FOG\n\tvFogDepth = - mvPosition.z;\n#endif";
  8202. var fog_pars_vertex = "#ifdef USE_FOG\n\tvarying float vFogDepth;\n#endif";
  8203. 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";
  8204. 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";
  8205. 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\tvec2 fw = fwidth( coord ) * 0.5;\n\t\treturn mix( vec3( 0.7 ), vec3( 1.0 ), smoothstep( 0.7 - fw.x, 0.7 + fw.x, coord.x ) );\n\t#endif\n}";
  8206. var lightmap_fragment = "#ifdef USE_LIGHTMAP\n\tvec4 lightMapTexel = texture2D( lightMap, vLightMapUv );\n\tvec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity;\n\treflectedLight.indirectDiffuse += lightMapIrradiance;\n#endif";
  8207. var lightmap_pars_fragment = "#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif";
  8208. var lights_lambert_fragment = "LambertMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularStrength = specularStrength;";
  8209. var lights_lambert_pars_fragment = "varying vec3 vViewPosition;\nstruct LambertMaterial {\n\tvec3 diffuseColor;\n\tfloat specularStrength;\n};\nvoid RE_Direct_Lambert( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in LambertMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometryNormal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Lambert( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in LambertMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_Lambert\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Lambert";
  8210. var lights_pars_begin = "uniform bool receiveShadow;\nuniform vec3 ambientLightColor;\n#if defined( USE_LIGHT_PROBES )\n\tuniform vec3 lightProbe[ 9 ];\n#endif\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 ( LEGACY_LIGHTS )\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#else\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#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, 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 vec3 geometryPosition, out IncidentLight light ) {\n\t\tvec3 lVector = pointLight.position - geometryPosition;\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 vec3 geometryPosition, out IncidentLight light ) {\n\t\tvec3 lVector = spotLight.position - geometryPosition;\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";
  8211. var envmap_physical_pars_fragment = "#ifdef USE_ENVMAP\n\tvec3 getIBLIrradiance( const in vec3 normal ) {\n\t\t#ifdef 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#ifdef 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\t#ifdef USE_ANISOTROPY\n\t\tvec3 getIBLAnisotropyRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness, const in vec3 bitangent, const in float anisotropy ) {\n\t\t\t#ifdef ENVMAP_TYPE_CUBE_UV\n\t\t\t\tvec3 bentNormal = cross( bitangent, viewDir );\n\t\t\t\tbentNormal = normalize( cross( bentNormal, bitangent ) );\n\t\t\t\tbentNormal = normalize( mix( bentNormal, normal, pow2( pow2( 1.0 - anisotropy * ( 1.0 - roughness ) ) ) ) );\n\t\t\t\treturn getIBLRadiance( viewDir, bentNormal, roughness );\n\t\t\t#else\n\t\t\t\treturn vec3( 0.0 );\n\t\t\t#endif\n\t\t}\n\t#endif\n#endif";
  8212. var lights_toon_fragment = "ToonMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;";
  8213. var lights_toon_pars_fragment = "varying vec3 vViewPosition;\nstruct ToonMaterial {\n\tvec3 diffuseColor;\n};\nvoid RE_Direct_Toon( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {\n\tvec3 irradiance = getGradientIrradiance( geometryNormal, directLight.direction ) * directLight.color;\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Toon( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, 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";
  8214. var lights_phong_fragment = "BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;";
  8215. 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 vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometryNormal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n\treflectedLight.directSpecular += irradiance * BRDF_BlinnPhong( directLight.direction, geometryViewDir, geometryNormal, material.specularColor, material.specularShininess ) * material.specularStrength;\n}\nvoid RE_IndirectDiffuse_BlinnPhong( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, 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";
  8216. var lights_physical_fragment = "PhysicalMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb * ( 1.0 - metalnessFactor );\nvec3 dxy = max( abs( dFdx( nonPerturbedNormal ) ), abs( dFdy( nonPerturbedNormal ) ) );\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\tmaterial.ior = ior;\n\t#ifdef USE_SPECULAR\n\t\tfloat specularIntensityFactor = specularIntensity;\n\t\tvec3 specularColorFactor = specularColor;\n\t\t#ifdef USE_SPECULAR_COLORMAP\n\t\t\tspecularColorFactor *= texture2D( specularColorMap, vSpecularColorMapUv ).rgb;\n\t\t#endif\n\t\t#ifdef USE_SPECULAR_INTENSITYMAP\n\t\t\tspecularIntensityFactor *= texture2D( specularIntensityMap, vSpecularIntensityMapUv ).a;\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( ( material.ior - 1.0 ) / ( material.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, vClearcoatMapUv ).x;\n\t#endif\n\t#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\t\tmaterial.clearcoatRoughness *= texture2D( clearcoatRoughnessMap, vClearcoatRoughnessMapUv ).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_IRIDESCENCE\n\tmaterial.iridescence = iridescence;\n\tmaterial.iridescenceIOR = iridescenceIOR;\n\t#ifdef USE_IRIDESCENCEMAP\n\t\tmaterial.iridescence *= texture2D( iridescenceMap, vIridescenceMapUv ).r;\n\t#endif\n\t#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\t\tmaterial.iridescenceThickness = (iridescenceThicknessMaximum - iridescenceThicknessMinimum) * texture2D( iridescenceThicknessMap, vIridescenceThicknessMapUv ).g + iridescenceThicknessMinimum;\n\t#else\n\t\tmaterial.iridescenceThickness = iridescenceThicknessMaximum;\n\t#endif\n#endif\n#ifdef USE_SHEEN\n\tmaterial.sheenColor = sheenColor;\n\t#ifdef USE_SHEEN_COLORMAP\n\t\tmaterial.sheenColor *= texture2D( sheenColorMap, vSheenColorMapUv ).rgb;\n\t#endif\n\tmaterial.sheenRoughness = clamp( sheenRoughness, 0.07, 1.0 );\n\t#ifdef USE_SHEEN_ROUGHNESSMAP\n\t\tmaterial.sheenRoughness *= texture2D( sheenRoughnessMap, vSheenRoughnessMapUv ).a;\n\t#endif\n#endif\n#ifdef USE_ANISOTROPY\n\t#ifdef USE_ANISOTROPYMAP\n\t\tmat2 anisotropyMat = mat2( anisotropyVector.x, anisotropyVector.y, - anisotropyVector.y, anisotropyVector.x );\n\t\tvec3 anisotropyPolar = texture2D( anisotropyMap, vAnisotropyMapUv ).rgb;\n\t\tvec2 anisotropyV = anisotropyMat * normalize( 2.0 * anisotropyPolar.rg - vec2( 1.0 ) ) * anisotropyPolar.b;\n\t#else\n\t\tvec2 anisotropyV = anisotropyVector;\n\t#endif\n\tmaterial.anisotropy = length( anisotropyV );\n\tif( material.anisotropy == 0.0 ) {\n\t\tanisotropyV = vec2( 1.0, 0.0 );\n\t} else {\n\t\tanisotropyV /= material.anisotropy;\n\t\tmaterial.anisotropy = saturate( material.anisotropy );\n\t}\n\tmaterial.alphaT = mix( pow2( material.roughness ), 1.0, pow2( material.anisotropy ) );\n\tmaterial.anisotropyT = tbn[ 0 ] * anisotropyV.x + tbn[ 1 ] * anisotropyV.y;\n\tmaterial.anisotropyB = tbn[ 1 ] * anisotropyV.x - tbn[ 0 ] * anisotropyV.y;\n#endif";
  8217. 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_IRIDESCENCE\n\t\tfloat iridescence;\n\t\tfloat iridescenceIOR;\n\t\tfloat iridescenceThickness;\n\t\tvec3 iridescenceFresnel;\n\t\tvec3 iridescenceF0;\n\t#endif\n\t#ifdef USE_SHEEN\n\t\tvec3 sheenColor;\n\t\tfloat sheenRoughness;\n\t#endif\n\t#ifdef IOR\n\t\tfloat ior;\n\t#endif\n\t#ifdef USE_TRANSMISSION\n\t\tfloat transmission;\n\t\tfloat transmissionAlpha;\n\t\tfloat thickness;\n\t\tfloat attenuationDistance;\n\t\tvec3 attenuationColor;\n\t#endif\n\t#ifdef USE_ANISOTROPY\n\t\tfloat anisotropy;\n\t\tfloat alphaT;\n\t\tvec3 anisotropyT;\n\t\tvec3 anisotropyB;\n\t#endif\n};\nvec3 clearcoatSpecularDirect = vec3( 0.0 );\nvec3 clearcoatSpecularIndirect = vec3( 0.0 );\nvec3 sheenSpecularDirect = vec3( 0.0 );\nvec3 sheenSpecularIndirect = vec3(0.0 );\nvec3 Schlick_to_F0( const in vec3 f, const in float f90, const in float dotVH ) {\n float x = clamp( 1.0 - dotVH, 0.0, 1.0 );\n float x2 = x * x;\n float x5 = clamp( x * x2 * x2, 0.0, 0.9999 );\n return ( f - vec3( f90 ) * x5 ) / ( 1.0 - x5 );\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}\n#ifdef USE_ANISOTROPY\n\tfloat V_GGX_SmithCorrelated_Anisotropic( const in float alphaT, const in float alphaB, const in float dotTV, const in float dotBV, const in float dotTL, const in float dotBL, const in float dotNV, const in float dotNL ) {\n\t\tfloat gv = dotNL * length( vec3( alphaT * dotTV, alphaB * dotBV, dotNV ) );\n\t\tfloat gl = dotNV * length( vec3( alphaT * dotTL, alphaB * dotBL, dotNL ) );\n\t\tfloat v = 0.5 / ( gv + gl );\n\t\treturn saturate(v);\n\t}\n\tfloat D_GGX_Anisotropic( const in float alphaT, const in float alphaB, const in float dotNH, const in float dotTH, const in float dotBH ) {\n\t\tfloat a2 = alphaT * alphaB;\n\t\thighp vec3 v = vec3( alphaB * dotTH, alphaT * dotBH, a2 * dotNH );\n\t\thighp float v2 = dot( v, v );\n\t\tfloat w2 = a2 / v2;\n\t\treturn RECIPROCAL_PI * a2 * pow2 ( w2 );\n\t}\n#endif\n#ifdef USE_CLEARCOAT\n\tvec3 BRDF_GGX_Clearcoat( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material) {\n\t\tvec3 f0 = material.clearcoatF0;\n\t\tfloat f90 = material.clearcoatF90;\n\t\tfloat roughness = material.clearcoatRoughness;\n\t\tfloat alpha = pow2( roughness );\n\t\tvec3 halfDir = normalize( lightDir + viewDir );\n\t\tfloat dotNL = saturate( dot( normal, lightDir ) );\n\t\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\t\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\t\tfloat dotVH = saturate( dot( viewDir, halfDir ) );\n\t\tvec3 F = F_Schlick( f0, f90, dotVH );\n\t\tfloat V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n\t\tfloat D = D_GGX( alpha, dotNH );\n\t\treturn F * ( V * D );\n\t}\n#endif\nvec3 BRDF_GGX( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material ) {\n\tvec3 f0 = material.specularColor;\n\tfloat f90 = material.specularF90;\n\tfloat roughness = material.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\t#ifdef USE_IRIDESCENCE\n\t\tF = mix( F, material.iridescenceFresnel, material.iridescence );\n\t#endif\n\t#ifdef USE_ANISOTROPY\n\t\tfloat dotTL = dot( material.anisotropyT, lightDir );\n\t\tfloat dotTV = dot( material.anisotropyT, viewDir );\n\t\tfloat dotTH = dot( material.anisotropyT, halfDir );\n\t\tfloat dotBL = dot( material.anisotropyB, lightDir );\n\t\tfloat dotBV = dot( material.anisotropyB, viewDir );\n\t\tfloat dotBH = dot( material.anisotropyB, halfDir );\n\t\tfloat V = V_GGX_SmithCorrelated_Anisotropic( material.alphaT, alpha, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL );\n\t\tfloat D = D_GGX_Anisotropic( material.alphaT, alpha, dotNH, dotTH, dotBH );\n\t#else\n\t\tfloat V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n\t\tfloat D = D_GGX( alpha, dotNH );\n\t#endif\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}\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\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}\n#ifdef USE_IRIDESCENCE\nvoid computeMultiscatteringIridescence( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float iridescence, const in vec3 iridescenceF0, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) {\n#else\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#endif\n\tvec2 fab = DFGApprox( normal, viewDir, roughness );\n\t#ifdef USE_IRIDESCENCE\n\t\tvec3 Fr = mix( specularColor, iridescenceF0, iridescence );\n\t#else\n\t\tvec3 Fr = specularColor;\n\t#endif\n\tvec3 FssEss = Fr * fab.x + specularF90 * fab.y;\n\tfloat Ess = fab.x + fab.y;\n\tfloat Ems = 1.0 - Ess;\n\tvec3 Favg = Fr + ( 1.0 - Fr ) * 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 vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\t\tvec3 normal = geometryNormal;\n\t\tvec3 viewDir = geometryViewDir;\n\t\tvec3 position = geometryPosition;\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 vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometryNormal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\t#ifdef USE_CLEARCOAT\n\t\tfloat dotNLcc = saturate( dot( geometryClearcoatNormal, directLight.direction ) );\n\t\tvec3 ccIrradiance = dotNLcc * directLight.color;\n\t\tclearcoatSpecularDirect += ccIrradiance * BRDF_GGX_Clearcoat( directLight.direction, geometryViewDir, geometryClearcoatNormal, material );\n\t#endif\n\t#ifdef USE_SHEEN\n\t\tsheenSpecularDirect += irradiance * BRDF_Sheen( directLight.direction, geometryViewDir, geometryNormal, material.sheenColor, material.sheenRoughness );\n\t#endif\n\treflectedLight.directSpecular += irradiance * BRDF_GGX( directLight.direction, geometryViewDir, geometryNormal, material );\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Physical( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, 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 vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight) {\n\t#ifdef USE_CLEARCOAT\n\t\tclearcoatSpecularIndirect += clearcoatRadiance * EnvironmentBRDF( geometryClearcoatNormal, geometryViewDir, material.clearcoatF0, material.clearcoatF90, material.clearcoatRoughness );\n\t#endif\n\t#ifdef USE_SHEEN\n\t\tsheenSpecularIndirect += irradiance * material.sheenColor * IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness );\n\t#endif\n\tvec3 singleScattering = vec3( 0.0 );\n\tvec3 multiScattering = vec3( 0.0 );\n\tvec3 cosineWeightedIrradiance = irradiance * RECIPROCAL_PI;\n\t#ifdef USE_IRIDESCENCE\n\t\tcomputeMultiscatteringIridescence( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.iridescence, material.iridescenceFresnel, material.roughness, singleScattering, multiScattering );\n\t#else\n\t\tcomputeMultiscattering( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.roughness, singleScattering, multiScattering );\n\t#endif\n\tvec3 totalScattering = singleScattering + multiScattering;\n\tvec3 diffuse = material.diffuseColor * ( 1.0 - max( max( totalScattering.r, totalScattering.g ), totalScattering.b ) );\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}";
  8218. var lights_fragment_begin = "\nvec3 geometryPosition = - vViewPosition;\nvec3 geometryNormal = normal;\nvec3 geometryViewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition );\nvec3 geometryClearcoatNormal = vec3( 0.0 );\n#ifdef USE_CLEARCOAT\n\tgeometryClearcoatNormal = clearcoatNormal;\n#endif\n#ifdef USE_IRIDESCENCE\n\tfloat dotNVi = saturate( dot( normal, geometryViewDir ) );\n\tif ( material.iridescenceThickness == 0.0 ) {\n\t\tmaterial.iridescence = 0.0;\n\t} else {\n\t\tmaterial.iridescence = saturate( material.iridescence );\n\t}\n\tif ( material.iridescence > 0.0 ) {\n\t\tmaterial.iridescenceFresnel = evalIridescence( 1.0, material.iridescenceIOR, dotNVi, material.iridescenceThickness, material.specularColor );\n\t\tmaterial.iridescenceF0 = Schlick_to_F0( material.iridescenceFresnel, 1.0, dotNVi );\n\t}\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, geometryPosition, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS )\n\t\tpointLightShadow = pointLightShadows[ i ];\n\t\tdirectLight.color *= ( 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, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, 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\tvec4 spotColor;\n\tvec3 spotLightCoord;\n\tbool inSpotLightMap;\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, geometryPosition, directLight );\n\t\t#if ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS )\n\t\t#define SPOT_LIGHT_MAP_INDEX UNROLLED_LOOP_INDEX\n\t\t#elif ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n\t\t#define SPOT_LIGHT_MAP_INDEX NUM_SPOT_LIGHT_MAPS\n\t\t#else\n\t\t#define SPOT_LIGHT_MAP_INDEX ( UNROLLED_LOOP_INDEX - NUM_SPOT_LIGHT_SHADOWS + NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS )\n\t\t#endif\n\t\t#if ( SPOT_LIGHT_MAP_INDEX < NUM_SPOT_LIGHT_MAPS )\n\t\t\tspotLightCoord = vSpotLightCoord[ i ].xyz / vSpotLightCoord[ i ].w;\n\t\t\tinSpotLightMap = all( lessThan( abs( spotLightCoord * 2. - 1. ), vec3( 1.0 ) ) );\n\t\t\tspotColor = texture2D( spotLightMap[ SPOT_LIGHT_MAP_INDEX ], spotLightCoord.xy );\n\t\t\tdirectLight.color = inSpotLightMap ? directLight.color * spotColor.rgb : directLight.color;\n\t\t#endif\n\t\t#undef SPOT_LIGHT_MAP_INDEX\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n\t\tspotLightShadow = spotLightShadows[ i ];\n\t\tdirectLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotLightCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, 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, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS )\n\t\tdirectionalLightShadow = directionalLightShadows[ i ];\n\t\tdirectLight.color *= ( 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, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, 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, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, 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\t#if defined( USE_LIGHT_PROBES )\n\t\tirradiance += getLightProbeIrradiance( lightProbe, geometryNormal );\n\t#endif\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 ], geometryNormal );\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";
  8219. var lights_fragment_maps = "#if defined( RE_IndirectDiffuse )\n\t#ifdef USE_LIGHTMAP\n\t\tvec4 lightMapTexel = texture2D( lightMap, vLightMapUv );\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( geometryNormal );\n\t#endif\n#endif\n#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular )\n\t#ifdef USE_ANISOTROPY\n\t\tradiance += getIBLAnisotropyRadiance( geometryViewDir, geometryNormal, material.roughness, material.anisotropyB, material.anisotropy );\n\t#else\n\t\tradiance += getIBLRadiance( geometryViewDir, geometryNormal, material.roughness );\n\t#endif\n\t#ifdef USE_CLEARCOAT\n\t\tclearcoatRadiance += getIBLRadiance( geometryViewDir, geometryClearcoatNormal, material.clearcoatRoughness );\n\t#endif\n#endif";
  8220. var lights_fragment_end = "#if defined( RE_IndirectDiffuse )\n\tRE_IndirectDiffuse( irradiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n#endif\n#if defined( RE_IndirectSpecular )\n\tRE_IndirectSpecular( radiance, iblIrradiance, clearcoatRadiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n#endif";
  8221. 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";
  8222. 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";
  8223. 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";
  8224. 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";
  8225. var map_fragment = "#ifdef USE_MAP\n\tvec4 sampledDiffuseColor = texture2D( map, vMapUv );\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\n\t#endif\n\tdiffuseColor *= sampledDiffuseColor;\n#endif";
  8226. var map_pars_fragment = "#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif";
  8227. var map_particle_fragment = "#if defined( USE_MAP ) || defined( USE_ALPHAMAP )\n\t#if defined( USE_POINTS_UV )\n\t\tvec2 uv = vUv;\n\t#else\n\t\tvec2 uv = ( uvTransform * vec3( gl_PointCoord.x, 1.0 - gl_PointCoord.y, 1 ) ).xy;\n\t#endif\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";
  8228. var map_particle_pars_fragment = "#if defined( USE_POINTS_UV )\n\tvarying vec2 vUv;\n#else\n\t#if defined( USE_MAP ) || defined( USE_ALPHAMAP )\n\t\tuniform mat3 uvTransform;\n\t#endif\n#endif\n#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif\n#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif";
  8229. var metalnessmap_fragment = "float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n\tvec4 texelMetalness = texture2D( metalnessMap, vMetalnessMapUv );\n\tmetalnessFactor *= texelMetalness.b;\n#endif";
  8230. var metalnessmap_pars_fragment = "#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif";
  8231. var morphinstance_vertex = "#ifdef USE_INSTANCING_MORPH\n\tfloat morphTargetInfluences[MORPHTARGETS_COUNT];\n\tfloat morphTargetBaseInfluence = texelFetch( morphTexture, ivec2( 0, gl_InstanceID ), 0 ).r;\n\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\tmorphTargetInfluences[i] = texelFetch( morphTexture, ivec2( i + 1, gl_InstanceID ), 0 ).r;\n\t}\n#endif";
  8232. 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";
  8233. 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";
  8234. var morphtarget_pars_vertex = "#ifdef USE_MORPHTARGETS\n\t#ifndef USE_INSTANCING_MORPH\n\t\tuniform float morphTargetBaseInfluence;\n\t#endif\n\t#ifdef MORPHTARGETS_TEXTURE\n\t\t#ifndef USE_INSTANCING_MORPH\n\t\t\tuniform float morphTargetInfluences[ MORPHTARGETS_COUNT ];\n\t\t#endif\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";
  8235. 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";
  8236. var normal_fragment_begin = "float faceDirection = gl_FrontFacing ? 1.0 : - 1.0;\n#ifdef FLAT_SHADED\n\tvec3 fdx = dFdx( vViewPosition );\n\tvec3 fdy = dFdy( vViewPosition );\n\tvec3 normal = normalize( cross( fdx, fdy ) );\n#else\n\tvec3 normal = normalize( vNormal );\n\t#ifdef DOUBLE_SIDED\n\t\tnormal *= faceDirection;\n\t#endif\n#endif\n#if defined( USE_NORMALMAP_TANGENTSPACE ) || defined( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY )\n\t#ifdef USE_TANGENT\n\t\tmat3 tbn = mat3( normalize( vTangent ), normalize( vBitangent ), normal );\n\t#else\n\t\tmat3 tbn = getTangentFrame( - vViewPosition, normal,\n\t\t#if defined( USE_NORMALMAP )\n\t\t\tvNormalMapUv\n\t\t#elif defined( USE_CLEARCOAT_NORMALMAP )\n\t\t\tvClearcoatNormalMapUv\n\t\t#else\n\t\t\tvUv\n\t\t#endif\n\t\t);\n\t#endif\n\t#if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED )\n\t\ttbn[0] *= faceDirection;\n\t\ttbn[1] *= faceDirection;\n\t#endif\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n\t#ifdef USE_TANGENT\n\t\tmat3 tbn2 = mat3( normalize( vTangent ), normalize( vBitangent ), normal );\n\t#else\n\t\tmat3 tbn2 = getTangentFrame( - vViewPosition, normal, vClearcoatNormalMapUv );\n\t#endif\n\t#if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED )\n\t\ttbn2[0] *= faceDirection;\n\t\ttbn2[1] *= faceDirection;\n\t#endif\n#endif\nvec3 nonPerturbedNormal = normal;";
  8237. var normal_fragment_maps = "#ifdef USE_NORMALMAP_OBJECTSPACE\n\tnormal = texture2D( normalMap, vNormalMapUv ).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( USE_NORMALMAP_TANGENTSPACE )\n\tvec3 mapN = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0;\n\tmapN.xy *= normalScale;\n\tnormal = normalize( tbn * mapN );\n#elif defined( USE_BUMPMAP )\n\tnormal = perturbNormalArb( - vViewPosition, normal, dHdxy_fwd(), faceDirection );\n#endif";
  8238. 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";
  8239. 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";
  8240. 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";
  8241. var normalmap_pars_fragment = "#ifdef USE_NORMALMAP\n\tuniform sampler2D normalMap;\n\tuniform vec2 normalScale;\n#endif\n#ifdef USE_NORMALMAP_OBJECTSPACE\n\tuniform mat3 normalMatrix;\n#endif\n#if ! defined ( USE_TANGENT ) && ( defined ( USE_NORMALMAP_TANGENTSPACE ) || defined ( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY ) )\n\tmat3 getTangentFrame( vec3 eye_pos, vec3 surf_norm, vec2 uv ) {\n\t\tvec3 q0 = dFdx( eye_pos.xyz );\n\t\tvec3 q1 = dFdy( eye_pos.xyz );\n\t\tvec2 st0 = dFdx( uv.st );\n\t\tvec2 st1 = dFdy( uv.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 : inversesqrt( det );\n\t\treturn mat3( T * scale, B * scale, N );\n\t}\n#endif";
  8242. var clearcoat_normal_fragment_begin = "#ifdef USE_CLEARCOAT\n\tvec3 clearcoatNormal = nonPerturbedNormal;\n#endif";
  8243. var clearcoat_normal_fragment_maps = "#ifdef USE_CLEARCOAT_NORMALMAP\n\tvec3 clearcoatMapN = texture2D( clearcoatNormalMap, vClearcoatNormalMapUv ).xyz * 2.0 - 1.0;\n\tclearcoatMapN.xy *= clearcoatNormalScale;\n\tclearcoatNormal = normalize( tbn2 * clearcoatMapN );\n#endif";
  8244. var clearcoat_pars_fragment = "#ifdef USE_CLEARCOATMAP\n\tuniform sampler2D clearcoatMap;\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n\tuniform sampler2D clearcoatNormalMap;\n\tuniform vec2 clearcoatNormalScale;\n#endif\n#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\tuniform sampler2D clearcoatRoughnessMap;\n#endif";
  8245. var iridescence_pars_fragment = "#ifdef USE_IRIDESCENCEMAP\n\tuniform sampler2D iridescenceMap;\n#endif\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\tuniform sampler2D iridescenceThicknessMap;\n#endif";
  8246. var opaque_fragment = "#ifdef OPAQUE\ndiffuseColor.a = 1.0;\n#endif\n#ifdef USE_TRANSMISSION\ndiffuseColor.a *= material.transmissionAlpha;\n#endif\ngl_FragColor = vec4( outgoingLight, diffuseColor.a );";
  8247. 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}\nvec2 packDepthToRG( in highp float v ) {\n\treturn packDepthToRGBA( v ).yx;\n}\nfloat unpackRGToDepth( const in highp vec2 v ) {\n\treturn unpackRGBAToDepth( vec4( v.xy, 0.0, 0.0 ) );\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 depth, const in float near, const in float far ) {\n\treturn depth * ( 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 depth, const in float near, const in float far ) {\n\treturn ( near * far ) / ( ( far - near ) * depth - far );\n}";
  8248. var premultiplied_alpha_fragment = "#ifdef PREMULTIPLIED_ALPHA\n\tgl_FragColor.rgb *= gl_FragColor.a;\n#endif";
  8249. var project_vertex = "vec4 mvPosition = vec4( transformed, 1.0 );\n#ifdef USE_BATCHING\n\tmvPosition = batchingMatrix * mvPosition;\n#endif\n#ifdef USE_INSTANCING\n\tmvPosition = instanceMatrix * mvPosition;\n#endif\nmvPosition = modelViewMatrix * mvPosition;\ngl_Position = projectionMatrix * mvPosition;";
  8250. var dithering_fragment = "#ifdef DITHERING\n\tgl_FragColor.rgb = dithering( gl_FragColor.rgb );\n#endif";
  8251. 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";
  8252. var roughnessmap_fragment = "float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n\tvec4 texelRoughness = texture2D( roughnessMap, vRoughnessMapUv );\n\troughnessFactor *= texelRoughness.g;\n#endif";
  8253. var roughnessmap_pars_fragment = "#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif";
  8254. var shadowmap_pars_fragment = "#if NUM_SPOT_LIGHT_COORDS > 0\n\tvarying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ];\n#endif\n#if NUM_SPOT_LIGHT_MAPS > 0\n\tuniform sampler2D spotLightMap[ NUM_SPOT_LIGHT_MAPS ];\n#endif\n#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\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\tbool inFrustum = shadowCoord.x >= 0.0 && shadowCoord.x <= 1.0 && shadowCoord.y >= 0.0 && shadowCoord.y <= 1.0;\n\t\tbool frustumTest = inFrustum && shadowCoord.z <= 1.0;\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";
  8255. var shadowmap_pars_vertex = "#if NUM_SPOT_LIGHT_COORDS > 0\n\tuniform mat4 spotLightMatrix[ NUM_SPOT_LIGHT_COORDS ];\n\tvarying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ];\n#endif\n#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\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";
  8256. var shadowmap_vertex = "#if ( defined( USE_SHADOWMAP ) && ( NUM_DIR_LIGHT_SHADOWS > 0 || NUM_POINT_LIGHT_SHADOWS > 0 ) ) || ( NUM_SPOT_LIGHT_COORDS > 0 )\n\tvec3 shadowWorldNormal = inverseTransformDirection( transformedNormal, viewMatrix );\n\tvec4 shadowWorldPosition;\n#endif\n#if defined( USE_SHADOWMAP )\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {\n\t\t\tshadowWorldPosition = worldPosition + vec4( shadowWorldNormal * directionalLightShadows[ i ].shadowNormalBias, 0 );\n\t\t\tvDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * shadowWorldPosition;\n\t\t}\n\t\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {\n\t\t\tshadowWorldPosition = worldPosition + vec4( shadowWorldNormal * pointLightShadows[ i ].shadowNormalBias, 0 );\n\t\t\tvPointShadowCoord[ i ] = pointShadowMatrix[ i ] * shadowWorldPosition;\n\t\t}\n\t\t#pragma unroll_loop_end\n\t#endif\n#endif\n#if NUM_SPOT_LIGHT_COORDS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHT_COORDS; i ++ ) {\n\t\tshadowWorldPosition = worldPosition;\n\t\t#if ( defined( USE_SHADOWMAP ) && UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n\t\t\tshadowWorldPosition.xyz += shadowWorldNormal * spotLightShadows[ i ].shadowNormalBias;\n\t\t#endif\n\t\tvSpotLightCoord[ i ] = spotLightMatrix[ i ] * shadowWorldPosition;\n\t}\n\t#pragma unroll_loop_end\n#endif";
  8257. 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, vSpotLightCoord[ 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}";
  8258. 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";
  8259. var skinning_pars_vertex = "#ifdef USE_SKINNING\n\tuniform mat4 bindMatrix;\n\tuniform mat4 bindMatrixInverse;\n\tuniform highp sampler2D boneTexture;\n\tmat4 getBoneMatrix( const in float i ) {\n\t\tint size = textureSize( boneTexture, 0 ).x;\n\t\tint j = int( i ) * 4;\n\t\tint x = j % size;\n\t\tint y = j / size;\n\t\tvec4 v1 = texelFetch( boneTexture, ivec2( x, y ), 0 );\n\t\tvec4 v2 = texelFetch( boneTexture, ivec2( x + 1, y ), 0 );\n\t\tvec4 v3 = texelFetch( boneTexture, ivec2( x + 2, y ), 0 );\n\t\tvec4 v4 = texelFetch( boneTexture, ivec2( x + 3, y ), 0 );\n\t\treturn mat4( v1, v2, v3, v4 );\n\t}\n#endif";
  8260. 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";
  8261. 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";
  8262. var specularmap_fragment = "float specularStrength;\n#ifdef USE_SPECULARMAP\n\tvec4 texelSpecular = texture2D( specularMap, vSpecularMapUv );\n\tspecularStrength = texelSpecular.r;\n#else\n\tspecularStrength = 1.0;\n#endif";
  8263. var specularmap_pars_fragment = "#ifdef USE_SPECULARMAP\n\tuniform sampler2D specularMap;\n#endif";
  8264. var tonemapping_fragment = "#if defined( TONE_MAPPING )\n\tgl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif";
  8265. 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 saturate( 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}\nconst mat3 LINEAR_REC2020_TO_LINEAR_SRGB = mat3(\n\tvec3( 1.6605, - 0.1246, - 0.0182 ),\n\tvec3( - 0.5876, 1.1329, - 0.1006 ),\n\tvec3( - 0.0728, - 0.0083, 1.1187 )\n);\nconst mat3 LINEAR_SRGB_TO_LINEAR_REC2020 = mat3(\n\tvec3( 0.6274, 0.0691, 0.0164 ),\n\tvec3( 0.3293, 0.9195, 0.0880 ),\n\tvec3( 0.0433, 0.0113, 0.8956 )\n);\nvec3 agxDefaultContrastApprox( vec3 x ) {\n\tvec3 x2 = x * x;\n\tvec3 x4 = x2 * x2;\n\treturn + 15.5 * x4 * x2\n\t\t- 40.14 * x4 * x\n\t\t+ 31.96 * x4\n\t\t- 6.868 * x2 * x\n\t\t+ 0.4298 * x2\n\t\t+ 0.1191 * x\n\t\t- 0.00232;\n}\nvec3 AgXToneMapping( vec3 color ) {\n\tconst mat3 AgXInsetMatrix = mat3(\n\t\tvec3( 0.856627153315983, 0.137318972929847, 0.11189821299995 ),\n\t\tvec3( 0.0951212405381588, 0.761241990602591, 0.0767994186031903 ),\n\t\tvec3( 0.0482516061458583, 0.101439036467562, 0.811302368396859 )\n\t);\n\tconst mat3 AgXOutsetMatrix = mat3(\n\t\tvec3( 1.1271005818144368, - 0.1413297634984383, - 0.14132976349843826 ),\n\t\tvec3( - 0.11060664309660323, 1.157823702216272, - 0.11060664309660294 ),\n\t\tvec3( - 0.016493938717834573, - 0.016493938717834257, 1.2519364065950405 )\n\t);\n\tconst float AgxMinEv = - 12.47393;\tconst float AgxMaxEv = 4.026069;\n\tcolor *= toneMappingExposure;\n\tcolor = LINEAR_SRGB_TO_LINEAR_REC2020 * color;\n\tcolor = AgXInsetMatrix * color;\n\tcolor = max( color, 1e-10 );\tcolor = log2( color );\n\tcolor = ( color - AgxMinEv ) / ( AgxMaxEv - AgxMinEv );\n\tcolor = clamp( color, 0.0, 1.0 );\n\tcolor = agxDefaultContrastApprox( color );\n\tcolor = AgXOutsetMatrix * color;\n\tcolor = pow( max( vec3( 0.0 ), color ), vec3( 2.2 ) );\n\tcolor = LINEAR_REC2020_TO_LINEAR_SRGB * color;\n\tcolor = clamp( color, 0.0, 1.0 );\n\treturn color;\n}\nvec3 NeutralToneMapping( vec3 color ) {\n\tfloat startCompression = 0.8 - 0.04;\n\tfloat desaturation = 0.15;\n\tcolor *= toneMappingExposure;\n\tfloat x = min(color.r, min(color.g, color.b));\n\tfloat offset = x < 0.08 ? x - 6.25 * x * x : 0.04;\n\tcolor -= offset;\n\tfloat peak = max(color.r, max(color.g, color.b));\n\tif (peak < startCompression) return color;\n\tfloat d = 1. - startCompression;\n\tfloat newPeak = 1. - d * d / (peak + d - startCompression);\n\tcolor *= newPeak / peak;\n\tfloat g = 1. - 1. / (desaturation * (peak - newPeak) + 1.);\n\treturn mix(color, vec3(1, 1, 1), g);\n}\nvec3 CustomToneMapping( vec3 color ) { return color; }";
  8266. var transmission_fragment = "#ifdef USE_TRANSMISSION\n\tmaterial.transmission = transmission;\n\tmaterial.transmissionAlpha = 1.0;\n\tmaterial.thickness = thickness;\n\tmaterial.attenuationDistance = attenuationDistance;\n\tmaterial.attenuationColor = attenuationColor;\n\t#ifdef USE_TRANSMISSIONMAP\n\t\tmaterial.transmission *= texture2D( transmissionMap, vTransmissionMapUv ).r;\n\t#endif\n\t#ifdef USE_THICKNESSMAP\n\t\tmaterial.thickness *= texture2D( thicknessMap, vThicknessMapUv ).g;\n\t#endif\n\tvec3 pos = vWorldPosition;\n\tvec3 v = normalize( cameraPosition - pos );\n\tvec3 n = inverseTransformDirection( normal, viewMatrix );\n\tvec4 transmitted = getIBLVolumeRefraction(\n\t\tn, v, material.roughness, material.diffuseColor, material.specularColor, material.specularF90,\n\t\tpos, modelMatrix, viewMatrix, projectionMatrix, material.ior, material.thickness,\n\t\tmaterial.attenuationColor, material.attenuationDistance );\n\tmaterial.transmissionAlpha = mix( material.transmissionAlpha, transmitted.a, material.transmission );\n\ttotalDiffuse = mix( totalDiffuse, transmitted.rgb, material.transmission );\n#endif";
  8267. 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\tfloat w0( float a ) {\n\t\treturn ( 1.0 / 6.0 ) * ( a * ( a * ( - a + 3.0 ) - 3.0 ) + 1.0 );\n\t}\n\tfloat w1( float a ) {\n\t\treturn ( 1.0 / 6.0 ) * ( a * a * ( 3.0 * a - 6.0 ) + 4.0 );\n\t}\n\tfloat w2( float a ){\n\t\treturn ( 1.0 / 6.0 ) * ( a * ( a * ( - 3.0 * a + 3.0 ) + 3.0 ) + 1.0 );\n\t}\n\tfloat w3( float a ) {\n\t\treturn ( 1.0 / 6.0 ) * ( a * a * a );\n\t}\n\tfloat g0( float a ) {\n\t\treturn w0( a ) + w1( a );\n\t}\n\tfloat g1( float a ) {\n\t\treturn w2( a ) + w3( a );\n\t}\n\tfloat h0( float a ) {\n\t\treturn - 1.0 + w1( a ) / ( w0( a ) + w1( a ) );\n\t}\n\tfloat h1( float a ) {\n\t\treturn 1.0 + w3( a ) / ( w2( a ) + w3( a ) );\n\t}\n\tvec4 bicubic( sampler2D tex, vec2 uv, vec4 texelSize, float lod ) {\n\t\tuv = uv * texelSize.zw + 0.5;\n\t\tvec2 iuv = floor( uv );\n\t\tvec2 fuv = fract( uv );\n\t\tfloat g0x = g0( fuv.x );\n\t\tfloat g1x = g1( fuv.x );\n\t\tfloat h0x = h0( fuv.x );\n\t\tfloat h1x = h1( fuv.x );\n\t\tfloat h0y = h0( fuv.y );\n\t\tfloat h1y = h1( fuv.y );\n\t\tvec2 p0 = ( vec2( iuv.x + h0x, iuv.y + h0y ) - 0.5 ) * texelSize.xy;\n\t\tvec2 p1 = ( vec2( iuv.x + h1x, iuv.y + h0y ) - 0.5 ) * texelSize.xy;\n\t\tvec2 p2 = ( vec2( iuv.x + h0x, iuv.y + h1y ) - 0.5 ) * texelSize.xy;\n\t\tvec2 p3 = ( vec2( iuv.x + h1x, iuv.y + h1y ) - 0.5 ) * texelSize.xy;\n\t\treturn g0( fuv.y ) * ( g0x * textureLod( tex, p0, lod ) + g1x * textureLod( tex, p1, lod ) ) +\n\t\t\tg1( fuv.y ) * ( g0x * textureLod( tex, p2, lod ) + g1x * textureLod( tex, p3, lod ) );\n\t}\n\tvec4 textureBicubic( sampler2D sampler, vec2 uv, float lod ) {\n\t\tvec2 fLodSize = vec2( textureSize( sampler, int( lod ) ) );\n\t\tvec2 cLodSize = vec2( textureSize( sampler, int( lod + 1.0 ) ) );\n\t\tvec2 fLodSizeInv = 1.0 / fLodSize;\n\t\tvec2 cLodSizeInv = 1.0 / cLodSize;\n\t\tvec4 fSample = bicubic( sampler, uv, vec4( fLodSizeInv, fLodSize ), floor( lod ) );\n\t\tvec4 cSample = bicubic( sampler, uv, vec4( cLodSizeInv, cLodSize ), ceil( lod ) );\n\t\treturn mix( fSample, cSample, fract( lod ) );\n\t}\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 lod = log2( transmissionSamplerSize.x ) * applyIorToRoughness( roughness, ior );\n\t\treturn textureBicubic( transmissionSamplerMap, fragCoord.xy, lod );\n\t}\n\tvec3 volumeAttenuation( const in float transmissionDistance, const in vec3 attenuationColor, const in float attenuationDistance ) {\n\t\tif ( isinf( attenuationDistance ) ) {\n\t\t\treturn vec3( 1.0 );\n\t\t} else {\n\t\t\tvec3 attenuationCoefficient = -log( attenuationColor ) / attenuationDistance;\n\t\t\tvec3 transmittance = exp( - attenuationCoefficient * transmissionDistance );\t\t\treturn transmittance;\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 transmittance = diffuseColor * volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance );\n\t\tvec3 attenuatedColor = transmittance * transmittedLight.rgb;\n\t\tvec3 F = EnvironmentBRDF( n, v, specularColor, specularF90, roughness );\n\t\tfloat transmittanceFactor = ( transmittance.r + transmittance.g + transmittance.b ) / 3.0;\n\t\treturn vec4( ( 1.0 - F ) * attenuatedColor, 1.0 - ( 1.0 - transmittedLight.a ) * transmittanceFactor );\n\t}\n#endif";
  8268. var uv_pars_fragment = "#if defined( USE_UV ) || defined( USE_ANISOTROPY )\n\tvarying vec2 vUv;\n#endif\n#ifdef USE_MAP\n\tvarying vec2 vMapUv;\n#endif\n#ifdef USE_ALPHAMAP\n\tvarying vec2 vAlphaMapUv;\n#endif\n#ifdef USE_LIGHTMAP\n\tvarying vec2 vLightMapUv;\n#endif\n#ifdef USE_AOMAP\n\tvarying vec2 vAoMapUv;\n#endif\n#ifdef USE_BUMPMAP\n\tvarying vec2 vBumpMapUv;\n#endif\n#ifdef USE_NORMALMAP\n\tvarying vec2 vNormalMapUv;\n#endif\n#ifdef USE_EMISSIVEMAP\n\tvarying vec2 vEmissiveMapUv;\n#endif\n#ifdef USE_METALNESSMAP\n\tvarying vec2 vMetalnessMapUv;\n#endif\n#ifdef USE_ROUGHNESSMAP\n\tvarying vec2 vRoughnessMapUv;\n#endif\n#ifdef USE_ANISOTROPYMAP\n\tvarying vec2 vAnisotropyMapUv;\n#endif\n#ifdef USE_CLEARCOATMAP\n\tvarying vec2 vClearcoatMapUv;\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n\tvarying vec2 vClearcoatNormalMapUv;\n#endif\n#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\tvarying vec2 vClearcoatRoughnessMapUv;\n#endif\n#ifdef USE_IRIDESCENCEMAP\n\tvarying vec2 vIridescenceMapUv;\n#endif\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\tvarying vec2 vIridescenceThicknessMapUv;\n#endif\n#ifdef USE_SHEEN_COLORMAP\n\tvarying vec2 vSheenColorMapUv;\n#endif\n#ifdef USE_SHEEN_ROUGHNESSMAP\n\tvarying vec2 vSheenRoughnessMapUv;\n#endif\n#ifdef USE_SPECULARMAP\n\tvarying vec2 vSpecularMapUv;\n#endif\n#ifdef USE_SPECULAR_COLORMAP\n\tvarying vec2 vSpecularColorMapUv;\n#endif\n#ifdef USE_SPECULAR_INTENSITYMAP\n\tvarying vec2 vSpecularIntensityMapUv;\n#endif\n#ifdef USE_TRANSMISSIONMAP\n\tuniform mat3 transmissionMapTransform;\n\tvarying vec2 vTransmissionMapUv;\n#endif\n#ifdef USE_THICKNESSMAP\n\tuniform mat3 thicknessMapTransform;\n\tvarying vec2 vThicknessMapUv;\n#endif";
  8269. var uv_pars_vertex = "#if defined( USE_UV ) || defined( USE_ANISOTROPY )\n\tvarying vec2 vUv;\n#endif\n#ifdef USE_MAP\n\tuniform mat3 mapTransform;\n\tvarying vec2 vMapUv;\n#endif\n#ifdef USE_ALPHAMAP\n\tuniform mat3 alphaMapTransform;\n\tvarying vec2 vAlphaMapUv;\n#endif\n#ifdef USE_LIGHTMAP\n\tuniform mat3 lightMapTransform;\n\tvarying vec2 vLightMapUv;\n#endif\n#ifdef USE_AOMAP\n\tuniform mat3 aoMapTransform;\n\tvarying vec2 vAoMapUv;\n#endif\n#ifdef USE_BUMPMAP\n\tuniform mat3 bumpMapTransform;\n\tvarying vec2 vBumpMapUv;\n#endif\n#ifdef USE_NORMALMAP\n\tuniform mat3 normalMapTransform;\n\tvarying vec2 vNormalMapUv;\n#endif\n#ifdef USE_DISPLACEMENTMAP\n\tuniform mat3 displacementMapTransform;\n\tvarying vec2 vDisplacementMapUv;\n#endif\n#ifdef USE_EMISSIVEMAP\n\tuniform mat3 emissiveMapTransform;\n\tvarying vec2 vEmissiveMapUv;\n#endif\n#ifdef USE_METALNESSMAP\n\tuniform mat3 metalnessMapTransform;\n\tvarying vec2 vMetalnessMapUv;\n#endif\n#ifdef USE_ROUGHNESSMAP\n\tuniform mat3 roughnessMapTransform;\n\tvarying vec2 vRoughnessMapUv;\n#endif\n#ifdef USE_ANISOTROPYMAP\n\tuniform mat3 anisotropyMapTransform;\n\tvarying vec2 vAnisotropyMapUv;\n#endif\n#ifdef USE_CLEARCOATMAP\n\tuniform mat3 clearcoatMapTransform;\n\tvarying vec2 vClearcoatMapUv;\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n\tuniform mat3 clearcoatNormalMapTransform;\n\tvarying vec2 vClearcoatNormalMapUv;\n#endif\n#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\tuniform mat3 clearcoatRoughnessMapTransform;\n\tvarying vec2 vClearcoatRoughnessMapUv;\n#endif\n#ifdef USE_SHEEN_COLORMAP\n\tuniform mat3 sheenColorMapTransform;\n\tvarying vec2 vSheenColorMapUv;\n#endif\n#ifdef USE_SHEEN_ROUGHNESSMAP\n\tuniform mat3 sheenRoughnessMapTransform;\n\tvarying vec2 vSheenRoughnessMapUv;\n#endif\n#ifdef USE_IRIDESCENCEMAP\n\tuniform mat3 iridescenceMapTransform;\n\tvarying vec2 vIridescenceMapUv;\n#endif\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\tuniform mat3 iridescenceThicknessMapTransform;\n\tvarying vec2 vIridescenceThicknessMapUv;\n#endif\n#ifdef USE_SPECULARMAP\n\tuniform mat3 specularMapTransform;\n\tvarying vec2 vSpecularMapUv;\n#endif\n#ifdef USE_SPECULAR_COLORMAP\n\tuniform mat3 specularColorMapTransform;\n\tvarying vec2 vSpecularColorMapUv;\n#endif\n#ifdef USE_SPECULAR_INTENSITYMAP\n\tuniform mat3 specularIntensityMapTransform;\n\tvarying vec2 vSpecularIntensityMapUv;\n#endif\n#ifdef USE_TRANSMISSIONMAP\n\tuniform mat3 transmissionMapTransform;\n\tvarying vec2 vTransmissionMapUv;\n#endif\n#ifdef USE_THICKNESSMAP\n\tuniform mat3 thicknessMapTransform;\n\tvarying vec2 vThicknessMapUv;\n#endif";
  8270. var uv_vertex = "#if defined( USE_UV ) || defined( USE_ANISOTROPY )\n\tvUv = vec3( uv, 1 ).xy;\n#endif\n#ifdef USE_MAP\n\tvMapUv = ( mapTransform * vec3( MAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_ALPHAMAP\n\tvAlphaMapUv = ( alphaMapTransform * vec3( ALPHAMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_LIGHTMAP\n\tvLightMapUv = ( lightMapTransform * vec3( LIGHTMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_AOMAP\n\tvAoMapUv = ( aoMapTransform * vec3( AOMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_BUMPMAP\n\tvBumpMapUv = ( bumpMapTransform * vec3( BUMPMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_NORMALMAP\n\tvNormalMapUv = ( normalMapTransform * vec3( NORMALMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_DISPLACEMENTMAP\n\tvDisplacementMapUv = ( displacementMapTransform * vec3( DISPLACEMENTMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_EMISSIVEMAP\n\tvEmissiveMapUv = ( emissiveMapTransform * vec3( EMISSIVEMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_METALNESSMAP\n\tvMetalnessMapUv = ( metalnessMapTransform * vec3( METALNESSMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_ROUGHNESSMAP\n\tvRoughnessMapUv = ( roughnessMapTransform * vec3( ROUGHNESSMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_ANISOTROPYMAP\n\tvAnisotropyMapUv = ( anisotropyMapTransform * vec3( ANISOTROPYMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_CLEARCOATMAP\n\tvClearcoatMapUv = ( clearcoatMapTransform * vec3( CLEARCOATMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n\tvClearcoatNormalMapUv = ( clearcoatNormalMapTransform * vec3( CLEARCOAT_NORMALMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\tvClearcoatRoughnessMapUv = ( clearcoatRoughnessMapTransform * vec3( CLEARCOAT_ROUGHNESSMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_IRIDESCENCEMAP\n\tvIridescenceMapUv = ( iridescenceMapTransform * vec3( IRIDESCENCEMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\tvIridescenceThicknessMapUv = ( iridescenceThicknessMapTransform * vec3( IRIDESCENCE_THICKNESSMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_SHEEN_COLORMAP\n\tvSheenColorMapUv = ( sheenColorMapTransform * vec3( SHEEN_COLORMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_SHEEN_ROUGHNESSMAP\n\tvSheenRoughnessMapUv = ( sheenRoughnessMapTransform * vec3( SHEEN_ROUGHNESSMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_SPECULARMAP\n\tvSpecularMapUv = ( specularMapTransform * vec3( SPECULARMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_SPECULAR_COLORMAP\n\tvSpecularColorMapUv = ( specularColorMapTransform * vec3( SPECULAR_COLORMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_SPECULAR_INTENSITYMAP\n\tvSpecularIntensityMapUv = ( specularIntensityMapTransform * vec3( SPECULAR_INTENSITYMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_TRANSMISSIONMAP\n\tvTransmissionMapUv = ( transmissionMapTransform * vec3( TRANSMISSIONMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_THICKNESSMAP\n\tvThicknessMapUv = ( thicknessMapTransform * vec3( THICKNESSMAP_UV, 1 ) ).xy;\n#endif";
  8271. var worldpos_vertex = "#if defined( USE_ENVMAP ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP ) || defined ( USE_TRANSMISSION ) || NUM_SPOT_LIGHT_COORDS > 0\n\tvec4 worldPosition = vec4( transformed, 1.0 );\n\t#ifdef USE_BATCHING\n\t\tworldPosition = batchingMatrix * worldPosition;\n\t#endif\n\t#ifdef USE_INSTANCING\n\t\tworldPosition = instanceMatrix * worldPosition;\n\t#endif\n\tworldPosition = modelMatrix * worldPosition;\n#endif";
  8272. const vertex$h = "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}";
  8273. const fragment$h = "uniform sampler2D t2D;\nuniform float backgroundIntensity;\nvarying vec2 vUv;\nvoid main() {\n\tvec4 texColor = texture2D( t2D, vUv );\n\t#ifdef DECODE_VIDEO_TEXTURE\n\t\ttexColor = vec4( mix( pow( texColor.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), texColor.rgb * 0.0773993808, vec3( lessThanEqual( texColor.rgb, vec3( 0.04045 ) ) ) ), texColor.w );\n\t#endif\n\ttexColor.rgb *= backgroundIntensity;\n\tgl_FragColor = texColor;\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n}";
  8274. const vertex$g = "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}";
  8275. const fragment$g = "#ifdef ENVMAP_TYPE_CUBE\n\tuniform samplerCube envMap;\n#elif defined( ENVMAP_TYPE_CUBE_UV )\n\tuniform sampler2D envMap;\n#endif\nuniform float flipEnvMap;\nuniform float backgroundBlurriness;\nuniform float backgroundIntensity;\nvarying vec3 vWorldDirection;\n#include <cube_uv_reflection_fragment>\nvoid main() {\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tvec4 texColor = textureCube( envMap, vec3( flipEnvMap * vWorldDirection.x, vWorldDirection.yz ) );\n\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\tvec4 texColor = textureCubeUV( envMap, vWorldDirection, backgroundBlurriness );\n\t#else\n\t\tvec4 texColor = vec4( 0.0, 0.0, 0.0, 1.0 );\n\t#endif\n\ttexColor.rgb *= backgroundIntensity;\n\tgl_FragColor = texColor;\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n}";
  8276. 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}";
  8277. const fragment$f = "uniform samplerCube tCube;\nuniform float tFlip;\nuniform float opacity;\nvarying vec3 vWorldDirection;\nvoid main() {\n\tvec4 texColor = textureCube( tCube, vec3( tFlip * vWorldDirection.x, vWorldDirection.yz ) );\n\tgl_FragColor = texColor;\n\tgl_FragColor.a *= opacity;\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n}";
  8278. const vertex$e = "#include <common>\n#include <batching_pars_vertex>\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 <batching_vertex>\n\t#include <skinbase_vertex>\n\t#include <morphinstance_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}";
  8279. 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 <alphahash_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvarying vec2 vHighPrecisionZW;\nvoid main() {\n\tvec4 diffuseColor = vec4( 1.0 );\n\t#include <clipping_planes_fragment>\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 <alphahash_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}";
  8280. const vertex$d = "#define DISTANCE\nvarying vec3 vWorldPosition;\n#include <common>\n#include <batching_pars_vertex>\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 <batching_vertex>\n\t#include <skinbase_vertex>\n\t#include <morphinstance_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}";
  8281. 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 <alphahash_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main () {\n\tvec4 diffuseColor = vec4( 1.0 );\n\t#include <clipping_planes_fragment>\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <alphahash_fragment>\n\tfloat dist = length( vWorldPosition - referencePosition );\n\tdist = ( dist - nearDistance ) / ( farDistance - nearDistance );\n\tdist = saturate( dist );\n\tgl_FragColor = packDepthToRGBA( dist );\n}";
  8282. 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}";
  8283. 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 <colorspace_fragment>\n}";
  8284. const vertex$b = "uniform float scale;\nattribute float lineDistance;\nvarying float vLineDistance;\n#include <common>\n#include <uv_pars_vertex>\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 <uv_vertex>\n\t#include <color_vertex>\n\t#include <morphinstance_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}";
  8285. 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 <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <fog_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <clipping_planes_fragment>\n\tif ( mod( vLineDistance, totalSize ) > dashSize ) {\n\t\tdiscard;\n\t}\n\tvec3 outgoingLight = vec3( 0.0 );\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\t#include <opaque_fragment>\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n}";
  8286. const vertex$a = "#include <common>\n#include <batching_pars_vertex>\n#include <uv_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 <color_vertex>\n\t#include <morphinstance_vertex>\n\t#include <morphcolor_vertex>\n\t#include <batching_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}";
  8287. 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 <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_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 <fog_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <clipping_planes_fragment>\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 <alphahash_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, vLightMapUv );\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 <opaque_fragment>\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  8288. const vertex$9 = "#define LAMBERT\nvarying vec3 vViewPosition;\n#include <common>\n#include <batching_pars_vertex>\n#include <uv_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 <color_vertex>\n\t#include <morphinstance_vertex>\n\t#include <morphcolor_vertex>\n\t#include <batching_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}";
  8289. const fragment$9 = "#define LAMBERT\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 <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_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 <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <normal_pars_fragment>\n#include <lights_lambert_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\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <clipping_planes_fragment>\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 <alphahash_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_lambert_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 <envmap_fragment>\n\t#include <opaque_fragment>\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  8290. const vertex$8 = "#define MATCAP\nvarying vec3 vViewPosition;\n#include <common>\n#include <batching_pars_vertex>\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 <morphinstance_vertex>\n\t#include <morphcolor_vertex>\n\t#include <batching_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}";
  8291. 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 <alphahash_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\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <clipping_planes_fragment>\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 <alphahash_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 <opaque_fragment>\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  8292. const vertex$7 = "#define NORMAL\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE )\n\tvarying vec3 vViewPosition;\n#endif\n#include <common>\n#include <batching_pars_vertex>\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 <batching_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphinstance_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( USE_NORMALMAP_TANGENTSPACE )\n\tvViewPosition = - mvPosition.xyz;\n#endif\n}";
  8293. const fragment$7 = "#define NORMAL\nuniform float opacity;\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE )\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\tvec4 diffuseColor = vec4( 0.0, 0.0, 0.0, opacity );\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 ), diffuseColor.a );\n\t#ifdef OPAQUE\n\t\tgl_FragColor.a = 1.0;\n\t#endif\n}";
  8294. const vertex$6 = "#define PHONG\nvarying vec3 vViewPosition;\n#include <common>\n#include <batching_pars_vertex>\n#include <uv_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 <color_vertex>\n\t#include <morphcolor_vertex>\n\t#include <batching_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphinstance_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}";
  8295. 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 <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_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 <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\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <clipping_planes_fragment>\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 <alphahash_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 <opaque_fragment>\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  8296. const vertex$5 = "#define STANDARD\nvarying vec3 vViewPosition;\n#ifdef USE_TRANSMISSION\n\tvarying vec3 vWorldPosition;\n#endif\n#include <common>\n#include <batching_pars_vertex>\n#include <uv_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 <color_vertex>\n\t#include <morphinstance_vertex>\n\t#include <morphcolor_vertex>\n\t#include <batching_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}";
  8297. const fragment$5 = "#define STANDARD\n#ifdef PHYSICAL\n\t#define IOR\n\t#define USE_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 USE_SPECULAR\n\tuniform float specularIntensity;\n\tuniform vec3 specularColor;\n\t#ifdef USE_SPECULAR_COLORMAP\n\t\tuniform sampler2D specularColorMap;\n\t#endif\n\t#ifdef USE_SPECULAR_INTENSITYMAP\n\t\tuniform sampler2D specularIntensityMap;\n\t#endif\n#endif\n#ifdef USE_CLEARCOAT\n\tuniform float clearcoat;\n\tuniform float clearcoatRoughness;\n#endif\n#ifdef USE_IRIDESCENCE\n\tuniform float iridescence;\n\tuniform float iridescenceIOR;\n\tuniform float iridescenceThicknessMinimum;\n\tuniform float iridescenceThicknessMaximum;\n#endif\n#ifdef USE_SHEEN\n\tuniform vec3 sheenColor;\n\tuniform float sheenRoughness;\n\t#ifdef USE_SHEEN_COLORMAP\n\t\tuniform sampler2D sheenColorMap;\n\t#endif\n\t#ifdef USE_SHEEN_ROUGHNESSMAP\n\t\tuniform sampler2D sheenRoughnessMap;\n\t#endif\n#endif\n#ifdef USE_ANISOTROPY\n\tuniform vec2 anisotropyVector;\n\t#ifdef USE_ANISOTROPYMAP\n\t\tuniform sampler2D anisotropyMap;\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 <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <iridescence_fragment>\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 <iridescence_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\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <clipping_planes_fragment>\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 <alphahash_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 + sheenSpecularDirect + sheenSpecularIndirect;\n\t#endif\n\t#ifdef USE_CLEARCOAT\n\t\tfloat dotNVcc = saturate( dot( geometryClearcoatNormal, geometryViewDir ) );\n\t\tvec3 Fcc = F_Schlick( material.clearcoatF0, material.clearcoatF90, dotNVcc );\n\t\toutgoingLight = outgoingLight * ( 1.0 - material.clearcoat * Fcc ) + ( clearcoatSpecularDirect + clearcoatSpecularIndirect ) * material.clearcoat;\n\t#endif\n\t#include <opaque_fragment>\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  8298. const vertex$4 = "#define TOON\nvarying vec3 vViewPosition;\n#include <common>\n#include <batching_pars_vertex>\n#include <uv_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 <color_vertex>\n\t#include <morphinstance_vertex>\n\t#include <morphcolor_vertex>\n\t#include <batching_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}";
  8299. 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 <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_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\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <clipping_planes_fragment>\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 <alphahash_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 <opaque_fragment>\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  8300. 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>\n#ifdef USE_POINTS_UV\n\tvarying vec2 vUv;\n\tuniform mat3 uvTransform;\n#endif\nvoid main() {\n\t#ifdef USE_POINTS_UV\n\t\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n\t#endif\n\t#include <color_vertex>\n\t#include <morphinstance_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}";
  8301. 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 <alphahash_pars_fragment>\n#include <fog_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <clipping_planes_fragment>\n\tvec3 outgoingLight = vec3( 0.0 );\n\t#include <logdepthbuf_fragment>\n\t#include <map_particle_fragment>\n\t#include <color_fragment>\n\t#include <alphatest_fragment>\n\t#include <alphahash_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\t#include <opaque_fragment>\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n}";
  8302. const vertex$2 = "#include <common>\n#include <batching_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <shadowmap_pars_vertex>\nvoid main() {\n\t#include <batching_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphinstance_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 <worldpos_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}";
  8303. 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 <logdepthbuf_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <shadowmask_pars_fragment>\nvoid main() {\n\t#include <logdepthbuf_fragment>\n\tgl_FragColor = vec4( color, opacity * ( 1.0 - getShadowMask() ) );\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n\t#include <fog_fragment>\n}";
  8304. 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}";
  8305. 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 <alphahash_pars_fragment>\n#include <fog_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <clipping_planes_fragment>\n\tvec3 outgoingLight = vec3( 0.0 );\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <alphahash_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\t#include <opaque_fragment>\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n\t#include <fog_fragment>\n}";
  8306. const ShaderChunk = {
  8307. alphahash_fragment: alphahash_fragment,
  8308. alphahash_pars_fragment: alphahash_pars_fragment,
  8309. alphamap_fragment: alphamap_fragment,
  8310. alphamap_pars_fragment: alphamap_pars_fragment,
  8311. alphatest_fragment: alphatest_fragment,
  8312. alphatest_pars_fragment: alphatest_pars_fragment,
  8313. aomap_fragment: aomap_fragment,
  8314. aomap_pars_fragment: aomap_pars_fragment,
  8315. batching_pars_vertex: batching_pars_vertex,
  8316. batching_vertex: batching_vertex,
  8317. begin_vertex: begin_vertex,
  8318. beginnormal_vertex: beginnormal_vertex,
  8319. bsdfs: bsdfs,
  8320. iridescence_fragment: iridescence_fragment,
  8321. bumpmap_pars_fragment: bumpmap_pars_fragment,
  8322. clipping_planes_fragment: clipping_planes_fragment,
  8323. clipping_planes_pars_fragment: clipping_planes_pars_fragment,
  8324. clipping_planes_pars_vertex: clipping_planes_pars_vertex,
  8325. clipping_planes_vertex: clipping_planes_vertex,
  8326. color_fragment: color_fragment,
  8327. color_pars_fragment: color_pars_fragment,
  8328. color_pars_vertex: color_pars_vertex,
  8329. color_vertex: color_vertex,
  8330. common: common,
  8331. cube_uv_reflection_fragment: cube_uv_reflection_fragment,
  8332. defaultnormal_vertex: defaultnormal_vertex,
  8333. displacementmap_pars_vertex: displacementmap_pars_vertex,
  8334. displacementmap_vertex: displacementmap_vertex,
  8335. emissivemap_fragment: emissivemap_fragment,
  8336. emissivemap_pars_fragment: emissivemap_pars_fragment,
  8337. colorspace_fragment: colorspace_fragment,
  8338. colorspace_pars_fragment: colorspace_pars_fragment,
  8339. envmap_fragment: envmap_fragment,
  8340. envmap_common_pars_fragment: envmap_common_pars_fragment,
  8341. envmap_pars_fragment: envmap_pars_fragment,
  8342. envmap_pars_vertex: envmap_pars_vertex,
  8343. envmap_physical_pars_fragment: envmap_physical_pars_fragment,
  8344. envmap_vertex: envmap_vertex,
  8345. fog_vertex: fog_vertex,
  8346. fog_pars_vertex: fog_pars_vertex,
  8347. fog_fragment: fog_fragment,
  8348. fog_pars_fragment: fog_pars_fragment,
  8349. gradientmap_pars_fragment: gradientmap_pars_fragment,
  8350. lightmap_fragment: lightmap_fragment,
  8351. lightmap_pars_fragment: lightmap_pars_fragment,
  8352. lights_lambert_fragment: lights_lambert_fragment,
  8353. lights_lambert_pars_fragment: lights_lambert_pars_fragment,
  8354. lights_pars_begin: lights_pars_begin,
  8355. lights_toon_fragment: lights_toon_fragment,
  8356. lights_toon_pars_fragment: lights_toon_pars_fragment,
  8357. lights_phong_fragment: lights_phong_fragment,
  8358. lights_phong_pars_fragment: lights_phong_pars_fragment,
  8359. lights_physical_fragment: lights_physical_fragment,
  8360. lights_physical_pars_fragment: lights_physical_pars_fragment,
  8361. lights_fragment_begin: lights_fragment_begin,
  8362. lights_fragment_maps: lights_fragment_maps,
  8363. lights_fragment_end: lights_fragment_end,
  8364. logdepthbuf_fragment: logdepthbuf_fragment,
  8365. logdepthbuf_pars_fragment: logdepthbuf_pars_fragment,
  8366. logdepthbuf_pars_vertex: logdepthbuf_pars_vertex,
  8367. logdepthbuf_vertex: logdepthbuf_vertex,
  8368. map_fragment: map_fragment,
  8369. map_pars_fragment: map_pars_fragment,
  8370. map_particle_fragment: map_particle_fragment,
  8371. map_particle_pars_fragment: map_particle_pars_fragment,
  8372. metalnessmap_fragment: metalnessmap_fragment,
  8373. metalnessmap_pars_fragment: metalnessmap_pars_fragment,
  8374. morphinstance_vertex: morphinstance_vertex,
  8375. morphcolor_vertex: morphcolor_vertex,
  8376. morphnormal_vertex: morphnormal_vertex,
  8377. morphtarget_pars_vertex: morphtarget_pars_vertex,
  8378. morphtarget_vertex: morphtarget_vertex,
  8379. normal_fragment_begin: normal_fragment_begin,
  8380. normal_fragment_maps: normal_fragment_maps,
  8381. normal_pars_fragment: normal_pars_fragment,
  8382. normal_pars_vertex: normal_pars_vertex,
  8383. normal_vertex: normal_vertex,
  8384. normalmap_pars_fragment: normalmap_pars_fragment,
  8385. clearcoat_normal_fragment_begin: clearcoat_normal_fragment_begin,
  8386. clearcoat_normal_fragment_maps: clearcoat_normal_fragment_maps,
  8387. clearcoat_pars_fragment: clearcoat_pars_fragment,
  8388. iridescence_pars_fragment: iridescence_pars_fragment,
  8389. opaque_fragment: opaque_fragment,
  8390. packing: packing,
  8391. premultiplied_alpha_fragment: premultiplied_alpha_fragment,
  8392. project_vertex: project_vertex,
  8393. dithering_fragment: dithering_fragment,
  8394. dithering_pars_fragment: dithering_pars_fragment,
  8395. roughnessmap_fragment: roughnessmap_fragment,
  8396. roughnessmap_pars_fragment: roughnessmap_pars_fragment,
  8397. shadowmap_pars_fragment: shadowmap_pars_fragment,
  8398. shadowmap_pars_vertex: shadowmap_pars_vertex,
  8399. shadowmap_vertex: shadowmap_vertex,
  8400. shadowmask_pars_fragment: shadowmask_pars_fragment,
  8401. skinbase_vertex: skinbase_vertex,
  8402. skinning_pars_vertex: skinning_pars_vertex,
  8403. skinning_vertex: skinning_vertex,
  8404. skinnormal_vertex: skinnormal_vertex,
  8405. specularmap_fragment: specularmap_fragment,
  8406. specularmap_pars_fragment: specularmap_pars_fragment,
  8407. tonemapping_fragment: tonemapping_fragment,
  8408. tonemapping_pars_fragment: tonemapping_pars_fragment,
  8409. transmission_fragment: transmission_fragment,
  8410. transmission_pars_fragment: transmission_pars_fragment,
  8411. uv_pars_fragment: uv_pars_fragment,
  8412. uv_pars_vertex: uv_pars_vertex,
  8413. uv_vertex: uv_vertex,
  8414. worldpos_vertex: worldpos_vertex,
  8415. background_vert: vertex$h,
  8416. background_frag: fragment$h,
  8417. backgroundCube_vert: vertex$g,
  8418. backgroundCube_frag: fragment$g,
  8419. cube_vert: vertex$f,
  8420. cube_frag: fragment$f,
  8421. depth_vert: vertex$e,
  8422. depth_frag: fragment$e,
  8423. distanceRGBA_vert: vertex$d,
  8424. distanceRGBA_frag: fragment$d,
  8425. equirect_vert: vertex$c,
  8426. equirect_frag: fragment$c,
  8427. linedashed_vert: vertex$b,
  8428. linedashed_frag: fragment$b,
  8429. meshbasic_vert: vertex$a,
  8430. meshbasic_frag: fragment$a,
  8431. meshlambert_vert: vertex$9,
  8432. meshlambert_frag: fragment$9,
  8433. meshmatcap_vert: vertex$8,
  8434. meshmatcap_frag: fragment$8,
  8435. meshnormal_vert: vertex$7,
  8436. meshnormal_frag: fragment$7,
  8437. meshphong_vert: vertex$6,
  8438. meshphong_frag: fragment$6,
  8439. meshphysical_vert: vertex$5,
  8440. meshphysical_frag: fragment$5,
  8441. meshtoon_vert: vertex$4,
  8442. meshtoon_frag: fragment$4,
  8443. points_vert: vertex$3,
  8444. points_frag: fragment$3,
  8445. shadow_vert: vertex$2,
  8446. shadow_frag: fragment$2,
  8447. sprite_vert: vertex$1,
  8448. sprite_frag: fragment$1
  8449. };
  8450. /**
  8451. * Uniforms library for shared webgl shaders
  8452. */
  8453. const UniformsLib = {
  8454. common: {
  8455. diffuse: { value: /*@__PURE__*/ new Color( 0xffffff ) },
  8456. opacity: { value: 1.0 },
  8457. map: { value: null },
  8458. mapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8459. alphaMap: { value: null },
  8460. alphaMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8461. alphaTest: { value: 0 }
  8462. },
  8463. specularmap: {
  8464. specularMap: { value: null },
  8465. specularMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  8466. },
  8467. envmap: {
  8468. envMap: { value: null },
  8469. flipEnvMap: { value: - 1 },
  8470. reflectivity: { value: 1.0 }, // basic, lambert, phong
  8471. ior: { value: 1.5 }, // physical
  8472. refractionRatio: { value: 0.98 }, // basic, lambert, phong
  8473. },
  8474. aomap: {
  8475. aoMap: { value: null },
  8476. aoMapIntensity: { value: 1 },
  8477. aoMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  8478. },
  8479. lightmap: {
  8480. lightMap: { value: null },
  8481. lightMapIntensity: { value: 1 },
  8482. lightMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  8483. },
  8484. bumpmap: {
  8485. bumpMap: { value: null },
  8486. bumpMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8487. bumpScale: { value: 1 }
  8488. },
  8489. normalmap: {
  8490. normalMap: { value: null },
  8491. normalMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8492. normalScale: { value: /*@__PURE__*/ new Vector2( 1, 1 ) }
  8493. },
  8494. displacementmap: {
  8495. displacementMap: { value: null },
  8496. displacementMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8497. displacementScale: { value: 1 },
  8498. displacementBias: { value: 0 }
  8499. },
  8500. emissivemap: {
  8501. emissiveMap: { value: null },
  8502. emissiveMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  8503. },
  8504. metalnessmap: {
  8505. metalnessMap: { value: null },
  8506. metalnessMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  8507. },
  8508. roughnessmap: {
  8509. roughnessMap: { value: null },
  8510. roughnessMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  8511. },
  8512. gradientmap: {
  8513. gradientMap: { value: null }
  8514. },
  8515. fog: {
  8516. fogDensity: { value: 0.00025 },
  8517. fogNear: { value: 1 },
  8518. fogFar: { value: 2000 },
  8519. fogColor: { value: /*@__PURE__*/ new Color( 0xffffff ) }
  8520. },
  8521. lights: {
  8522. ambientLightColor: { value: [] },
  8523. lightProbe: { value: [] },
  8524. directionalLights: { value: [], properties: {
  8525. direction: {},
  8526. color: {}
  8527. } },
  8528. directionalLightShadows: { value: [], properties: {
  8529. shadowBias: {},
  8530. shadowNormalBias: {},
  8531. shadowRadius: {},
  8532. shadowMapSize: {}
  8533. } },
  8534. directionalShadowMap: { value: [] },
  8535. directionalShadowMatrix: { value: [] },
  8536. spotLights: { value: [], properties: {
  8537. color: {},
  8538. position: {},
  8539. direction: {},
  8540. distance: {},
  8541. coneCos: {},
  8542. penumbraCos: {},
  8543. decay: {}
  8544. } },
  8545. spotLightShadows: { value: [], properties: {
  8546. shadowBias: {},
  8547. shadowNormalBias: {},
  8548. shadowRadius: {},
  8549. shadowMapSize: {}
  8550. } },
  8551. spotLightMap: { value: [] },
  8552. spotShadowMap: { value: [] },
  8553. spotLightMatrix: { value: [] },
  8554. pointLights: { value: [], properties: {
  8555. color: {},
  8556. position: {},
  8557. decay: {},
  8558. distance: {}
  8559. } },
  8560. pointLightShadows: { value: [], properties: {
  8561. shadowBias: {},
  8562. shadowNormalBias: {},
  8563. shadowRadius: {},
  8564. shadowMapSize: {},
  8565. shadowCameraNear: {},
  8566. shadowCameraFar: {}
  8567. } },
  8568. pointShadowMap: { value: [] },
  8569. pointShadowMatrix: { value: [] },
  8570. hemisphereLights: { value: [], properties: {
  8571. direction: {},
  8572. skyColor: {},
  8573. groundColor: {}
  8574. } },
  8575. // TODO (abelnation): RectAreaLight BRDF data needs to be moved from example to main src
  8576. rectAreaLights: { value: [], properties: {
  8577. color: {},
  8578. position: {},
  8579. width: {},
  8580. height: {}
  8581. } },
  8582. ltc_1: { value: null },
  8583. ltc_2: { value: null }
  8584. },
  8585. points: {
  8586. diffuse: { value: /*@__PURE__*/ new Color( 0xffffff ) },
  8587. opacity: { value: 1.0 },
  8588. size: { value: 1.0 },
  8589. scale: { value: 1.0 },
  8590. map: { value: null },
  8591. alphaMap: { value: null },
  8592. alphaMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8593. alphaTest: { value: 0 },
  8594. uvTransform: { value: /*@__PURE__*/ new Matrix3() }
  8595. },
  8596. sprite: {
  8597. diffuse: { value: /*@__PURE__*/ new Color( 0xffffff ) },
  8598. opacity: { value: 1.0 },
  8599. center: { value: /*@__PURE__*/ new Vector2( 0.5, 0.5 ) },
  8600. rotation: { value: 0.0 },
  8601. map: { value: null },
  8602. mapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8603. alphaMap: { value: null },
  8604. alphaMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8605. alphaTest: { value: 0 }
  8606. }
  8607. };
  8608. const ShaderLib = {
  8609. basic: {
  8610. uniforms: /*@__PURE__*/ mergeUniforms( [
  8611. UniformsLib.common,
  8612. UniformsLib.specularmap,
  8613. UniformsLib.envmap,
  8614. UniformsLib.aomap,
  8615. UniformsLib.lightmap,
  8616. UniformsLib.fog
  8617. ] ),
  8618. vertexShader: ShaderChunk.meshbasic_vert,
  8619. fragmentShader: ShaderChunk.meshbasic_frag
  8620. },
  8621. lambert: {
  8622. uniforms: /*@__PURE__*/ mergeUniforms( [
  8623. UniformsLib.common,
  8624. UniformsLib.specularmap,
  8625. UniformsLib.envmap,
  8626. UniformsLib.aomap,
  8627. UniformsLib.lightmap,
  8628. UniformsLib.emissivemap,
  8629. UniformsLib.bumpmap,
  8630. UniformsLib.normalmap,
  8631. UniformsLib.displacementmap,
  8632. UniformsLib.fog,
  8633. UniformsLib.lights,
  8634. {
  8635. emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) }
  8636. }
  8637. ] ),
  8638. vertexShader: ShaderChunk.meshlambert_vert,
  8639. fragmentShader: ShaderChunk.meshlambert_frag
  8640. },
  8641. phong: {
  8642. uniforms: /*@__PURE__*/ mergeUniforms( [
  8643. UniformsLib.common,
  8644. UniformsLib.specularmap,
  8645. UniformsLib.envmap,
  8646. UniformsLib.aomap,
  8647. UniformsLib.lightmap,
  8648. UniformsLib.emissivemap,
  8649. UniformsLib.bumpmap,
  8650. UniformsLib.normalmap,
  8651. UniformsLib.displacementmap,
  8652. UniformsLib.fog,
  8653. UniformsLib.lights,
  8654. {
  8655. emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) },
  8656. specular: { value: /*@__PURE__*/ new Color( 0x111111 ) },
  8657. shininess: { value: 30 }
  8658. }
  8659. ] ),
  8660. vertexShader: ShaderChunk.meshphong_vert,
  8661. fragmentShader: ShaderChunk.meshphong_frag
  8662. },
  8663. standard: {
  8664. uniforms: /*@__PURE__*/ mergeUniforms( [
  8665. UniformsLib.common,
  8666. UniformsLib.envmap,
  8667. UniformsLib.aomap,
  8668. UniformsLib.lightmap,
  8669. UniformsLib.emissivemap,
  8670. UniformsLib.bumpmap,
  8671. UniformsLib.normalmap,
  8672. UniformsLib.displacementmap,
  8673. UniformsLib.roughnessmap,
  8674. UniformsLib.metalnessmap,
  8675. UniformsLib.fog,
  8676. UniformsLib.lights,
  8677. {
  8678. emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) },
  8679. roughness: { value: 1.0 },
  8680. metalness: { value: 0.0 },
  8681. envMapIntensity: { value: 1 } // temporary
  8682. }
  8683. ] ),
  8684. vertexShader: ShaderChunk.meshphysical_vert,
  8685. fragmentShader: ShaderChunk.meshphysical_frag
  8686. },
  8687. toon: {
  8688. uniforms: /*@__PURE__*/ mergeUniforms( [
  8689. UniformsLib.common,
  8690. UniformsLib.aomap,
  8691. UniformsLib.lightmap,
  8692. UniformsLib.emissivemap,
  8693. UniformsLib.bumpmap,
  8694. UniformsLib.normalmap,
  8695. UniformsLib.displacementmap,
  8696. UniformsLib.gradientmap,
  8697. UniformsLib.fog,
  8698. UniformsLib.lights,
  8699. {
  8700. emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) }
  8701. }
  8702. ] ),
  8703. vertexShader: ShaderChunk.meshtoon_vert,
  8704. fragmentShader: ShaderChunk.meshtoon_frag
  8705. },
  8706. matcap: {
  8707. uniforms: /*@__PURE__*/ mergeUniforms( [
  8708. UniformsLib.common,
  8709. UniformsLib.bumpmap,
  8710. UniformsLib.normalmap,
  8711. UniformsLib.displacementmap,
  8712. UniformsLib.fog,
  8713. {
  8714. matcap: { value: null }
  8715. }
  8716. ] ),
  8717. vertexShader: ShaderChunk.meshmatcap_vert,
  8718. fragmentShader: ShaderChunk.meshmatcap_frag
  8719. },
  8720. points: {
  8721. uniforms: /*@__PURE__*/ mergeUniforms( [
  8722. UniformsLib.points,
  8723. UniformsLib.fog
  8724. ] ),
  8725. vertexShader: ShaderChunk.points_vert,
  8726. fragmentShader: ShaderChunk.points_frag
  8727. },
  8728. dashed: {
  8729. uniforms: /*@__PURE__*/ mergeUniforms( [
  8730. UniformsLib.common,
  8731. UniformsLib.fog,
  8732. {
  8733. scale: { value: 1 },
  8734. dashSize: { value: 1 },
  8735. totalSize: { value: 2 }
  8736. }
  8737. ] ),
  8738. vertexShader: ShaderChunk.linedashed_vert,
  8739. fragmentShader: ShaderChunk.linedashed_frag
  8740. },
  8741. depth: {
  8742. uniforms: /*@__PURE__*/ mergeUniforms( [
  8743. UniformsLib.common,
  8744. UniformsLib.displacementmap
  8745. ] ),
  8746. vertexShader: ShaderChunk.depth_vert,
  8747. fragmentShader: ShaderChunk.depth_frag
  8748. },
  8749. normal: {
  8750. uniforms: /*@__PURE__*/ mergeUniforms( [
  8751. UniformsLib.common,
  8752. UniformsLib.bumpmap,
  8753. UniformsLib.normalmap,
  8754. UniformsLib.displacementmap,
  8755. {
  8756. opacity: { value: 1.0 }
  8757. }
  8758. ] ),
  8759. vertexShader: ShaderChunk.meshnormal_vert,
  8760. fragmentShader: ShaderChunk.meshnormal_frag
  8761. },
  8762. sprite: {
  8763. uniforms: /*@__PURE__*/ mergeUniforms( [
  8764. UniformsLib.sprite,
  8765. UniformsLib.fog
  8766. ] ),
  8767. vertexShader: ShaderChunk.sprite_vert,
  8768. fragmentShader: ShaderChunk.sprite_frag
  8769. },
  8770. background: {
  8771. uniforms: {
  8772. uvTransform: { value: /*@__PURE__*/ new Matrix3() },
  8773. t2D: { value: null },
  8774. backgroundIntensity: { value: 1 }
  8775. },
  8776. vertexShader: ShaderChunk.background_vert,
  8777. fragmentShader: ShaderChunk.background_frag
  8778. },
  8779. backgroundCube: {
  8780. uniforms: {
  8781. envMap: { value: null },
  8782. flipEnvMap: { value: - 1 },
  8783. backgroundBlurriness: { value: 0 },
  8784. backgroundIntensity: { value: 1 }
  8785. },
  8786. vertexShader: ShaderChunk.backgroundCube_vert,
  8787. fragmentShader: ShaderChunk.backgroundCube_frag
  8788. },
  8789. cube: {
  8790. uniforms: {
  8791. tCube: { value: null },
  8792. tFlip: { value: - 1 },
  8793. opacity: { value: 1.0 }
  8794. },
  8795. vertexShader: ShaderChunk.cube_vert,
  8796. fragmentShader: ShaderChunk.cube_frag
  8797. },
  8798. equirect: {
  8799. uniforms: {
  8800. tEquirect: { value: null },
  8801. },
  8802. vertexShader: ShaderChunk.equirect_vert,
  8803. fragmentShader: ShaderChunk.equirect_frag
  8804. },
  8805. distanceRGBA: {
  8806. uniforms: /*@__PURE__*/ mergeUniforms( [
  8807. UniformsLib.common,
  8808. UniformsLib.displacementmap,
  8809. {
  8810. referencePosition: { value: /*@__PURE__*/ new Vector3() },
  8811. nearDistance: { value: 1 },
  8812. farDistance: { value: 1000 }
  8813. }
  8814. ] ),
  8815. vertexShader: ShaderChunk.distanceRGBA_vert,
  8816. fragmentShader: ShaderChunk.distanceRGBA_frag
  8817. },
  8818. shadow: {
  8819. uniforms: /*@__PURE__*/ mergeUniforms( [
  8820. UniformsLib.lights,
  8821. UniformsLib.fog,
  8822. {
  8823. color: { value: /*@__PURE__*/ new Color( 0x00000 ) },
  8824. opacity: { value: 1.0 }
  8825. },
  8826. ] ),
  8827. vertexShader: ShaderChunk.shadow_vert,
  8828. fragmentShader: ShaderChunk.shadow_frag
  8829. }
  8830. };
  8831. ShaderLib.physical = {
  8832. uniforms: /*@__PURE__*/ mergeUniforms( [
  8833. ShaderLib.standard.uniforms,
  8834. {
  8835. clearcoat: { value: 0 },
  8836. clearcoatMap: { value: null },
  8837. clearcoatMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8838. clearcoatNormalMap: { value: null },
  8839. clearcoatNormalMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8840. clearcoatNormalScale: { value: /*@__PURE__*/ new Vector2( 1, 1 ) },
  8841. clearcoatRoughness: { value: 0 },
  8842. clearcoatRoughnessMap: { value: null },
  8843. clearcoatRoughnessMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8844. iridescence: { value: 0 },
  8845. iridescenceMap: { value: null },
  8846. iridescenceMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8847. iridescenceIOR: { value: 1.3 },
  8848. iridescenceThicknessMinimum: { value: 100 },
  8849. iridescenceThicknessMaximum: { value: 400 },
  8850. iridescenceThicknessMap: { value: null },
  8851. iridescenceThicknessMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8852. sheen: { value: 0 },
  8853. sheenColor: { value: /*@__PURE__*/ new Color( 0x000000 ) },
  8854. sheenColorMap: { value: null },
  8855. sheenColorMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8856. sheenRoughness: { value: 1 },
  8857. sheenRoughnessMap: { value: null },
  8858. sheenRoughnessMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8859. transmission: { value: 0 },
  8860. transmissionMap: { value: null },
  8861. transmissionMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8862. transmissionSamplerSize: { value: /*@__PURE__*/ new Vector2() },
  8863. transmissionSamplerMap: { value: null },
  8864. thickness: { value: 0 },
  8865. thicknessMap: { value: null },
  8866. thicknessMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8867. attenuationDistance: { value: 0 },
  8868. attenuationColor: { value: /*@__PURE__*/ new Color( 0x000000 ) },
  8869. specularColor: { value: /*@__PURE__*/ new Color( 1, 1, 1 ) },
  8870. specularColorMap: { value: null },
  8871. specularColorMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8872. specularIntensity: { value: 1 },
  8873. specularIntensityMap: { value: null },
  8874. specularIntensityMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8875. anisotropyVector: { value: /*@__PURE__*/ new Vector2() },
  8876. anisotropyMap: { value: null },
  8877. anisotropyMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8878. }
  8879. ] ),
  8880. vertexShader: ShaderChunk.meshphysical_vert,
  8881. fragmentShader: ShaderChunk.meshphysical_frag
  8882. };
  8883. const _rgb = { r: 0, b: 0, g: 0 };
  8884. function WebGLBackground( renderer, cubemaps, cubeuvmaps, state, objects, alpha, premultipliedAlpha ) {
  8885. const clearColor = new Color( 0x000000 );
  8886. let clearAlpha = alpha === true ? 0 : 1;
  8887. let planeMesh;
  8888. let boxMesh;
  8889. let currentBackground = null;
  8890. let currentBackgroundVersion = 0;
  8891. let currentTonemapping = null;
  8892. function render( renderList, scene ) {
  8893. let forceClear = false;
  8894. let background = scene.isScene === true ? scene.background : null;
  8895. if ( background && background.isTexture ) {
  8896. const usePMREM = scene.backgroundBlurriness > 0; // use PMREM if the user wants to blur the background
  8897. background = ( usePMREM ? cubeuvmaps : cubemaps ).get( background );
  8898. }
  8899. if ( background === null ) {
  8900. setClear( clearColor, clearAlpha );
  8901. } else if ( background && background.isColor ) {
  8902. setClear( background, 1 );
  8903. forceClear = true;
  8904. }
  8905. const environmentBlendMode = renderer.xr.getEnvironmentBlendMode();
  8906. if ( environmentBlendMode === 'additive' ) {
  8907. state.buffers.color.setClear( 0, 0, 0, 1, premultipliedAlpha );
  8908. } else if ( environmentBlendMode === 'alpha-blend' ) {
  8909. state.buffers.color.setClear( 0, 0, 0, 0, premultipliedAlpha );
  8910. }
  8911. if ( renderer.autoClear || forceClear ) {
  8912. renderer.clear( renderer.autoClearColor, renderer.autoClearDepth, renderer.autoClearStencil );
  8913. }
  8914. if ( background && ( background.isCubeTexture || background.mapping === CubeUVReflectionMapping ) ) {
  8915. if ( boxMesh === undefined ) {
  8916. boxMesh = new Mesh(
  8917. new BoxGeometry( 1, 1, 1 ),
  8918. new ShaderMaterial( {
  8919. name: 'BackgroundCubeMaterial',
  8920. uniforms: cloneUniforms( ShaderLib.backgroundCube.uniforms ),
  8921. vertexShader: ShaderLib.backgroundCube.vertexShader,
  8922. fragmentShader: ShaderLib.backgroundCube.fragmentShader,
  8923. side: BackSide,
  8924. depthTest: false,
  8925. depthWrite: false,
  8926. fog: false
  8927. } )
  8928. );
  8929. boxMesh.geometry.deleteAttribute( 'normal' );
  8930. boxMesh.geometry.deleteAttribute( 'uv' );
  8931. boxMesh.onBeforeRender = function ( renderer, scene, camera ) {
  8932. this.matrixWorld.copyPosition( camera.matrixWorld );
  8933. };
  8934. // add "envMap" material property so the renderer can evaluate it like for built-in materials
  8935. Object.defineProperty( boxMesh.material, 'envMap', {
  8936. get: function () {
  8937. return this.uniforms.envMap.value;
  8938. }
  8939. } );
  8940. objects.update( boxMesh );
  8941. }
  8942. boxMesh.material.uniforms.envMap.value = background;
  8943. boxMesh.material.uniforms.flipEnvMap.value = ( background.isCubeTexture && background.isRenderTargetTexture === false ) ? - 1 : 1;
  8944. boxMesh.material.uniforms.backgroundBlurriness.value = scene.backgroundBlurriness;
  8945. boxMesh.material.uniforms.backgroundIntensity.value = scene.backgroundIntensity;
  8946. boxMesh.material.toneMapped = ColorManagement.getTransfer( background.colorSpace ) !== SRGBTransfer;
  8947. if ( currentBackground !== background ||
  8948. currentBackgroundVersion !== background.version ||
  8949. currentTonemapping !== renderer.toneMapping ) {
  8950. boxMesh.material.needsUpdate = true;
  8951. currentBackground = background;
  8952. currentBackgroundVersion = background.version;
  8953. currentTonemapping = renderer.toneMapping;
  8954. }
  8955. boxMesh.layers.enableAll();
  8956. // push to the pre-sorted opaque render list
  8957. renderList.unshift( boxMesh, boxMesh.geometry, boxMesh.material, 0, 0, null );
  8958. } else if ( background && background.isTexture ) {
  8959. if ( planeMesh === undefined ) {
  8960. planeMesh = new Mesh(
  8961. new PlaneGeometry( 2, 2 ),
  8962. new ShaderMaterial( {
  8963. name: 'BackgroundMaterial',
  8964. uniforms: cloneUniforms( ShaderLib.background.uniforms ),
  8965. vertexShader: ShaderLib.background.vertexShader,
  8966. fragmentShader: ShaderLib.background.fragmentShader,
  8967. side: FrontSide,
  8968. depthTest: false,
  8969. depthWrite: false,
  8970. fog: false
  8971. } )
  8972. );
  8973. planeMesh.geometry.deleteAttribute( 'normal' );
  8974. // add "map" material property so the renderer can evaluate it like for built-in materials
  8975. Object.defineProperty( planeMesh.material, 'map', {
  8976. get: function () {
  8977. return this.uniforms.t2D.value;
  8978. }
  8979. } );
  8980. objects.update( planeMesh );
  8981. }
  8982. planeMesh.material.uniforms.t2D.value = background;
  8983. planeMesh.material.uniforms.backgroundIntensity.value = scene.backgroundIntensity;
  8984. planeMesh.material.toneMapped = ColorManagement.getTransfer( background.colorSpace ) !== SRGBTransfer;
  8985. if ( background.matrixAutoUpdate === true ) {
  8986. background.updateMatrix();
  8987. }
  8988. planeMesh.material.uniforms.uvTransform.value.copy( background.matrix );
  8989. if ( currentBackground !== background ||
  8990. currentBackgroundVersion !== background.version ||
  8991. currentTonemapping !== renderer.toneMapping ) {
  8992. planeMesh.material.needsUpdate = true;
  8993. currentBackground = background;
  8994. currentBackgroundVersion = background.version;
  8995. currentTonemapping = renderer.toneMapping;
  8996. }
  8997. planeMesh.layers.enableAll();
  8998. // push to the pre-sorted opaque render list
  8999. renderList.unshift( planeMesh, planeMesh.geometry, planeMesh.material, 0, 0, null );
  9000. }
  9001. }
  9002. function setClear( color, alpha ) {
  9003. color.getRGB( _rgb, getUnlitUniformColorSpace( renderer ) );
  9004. state.buffers.color.setClear( _rgb.r, _rgb.g, _rgb.b, alpha, premultipliedAlpha );
  9005. }
  9006. return {
  9007. getClearColor: function () {
  9008. return clearColor;
  9009. },
  9010. setClearColor: function ( color, alpha = 1 ) {
  9011. clearColor.set( color );
  9012. clearAlpha = alpha;
  9013. setClear( clearColor, clearAlpha );
  9014. },
  9015. getClearAlpha: function () {
  9016. return clearAlpha;
  9017. },
  9018. setClearAlpha: function ( alpha ) {
  9019. clearAlpha = alpha;
  9020. setClear( clearColor, clearAlpha );
  9021. },
  9022. render: render
  9023. };
  9024. }
  9025. function WebGLBindingStates( gl, extensions, attributes, capabilities ) {
  9026. const maxVertexAttributes = gl.getParameter( gl.MAX_VERTEX_ATTRIBS );
  9027. const extension = capabilities.isWebGL2 ? null : extensions.get( 'OES_vertex_array_object' );
  9028. const vaoAvailable = capabilities.isWebGL2 || extension !== null;
  9029. const bindingStates = {};
  9030. const defaultState = createBindingState( null );
  9031. let currentState = defaultState;
  9032. let forceUpdate = false;
  9033. function setup( object, material, program, geometry, index ) {
  9034. let updateBuffers = false;
  9035. if ( vaoAvailable ) {
  9036. const state = getBindingState( geometry, program, material );
  9037. if ( currentState !== state ) {
  9038. currentState = state;
  9039. bindVertexArrayObject( currentState.object );
  9040. }
  9041. updateBuffers = needsUpdate( object, geometry, program, index );
  9042. if ( updateBuffers ) saveCache( object, geometry, program, index );
  9043. } else {
  9044. const wireframe = ( material.wireframe === true );
  9045. if ( currentState.geometry !== geometry.id ||
  9046. currentState.program !== program.id ||
  9047. currentState.wireframe !== wireframe ) {
  9048. currentState.geometry = geometry.id;
  9049. currentState.program = program.id;
  9050. currentState.wireframe = wireframe;
  9051. updateBuffers = true;
  9052. }
  9053. }
  9054. if ( index !== null ) {
  9055. attributes.update( index, gl.ELEMENT_ARRAY_BUFFER );
  9056. }
  9057. if ( updateBuffers || forceUpdate ) {
  9058. forceUpdate = false;
  9059. setupVertexAttributes( object, material, program, geometry );
  9060. if ( index !== null ) {
  9061. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, attributes.get( index ).buffer );
  9062. }
  9063. }
  9064. }
  9065. function createVertexArrayObject() {
  9066. if ( capabilities.isWebGL2 ) return gl.createVertexArray();
  9067. return extension.createVertexArrayOES();
  9068. }
  9069. function bindVertexArrayObject( vao ) {
  9070. if ( capabilities.isWebGL2 ) return gl.bindVertexArray( vao );
  9071. return extension.bindVertexArrayOES( vao );
  9072. }
  9073. function deleteVertexArrayObject( vao ) {
  9074. if ( capabilities.isWebGL2 ) return gl.deleteVertexArray( vao );
  9075. return extension.deleteVertexArrayOES( vao );
  9076. }
  9077. function getBindingState( geometry, program, material ) {
  9078. const wireframe = ( material.wireframe === true );
  9079. let programMap = bindingStates[ geometry.id ];
  9080. if ( programMap === undefined ) {
  9081. programMap = {};
  9082. bindingStates[ geometry.id ] = programMap;
  9083. }
  9084. let stateMap = programMap[ program.id ];
  9085. if ( stateMap === undefined ) {
  9086. stateMap = {};
  9087. programMap[ program.id ] = stateMap;
  9088. }
  9089. let state = stateMap[ wireframe ];
  9090. if ( state === undefined ) {
  9091. state = createBindingState( createVertexArrayObject() );
  9092. stateMap[ wireframe ] = state;
  9093. }
  9094. return state;
  9095. }
  9096. function createBindingState( vao ) {
  9097. const newAttributes = [];
  9098. const enabledAttributes = [];
  9099. const attributeDivisors = [];
  9100. for ( let i = 0; i < maxVertexAttributes; i ++ ) {
  9101. newAttributes[ i ] = 0;
  9102. enabledAttributes[ i ] = 0;
  9103. attributeDivisors[ i ] = 0;
  9104. }
  9105. return {
  9106. // for backward compatibility on non-VAO support browser
  9107. geometry: null,
  9108. program: null,
  9109. wireframe: false,
  9110. newAttributes: newAttributes,
  9111. enabledAttributes: enabledAttributes,
  9112. attributeDivisors: attributeDivisors,
  9113. object: vao,
  9114. attributes: {},
  9115. index: null
  9116. };
  9117. }
  9118. function needsUpdate( object, geometry, program, index ) {
  9119. const cachedAttributes = currentState.attributes;
  9120. const geometryAttributes = geometry.attributes;
  9121. let attributesNum = 0;
  9122. const programAttributes = program.getAttributes();
  9123. for ( const name in programAttributes ) {
  9124. const programAttribute = programAttributes[ name ];
  9125. if ( programAttribute.location >= 0 ) {
  9126. const cachedAttribute = cachedAttributes[ name ];
  9127. let geometryAttribute = geometryAttributes[ name ];
  9128. if ( geometryAttribute === undefined ) {
  9129. if ( name === 'instanceMatrix' && object.instanceMatrix ) geometryAttribute = object.instanceMatrix;
  9130. if ( name === 'instanceColor' && object.instanceColor ) geometryAttribute = object.instanceColor;
  9131. }
  9132. if ( cachedAttribute === undefined ) return true;
  9133. if ( cachedAttribute.attribute !== geometryAttribute ) return true;
  9134. if ( geometryAttribute && cachedAttribute.data !== geometryAttribute.data ) return true;
  9135. attributesNum ++;
  9136. }
  9137. }
  9138. if ( currentState.attributesNum !== attributesNum ) return true;
  9139. if ( currentState.index !== index ) return true;
  9140. return false;
  9141. }
  9142. function saveCache( object, geometry, program, index ) {
  9143. const cache = {};
  9144. const attributes = geometry.attributes;
  9145. let attributesNum = 0;
  9146. const programAttributes = program.getAttributes();
  9147. for ( const name in programAttributes ) {
  9148. const programAttribute = programAttributes[ name ];
  9149. if ( programAttribute.location >= 0 ) {
  9150. let attribute = attributes[ name ];
  9151. if ( attribute === undefined ) {
  9152. if ( name === 'instanceMatrix' && object.instanceMatrix ) attribute = object.instanceMatrix;
  9153. if ( name === 'instanceColor' && object.instanceColor ) attribute = object.instanceColor;
  9154. }
  9155. const data = {};
  9156. data.attribute = attribute;
  9157. if ( attribute && attribute.data ) {
  9158. data.data = attribute.data;
  9159. }
  9160. cache[ name ] = data;
  9161. attributesNum ++;
  9162. }
  9163. }
  9164. currentState.attributes = cache;
  9165. currentState.attributesNum = attributesNum;
  9166. currentState.index = index;
  9167. }
  9168. function initAttributes() {
  9169. const newAttributes = currentState.newAttributes;
  9170. for ( let i = 0, il = newAttributes.length; i < il; i ++ ) {
  9171. newAttributes[ i ] = 0;
  9172. }
  9173. }
  9174. function enableAttribute( attribute ) {
  9175. enableAttributeAndDivisor( attribute, 0 );
  9176. }
  9177. function enableAttributeAndDivisor( attribute, meshPerAttribute ) {
  9178. const newAttributes = currentState.newAttributes;
  9179. const enabledAttributes = currentState.enabledAttributes;
  9180. const attributeDivisors = currentState.attributeDivisors;
  9181. newAttributes[ attribute ] = 1;
  9182. if ( enabledAttributes[ attribute ] === 0 ) {
  9183. gl.enableVertexAttribArray( attribute );
  9184. enabledAttributes[ attribute ] = 1;
  9185. }
  9186. if ( attributeDivisors[ attribute ] !== meshPerAttribute ) {
  9187. const extension = capabilities.isWebGL2 ? gl : extensions.get( 'ANGLE_instanced_arrays' );
  9188. extension[ capabilities.isWebGL2 ? 'vertexAttribDivisor' : 'vertexAttribDivisorANGLE' ]( attribute, meshPerAttribute );
  9189. attributeDivisors[ attribute ] = meshPerAttribute;
  9190. }
  9191. }
  9192. function disableUnusedAttributes() {
  9193. const newAttributes = currentState.newAttributes;
  9194. const enabledAttributes = currentState.enabledAttributes;
  9195. for ( let i = 0, il = enabledAttributes.length; i < il; i ++ ) {
  9196. if ( enabledAttributes[ i ] !== newAttributes[ i ] ) {
  9197. gl.disableVertexAttribArray( i );
  9198. enabledAttributes[ i ] = 0;
  9199. }
  9200. }
  9201. }
  9202. function vertexAttribPointer( index, size, type, normalized, stride, offset, integer ) {
  9203. if ( integer === true ) {
  9204. gl.vertexAttribIPointer( index, size, type, stride, offset );
  9205. } else {
  9206. gl.vertexAttribPointer( index, size, type, normalized, stride, offset );
  9207. }
  9208. }
  9209. function setupVertexAttributes( object, material, program, geometry ) {
  9210. if ( capabilities.isWebGL2 === false && ( object.isInstancedMesh || geometry.isInstancedBufferGeometry ) ) {
  9211. if ( extensions.get( 'ANGLE_instanced_arrays' ) === null ) return;
  9212. }
  9213. initAttributes();
  9214. const geometryAttributes = geometry.attributes;
  9215. const programAttributes = program.getAttributes();
  9216. const materialDefaultAttributeValues = material.defaultAttributeValues;
  9217. for ( const name in programAttributes ) {
  9218. const programAttribute = programAttributes[ name ];
  9219. if ( programAttribute.location >= 0 ) {
  9220. let geometryAttribute = geometryAttributes[ name ];
  9221. if ( geometryAttribute === undefined ) {
  9222. if ( name === 'instanceMatrix' && object.instanceMatrix ) geometryAttribute = object.instanceMatrix;
  9223. if ( name === 'instanceColor' && object.instanceColor ) geometryAttribute = object.instanceColor;
  9224. }
  9225. if ( geometryAttribute !== undefined ) {
  9226. const normalized = geometryAttribute.normalized;
  9227. const size = geometryAttribute.itemSize;
  9228. const attribute = attributes.get( geometryAttribute );
  9229. // TODO Attribute may not be available on context restore
  9230. if ( attribute === undefined ) continue;
  9231. const buffer = attribute.buffer;
  9232. const type = attribute.type;
  9233. const bytesPerElement = attribute.bytesPerElement;
  9234. // check for integer attributes (WebGL 2 only)
  9235. const integer = ( capabilities.isWebGL2 === true && ( type === gl.INT || type === gl.UNSIGNED_INT || geometryAttribute.gpuType === IntType ) );
  9236. if ( geometryAttribute.isInterleavedBufferAttribute ) {
  9237. const data = geometryAttribute.data;
  9238. const stride = data.stride;
  9239. const offset = geometryAttribute.offset;
  9240. if ( data.isInstancedInterleavedBuffer ) {
  9241. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  9242. enableAttributeAndDivisor( programAttribute.location + i, data.meshPerAttribute );
  9243. }
  9244. if ( object.isInstancedMesh !== true && geometry._maxInstanceCount === undefined ) {
  9245. geometry._maxInstanceCount = data.meshPerAttribute * data.count;
  9246. }
  9247. } else {
  9248. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  9249. enableAttribute( programAttribute.location + i );
  9250. }
  9251. }
  9252. gl.bindBuffer( gl.ARRAY_BUFFER, buffer );
  9253. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  9254. vertexAttribPointer(
  9255. programAttribute.location + i,
  9256. size / programAttribute.locationSize,
  9257. type,
  9258. normalized,
  9259. stride * bytesPerElement,
  9260. ( offset + ( size / programAttribute.locationSize ) * i ) * bytesPerElement,
  9261. integer
  9262. );
  9263. }
  9264. } else {
  9265. if ( geometryAttribute.isInstancedBufferAttribute ) {
  9266. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  9267. enableAttributeAndDivisor( programAttribute.location + i, geometryAttribute.meshPerAttribute );
  9268. }
  9269. if ( object.isInstancedMesh !== true && geometry._maxInstanceCount === undefined ) {
  9270. geometry._maxInstanceCount = geometryAttribute.meshPerAttribute * geometryAttribute.count;
  9271. }
  9272. } else {
  9273. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  9274. enableAttribute( programAttribute.location + i );
  9275. }
  9276. }
  9277. gl.bindBuffer( gl.ARRAY_BUFFER, buffer );
  9278. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  9279. vertexAttribPointer(
  9280. programAttribute.location + i,
  9281. size / programAttribute.locationSize,
  9282. type,
  9283. normalized,
  9284. size * bytesPerElement,
  9285. ( size / programAttribute.locationSize ) * i * bytesPerElement,
  9286. integer
  9287. );
  9288. }
  9289. }
  9290. } else if ( materialDefaultAttributeValues !== undefined ) {
  9291. const value = materialDefaultAttributeValues[ name ];
  9292. if ( value !== undefined ) {
  9293. switch ( value.length ) {
  9294. case 2:
  9295. gl.vertexAttrib2fv( programAttribute.location, value );
  9296. break;
  9297. case 3:
  9298. gl.vertexAttrib3fv( programAttribute.location, value );
  9299. break;
  9300. case 4:
  9301. gl.vertexAttrib4fv( programAttribute.location, value );
  9302. break;
  9303. default:
  9304. gl.vertexAttrib1fv( programAttribute.location, value );
  9305. }
  9306. }
  9307. }
  9308. }
  9309. }
  9310. disableUnusedAttributes();
  9311. }
  9312. function dispose() {
  9313. reset();
  9314. for ( const geometryId in bindingStates ) {
  9315. const programMap = bindingStates[ geometryId ];
  9316. for ( const programId in programMap ) {
  9317. const stateMap = programMap[ programId ];
  9318. for ( const wireframe in stateMap ) {
  9319. deleteVertexArrayObject( stateMap[ wireframe ].object );
  9320. delete stateMap[ wireframe ];
  9321. }
  9322. delete programMap[ programId ];
  9323. }
  9324. delete bindingStates[ geometryId ];
  9325. }
  9326. }
  9327. function releaseStatesOfGeometry( geometry ) {
  9328. if ( bindingStates[ geometry.id ] === undefined ) return;
  9329. const programMap = bindingStates[ geometry.id ];
  9330. for ( const programId in programMap ) {
  9331. const stateMap = programMap[ programId ];
  9332. for ( const wireframe in stateMap ) {
  9333. deleteVertexArrayObject( stateMap[ wireframe ].object );
  9334. delete stateMap[ wireframe ];
  9335. }
  9336. delete programMap[ programId ];
  9337. }
  9338. delete bindingStates[ geometry.id ];
  9339. }
  9340. function releaseStatesOfProgram( program ) {
  9341. for ( const geometryId in bindingStates ) {
  9342. const programMap = bindingStates[ geometryId ];
  9343. if ( programMap[ program.id ] === undefined ) continue;
  9344. const stateMap = programMap[ program.id ];
  9345. for ( const wireframe in stateMap ) {
  9346. deleteVertexArrayObject( stateMap[ wireframe ].object );
  9347. delete stateMap[ wireframe ];
  9348. }
  9349. delete programMap[ program.id ];
  9350. }
  9351. }
  9352. function reset() {
  9353. resetDefaultState();
  9354. forceUpdate = true;
  9355. if ( currentState === defaultState ) return;
  9356. currentState = defaultState;
  9357. bindVertexArrayObject( currentState.object );
  9358. }
  9359. // for backward-compatibility
  9360. function resetDefaultState() {
  9361. defaultState.geometry = null;
  9362. defaultState.program = null;
  9363. defaultState.wireframe = false;
  9364. }
  9365. return {
  9366. setup: setup,
  9367. reset: reset,
  9368. resetDefaultState: resetDefaultState,
  9369. dispose: dispose,
  9370. releaseStatesOfGeometry: releaseStatesOfGeometry,
  9371. releaseStatesOfProgram: releaseStatesOfProgram,
  9372. initAttributes: initAttributes,
  9373. enableAttribute: enableAttribute,
  9374. disableUnusedAttributes: disableUnusedAttributes
  9375. };
  9376. }
  9377. function WebGLBufferRenderer( gl, extensions, info, capabilities ) {
  9378. const isWebGL2 = capabilities.isWebGL2;
  9379. let mode;
  9380. function setMode( value ) {
  9381. mode = value;
  9382. }
  9383. function render( start, count ) {
  9384. gl.drawArrays( mode, start, count );
  9385. info.update( count, mode, 1 );
  9386. }
  9387. function renderInstances( start, count, primcount ) {
  9388. if ( primcount === 0 ) return;
  9389. let extension, methodName;
  9390. if ( isWebGL2 ) {
  9391. extension = gl;
  9392. methodName = 'drawArraysInstanced';
  9393. } else {
  9394. extension = extensions.get( 'ANGLE_instanced_arrays' );
  9395. methodName = 'drawArraysInstancedANGLE';
  9396. if ( extension === null ) {
  9397. console.error( 'THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  9398. return;
  9399. }
  9400. }
  9401. extension[ methodName ]( mode, start, count, primcount );
  9402. info.update( count, mode, primcount );
  9403. }
  9404. function renderMultiDraw( starts, counts, drawCount ) {
  9405. if ( drawCount === 0 ) return;
  9406. const extension = extensions.get( 'WEBGL_multi_draw' );
  9407. if ( extension === null ) {
  9408. for ( let i = 0; i < drawCount; i ++ ) {
  9409. this.render( starts[ i ], counts[ i ] );
  9410. }
  9411. } else {
  9412. extension.multiDrawArraysWEBGL( mode, starts, 0, counts, 0, drawCount );
  9413. let elementCount = 0;
  9414. for ( let i = 0; i < drawCount; i ++ ) {
  9415. elementCount += counts[ i ];
  9416. }
  9417. info.update( elementCount, mode, 1 );
  9418. }
  9419. }
  9420. //
  9421. this.setMode = setMode;
  9422. this.render = render;
  9423. this.renderInstances = renderInstances;
  9424. this.renderMultiDraw = renderMultiDraw;
  9425. }
  9426. function WebGLCapabilities( gl, extensions, parameters ) {
  9427. let maxAnisotropy;
  9428. function getMaxAnisotropy() {
  9429. if ( maxAnisotropy !== undefined ) return maxAnisotropy;
  9430. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  9431. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  9432. maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT );
  9433. } else {
  9434. maxAnisotropy = 0;
  9435. }
  9436. return maxAnisotropy;
  9437. }
  9438. function getMaxPrecision( precision ) {
  9439. if ( precision === 'highp' ) {
  9440. if ( gl.getShaderPrecisionFormat( gl.VERTEX_SHADER, gl.HIGH_FLOAT ).precision > 0 &&
  9441. gl.getShaderPrecisionFormat( gl.FRAGMENT_SHADER, gl.HIGH_FLOAT ).precision > 0 ) {
  9442. return 'highp';
  9443. }
  9444. precision = 'mediump';
  9445. }
  9446. if ( precision === 'mediump' ) {
  9447. if ( gl.getShaderPrecisionFormat( gl.VERTEX_SHADER, gl.MEDIUM_FLOAT ).precision > 0 &&
  9448. gl.getShaderPrecisionFormat( gl.FRAGMENT_SHADER, gl.MEDIUM_FLOAT ).precision > 0 ) {
  9449. return 'mediump';
  9450. }
  9451. }
  9452. return 'lowp';
  9453. }
  9454. const isWebGL2 = typeof WebGL2RenderingContext !== 'undefined' && gl.constructor.name === 'WebGL2RenderingContext';
  9455. let precision = parameters.precision !== undefined ? parameters.precision : 'highp';
  9456. const maxPrecision = getMaxPrecision( precision );
  9457. if ( maxPrecision !== precision ) {
  9458. console.warn( 'THREE.WebGLRenderer:', precision, 'not supported, using', maxPrecision, 'instead.' );
  9459. precision = maxPrecision;
  9460. }
  9461. const drawBuffers = isWebGL2 || extensions.has( 'WEBGL_draw_buffers' );
  9462. const logarithmicDepthBuffer = parameters.logarithmicDepthBuffer === true;
  9463. const maxTextures = gl.getParameter( gl.MAX_TEXTURE_IMAGE_UNITS );
  9464. const maxVertexTextures = gl.getParameter( gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS );
  9465. const maxTextureSize = gl.getParameter( gl.MAX_TEXTURE_SIZE );
  9466. const maxCubemapSize = gl.getParameter( gl.MAX_CUBE_MAP_TEXTURE_SIZE );
  9467. const maxAttributes = gl.getParameter( gl.MAX_VERTEX_ATTRIBS );
  9468. const maxVertexUniforms = gl.getParameter( gl.MAX_VERTEX_UNIFORM_VECTORS );
  9469. const maxVaryings = gl.getParameter( gl.MAX_VARYING_VECTORS );
  9470. const maxFragmentUniforms = gl.getParameter( gl.MAX_FRAGMENT_UNIFORM_VECTORS );
  9471. const vertexTextures = maxVertexTextures > 0;
  9472. const floatFragmentTextures = isWebGL2 || extensions.has( 'OES_texture_float' );
  9473. const floatVertexTextures = vertexTextures && floatFragmentTextures;
  9474. const maxSamples = isWebGL2 ? gl.getParameter( gl.MAX_SAMPLES ) : 0;
  9475. return {
  9476. isWebGL2: isWebGL2,
  9477. drawBuffers: drawBuffers,
  9478. getMaxAnisotropy: getMaxAnisotropy,
  9479. getMaxPrecision: getMaxPrecision,
  9480. precision: precision,
  9481. logarithmicDepthBuffer: logarithmicDepthBuffer,
  9482. maxTextures: maxTextures,
  9483. maxVertexTextures: maxVertexTextures,
  9484. maxTextureSize: maxTextureSize,
  9485. maxCubemapSize: maxCubemapSize,
  9486. maxAttributes: maxAttributes,
  9487. maxVertexUniforms: maxVertexUniforms,
  9488. maxVaryings: maxVaryings,
  9489. maxFragmentUniforms: maxFragmentUniforms,
  9490. vertexTextures: vertexTextures,
  9491. floatFragmentTextures: floatFragmentTextures,
  9492. floatVertexTextures: floatVertexTextures,
  9493. maxSamples: maxSamples
  9494. };
  9495. }
  9496. function WebGLClipping( properties ) {
  9497. const scope = this;
  9498. let globalState = null,
  9499. numGlobalPlanes = 0,
  9500. localClippingEnabled = false,
  9501. renderingShadows = false;
  9502. const plane = new Plane(),
  9503. viewNormalMatrix = new Matrix3(),
  9504. uniform = { value: null, needsUpdate: false };
  9505. this.uniform = uniform;
  9506. this.numPlanes = 0;
  9507. this.numIntersection = 0;
  9508. this.init = function ( planes, enableLocalClipping ) {
  9509. const enabled =
  9510. planes.length !== 0 ||
  9511. enableLocalClipping ||
  9512. // enable state of previous frame - the clipping code has to
  9513. // run another frame in order to reset the state:
  9514. numGlobalPlanes !== 0 ||
  9515. localClippingEnabled;
  9516. localClippingEnabled = enableLocalClipping;
  9517. numGlobalPlanes = planes.length;
  9518. return enabled;
  9519. };
  9520. this.beginShadows = function () {
  9521. renderingShadows = true;
  9522. projectPlanes( null );
  9523. };
  9524. this.endShadows = function () {
  9525. renderingShadows = false;
  9526. };
  9527. this.setGlobalState = function ( planes, camera ) {
  9528. globalState = projectPlanes( planes, camera, 0 );
  9529. };
  9530. this.setState = function ( material, camera, useCache ) {
  9531. const planes = material.clippingPlanes,
  9532. clipIntersection = material.clipIntersection,
  9533. clipShadows = material.clipShadows;
  9534. const materialProperties = properties.get( material );
  9535. if ( ! localClippingEnabled || planes === null || planes.length === 0 || renderingShadows && ! clipShadows ) {
  9536. // there's no local clipping
  9537. if ( renderingShadows ) {
  9538. // there's no global clipping
  9539. projectPlanes( null );
  9540. } else {
  9541. resetGlobalState();
  9542. }
  9543. } else {
  9544. const nGlobal = renderingShadows ? 0 : numGlobalPlanes,
  9545. lGlobal = nGlobal * 4;
  9546. let dstArray = materialProperties.clippingState || null;
  9547. uniform.value = dstArray; // ensure unique state
  9548. dstArray = projectPlanes( planes, camera, lGlobal, useCache );
  9549. for ( let i = 0; i !== lGlobal; ++ i ) {
  9550. dstArray[ i ] = globalState[ i ];
  9551. }
  9552. materialProperties.clippingState = dstArray;
  9553. this.numIntersection = clipIntersection ? this.numPlanes : 0;
  9554. this.numPlanes += nGlobal;
  9555. }
  9556. };
  9557. function resetGlobalState() {
  9558. if ( uniform.value !== globalState ) {
  9559. uniform.value = globalState;
  9560. uniform.needsUpdate = numGlobalPlanes > 0;
  9561. }
  9562. scope.numPlanes = numGlobalPlanes;
  9563. scope.numIntersection = 0;
  9564. }
  9565. function projectPlanes( planes, camera, dstOffset, skipTransform ) {
  9566. const nPlanes = planes !== null ? planes.length : 0;
  9567. let dstArray = null;
  9568. if ( nPlanes !== 0 ) {
  9569. dstArray = uniform.value;
  9570. if ( skipTransform !== true || dstArray === null ) {
  9571. const flatSize = dstOffset + nPlanes * 4,
  9572. viewMatrix = camera.matrixWorldInverse;
  9573. viewNormalMatrix.getNormalMatrix( viewMatrix );
  9574. if ( dstArray === null || dstArray.length < flatSize ) {
  9575. dstArray = new Float32Array( flatSize );
  9576. }
  9577. for ( let i = 0, i4 = dstOffset; i !== nPlanes; ++ i, i4 += 4 ) {
  9578. plane.copy( planes[ i ] ).applyMatrix4( viewMatrix, viewNormalMatrix );
  9579. plane.normal.toArray( dstArray, i4 );
  9580. dstArray[ i4 + 3 ] = plane.constant;
  9581. }
  9582. }
  9583. uniform.value = dstArray;
  9584. uniform.needsUpdate = true;
  9585. }
  9586. scope.numPlanes = nPlanes;
  9587. scope.numIntersection = 0;
  9588. return dstArray;
  9589. }
  9590. }
  9591. function WebGLCubeMaps( renderer ) {
  9592. let cubemaps = new WeakMap();
  9593. function mapTextureMapping( texture, mapping ) {
  9594. if ( mapping === EquirectangularReflectionMapping ) {
  9595. texture.mapping = CubeReflectionMapping;
  9596. } else if ( mapping === EquirectangularRefractionMapping ) {
  9597. texture.mapping = CubeRefractionMapping;
  9598. }
  9599. return texture;
  9600. }
  9601. function get( texture ) {
  9602. if ( texture && texture.isTexture ) {
  9603. const mapping = texture.mapping;
  9604. if ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) {
  9605. if ( cubemaps.has( texture ) ) {
  9606. const cubemap = cubemaps.get( texture ).texture;
  9607. return mapTextureMapping( cubemap, texture.mapping );
  9608. } else {
  9609. const image = texture.image;
  9610. if ( image && image.height > 0 ) {
  9611. const renderTarget = new WebGLCubeRenderTarget( image.height );
  9612. renderTarget.fromEquirectangularTexture( renderer, texture );
  9613. cubemaps.set( texture, renderTarget );
  9614. texture.addEventListener( 'dispose', onTextureDispose );
  9615. return mapTextureMapping( renderTarget.texture, texture.mapping );
  9616. } else {
  9617. // image not yet ready. try the conversion next frame
  9618. return null;
  9619. }
  9620. }
  9621. }
  9622. }
  9623. return texture;
  9624. }
  9625. function onTextureDispose( event ) {
  9626. const texture = event.target;
  9627. texture.removeEventListener( 'dispose', onTextureDispose );
  9628. const cubemap = cubemaps.get( texture );
  9629. if ( cubemap !== undefined ) {
  9630. cubemaps.delete( texture );
  9631. cubemap.dispose();
  9632. }
  9633. }
  9634. function dispose() {
  9635. cubemaps = new WeakMap();
  9636. }
  9637. return {
  9638. get: get,
  9639. dispose: dispose
  9640. };
  9641. }
  9642. class OrthographicCamera extends Camera {
  9643. constructor( left = - 1, right = 1, top = 1, bottom = - 1, near = 0.1, far = 2000 ) {
  9644. super();
  9645. this.isOrthographicCamera = true;
  9646. this.type = 'OrthographicCamera';
  9647. this.zoom = 1;
  9648. this.view = null;
  9649. this.left = left;
  9650. this.right = right;
  9651. this.top = top;
  9652. this.bottom = bottom;
  9653. this.near = near;
  9654. this.far = far;
  9655. this.updateProjectionMatrix();
  9656. }
  9657. copy( source, recursive ) {
  9658. super.copy( source, recursive );
  9659. this.left = source.left;
  9660. this.right = source.right;
  9661. this.top = source.top;
  9662. this.bottom = source.bottom;
  9663. this.near = source.near;
  9664. this.far = source.far;
  9665. this.zoom = source.zoom;
  9666. this.view = source.view === null ? null : Object.assign( {}, source.view );
  9667. return this;
  9668. }
  9669. setViewOffset( fullWidth, fullHeight, x, y, width, height ) {
  9670. if ( this.view === null ) {
  9671. this.view = {
  9672. enabled: true,
  9673. fullWidth: 1,
  9674. fullHeight: 1,
  9675. offsetX: 0,
  9676. offsetY: 0,
  9677. width: 1,
  9678. height: 1
  9679. };
  9680. }
  9681. this.view.enabled = true;
  9682. this.view.fullWidth = fullWidth;
  9683. this.view.fullHeight = fullHeight;
  9684. this.view.offsetX = x;
  9685. this.view.offsetY = y;
  9686. this.view.width = width;
  9687. this.view.height = height;
  9688. this.updateProjectionMatrix();
  9689. }
  9690. clearViewOffset() {
  9691. if ( this.view !== null ) {
  9692. this.view.enabled = false;
  9693. }
  9694. this.updateProjectionMatrix();
  9695. }
  9696. updateProjectionMatrix() {
  9697. const dx = ( this.right - this.left ) / ( 2 * this.zoom );
  9698. const dy = ( this.top - this.bottom ) / ( 2 * this.zoom );
  9699. const cx = ( this.right + this.left ) / 2;
  9700. const cy = ( this.top + this.bottom ) / 2;
  9701. let left = cx - dx;
  9702. let right = cx + dx;
  9703. let top = cy + dy;
  9704. let bottom = cy - dy;
  9705. if ( this.view !== null && this.view.enabled ) {
  9706. const scaleW = ( this.right - this.left ) / this.view.fullWidth / this.zoom;
  9707. const scaleH = ( this.top - this.bottom ) / this.view.fullHeight / this.zoom;
  9708. left += scaleW * this.view.offsetX;
  9709. right = left + scaleW * this.view.width;
  9710. top -= scaleH * this.view.offsetY;
  9711. bottom = top - scaleH * this.view.height;
  9712. }
  9713. this.projectionMatrix.makeOrthographic( left, right, top, bottom, this.near, this.far, this.coordinateSystem );
  9714. this.projectionMatrixInverse.copy( this.projectionMatrix ).invert();
  9715. }
  9716. toJSON( meta ) {
  9717. const data = super.toJSON( meta );
  9718. data.object.zoom = this.zoom;
  9719. data.object.left = this.left;
  9720. data.object.right = this.right;
  9721. data.object.top = this.top;
  9722. data.object.bottom = this.bottom;
  9723. data.object.near = this.near;
  9724. data.object.far = this.far;
  9725. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  9726. return data;
  9727. }
  9728. }
  9729. const LOD_MIN = 4;
  9730. // The standard deviations (radians) associated with the extra mips. These are
  9731. // chosen to approximate a Trowbridge-Reitz distribution function times the
  9732. // geometric shadowing function. These sigma values squared must match the
  9733. // variance #defines in cube_uv_reflection_fragment.glsl.js.
  9734. const EXTRA_LOD_SIGMA = [ 0.125, 0.215, 0.35, 0.446, 0.526, 0.582 ];
  9735. // The maximum length of the blur for loop. Smaller sigmas will use fewer
  9736. // samples and exit early, but not recompile the shader.
  9737. const MAX_SAMPLES = 20;
  9738. const _flatCamera = /*@__PURE__*/ new OrthographicCamera();
  9739. const _clearColor = /*@__PURE__*/ new Color();
  9740. let _oldTarget = null;
  9741. let _oldActiveCubeFace = 0;
  9742. let _oldActiveMipmapLevel = 0;
  9743. // Golden Ratio
  9744. const PHI = ( 1 + Math.sqrt( 5 ) ) / 2;
  9745. const INV_PHI = 1 / PHI;
  9746. // Vertices of a dodecahedron (except the opposites, which represent the
  9747. // same axis), used as axis directions evenly spread on a sphere.
  9748. const _axisDirections = [
  9749. /*@__PURE__*/ new Vector3( 1, 1, 1 ),
  9750. /*@__PURE__*/ new Vector3( - 1, 1, 1 ),
  9751. /*@__PURE__*/ new Vector3( 1, 1, - 1 ),
  9752. /*@__PURE__*/ new Vector3( - 1, 1, - 1 ),
  9753. /*@__PURE__*/ new Vector3( 0, PHI, INV_PHI ),
  9754. /*@__PURE__*/ new Vector3( 0, PHI, - INV_PHI ),
  9755. /*@__PURE__*/ new Vector3( INV_PHI, 0, PHI ),
  9756. /*@__PURE__*/ new Vector3( - INV_PHI, 0, PHI ),
  9757. /*@__PURE__*/ new Vector3( PHI, INV_PHI, 0 ),
  9758. /*@__PURE__*/ new Vector3( - PHI, INV_PHI, 0 ) ];
  9759. /**
  9760. * This class generates a Prefiltered, Mipmapped Radiance Environment Map
  9761. * (PMREM) from a cubeMap environment texture. This allows different levels of
  9762. * blur to be quickly accessed based on material roughness. It is packed into a
  9763. * special CubeUV format that allows us to perform custom interpolation so that
  9764. * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap
  9765. * chain, it only goes down to the LOD_MIN level (above), and then creates extra
  9766. * even more filtered 'mips' at the same LOD_MIN resolution, associated with
  9767. * higher roughness levels. In this way we maintain resolution to smoothly
  9768. * interpolate diffuse lighting while limiting sampling computation.
  9769. *
  9770. * Paper: Fast, Accurate Image-Based Lighting
  9771. * https://drive.google.com/file/d/15y8r_UpKlU9SvV4ILb0C3qCPecS8pvLz/view
  9772. */
  9773. class PMREMGenerator {
  9774. constructor( renderer ) {
  9775. this._renderer = renderer;
  9776. this._pingPongRenderTarget = null;
  9777. this._lodMax = 0;
  9778. this._cubeSize = 0;
  9779. this._lodPlanes = [];
  9780. this._sizeLods = [];
  9781. this._sigmas = [];
  9782. this._blurMaterial = null;
  9783. this._cubemapMaterial = null;
  9784. this._equirectMaterial = null;
  9785. this._compileMaterial( this._blurMaterial );
  9786. }
  9787. /**
  9788. * Generates a PMREM from a supplied Scene, which can be faster than using an
  9789. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  9790. * in radians to be applied to the scene before PMREM generation. Optional near
  9791. * and far planes ensure the scene is rendered in its entirety (the cubeCamera
  9792. * is placed at the origin).
  9793. */
  9794. fromScene( scene, sigma = 0, near = 0.1, far = 100 ) {
  9795. _oldTarget = this._renderer.getRenderTarget();
  9796. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  9797. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  9798. this._setSize( 256 );
  9799. const cubeUVRenderTarget = this._allocateTargets();
  9800. cubeUVRenderTarget.depthBuffer = true;
  9801. this._sceneToCubeUV( scene, near, far, cubeUVRenderTarget );
  9802. if ( sigma > 0 ) {
  9803. this._blur( cubeUVRenderTarget, 0, 0, sigma );
  9804. }
  9805. this._applyPMREM( cubeUVRenderTarget );
  9806. this._cleanup( cubeUVRenderTarget );
  9807. return cubeUVRenderTarget;
  9808. }
  9809. /**
  9810. * Generates a PMREM from an equirectangular texture, which can be either LDR
  9811. * or HDR. The ideal input image size is 1k (1024 x 512),
  9812. * as this matches best with the 256 x 256 cubemap output.
  9813. */
  9814. fromEquirectangular( equirectangular, renderTarget = null ) {
  9815. return this._fromTexture( equirectangular, renderTarget );
  9816. }
  9817. /**
  9818. * Generates a PMREM from an cubemap texture, which can be either LDR
  9819. * or HDR. The ideal input cube size is 256 x 256,
  9820. * as this matches best with the 256 x 256 cubemap output.
  9821. */
  9822. fromCubemap( cubemap, renderTarget = null ) {
  9823. return this._fromTexture( cubemap, renderTarget );
  9824. }
  9825. /**
  9826. * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during
  9827. * your texture's network fetch for increased concurrency.
  9828. */
  9829. compileCubemapShader() {
  9830. if ( this._cubemapMaterial === null ) {
  9831. this._cubemapMaterial = _getCubemapMaterial();
  9832. this._compileMaterial( this._cubemapMaterial );
  9833. }
  9834. }
  9835. /**
  9836. * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during
  9837. * your texture's network fetch for increased concurrency.
  9838. */
  9839. compileEquirectangularShader() {
  9840. if ( this._equirectMaterial === null ) {
  9841. this._equirectMaterial = _getEquirectMaterial();
  9842. this._compileMaterial( this._equirectMaterial );
  9843. }
  9844. }
  9845. /**
  9846. * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class,
  9847. * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on
  9848. * one of them will cause any others to also become unusable.
  9849. */
  9850. dispose() {
  9851. this._dispose();
  9852. if ( this._cubemapMaterial !== null ) this._cubemapMaterial.dispose();
  9853. if ( this._equirectMaterial !== null ) this._equirectMaterial.dispose();
  9854. }
  9855. // private interface
  9856. _setSize( cubeSize ) {
  9857. this._lodMax = Math.floor( Math.log2( cubeSize ) );
  9858. this._cubeSize = Math.pow( 2, this._lodMax );
  9859. }
  9860. _dispose() {
  9861. if ( this._blurMaterial !== null ) this._blurMaterial.dispose();
  9862. if ( this._pingPongRenderTarget !== null ) this._pingPongRenderTarget.dispose();
  9863. for ( let i = 0; i < this._lodPlanes.length; i ++ ) {
  9864. this._lodPlanes[ i ].dispose();
  9865. }
  9866. }
  9867. _cleanup( outputTarget ) {
  9868. this._renderer.setRenderTarget( _oldTarget, _oldActiveCubeFace, _oldActiveMipmapLevel );
  9869. outputTarget.scissorTest = false;
  9870. _setViewport( outputTarget, 0, 0, outputTarget.width, outputTarget.height );
  9871. }
  9872. _fromTexture( texture, renderTarget ) {
  9873. if ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping ) {
  9874. this._setSize( texture.image.length === 0 ? 16 : ( texture.image[ 0 ].width || texture.image[ 0 ].image.width ) );
  9875. } else { // Equirectangular
  9876. this._setSize( texture.image.width / 4 );
  9877. }
  9878. _oldTarget = this._renderer.getRenderTarget();
  9879. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  9880. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  9881. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  9882. this._textureToCubeUV( texture, cubeUVRenderTarget );
  9883. this._applyPMREM( cubeUVRenderTarget );
  9884. this._cleanup( cubeUVRenderTarget );
  9885. return cubeUVRenderTarget;
  9886. }
  9887. _allocateTargets() {
  9888. const width = 3 * Math.max( this._cubeSize, 16 * 7 );
  9889. const height = 4 * this._cubeSize;
  9890. const params = {
  9891. magFilter: LinearFilter,
  9892. minFilter: LinearFilter,
  9893. generateMipmaps: false,
  9894. type: HalfFloatType,
  9895. format: RGBAFormat,
  9896. colorSpace: LinearSRGBColorSpace,
  9897. depthBuffer: false
  9898. };
  9899. const cubeUVRenderTarget = _createRenderTarget( width, height, params );
  9900. if ( this._pingPongRenderTarget === null || this._pingPongRenderTarget.width !== width || this._pingPongRenderTarget.height !== height ) {
  9901. if ( this._pingPongRenderTarget !== null ) {
  9902. this._dispose();
  9903. }
  9904. this._pingPongRenderTarget = _createRenderTarget( width, height, params );
  9905. const { _lodMax } = this;
  9906. ( { sizeLods: this._sizeLods, lodPlanes: this._lodPlanes, sigmas: this._sigmas } = _createPlanes( _lodMax ) );
  9907. this._blurMaterial = _getBlurShader( _lodMax, width, height );
  9908. }
  9909. return cubeUVRenderTarget;
  9910. }
  9911. _compileMaterial( material ) {
  9912. const tmpMesh = new Mesh( this._lodPlanes[ 0 ], material );
  9913. this._renderer.compile( tmpMesh, _flatCamera );
  9914. }
  9915. _sceneToCubeUV( scene, near, far, cubeUVRenderTarget ) {
  9916. const fov = 90;
  9917. const aspect = 1;
  9918. const cubeCamera = new PerspectiveCamera( fov, aspect, near, far );
  9919. const upSign = [ 1, - 1, 1, 1, 1, 1 ];
  9920. const forwardSign = [ 1, 1, 1, - 1, - 1, - 1 ];
  9921. const renderer = this._renderer;
  9922. const originalAutoClear = renderer.autoClear;
  9923. const toneMapping = renderer.toneMapping;
  9924. renderer.getClearColor( _clearColor );
  9925. renderer.toneMapping = NoToneMapping;
  9926. renderer.autoClear = false;
  9927. const backgroundMaterial = new MeshBasicMaterial( {
  9928. name: 'PMREM.Background',
  9929. side: BackSide,
  9930. depthWrite: false,
  9931. depthTest: false,
  9932. } );
  9933. const backgroundBox = new Mesh( new BoxGeometry(), backgroundMaterial );
  9934. let useSolidColor = false;
  9935. const background = scene.background;
  9936. if ( background ) {
  9937. if ( background.isColor ) {
  9938. backgroundMaterial.color.copy( background );
  9939. scene.background = null;
  9940. useSolidColor = true;
  9941. }
  9942. } else {
  9943. backgroundMaterial.color.copy( _clearColor );
  9944. useSolidColor = true;
  9945. }
  9946. for ( let i = 0; i < 6; i ++ ) {
  9947. const col = i % 3;
  9948. if ( col === 0 ) {
  9949. cubeCamera.up.set( 0, upSign[ i ], 0 );
  9950. cubeCamera.lookAt( forwardSign[ i ], 0, 0 );
  9951. } else if ( col === 1 ) {
  9952. cubeCamera.up.set( 0, 0, upSign[ i ] );
  9953. cubeCamera.lookAt( 0, forwardSign[ i ], 0 );
  9954. } else {
  9955. cubeCamera.up.set( 0, upSign[ i ], 0 );
  9956. cubeCamera.lookAt( 0, 0, forwardSign[ i ] );
  9957. }
  9958. const size = this._cubeSize;
  9959. _setViewport( cubeUVRenderTarget, col * size, i > 2 ? size : 0, size, size );
  9960. renderer.setRenderTarget( cubeUVRenderTarget );
  9961. if ( useSolidColor ) {
  9962. renderer.render( backgroundBox, cubeCamera );
  9963. }
  9964. renderer.render( scene, cubeCamera );
  9965. }
  9966. backgroundBox.geometry.dispose();
  9967. backgroundBox.material.dispose();
  9968. renderer.toneMapping = toneMapping;
  9969. renderer.autoClear = originalAutoClear;
  9970. scene.background = background;
  9971. }
  9972. _textureToCubeUV( texture, cubeUVRenderTarget ) {
  9973. const renderer = this._renderer;
  9974. const isCubeTexture = ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping );
  9975. if ( isCubeTexture ) {
  9976. if ( this._cubemapMaterial === null ) {
  9977. this._cubemapMaterial = _getCubemapMaterial();
  9978. }
  9979. this._cubemapMaterial.uniforms.flipEnvMap.value = ( texture.isRenderTargetTexture === false ) ? - 1 : 1;
  9980. } else {
  9981. if ( this._equirectMaterial === null ) {
  9982. this._equirectMaterial = _getEquirectMaterial();
  9983. }
  9984. }
  9985. const material = isCubeTexture ? this._cubemapMaterial : this._equirectMaterial;
  9986. const mesh = new Mesh( this._lodPlanes[ 0 ], material );
  9987. const uniforms = material.uniforms;
  9988. uniforms[ 'envMap' ].value = texture;
  9989. const size = this._cubeSize;
  9990. _setViewport( cubeUVRenderTarget, 0, 0, 3 * size, 2 * size );
  9991. renderer.setRenderTarget( cubeUVRenderTarget );
  9992. renderer.render( mesh, _flatCamera );
  9993. }
  9994. _applyPMREM( cubeUVRenderTarget ) {
  9995. const renderer = this._renderer;
  9996. const autoClear = renderer.autoClear;
  9997. renderer.autoClear = false;
  9998. for ( let i = 1; i < this._lodPlanes.length; i ++ ) {
  9999. const sigma = Math.sqrt( this._sigmas[ i ] * this._sigmas[ i ] - this._sigmas[ i - 1 ] * this._sigmas[ i - 1 ] );
  10000. const poleAxis = _axisDirections[ ( i - 1 ) % _axisDirections.length ];
  10001. this._blur( cubeUVRenderTarget, i - 1, i, sigma, poleAxis );
  10002. }
  10003. renderer.autoClear = autoClear;
  10004. }
  10005. /**
  10006. * This is a two-pass Gaussian blur for a cubemap. Normally this is done
  10007. * vertically and horizontally, but this breaks down on a cube. Here we apply
  10008. * the blur latitudinally (around the poles), and then longitudinally (towards
  10009. * the poles) to approximate the orthogonally-separable blur. It is least
  10010. * accurate at the poles, but still does a decent job.
  10011. */
  10012. _blur( cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis ) {
  10013. const pingPongRenderTarget = this._pingPongRenderTarget;
  10014. this._halfBlur(
  10015. cubeUVRenderTarget,
  10016. pingPongRenderTarget,
  10017. lodIn,
  10018. lodOut,
  10019. sigma,
  10020. 'latitudinal',
  10021. poleAxis );
  10022. this._halfBlur(
  10023. pingPongRenderTarget,
  10024. cubeUVRenderTarget,
  10025. lodOut,
  10026. lodOut,
  10027. sigma,
  10028. 'longitudinal',
  10029. poleAxis );
  10030. }
  10031. _halfBlur( targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis ) {
  10032. const renderer = this._renderer;
  10033. const blurMaterial = this._blurMaterial;
  10034. if ( direction !== 'latitudinal' && direction !== 'longitudinal' ) {
  10035. console.error(
  10036. 'blur direction must be either latitudinal or longitudinal!' );
  10037. }
  10038. // Number of standard deviations at which to cut off the discrete approximation.
  10039. const STANDARD_DEVIATIONS = 3;
  10040. const blurMesh = new Mesh( this._lodPlanes[ lodOut ], blurMaterial );
  10041. const blurUniforms = blurMaterial.uniforms;
  10042. const pixels = this._sizeLods[ lodIn ] - 1;
  10043. const radiansPerPixel = isFinite( sigmaRadians ) ? Math.PI / ( 2 * pixels ) : 2 * Math.PI / ( 2 * MAX_SAMPLES - 1 );
  10044. const sigmaPixels = sigmaRadians / radiansPerPixel;
  10045. const samples = isFinite( sigmaRadians ) ? 1 + Math.floor( STANDARD_DEVIATIONS * sigmaPixels ) : MAX_SAMPLES;
  10046. if ( samples > MAX_SAMPLES ) {
  10047. console.warn( `sigmaRadians, ${
  10048. sigmaRadians}, is too large and will clip, as it requested ${
  10049. samples} samples when the maximum is set to ${MAX_SAMPLES}` );
  10050. }
  10051. const weights = [];
  10052. let sum = 0;
  10053. for ( let i = 0; i < MAX_SAMPLES; ++ i ) {
  10054. const x = i / sigmaPixels;
  10055. const weight = Math.exp( - x * x / 2 );
  10056. weights.push( weight );
  10057. if ( i === 0 ) {
  10058. sum += weight;
  10059. } else if ( i < samples ) {
  10060. sum += 2 * weight;
  10061. }
  10062. }
  10063. for ( let i = 0; i < weights.length; i ++ ) {
  10064. weights[ i ] = weights[ i ] / sum;
  10065. }
  10066. blurUniforms[ 'envMap' ].value = targetIn.texture;
  10067. blurUniforms[ 'samples' ].value = samples;
  10068. blurUniforms[ 'weights' ].value = weights;
  10069. blurUniforms[ 'latitudinal' ].value = direction === 'latitudinal';
  10070. if ( poleAxis ) {
  10071. blurUniforms[ 'poleAxis' ].value = poleAxis;
  10072. }
  10073. const { _lodMax } = this;
  10074. blurUniforms[ 'dTheta' ].value = radiansPerPixel;
  10075. blurUniforms[ 'mipInt' ].value = _lodMax - lodIn;
  10076. const outputSize = this._sizeLods[ lodOut ];
  10077. const x = 3 * outputSize * ( lodOut > _lodMax - LOD_MIN ? lodOut - _lodMax + LOD_MIN : 0 );
  10078. const y = 4 * ( this._cubeSize - outputSize );
  10079. _setViewport( targetOut, x, y, 3 * outputSize, 2 * outputSize );
  10080. renderer.setRenderTarget( targetOut );
  10081. renderer.render( blurMesh, _flatCamera );
  10082. }
  10083. }
  10084. function _createPlanes( lodMax ) {
  10085. const lodPlanes = [];
  10086. const sizeLods = [];
  10087. const sigmas = [];
  10088. let lod = lodMax;
  10089. const totalLods = lodMax - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length;
  10090. for ( let i = 0; i < totalLods; i ++ ) {
  10091. const sizeLod = Math.pow( 2, lod );
  10092. sizeLods.push( sizeLod );
  10093. let sigma = 1.0 / sizeLod;
  10094. if ( i > lodMax - LOD_MIN ) {
  10095. sigma = EXTRA_LOD_SIGMA[ i - lodMax + LOD_MIN - 1 ];
  10096. } else if ( i === 0 ) {
  10097. sigma = 0;
  10098. }
  10099. sigmas.push( sigma );
  10100. const texelSize = 1.0 / ( sizeLod - 2 );
  10101. const min = - texelSize;
  10102. const max = 1 + texelSize;
  10103. const uv1 = [ min, min, max, min, max, max, min, min, max, max, min, max ];
  10104. const cubeFaces = 6;
  10105. const vertices = 6;
  10106. const positionSize = 3;
  10107. const uvSize = 2;
  10108. const faceIndexSize = 1;
  10109. const position = new Float32Array( positionSize * vertices * cubeFaces );
  10110. const uv = new Float32Array( uvSize * vertices * cubeFaces );
  10111. const faceIndex = new Float32Array( faceIndexSize * vertices * cubeFaces );
  10112. for ( let face = 0; face < cubeFaces; face ++ ) {
  10113. const x = ( face % 3 ) * 2 / 3 - 1;
  10114. const y = face > 2 ? 0 : - 1;
  10115. const coordinates = [
  10116. x, y, 0,
  10117. x + 2 / 3, y, 0,
  10118. x + 2 / 3, y + 1, 0,
  10119. x, y, 0,
  10120. x + 2 / 3, y + 1, 0,
  10121. x, y + 1, 0
  10122. ];
  10123. position.set( coordinates, positionSize * vertices * face );
  10124. uv.set( uv1, uvSize * vertices * face );
  10125. const fill = [ face, face, face, face, face, face ];
  10126. faceIndex.set( fill, faceIndexSize * vertices * face );
  10127. }
  10128. const planes = new BufferGeometry();
  10129. planes.setAttribute( 'position', new BufferAttribute( position, positionSize ) );
  10130. planes.setAttribute( 'uv', new BufferAttribute( uv, uvSize ) );
  10131. planes.setAttribute( 'faceIndex', new BufferAttribute( faceIndex, faceIndexSize ) );
  10132. lodPlanes.push( planes );
  10133. if ( lod > LOD_MIN ) {
  10134. lod --;
  10135. }
  10136. }
  10137. return { lodPlanes, sizeLods, sigmas };
  10138. }
  10139. function _createRenderTarget( width, height, params ) {
  10140. const cubeUVRenderTarget = new WebGLRenderTarget( width, height, params );
  10141. cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping;
  10142. cubeUVRenderTarget.texture.name = 'PMREM.cubeUv';
  10143. cubeUVRenderTarget.scissorTest = true;
  10144. return cubeUVRenderTarget;
  10145. }
  10146. function _setViewport( target, x, y, width, height ) {
  10147. target.viewport.set( x, y, width, height );
  10148. target.scissor.set( x, y, width, height );
  10149. }
  10150. function _getBlurShader( lodMax, width, height ) {
  10151. const weights = new Float32Array( MAX_SAMPLES );
  10152. const poleAxis = new Vector3( 0, 1, 0 );
  10153. const shaderMaterial = new ShaderMaterial( {
  10154. name: 'SphericalGaussianBlur',
  10155. defines: {
  10156. 'n': MAX_SAMPLES,
  10157. 'CUBEUV_TEXEL_WIDTH': 1.0 / width,
  10158. 'CUBEUV_TEXEL_HEIGHT': 1.0 / height,
  10159. 'CUBEUV_MAX_MIP': `${lodMax}.0`,
  10160. },
  10161. uniforms: {
  10162. 'envMap': { value: null },
  10163. 'samples': { value: 1 },
  10164. 'weights': { value: weights },
  10165. 'latitudinal': { value: false },
  10166. 'dTheta': { value: 0 },
  10167. 'mipInt': { value: 0 },
  10168. 'poleAxis': { value: poleAxis }
  10169. },
  10170. vertexShader: _getCommonVertexShader(),
  10171. fragmentShader: /* glsl */`
  10172. precision mediump float;
  10173. precision mediump int;
  10174. varying vec3 vOutputDirection;
  10175. uniform sampler2D envMap;
  10176. uniform int samples;
  10177. uniform float weights[ n ];
  10178. uniform bool latitudinal;
  10179. uniform float dTheta;
  10180. uniform float mipInt;
  10181. uniform vec3 poleAxis;
  10182. #define ENVMAP_TYPE_CUBE_UV
  10183. #include <cube_uv_reflection_fragment>
  10184. vec3 getSample( float theta, vec3 axis ) {
  10185. float cosTheta = cos( theta );
  10186. // Rodrigues' axis-angle rotation
  10187. vec3 sampleDirection = vOutputDirection * cosTheta
  10188. + cross( axis, vOutputDirection ) * sin( theta )
  10189. + axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta );
  10190. return bilinearCubeUV( envMap, sampleDirection, mipInt );
  10191. }
  10192. void main() {
  10193. vec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection );
  10194. if ( all( equal( axis, vec3( 0.0 ) ) ) ) {
  10195. axis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x );
  10196. }
  10197. axis = normalize( axis );
  10198. gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );
  10199. gl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis );
  10200. for ( int i = 1; i < n; i++ ) {
  10201. if ( i >= samples ) {
  10202. break;
  10203. }
  10204. float theta = dTheta * float( i );
  10205. gl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis );
  10206. gl_FragColor.rgb += weights[ i ] * getSample( theta, axis );
  10207. }
  10208. }
  10209. `,
  10210. blending: NoBlending,
  10211. depthTest: false,
  10212. depthWrite: false
  10213. } );
  10214. return shaderMaterial;
  10215. }
  10216. function _getEquirectMaterial() {
  10217. return new ShaderMaterial( {
  10218. name: 'EquirectangularToCubeUV',
  10219. uniforms: {
  10220. 'envMap': { value: null }
  10221. },
  10222. vertexShader: _getCommonVertexShader(),
  10223. fragmentShader: /* glsl */`
  10224. precision mediump float;
  10225. precision mediump int;
  10226. varying vec3 vOutputDirection;
  10227. uniform sampler2D envMap;
  10228. #include <common>
  10229. void main() {
  10230. vec3 outputDirection = normalize( vOutputDirection );
  10231. vec2 uv = equirectUv( outputDirection );
  10232. gl_FragColor = vec4( texture2D ( envMap, uv ).rgb, 1.0 );
  10233. }
  10234. `,
  10235. blending: NoBlending,
  10236. depthTest: false,
  10237. depthWrite: false
  10238. } );
  10239. }
  10240. function _getCubemapMaterial() {
  10241. return new ShaderMaterial( {
  10242. name: 'CubemapToCubeUV',
  10243. uniforms: {
  10244. 'envMap': { value: null },
  10245. 'flipEnvMap': { value: - 1 }
  10246. },
  10247. vertexShader: _getCommonVertexShader(),
  10248. fragmentShader: /* glsl */`
  10249. precision mediump float;
  10250. precision mediump int;
  10251. uniform float flipEnvMap;
  10252. varying vec3 vOutputDirection;
  10253. uniform samplerCube envMap;
  10254. void main() {
  10255. gl_FragColor = textureCube( envMap, vec3( flipEnvMap * vOutputDirection.x, vOutputDirection.yz ) );
  10256. }
  10257. `,
  10258. blending: NoBlending,
  10259. depthTest: false,
  10260. depthWrite: false
  10261. } );
  10262. }
  10263. function _getCommonVertexShader() {
  10264. return /* glsl */`
  10265. precision mediump float;
  10266. precision mediump int;
  10267. attribute float faceIndex;
  10268. varying vec3 vOutputDirection;
  10269. // RH coordinate system; PMREM face-indexing convention
  10270. vec3 getDirection( vec2 uv, float face ) {
  10271. uv = 2.0 * uv - 1.0;
  10272. vec3 direction = vec3( uv, 1.0 );
  10273. if ( face == 0.0 ) {
  10274. direction = direction.zyx; // ( 1, v, u ) pos x
  10275. } else if ( face == 1.0 ) {
  10276. direction = direction.xzy;
  10277. direction.xz *= -1.0; // ( -u, 1, -v ) pos y
  10278. } else if ( face == 2.0 ) {
  10279. direction.x *= -1.0; // ( -u, v, 1 ) pos z
  10280. } else if ( face == 3.0 ) {
  10281. direction = direction.zyx;
  10282. direction.xz *= -1.0; // ( -1, v, -u ) neg x
  10283. } else if ( face == 4.0 ) {
  10284. direction = direction.xzy;
  10285. direction.xy *= -1.0; // ( -u, -1, v ) neg y
  10286. } else if ( face == 5.0 ) {
  10287. direction.z *= -1.0; // ( u, v, -1 ) neg z
  10288. }
  10289. return direction;
  10290. }
  10291. void main() {
  10292. vOutputDirection = getDirection( uv, faceIndex );
  10293. gl_Position = vec4( position, 1.0 );
  10294. }
  10295. `;
  10296. }
  10297. function WebGLCubeUVMaps( renderer ) {
  10298. let cubeUVmaps = new WeakMap();
  10299. let pmremGenerator = null;
  10300. function get( texture ) {
  10301. if ( texture && texture.isTexture ) {
  10302. const mapping = texture.mapping;
  10303. const isEquirectMap = ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping );
  10304. const isCubeMap = ( mapping === CubeReflectionMapping || mapping === CubeRefractionMapping );
  10305. // equirect/cube map to cubeUV conversion
  10306. if ( isEquirectMap || isCubeMap ) {
  10307. if ( texture.isRenderTargetTexture && texture.needsPMREMUpdate === true ) {
  10308. texture.needsPMREMUpdate = false;
  10309. let renderTarget = cubeUVmaps.get( texture );
  10310. if ( pmremGenerator === null ) pmremGenerator = new PMREMGenerator( renderer );
  10311. renderTarget = isEquirectMap ? pmremGenerator.fromEquirectangular( texture, renderTarget ) : pmremGenerator.fromCubemap( texture, renderTarget );
  10312. cubeUVmaps.set( texture, renderTarget );
  10313. return renderTarget.texture;
  10314. } else {
  10315. if ( cubeUVmaps.has( texture ) ) {
  10316. return cubeUVmaps.get( texture ).texture;
  10317. } else {
  10318. const image = texture.image;
  10319. if ( ( isEquirectMap && image && image.height > 0 ) || ( isCubeMap && image && isCubeTextureComplete( image ) ) ) {
  10320. if ( pmremGenerator === null ) pmremGenerator = new PMREMGenerator( renderer );
  10321. const renderTarget = isEquirectMap ? pmremGenerator.fromEquirectangular( texture ) : pmremGenerator.fromCubemap( texture );
  10322. cubeUVmaps.set( texture, renderTarget );
  10323. texture.addEventListener( 'dispose', onTextureDispose );
  10324. return renderTarget.texture;
  10325. } else {
  10326. // image not yet ready. try the conversion next frame
  10327. return null;
  10328. }
  10329. }
  10330. }
  10331. }
  10332. }
  10333. return texture;
  10334. }
  10335. function isCubeTextureComplete( image ) {
  10336. let count = 0;
  10337. const length = 6;
  10338. for ( let i = 0; i < length; i ++ ) {
  10339. if ( image[ i ] !== undefined ) count ++;
  10340. }
  10341. return count === length;
  10342. }
  10343. function onTextureDispose( event ) {
  10344. const texture = event.target;
  10345. texture.removeEventListener( 'dispose', onTextureDispose );
  10346. const cubemapUV = cubeUVmaps.get( texture );
  10347. if ( cubemapUV !== undefined ) {
  10348. cubeUVmaps.delete( texture );
  10349. cubemapUV.dispose();
  10350. }
  10351. }
  10352. function dispose() {
  10353. cubeUVmaps = new WeakMap();
  10354. if ( pmremGenerator !== null ) {
  10355. pmremGenerator.dispose();
  10356. pmremGenerator = null;
  10357. }
  10358. }
  10359. return {
  10360. get: get,
  10361. dispose: dispose
  10362. };
  10363. }
  10364. function WebGLExtensions( gl ) {
  10365. const extensions = {};
  10366. function getExtension( name ) {
  10367. if ( extensions[ name ] !== undefined ) {
  10368. return extensions[ name ];
  10369. }
  10370. let extension;
  10371. switch ( name ) {
  10372. case 'WEBGL_depth_texture':
  10373. extension = gl.getExtension( 'WEBGL_depth_texture' ) || gl.getExtension( 'MOZ_WEBGL_depth_texture' ) || gl.getExtension( 'WEBKIT_WEBGL_depth_texture' );
  10374. break;
  10375. case 'EXT_texture_filter_anisotropic':
  10376. extension = gl.getExtension( 'EXT_texture_filter_anisotropic' ) || gl.getExtension( 'MOZ_EXT_texture_filter_anisotropic' ) || gl.getExtension( 'WEBKIT_EXT_texture_filter_anisotropic' );
  10377. break;
  10378. case 'WEBGL_compressed_texture_s3tc':
  10379. extension = gl.getExtension( 'WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'MOZ_WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_s3tc' );
  10380. break;
  10381. case 'WEBGL_compressed_texture_pvrtc':
  10382. extension = gl.getExtension( 'WEBGL_compressed_texture_pvrtc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_pvrtc' );
  10383. break;
  10384. default:
  10385. extension = gl.getExtension( name );
  10386. }
  10387. extensions[ name ] = extension;
  10388. return extension;
  10389. }
  10390. return {
  10391. has: function ( name ) {
  10392. return getExtension( name ) !== null;
  10393. },
  10394. init: function ( capabilities ) {
  10395. if ( capabilities.isWebGL2 ) {
  10396. getExtension( 'EXT_color_buffer_float' );
  10397. getExtension( 'WEBGL_clip_cull_distance' );
  10398. } else {
  10399. getExtension( 'WEBGL_depth_texture' );
  10400. getExtension( 'OES_texture_float' );
  10401. getExtension( 'OES_texture_half_float' );
  10402. getExtension( 'OES_texture_half_float_linear' );
  10403. getExtension( 'OES_standard_derivatives' );
  10404. getExtension( 'OES_element_index_uint' );
  10405. getExtension( 'OES_vertex_array_object' );
  10406. getExtension( 'ANGLE_instanced_arrays' );
  10407. }
  10408. getExtension( 'OES_texture_float_linear' );
  10409. getExtension( 'EXT_color_buffer_half_float' );
  10410. getExtension( 'WEBGL_multisampled_render_to_texture' );
  10411. },
  10412. get: function ( name ) {
  10413. const extension = getExtension( name );
  10414. if ( extension === null ) {
  10415. console.warn( 'THREE.WebGLRenderer: ' + name + ' extension not supported.' );
  10416. }
  10417. return extension;
  10418. }
  10419. };
  10420. }
  10421. function WebGLGeometries( gl, attributes, info, bindingStates ) {
  10422. const geometries = {};
  10423. const wireframeAttributes = new WeakMap();
  10424. function onGeometryDispose( event ) {
  10425. const geometry = event.target;
  10426. if ( geometry.index !== null ) {
  10427. attributes.remove( geometry.index );
  10428. }
  10429. for ( const name in geometry.attributes ) {
  10430. attributes.remove( geometry.attributes[ name ] );
  10431. }
  10432. for ( const name in geometry.morphAttributes ) {
  10433. const array = geometry.morphAttributes[ name ];
  10434. for ( let i = 0, l = array.length; i < l; i ++ ) {
  10435. attributes.remove( array[ i ] );
  10436. }
  10437. }
  10438. geometry.removeEventListener( 'dispose', onGeometryDispose );
  10439. delete geometries[ geometry.id ];
  10440. const attribute = wireframeAttributes.get( geometry );
  10441. if ( attribute ) {
  10442. attributes.remove( attribute );
  10443. wireframeAttributes.delete( geometry );
  10444. }
  10445. bindingStates.releaseStatesOfGeometry( geometry );
  10446. if ( geometry.isInstancedBufferGeometry === true ) {
  10447. delete geometry._maxInstanceCount;
  10448. }
  10449. //
  10450. info.memory.geometries --;
  10451. }
  10452. function get( object, geometry ) {
  10453. if ( geometries[ geometry.id ] === true ) return geometry;
  10454. geometry.addEventListener( 'dispose', onGeometryDispose );
  10455. geometries[ geometry.id ] = true;
  10456. info.memory.geometries ++;
  10457. return geometry;
  10458. }
  10459. function update( geometry ) {
  10460. const geometryAttributes = geometry.attributes;
  10461. // Updating index buffer in VAO now. See WebGLBindingStates.
  10462. for ( const name in geometryAttributes ) {
  10463. attributes.update( geometryAttributes[ name ], gl.ARRAY_BUFFER );
  10464. }
  10465. // morph targets
  10466. const morphAttributes = geometry.morphAttributes;
  10467. for ( const name in morphAttributes ) {
  10468. const array = morphAttributes[ name ];
  10469. for ( let i = 0, l = array.length; i < l; i ++ ) {
  10470. attributes.update( array[ i ], gl.ARRAY_BUFFER );
  10471. }
  10472. }
  10473. }
  10474. function updateWireframeAttribute( geometry ) {
  10475. const indices = [];
  10476. const geometryIndex = geometry.index;
  10477. const geometryPosition = geometry.attributes.position;
  10478. let version = 0;
  10479. if ( geometryIndex !== null ) {
  10480. const array = geometryIndex.array;
  10481. version = geometryIndex.version;
  10482. for ( let i = 0, l = array.length; i < l; i += 3 ) {
  10483. const a = array[ i + 0 ];
  10484. const b = array[ i + 1 ];
  10485. const c = array[ i + 2 ];
  10486. indices.push( a, b, b, c, c, a );
  10487. }
  10488. } else if ( geometryPosition !== undefined ) {
  10489. const array = geometryPosition.array;
  10490. version = geometryPosition.version;
  10491. for ( let i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) {
  10492. const a = i + 0;
  10493. const b = i + 1;
  10494. const c = i + 2;
  10495. indices.push( a, b, b, c, c, a );
  10496. }
  10497. } else {
  10498. return;
  10499. }
  10500. const attribute = new ( arrayNeedsUint32( indices ) ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 );
  10501. attribute.version = version;
  10502. // Updating index buffer in VAO now. See WebGLBindingStates
  10503. //
  10504. const previousAttribute = wireframeAttributes.get( geometry );
  10505. if ( previousAttribute ) attributes.remove( previousAttribute );
  10506. //
  10507. wireframeAttributes.set( geometry, attribute );
  10508. }
  10509. function getWireframeAttribute( geometry ) {
  10510. const currentAttribute = wireframeAttributes.get( geometry );
  10511. if ( currentAttribute ) {
  10512. const geometryIndex = geometry.index;
  10513. if ( geometryIndex !== null ) {
  10514. // if the attribute is obsolete, create a new one
  10515. if ( currentAttribute.version < geometryIndex.version ) {
  10516. updateWireframeAttribute( geometry );
  10517. }
  10518. }
  10519. } else {
  10520. updateWireframeAttribute( geometry );
  10521. }
  10522. return wireframeAttributes.get( geometry );
  10523. }
  10524. return {
  10525. get: get,
  10526. update: update,
  10527. getWireframeAttribute: getWireframeAttribute
  10528. };
  10529. }
  10530. function WebGLIndexedBufferRenderer( gl, extensions, info, capabilities ) {
  10531. const isWebGL2 = capabilities.isWebGL2;
  10532. let mode;
  10533. function setMode( value ) {
  10534. mode = value;
  10535. }
  10536. let type, bytesPerElement;
  10537. function setIndex( value ) {
  10538. type = value.type;
  10539. bytesPerElement = value.bytesPerElement;
  10540. }
  10541. function render( start, count ) {
  10542. gl.drawElements( mode, count, type, start * bytesPerElement );
  10543. info.update( count, mode, 1 );
  10544. }
  10545. function renderInstances( start, count, primcount ) {
  10546. if ( primcount === 0 ) return;
  10547. let extension, methodName;
  10548. if ( isWebGL2 ) {
  10549. extension = gl;
  10550. methodName = 'drawElementsInstanced';
  10551. } else {
  10552. extension = extensions.get( 'ANGLE_instanced_arrays' );
  10553. methodName = 'drawElementsInstancedANGLE';
  10554. if ( extension === null ) {
  10555. console.error( 'THREE.WebGLIndexedBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  10556. return;
  10557. }
  10558. }
  10559. extension[ methodName ]( mode, count, type, start * bytesPerElement, primcount );
  10560. info.update( count, mode, primcount );
  10561. }
  10562. function renderMultiDraw( starts, counts, drawCount ) {
  10563. if ( drawCount === 0 ) return;
  10564. const extension = extensions.get( 'WEBGL_multi_draw' );
  10565. if ( extension === null ) {
  10566. for ( let i = 0; i < drawCount; i ++ ) {
  10567. this.render( starts[ i ] / bytesPerElement, counts[ i ] );
  10568. }
  10569. } else {
  10570. extension.multiDrawElementsWEBGL( mode, counts, 0, type, starts, 0, drawCount );
  10571. let elementCount = 0;
  10572. for ( let i = 0; i < drawCount; i ++ ) {
  10573. elementCount += counts[ i ];
  10574. }
  10575. info.update( elementCount, mode, 1 );
  10576. }
  10577. }
  10578. //
  10579. this.setMode = setMode;
  10580. this.setIndex = setIndex;
  10581. this.render = render;
  10582. this.renderInstances = renderInstances;
  10583. this.renderMultiDraw = renderMultiDraw;
  10584. }
  10585. function WebGLInfo( gl ) {
  10586. const memory = {
  10587. geometries: 0,
  10588. textures: 0
  10589. };
  10590. const render = {
  10591. frame: 0,
  10592. calls: 0,
  10593. triangles: 0,
  10594. points: 0,
  10595. lines: 0
  10596. };
  10597. function update( count, mode, instanceCount ) {
  10598. render.calls ++;
  10599. switch ( mode ) {
  10600. case gl.TRIANGLES:
  10601. render.triangles += instanceCount * ( count / 3 );
  10602. break;
  10603. case gl.LINES:
  10604. render.lines += instanceCount * ( count / 2 );
  10605. break;
  10606. case gl.LINE_STRIP:
  10607. render.lines += instanceCount * ( count - 1 );
  10608. break;
  10609. case gl.LINE_LOOP:
  10610. render.lines += instanceCount * count;
  10611. break;
  10612. case gl.POINTS:
  10613. render.points += instanceCount * count;
  10614. break;
  10615. default:
  10616. console.error( 'THREE.WebGLInfo: Unknown draw mode:', mode );
  10617. break;
  10618. }
  10619. }
  10620. function reset() {
  10621. render.calls = 0;
  10622. render.triangles = 0;
  10623. render.points = 0;
  10624. render.lines = 0;
  10625. }
  10626. return {
  10627. memory: memory,
  10628. render: render,
  10629. programs: null,
  10630. autoReset: true,
  10631. reset: reset,
  10632. update: update
  10633. };
  10634. }
  10635. function numericalSort( a, b ) {
  10636. return a[ 0 ] - b[ 0 ];
  10637. }
  10638. function absNumericalSort( a, b ) {
  10639. return Math.abs( b[ 1 ] ) - Math.abs( a[ 1 ] );
  10640. }
  10641. function WebGLMorphtargets( gl, capabilities, textures ) {
  10642. const influencesList = {};
  10643. const morphInfluences = new Float32Array( 8 );
  10644. const morphTextures = new WeakMap();
  10645. const morph = new Vector4();
  10646. const workInfluences = [];
  10647. for ( let i = 0; i < 8; i ++ ) {
  10648. workInfluences[ i ] = [ i, 0 ];
  10649. }
  10650. function update( object, geometry, program ) {
  10651. const objectInfluences = object.morphTargetInfluences;
  10652. if ( capabilities.isWebGL2 === true ) {
  10653. // instead of using attributes, the WebGL 2 code path encodes morph targets
  10654. // into an array of data textures. Each layer represents a single morph target.
  10655. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  10656. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  10657. let entry = morphTextures.get( geometry );
  10658. if ( entry === undefined || entry.count !== morphTargetsCount ) {
  10659. if ( entry !== undefined ) entry.texture.dispose();
  10660. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  10661. const hasMorphNormals = geometry.morphAttributes.normal !== undefined;
  10662. const hasMorphColors = geometry.morphAttributes.color !== undefined;
  10663. const morphTargets = geometry.morphAttributes.position || [];
  10664. const morphNormals = geometry.morphAttributes.normal || [];
  10665. const morphColors = geometry.morphAttributes.color || [];
  10666. let vertexDataCount = 0;
  10667. if ( hasMorphPosition === true ) vertexDataCount = 1;
  10668. if ( hasMorphNormals === true ) vertexDataCount = 2;
  10669. if ( hasMorphColors === true ) vertexDataCount = 3;
  10670. let width = geometry.attributes.position.count * vertexDataCount;
  10671. let height = 1;
  10672. if ( width > capabilities.maxTextureSize ) {
  10673. height = Math.ceil( width / capabilities.maxTextureSize );
  10674. width = capabilities.maxTextureSize;
  10675. }
  10676. const buffer = new Float32Array( width * height * 4 * morphTargetsCount );
  10677. const texture = new DataArrayTexture( buffer, width, height, morphTargetsCount );
  10678. texture.type = FloatType;
  10679. texture.needsUpdate = true;
  10680. // fill buffer
  10681. const vertexDataStride = vertexDataCount * 4;
  10682. for ( let i = 0; i < morphTargetsCount; i ++ ) {
  10683. const morphTarget = morphTargets[ i ];
  10684. const morphNormal = morphNormals[ i ];
  10685. const morphColor = morphColors[ i ];
  10686. const offset = width * height * 4 * i;
  10687. for ( let j = 0; j < morphTarget.count; j ++ ) {
  10688. const stride = j * vertexDataStride;
  10689. if ( hasMorphPosition === true ) {
  10690. morph.fromBufferAttribute( morphTarget, j );
  10691. buffer[ offset + stride + 0 ] = morph.x;
  10692. buffer[ offset + stride + 1 ] = morph.y;
  10693. buffer[ offset + stride + 2 ] = morph.z;
  10694. buffer[ offset + stride + 3 ] = 0;
  10695. }
  10696. if ( hasMorphNormals === true ) {
  10697. morph.fromBufferAttribute( morphNormal, j );
  10698. buffer[ offset + stride + 4 ] = morph.x;
  10699. buffer[ offset + stride + 5 ] = morph.y;
  10700. buffer[ offset + stride + 6 ] = morph.z;
  10701. buffer[ offset + stride + 7 ] = 0;
  10702. }
  10703. if ( hasMorphColors === true ) {
  10704. morph.fromBufferAttribute( morphColor, j );
  10705. buffer[ offset + stride + 8 ] = morph.x;
  10706. buffer[ offset + stride + 9 ] = morph.y;
  10707. buffer[ offset + stride + 10 ] = morph.z;
  10708. buffer[ offset + stride + 11 ] = ( morphColor.itemSize === 4 ) ? morph.w : 1;
  10709. }
  10710. }
  10711. }
  10712. entry = {
  10713. count: morphTargetsCount,
  10714. texture: texture,
  10715. size: new Vector2( width, height )
  10716. };
  10717. morphTextures.set( geometry, entry );
  10718. function disposeTexture() {
  10719. texture.dispose();
  10720. morphTextures.delete( geometry );
  10721. geometry.removeEventListener( 'dispose', disposeTexture );
  10722. }
  10723. geometry.addEventListener( 'dispose', disposeTexture );
  10724. }
  10725. //
  10726. if ( object.isInstancedMesh === true && object.morphTexture !== null ) {
  10727. program.getUniforms().setValue( gl, 'morphTexture', object.morphTexture, textures );
  10728. } else {
  10729. let morphInfluencesSum = 0;
  10730. for ( let i = 0; i < objectInfluences.length; i ++ ) {
  10731. morphInfluencesSum += objectInfluences[ i ];
  10732. }
  10733. const morphBaseInfluence = geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
  10734. program.getUniforms().setValue( gl, 'morphTargetBaseInfluence', morphBaseInfluence );
  10735. program.getUniforms().setValue( gl, 'morphTargetInfluences', objectInfluences );
  10736. }
  10737. program.getUniforms().setValue( gl, 'morphTargetsTexture', entry.texture, textures );
  10738. program.getUniforms().setValue( gl, 'morphTargetsTextureSize', entry.size );
  10739. } else {
  10740. // When object doesn't have morph target influences defined, we treat it as a 0-length array
  10741. // This is important to make sure we set up morphTargetBaseInfluence / morphTargetInfluences
  10742. const length = objectInfluences === undefined ? 0 : objectInfluences.length;
  10743. let influences = influencesList[ geometry.id ];
  10744. if ( influences === undefined || influences.length !== length ) {
  10745. // initialise list
  10746. influences = [];
  10747. for ( let i = 0; i < length; i ++ ) {
  10748. influences[ i ] = [ i, 0 ];
  10749. }
  10750. influencesList[ geometry.id ] = influences;
  10751. }
  10752. // Collect influences
  10753. for ( let i = 0; i < length; i ++ ) {
  10754. const influence = influences[ i ];
  10755. influence[ 0 ] = i;
  10756. influence[ 1 ] = objectInfluences[ i ];
  10757. }
  10758. influences.sort( absNumericalSort );
  10759. for ( let i = 0; i < 8; i ++ ) {
  10760. if ( i < length && influences[ i ][ 1 ] ) {
  10761. workInfluences[ i ][ 0 ] = influences[ i ][ 0 ];
  10762. workInfluences[ i ][ 1 ] = influences[ i ][ 1 ];
  10763. } else {
  10764. workInfluences[ i ][ 0 ] = Number.MAX_SAFE_INTEGER;
  10765. workInfluences[ i ][ 1 ] = 0;
  10766. }
  10767. }
  10768. workInfluences.sort( numericalSort );
  10769. const morphTargets = geometry.morphAttributes.position;
  10770. const morphNormals = geometry.morphAttributes.normal;
  10771. let morphInfluencesSum = 0;
  10772. for ( let i = 0; i < 8; i ++ ) {
  10773. const influence = workInfluences[ i ];
  10774. const index = influence[ 0 ];
  10775. const value = influence[ 1 ];
  10776. if ( index !== Number.MAX_SAFE_INTEGER && value ) {
  10777. if ( morphTargets && geometry.getAttribute( 'morphTarget' + i ) !== morphTargets[ index ] ) {
  10778. geometry.setAttribute( 'morphTarget' + i, morphTargets[ index ] );
  10779. }
  10780. if ( morphNormals && geometry.getAttribute( 'morphNormal' + i ) !== morphNormals[ index ] ) {
  10781. geometry.setAttribute( 'morphNormal' + i, morphNormals[ index ] );
  10782. }
  10783. morphInfluences[ i ] = value;
  10784. morphInfluencesSum += value;
  10785. } else {
  10786. if ( morphTargets && geometry.hasAttribute( 'morphTarget' + i ) === true ) {
  10787. geometry.deleteAttribute( 'morphTarget' + i );
  10788. }
  10789. if ( morphNormals && geometry.hasAttribute( 'morphNormal' + i ) === true ) {
  10790. geometry.deleteAttribute( 'morphNormal' + i );
  10791. }
  10792. morphInfluences[ i ] = 0;
  10793. }
  10794. }
  10795. // GLSL shader uses formula baseinfluence * base + sum(target * influence)
  10796. // This allows us to switch between absolute morphs and relative morphs without changing shader code
  10797. // When baseinfluence = 1 - sum(influence), the above is equivalent to sum((target - base) * influence)
  10798. const morphBaseInfluence = geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
  10799. program.getUniforms().setValue( gl, 'morphTargetBaseInfluence', morphBaseInfluence );
  10800. program.getUniforms().setValue( gl, 'morphTargetInfluences', morphInfluences );
  10801. }
  10802. }
  10803. return {
  10804. update: update
  10805. };
  10806. }
  10807. function WebGLObjects( gl, geometries, attributes, info ) {
  10808. let updateMap = new WeakMap();
  10809. function update( object ) {
  10810. const frame = info.render.frame;
  10811. const geometry = object.geometry;
  10812. const buffergeometry = geometries.get( object, geometry );
  10813. // Update once per frame
  10814. if ( updateMap.get( buffergeometry ) !== frame ) {
  10815. geometries.update( buffergeometry );
  10816. updateMap.set( buffergeometry, frame );
  10817. }
  10818. if ( object.isInstancedMesh ) {
  10819. if ( object.hasEventListener( 'dispose', onInstancedMeshDispose ) === false ) {
  10820. object.addEventListener( 'dispose', onInstancedMeshDispose );
  10821. }
  10822. if ( updateMap.get( object ) !== frame ) {
  10823. attributes.update( object.instanceMatrix, gl.ARRAY_BUFFER );
  10824. if ( object.instanceColor !== null ) {
  10825. attributes.update( object.instanceColor, gl.ARRAY_BUFFER );
  10826. }
  10827. updateMap.set( object, frame );
  10828. }
  10829. }
  10830. if ( object.isSkinnedMesh ) {
  10831. const skeleton = object.skeleton;
  10832. if ( updateMap.get( skeleton ) !== frame ) {
  10833. skeleton.update();
  10834. updateMap.set( skeleton, frame );
  10835. }
  10836. }
  10837. return buffergeometry;
  10838. }
  10839. function dispose() {
  10840. updateMap = new WeakMap();
  10841. }
  10842. function onInstancedMeshDispose( event ) {
  10843. const instancedMesh = event.target;
  10844. instancedMesh.removeEventListener( 'dispose', onInstancedMeshDispose );
  10845. attributes.remove( instancedMesh.instanceMatrix );
  10846. if ( instancedMesh.instanceColor !== null ) attributes.remove( instancedMesh.instanceColor );
  10847. }
  10848. return {
  10849. update: update,
  10850. dispose: dispose
  10851. };
  10852. }
  10853. class DepthTexture extends Texture {
  10854. constructor( width, height, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, format ) {
  10855. format = format !== undefined ? format : DepthFormat;
  10856. if ( format !== DepthFormat && format !== DepthStencilFormat ) {
  10857. throw new Error( 'DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat' );
  10858. }
  10859. if ( type === undefined && format === DepthFormat ) type = UnsignedIntType;
  10860. if ( type === undefined && format === DepthStencilFormat ) type = UnsignedInt248Type;
  10861. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  10862. this.isDepthTexture = true;
  10863. this.image = { width: width, height: height };
  10864. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  10865. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  10866. this.flipY = false;
  10867. this.generateMipmaps = false;
  10868. this.compareFunction = null;
  10869. }
  10870. copy( source ) {
  10871. super.copy( source );
  10872. this.compareFunction = source.compareFunction;
  10873. return this;
  10874. }
  10875. toJSON( meta ) {
  10876. const data = super.toJSON( meta );
  10877. if ( this.compareFunction !== null ) data.compareFunction = this.compareFunction;
  10878. return data;
  10879. }
  10880. }
  10881. /**
  10882. * Uniforms of a program.
  10883. * Those form a tree structure with a special top-level container for the root,
  10884. * which you get by calling 'new WebGLUniforms( gl, program )'.
  10885. *
  10886. *
  10887. * Properties of inner nodes including the top-level container:
  10888. *
  10889. * .seq - array of nested uniforms
  10890. * .map - nested uniforms by name
  10891. *
  10892. *
  10893. * Methods of all nodes except the top-level container:
  10894. *
  10895. * .setValue( gl, value, [textures] )
  10896. *
  10897. * uploads a uniform value(s)
  10898. * the 'textures' parameter is needed for sampler uniforms
  10899. *
  10900. *
  10901. * Static methods of the top-level container (textures factorizations):
  10902. *
  10903. * .upload( gl, seq, values, textures )
  10904. *
  10905. * sets uniforms in 'seq' to 'values[id].value'
  10906. *
  10907. * .seqWithValue( seq, values ) : filteredSeq
  10908. *
  10909. * filters 'seq' entries with corresponding entry in values
  10910. *
  10911. *
  10912. * Methods of the top-level container (textures factorizations):
  10913. *
  10914. * .setValue( gl, name, value, textures )
  10915. *
  10916. * sets uniform with name 'name' to 'value'
  10917. *
  10918. * .setOptional( gl, obj, prop )
  10919. *
  10920. * like .set for an optional property of the object
  10921. *
  10922. */
  10923. const emptyTexture = /*@__PURE__*/ new Texture();
  10924. const emptyShadowTexture = /*@__PURE__*/ new DepthTexture( 1, 1 );
  10925. emptyShadowTexture.compareFunction = LessEqualCompare;
  10926. const emptyArrayTexture = /*@__PURE__*/ new DataArrayTexture();
  10927. const empty3dTexture = /*@__PURE__*/ new Data3DTexture();
  10928. const emptyCubeTexture = /*@__PURE__*/ new CubeTexture();
  10929. // --- Utilities ---
  10930. // Array Caches (provide typed arrays for temporary by size)
  10931. const arrayCacheF32 = [];
  10932. const arrayCacheI32 = [];
  10933. // Float32Array caches used for uploading Matrix uniforms
  10934. const mat4array = new Float32Array( 16 );
  10935. const mat3array = new Float32Array( 9 );
  10936. const mat2array = new Float32Array( 4 );
  10937. // Flattening for arrays of vectors and matrices
  10938. function flatten( array, nBlocks, blockSize ) {
  10939. const firstElem = array[ 0 ];
  10940. if ( firstElem <= 0 || firstElem > 0 ) return array;
  10941. // unoptimized: ! isNaN( firstElem )
  10942. // see http://jacksondunstan.com/articles/983
  10943. const n = nBlocks * blockSize;
  10944. let r = arrayCacheF32[ n ];
  10945. if ( r === undefined ) {
  10946. r = new Float32Array( n );
  10947. arrayCacheF32[ n ] = r;
  10948. }
  10949. if ( nBlocks !== 0 ) {
  10950. firstElem.toArray( r, 0 );
  10951. for ( let i = 1, offset = 0; i !== nBlocks; ++ i ) {
  10952. offset += blockSize;
  10953. array[ i ].toArray( r, offset );
  10954. }
  10955. }
  10956. return r;
  10957. }
  10958. function arraysEqual( a, b ) {
  10959. if ( a.length !== b.length ) return false;
  10960. for ( let i = 0, l = a.length; i < l; i ++ ) {
  10961. if ( a[ i ] !== b[ i ] ) return false;
  10962. }
  10963. return true;
  10964. }
  10965. function copyArray( a, b ) {
  10966. for ( let i = 0, l = b.length; i < l; i ++ ) {
  10967. a[ i ] = b[ i ];
  10968. }
  10969. }
  10970. // Texture unit allocation
  10971. function allocTexUnits( textures, n ) {
  10972. let r = arrayCacheI32[ n ];
  10973. if ( r === undefined ) {
  10974. r = new Int32Array( n );
  10975. arrayCacheI32[ n ] = r;
  10976. }
  10977. for ( let i = 0; i !== n; ++ i ) {
  10978. r[ i ] = textures.allocateTextureUnit();
  10979. }
  10980. return r;
  10981. }
  10982. // --- Setters ---
  10983. // Note: Defining these methods externally, because they come in a bunch
  10984. // and this way their names minify.
  10985. // Single scalar
  10986. function setValueV1f( gl, v ) {
  10987. const cache = this.cache;
  10988. if ( cache[ 0 ] === v ) return;
  10989. gl.uniform1f( this.addr, v );
  10990. cache[ 0 ] = v;
  10991. }
  10992. // Single float vector (from flat array or THREE.VectorN)
  10993. function setValueV2f( gl, v ) {
  10994. const cache = this.cache;
  10995. if ( v.x !== undefined ) {
  10996. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y ) {
  10997. gl.uniform2f( this.addr, v.x, v.y );
  10998. cache[ 0 ] = v.x;
  10999. cache[ 1 ] = v.y;
  11000. }
  11001. } else {
  11002. if ( arraysEqual( cache, v ) ) return;
  11003. gl.uniform2fv( this.addr, v );
  11004. copyArray( cache, v );
  11005. }
  11006. }
  11007. function setValueV3f( gl, v ) {
  11008. const cache = this.cache;
  11009. if ( v.x !== undefined ) {
  11010. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z ) {
  11011. gl.uniform3f( this.addr, v.x, v.y, v.z );
  11012. cache[ 0 ] = v.x;
  11013. cache[ 1 ] = v.y;
  11014. cache[ 2 ] = v.z;
  11015. }
  11016. } else if ( v.r !== undefined ) {
  11017. if ( cache[ 0 ] !== v.r || cache[ 1 ] !== v.g || cache[ 2 ] !== v.b ) {
  11018. gl.uniform3f( this.addr, v.r, v.g, v.b );
  11019. cache[ 0 ] = v.r;
  11020. cache[ 1 ] = v.g;
  11021. cache[ 2 ] = v.b;
  11022. }
  11023. } else {
  11024. if ( arraysEqual( cache, v ) ) return;
  11025. gl.uniform3fv( this.addr, v );
  11026. copyArray( cache, v );
  11027. }
  11028. }
  11029. function setValueV4f( gl, v ) {
  11030. const cache = this.cache;
  11031. if ( v.x !== undefined ) {
  11032. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z || cache[ 3 ] !== v.w ) {
  11033. gl.uniform4f( this.addr, v.x, v.y, v.z, v.w );
  11034. cache[ 0 ] = v.x;
  11035. cache[ 1 ] = v.y;
  11036. cache[ 2 ] = v.z;
  11037. cache[ 3 ] = v.w;
  11038. }
  11039. } else {
  11040. if ( arraysEqual( cache, v ) ) return;
  11041. gl.uniform4fv( this.addr, v );
  11042. copyArray( cache, v );
  11043. }
  11044. }
  11045. // Single matrix (from flat array or THREE.MatrixN)
  11046. function setValueM2( gl, v ) {
  11047. const cache = this.cache;
  11048. const elements = v.elements;
  11049. if ( elements === undefined ) {
  11050. if ( arraysEqual( cache, v ) ) return;
  11051. gl.uniformMatrix2fv( this.addr, false, v );
  11052. copyArray( cache, v );
  11053. } else {
  11054. if ( arraysEqual( cache, elements ) ) return;
  11055. mat2array.set( elements );
  11056. gl.uniformMatrix2fv( this.addr, false, mat2array );
  11057. copyArray( cache, elements );
  11058. }
  11059. }
  11060. function setValueM3( gl, v ) {
  11061. const cache = this.cache;
  11062. const elements = v.elements;
  11063. if ( elements === undefined ) {
  11064. if ( arraysEqual( cache, v ) ) return;
  11065. gl.uniformMatrix3fv( this.addr, false, v );
  11066. copyArray( cache, v );
  11067. } else {
  11068. if ( arraysEqual( cache, elements ) ) return;
  11069. mat3array.set( elements );
  11070. gl.uniformMatrix3fv( this.addr, false, mat3array );
  11071. copyArray( cache, elements );
  11072. }
  11073. }
  11074. function setValueM4( gl, v ) {
  11075. const cache = this.cache;
  11076. const elements = v.elements;
  11077. if ( elements === undefined ) {
  11078. if ( arraysEqual( cache, v ) ) return;
  11079. gl.uniformMatrix4fv( this.addr, false, v );
  11080. copyArray( cache, v );
  11081. } else {
  11082. if ( arraysEqual( cache, elements ) ) return;
  11083. mat4array.set( elements );
  11084. gl.uniformMatrix4fv( this.addr, false, mat4array );
  11085. copyArray( cache, elements );
  11086. }
  11087. }
  11088. // Single integer / boolean
  11089. function setValueV1i( gl, v ) {
  11090. const cache = this.cache;
  11091. if ( cache[ 0 ] === v ) return;
  11092. gl.uniform1i( this.addr, v );
  11093. cache[ 0 ] = v;
  11094. }
  11095. // Single integer / boolean vector (from flat array or THREE.VectorN)
  11096. function setValueV2i( gl, v ) {
  11097. const cache = this.cache;
  11098. if ( v.x !== undefined ) {
  11099. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y ) {
  11100. gl.uniform2i( this.addr, v.x, v.y );
  11101. cache[ 0 ] = v.x;
  11102. cache[ 1 ] = v.y;
  11103. }
  11104. } else {
  11105. if ( arraysEqual( cache, v ) ) return;
  11106. gl.uniform2iv( this.addr, v );
  11107. copyArray( cache, v );
  11108. }
  11109. }
  11110. function setValueV3i( gl, v ) {
  11111. const cache = this.cache;
  11112. if ( v.x !== undefined ) {
  11113. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z ) {
  11114. gl.uniform3i( this.addr, v.x, v.y, v.z );
  11115. cache[ 0 ] = v.x;
  11116. cache[ 1 ] = v.y;
  11117. cache[ 2 ] = v.z;
  11118. }
  11119. } else {
  11120. if ( arraysEqual( cache, v ) ) return;
  11121. gl.uniform3iv( this.addr, v );
  11122. copyArray( cache, v );
  11123. }
  11124. }
  11125. function setValueV4i( gl, v ) {
  11126. const cache = this.cache;
  11127. if ( v.x !== undefined ) {
  11128. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z || cache[ 3 ] !== v.w ) {
  11129. gl.uniform4i( this.addr, v.x, v.y, v.z, v.w );
  11130. cache[ 0 ] = v.x;
  11131. cache[ 1 ] = v.y;
  11132. cache[ 2 ] = v.z;
  11133. cache[ 3 ] = v.w;
  11134. }
  11135. } else {
  11136. if ( arraysEqual( cache, v ) ) return;
  11137. gl.uniform4iv( this.addr, v );
  11138. copyArray( cache, v );
  11139. }
  11140. }
  11141. // Single unsigned integer
  11142. function setValueV1ui( gl, v ) {
  11143. const cache = this.cache;
  11144. if ( cache[ 0 ] === v ) return;
  11145. gl.uniform1ui( this.addr, v );
  11146. cache[ 0 ] = v;
  11147. }
  11148. // Single unsigned integer vector (from flat array or THREE.VectorN)
  11149. function setValueV2ui( gl, v ) {
  11150. const cache = this.cache;
  11151. if ( v.x !== undefined ) {
  11152. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y ) {
  11153. gl.uniform2ui( this.addr, v.x, v.y );
  11154. cache[ 0 ] = v.x;
  11155. cache[ 1 ] = v.y;
  11156. }
  11157. } else {
  11158. if ( arraysEqual( cache, v ) ) return;
  11159. gl.uniform2uiv( this.addr, v );
  11160. copyArray( cache, v );
  11161. }
  11162. }
  11163. function setValueV3ui( gl, v ) {
  11164. const cache = this.cache;
  11165. if ( v.x !== undefined ) {
  11166. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z ) {
  11167. gl.uniform3ui( this.addr, v.x, v.y, v.z );
  11168. cache[ 0 ] = v.x;
  11169. cache[ 1 ] = v.y;
  11170. cache[ 2 ] = v.z;
  11171. }
  11172. } else {
  11173. if ( arraysEqual( cache, v ) ) return;
  11174. gl.uniform3uiv( this.addr, v );
  11175. copyArray( cache, v );
  11176. }
  11177. }
  11178. function setValueV4ui( gl, v ) {
  11179. const cache = this.cache;
  11180. if ( v.x !== undefined ) {
  11181. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z || cache[ 3 ] !== v.w ) {
  11182. gl.uniform4ui( this.addr, v.x, v.y, v.z, v.w );
  11183. cache[ 0 ] = v.x;
  11184. cache[ 1 ] = v.y;
  11185. cache[ 2 ] = v.z;
  11186. cache[ 3 ] = v.w;
  11187. }
  11188. } else {
  11189. if ( arraysEqual( cache, v ) ) return;
  11190. gl.uniform4uiv( this.addr, v );
  11191. copyArray( cache, v );
  11192. }
  11193. }
  11194. // Single texture (2D / Cube)
  11195. function setValueT1( gl, v, textures ) {
  11196. const cache = this.cache;
  11197. const unit = textures.allocateTextureUnit();
  11198. if ( cache[ 0 ] !== unit ) {
  11199. gl.uniform1i( this.addr, unit );
  11200. cache[ 0 ] = unit;
  11201. }
  11202. const emptyTexture2D = ( this.type === gl.SAMPLER_2D_SHADOW ) ? emptyShadowTexture : emptyTexture;
  11203. textures.setTexture2D( v || emptyTexture2D, unit );
  11204. }
  11205. function setValueT3D1( gl, v, textures ) {
  11206. const cache = this.cache;
  11207. const unit = textures.allocateTextureUnit();
  11208. if ( cache[ 0 ] !== unit ) {
  11209. gl.uniform1i( this.addr, unit );
  11210. cache[ 0 ] = unit;
  11211. }
  11212. textures.setTexture3D( v || empty3dTexture, unit );
  11213. }
  11214. function setValueT6( gl, v, textures ) {
  11215. const cache = this.cache;
  11216. const unit = textures.allocateTextureUnit();
  11217. if ( cache[ 0 ] !== unit ) {
  11218. gl.uniform1i( this.addr, unit );
  11219. cache[ 0 ] = unit;
  11220. }
  11221. textures.setTextureCube( v || emptyCubeTexture, unit );
  11222. }
  11223. function setValueT2DArray1( gl, v, textures ) {
  11224. const cache = this.cache;
  11225. const unit = textures.allocateTextureUnit();
  11226. if ( cache[ 0 ] !== unit ) {
  11227. gl.uniform1i( this.addr, unit );
  11228. cache[ 0 ] = unit;
  11229. }
  11230. textures.setTexture2DArray( v || emptyArrayTexture, unit );
  11231. }
  11232. // Helper to pick the right setter for the singular case
  11233. function getSingularSetter( type ) {
  11234. switch ( type ) {
  11235. case 0x1406: return setValueV1f; // FLOAT
  11236. case 0x8b50: return setValueV2f; // _VEC2
  11237. case 0x8b51: return setValueV3f; // _VEC3
  11238. case 0x8b52: return setValueV4f; // _VEC4
  11239. case 0x8b5a: return setValueM2; // _MAT2
  11240. case 0x8b5b: return setValueM3; // _MAT3
  11241. case 0x8b5c: return setValueM4; // _MAT4
  11242. case 0x1404: case 0x8b56: return setValueV1i; // INT, BOOL
  11243. case 0x8b53: case 0x8b57: return setValueV2i; // _VEC2
  11244. case 0x8b54: case 0x8b58: return setValueV3i; // _VEC3
  11245. case 0x8b55: case 0x8b59: return setValueV4i; // _VEC4
  11246. case 0x1405: return setValueV1ui; // UINT
  11247. case 0x8dc6: return setValueV2ui; // _VEC2
  11248. case 0x8dc7: return setValueV3ui; // _VEC3
  11249. case 0x8dc8: return setValueV4ui; // _VEC4
  11250. case 0x8b5e: // SAMPLER_2D
  11251. case 0x8d66: // SAMPLER_EXTERNAL_OES
  11252. case 0x8dca: // INT_SAMPLER_2D
  11253. case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
  11254. case 0x8b62: // SAMPLER_2D_SHADOW
  11255. return setValueT1;
  11256. case 0x8b5f: // SAMPLER_3D
  11257. case 0x8dcb: // INT_SAMPLER_3D
  11258. case 0x8dd3: // UNSIGNED_INT_SAMPLER_3D
  11259. return setValueT3D1;
  11260. case 0x8b60: // SAMPLER_CUBE
  11261. case 0x8dcc: // INT_SAMPLER_CUBE
  11262. case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
  11263. case 0x8dc5: // SAMPLER_CUBE_SHADOW
  11264. return setValueT6;
  11265. case 0x8dc1: // SAMPLER_2D_ARRAY
  11266. case 0x8dcf: // INT_SAMPLER_2D_ARRAY
  11267. case 0x8dd7: // UNSIGNED_INT_SAMPLER_2D_ARRAY
  11268. case 0x8dc4: // SAMPLER_2D_ARRAY_SHADOW
  11269. return setValueT2DArray1;
  11270. }
  11271. }
  11272. // Array of scalars
  11273. function setValueV1fArray( gl, v ) {
  11274. gl.uniform1fv( this.addr, v );
  11275. }
  11276. // Array of vectors (from flat array or array of THREE.VectorN)
  11277. function setValueV2fArray( gl, v ) {
  11278. const data = flatten( v, this.size, 2 );
  11279. gl.uniform2fv( this.addr, data );
  11280. }
  11281. function setValueV3fArray( gl, v ) {
  11282. const data = flatten( v, this.size, 3 );
  11283. gl.uniform3fv( this.addr, data );
  11284. }
  11285. function setValueV4fArray( gl, v ) {
  11286. const data = flatten( v, this.size, 4 );
  11287. gl.uniform4fv( this.addr, data );
  11288. }
  11289. // Array of matrices (from flat array or array of THREE.MatrixN)
  11290. function setValueM2Array( gl, v ) {
  11291. const data = flatten( v, this.size, 4 );
  11292. gl.uniformMatrix2fv( this.addr, false, data );
  11293. }
  11294. function setValueM3Array( gl, v ) {
  11295. const data = flatten( v, this.size, 9 );
  11296. gl.uniformMatrix3fv( this.addr, false, data );
  11297. }
  11298. function setValueM4Array( gl, v ) {
  11299. const data = flatten( v, this.size, 16 );
  11300. gl.uniformMatrix4fv( this.addr, false, data );
  11301. }
  11302. // Array of integer / boolean
  11303. function setValueV1iArray( gl, v ) {
  11304. gl.uniform1iv( this.addr, v );
  11305. }
  11306. // Array of integer / boolean vectors (from flat array)
  11307. function setValueV2iArray( gl, v ) {
  11308. gl.uniform2iv( this.addr, v );
  11309. }
  11310. function setValueV3iArray( gl, v ) {
  11311. gl.uniform3iv( this.addr, v );
  11312. }
  11313. function setValueV4iArray( gl, v ) {
  11314. gl.uniform4iv( this.addr, v );
  11315. }
  11316. // Array of unsigned integer
  11317. function setValueV1uiArray( gl, v ) {
  11318. gl.uniform1uiv( this.addr, v );
  11319. }
  11320. // Array of unsigned integer vectors (from flat array)
  11321. function setValueV2uiArray( gl, v ) {
  11322. gl.uniform2uiv( this.addr, v );
  11323. }
  11324. function setValueV3uiArray( gl, v ) {
  11325. gl.uniform3uiv( this.addr, v );
  11326. }
  11327. function setValueV4uiArray( gl, v ) {
  11328. gl.uniform4uiv( this.addr, v );
  11329. }
  11330. // Array of textures (2D / 3D / Cube / 2DArray)
  11331. function setValueT1Array( gl, v, textures ) {
  11332. const cache = this.cache;
  11333. const n = v.length;
  11334. const units = allocTexUnits( textures, n );
  11335. if ( ! arraysEqual( cache, units ) ) {
  11336. gl.uniform1iv( this.addr, units );
  11337. copyArray( cache, units );
  11338. }
  11339. for ( let i = 0; i !== n; ++ i ) {
  11340. textures.setTexture2D( v[ i ] || emptyTexture, units[ i ] );
  11341. }
  11342. }
  11343. function setValueT3DArray( gl, v, textures ) {
  11344. const cache = this.cache;
  11345. const n = v.length;
  11346. const units = allocTexUnits( textures, n );
  11347. if ( ! arraysEqual( cache, units ) ) {
  11348. gl.uniform1iv( this.addr, units );
  11349. copyArray( cache, units );
  11350. }
  11351. for ( let i = 0; i !== n; ++ i ) {
  11352. textures.setTexture3D( v[ i ] || empty3dTexture, units[ i ] );
  11353. }
  11354. }
  11355. function setValueT6Array( gl, v, textures ) {
  11356. const cache = this.cache;
  11357. const n = v.length;
  11358. const units = allocTexUnits( textures, n );
  11359. if ( ! arraysEqual( cache, units ) ) {
  11360. gl.uniform1iv( this.addr, units );
  11361. copyArray( cache, units );
  11362. }
  11363. for ( let i = 0; i !== n; ++ i ) {
  11364. textures.setTextureCube( v[ i ] || emptyCubeTexture, units[ i ] );
  11365. }
  11366. }
  11367. function setValueT2DArrayArray( gl, v, textures ) {
  11368. const cache = this.cache;
  11369. const n = v.length;
  11370. const units = allocTexUnits( textures, n );
  11371. if ( ! arraysEqual( cache, units ) ) {
  11372. gl.uniform1iv( this.addr, units );
  11373. copyArray( cache, units );
  11374. }
  11375. for ( let i = 0; i !== n; ++ i ) {
  11376. textures.setTexture2DArray( v[ i ] || emptyArrayTexture, units[ i ] );
  11377. }
  11378. }
  11379. // Helper to pick the right setter for a pure (bottom-level) array
  11380. function getPureArraySetter( type ) {
  11381. switch ( type ) {
  11382. case 0x1406: return setValueV1fArray; // FLOAT
  11383. case 0x8b50: return setValueV2fArray; // _VEC2
  11384. case 0x8b51: return setValueV3fArray; // _VEC3
  11385. case 0x8b52: return setValueV4fArray; // _VEC4
  11386. case 0x8b5a: return setValueM2Array; // _MAT2
  11387. case 0x8b5b: return setValueM3Array; // _MAT3
  11388. case 0x8b5c: return setValueM4Array; // _MAT4
  11389. case 0x1404: case 0x8b56: return setValueV1iArray; // INT, BOOL
  11390. case 0x8b53: case 0x8b57: return setValueV2iArray; // _VEC2
  11391. case 0x8b54: case 0x8b58: return setValueV3iArray; // _VEC3
  11392. case 0x8b55: case 0x8b59: return setValueV4iArray; // _VEC4
  11393. case 0x1405: return setValueV1uiArray; // UINT
  11394. case 0x8dc6: return setValueV2uiArray; // _VEC2
  11395. case 0x8dc7: return setValueV3uiArray; // _VEC3
  11396. case 0x8dc8: return setValueV4uiArray; // _VEC4
  11397. case 0x8b5e: // SAMPLER_2D
  11398. case 0x8d66: // SAMPLER_EXTERNAL_OES
  11399. case 0x8dca: // INT_SAMPLER_2D
  11400. case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
  11401. case 0x8b62: // SAMPLER_2D_SHADOW
  11402. return setValueT1Array;
  11403. case 0x8b5f: // SAMPLER_3D
  11404. case 0x8dcb: // INT_SAMPLER_3D
  11405. case 0x8dd3: // UNSIGNED_INT_SAMPLER_3D
  11406. return setValueT3DArray;
  11407. case 0x8b60: // SAMPLER_CUBE
  11408. case 0x8dcc: // INT_SAMPLER_CUBE
  11409. case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
  11410. case 0x8dc5: // SAMPLER_CUBE_SHADOW
  11411. return setValueT6Array;
  11412. case 0x8dc1: // SAMPLER_2D_ARRAY
  11413. case 0x8dcf: // INT_SAMPLER_2D_ARRAY
  11414. case 0x8dd7: // UNSIGNED_INT_SAMPLER_2D_ARRAY
  11415. case 0x8dc4: // SAMPLER_2D_ARRAY_SHADOW
  11416. return setValueT2DArrayArray;
  11417. }
  11418. }
  11419. // --- Uniform Classes ---
  11420. class SingleUniform {
  11421. constructor( id, activeInfo, addr ) {
  11422. this.id = id;
  11423. this.addr = addr;
  11424. this.cache = [];
  11425. this.type = activeInfo.type;
  11426. this.setValue = getSingularSetter( activeInfo.type );
  11427. // this.path = activeInfo.name; // DEBUG
  11428. }
  11429. }
  11430. class PureArrayUniform {
  11431. constructor( id, activeInfo, addr ) {
  11432. this.id = id;
  11433. this.addr = addr;
  11434. this.cache = [];
  11435. this.type = activeInfo.type;
  11436. this.size = activeInfo.size;
  11437. this.setValue = getPureArraySetter( activeInfo.type );
  11438. // this.path = activeInfo.name; // DEBUG
  11439. }
  11440. }
  11441. class StructuredUniform {
  11442. constructor( id ) {
  11443. this.id = id;
  11444. this.seq = [];
  11445. this.map = {};
  11446. }
  11447. setValue( gl, value, textures ) {
  11448. const seq = this.seq;
  11449. for ( let i = 0, n = seq.length; i !== n; ++ i ) {
  11450. const u = seq[ i ];
  11451. u.setValue( gl, value[ u.id ], textures );
  11452. }
  11453. }
  11454. }
  11455. // --- Top-level ---
  11456. // Parser - builds up the property tree from the path strings
  11457. const RePathPart = /(\w+)(\])?(\[|\.)?/g;
  11458. // extracts
  11459. // - the identifier (member name or array index)
  11460. // - followed by an optional right bracket (found when array index)
  11461. // - followed by an optional left bracket or dot (type of subscript)
  11462. //
  11463. // Note: These portions can be read in a non-overlapping fashion and
  11464. // allow straightforward parsing of the hierarchy that WebGL encodes
  11465. // in the uniform names.
  11466. function addUniform( container, uniformObject ) {
  11467. container.seq.push( uniformObject );
  11468. container.map[ uniformObject.id ] = uniformObject;
  11469. }
  11470. function parseUniform( activeInfo, addr, container ) {
  11471. const path = activeInfo.name,
  11472. pathLength = path.length;
  11473. // reset RegExp object, because of the early exit of a previous run
  11474. RePathPart.lastIndex = 0;
  11475. while ( true ) {
  11476. const match = RePathPart.exec( path ),
  11477. matchEnd = RePathPart.lastIndex;
  11478. let id = match[ 1 ];
  11479. const idIsIndex = match[ 2 ] === ']',
  11480. subscript = match[ 3 ];
  11481. if ( idIsIndex ) id = id | 0; // convert to integer
  11482. if ( subscript === undefined || subscript === '[' && matchEnd + 2 === pathLength ) {
  11483. // bare name or "pure" bottom-level array "[0]" suffix
  11484. addUniform( container, subscript === undefined ?
  11485. new SingleUniform( id, activeInfo, addr ) :
  11486. new PureArrayUniform( id, activeInfo, addr ) );
  11487. break;
  11488. } else {
  11489. // step into inner node / create it in case it doesn't exist
  11490. const map = container.map;
  11491. let next = map[ id ];
  11492. if ( next === undefined ) {
  11493. next = new StructuredUniform( id );
  11494. addUniform( container, next );
  11495. }
  11496. container = next;
  11497. }
  11498. }
  11499. }
  11500. // Root Container
  11501. class WebGLUniforms {
  11502. constructor( gl, program ) {
  11503. this.seq = [];
  11504. this.map = {};
  11505. const n = gl.getProgramParameter( program, gl.ACTIVE_UNIFORMS );
  11506. for ( let i = 0; i < n; ++ i ) {
  11507. const info = gl.getActiveUniform( program, i ),
  11508. addr = gl.getUniformLocation( program, info.name );
  11509. parseUniform( info, addr, this );
  11510. }
  11511. }
  11512. setValue( gl, name, value, textures ) {
  11513. const u = this.map[ name ];
  11514. if ( u !== undefined ) u.setValue( gl, value, textures );
  11515. }
  11516. setOptional( gl, object, name ) {
  11517. const v = object[ name ];
  11518. if ( v !== undefined ) this.setValue( gl, name, v );
  11519. }
  11520. static upload( gl, seq, values, textures ) {
  11521. for ( let i = 0, n = seq.length; i !== n; ++ i ) {
  11522. const u = seq[ i ],
  11523. v = values[ u.id ];
  11524. if ( v.needsUpdate !== false ) {
  11525. // note: always updating when .needsUpdate is undefined
  11526. u.setValue( gl, v.value, textures );
  11527. }
  11528. }
  11529. }
  11530. static seqWithValue( seq, values ) {
  11531. const r = [];
  11532. for ( let i = 0, n = seq.length; i !== n; ++ i ) {
  11533. const u = seq[ i ];
  11534. if ( u.id in values ) r.push( u );
  11535. }
  11536. return r;
  11537. }
  11538. }
  11539. function WebGLShader( gl, type, string ) {
  11540. const shader = gl.createShader( type );
  11541. gl.shaderSource( shader, string );
  11542. gl.compileShader( shader );
  11543. return shader;
  11544. }
  11545. // From https://www.khronos.org/registry/webgl/extensions/KHR_parallel_shader_compile/
  11546. const COMPLETION_STATUS_KHR = 0x91B1;
  11547. let programIdCount = 0;
  11548. function handleSource( string, errorLine ) {
  11549. const lines = string.split( '\n' );
  11550. const lines2 = [];
  11551. const from = Math.max( errorLine - 6, 0 );
  11552. const to = Math.min( errorLine + 6, lines.length );
  11553. for ( let i = from; i < to; i ++ ) {
  11554. const line = i + 1;
  11555. lines2.push( `${line === errorLine ? '>' : ' '} ${line}: ${lines[ i ]}` );
  11556. }
  11557. return lines2.join( '\n' );
  11558. }
  11559. function getEncodingComponents( colorSpace ) {
  11560. const workingPrimaries = ColorManagement.getPrimaries( ColorManagement.workingColorSpace );
  11561. const encodingPrimaries = ColorManagement.getPrimaries( colorSpace );
  11562. let gamutMapping;
  11563. if ( workingPrimaries === encodingPrimaries ) {
  11564. gamutMapping = '';
  11565. } else if ( workingPrimaries === P3Primaries && encodingPrimaries === Rec709Primaries ) {
  11566. gamutMapping = 'LinearDisplayP3ToLinearSRGB';
  11567. } else if ( workingPrimaries === Rec709Primaries && encodingPrimaries === P3Primaries ) {
  11568. gamutMapping = 'LinearSRGBToLinearDisplayP3';
  11569. }
  11570. switch ( colorSpace ) {
  11571. case LinearSRGBColorSpace:
  11572. case LinearDisplayP3ColorSpace:
  11573. return [ gamutMapping, 'LinearTransferOETF' ];
  11574. case SRGBColorSpace:
  11575. case DisplayP3ColorSpace:
  11576. return [ gamutMapping, 'sRGBTransferOETF' ];
  11577. default:
  11578. console.warn( 'THREE.WebGLProgram: Unsupported color space:', colorSpace );
  11579. return [ gamutMapping, 'LinearTransferOETF' ];
  11580. }
  11581. }
  11582. function getShaderErrors( gl, shader, type ) {
  11583. const status = gl.getShaderParameter( shader, gl.COMPILE_STATUS );
  11584. const errors = gl.getShaderInfoLog( shader ).trim();
  11585. if ( status && errors === '' ) return '';
  11586. const errorMatches = /ERROR: 0:(\d+)/.exec( errors );
  11587. if ( errorMatches ) {
  11588. // --enable-privileged-webgl-extension
  11589. // console.log( '**' + type + '**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) );
  11590. const errorLine = parseInt( errorMatches[ 1 ] );
  11591. return type.toUpperCase() + '\n\n' + errors + '\n\n' + handleSource( gl.getShaderSource( shader ), errorLine );
  11592. } else {
  11593. return errors;
  11594. }
  11595. }
  11596. function getTexelEncodingFunction( functionName, colorSpace ) {
  11597. const components = getEncodingComponents( colorSpace );
  11598. return `vec4 ${functionName}( vec4 value ) { return ${components[ 0 ]}( ${components[ 1 ]}( value ) ); }`;
  11599. }
  11600. function getToneMappingFunction( functionName, toneMapping ) {
  11601. let toneMappingName;
  11602. switch ( toneMapping ) {
  11603. case LinearToneMapping:
  11604. toneMappingName = 'Linear';
  11605. break;
  11606. case ReinhardToneMapping:
  11607. toneMappingName = 'Reinhard';
  11608. break;
  11609. case CineonToneMapping:
  11610. toneMappingName = 'OptimizedCineon';
  11611. break;
  11612. case ACESFilmicToneMapping:
  11613. toneMappingName = 'ACESFilmic';
  11614. break;
  11615. case AgXToneMapping:
  11616. toneMappingName = 'AgX';
  11617. break;
  11618. case NeutralToneMapping:
  11619. toneMappingName = 'Neutral';
  11620. break;
  11621. case CustomToneMapping:
  11622. toneMappingName = 'Custom';
  11623. break;
  11624. default:
  11625. console.warn( 'THREE.WebGLProgram: Unsupported toneMapping:', toneMapping );
  11626. toneMappingName = 'Linear';
  11627. }
  11628. return 'vec3 ' + functionName + '( vec3 color ) { return ' + toneMappingName + 'ToneMapping( color ); }';
  11629. }
  11630. function generateExtensions( parameters ) {
  11631. const chunks = [
  11632. ( parameters.extensionDerivatives || !! parameters.envMapCubeUVHeight || parameters.bumpMap || parameters.normalMapTangentSpace || parameters.clearcoatNormalMap || parameters.flatShading || parameters.alphaToCoverage || parameters.shaderID === 'physical' ) ? '#extension GL_OES_standard_derivatives : enable' : '',
  11633. ( parameters.extensionFragDepth || parameters.logarithmicDepthBuffer ) && parameters.rendererExtensionFragDepth ? '#extension GL_EXT_frag_depth : enable' : '',
  11634. ( parameters.extensionDrawBuffers && parameters.rendererExtensionDrawBuffers ) ? '#extension GL_EXT_draw_buffers : require' : '',
  11635. ( parameters.extensionShaderTextureLOD || parameters.envMap || parameters.transmission ) && parameters.rendererExtensionShaderTextureLod ? '#extension GL_EXT_shader_texture_lod : enable' : ''
  11636. ];
  11637. return chunks.filter( filterEmptyLine ).join( '\n' );
  11638. }
  11639. function generateVertexExtensions( parameters ) {
  11640. const chunks = [
  11641. parameters.extensionClipCullDistance ? '#extension GL_ANGLE_clip_cull_distance : require' : '',
  11642. parameters.extensionMultiDraw ? '#extension GL_ANGLE_multi_draw : require' : '',
  11643. ];
  11644. return chunks.filter( filterEmptyLine ).join( '\n' );
  11645. }
  11646. function generateDefines( defines ) {
  11647. const chunks = [];
  11648. for ( const name in defines ) {
  11649. const value = defines[ name ];
  11650. if ( value === false ) continue;
  11651. chunks.push( '#define ' + name + ' ' + value );
  11652. }
  11653. return chunks.join( '\n' );
  11654. }
  11655. function fetchAttributeLocations( gl, program ) {
  11656. const attributes = {};
  11657. const n = gl.getProgramParameter( program, gl.ACTIVE_ATTRIBUTES );
  11658. for ( let i = 0; i < n; i ++ ) {
  11659. const info = gl.getActiveAttrib( program, i );
  11660. const name = info.name;
  11661. let locationSize = 1;
  11662. if ( info.type === gl.FLOAT_MAT2 ) locationSize = 2;
  11663. if ( info.type === gl.FLOAT_MAT3 ) locationSize = 3;
  11664. if ( info.type === gl.FLOAT_MAT4 ) locationSize = 4;
  11665. // console.log( 'THREE.WebGLProgram: ACTIVE VERTEX ATTRIBUTE:', name, i );
  11666. attributes[ name ] = {
  11667. type: info.type,
  11668. location: gl.getAttribLocation( program, name ),
  11669. locationSize: locationSize
  11670. };
  11671. }
  11672. return attributes;
  11673. }
  11674. function filterEmptyLine( string ) {
  11675. return string !== '';
  11676. }
  11677. function replaceLightNums( string, parameters ) {
  11678. const numSpotLightCoords = parameters.numSpotLightShadows + parameters.numSpotLightMaps - parameters.numSpotLightShadowsWithMaps;
  11679. return string
  11680. .replace( /NUM_DIR_LIGHTS/g, parameters.numDirLights )
  11681. .replace( /NUM_SPOT_LIGHTS/g, parameters.numSpotLights )
  11682. .replace( /NUM_SPOT_LIGHT_MAPS/g, parameters.numSpotLightMaps )
  11683. .replace( /NUM_SPOT_LIGHT_COORDS/g, numSpotLightCoords )
  11684. .replace( /NUM_RECT_AREA_LIGHTS/g, parameters.numRectAreaLights )
  11685. .replace( /NUM_POINT_LIGHTS/g, parameters.numPointLights )
  11686. .replace( /NUM_HEMI_LIGHTS/g, parameters.numHemiLights )
  11687. .replace( /NUM_DIR_LIGHT_SHADOWS/g, parameters.numDirLightShadows )
  11688. .replace( /NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS/g, parameters.numSpotLightShadowsWithMaps )
  11689. .replace( /NUM_SPOT_LIGHT_SHADOWS/g, parameters.numSpotLightShadows )
  11690. .replace( /NUM_POINT_LIGHT_SHADOWS/g, parameters.numPointLightShadows );
  11691. }
  11692. function replaceClippingPlaneNums( string, parameters ) {
  11693. return string
  11694. .replace( /NUM_CLIPPING_PLANES/g, parameters.numClippingPlanes )
  11695. .replace( /UNION_CLIPPING_PLANES/g, ( parameters.numClippingPlanes - parameters.numClipIntersection ) );
  11696. }
  11697. // Resolve Includes
  11698. const includePattern = /^[ \t]*#include +<([\w\d./]+)>/gm;
  11699. function resolveIncludes( string ) {
  11700. return string.replace( includePattern, includeReplacer );
  11701. }
  11702. const shaderChunkMap = new Map( [
  11703. [ 'encodings_fragment', 'colorspace_fragment' ], // @deprecated, r154
  11704. [ 'encodings_pars_fragment', 'colorspace_pars_fragment' ], // @deprecated, r154
  11705. [ 'output_fragment', 'opaque_fragment' ], // @deprecated, r154
  11706. ] );
  11707. function includeReplacer( match, include ) {
  11708. let string = ShaderChunk[ include ];
  11709. if ( string === undefined ) {
  11710. const newInclude = shaderChunkMap.get( include );
  11711. if ( newInclude !== undefined ) {
  11712. string = ShaderChunk[ newInclude ];
  11713. console.warn( 'THREE.WebGLRenderer: Shader chunk "%s" has been deprecated. Use "%s" instead.', include, newInclude );
  11714. } else {
  11715. throw new Error( 'Can not resolve #include <' + include + '>' );
  11716. }
  11717. }
  11718. return resolveIncludes( string );
  11719. }
  11720. // Unroll Loops
  11721. 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;
  11722. function unrollLoops( string ) {
  11723. return string.replace( unrollLoopPattern, loopReplacer );
  11724. }
  11725. function loopReplacer( match, start, end, snippet ) {
  11726. let string = '';
  11727. for ( let i = parseInt( start ); i < parseInt( end ); i ++ ) {
  11728. string += snippet
  11729. .replace( /\[\s*i\s*\]/g, '[ ' + i + ' ]' )
  11730. .replace( /UNROLLED_LOOP_INDEX/g, i );
  11731. }
  11732. return string;
  11733. }
  11734. //
  11735. function generatePrecision( parameters ) {
  11736. let precisionstring = `precision ${parameters.precision} float;
  11737. precision ${parameters.precision} int;
  11738. precision ${parameters.precision} sampler2D;
  11739. precision ${parameters.precision} samplerCube;
  11740. `;
  11741. if ( parameters.isWebGL2 ) {
  11742. precisionstring += `precision ${parameters.precision} sampler3D;
  11743. precision ${parameters.precision} sampler2DArray;
  11744. precision ${parameters.precision} sampler2DShadow;
  11745. precision ${parameters.precision} samplerCubeShadow;
  11746. precision ${parameters.precision} sampler2DArrayShadow;
  11747. precision ${parameters.precision} isampler2D;
  11748. precision ${parameters.precision} isampler3D;
  11749. precision ${parameters.precision} isamplerCube;
  11750. precision ${parameters.precision} isampler2DArray;
  11751. precision ${parameters.precision} usampler2D;
  11752. precision ${parameters.precision} usampler3D;
  11753. precision ${parameters.precision} usamplerCube;
  11754. precision ${parameters.precision} usampler2DArray;
  11755. `;
  11756. }
  11757. if ( parameters.precision === 'highp' ) {
  11758. precisionstring += '\n#define HIGH_PRECISION';
  11759. } else if ( parameters.precision === 'mediump' ) {
  11760. precisionstring += '\n#define MEDIUM_PRECISION';
  11761. } else if ( parameters.precision === 'lowp' ) {
  11762. precisionstring += '\n#define LOW_PRECISION';
  11763. }
  11764. return precisionstring;
  11765. }
  11766. function generateShadowMapTypeDefine( parameters ) {
  11767. let shadowMapTypeDefine = 'SHADOWMAP_TYPE_BASIC';
  11768. if ( parameters.shadowMapType === PCFShadowMap ) {
  11769. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF';
  11770. } else if ( parameters.shadowMapType === PCFSoftShadowMap ) {
  11771. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF_SOFT';
  11772. } else if ( parameters.shadowMapType === VSMShadowMap ) {
  11773. shadowMapTypeDefine = 'SHADOWMAP_TYPE_VSM';
  11774. }
  11775. return shadowMapTypeDefine;
  11776. }
  11777. function generateEnvMapTypeDefine( parameters ) {
  11778. let envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  11779. if ( parameters.envMap ) {
  11780. switch ( parameters.envMapMode ) {
  11781. case CubeReflectionMapping:
  11782. case CubeRefractionMapping:
  11783. envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  11784. break;
  11785. case CubeUVReflectionMapping:
  11786. envMapTypeDefine = 'ENVMAP_TYPE_CUBE_UV';
  11787. break;
  11788. }
  11789. }
  11790. return envMapTypeDefine;
  11791. }
  11792. function generateEnvMapModeDefine( parameters ) {
  11793. let envMapModeDefine = 'ENVMAP_MODE_REFLECTION';
  11794. if ( parameters.envMap ) {
  11795. switch ( parameters.envMapMode ) {
  11796. case CubeRefractionMapping:
  11797. envMapModeDefine = 'ENVMAP_MODE_REFRACTION';
  11798. break;
  11799. }
  11800. }
  11801. return envMapModeDefine;
  11802. }
  11803. function generateEnvMapBlendingDefine( parameters ) {
  11804. let envMapBlendingDefine = 'ENVMAP_BLENDING_NONE';
  11805. if ( parameters.envMap ) {
  11806. switch ( parameters.combine ) {
  11807. case MultiplyOperation:
  11808. envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  11809. break;
  11810. case MixOperation:
  11811. envMapBlendingDefine = 'ENVMAP_BLENDING_MIX';
  11812. break;
  11813. case AddOperation:
  11814. envMapBlendingDefine = 'ENVMAP_BLENDING_ADD';
  11815. break;
  11816. }
  11817. }
  11818. return envMapBlendingDefine;
  11819. }
  11820. function generateCubeUVSize( parameters ) {
  11821. const imageHeight = parameters.envMapCubeUVHeight;
  11822. if ( imageHeight === null ) return null;
  11823. const maxMip = Math.log2( imageHeight ) - 2;
  11824. const texelHeight = 1.0 / imageHeight;
  11825. const texelWidth = 1.0 / ( 3 * Math.max( Math.pow( 2, maxMip ), 7 * 16 ) );
  11826. return { texelWidth, texelHeight, maxMip };
  11827. }
  11828. function WebGLProgram( renderer, cacheKey, parameters, bindingStates ) {
  11829. // TODO Send this event to Three.js DevTools
  11830. // console.log( 'WebGLProgram', cacheKey );
  11831. const gl = renderer.getContext();
  11832. const defines = parameters.defines;
  11833. let vertexShader = parameters.vertexShader;
  11834. let fragmentShader = parameters.fragmentShader;
  11835. const shadowMapTypeDefine = generateShadowMapTypeDefine( parameters );
  11836. const envMapTypeDefine = generateEnvMapTypeDefine( parameters );
  11837. const envMapModeDefine = generateEnvMapModeDefine( parameters );
  11838. const envMapBlendingDefine = generateEnvMapBlendingDefine( parameters );
  11839. const envMapCubeUVSize = generateCubeUVSize( parameters );
  11840. const customExtensions = parameters.isWebGL2 ? '' : generateExtensions( parameters );
  11841. const customVertexExtensions = generateVertexExtensions( parameters );
  11842. const customDefines = generateDefines( defines );
  11843. const program = gl.createProgram();
  11844. let prefixVertex, prefixFragment;
  11845. let versionString = parameters.glslVersion ? '#version ' + parameters.glslVersion + '\n' : '';
  11846. if ( parameters.isRawShaderMaterial ) {
  11847. prefixVertex = [
  11848. '#define SHADER_TYPE ' + parameters.shaderType,
  11849. '#define SHADER_NAME ' + parameters.shaderName,
  11850. customDefines
  11851. ].filter( filterEmptyLine ).join( '\n' );
  11852. if ( prefixVertex.length > 0 ) {
  11853. prefixVertex += '\n';
  11854. }
  11855. prefixFragment = [
  11856. customExtensions,
  11857. '#define SHADER_TYPE ' + parameters.shaderType,
  11858. '#define SHADER_NAME ' + parameters.shaderName,
  11859. customDefines
  11860. ].filter( filterEmptyLine ).join( '\n' );
  11861. if ( prefixFragment.length > 0 ) {
  11862. prefixFragment += '\n';
  11863. }
  11864. } else {
  11865. prefixVertex = [
  11866. generatePrecision( parameters ),
  11867. '#define SHADER_TYPE ' + parameters.shaderType,
  11868. '#define SHADER_NAME ' + parameters.shaderName,
  11869. customDefines,
  11870. parameters.extensionClipCullDistance ? '#define USE_CLIP_DISTANCE' : '',
  11871. parameters.batching ? '#define USE_BATCHING' : '',
  11872. parameters.instancing ? '#define USE_INSTANCING' : '',
  11873. parameters.instancingColor ? '#define USE_INSTANCING_COLOR' : '',
  11874. parameters.instancingMorph ? '#define USE_INSTANCING_MORPH' : '',
  11875. parameters.useFog && parameters.fog ? '#define USE_FOG' : '',
  11876. parameters.useFog && parameters.fogExp2 ? '#define FOG_EXP2' : '',
  11877. parameters.map ? '#define USE_MAP' : '',
  11878. parameters.envMap ? '#define USE_ENVMAP' : '',
  11879. parameters.envMap ? '#define ' + envMapModeDefine : '',
  11880. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  11881. parameters.aoMap ? '#define USE_AOMAP' : '',
  11882. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  11883. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  11884. parameters.normalMapObjectSpace ? '#define USE_NORMALMAP_OBJECTSPACE' : '',
  11885. parameters.normalMapTangentSpace ? '#define USE_NORMALMAP_TANGENTSPACE' : '',
  11886. parameters.displacementMap ? '#define USE_DISPLACEMENTMAP' : '',
  11887. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  11888. parameters.anisotropy ? '#define USE_ANISOTROPY' : '',
  11889. parameters.anisotropyMap ? '#define USE_ANISOTROPYMAP' : '',
  11890. parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '',
  11891. parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '',
  11892. parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '',
  11893. parameters.iridescenceMap ? '#define USE_IRIDESCENCEMAP' : '',
  11894. parameters.iridescenceThicknessMap ? '#define USE_IRIDESCENCE_THICKNESSMAP' : '',
  11895. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  11896. parameters.specularColorMap ? '#define USE_SPECULAR_COLORMAP' : '',
  11897. parameters.specularIntensityMap ? '#define USE_SPECULAR_INTENSITYMAP' : '',
  11898. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  11899. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  11900. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  11901. parameters.alphaHash ? '#define USE_ALPHAHASH' : '',
  11902. parameters.transmission ? '#define USE_TRANSMISSION' : '',
  11903. parameters.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '',
  11904. parameters.thicknessMap ? '#define USE_THICKNESSMAP' : '',
  11905. parameters.sheenColorMap ? '#define USE_SHEEN_COLORMAP' : '',
  11906. parameters.sheenRoughnessMap ? '#define USE_SHEEN_ROUGHNESSMAP' : '',
  11907. //
  11908. parameters.mapUv ? '#define MAP_UV ' + parameters.mapUv : '',
  11909. parameters.alphaMapUv ? '#define ALPHAMAP_UV ' + parameters.alphaMapUv : '',
  11910. parameters.lightMapUv ? '#define LIGHTMAP_UV ' + parameters.lightMapUv : '',
  11911. parameters.aoMapUv ? '#define AOMAP_UV ' + parameters.aoMapUv : '',
  11912. parameters.emissiveMapUv ? '#define EMISSIVEMAP_UV ' + parameters.emissiveMapUv : '',
  11913. parameters.bumpMapUv ? '#define BUMPMAP_UV ' + parameters.bumpMapUv : '',
  11914. parameters.normalMapUv ? '#define NORMALMAP_UV ' + parameters.normalMapUv : '',
  11915. parameters.displacementMapUv ? '#define DISPLACEMENTMAP_UV ' + parameters.displacementMapUv : '',
  11916. parameters.metalnessMapUv ? '#define METALNESSMAP_UV ' + parameters.metalnessMapUv : '',
  11917. parameters.roughnessMapUv ? '#define ROUGHNESSMAP_UV ' + parameters.roughnessMapUv : '',
  11918. parameters.anisotropyMapUv ? '#define ANISOTROPYMAP_UV ' + parameters.anisotropyMapUv : '',
  11919. parameters.clearcoatMapUv ? '#define CLEARCOATMAP_UV ' + parameters.clearcoatMapUv : '',
  11920. parameters.clearcoatNormalMapUv ? '#define CLEARCOAT_NORMALMAP_UV ' + parameters.clearcoatNormalMapUv : '',
  11921. parameters.clearcoatRoughnessMapUv ? '#define CLEARCOAT_ROUGHNESSMAP_UV ' + parameters.clearcoatRoughnessMapUv : '',
  11922. parameters.iridescenceMapUv ? '#define IRIDESCENCEMAP_UV ' + parameters.iridescenceMapUv : '',
  11923. parameters.iridescenceThicknessMapUv ? '#define IRIDESCENCE_THICKNESSMAP_UV ' + parameters.iridescenceThicknessMapUv : '',
  11924. parameters.sheenColorMapUv ? '#define SHEEN_COLORMAP_UV ' + parameters.sheenColorMapUv : '',
  11925. parameters.sheenRoughnessMapUv ? '#define SHEEN_ROUGHNESSMAP_UV ' + parameters.sheenRoughnessMapUv : '',
  11926. parameters.specularMapUv ? '#define SPECULARMAP_UV ' + parameters.specularMapUv : '',
  11927. parameters.specularColorMapUv ? '#define SPECULAR_COLORMAP_UV ' + parameters.specularColorMapUv : '',
  11928. parameters.specularIntensityMapUv ? '#define SPECULAR_INTENSITYMAP_UV ' + parameters.specularIntensityMapUv : '',
  11929. parameters.transmissionMapUv ? '#define TRANSMISSIONMAP_UV ' + parameters.transmissionMapUv : '',
  11930. parameters.thicknessMapUv ? '#define THICKNESSMAP_UV ' + parameters.thicknessMapUv : '',
  11931. //
  11932. parameters.vertexTangents && parameters.flatShading === false ? '#define USE_TANGENT' : '',
  11933. parameters.vertexColors ? '#define USE_COLOR' : '',
  11934. parameters.vertexAlphas ? '#define USE_COLOR_ALPHA' : '',
  11935. parameters.vertexUv1s ? '#define USE_UV1' : '',
  11936. parameters.vertexUv2s ? '#define USE_UV2' : '',
  11937. parameters.vertexUv3s ? '#define USE_UV3' : '',
  11938. parameters.pointsUvs ? '#define USE_POINTS_UV' : '',
  11939. parameters.flatShading ? '#define FLAT_SHADED' : '',
  11940. parameters.skinning ? '#define USE_SKINNING' : '',
  11941. parameters.morphTargets ? '#define USE_MORPHTARGETS' : '',
  11942. parameters.morphNormals && parameters.flatShading === false ? '#define USE_MORPHNORMALS' : '',
  11943. ( parameters.morphColors && parameters.isWebGL2 ) ? '#define USE_MORPHCOLORS' : '',
  11944. ( parameters.morphTargetsCount > 0 && parameters.isWebGL2 ) ? '#define MORPHTARGETS_TEXTURE' : '',
  11945. ( parameters.morphTargetsCount > 0 && parameters.isWebGL2 ) ? '#define MORPHTARGETS_TEXTURE_STRIDE ' + parameters.morphTextureStride : '',
  11946. ( parameters.morphTargetsCount > 0 && parameters.isWebGL2 ) ? '#define MORPHTARGETS_COUNT ' + parameters.morphTargetsCount : '',
  11947. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  11948. parameters.flipSided ? '#define FLIP_SIDED' : '',
  11949. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  11950. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  11951. parameters.sizeAttenuation ? '#define USE_SIZEATTENUATION' : '',
  11952. parameters.numLightProbes > 0 ? '#define USE_LIGHT_PROBES' : '',
  11953. parameters.useLegacyLights ? '#define LEGACY_LIGHTS' : '',
  11954. parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
  11955. ( parameters.logarithmicDepthBuffer && parameters.rendererExtensionFragDepth ) ? '#define USE_LOGDEPTHBUF_EXT' : '',
  11956. 'uniform mat4 modelMatrix;',
  11957. 'uniform mat4 modelViewMatrix;',
  11958. 'uniform mat4 projectionMatrix;',
  11959. 'uniform mat4 viewMatrix;',
  11960. 'uniform mat3 normalMatrix;',
  11961. 'uniform vec3 cameraPosition;',
  11962. 'uniform bool isOrthographic;',
  11963. '#ifdef USE_INSTANCING',
  11964. ' attribute mat4 instanceMatrix;',
  11965. '#endif',
  11966. '#ifdef USE_INSTANCING_COLOR',
  11967. ' attribute vec3 instanceColor;',
  11968. '#endif',
  11969. '#ifdef USE_INSTANCING_MORPH',
  11970. ' uniform sampler2D morphTexture;',
  11971. '#endif',
  11972. 'attribute vec3 position;',
  11973. 'attribute vec3 normal;',
  11974. 'attribute vec2 uv;',
  11975. '#ifdef USE_UV1',
  11976. ' attribute vec2 uv1;',
  11977. '#endif',
  11978. '#ifdef USE_UV2',
  11979. ' attribute vec2 uv2;',
  11980. '#endif',
  11981. '#ifdef USE_UV3',
  11982. ' attribute vec2 uv3;',
  11983. '#endif',
  11984. '#ifdef USE_TANGENT',
  11985. ' attribute vec4 tangent;',
  11986. '#endif',
  11987. '#if defined( USE_COLOR_ALPHA )',
  11988. ' attribute vec4 color;',
  11989. '#elif defined( USE_COLOR )',
  11990. ' attribute vec3 color;',
  11991. '#endif',
  11992. '#if ( defined( USE_MORPHTARGETS ) && ! defined( MORPHTARGETS_TEXTURE ) )',
  11993. ' attribute vec3 morphTarget0;',
  11994. ' attribute vec3 morphTarget1;',
  11995. ' attribute vec3 morphTarget2;',
  11996. ' attribute vec3 morphTarget3;',
  11997. ' #ifdef USE_MORPHNORMALS',
  11998. ' attribute vec3 morphNormal0;',
  11999. ' attribute vec3 morphNormal1;',
  12000. ' attribute vec3 morphNormal2;',
  12001. ' attribute vec3 morphNormal3;',
  12002. ' #else',
  12003. ' attribute vec3 morphTarget4;',
  12004. ' attribute vec3 morphTarget5;',
  12005. ' attribute vec3 morphTarget6;',
  12006. ' attribute vec3 morphTarget7;',
  12007. ' #endif',
  12008. '#endif',
  12009. '#ifdef USE_SKINNING',
  12010. ' attribute vec4 skinIndex;',
  12011. ' attribute vec4 skinWeight;',
  12012. '#endif',
  12013. '\n'
  12014. ].filter( filterEmptyLine ).join( '\n' );
  12015. prefixFragment = [
  12016. customExtensions,
  12017. generatePrecision( parameters ),
  12018. '#define SHADER_TYPE ' + parameters.shaderType,
  12019. '#define SHADER_NAME ' + parameters.shaderName,
  12020. customDefines,
  12021. parameters.useFog && parameters.fog ? '#define USE_FOG' : '',
  12022. parameters.useFog && parameters.fogExp2 ? '#define FOG_EXP2' : '',
  12023. parameters.alphaToCoverage ? '#define ALPHA_TO_COVERAGE' : '',
  12024. parameters.map ? '#define USE_MAP' : '',
  12025. parameters.matcap ? '#define USE_MATCAP' : '',
  12026. parameters.envMap ? '#define USE_ENVMAP' : '',
  12027. parameters.envMap ? '#define ' + envMapTypeDefine : '',
  12028. parameters.envMap ? '#define ' + envMapModeDefine : '',
  12029. parameters.envMap ? '#define ' + envMapBlendingDefine : '',
  12030. envMapCubeUVSize ? '#define CUBEUV_TEXEL_WIDTH ' + envMapCubeUVSize.texelWidth : '',
  12031. envMapCubeUVSize ? '#define CUBEUV_TEXEL_HEIGHT ' + envMapCubeUVSize.texelHeight : '',
  12032. envMapCubeUVSize ? '#define CUBEUV_MAX_MIP ' + envMapCubeUVSize.maxMip + '.0' : '',
  12033. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  12034. parameters.aoMap ? '#define USE_AOMAP' : '',
  12035. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  12036. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  12037. parameters.normalMapObjectSpace ? '#define USE_NORMALMAP_OBJECTSPACE' : '',
  12038. parameters.normalMapTangentSpace ? '#define USE_NORMALMAP_TANGENTSPACE' : '',
  12039. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  12040. parameters.anisotropy ? '#define USE_ANISOTROPY' : '',
  12041. parameters.anisotropyMap ? '#define USE_ANISOTROPYMAP' : '',
  12042. parameters.clearcoat ? '#define USE_CLEARCOAT' : '',
  12043. parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '',
  12044. parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '',
  12045. parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '',
  12046. parameters.iridescence ? '#define USE_IRIDESCENCE' : '',
  12047. parameters.iridescenceMap ? '#define USE_IRIDESCENCEMAP' : '',
  12048. parameters.iridescenceThicknessMap ? '#define USE_IRIDESCENCE_THICKNESSMAP' : '',
  12049. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  12050. parameters.specularColorMap ? '#define USE_SPECULAR_COLORMAP' : '',
  12051. parameters.specularIntensityMap ? '#define USE_SPECULAR_INTENSITYMAP' : '',
  12052. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  12053. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  12054. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  12055. parameters.alphaTest ? '#define USE_ALPHATEST' : '',
  12056. parameters.alphaHash ? '#define USE_ALPHAHASH' : '',
  12057. parameters.sheen ? '#define USE_SHEEN' : '',
  12058. parameters.sheenColorMap ? '#define USE_SHEEN_COLORMAP' : '',
  12059. parameters.sheenRoughnessMap ? '#define USE_SHEEN_ROUGHNESSMAP' : '',
  12060. parameters.transmission ? '#define USE_TRANSMISSION' : '',
  12061. parameters.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '',
  12062. parameters.thicknessMap ? '#define USE_THICKNESSMAP' : '',
  12063. parameters.vertexTangents && parameters.flatShading === false ? '#define USE_TANGENT' : '',
  12064. parameters.vertexColors || parameters.instancingColor ? '#define USE_COLOR' : '',
  12065. parameters.vertexAlphas ? '#define USE_COLOR_ALPHA' : '',
  12066. parameters.vertexUv1s ? '#define USE_UV1' : '',
  12067. parameters.vertexUv2s ? '#define USE_UV2' : '',
  12068. parameters.vertexUv3s ? '#define USE_UV3' : '',
  12069. parameters.pointsUvs ? '#define USE_POINTS_UV' : '',
  12070. parameters.gradientMap ? '#define USE_GRADIENTMAP' : '',
  12071. parameters.flatShading ? '#define FLAT_SHADED' : '',
  12072. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  12073. parameters.flipSided ? '#define FLIP_SIDED' : '',
  12074. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  12075. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  12076. parameters.premultipliedAlpha ? '#define PREMULTIPLIED_ALPHA' : '',
  12077. parameters.numLightProbes > 0 ? '#define USE_LIGHT_PROBES' : '',
  12078. parameters.useLegacyLights ? '#define LEGACY_LIGHTS' : '',
  12079. parameters.decodeVideoTexture ? '#define DECODE_VIDEO_TEXTURE' : '',
  12080. parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
  12081. ( parameters.logarithmicDepthBuffer && parameters.rendererExtensionFragDepth ) ? '#define USE_LOGDEPTHBUF_EXT' : '',
  12082. 'uniform mat4 viewMatrix;',
  12083. 'uniform vec3 cameraPosition;',
  12084. 'uniform bool isOrthographic;',
  12085. ( parameters.toneMapping !== NoToneMapping ) ? '#define TONE_MAPPING' : '',
  12086. ( parameters.toneMapping !== NoToneMapping ) ? ShaderChunk[ 'tonemapping_pars_fragment' ] : '', // this code is required here because it is used by the toneMapping() function defined below
  12087. ( parameters.toneMapping !== NoToneMapping ) ? getToneMappingFunction( 'toneMapping', parameters.toneMapping ) : '',
  12088. parameters.dithering ? '#define DITHERING' : '',
  12089. parameters.opaque ? '#define OPAQUE' : '',
  12090. ShaderChunk[ 'colorspace_pars_fragment' ], // this code is required here because it is used by the various encoding/decoding function defined below
  12091. getTexelEncodingFunction( 'linearToOutputTexel', parameters.outputColorSpace ),
  12092. parameters.useDepthPacking ? '#define DEPTH_PACKING ' + parameters.depthPacking : '',
  12093. '\n'
  12094. ].filter( filterEmptyLine ).join( '\n' );
  12095. }
  12096. vertexShader = resolveIncludes( vertexShader );
  12097. vertexShader = replaceLightNums( vertexShader, parameters );
  12098. vertexShader = replaceClippingPlaneNums( vertexShader, parameters );
  12099. fragmentShader = resolveIncludes( fragmentShader );
  12100. fragmentShader = replaceLightNums( fragmentShader, parameters );
  12101. fragmentShader = replaceClippingPlaneNums( fragmentShader, parameters );
  12102. vertexShader = unrollLoops( vertexShader );
  12103. fragmentShader = unrollLoops( fragmentShader );
  12104. if ( parameters.isWebGL2 && parameters.isRawShaderMaterial !== true ) {
  12105. // GLSL 3.0 conversion for built-in materials and ShaderMaterial
  12106. versionString = '#version 300 es\n';
  12107. prefixVertex = [
  12108. customVertexExtensions,
  12109. 'precision mediump sampler2DArray;',
  12110. '#define attribute in',
  12111. '#define varying out',
  12112. '#define texture2D texture'
  12113. ].join( '\n' ) + '\n' + prefixVertex;
  12114. prefixFragment = [
  12115. 'precision mediump sampler2DArray;',
  12116. '#define varying in',
  12117. ( parameters.glslVersion === GLSL3 ) ? '' : 'layout(location = 0) out highp vec4 pc_fragColor;',
  12118. ( parameters.glslVersion === GLSL3 ) ? '' : '#define gl_FragColor pc_fragColor',
  12119. '#define gl_FragDepthEXT gl_FragDepth',
  12120. '#define texture2D texture',
  12121. '#define textureCube texture',
  12122. '#define texture2DProj textureProj',
  12123. '#define texture2DLodEXT textureLod',
  12124. '#define texture2DProjLodEXT textureProjLod',
  12125. '#define textureCubeLodEXT textureLod',
  12126. '#define texture2DGradEXT textureGrad',
  12127. '#define texture2DProjGradEXT textureProjGrad',
  12128. '#define textureCubeGradEXT textureGrad'
  12129. ].join( '\n' ) + '\n' + prefixFragment;
  12130. }
  12131. const vertexGlsl = versionString + prefixVertex + vertexShader;
  12132. const fragmentGlsl = versionString + prefixFragment + fragmentShader;
  12133. // console.log( '*VERTEX*', vertexGlsl );
  12134. // console.log( '*FRAGMENT*', fragmentGlsl );
  12135. const glVertexShader = WebGLShader( gl, gl.VERTEX_SHADER, vertexGlsl );
  12136. const glFragmentShader = WebGLShader( gl, gl.FRAGMENT_SHADER, fragmentGlsl );
  12137. gl.attachShader( program, glVertexShader );
  12138. gl.attachShader( program, glFragmentShader );
  12139. // Force a particular attribute to index 0.
  12140. if ( parameters.index0AttributeName !== undefined ) {
  12141. gl.bindAttribLocation( program, 0, parameters.index0AttributeName );
  12142. } else if ( parameters.morphTargets === true ) {
  12143. // programs with morphTargets displace position out of attribute 0
  12144. gl.bindAttribLocation( program, 0, 'position' );
  12145. }
  12146. gl.linkProgram( program );
  12147. function onFirstUse( self ) {
  12148. // check for link errors
  12149. if ( renderer.debug.checkShaderErrors ) {
  12150. const programLog = gl.getProgramInfoLog( program ).trim();
  12151. const vertexLog = gl.getShaderInfoLog( glVertexShader ).trim();
  12152. const fragmentLog = gl.getShaderInfoLog( glFragmentShader ).trim();
  12153. let runnable = true;
  12154. let haveDiagnostics = true;
  12155. if ( gl.getProgramParameter( program, gl.LINK_STATUS ) === false ) {
  12156. runnable = false;
  12157. if ( typeof renderer.debug.onShaderError === 'function' ) {
  12158. renderer.debug.onShaderError( gl, program, glVertexShader, glFragmentShader );
  12159. } else {
  12160. // default error reporting
  12161. const vertexErrors = getShaderErrors( gl, glVertexShader, 'vertex' );
  12162. const fragmentErrors = getShaderErrors( gl, glFragmentShader, 'fragment' );
  12163. console.error(
  12164. 'THREE.WebGLProgram: Shader Error ' + gl.getError() + ' - ' +
  12165. 'VALIDATE_STATUS ' + gl.getProgramParameter( program, gl.VALIDATE_STATUS ) + '\n\n' +
  12166. 'Material Name: ' + self.name + '\n' +
  12167. 'Material Type: ' + self.type + '\n\n' +
  12168. 'Program Info Log: ' + programLog + '\n' +
  12169. vertexErrors + '\n' +
  12170. fragmentErrors
  12171. );
  12172. }
  12173. } else if ( programLog !== '' ) {
  12174. console.warn( 'THREE.WebGLProgram: Program Info Log:', programLog );
  12175. } else if ( vertexLog === '' || fragmentLog === '' ) {
  12176. haveDiagnostics = false;
  12177. }
  12178. if ( haveDiagnostics ) {
  12179. self.diagnostics = {
  12180. runnable: runnable,
  12181. programLog: programLog,
  12182. vertexShader: {
  12183. log: vertexLog,
  12184. prefix: prefixVertex
  12185. },
  12186. fragmentShader: {
  12187. log: fragmentLog,
  12188. prefix: prefixFragment
  12189. }
  12190. };
  12191. }
  12192. }
  12193. // Clean up
  12194. // Crashes in iOS9 and iOS10. #18402
  12195. // gl.detachShader( program, glVertexShader );
  12196. // gl.detachShader( program, glFragmentShader );
  12197. gl.deleteShader( glVertexShader );
  12198. gl.deleteShader( glFragmentShader );
  12199. cachedUniforms = new WebGLUniforms( gl, program );
  12200. cachedAttributes = fetchAttributeLocations( gl, program );
  12201. }
  12202. // set up caching for uniform locations
  12203. let cachedUniforms;
  12204. this.getUniforms = function () {
  12205. if ( cachedUniforms === undefined ) {
  12206. // Populates cachedUniforms and cachedAttributes
  12207. onFirstUse( this );
  12208. }
  12209. return cachedUniforms;
  12210. };
  12211. // set up caching for attribute locations
  12212. let cachedAttributes;
  12213. this.getAttributes = function () {
  12214. if ( cachedAttributes === undefined ) {
  12215. // Populates cachedAttributes and cachedUniforms
  12216. onFirstUse( this );
  12217. }
  12218. return cachedAttributes;
  12219. };
  12220. // indicate when the program is ready to be used. if the KHR_parallel_shader_compile extension isn't supported,
  12221. // flag the program as ready immediately. It may cause a stall when it's first used.
  12222. let programReady = ( parameters.rendererExtensionParallelShaderCompile === false );
  12223. this.isReady = function () {
  12224. if ( programReady === false ) {
  12225. programReady = gl.getProgramParameter( program, COMPLETION_STATUS_KHR );
  12226. }
  12227. return programReady;
  12228. };
  12229. // free resource
  12230. this.destroy = function () {
  12231. bindingStates.releaseStatesOfProgram( this );
  12232. gl.deleteProgram( program );
  12233. this.program = undefined;
  12234. };
  12235. //
  12236. this.type = parameters.shaderType;
  12237. this.name = parameters.shaderName;
  12238. this.id = programIdCount ++;
  12239. this.cacheKey = cacheKey;
  12240. this.usedTimes = 1;
  12241. this.program = program;
  12242. this.vertexShader = glVertexShader;
  12243. this.fragmentShader = glFragmentShader;
  12244. return this;
  12245. }
  12246. let _id$1 = 0;
  12247. class WebGLShaderCache {
  12248. constructor() {
  12249. this.shaderCache = new Map();
  12250. this.materialCache = new Map();
  12251. }
  12252. update( material ) {
  12253. const vertexShader = material.vertexShader;
  12254. const fragmentShader = material.fragmentShader;
  12255. const vertexShaderStage = this._getShaderStage( vertexShader );
  12256. const fragmentShaderStage = this._getShaderStage( fragmentShader );
  12257. const materialShaders = this._getShaderCacheForMaterial( material );
  12258. if ( materialShaders.has( vertexShaderStage ) === false ) {
  12259. materialShaders.add( vertexShaderStage );
  12260. vertexShaderStage.usedTimes ++;
  12261. }
  12262. if ( materialShaders.has( fragmentShaderStage ) === false ) {
  12263. materialShaders.add( fragmentShaderStage );
  12264. fragmentShaderStage.usedTimes ++;
  12265. }
  12266. return this;
  12267. }
  12268. remove( material ) {
  12269. const materialShaders = this.materialCache.get( material );
  12270. for ( const shaderStage of materialShaders ) {
  12271. shaderStage.usedTimes --;
  12272. if ( shaderStage.usedTimes === 0 ) this.shaderCache.delete( shaderStage.code );
  12273. }
  12274. this.materialCache.delete( material );
  12275. return this;
  12276. }
  12277. getVertexShaderID( material ) {
  12278. return this._getShaderStage( material.vertexShader ).id;
  12279. }
  12280. getFragmentShaderID( material ) {
  12281. return this._getShaderStage( material.fragmentShader ).id;
  12282. }
  12283. dispose() {
  12284. this.shaderCache.clear();
  12285. this.materialCache.clear();
  12286. }
  12287. _getShaderCacheForMaterial( material ) {
  12288. const cache = this.materialCache;
  12289. let set = cache.get( material );
  12290. if ( set === undefined ) {
  12291. set = new Set();
  12292. cache.set( material, set );
  12293. }
  12294. return set;
  12295. }
  12296. _getShaderStage( code ) {
  12297. const cache = this.shaderCache;
  12298. let stage = cache.get( code );
  12299. if ( stage === undefined ) {
  12300. stage = new WebGLShaderStage( code );
  12301. cache.set( code, stage );
  12302. }
  12303. return stage;
  12304. }
  12305. }
  12306. class WebGLShaderStage {
  12307. constructor( code ) {
  12308. this.id = _id$1 ++;
  12309. this.code = code;
  12310. this.usedTimes = 0;
  12311. }
  12312. }
  12313. function WebGLPrograms( renderer, cubemaps, cubeuvmaps, extensions, capabilities, bindingStates, clipping ) {
  12314. const _programLayers = new Layers();
  12315. const _customShaders = new WebGLShaderCache();
  12316. const _activeChannels = new Set();
  12317. const programs = [];
  12318. const IS_WEBGL2 = capabilities.isWebGL2;
  12319. const logarithmicDepthBuffer = capabilities.logarithmicDepthBuffer;
  12320. const SUPPORTS_VERTEX_TEXTURES = capabilities.vertexTextures;
  12321. let precision = capabilities.precision;
  12322. const shaderIDs = {
  12323. MeshDepthMaterial: 'depth',
  12324. MeshDistanceMaterial: 'distanceRGBA',
  12325. MeshNormalMaterial: 'normal',
  12326. MeshBasicMaterial: 'basic',
  12327. MeshLambertMaterial: 'lambert',
  12328. MeshPhongMaterial: 'phong',
  12329. MeshToonMaterial: 'toon',
  12330. MeshStandardMaterial: 'physical',
  12331. MeshPhysicalMaterial: 'physical',
  12332. MeshMatcapMaterial: 'matcap',
  12333. LineBasicMaterial: 'basic',
  12334. LineDashedMaterial: 'dashed',
  12335. PointsMaterial: 'points',
  12336. ShadowMaterial: 'shadow',
  12337. SpriteMaterial: 'sprite'
  12338. };
  12339. function getChannel( value ) {
  12340. _activeChannels.add( value );
  12341. if ( value === 0 ) return 'uv';
  12342. return `uv${ value }`;
  12343. }
  12344. function getParameters( material, lights, shadows, scene, object ) {
  12345. const fog = scene.fog;
  12346. const geometry = object.geometry;
  12347. const environment = material.isMeshStandardMaterial ? scene.environment : null;
  12348. const envMap = ( material.isMeshStandardMaterial ? cubeuvmaps : cubemaps ).get( material.envMap || environment );
  12349. const envMapCubeUVHeight = ( !! envMap ) && ( envMap.mapping === CubeUVReflectionMapping ) ? envMap.image.height : null;
  12350. const shaderID = shaderIDs[ material.type ];
  12351. // heuristics to create shader parameters according to lights in the scene
  12352. // (not to blow over maxLights budget)
  12353. if ( material.precision !== null ) {
  12354. precision = capabilities.getMaxPrecision( material.precision );
  12355. if ( precision !== material.precision ) {
  12356. console.warn( 'THREE.WebGLProgram.getParameters:', material.precision, 'not supported, using', precision, 'instead.' );
  12357. }
  12358. }
  12359. //
  12360. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  12361. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  12362. let morphTextureStride = 0;
  12363. if ( geometry.morphAttributes.position !== undefined ) morphTextureStride = 1;
  12364. if ( geometry.morphAttributes.normal !== undefined ) morphTextureStride = 2;
  12365. if ( geometry.morphAttributes.color !== undefined ) morphTextureStride = 3;
  12366. //
  12367. let vertexShader, fragmentShader;
  12368. let customVertexShaderID, customFragmentShaderID;
  12369. if ( shaderID ) {
  12370. const shader = ShaderLib[ shaderID ];
  12371. vertexShader = shader.vertexShader;
  12372. fragmentShader = shader.fragmentShader;
  12373. } else {
  12374. vertexShader = material.vertexShader;
  12375. fragmentShader = material.fragmentShader;
  12376. _customShaders.update( material );
  12377. customVertexShaderID = _customShaders.getVertexShaderID( material );
  12378. customFragmentShaderID = _customShaders.getFragmentShaderID( material );
  12379. }
  12380. const currentRenderTarget = renderer.getRenderTarget();
  12381. const IS_INSTANCEDMESH = object.isInstancedMesh === true;
  12382. const IS_BATCHEDMESH = object.isBatchedMesh === true;
  12383. const HAS_MAP = !! material.map;
  12384. const HAS_MATCAP = !! material.matcap;
  12385. const HAS_ENVMAP = !! envMap;
  12386. const HAS_AOMAP = !! material.aoMap;
  12387. const HAS_LIGHTMAP = !! material.lightMap;
  12388. const HAS_BUMPMAP = !! material.bumpMap;
  12389. const HAS_NORMALMAP = !! material.normalMap;
  12390. const HAS_DISPLACEMENTMAP = !! material.displacementMap;
  12391. const HAS_EMISSIVEMAP = !! material.emissiveMap;
  12392. const HAS_METALNESSMAP = !! material.metalnessMap;
  12393. const HAS_ROUGHNESSMAP = !! material.roughnessMap;
  12394. const HAS_ANISOTROPY = material.anisotropy > 0;
  12395. const HAS_CLEARCOAT = material.clearcoat > 0;
  12396. const HAS_IRIDESCENCE = material.iridescence > 0;
  12397. const HAS_SHEEN = material.sheen > 0;
  12398. const HAS_TRANSMISSION = material.transmission > 0;
  12399. const HAS_ANISOTROPYMAP = HAS_ANISOTROPY && !! material.anisotropyMap;
  12400. const HAS_CLEARCOATMAP = HAS_CLEARCOAT && !! material.clearcoatMap;
  12401. const HAS_CLEARCOAT_NORMALMAP = HAS_CLEARCOAT && !! material.clearcoatNormalMap;
  12402. const HAS_CLEARCOAT_ROUGHNESSMAP = HAS_CLEARCOAT && !! material.clearcoatRoughnessMap;
  12403. const HAS_IRIDESCENCEMAP = HAS_IRIDESCENCE && !! material.iridescenceMap;
  12404. const HAS_IRIDESCENCE_THICKNESSMAP = HAS_IRIDESCENCE && !! material.iridescenceThicknessMap;
  12405. const HAS_SHEEN_COLORMAP = HAS_SHEEN && !! material.sheenColorMap;
  12406. const HAS_SHEEN_ROUGHNESSMAP = HAS_SHEEN && !! material.sheenRoughnessMap;
  12407. const HAS_SPECULARMAP = !! material.specularMap;
  12408. const HAS_SPECULAR_COLORMAP = !! material.specularColorMap;
  12409. const HAS_SPECULAR_INTENSITYMAP = !! material.specularIntensityMap;
  12410. const HAS_TRANSMISSIONMAP = HAS_TRANSMISSION && !! material.transmissionMap;
  12411. const HAS_THICKNESSMAP = HAS_TRANSMISSION && !! material.thicknessMap;
  12412. const HAS_GRADIENTMAP = !! material.gradientMap;
  12413. const HAS_ALPHAMAP = !! material.alphaMap;
  12414. const HAS_ALPHATEST = material.alphaTest > 0;
  12415. const HAS_ALPHAHASH = !! material.alphaHash;
  12416. const HAS_EXTENSIONS = !! material.extensions;
  12417. let toneMapping = NoToneMapping;
  12418. if ( material.toneMapped ) {
  12419. if ( currentRenderTarget === null || currentRenderTarget.isXRRenderTarget === true ) {
  12420. toneMapping = renderer.toneMapping;
  12421. }
  12422. }
  12423. const parameters = {
  12424. isWebGL2: IS_WEBGL2,
  12425. shaderID: shaderID,
  12426. shaderType: material.type,
  12427. shaderName: material.name,
  12428. vertexShader: vertexShader,
  12429. fragmentShader: fragmentShader,
  12430. defines: material.defines,
  12431. customVertexShaderID: customVertexShaderID,
  12432. customFragmentShaderID: customFragmentShaderID,
  12433. isRawShaderMaterial: material.isRawShaderMaterial === true,
  12434. glslVersion: material.glslVersion,
  12435. precision: precision,
  12436. batching: IS_BATCHEDMESH,
  12437. instancing: IS_INSTANCEDMESH,
  12438. instancingColor: IS_INSTANCEDMESH && object.instanceColor !== null,
  12439. instancingMorph: IS_INSTANCEDMESH && object.morphTexture !== null,
  12440. supportsVertexTextures: SUPPORTS_VERTEX_TEXTURES,
  12441. outputColorSpace: ( currentRenderTarget === null ) ? renderer.outputColorSpace : ( currentRenderTarget.isXRRenderTarget === true ? currentRenderTarget.texture.colorSpace : LinearSRGBColorSpace ),
  12442. alphaToCoverage: !! material.alphaToCoverage,
  12443. map: HAS_MAP,
  12444. matcap: HAS_MATCAP,
  12445. envMap: HAS_ENVMAP,
  12446. envMapMode: HAS_ENVMAP && envMap.mapping,
  12447. envMapCubeUVHeight: envMapCubeUVHeight,
  12448. aoMap: HAS_AOMAP,
  12449. lightMap: HAS_LIGHTMAP,
  12450. bumpMap: HAS_BUMPMAP,
  12451. normalMap: HAS_NORMALMAP,
  12452. displacementMap: SUPPORTS_VERTEX_TEXTURES && HAS_DISPLACEMENTMAP,
  12453. emissiveMap: HAS_EMISSIVEMAP,
  12454. normalMapObjectSpace: HAS_NORMALMAP && material.normalMapType === ObjectSpaceNormalMap,
  12455. normalMapTangentSpace: HAS_NORMALMAP && material.normalMapType === TangentSpaceNormalMap,
  12456. metalnessMap: HAS_METALNESSMAP,
  12457. roughnessMap: HAS_ROUGHNESSMAP,
  12458. anisotropy: HAS_ANISOTROPY,
  12459. anisotropyMap: HAS_ANISOTROPYMAP,
  12460. clearcoat: HAS_CLEARCOAT,
  12461. clearcoatMap: HAS_CLEARCOATMAP,
  12462. clearcoatNormalMap: HAS_CLEARCOAT_NORMALMAP,
  12463. clearcoatRoughnessMap: HAS_CLEARCOAT_ROUGHNESSMAP,
  12464. iridescence: HAS_IRIDESCENCE,
  12465. iridescenceMap: HAS_IRIDESCENCEMAP,
  12466. iridescenceThicknessMap: HAS_IRIDESCENCE_THICKNESSMAP,
  12467. sheen: HAS_SHEEN,
  12468. sheenColorMap: HAS_SHEEN_COLORMAP,
  12469. sheenRoughnessMap: HAS_SHEEN_ROUGHNESSMAP,
  12470. specularMap: HAS_SPECULARMAP,
  12471. specularColorMap: HAS_SPECULAR_COLORMAP,
  12472. specularIntensityMap: HAS_SPECULAR_INTENSITYMAP,
  12473. transmission: HAS_TRANSMISSION,
  12474. transmissionMap: HAS_TRANSMISSIONMAP,
  12475. thicknessMap: HAS_THICKNESSMAP,
  12476. gradientMap: HAS_GRADIENTMAP,
  12477. opaque: material.transparent === false && material.blending === NormalBlending && material.alphaToCoverage === false,
  12478. alphaMap: HAS_ALPHAMAP,
  12479. alphaTest: HAS_ALPHATEST,
  12480. alphaHash: HAS_ALPHAHASH,
  12481. combine: material.combine,
  12482. //
  12483. mapUv: HAS_MAP && getChannel( material.map.channel ),
  12484. aoMapUv: HAS_AOMAP && getChannel( material.aoMap.channel ),
  12485. lightMapUv: HAS_LIGHTMAP && getChannel( material.lightMap.channel ),
  12486. bumpMapUv: HAS_BUMPMAP && getChannel( material.bumpMap.channel ),
  12487. normalMapUv: HAS_NORMALMAP && getChannel( material.normalMap.channel ),
  12488. displacementMapUv: HAS_DISPLACEMENTMAP && getChannel( material.displacementMap.channel ),
  12489. emissiveMapUv: HAS_EMISSIVEMAP && getChannel( material.emissiveMap.channel ),
  12490. metalnessMapUv: HAS_METALNESSMAP && getChannel( material.metalnessMap.channel ),
  12491. roughnessMapUv: HAS_ROUGHNESSMAP && getChannel( material.roughnessMap.channel ),
  12492. anisotropyMapUv: HAS_ANISOTROPYMAP && getChannel( material.anisotropyMap.channel ),
  12493. clearcoatMapUv: HAS_CLEARCOATMAP && getChannel( material.clearcoatMap.channel ),
  12494. clearcoatNormalMapUv: HAS_CLEARCOAT_NORMALMAP && getChannel( material.clearcoatNormalMap.channel ),
  12495. clearcoatRoughnessMapUv: HAS_CLEARCOAT_ROUGHNESSMAP && getChannel( material.clearcoatRoughnessMap.channel ),
  12496. iridescenceMapUv: HAS_IRIDESCENCEMAP && getChannel( material.iridescenceMap.channel ),
  12497. iridescenceThicknessMapUv: HAS_IRIDESCENCE_THICKNESSMAP && getChannel( material.iridescenceThicknessMap.channel ),
  12498. sheenColorMapUv: HAS_SHEEN_COLORMAP && getChannel( material.sheenColorMap.channel ),
  12499. sheenRoughnessMapUv: HAS_SHEEN_ROUGHNESSMAP && getChannel( material.sheenRoughnessMap.channel ),
  12500. specularMapUv: HAS_SPECULARMAP && getChannel( material.specularMap.channel ),
  12501. specularColorMapUv: HAS_SPECULAR_COLORMAP && getChannel( material.specularColorMap.channel ),
  12502. specularIntensityMapUv: HAS_SPECULAR_INTENSITYMAP && getChannel( material.specularIntensityMap.channel ),
  12503. transmissionMapUv: HAS_TRANSMISSIONMAP && getChannel( material.transmissionMap.channel ),
  12504. thicknessMapUv: HAS_THICKNESSMAP && getChannel( material.thicknessMap.channel ),
  12505. alphaMapUv: HAS_ALPHAMAP && getChannel( material.alphaMap.channel ),
  12506. //
  12507. vertexTangents: !! geometry.attributes.tangent && ( HAS_NORMALMAP || HAS_ANISOTROPY ),
  12508. vertexColors: material.vertexColors,
  12509. vertexAlphas: material.vertexColors === true && !! geometry.attributes.color && geometry.attributes.color.itemSize === 4,
  12510. pointsUvs: object.isPoints === true && !! geometry.attributes.uv && ( HAS_MAP || HAS_ALPHAMAP ),
  12511. fog: !! fog,
  12512. useFog: material.fog === true,
  12513. fogExp2: ( !! fog && fog.isFogExp2 ),
  12514. flatShading: material.flatShading === true,
  12515. sizeAttenuation: material.sizeAttenuation === true,
  12516. logarithmicDepthBuffer: logarithmicDepthBuffer,
  12517. skinning: object.isSkinnedMesh === true,
  12518. morphTargets: geometry.morphAttributes.position !== undefined,
  12519. morphNormals: geometry.morphAttributes.normal !== undefined,
  12520. morphColors: geometry.morphAttributes.color !== undefined,
  12521. morphTargetsCount: morphTargetsCount,
  12522. morphTextureStride: morphTextureStride,
  12523. numDirLights: lights.directional.length,
  12524. numPointLights: lights.point.length,
  12525. numSpotLights: lights.spot.length,
  12526. numSpotLightMaps: lights.spotLightMap.length,
  12527. numRectAreaLights: lights.rectArea.length,
  12528. numHemiLights: lights.hemi.length,
  12529. numDirLightShadows: lights.directionalShadowMap.length,
  12530. numPointLightShadows: lights.pointShadowMap.length,
  12531. numSpotLightShadows: lights.spotShadowMap.length,
  12532. numSpotLightShadowsWithMaps: lights.numSpotLightShadowsWithMaps,
  12533. numLightProbes: lights.numLightProbes,
  12534. numClippingPlanes: clipping.numPlanes,
  12535. numClipIntersection: clipping.numIntersection,
  12536. dithering: material.dithering,
  12537. shadowMapEnabled: renderer.shadowMap.enabled && shadows.length > 0,
  12538. shadowMapType: renderer.shadowMap.type,
  12539. toneMapping: toneMapping,
  12540. useLegacyLights: renderer._useLegacyLights,
  12541. decodeVideoTexture: HAS_MAP && ( material.map.isVideoTexture === true ) && ( ColorManagement.getTransfer( material.map.colorSpace ) === SRGBTransfer ),
  12542. premultipliedAlpha: material.premultipliedAlpha,
  12543. doubleSided: material.side === DoubleSide,
  12544. flipSided: material.side === BackSide,
  12545. useDepthPacking: material.depthPacking >= 0,
  12546. depthPacking: material.depthPacking || 0,
  12547. index0AttributeName: material.index0AttributeName,
  12548. extensionDerivatives: HAS_EXTENSIONS && material.extensions.derivatives === true,
  12549. extensionFragDepth: HAS_EXTENSIONS && material.extensions.fragDepth === true,
  12550. extensionDrawBuffers: HAS_EXTENSIONS && material.extensions.drawBuffers === true,
  12551. extensionShaderTextureLOD: HAS_EXTENSIONS && material.extensions.shaderTextureLOD === true,
  12552. extensionClipCullDistance: HAS_EXTENSIONS && material.extensions.clipCullDistance === true && extensions.has( 'WEBGL_clip_cull_distance' ),
  12553. extensionMultiDraw: HAS_EXTENSIONS && material.extensions.multiDraw === true && extensions.has( 'WEBGL_multi_draw' ),
  12554. rendererExtensionFragDepth: IS_WEBGL2 || extensions.has( 'EXT_frag_depth' ),
  12555. rendererExtensionDrawBuffers: IS_WEBGL2 || extensions.has( 'WEBGL_draw_buffers' ),
  12556. rendererExtensionShaderTextureLod: IS_WEBGL2 || extensions.has( 'EXT_shader_texture_lod' ),
  12557. rendererExtensionParallelShaderCompile: extensions.has( 'KHR_parallel_shader_compile' ),
  12558. customProgramCacheKey: material.customProgramCacheKey()
  12559. };
  12560. // the usage of getChannel() determines the active texture channels for this shader
  12561. parameters.vertexUv1s = _activeChannels.has( 1 );
  12562. parameters.vertexUv2s = _activeChannels.has( 2 );
  12563. parameters.vertexUv3s = _activeChannels.has( 3 );
  12564. _activeChannels.clear();
  12565. return parameters;
  12566. }
  12567. function getProgramCacheKey( parameters ) {
  12568. const array = [];
  12569. if ( parameters.shaderID ) {
  12570. array.push( parameters.shaderID );
  12571. } else {
  12572. array.push( parameters.customVertexShaderID );
  12573. array.push( parameters.customFragmentShaderID );
  12574. }
  12575. if ( parameters.defines !== undefined ) {
  12576. for ( const name in parameters.defines ) {
  12577. array.push( name );
  12578. array.push( parameters.defines[ name ] );
  12579. }
  12580. }
  12581. if ( parameters.isRawShaderMaterial === false ) {
  12582. getProgramCacheKeyParameters( array, parameters );
  12583. getProgramCacheKeyBooleans( array, parameters );
  12584. array.push( renderer.outputColorSpace );
  12585. }
  12586. array.push( parameters.customProgramCacheKey );
  12587. return array.join();
  12588. }
  12589. function getProgramCacheKeyParameters( array, parameters ) {
  12590. array.push( parameters.precision );
  12591. array.push( parameters.outputColorSpace );
  12592. array.push( parameters.envMapMode );
  12593. array.push( parameters.envMapCubeUVHeight );
  12594. array.push( parameters.mapUv );
  12595. array.push( parameters.alphaMapUv );
  12596. array.push( parameters.lightMapUv );
  12597. array.push( parameters.aoMapUv );
  12598. array.push( parameters.bumpMapUv );
  12599. array.push( parameters.normalMapUv );
  12600. array.push( parameters.displacementMapUv );
  12601. array.push( parameters.emissiveMapUv );
  12602. array.push( parameters.metalnessMapUv );
  12603. array.push( parameters.roughnessMapUv );
  12604. array.push( parameters.anisotropyMapUv );
  12605. array.push( parameters.clearcoatMapUv );
  12606. array.push( parameters.clearcoatNormalMapUv );
  12607. array.push( parameters.clearcoatRoughnessMapUv );
  12608. array.push( parameters.iridescenceMapUv );
  12609. array.push( parameters.iridescenceThicknessMapUv );
  12610. array.push( parameters.sheenColorMapUv );
  12611. array.push( parameters.sheenRoughnessMapUv );
  12612. array.push( parameters.specularMapUv );
  12613. array.push( parameters.specularColorMapUv );
  12614. array.push( parameters.specularIntensityMapUv );
  12615. array.push( parameters.transmissionMapUv );
  12616. array.push( parameters.thicknessMapUv );
  12617. array.push( parameters.combine );
  12618. array.push( parameters.fogExp2 );
  12619. array.push( parameters.sizeAttenuation );
  12620. array.push( parameters.morphTargetsCount );
  12621. array.push( parameters.morphAttributeCount );
  12622. array.push( parameters.numDirLights );
  12623. array.push( parameters.numPointLights );
  12624. array.push( parameters.numSpotLights );
  12625. array.push( parameters.numSpotLightMaps );
  12626. array.push( parameters.numHemiLights );
  12627. array.push( parameters.numRectAreaLights );
  12628. array.push( parameters.numDirLightShadows );
  12629. array.push( parameters.numPointLightShadows );
  12630. array.push( parameters.numSpotLightShadows );
  12631. array.push( parameters.numSpotLightShadowsWithMaps );
  12632. array.push( parameters.numLightProbes );
  12633. array.push( parameters.shadowMapType );
  12634. array.push( parameters.toneMapping );
  12635. array.push( parameters.numClippingPlanes );
  12636. array.push( parameters.numClipIntersection );
  12637. array.push( parameters.depthPacking );
  12638. }
  12639. function getProgramCacheKeyBooleans( array, parameters ) {
  12640. _programLayers.disableAll();
  12641. if ( parameters.isWebGL2 )
  12642. _programLayers.enable( 0 );
  12643. if ( parameters.supportsVertexTextures )
  12644. _programLayers.enable( 1 );
  12645. if ( parameters.instancing )
  12646. _programLayers.enable( 2 );
  12647. if ( parameters.instancingColor )
  12648. _programLayers.enable( 3 );
  12649. if ( parameters.instancingMorph )
  12650. _programLayers.enable( 4 );
  12651. if ( parameters.matcap )
  12652. _programLayers.enable( 5 );
  12653. if ( parameters.envMap )
  12654. _programLayers.enable( 6 );
  12655. if ( parameters.normalMapObjectSpace )
  12656. _programLayers.enable( 7 );
  12657. if ( parameters.normalMapTangentSpace )
  12658. _programLayers.enable( 8 );
  12659. if ( parameters.clearcoat )
  12660. _programLayers.enable( 9 );
  12661. if ( parameters.iridescence )
  12662. _programLayers.enable( 10 );
  12663. if ( parameters.alphaTest )
  12664. _programLayers.enable( 11 );
  12665. if ( parameters.vertexColors )
  12666. _programLayers.enable( 12 );
  12667. if ( parameters.vertexAlphas )
  12668. _programLayers.enable( 13 );
  12669. if ( parameters.vertexUv1s )
  12670. _programLayers.enable( 14 );
  12671. if ( parameters.vertexUv2s )
  12672. _programLayers.enable( 15 );
  12673. if ( parameters.vertexUv3s )
  12674. _programLayers.enable( 16 );
  12675. if ( parameters.vertexTangents )
  12676. _programLayers.enable( 17 );
  12677. if ( parameters.anisotropy )
  12678. _programLayers.enable( 18 );
  12679. if ( parameters.alphaHash )
  12680. _programLayers.enable( 19 );
  12681. if ( parameters.batching )
  12682. _programLayers.enable( 20 );
  12683. array.push( _programLayers.mask );
  12684. _programLayers.disableAll();
  12685. if ( parameters.fog )
  12686. _programLayers.enable( 0 );
  12687. if ( parameters.useFog )
  12688. _programLayers.enable( 1 );
  12689. if ( parameters.flatShading )
  12690. _programLayers.enable( 2 );
  12691. if ( parameters.logarithmicDepthBuffer )
  12692. _programLayers.enable( 3 );
  12693. if ( parameters.skinning )
  12694. _programLayers.enable( 4 );
  12695. if ( parameters.morphTargets )
  12696. _programLayers.enable( 5 );
  12697. if ( parameters.morphNormals )
  12698. _programLayers.enable( 6 );
  12699. if ( parameters.morphColors )
  12700. _programLayers.enable( 7 );
  12701. if ( parameters.premultipliedAlpha )
  12702. _programLayers.enable( 8 );
  12703. if ( parameters.shadowMapEnabled )
  12704. _programLayers.enable( 9 );
  12705. if ( parameters.useLegacyLights )
  12706. _programLayers.enable( 10 );
  12707. if ( parameters.doubleSided )
  12708. _programLayers.enable( 11 );
  12709. if ( parameters.flipSided )
  12710. _programLayers.enable( 12 );
  12711. if ( parameters.useDepthPacking )
  12712. _programLayers.enable( 13 );
  12713. if ( parameters.dithering )
  12714. _programLayers.enable( 14 );
  12715. if ( parameters.transmission )
  12716. _programLayers.enable( 15 );
  12717. if ( parameters.sheen )
  12718. _programLayers.enable( 16 );
  12719. if ( parameters.opaque )
  12720. _programLayers.enable( 17 );
  12721. if ( parameters.pointsUvs )
  12722. _programLayers.enable( 18 );
  12723. if ( parameters.decodeVideoTexture )
  12724. _programLayers.enable( 19 );
  12725. if ( parameters.alphaToCoverage )
  12726. _programLayers.enable( 20 );
  12727. array.push( _programLayers.mask );
  12728. }
  12729. function getUniforms( material ) {
  12730. const shaderID = shaderIDs[ material.type ];
  12731. let uniforms;
  12732. if ( shaderID ) {
  12733. const shader = ShaderLib[ shaderID ];
  12734. uniforms = UniformsUtils.clone( shader.uniforms );
  12735. } else {
  12736. uniforms = material.uniforms;
  12737. }
  12738. return uniforms;
  12739. }
  12740. function acquireProgram( parameters, cacheKey ) {
  12741. let program;
  12742. // Check if code has been already compiled
  12743. for ( let p = 0, pl = programs.length; p < pl; p ++ ) {
  12744. const preexistingProgram = programs[ p ];
  12745. if ( preexistingProgram.cacheKey === cacheKey ) {
  12746. program = preexistingProgram;
  12747. ++ program.usedTimes;
  12748. break;
  12749. }
  12750. }
  12751. if ( program === undefined ) {
  12752. program = new WebGLProgram( renderer, cacheKey, parameters, bindingStates );
  12753. programs.push( program );
  12754. }
  12755. return program;
  12756. }
  12757. function releaseProgram( program ) {
  12758. if ( -- program.usedTimes === 0 ) {
  12759. // Remove from unordered set
  12760. const i = programs.indexOf( program );
  12761. programs[ i ] = programs[ programs.length - 1 ];
  12762. programs.pop();
  12763. // Free WebGL resources
  12764. program.destroy();
  12765. }
  12766. }
  12767. function releaseShaderCache( material ) {
  12768. _customShaders.remove( material );
  12769. }
  12770. function dispose() {
  12771. _customShaders.dispose();
  12772. }
  12773. return {
  12774. getParameters: getParameters,
  12775. getProgramCacheKey: getProgramCacheKey,
  12776. getUniforms: getUniforms,
  12777. acquireProgram: acquireProgram,
  12778. releaseProgram: releaseProgram,
  12779. releaseShaderCache: releaseShaderCache,
  12780. // Exposed for resource monitoring & error feedback via renderer.info:
  12781. programs: programs,
  12782. dispose: dispose
  12783. };
  12784. }
  12785. function WebGLProperties() {
  12786. let properties = new WeakMap();
  12787. function get( object ) {
  12788. let map = properties.get( object );
  12789. if ( map === undefined ) {
  12790. map = {};
  12791. properties.set( object, map );
  12792. }
  12793. return map;
  12794. }
  12795. function remove( object ) {
  12796. properties.delete( object );
  12797. }
  12798. function update( object, key, value ) {
  12799. properties.get( object )[ key ] = value;
  12800. }
  12801. function dispose() {
  12802. properties = new WeakMap();
  12803. }
  12804. return {
  12805. get: get,
  12806. remove: remove,
  12807. update: update,
  12808. dispose: dispose
  12809. };
  12810. }
  12811. function painterSortStable( a, b ) {
  12812. if ( a.groupOrder !== b.groupOrder ) {
  12813. return a.groupOrder - b.groupOrder;
  12814. } else if ( a.renderOrder !== b.renderOrder ) {
  12815. return a.renderOrder - b.renderOrder;
  12816. } else if ( a.material.id !== b.material.id ) {
  12817. return a.material.id - b.material.id;
  12818. } else if ( a.z !== b.z ) {
  12819. return a.z - b.z;
  12820. } else {
  12821. return a.id - b.id;
  12822. }
  12823. }
  12824. function reversePainterSortStable( a, b ) {
  12825. if ( a.groupOrder !== b.groupOrder ) {
  12826. return a.groupOrder - b.groupOrder;
  12827. } else if ( a.renderOrder !== b.renderOrder ) {
  12828. return a.renderOrder - b.renderOrder;
  12829. } else if ( a.z !== b.z ) {
  12830. return b.z - a.z;
  12831. } else {
  12832. return a.id - b.id;
  12833. }
  12834. }
  12835. function WebGLRenderList() {
  12836. const renderItems = [];
  12837. let renderItemsIndex = 0;
  12838. const opaque = [];
  12839. const transmissive = [];
  12840. const transparent = [];
  12841. function init() {
  12842. renderItemsIndex = 0;
  12843. opaque.length = 0;
  12844. transmissive.length = 0;
  12845. transparent.length = 0;
  12846. }
  12847. function getNextRenderItem( object, geometry, material, groupOrder, z, group ) {
  12848. let renderItem = renderItems[ renderItemsIndex ];
  12849. if ( renderItem === undefined ) {
  12850. renderItem = {
  12851. id: object.id,
  12852. object: object,
  12853. geometry: geometry,
  12854. material: material,
  12855. groupOrder: groupOrder,
  12856. renderOrder: object.renderOrder,
  12857. z: z,
  12858. group: group
  12859. };
  12860. renderItems[ renderItemsIndex ] = renderItem;
  12861. } else {
  12862. renderItem.id = object.id;
  12863. renderItem.object = object;
  12864. renderItem.geometry = geometry;
  12865. renderItem.material = material;
  12866. renderItem.groupOrder = groupOrder;
  12867. renderItem.renderOrder = object.renderOrder;
  12868. renderItem.z = z;
  12869. renderItem.group = group;
  12870. }
  12871. renderItemsIndex ++;
  12872. return renderItem;
  12873. }
  12874. function push( object, geometry, material, groupOrder, z, group ) {
  12875. const renderItem = getNextRenderItem( object, geometry, material, groupOrder, z, group );
  12876. if ( material.transmission > 0.0 ) {
  12877. transmissive.push( renderItem );
  12878. } else if ( material.transparent === true ) {
  12879. transparent.push( renderItem );
  12880. } else {
  12881. opaque.push( renderItem );
  12882. }
  12883. }
  12884. function unshift( object, geometry, material, groupOrder, z, group ) {
  12885. const renderItem = getNextRenderItem( object, geometry, material, groupOrder, z, group );
  12886. if ( material.transmission > 0.0 ) {
  12887. transmissive.unshift( renderItem );
  12888. } else if ( material.transparent === true ) {
  12889. transparent.unshift( renderItem );
  12890. } else {
  12891. opaque.unshift( renderItem );
  12892. }
  12893. }
  12894. function sort( customOpaqueSort, customTransparentSort ) {
  12895. if ( opaque.length > 1 ) opaque.sort( customOpaqueSort || painterSortStable );
  12896. if ( transmissive.length > 1 ) transmissive.sort( customTransparentSort || reversePainterSortStable );
  12897. if ( transparent.length > 1 ) transparent.sort( customTransparentSort || reversePainterSortStable );
  12898. }
  12899. function finish() {
  12900. // Clear references from inactive renderItems in the list
  12901. for ( let i = renderItemsIndex, il = renderItems.length; i < il; i ++ ) {
  12902. const renderItem = renderItems[ i ];
  12903. if ( renderItem.id === null ) break;
  12904. renderItem.id = null;
  12905. renderItem.object = null;
  12906. renderItem.geometry = null;
  12907. renderItem.material = null;
  12908. renderItem.group = null;
  12909. }
  12910. }
  12911. return {
  12912. opaque: opaque,
  12913. transmissive: transmissive,
  12914. transparent: transparent,
  12915. init: init,
  12916. push: push,
  12917. unshift: unshift,
  12918. finish: finish,
  12919. sort: sort
  12920. };
  12921. }
  12922. function WebGLRenderLists() {
  12923. let lists = new WeakMap();
  12924. function get( scene, renderCallDepth ) {
  12925. const listArray = lists.get( scene );
  12926. let list;
  12927. if ( listArray === undefined ) {
  12928. list = new WebGLRenderList();
  12929. lists.set( scene, [ list ] );
  12930. } else {
  12931. if ( renderCallDepth >= listArray.length ) {
  12932. list = new WebGLRenderList();
  12933. listArray.push( list );
  12934. } else {
  12935. list = listArray[ renderCallDepth ];
  12936. }
  12937. }
  12938. return list;
  12939. }
  12940. function dispose() {
  12941. lists = new WeakMap();
  12942. }
  12943. return {
  12944. get: get,
  12945. dispose: dispose
  12946. };
  12947. }
  12948. function UniformsCache() {
  12949. const lights = {};
  12950. return {
  12951. get: function ( light ) {
  12952. if ( lights[ light.id ] !== undefined ) {
  12953. return lights[ light.id ];
  12954. }
  12955. let uniforms;
  12956. switch ( light.type ) {
  12957. case 'DirectionalLight':
  12958. uniforms = {
  12959. direction: new Vector3(),
  12960. color: new Color()
  12961. };
  12962. break;
  12963. case 'SpotLight':
  12964. uniforms = {
  12965. position: new Vector3(),
  12966. direction: new Vector3(),
  12967. color: new Color(),
  12968. distance: 0,
  12969. coneCos: 0,
  12970. penumbraCos: 0,
  12971. decay: 0
  12972. };
  12973. break;
  12974. case 'PointLight':
  12975. uniforms = {
  12976. position: new Vector3(),
  12977. color: new Color(),
  12978. distance: 0,
  12979. decay: 0
  12980. };
  12981. break;
  12982. case 'HemisphereLight':
  12983. uniforms = {
  12984. direction: new Vector3(),
  12985. skyColor: new Color(),
  12986. groundColor: new Color()
  12987. };
  12988. break;
  12989. case 'RectAreaLight':
  12990. uniforms = {
  12991. color: new Color(),
  12992. position: new Vector3(),
  12993. halfWidth: new Vector3(),
  12994. halfHeight: new Vector3()
  12995. };
  12996. break;
  12997. }
  12998. lights[ light.id ] = uniforms;
  12999. return uniforms;
  13000. }
  13001. };
  13002. }
  13003. function ShadowUniformsCache() {
  13004. const lights = {};
  13005. return {
  13006. get: function ( light ) {
  13007. if ( lights[ light.id ] !== undefined ) {
  13008. return lights[ light.id ];
  13009. }
  13010. let uniforms;
  13011. switch ( light.type ) {
  13012. case 'DirectionalLight':
  13013. uniforms = {
  13014. shadowBias: 0,
  13015. shadowNormalBias: 0,
  13016. shadowRadius: 1,
  13017. shadowMapSize: new Vector2()
  13018. };
  13019. break;
  13020. case 'SpotLight':
  13021. uniforms = {
  13022. shadowBias: 0,
  13023. shadowNormalBias: 0,
  13024. shadowRadius: 1,
  13025. shadowMapSize: new Vector2()
  13026. };
  13027. break;
  13028. case 'PointLight':
  13029. uniforms = {
  13030. shadowBias: 0,
  13031. shadowNormalBias: 0,
  13032. shadowRadius: 1,
  13033. shadowMapSize: new Vector2(),
  13034. shadowCameraNear: 1,
  13035. shadowCameraFar: 1000
  13036. };
  13037. break;
  13038. // TODO (abelnation): set RectAreaLight shadow uniforms
  13039. }
  13040. lights[ light.id ] = uniforms;
  13041. return uniforms;
  13042. }
  13043. };
  13044. }
  13045. let nextVersion = 0;
  13046. function shadowCastingAndTexturingLightsFirst( lightA, lightB ) {
  13047. return ( lightB.castShadow ? 2 : 0 ) - ( lightA.castShadow ? 2 : 0 ) + ( lightB.map ? 1 : 0 ) - ( lightA.map ? 1 : 0 );
  13048. }
  13049. function WebGLLights( extensions, capabilities ) {
  13050. const cache = new UniformsCache();
  13051. const shadowCache = ShadowUniformsCache();
  13052. const state = {
  13053. version: 0,
  13054. hash: {
  13055. directionalLength: - 1,
  13056. pointLength: - 1,
  13057. spotLength: - 1,
  13058. rectAreaLength: - 1,
  13059. hemiLength: - 1,
  13060. numDirectionalShadows: - 1,
  13061. numPointShadows: - 1,
  13062. numSpotShadows: - 1,
  13063. numSpotMaps: - 1,
  13064. numLightProbes: - 1
  13065. },
  13066. ambient: [ 0, 0, 0 ],
  13067. probe: [],
  13068. directional: [],
  13069. directionalShadow: [],
  13070. directionalShadowMap: [],
  13071. directionalShadowMatrix: [],
  13072. spot: [],
  13073. spotLightMap: [],
  13074. spotShadow: [],
  13075. spotShadowMap: [],
  13076. spotLightMatrix: [],
  13077. rectArea: [],
  13078. rectAreaLTC1: null,
  13079. rectAreaLTC2: null,
  13080. point: [],
  13081. pointShadow: [],
  13082. pointShadowMap: [],
  13083. pointShadowMatrix: [],
  13084. hemi: [],
  13085. numSpotLightShadowsWithMaps: 0,
  13086. numLightProbes: 0
  13087. };
  13088. for ( let i = 0; i < 9; i ++ ) state.probe.push( new Vector3() );
  13089. const vector3 = new Vector3();
  13090. const matrix4 = new Matrix4();
  13091. const matrix42 = new Matrix4();
  13092. function setup( lights, useLegacyLights ) {
  13093. let r = 0, g = 0, b = 0;
  13094. for ( let i = 0; i < 9; i ++ ) state.probe[ i ].set( 0, 0, 0 );
  13095. let directionalLength = 0;
  13096. let pointLength = 0;
  13097. let spotLength = 0;
  13098. let rectAreaLength = 0;
  13099. let hemiLength = 0;
  13100. let numDirectionalShadows = 0;
  13101. let numPointShadows = 0;
  13102. let numSpotShadows = 0;
  13103. let numSpotMaps = 0;
  13104. let numSpotShadowsWithMaps = 0;
  13105. let numLightProbes = 0;
  13106. // ordering : [shadow casting + map texturing, map texturing, shadow casting, none ]
  13107. lights.sort( shadowCastingAndTexturingLightsFirst );
  13108. // artist-friendly light intensity scaling factor
  13109. const scaleFactor = ( useLegacyLights === true ) ? Math.PI : 1;
  13110. for ( let i = 0, l = lights.length; i < l; i ++ ) {
  13111. const light = lights[ i ];
  13112. const color = light.color;
  13113. const intensity = light.intensity;
  13114. const distance = light.distance;
  13115. const shadowMap = ( light.shadow && light.shadow.map ) ? light.shadow.map.texture : null;
  13116. if ( light.isAmbientLight ) {
  13117. r += color.r * intensity * scaleFactor;
  13118. g += color.g * intensity * scaleFactor;
  13119. b += color.b * intensity * scaleFactor;
  13120. } else if ( light.isLightProbe ) {
  13121. for ( let j = 0; j < 9; j ++ ) {
  13122. state.probe[ j ].addScaledVector( light.sh.coefficients[ j ], intensity );
  13123. }
  13124. numLightProbes ++;
  13125. } else if ( light.isDirectionalLight ) {
  13126. const uniforms = cache.get( light );
  13127. uniforms.color.copy( light.color ).multiplyScalar( light.intensity * scaleFactor );
  13128. if ( light.castShadow ) {
  13129. const shadow = light.shadow;
  13130. const shadowUniforms = shadowCache.get( light );
  13131. shadowUniforms.shadowBias = shadow.bias;
  13132. shadowUniforms.shadowNormalBias = shadow.normalBias;
  13133. shadowUniforms.shadowRadius = shadow.radius;
  13134. shadowUniforms.shadowMapSize = shadow.mapSize;
  13135. state.directionalShadow[ directionalLength ] = shadowUniforms;
  13136. state.directionalShadowMap[ directionalLength ] = shadowMap;
  13137. state.directionalShadowMatrix[ directionalLength ] = light.shadow.matrix;
  13138. numDirectionalShadows ++;
  13139. }
  13140. state.directional[ directionalLength ] = uniforms;
  13141. directionalLength ++;
  13142. } else if ( light.isSpotLight ) {
  13143. const uniforms = cache.get( light );
  13144. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  13145. uniforms.color.copy( color ).multiplyScalar( intensity * scaleFactor );
  13146. uniforms.distance = distance;
  13147. uniforms.coneCos = Math.cos( light.angle );
  13148. uniforms.penumbraCos = Math.cos( light.angle * ( 1 - light.penumbra ) );
  13149. uniforms.decay = light.decay;
  13150. state.spot[ spotLength ] = uniforms;
  13151. const shadow = light.shadow;
  13152. if ( light.map ) {
  13153. state.spotLightMap[ numSpotMaps ] = light.map;
  13154. numSpotMaps ++;
  13155. // make sure the lightMatrix is up to date
  13156. // TODO : do it if required only
  13157. shadow.updateMatrices( light );
  13158. if ( light.castShadow ) numSpotShadowsWithMaps ++;
  13159. }
  13160. state.spotLightMatrix[ spotLength ] = shadow.matrix;
  13161. if ( light.castShadow ) {
  13162. const shadowUniforms = shadowCache.get( light );
  13163. shadowUniforms.shadowBias = shadow.bias;
  13164. shadowUniforms.shadowNormalBias = shadow.normalBias;
  13165. shadowUniforms.shadowRadius = shadow.radius;
  13166. shadowUniforms.shadowMapSize = shadow.mapSize;
  13167. state.spotShadow[ spotLength ] = shadowUniforms;
  13168. state.spotShadowMap[ spotLength ] = shadowMap;
  13169. numSpotShadows ++;
  13170. }
  13171. spotLength ++;
  13172. } else if ( light.isRectAreaLight ) {
  13173. const uniforms = cache.get( light );
  13174. uniforms.color.copy( color ).multiplyScalar( intensity );
  13175. uniforms.halfWidth.set( light.width * 0.5, 0.0, 0.0 );
  13176. uniforms.halfHeight.set( 0.0, light.height * 0.5, 0.0 );
  13177. state.rectArea[ rectAreaLength ] = uniforms;
  13178. rectAreaLength ++;
  13179. } else if ( light.isPointLight ) {
  13180. const uniforms = cache.get( light );
  13181. uniforms.color.copy( light.color ).multiplyScalar( light.intensity * scaleFactor );
  13182. uniforms.distance = light.distance;
  13183. uniforms.decay = light.decay;
  13184. if ( light.castShadow ) {
  13185. const shadow = light.shadow;
  13186. const shadowUniforms = shadowCache.get( light );
  13187. shadowUniforms.shadowBias = shadow.bias;
  13188. shadowUniforms.shadowNormalBias = shadow.normalBias;
  13189. shadowUniforms.shadowRadius = shadow.radius;
  13190. shadowUniforms.shadowMapSize = shadow.mapSize;
  13191. shadowUniforms.shadowCameraNear = shadow.camera.near;
  13192. shadowUniforms.shadowCameraFar = shadow.camera.far;
  13193. state.pointShadow[ pointLength ] = shadowUniforms;
  13194. state.pointShadowMap[ pointLength ] = shadowMap;
  13195. state.pointShadowMatrix[ pointLength ] = light.shadow.matrix;
  13196. numPointShadows ++;
  13197. }
  13198. state.point[ pointLength ] = uniforms;
  13199. pointLength ++;
  13200. } else if ( light.isHemisphereLight ) {
  13201. const uniforms = cache.get( light );
  13202. uniforms.skyColor.copy( light.color ).multiplyScalar( intensity * scaleFactor );
  13203. uniforms.groundColor.copy( light.groundColor ).multiplyScalar( intensity * scaleFactor );
  13204. state.hemi[ hemiLength ] = uniforms;
  13205. hemiLength ++;
  13206. }
  13207. }
  13208. if ( rectAreaLength > 0 ) {
  13209. if ( capabilities.isWebGL2 ) {
  13210. // WebGL 2
  13211. if ( extensions.has( 'OES_texture_float_linear' ) === true ) {
  13212. state.rectAreaLTC1 = UniformsLib.LTC_FLOAT_1;
  13213. state.rectAreaLTC2 = UniformsLib.LTC_FLOAT_2;
  13214. } else {
  13215. state.rectAreaLTC1 = UniformsLib.LTC_HALF_1;
  13216. state.rectAreaLTC2 = UniformsLib.LTC_HALF_2;
  13217. }
  13218. } else {
  13219. // WebGL 1
  13220. if ( extensions.has( 'OES_texture_float_linear' ) === true ) {
  13221. state.rectAreaLTC1 = UniformsLib.LTC_FLOAT_1;
  13222. state.rectAreaLTC2 = UniformsLib.LTC_FLOAT_2;
  13223. } else if ( extensions.has( 'OES_texture_half_float_linear' ) === true ) {
  13224. state.rectAreaLTC1 = UniformsLib.LTC_HALF_1;
  13225. state.rectAreaLTC2 = UniformsLib.LTC_HALF_2;
  13226. } else {
  13227. console.error( 'THREE.WebGLRenderer: Unable to use RectAreaLight. Missing WebGL extensions.' );
  13228. }
  13229. }
  13230. }
  13231. state.ambient[ 0 ] = r;
  13232. state.ambient[ 1 ] = g;
  13233. state.ambient[ 2 ] = b;
  13234. const hash = state.hash;
  13235. if ( hash.directionalLength !== directionalLength ||
  13236. hash.pointLength !== pointLength ||
  13237. hash.spotLength !== spotLength ||
  13238. hash.rectAreaLength !== rectAreaLength ||
  13239. hash.hemiLength !== hemiLength ||
  13240. hash.numDirectionalShadows !== numDirectionalShadows ||
  13241. hash.numPointShadows !== numPointShadows ||
  13242. hash.numSpotShadows !== numSpotShadows ||
  13243. hash.numSpotMaps !== numSpotMaps ||
  13244. hash.numLightProbes !== numLightProbes ) {
  13245. state.directional.length = directionalLength;
  13246. state.spot.length = spotLength;
  13247. state.rectArea.length = rectAreaLength;
  13248. state.point.length = pointLength;
  13249. state.hemi.length = hemiLength;
  13250. state.directionalShadow.length = numDirectionalShadows;
  13251. state.directionalShadowMap.length = numDirectionalShadows;
  13252. state.pointShadow.length = numPointShadows;
  13253. state.pointShadowMap.length = numPointShadows;
  13254. state.spotShadow.length = numSpotShadows;
  13255. state.spotShadowMap.length = numSpotShadows;
  13256. state.directionalShadowMatrix.length = numDirectionalShadows;
  13257. state.pointShadowMatrix.length = numPointShadows;
  13258. state.spotLightMatrix.length = numSpotShadows + numSpotMaps - numSpotShadowsWithMaps;
  13259. state.spotLightMap.length = numSpotMaps;
  13260. state.numSpotLightShadowsWithMaps = numSpotShadowsWithMaps;
  13261. state.numLightProbes = numLightProbes;
  13262. hash.directionalLength = directionalLength;
  13263. hash.pointLength = pointLength;
  13264. hash.spotLength = spotLength;
  13265. hash.rectAreaLength = rectAreaLength;
  13266. hash.hemiLength = hemiLength;
  13267. hash.numDirectionalShadows = numDirectionalShadows;
  13268. hash.numPointShadows = numPointShadows;
  13269. hash.numSpotShadows = numSpotShadows;
  13270. hash.numSpotMaps = numSpotMaps;
  13271. hash.numLightProbes = numLightProbes;
  13272. state.version = nextVersion ++;
  13273. }
  13274. }
  13275. function setupView( lights, camera ) {
  13276. let directionalLength = 0;
  13277. let pointLength = 0;
  13278. let spotLength = 0;
  13279. let rectAreaLength = 0;
  13280. let hemiLength = 0;
  13281. const viewMatrix = camera.matrixWorldInverse;
  13282. for ( let i = 0, l = lights.length; i < l; i ++ ) {
  13283. const light = lights[ i ];
  13284. if ( light.isDirectionalLight ) {
  13285. const uniforms = state.directional[ directionalLength ];
  13286. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  13287. vector3.setFromMatrixPosition( light.target.matrixWorld );
  13288. uniforms.direction.sub( vector3 );
  13289. uniforms.direction.transformDirection( viewMatrix );
  13290. directionalLength ++;
  13291. } else if ( light.isSpotLight ) {
  13292. const uniforms = state.spot[ spotLength ];
  13293. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  13294. uniforms.position.applyMatrix4( viewMatrix );
  13295. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  13296. vector3.setFromMatrixPosition( light.target.matrixWorld );
  13297. uniforms.direction.sub( vector3 );
  13298. uniforms.direction.transformDirection( viewMatrix );
  13299. spotLength ++;
  13300. } else if ( light.isRectAreaLight ) {
  13301. const uniforms = state.rectArea[ rectAreaLength ];
  13302. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  13303. uniforms.position.applyMatrix4( viewMatrix );
  13304. // extract local rotation of light to derive width/height half vectors
  13305. matrix42.identity();
  13306. matrix4.copy( light.matrixWorld );
  13307. matrix4.premultiply( viewMatrix );
  13308. matrix42.extractRotation( matrix4 );
  13309. uniforms.halfWidth.set( light.width * 0.5, 0.0, 0.0 );
  13310. uniforms.halfHeight.set( 0.0, light.height * 0.5, 0.0 );
  13311. uniforms.halfWidth.applyMatrix4( matrix42 );
  13312. uniforms.halfHeight.applyMatrix4( matrix42 );
  13313. rectAreaLength ++;
  13314. } else if ( light.isPointLight ) {
  13315. const uniforms = state.point[ pointLength ];
  13316. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  13317. uniforms.position.applyMatrix4( viewMatrix );
  13318. pointLength ++;
  13319. } else if ( light.isHemisphereLight ) {
  13320. const uniforms = state.hemi[ hemiLength ];
  13321. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  13322. uniforms.direction.transformDirection( viewMatrix );
  13323. hemiLength ++;
  13324. }
  13325. }
  13326. }
  13327. return {
  13328. setup: setup,
  13329. setupView: setupView,
  13330. state: state
  13331. };
  13332. }
  13333. function WebGLRenderState( extensions, capabilities ) {
  13334. const lights = new WebGLLights( extensions, capabilities );
  13335. const lightsArray = [];
  13336. const shadowsArray = [];
  13337. function init() {
  13338. lightsArray.length = 0;
  13339. shadowsArray.length = 0;
  13340. }
  13341. function pushLight( light ) {
  13342. lightsArray.push( light );
  13343. }
  13344. function pushShadow( shadowLight ) {
  13345. shadowsArray.push( shadowLight );
  13346. }
  13347. function setupLights( useLegacyLights ) {
  13348. lights.setup( lightsArray, useLegacyLights );
  13349. }
  13350. function setupLightsView( camera ) {
  13351. lights.setupView( lightsArray, camera );
  13352. }
  13353. const state = {
  13354. lightsArray: lightsArray,
  13355. shadowsArray: shadowsArray,
  13356. lights: lights
  13357. };
  13358. return {
  13359. init: init,
  13360. state: state,
  13361. setupLights: setupLights,
  13362. setupLightsView: setupLightsView,
  13363. pushLight: pushLight,
  13364. pushShadow: pushShadow
  13365. };
  13366. }
  13367. function WebGLRenderStates( extensions, capabilities ) {
  13368. let renderStates = new WeakMap();
  13369. function get( scene, renderCallDepth = 0 ) {
  13370. const renderStateArray = renderStates.get( scene );
  13371. let renderState;
  13372. if ( renderStateArray === undefined ) {
  13373. renderState = new WebGLRenderState( extensions, capabilities );
  13374. renderStates.set( scene, [ renderState ] );
  13375. } else {
  13376. if ( renderCallDepth >= renderStateArray.length ) {
  13377. renderState = new WebGLRenderState( extensions, capabilities );
  13378. renderStateArray.push( renderState );
  13379. } else {
  13380. renderState = renderStateArray[ renderCallDepth ];
  13381. }
  13382. }
  13383. return renderState;
  13384. }
  13385. function dispose() {
  13386. renderStates = new WeakMap();
  13387. }
  13388. return {
  13389. get: get,
  13390. dispose: dispose
  13391. };
  13392. }
  13393. class MeshDepthMaterial extends Material {
  13394. constructor( parameters ) {
  13395. super();
  13396. this.isMeshDepthMaterial = true;
  13397. this.type = 'MeshDepthMaterial';
  13398. this.depthPacking = BasicDepthPacking;
  13399. this.map = null;
  13400. this.alphaMap = null;
  13401. this.displacementMap = null;
  13402. this.displacementScale = 1;
  13403. this.displacementBias = 0;
  13404. this.wireframe = false;
  13405. this.wireframeLinewidth = 1;
  13406. this.setValues( parameters );
  13407. }
  13408. copy( source ) {
  13409. super.copy( source );
  13410. this.depthPacking = source.depthPacking;
  13411. this.map = source.map;
  13412. this.alphaMap = source.alphaMap;
  13413. this.displacementMap = source.displacementMap;
  13414. this.displacementScale = source.displacementScale;
  13415. this.displacementBias = source.displacementBias;
  13416. this.wireframe = source.wireframe;
  13417. this.wireframeLinewidth = source.wireframeLinewidth;
  13418. return this;
  13419. }
  13420. }
  13421. class MeshDistanceMaterial extends Material {
  13422. constructor( parameters ) {
  13423. super();
  13424. this.isMeshDistanceMaterial = true;
  13425. this.type = 'MeshDistanceMaterial';
  13426. this.map = null;
  13427. this.alphaMap = null;
  13428. this.displacementMap = null;
  13429. this.displacementScale = 1;
  13430. this.displacementBias = 0;
  13431. this.setValues( parameters );
  13432. }
  13433. copy( source ) {
  13434. super.copy( source );
  13435. this.map = source.map;
  13436. this.alphaMap = source.alphaMap;
  13437. this.displacementMap = source.displacementMap;
  13438. this.displacementScale = source.displacementScale;
  13439. this.displacementBias = source.displacementBias;
  13440. return this;
  13441. }
  13442. }
  13443. const vertex = "void main() {\n\tgl_Position = vec4( position, 1.0 );\n}";
  13444. 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}";
  13445. function WebGLShadowMap( _renderer, _objects, _capabilities ) {
  13446. let _frustum = new Frustum();
  13447. const _shadowMapSize = new Vector2(),
  13448. _viewportSize = new Vector2(),
  13449. _viewport = new Vector4(),
  13450. _depthMaterial = new MeshDepthMaterial( { depthPacking: RGBADepthPacking } ),
  13451. _distanceMaterial = new MeshDistanceMaterial(),
  13452. _materialCache = {},
  13453. _maxTextureSize = _capabilities.maxTextureSize;
  13454. const shadowSide = { [ FrontSide ]: BackSide, [ BackSide ]: FrontSide, [ DoubleSide ]: DoubleSide };
  13455. const shadowMaterialVertical = new ShaderMaterial( {
  13456. defines: {
  13457. VSM_SAMPLES: 8
  13458. },
  13459. uniforms: {
  13460. shadow_pass: { value: null },
  13461. resolution: { value: new Vector2() },
  13462. radius: { value: 4.0 }
  13463. },
  13464. vertexShader: vertex,
  13465. fragmentShader: fragment
  13466. } );
  13467. const shadowMaterialHorizontal = shadowMaterialVertical.clone();
  13468. shadowMaterialHorizontal.defines.HORIZONTAL_PASS = 1;
  13469. const fullScreenTri = new BufferGeometry();
  13470. fullScreenTri.setAttribute(
  13471. 'position',
  13472. new BufferAttribute(
  13473. new Float32Array( [ - 1, - 1, 0.5, 3, - 1, 0.5, - 1, 3, 0.5 ] ),
  13474. 3
  13475. )
  13476. );
  13477. const fullScreenMesh = new Mesh( fullScreenTri, shadowMaterialVertical );
  13478. const scope = this;
  13479. this.enabled = false;
  13480. this.autoUpdate = true;
  13481. this.needsUpdate = false;
  13482. this.type = PCFShadowMap;
  13483. let _previousType = this.type;
  13484. this.render = function ( lights, scene, camera ) {
  13485. if ( scope.enabled === false ) return;
  13486. if ( scope.autoUpdate === false && scope.needsUpdate === false ) return;
  13487. if ( lights.length === 0 ) return;
  13488. const currentRenderTarget = _renderer.getRenderTarget();
  13489. const activeCubeFace = _renderer.getActiveCubeFace();
  13490. const activeMipmapLevel = _renderer.getActiveMipmapLevel();
  13491. const _state = _renderer.state;
  13492. // Set GL state for depth map.
  13493. _state.setBlending( NoBlending );
  13494. _state.buffers.color.setClear( 1, 1, 1, 1 );
  13495. _state.buffers.depth.setTest( true );
  13496. _state.setScissorTest( false );
  13497. // check for shadow map type changes
  13498. const toVSM = ( _previousType !== VSMShadowMap && this.type === VSMShadowMap );
  13499. const fromVSM = ( _previousType === VSMShadowMap && this.type !== VSMShadowMap );
  13500. // render depth map
  13501. for ( let i = 0, il = lights.length; i < il; i ++ ) {
  13502. const light = lights[ i ];
  13503. const shadow = light.shadow;
  13504. if ( shadow === undefined ) {
  13505. console.warn( 'THREE.WebGLShadowMap:', light, 'has no shadow.' );
  13506. continue;
  13507. }
  13508. if ( shadow.autoUpdate === false && shadow.needsUpdate === false ) continue;
  13509. _shadowMapSize.copy( shadow.mapSize );
  13510. const shadowFrameExtents = shadow.getFrameExtents();
  13511. _shadowMapSize.multiply( shadowFrameExtents );
  13512. _viewportSize.copy( shadow.mapSize );
  13513. if ( _shadowMapSize.x > _maxTextureSize || _shadowMapSize.y > _maxTextureSize ) {
  13514. if ( _shadowMapSize.x > _maxTextureSize ) {
  13515. _viewportSize.x = Math.floor( _maxTextureSize / shadowFrameExtents.x );
  13516. _shadowMapSize.x = _viewportSize.x * shadowFrameExtents.x;
  13517. shadow.mapSize.x = _viewportSize.x;
  13518. }
  13519. if ( _shadowMapSize.y > _maxTextureSize ) {
  13520. _viewportSize.y = Math.floor( _maxTextureSize / shadowFrameExtents.y );
  13521. _shadowMapSize.y = _viewportSize.y * shadowFrameExtents.y;
  13522. shadow.mapSize.y = _viewportSize.y;
  13523. }
  13524. }
  13525. if ( shadow.map === null || toVSM === true || fromVSM === true ) {
  13526. const pars = ( this.type !== VSMShadowMap ) ? { minFilter: NearestFilter, magFilter: NearestFilter } : {};
  13527. if ( shadow.map !== null ) {
  13528. shadow.map.dispose();
  13529. }
  13530. shadow.map = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, pars );
  13531. shadow.map.texture.name = light.name + '.shadowMap';
  13532. shadow.camera.updateProjectionMatrix();
  13533. }
  13534. _renderer.setRenderTarget( shadow.map );
  13535. _renderer.clear();
  13536. const viewportCount = shadow.getViewportCount();
  13537. for ( let vp = 0; vp < viewportCount; vp ++ ) {
  13538. const viewport = shadow.getViewport( vp );
  13539. _viewport.set(
  13540. _viewportSize.x * viewport.x,
  13541. _viewportSize.y * viewport.y,
  13542. _viewportSize.x * viewport.z,
  13543. _viewportSize.y * viewport.w
  13544. );
  13545. _state.viewport( _viewport );
  13546. shadow.updateMatrices( light, vp );
  13547. _frustum = shadow.getFrustum();
  13548. renderObject( scene, camera, shadow.camera, light, this.type );
  13549. }
  13550. // do blur pass for VSM
  13551. if ( shadow.isPointLightShadow !== true && this.type === VSMShadowMap ) {
  13552. VSMPass( shadow, camera );
  13553. }
  13554. shadow.needsUpdate = false;
  13555. }
  13556. _previousType = this.type;
  13557. scope.needsUpdate = false;
  13558. _renderer.setRenderTarget( currentRenderTarget, activeCubeFace, activeMipmapLevel );
  13559. };
  13560. function VSMPass( shadow, camera ) {
  13561. const geometry = _objects.update( fullScreenMesh );
  13562. if ( shadowMaterialVertical.defines.VSM_SAMPLES !== shadow.blurSamples ) {
  13563. shadowMaterialVertical.defines.VSM_SAMPLES = shadow.blurSamples;
  13564. shadowMaterialHorizontal.defines.VSM_SAMPLES = shadow.blurSamples;
  13565. shadowMaterialVertical.needsUpdate = true;
  13566. shadowMaterialHorizontal.needsUpdate = true;
  13567. }
  13568. if ( shadow.mapPass === null ) {
  13569. shadow.mapPass = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y );
  13570. }
  13571. // vertical pass
  13572. shadowMaterialVertical.uniforms.shadow_pass.value = shadow.map.texture;
  13573. shadowMaterialVertical.uniforms.resolution.value = shadow.mapSize;
  13574. shadowMaterialVertical.uniforms.radius.value = shadow.radius;
  13575. _renderer.setRenderTarget( shadow.mapPass );
  13576. _renderer.clear();
  13577. _renderer.renderBufferDirect( camera, null, geometry, shadowMaterialVertical, fullScreenMesh, null );
  13578. // horizontal pass
  13579. shadowMaterialHorizontal.uniforms.shadow_pass.value = shadow.mapPass.texture;
  13580. shadowMaterialHorizontal.uniforms.resolution.value = shadow.mapSize;
  13581. shadowMaterialHorizontal.uniforms.radius.value = shadow.radius;
  13582. _renderer.setRenderTarget( shadow.map );
  13583. _renderer.clear();
  13584. _renderer.renderBufferDirect( camera, null, geometry, shadowMaterialHorizontal, fullScreenMesh, null );
  13585. }
  13586. function getDepthMaterial( object, material, light, type ) {
  13587. let result = null;
  13588. const customMaterial = ( light.isPointLight === true ) ? object.customDistanceMaterial : object.customDepthMaterial;
  13589. if ( customMaterial !== undefined ) {
  13590. result = customMaterial;
  13591. } else {
  13592. result = ( light.isPointLight === true ) ? _distanceMaterial : _depthMaterial;
  13593. if ( ( _renderer.localClippingEnabled && material.clipShadows === true && Array.isArray( material.clippingPlanes ) && material.clippingPlanes.length !== 0 ) ||
  13594. ( material.displacementMap && material.displacementScale !== 0 ) ||
  13595. ( material.alphaMap && material.alphaTest > 0 ) ||
  13596. ( material.map && material.alphaTest > 0 ) ) {
  13597. // in this case we need a unique material instance reflecting the
  13598. // appropriate state
  13599. const keyA = result.uuid, keyB = material.uuid;
  13600. let materialsForVariant = _materialCache[ keyA ];
  13601. if ( materialsForVariant === undefined ) {
  13602. materialsForVariant = {};
  13603. _materialCache[ keyA ] = materialsForVariant;
  13604. }
  13605. let cachedMaterial = materialsForVariant[ keyB ];
  13606. if ( cachedMaterial === undefined ) {
  13607. cachedMaterial = result.clone();
  13608. materialsForVariant[ keyB ] = cachedMaterial;
  13609. material.addEventListener( 'dispose', onMaterialDispose );
  13610. }
  13611. result = cachedMaterial;
  13612. }
  13613. }
  13614. result.visible = material.visible;
  13615. result.wireframe = material.wireframe;
  13616. if ( type === VSMShadowMap ) {
  13617. result.side = ( material.shadowSide !== null ) ? material.shadowSide : material.side;
  13618. } else {
  13619. result.side = ( material.shadowSide !== null ) ? material.shadowSide : shadowSide[ material.side ];
  13620. }
  13621. result.alphaMap = material.alphaMap;
  13622. result.alphaTest = material.alphaTest;
  13623. result.map = material.map;
  13624. result.clipShadows = material.clipShadows;
  13625. result.clippingPlanes = material.clippingPlanes;
  13626. result.clipIntersection = material.clipIntersection;
  13627. result.displacementMap = material.displacementMap;
  13628. result.displacementScale = material.displacementScale;
  13629. result.displacementBias = material.displacementBias;
  13630. result.wireframeLinewidth = material.wireframeLinewidth;
  13631. result.linewidth = material.linewidth;
  13632. if ( light.isPointLight === true && result.isMeshDistanceMaterial === true ) {
  13633. const materialProperties = _renderer.properties.get( result );
  13634. materialProperties.light = light;
  13635. }
  13636. return result;
  13637. }
  13638. function renderObject( object, camera, shadowCamera, light, type ) {
  13639. if ( object.visible === false ) return;
  13640. const visible = object.layers.test( camera.layers );
  13641. if ( visible && ( object.isMesh || object.isLine || object.isPoints ) ) {
  13642. if ( ( object.castShadow || ( object.receiveShadow && type === VSMShadowMap ) ) && ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) ) {
  13643. object.modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  13644. const geometry = _objects.update( object );
  13645. const material = object.material;
  13646. if ( Array.isArray( material ) ) {
  13647. const groups = geometry.groups;
  13648. for ( let k = 0, kl = groups.length; k < kl; k ++ ) {
  13649. const group = groups[ k ];
  13650. const groupMaterial = material[ group.materialIndex ];
  13651. if ( groupMaterial && groupMaterial.visible ) {
  13652. const depthMaterial = getDepthMaterial( object, groupMaterial, light, type );
  13653. object.onBeforeShadow( _renderer, object, camera, shadowCamera, geometry, depthMaterial, group );
  13654. _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, group );
  13655. object.onAfterShadow( _renderer, object, camera, shadowCamera, geometry, depthMaterial, group );
  13656. }
  13657. }
  13658. } else if ( material.visible ) {
  13659. const depthMaterial = getDepthMaterial( object, material, light, type );
  13660. object.onBeforeShadow( _renderer, object, camera, shadowCamera, geometry, depthMaterial, null );
  13661. _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, null );
  13662. object.onAfterShadow( _renderer, object, camera, shadowCamera, geometry, depthMaterial, null );
  13663. }
  13664. }
  13665. }
  13666. const children = object.children;
  13667. for ( let i = 0, l = children.length; i < l; i ++ ) {
  13668. renderObject( children[ i ], camera, shadowCamera, light, type );
  13669. }
  13670. }
  13671. function onMaterialDispose( event ) {
  13672. const material = event.target;
  13673. material.removeEventListener( 'dispose', onMaterialDispose );
  13674. // make sure to remove the unique distance/depth materials used for shadow map rendering
  13675. for ( const id in _materialCache ) {
  13676. const cache = _materialCache[ id ];
  13677. const uuid = event.target.uuid;
  13678. if ( uuid in cache ) {
  13679. const shadowMaterial = cache[ uuid ];
  13680. shadowMaterial.dispose();
  13681. delete cache[ uuid ];
  13682. }
  13683. }
  13684. }
  13685. }
  13686. function WebGLState( gl, extensions, capabilities ) {
  13687. const isWebGL2 = capabilities.isWebGL2;
  13688. function ColorBuffer() {
  13689. let locked = false;
  13690. const color = new Vector4();
  13691. let currentColorMask = null;
  13692. const currentColorClear = new Vector4( 0, 0, 0, 0 );
  13693. return {
  13694. setMask: function ( colorMask ) {
  13695. if ( currentColorMask !== colorMask && ! locked ) {
  13696. gl.colorMask( colorMask, colorMask, colorMask, colorMask );
  13697. currentColorMask = colorMask;
  13698. }
  13699. },
  13700. setLocked: function ( lock ) {
  13701. locked = lock;
  13702. },
  13703. setClear: function ( r, g, b, a, premultipliedAlpha ) {
  13704. if ( premultipliedAlpha === true ) {
  13705. r *= a; g *= a; b *= a;
  13706. }
  13707. color.set( r, g, b, a );
  13708. if ( currentColorClear.equals( color ) === false ) {
  13709. gl.clearColor( r, g, b, a );
  13710. currentColorClear.copy( color );
  13711. }
  13712. },
  13713. reset: function () {
  13714. locked = false;
  13715. currentColorMask = null;
  13716. currentColorClear.set( - 1, 0, 0, 0 ); // set to invalid state
  13717. }
  13718. };
  13719. }
  13720. function DepthBuffer() {
  13721. let locked = false;
  13722. let currentDepthMask = null;
  13723. let currentDepthFunc = null;
  13724. let currentDepthClear = null;
  13725. return {
  13726. setTest: function ( depthTest ) {
  13727. if ( depthTest ) {
  13728. enable( gl.DEPTH_TEST );
  13729. } else {
  13730. disable( gl.DEPTH_TEST );
  13731. }
  13732. },
  13733. setMask: function ( depthMask ) {
  13734. if ( currentDepthMask !== depthMask && ! locked ) {
  13735. gl.depthMask( depthMask );
  13736. currentDepthMask = depthMask;
  13737. }
  13738. },
  13739. setFunc: function ( depthFunc ) {
  13740. if ( currentDepthFunc !== depthFunc ) {
  13741. switch ( depthFunc ) {
  13742. case NeverDepth:
  13743. gl.depthFunc( gl.NEVER );
  13744. break;
  13745. case AlwaysDepth:
  13746. gl.depthFunc( gl.ALWAYS );
  13747. break;
  13748. case LessDepth:
  13749. gl.depthFunc( gl.LESS );
  13750. break;
  13751. case LessEqualDepth:
  13752. gl.depthFunc( gl.LEQUAL );
  13753. break;
  13754. case EqualDepth:
  13755. gl.depthFunc( gl.EQUAL );
  13756. break;
  13757. case GreaterEqualDepth:
  13758. gl.depthFunc( gl.GEQUAL );
  13759. break;
  13760. case GreaterDepth:
  13761. gl.depthFunc( gl.GREATER );
  13762. break;
  13763. case NotEqualDepth:
  13764. gl.depthFunc( gl.NOTEQUAL );
  13765. break;
  13766. default:
  13767. gl.depthFunc( gl.LEQUAL );
  13768. }
  13769. currentDepthFunc = depthFunc;
  13770. }
  13771. },
  13772. setLocked: function ( lock ) {
  13773. locked = lock;
  13774. },
  13775. setClear: function ( depth ) {
  13776. if ( currentDepthClear !== depth ) {
  13777. gl.clearDepth( depth );
  13778. currentDepthClear = depth;
  13779. }
  13780. },
  13781. reset: function () {
  13782. locked = false;
  13783. currentDepthMask = null;
  13784. currentDepthFunc = null;
  13785. currentDepthClear = null;
  13786. }
  13787. };
  13788. }
  13789. function StencilBuffer() {
  13790. let locked = false;
  13791. let currentStencilMask = null;
  13792. let currentStencilFunc = null;
  13793. let currentStencilRef = null;
  13794. let currentStencilFuncMask = null;
  13795. let currentStencilFail = null;
  13796. let currentStencilZFail = null;
  13797. let currentStencilZPass = null;
  13798. let currentStencilClear = null;
  13799. return {
  13800. setTest: function ( stencilTest ) {
  13801. if ( ! locked ) {
  13802. if ( stencilTest ) {
  13803. enable( gl.STENCIL_TEST );
  13804. } else {
  13805. disable( gl.STENCIL_TEST );
  13806. }
  13807. }
  13808. },
  13809. setMask: function ( stencilMask ) {
  13810. if ( currentStencilMask !== stencilMask && ! locked ) {
  13811. gl.stencilMask( stencilMask );
  13812. currentStencilMask = stencilMask;
  13813. }
  13814. },
  13815. setFunc: function ( stencilFunc, stencilRef, stencilMask ) {
  13816. if ( currentStencilFunc !== stencilFunc ||
  13817. currentStencilRef !== stencilRef ||
  13818. currentStencilFuncMask !== stencilMask ) {
  13819. gl.stencilFunc( stencilFunc, stencilRef, stencilMask );
  13820. currentStencilFunc = stencilFunc;
  13821. currentStencilRef = stencilRef;
  13822. currentStencilFuncMask = stencilMask;
  13823. }
  13824. },
  13825. setOp: function ( stencilFail, stencilZFail, stencilZPass ) {
  13826. if ( currentStencilFail !== stencilFail ||
  13827. currentStencilZFail !== stencilZFail ||
  13828. currentStencilZPass !== stencilZPass ) {
  13829. gl.stencilOp( stencilFail, stencilZFail, stencilZPass );
  13830. currentStencilFail = stencilFail;
  13831. currentStencilZFail = stencilZFail;
  13832. currentStencilZPass = stencilZPass;
  13833. }
  13834. },
  13835. setLocked: function ( lock ) {
  13836. locked = lock;
  13837. },
  13838. setClear: function ( stencil ) {
  13839. if ( currentStencilClear !== stencil ) {
  13840. gl.clearStencil( stencil );
  13841. currentStencilClear = stencil;
  13842. }
  13843. },
  13844. reset: function () {
  13845. locked = false;
  13846. currentStencilMask = null;
  13847. currentStencilFunc = null;
  13848. currentStencilRef = null;
  13849. currentStencilFuncMask = null;
  13850. currentStencilFail = null;
  13851. currentStencilZFail = null;
  13852. currentStencilZPass = null;
  13853. currentStencilClear = null;
  13854. }
  13855. };
  13856. }
  13857. //
  13858. const colorBuffer = new ColorBuffer();
  13859. const depthBuffer = new DepthBuffer();
  13860. const stencilBuffer = new StencilBuffer();
  13861. const uboBindings = new WeakMap();
  13862. const uboProgramMap = new WeakMap();
  13863. let enabledCapabilities = {};
  13864. let currentBoundFramebuffers = {};
  13865. let currentDrawbuffers = new WeakMap();
  13866. let defaultDrawbuffers = [];
  13867. let currentProgram = null;
  13868. let currentBlendingEnabled = false;
  13869. let currentBlending = null;
  13870. let currentBlendEquation = null;
  13871. let currentBlendSrc = null;
  13872. let currentBlendDst = null;
  13873. let currentBlendEquationAlpha = null;
  13874. let currentBlendSrcAlpha = null;
  13875. let currentBlendDstAlpha = null;
  13876. let currentBlendColor = new Color( 0, 0, 0 );
  13877. let currentBlendAlpha = 0;
  13878. let currentPremultipledAlpha = false;
  13879. let currentFlipSided = null;
  13880. let currentCullFace = null;
  13881. let currentLineWidth = null;
  13882. let currentPolygonOffsetFactor = null;
  13883. let currentPolygonOffsetUnits = null;
  13884. const maxTextures = gl.getParameter( gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS );
  13885. let lineWidthAvailable = false;
  13886. let version = 0;
  13887. const glVersion = gl.getParameter( gl.VERSION );
  13888. if ( glVersion.indexOf( 'WebGL' ) !== - 1 ) {
  13889. version = parseFloat( /^WebGL (\d)/.exec( glVersion )[ 1 ] );
  13890. lineWidthAvailable = ( version >= 1.0 );
  13891. } else if ( glVersion.indexOf( 'OpenGL ES' ) !== - 1 ) {
  13892. version = parseFloat( /^OpenGL ES (\d)/.exec( glVersion )[ 1 ] );
  13893. lineWidthAvailable = ( version >= 2.0 );
  13894. }
  13895. let currentTextureSlot = null;
  13896. let currentBoundTextures = {};
  13897. const scissorParam = gl.getParameter( gl.SCISSOR_BOX );
  13898. const viewportParam = gl.getParameter( gl.VIEWPORT );
  13899. const currentScissor = new Vector4().fromArray( scissorParam );
  13900. const currentViewport = new Vector4().fromArray( viewportParam );
  13901. function createTexture( type, target, count, dimensions ) {
  13902. const data = new Uint8Array( 4 ); // 4 is required to match default unpack alignment of 4.
  13903. const texture = gl.createTexture();
  13904. gl.bindTexture( type, texture );
  13905. gl.texParameteri( type, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  13906. gl.texParameteri( type, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  13907. for ( let i = 0; i < count; i ++ ) {
  13908. if ( isWebGL2 && ( type === gl.TEXTURE_3D || type === gl.TEXTURE_2D_ARRAY ) ) {
  13909. gl.texImage3D( target, 0, gl.RGBA, 1, 1, dimensions, 0, gl.RGBA, gl.UNSIGNED_BYTE, data );
  13910. } else {
  13911. gl.texImage2D( target + i, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data );
  13912. }
  13913. }
  13914. return texture;
  13915. }
  13916. const emptyTextures = {};
  13917. emptyTextures[ gl.TEXTURE_2D ] = createTexture( gl.TEXTURE_2D, gl.TEXTURE_2D, 1 );
  13918. emptyTextures[ gl.TEXTURE_CUBE_MAP ] = createTexture( gl.TEXTURE_CUBE_MAP, gl.TEXTURE_CUBE_MAP_POSITIVE_X, 6 );
  13919. if ( isWebGL2 ) {
  13920. emptyTextures[ gl.TEXTURE_2D_ARRAY ] = createTexture( gl.TEXTURE_2D_ARRAY, gl.TEXTURE_2D_ARRAY, 1, 1 );
  13921. emptyTextures[ gl.TEXTURE_3D ] = createTexture( gl.TEXTURE_3D, gl.TEXTURE_3D, 1, 1 );
  13922. }
  13923. // init
  13924. colorBuffer.setClear( 0, 0, 0, 1 );
  13925. depthBuffer.setClear( 1 );
  13926. stencilBuffer.setClear( 0 );
  13927. enable( gl.DEPTH_TEST );
  13928. depthBuffer.setFunc( LessEqualDepth );
  13929. setFlipSided( false );
  13930. setCullFace( CullFaceBack );
  13931. enable( gl.CULL_FACE );
  13932. setBlending( NoBlending );
  13933. //
  13934. function enable( id ) {
  13935. if ( enabledCapabilities[ id ] !== true ) {
  13936. gl.enable( id );
  13937. enabledCapabilities[ id ] = true;
  13938. }
  13939. }
  13940. function disable( id ) {
  13941. if ( enabledCapabilities[ id ] !== false ) {
  13942. gl.disable( id );
  13943. enabledCapabilities[ id ] = false;
  13944. }
  13945. }
  13946. function bindFramebuffer( target, framebuffer ) {
  13947. if ( currentBoundFramebuffers[ target ] !== framebuffer ) {
  13948. gl.bindFramebuffer( target, framebuffer );
  13949. currentBoundFramebuffers[ target ] = framebuffer;
  13950. if ( isWebGL2 ) {
  13951. // gl.DRAW_FRAMEBUFFER is equivalent to gl.FRAMEBUFFER
  13952. if ( target === gl.DRAW_FRAMEBUFFER ) {
  13953. currentBoundFramebuffers[ gl.FRAMEBUFFER ] = framebuffer;
  13954. }
  13955. if ( target === gl.FRAMEBUFFER ) {
  13956. currentBoundFramebuffers[ gl.DRAW_FRAMEBUFFER ] = framebuffer;
  13957. }
  13958. }
  13959. return true;
  13960. }
  13961. return false;
  13962. }
  13963. function drawBuffers( renderTarget, framebuffer ) {
  13964. let drawBuffers = defaultDrawbuffers;
  13965. let needsUpdate = false;
  13966. if ( renderTarget ) {
  13967. drawBuffers = currentDrawbuffers.get( framebuffer );
  13968. if ( drawBuffers === undefined ) {
  13969. drawBuffers = [];
  13970. currentDrawbuffers.set( framebuffer, drawBuffers );
  13971. }
  13972. const textures = renderTarget.textures;
  13973. if ( drawBuffers.length !== textures.length || drawBuffers[ 0 ] !== gl.COLOR_ATTACHMENT0 ) {
  13974. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  13975. drawBuffers[ i ] = gl.COLOR_ATTACHMENT0 + i;
  13976. }
  13977. drawBuffers.length = textures.length;
  13978. needsUpdate = true;
  13979. }
  13980. } else {
  13981. if ( drawBuffers[ 0 ] !== gl.BACK ) {
  13982. drawBuffers[ 0 ] = gl.BACK;
  13983. needsUpdate = true;
  13984. }
  13985. }
  13986. if ( needsUpdate ) {
  13987. if ( capabilities.isWebGL2 ) {
  13988. gl.drawBuffers( drawBuffers );
  13989. } else if ( extensions.has( 'WEBGL_draw_buffers' ) === true ) {
  13990. extensions.get( 'WEBGL_draw_buffers' ).drawBuffersWEBGL( drawBuffers );
  13991. } else {
  13992. throw new Error( 'THREE.WebGLState: Usage of gl.drawBuffers() require WebGL2 or WEBGL_draw_buffers extension' );
  13993. }
  13994. }
  13995. }
  13996. function useProgram( program ) {
  13997. if ( currentProgram !== program ) {
  13998. gl.useProgram( program );
  13999. currentProgram = program;
  14000. return true;
  14001. }
  14002. return false;
  14003. }
  14004. const equationToGL = {
  14005. [ AddEquation ]: gl.FUNC_ADD,
  14006. [ SubtractEquation ]: gl.FUNC_SUBTRACT,
  14007. [ ReverseSubtractEquation ]: gl.FUNC_REVERSE_SUBTRACT
  14008. };
  14009. if ( isWebGL2 ) {
  14010. equationToGL[ MinEquation ] = gl.MIN;
  14011. equationToGL[ MaxEquation ] = gl.MAX;
  14012. } else {
  14013. const extension = extensions.get( 'EXT_blend_minmax' );
  14014. if ( extension !== null ) {
  14015. equationToGL[ MinEquation ] = extension.MIN_EXT;
  14016. equationToGL[ MaxEquation ] = extension.MAX_EXT;
  14017. }
  14018. }
  14019. const factorToGL = {
  14020. [ ZeroFactor ]: gl.ZERO,
  14021. [ OneFactor ]: gl.ONE,
  14022. [ SrcColorFactor ]: gl.SRC_COLOR,
  14023. [ SrcAlphaFactor ]: gl.SRC_ALPHA,
  14024. [ SrcAlphaSaturateFactor ]: gl.SRC_ALPHA_SATURATE,
  14025. [ DstColorFactor ]: gl.DST_COLOR,
  14026. [ DstAlphaFactor ]: gl.DST_ALPHA,
  14027. [ OneMinusSrcColorFactor ]: gl.ONE_MINUS_SRC_COLOR,
  14028. [ OneMinusSrcAlphaFactor ]: gl.ONE_MINUS_SRC_ALPHA,
  14029. [ OneMinusDstColorFactor ]: gl.ONE_MINUS_DST_COLOR,
  14030. [ OneMinusDstAlphaFactor ]: gl.ONE_MINUS_DST_ALPHA,
  14031. [ ConstantColorFactor ]: gl.CONSTANT_COLOR,
  14032. [ OneMinusConstantColorFactor ]: gl.ONE_MINUS_CONSTANT_COLOR,
  14033. [ ConstantAlphaFactor ]: gl.CONSTANT_ALPHA,
  14034. [ OneMinusConstantAlphaFactor ]: gl.ONE_MINUS_CONSTANT_ALPHA
  14035. };
  14036. function setBlending( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, blendColor, blendAlpha, premultipliedAlpha ) {
  14037. if ( blending === NoBlending ) {
  14038. if ( currentBlendingEnabled === true ) {
  14039. disable( gl.BLEND );
  14040. currentBlendingEnabled = false;
  14041. }
  14042. return;
  14043. }
  14044. if ( currentBlendingEnabled === false ) {
  14045. enable( gl.BLEND );
  14046. currentBlendingEnabled = true;
  14047. }
  14048. if ( blending !== CustomBlending ) {
  14049. if ( blending !== currentBlending || premultipliedAlpha !== currentPremultipledAlpha ) {
  14050. if ( currentBlendEquation !== AddEquation || currentBlendEquationAlpha !== AddEquation ) {
  14051. gl.blendEquation( gl.FUNC_ADD );
  14052. currentBlendEquation = AddEquation;
  14053. currentBlendEquationAlpha = AddEquation;
  14054. }
  14055. if ( premultipliedAlpha ) {
  14056. switch ( blending ) {
  14057. case NormalBlending:
  14058. gl.blendFuncSeparate( gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  14059. break;
  14060. case AdditiveBlending:
  14061. gl.blendFunc( gl.ONE, gl.ONE );
  14062. break;
  14063. case SubtractiveBlending:
  14064. gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  14065. break;
  14066. case MultiplyBlending:
  14067. gl.blendFuncSeparate( gl.ZERO, gl.SRC_COLOR, gl.ZERO, gl.SRC_ALPHA );
  14068. break;
  14069. default:
  14070. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  14071. break;
  14072. }
  14073. } else {
  14074. switch ( blending ) {
  14075. case NormalBlending:
  14076. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  14077. break;
  14078. case AdditiveBlending:
  14079. gl.blendFunc( gl.SRC_ALPHA, gl.ONE );
  14080. break;
  14081. case SubtractiveBlending:
  14082. gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  14083. break;
  14084. case MultiplyBlending:
  14085. gl.blendFunc( gl.ZERO, gl.SRC_COLOR );
  14086. break;
  14087. default:
  14088. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  14089. break;
  14090. }
  14091. }
  14092. currentBlendSrc = null;
  14093. currentBlendDst = null;
  14094. currentBlendSrcAlpha = null;
  14095. currentBlendDstAlpha = null;
  14096. currentBlendColor.set( 0, 0, 0 );
  14097. currentBlendAlpha = 0;
  14098. currentBlending = blending;
  14099. currentPremultipledAlpha = premultipliedAlpha;
  14100. }
  14101. return;
  14102. }
  14103. // custom blending
  14104. blendEquationAlpha = blendEquationAlpha || blendEquation;
  14105. blendSrcAlpha = blendSrcAlpha || blendSrc;
  14106. blendDstAlpha = blendDstAlpha || blendDst;
  14107. if ( blendEquation !== currentBlendEquation || blendEquationAlpha !== currentBlendEquationAlpha ) {
  14108. gl.blendEquationSeparate( equationToGL[ blendEquation ], equationToGL[ blendEquationAlpha ] );
  14109. currentBlendEquation = blendEquation;
  14110. currentBlendEquationAlpha = blendEquationAlpha;
  14111. }
  14112. if ( blendSrc !== currentBlendSrc || blendDst !== currentBlendDst || blendSrcAlpha !== currentBlendSrcAlpha || blendDstAlpha !== currentBlendDstAlpha ) {
  14113. gl.blendFuncSeparate( factorToGL[ blendSrc ], factorToGL[ blendDst ], factorToGL[ blendSrcAlpha ], factorToGL[ blendDstAlpha ] );
  14114. currentBlendSrc = blendSrc;
  14115. currentBlendDst = blendDst;
  14116. currentBlendSrcAlpha = blendSrcAlpha;
  14117. currentBlendDstAlpha = blendDstAlpha;
  14118. }
  14119. if ( blendColor.equals( currentBlendColor ) === false || blendAlpha !== currentBlendAlpha ) {
  14120. gl.blendColor( blendColor.r, blendColor.g, blendColor.b, blendAlpha );
  14121. currentBlendColor.copy( blendColor );
  14122. currentBlendAlpha = blendAlpha;
  14123. }
  14124. currentBlending = blending;
  14125. currentPremultipledAlpha = false;
  14126. }
  14127. function setMaterial( material, frontFaceCW ) {
  14128. material.side === DoubleSide
  14129. ? disable( gl.CULL_FACE )
  14130. : enable( gl.CULL_FACE );
  14131. let flipSided = ( material.side === BackSide );
  14132. if ( frontFaceCW ) flipSided = ! flipSided;
  14133. setFlipSided( flipSided );
  14134. ( material.blending === NormalBlending && material.transparent === false )
  14135. ? setBlending( NoBlending )
  14136. : setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.blendColor, material.blendAlpha, material.premultipliedAlpha );
  14137. depthBuffer.setFunc( material.depthFunc );
  14138. depthBuffer.setTest( material.depthTest );
  14139. depthBuffer.setMask( material.depthWrite );
  14140. colorBuffer.setMask( material.colorWrite );
  14141. const stencilWrite = material.stencilWrite;
  14142. stencilBuffer.setTest( stencilWrite );
  14143. if ( stencilWrite ) {
  14144. stencilBuffer.setMask( material.stencilWriteMask );
  14145. stencilBuffer.setFunc( material.stencilFunc, material.stencilRef, material.stencilFuncMask );
  14146. stencilBuffer.setOp( material.stencilFail, material.stencilZFail, material.stencilZPass );
  14147. }
  14148. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  14149. material.alphaToCoverage === true
  14150. ? enable( gl.SAMPLE_ALPHA_TO_COVERAGE )
  14151. : disable( gl.SAMPLE_ALPHA_TO_COVERAGE );
  14152. }
  14153. //
  14154. function setFlipSided( flipSided ) {
  14155. if ( currentFlipSided !== flipSided ) {
  14156. if ( flipSided ) {
  14157. gl.frontFace( gl.CW );
  14158. } else {
  14159. gl.frontFace( gl.CCW );
  14160. }
  14161. currentFlipSided = flipSided;
  14162. }
  14163. }
  14164. function setCullFace( cullFace ) {
  14165. if ( cullFace !== CullFaceNone ) {
  14166. enable( gl.CULL_FACE );
  14167. if ( cullFace !== currentCullFace ) {
  14168. if ( cullFace === CullFaceBack ) {
  14169. gl.cullFace( gl.BACK );
  14170. } else if ( cullFace === CullFaceFront ) {
  14171. gl.cullFace( gl.FRONT );
  14172. } else {
  14173. gl.cullFace( gl.FRONT_AND_BACK );
  14174. }
  14175. }
  14176. } else {
  14177. disable( gl.CULL_FACE );
  14178. }
  14179. currentCullFace = cullFace;
  14180. }
  14181. function setLineWidth( width ) {
  14182. if ( width !== currentLineWidth ) {
  14183. if ( lineWidthAvailable ) gl.lineWidth( width );
  14184. currentLineWidth = width;
  14185. }
  14186. }
  14187. function setPolygonOffset( polygonOffset, factor, units ) {
  14188. if ( polygonOffset ) {
  14189. enable( gl.POLYGON_OFFSET_FILL );
  14190. if ( currentPolygonOffsetFactor !== factor || currentPolygonOffsetUnits !== units ) {
  14191. gl.polygonOffset( factor, units );
  14192. currentPolygonOffsetFactor = factor;
  14193. currentPolygonOffsetUnits = units;
  14194. }
  14195. } else {
  14196. disable( gl.POLYGON_OFFSET_FILL );
  14197. }
  14198. }
  14199. function setScissorTest( scissorTest ) {
  14200. if ( scissorTest ) {
  14201. enable( gl.SCISSOR_TEST );
  14202. } else {
  14203. disable( gl.SCISSOR_TEST );
  14204. }
  14205. }
  14206. // texture
  14207. function activeTexture( webglSlot ) {
  14208. if ( webglSlot === undefined ) webglSlot = gl.TEXTURE0 + maxTextures - 1;
  14209. if ( currentTextureSlot !== webglSlot ) {
  14210. gl.activeTexture( webglSlot );
  14211. currentTextureSlot = webglSlot;
  14212. }
  14213. }
  14214. function bindTexture( webglType, webglTexture, webglSlot ) {
  14215. if ( webglSlot === undefined ) {
  14216. if ( currentTextureSlot === null ) {
  14217. webglSlot = gl.TEXTURE0 + maxTextures - 1;
  14218. } else {
  14219. webglSlot = currentTextureSlot;
  14220. }
  14221. }
  14222. let boundTexture = currentBoundTextures[ webglSlot ];
  14223. if ( boundTexture === undefined ) {
  14224. boundTexture = { type: undefined, texture: undefined };
  14225. currentBoundTextures[ webglSlot ] = boundTexture;
  14226. }
  14227. if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) {
  14228. if ( currentTextureSlot !== webglSlot ) {
  14229. gl.activeTexture( webglSlot );
  14230. currentTextureSlot = webglSlot;
  14231. }
  14232. gl.bindTexture( webglType, webglTexture || emptyTextures[ webglType ] );
  14233. boundTexture.type = webglType;
  14234. boundTexture.texture = webglTexture;
  14235. }
  14236. }
  14237. function unbindTexture() {
  14238. const boundTexture = currentBoundTextures[ currentTextureSlot ];
  14239. if ( boundTexture !== undefined && boundTexture.type !== undefined ) {
  14240. gl.bindTexture( boundTexture.type, null );
  14241. boundTexture.type = undefined;
  14242. boundTexture.texture = undefined;
  14243. }
  14244. }
  14245. function compressedTexImage2D() {
  14246. try {
  14247. gl.compressedTexImage2D.apply( gl, arguments );
  14248. } catch ( error ) {
  14249. console.error( 'THREE.WebGLState:', error );
  14250. }
  14251. }
  14252. function compressedTexImage3D() {
  14253. try {
  14254. gl.compressedTexImage3D.apply( gl, arguments );
  14255. } catch ( error ) {
  14256. console.error( 'THREE.WebGLState:', error );
  14257. }
  14258. }
  14259. function texSubImage2D() {
  14260. try {
  14261. gl.texSubImage2D.apply( gl, arguments );
  14262. } catch ( error ) {
  14263. console.error( 'THREE.WebGLState:', error );
  14264. }
  14265. }
  14266. function texSubImage3D() {
  14267. try {
  14268. gl.texSubImage3D.apply( gl, arguments );
  14269. } catch ( error ) {
  14270. console.error( 'THREE.WebGLState:', error );
  14271. }
  14272. }
  14273. function compressedTexSubImage2D() {
  14274. try {
  14275. gl.compressedTexSubImage2D.apply( gl, arguments );
  14276. } catch ( error ) {
  14277. console.error( 'THREE.WebGLState:', error );
  14278. }
  14279. }
  14280. function compressedTexSubImage3D() {
  14281. try {
  14282. gl.compressedTexSubImage3D.apply( gl, arguments );
  14283. } catch ( error ) {
  14284. console.error( 'THREE.WebGLState:', error );
  14285. }
  14286. }
  14287. function texStorage2D() {
  14288. try {
  14289. gl.texStorage2D.apply( gl, arguments );
  14290. } catch ( error ) {
  14291. console.error( 'THREE.WebGLState:', error );
  14292. }
  14293. }
  14294. function texStorage3D() {
  14295. try {
  14296. gl.texStorage3D.apply( gl, arguments );
  14297. } catch ( error ) {
  14298. console.error( 'THREE.WebGLState:', error );
  14299. }
  14300. }
  14301. function texImage2D() {
  14302. try {
  14303. gl.texImage2D.apply( gl, arguments );
  14304. } catch ( error ) {
  14305. console.error( 'THREE.WebGLState:', error );
  14306. }
  14307. }
  14308. function texImage3D() {
  14309. try {
  14310. gl.texImage3D.apply( gl, arguments );
  14311. } catch ( error ) {
  14312. console.error( 'THREE.WebGLState:', error );
  14313. }
  14314. }
  14315. //
  14316. function scissor( scissor ) {
  14317. if ( currentScissor.equals( scissor ) === false ) {
  14318. gl.scissor( scissor.x, scissor.y, scissor.z, scissor.w );
  14319. currentScissor.copy( scissor );
  14320. }
  14321. }
  14322. function viewport( viewport ) {
  14323. if ( currentViewport.equals( viewport ) === false ) {
  14324. gl.viewport( viewport.x, viewport.y, viewport.z, viewport.w );
  14325. currentViewport.copy( viewport );
  14326. }
  14327. }
  14328. function updateUBOMapping( uniformsGroup, program ) {
  14329. let mapping = uboProgramMap.get( program );
  14330. if ( mapping === undefined ) {
  14331. mapping = new WeakMap();
  14332. uboProgramMap.set( program, mapping );
  14333. }
  14334. let blockIndex = mapping.get( uniformsGroup );
  14335. if ( blockIndex === undefined ) {
  14336. blockIndex = gl.getUniformBlockIndex( program, uniformsGroup.name );
  14337. mapping.set( uniformsGroup, blockIndex );
  14338. }
  14339. }
  14340. function uniformBlockBinding( uniformsGroup, program ) {
  14341. const mapping = uboProgramMap.get( program );
  14342. const blockIndex = mapping.get( uniformsGroup );
  14343. if ( uboBindings.get( program ) !== blockIndex ) {
  14344. // bind shader specific block index to global block point
  14345. gl.uniformBlockBinding( program, blockIndex, uniformsGroup.__bindingPointIndex );
  14346. uboBindings.set( program, blockIndex );
  14347. }
  14348. }
  14349. //
  14350. function reset() {
  14351. // reset state
  14352. gl.disable( gl.BLEND );
  14353. gl.disable( gl.CULL_FACE );
  14354. gl.disable( gl.DEPTH_TEST );
  14355. gl.disable( gl.POLYGON_OFFSET_FILL );
  14356. gl.disable( gl.SCISSOR_TEST );
  14357. gl.disable( gl.STENCIL_TEST );
  14358. gl.disable( gl.SAMPLE_ALPHA_TO_COVERAGE );
  14359. gl.blendEquation( gl.FUNC_ADD );
  14360. gl.blendFunc( gl.ONE, gl.ZERO );
  14361. gl.blendFuncSeparate( gl.ONE, gl.ZERO, gl.ONE, gl.ZERO );
  14362. gl.blendColor( 0, 0, 0, 0 );
  14363. gl.colorMask( true, true, true, true );
  14364. gl.clearColor( 0, 0, 0, 0 );
  14365. gl.depthMask( true );
  14366. gl.depthFunc( gl.LESS );
  14367. gl.clearDepth( 1 );
  14368. gl.stencilMask( 0xffffffff );
  14369. gl.stencilFunc( gl.ALWAYS, 0, 0xffffffff );
  14370. gl.stencilOp( gl.KEEP, gl.KEEP, gl.KEEP );
  14371. gl.clearStencil( 0 );
  14372. gl.cullFace( gl.BACK );
  14373. gl.frontFace( gl.CCW );
  14374. gl.polygonOffset( 0, 0 );
  14375. gl.activeTexture( gl.TEXTURE0 );
  14376. gl.bindFramebuffer( gl.FRAMEBUFFER, null );
  14377. if ( isWebGL2 === true ) {
  14378. gl.bindFramebuffer( gl.DRAW_FRAMEBUFFER, null );
  14379. gl.bindFramebuffer( gl.READ_FRAMEBUFFER, null );
  14380. }
  14381. gl.useProgram( null );
  14382. gl.lineWidth( 1 );
  14383. gl.scissor( 0, 0, gl.canvas.width, gl.canvas.height );
  14384. gl.viewport( 0, 0, gl.canvas.width, gl.canvas.height );
  14385. // reset internals
  14386. enabledCapabilities = {};
  14387. currentTextureSlot = null;
  14388. currentBoundTextures = {};
  14389. currentBoundFramebuffers = {};
  14390. currentDrawbuffers = new WeakMap();
  14391. defaultDrawbuffers = [];
  14392. currentProgram = null;
  14393. currentBlendingEnabled = false;
  14394. currentBlending = null;
  14395. currentBlendEquation = null;
  14396. currentBlendSrc = null;
  14397. currentBlendDst = null;
  14398. currentBlendEquationAlpha = null;
  14399. currentBlendSrcAlpha = null;
  14400. currentBlendDstAlpha = null;
  14401. currentBlendColor = new Color( 0, 0, 0 );
  14402. currentBlendAlpha = 0;
  14403. currentPremultipledAlpha = false;
  14404. currentFlipSided = null;
  14405. currentCullFace = null;
  14406. currentLineWidth = null;
  14407. currentPolygonOffsetFactor = null;
  14408. currentPolygonOffsetUnits = null;
  14409. currentScissor.set( 0, 0, gl.canvas.width, gl.canvas.height );
  14410. currentViewport.set( 0, 0, gl.canvas.width, gl.canvas.height );
  14411. colorBuffer.reset();
  14412. depthBuffer.reset();
  14413. stencilBuffer.reset();
  14414. }
  14415. return {
  14416. buffers: {
  14417. color: colorBuffer,
  14418. depth: depthBuffer,
  14419. stencil: stencilBuffer
  14420. },
  14421. enable: enable,
  14422. disable: disable,
  14423. bindFramebuffer: bindFramebuffer,
  14424. drawBuffers: drawBuffers,
  14425. useProgram: useProgram,
  14426. setBlending: setBlending,
  14427. setMaterial: setMaterial,
  14428. setFlipSided: setFlipSided,
  14429. setCullFace: setCullFace,
  14430. setLineWidth: setLineWidth,
  14431. setPolygonOffset: setPolygonOffset,
  14432. setScissorTest: setScissorTest,
  14433. activeTexture: activeTexture,
  14434. bindTexture: bindTexture,
  14435. unbindTexture: unbindTexture,
  14436. compressedTexImage2D: compressedTexImage2D,
  14437. compressedTexImage3D: compressedTexImage3D,
  14438. texImage2D: texImage2D,
  14439. texImage3D: texImage3D,
  14440. updateUBOMapping: updateUBOMapping,
  14441. uniformBlockBinding: uniformBlockBinding,
  14442. texStorage2D: texStorage2D,
  14443. texStorage3D: texStorage3D,
  14444. texSubImage2D: texSubImage2D,
  14445. texSubImage3D: texSubImage3D,
  14446. compressedTexSubImage2D: compressedTexSubImage2D,
  14447. compressedTexSubImage3D: compressedTexSubImage3D,
  14448. scissor: scissor,
  14449. viewport: viewport,
  14450. reset: reset
  14451. };
  14452. }
  14453. function WebGLTextures( _gl, extensions, state, properties, capabilities, utils, info ) {
  14454. const isWebGL2 = capabilities.isWebGL2;
  14455. const multisampledRTTExt = extensions.has( 'WEBGL_multisampled_render_to_texture' ) ? extensions.get( 'WEBGL_multisampled_render_to_texture' ) : null;
  14456. const supportsInvalidateFramebuffer = typeof navigator === 'undefined' ? false : /OculusBrowser/g.test( navigator.userAgent );
  14457. const _videoTextures = new WeakMap();
  14458. let _canvas;
  14459. const _sources = new WeakMap(); // maps WebglTexture objects to instances of Source
  14460. // cordova iOS (as of 5.0) still uses UIWebView, which provides OffscreenCanvas,
  14461. // also OffscreenCanvas.getContext("webgl"), but not OffscreenCanvas.getContext("2d")!
  14462. // Some implementations may only implement OffscreenCanvas partially (e.g. lacking 2d).
  14463. let useOffscreenCanvas = false;
  14464. try {
  14465. useOffscreenCanvas = typeof OffscreenCanvas !== 'undefined'
  14466. // eslint-disable-next-line compat/compat
  14467. && ( new OffscreenCanvas( 1, 1 ).getContext( '2d' ) ) !== null;
  14468. } catch ( err ) {
  14469. // Ignore any errors
  14470. }
  14471. function createCanvas( width, height ) {
  14472. // Use OffscreenCanvas when available. Specially needed in web workers
  14473. return useOffscreenCanvas ?
  14474. // eslint-disable-next-line compat/compat
  14475. new OffscreenCanvas( width, height ) : createElementNS( 'canvas' );
  14476. }
  14477. function resizeImage( image, needsPowerOfTwo, needsNewCanvas, maxSize ) {
  14478. let scale = 1;
  14479. // handle case if texture exceeds max size
  14480. if ( image.width > maxSize || image.height > maxSize ) {
  14481. scale = maxSize / Math.max( image.width, image.height );
  14482. }
  14483. // only perform resize if necessary
  14484. if ( scale < 1 || needsPowerOfTwo === true ) {
  14485. // only perform resize for certain image types
  14486. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  14487. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  14488. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  14489. const floor = needsPowerOfTwo ? floorPowerOfTwo : Math.floor;
  14490. const width = floor( scale * image.width );
  14491. const height = floor( scale * image.height );
  14492. if ( _canvas === undefined ) _canvas = createCanvas( width, height );
  14493. // cube textures can't reuse the same canvas
  14494. const canvas = needsNewCanvas ? createCanvas( width, height ) : _canvas;
  14495. canvas.width = width;
  14496. canvas.height = height;
  14497. const context = canvas.getContext( '2d' );
  14498. context.drawImage( image, 0, 0, width, height );
  14499. console.warn( 'THREE.WebGLRenderer: Texture has been resized from (' + image.width + 'x' + image.height + ') to (' + width + 'x' + height + ').' );
  14500. return canvas;
  14501. } else {
  14502. if ( 'data' in image ) {
  14503. console.warn( 'THREE.WebGLRenderer: Image in DataTexture is too big (' + image.width + 'x' + image.height + ').' );
  14504. }
  14505. return image;
  14506. }
  14507. }
  14508. return image;
  14509. }
  14510. function isPowerOfTwo$1( image ) {
  14511. return isPowerOfTwo( image.width ) && isPowerOfTwo( image.height );
  14512. }
  14513. function textureNeedsPowerOfTwo( texture ) {
  14514. if ( isWebGL2 ) return false;
  14515. return ( texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping ) ||
  14516. ( texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter );
  14517. }
  14518. function textureNeedsGenerateMipmaps( texture, supportsMips ) {
  14519. return texture.generateMipmaps && supportsMips &&
  14520. texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter;
  14521. }
  14522. function generateMipmap( target ) {
  14523. _gl.generateMipmap( target );
  14524. }
  14525. function getInternalFormat( internalFormatName, glFormat, glType, colorSpace, forceLinearTransfer = false ) {
  14526. if ( isWebGL2 === false ) return glFormat;
  14527. if ( internalFormatName !== null ) {
  14528. if ( _gl[ internalFormatName ] !== undefined ) return _gl[ internalFormatName ];
  14529. console.warn( 'THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\'' );
  14530. }
  14531. let internalFormat = glFormat;
  14532. if ( glFormat === _gl.RED ) {
  14533. if ( glType === _gl.FLOAT ) internalFormat = _gl.R32F;
  14534. if ( glType === _gl.HALF_FLOAT ) internalFormat = _gl.R16F;
  14535. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.R8;
  14536. }
  14537. if ( glFormat === _gl.RED_INTEGER ) {
  14538. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.R8UI;
  14539. if ( glType === _gl.UNSIGNED_SHORT ) internalFormat = _gl.R16UI;
  14540. if ( glType === _gl.UNSIGNED_INT ) internalFormat = _gl.R32UI;
  14541. if ( glType === _gl.BYTE ) internalFormat = _gl.R8I;
  14542. if ( glType === _gl.SHORT ) internalFormat = _gl.R16I;
  14543. if ( glType === _gl.INT ) internalFormat = _gl.R32I;
  14544. }
  14545. if ( glFormat === _gl.RG ) {
  14546. if ( glType === _gl.FLOAT ) internalFormat = _gl.RG32F;
  14547. if ( glType === _gl.HALF_FLOAT ) internalFormat = _gl.RG16F;
  14548. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.RG8;
  14549. }
  14550. if ( glFormat === _gl.RG_INTEGER ) {
  14551. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.RG8UI;
  14552. if ( glType === _gl.UNSIGNED_SHORT ) internalFormat = _gl.RG16UI;
  14553. if ( glType === _gl.UNSIGNED_INT ) internalFormat = _gl.RG32UI;
  14554. if ( glType === _gl.BYTE ) internalFormat = _gl.RG8I;
  14555. if ( glType === _gl.SHORT ) internalFormat = _gl.RG16I;
  14556. if ( glType === _gl.INT ) internalFormat = _gl.RG32I;
  14557. }
  14558. if ( glFormat === _gl.RGBA ) {
  14559. const transfer = forceLinearTransfer ? LinearTransfer : ColorManagement.getTransfer( colorSpace );
  14560. if ( glType === _gl.FLOAT ) internalFormat = _gl.RGBA32F;
  14561. if ( glType === _gl.HALF_FLOAT ) internalFormat = _gl.RGBA16F;
  14562. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = ( transfer === SRGBTransfer ) ? _gl.SRGB8_ALPHA8 : _gl.RGBA8;
  14563. if ( glType === _gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = _gl.RGBA4;
  14564. if ( glType === _gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = _gl.RGB5_A1;
  14565. }
  14566. if ( internalFormat === _gl.R16F || internalFormat === _gl.R32F ||
  14567. internalFormat === _gl.RG16F || internalFormat === _gl.RG32F ||
  14568. internalFormat === _gl.RGBA16F || internalFormat === _gl.RGBA32F ) {
  14569. extensions.get( 'EXT_color_buffer_float' );
  14570. }
  14571. return internalFormat;
  14572. }
  14573. function getMipLevels( texture, image, supportsMips ) {
  14574. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) === true || ( texture.isFramebufferTexture && texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter ) ) {
  14575. return Math.log2( Math.max( image.width, image.height ) ) + 1;
  14576. } else if ( texture.mipmaps !== undefined && texture.mipmaps.length > 0 ) {
  14577. // user-defined mipmaps
  14578. return texture.mipmaps.length;
  14579. } else if ( texture.isCompressedTexture && Array.isArray( texture.image ) ) {
  14580. return image.mipmaps.length;
  14581. } else {
  14582. // texture without mipmaps (only base level)
  14583. return 1;
  14584. }
  14585. }
  14586. // Fallback filters for non-power-of-2 textures
  14587. function filterFallback( f ) {
  14588. if ( f === NearestFilter || f === NearestMipmapNearestFilter || f === NearestMipmapLinearFilter ) {
  14589. return _gl.NEAREST;
  14590. }
  14591. return _gl.LINEAR;
  14592. }
  14593. //
  14594. function onTextureDispose( event ) {
  14595. const texture = event.target;
  14596. texture.removeEventListener( 'dispose', onTextureDispose );
  14597. deallocateTexture( texture );
  14598. if ( texture.isVideoTexture ) {
  14599. _videoTextures.delete( texture );
  14600. }
  14601. }
  14602. function onRenderTargetDispose( event ) {
  14603. const renderTarget = event.target;
  14604. renderTarget.removeEventListener( 'dispose', onRenderTargetDispose );
  14605. deallocateRenderTarget( renderTarget );
  14606. }
  14607. //
  14608. function deallocateTexture( texture ) {
  14609. const textureProperties = properties.get( texture );
  14610. if ( textureProperties.__webglInit === undefined ) return;
  14611. // check if it's necessary to remove the WebGLTexture object
  14612. const source = texture.source;
  14613. const webglTextures = _sources.get( source );
  14614. if ( webglTextures ) {
  14615. const webglTexture = webglTextures[ textureProperties.__cacheKey ];
  14616. webglTexture.usedTimes --;
  14617. // the WebGLTexture object is not used anymore, remove it
  14618. if ( webglTexture.usedTimes === 0 ) {
  14619. deleteTexture( texture );
  14620. }
  14621. // remove the weak map entry if no WebGLTexture uses the source anymore
  14622. if ( Object.keys( webglTextures ).length === 0 ) {
  14623. _sources.delete( source );
  14624. }
  14625. }
  14626. properties.remove( texture );
  14627. }
  14628. function deleteTexture( texture ) {
  14629. const textureProperties = properties.get( texture );
  14630. _gl.deleteTexture( textureProperties.__webglTexture );
  14631. const source = texture.source;
  14632. const webglTextures = _sources.get( source );
  14633. delete webglTextures[ textureProperties.__cacheKey ];
  14634. info.memory.textures --;
  14635. }
  14636. function deallocateRenderTarget( renderTarget ) {
  14637. const renderTargetProperties = properties.get( renderTarget );
  14638. if ( renderTarget.depthTexture ) {
  14639. renderTarget.depthTexture.dispose();
  14640. }
  14641. if ( renderTarget.isWebGLCubeRenderTarget ) {
  14642. for ( let i = 0; i < 6; i ++ ) {
  14643. if ( Array.isArray( renderTargetProperties.__webglFramebuffer[ i ] ) ) {
  14644. for ( let level = 0; level < renderTargetProperties.__webglFramebuffer[ i ].length; level ++ ) _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ i ][ level ] );
  14645. } else {
  14646. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ i ] );
  14647. }
  14648. if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer[ i ] );
  14649. }
  14650. } else {
  14651. if ( Array.isArray( renderTargetProperties.__webglFramebuffer ) ) {
  14652. for ( let level = 0; level < renderTargetProperties.__webglFramebuffer.length; level ++ ) _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ level ] );
  14653. } else {
  14654. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer );
  14655. }
  14656. if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer );
  14657. if ( renderTargetProperties.__webglMultisampledFramebuffer ) _gl.deleteFramebuffer( renderTargetProperties.__webglMultisampledFramebuffer );
  14658. if ( renderTargetProperties.__webglColorRenderbuffer ) {
  14659. for ( let i = 0; i < renderTargetProperties.__webglColorRenderbuffer.length; i ++ ) {
  14660. if ( renderTargetProperties.__webglColorRenderbuffer[ i ] ) _gl.deleteRenderbuffer( renderTargetProperties.__webglColorRenderbuffer[ i ] );
  14661. }
  14662. }
  14663. if ( renderTargetProperties.__webglDepthRenderbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthRenderbuffer );
  14664. }
  14665. const textures = renderTarget.textures;
  14666. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  14667. const attachmentProperties = properties.get( textures[ i ] );
  14668. if ( attachmentProperties.__webglTexture ) {
  14669. _gl.deleteTexture( attachmentProperties.__webglTexture );
  14670. info.memory.textures --;
  14671. }
  14672. properties.remove( textures[ i ] );
  14673. }
  14674. properties.remove( renderTarget );
  14675. }
  14676. //
  14677. let textureUnits = 0;
  14678. function resetTextureUnits() {
  14679. textureUnits = 0;
  14680. }
  14681. function allocateTextureUnit() {
  14682. const textureUnit = textureUnits;
  14683. if ( textureUnit >= capabilities.maxTextures ) {
  14684. console.warn( 'THREE.WebGLTextures: Trying to use ' + textureUnit + ' texture units while this GPU supports only ' + capabilities.maxTextures );
  14685. }
  14686. textureUnits += 1;
  14687. return textureUnit;
  14688. }
  14689. function getTextureCacheKey( texture ) {
  14690. const array = [];
  14691. array.push( texture.wrapS );
  14692. array.push( texture.wrapT );
  14693. array.push( texture.wrapR || 0 );
  14694. array.push( texture.magFilter );
  14695. array.push( texture.minFilter );
  14696. array.push( texture.anisotropy );
  14697. array.push( texture.internalFormat );
  14698. array.push( texture.format );
  14699. array.push( texture.type );
  14700. array.push( texture.generateMipmaps );
  14701. array.push( texture.premultiplyAlpha );
  14702. array.push( texture.flipY );
  14703. array.push( texture.unpackAlignment );
  14704. array.push( texture.colorSpace );
  14705. return array.join();
  14706. }
  14707. //
  14708. function setTexture2D( texture, slot ) {
  14709. const textureProperties = properties.get( texture );
  14710. if ( texture.isVideoTexture ) updateVideoTexture( texture );
  14711. if ( texture.isRenderTargetTexture === false && texture.version > 0 && textureProperties.__version !== texture.version ) {
  14712. const image = texture.image;
  14713. if ( image === null ) {
  14714. console.warn( 'THREE.WebGLRenderer: Texture marked for update but no image data found.' );
  14715. } else if ( image.complete === false ) {
  14716. console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is incomplete' );
  14717. } else {
  14718. uploadTexture( textureProperties, texture, slot );
  14719. return;
  14720. }
  14721. }
  14722. state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  14723. }
  14724. function setTexture2DArray( texture, slot ) {
  14725. const textureProperties = properties.get( texture );
  14726. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  14727. uploadTexture( textureProperties, texture, slot );
  14728. return;
  14729. }
  14730. state.bindTexture( _gl.TEXTURE_2D_ARRAY, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  14731. }
  14732. function setTexture3D( texture, slot ) {
  14733. const textureProperties = properties.get( texture );
  14734. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  14735. uploadTexture( textureProperties, texture, slot );
  14736. return;
  14737. }
  14738. state.bindTexture( _gl.TEXTURE_3D, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  14739. }
  14740. function setTextureCube( texture, slot ) {
  14741. const textureProperties = properties.get( texture );
  14742. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  14743. uploadCubeTexture( textureProperties, texture, slot );
  14744. return;
  14745. }
  14746. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  14747. }
  14748. const wrappingToGL = {
  14749. [ RepeatWrapping ]: _gl.REPEAT,
  14750. [ ClampToEdgeWrapping ]: _gl.CLAMP_TO_EDGE,
  14751. [ MirroredRepeatWrapping ]: _gl.MIRRORED_REPEAT
  14752. };
  14753. const filterToGL = {
  14754. [ NearestFilter ]: _gl.NEAREST,
  14755. [ NearestMipmapNearestFilter ]: _gl.NEAREST_MIPMAP_NEAREST,
  14756. [ NearestMipmapLinearFilter ]: _gl.NEAREST_MIPMAP_LINEAR,
  14757. [ LinearFilter ]: _gl.LINEAR,
  14758. [ LinearMipmapNearestFilter ]: _gl.LINEAR_MIPMAP_NEAREST,
  14759. [ LinearMipmapLinearFilter ]: _gl.LINEAR_MIPMAP_LINEAR
  14760. };
  14761. const compareToGL = {
  14762. [ NeverCompare ]: _gl.NEVER,
  14763. [ AlwaysCompare ]: _gl.ALWAYS,
  14764. [ LessCompare ]: _gl.LESS,
  14765. [ LessEqualCompare ]: _gl.LEQUAL,
  14766. [ EqualCompare ]: _gl.EQUAL,
  14767. [ GreaterEqualCompare ]: _gl.GEQUAL,
  14768. [ GreaterCompare ]: _gl.GREATER,
  14769. [ NotEqualCompare ]: _gl.NOTEQUAL
  14770. };
  14771. function setTextureParameters( textureType, texture, supportsMips ) {
  14772. if ( texture.type === FloatType && extensions.has( 'OES_texture_float_linear' ) === false &&
  14773. ( texture.magFilter === LinearFilter || texture.magFilter === LinearMipmapNearestFilter || texture.magFilter === NearestMipmapLinearFilter || texture.magFilter === LinearMipmapLinearFilter ||
  14774. texture.minFilter === LinearFilter || texture.minFilter === LinearMipmapNearestFilter || texture.minFilter === NearestMipmapLinearFilter || texture.minFilter === LinearMipmapLinearFilter ) ) {
  14775. console.warn( 'THREE.WebGLRenderer: Unable to use linear filtering with floating point textures. OES_texture_float_linear not supported on this device.' );
  14776. }
  14777. if ( supportsMips ) {
  14778. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, wrappingToGL[ texture.wrapS ] );
  14779. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, wrappingToGL[ texture.wrapT ] );
  14780. if ( textureType === _gl.TEXTURE_3D || textureType === _gl.TEXTURE_2D_ARRAY ) {
  14781. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_R, wrappingToGL[ texture.wrapR ] );
  14782. }
  14783. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterToGL[ texture.magFilter ] );
  14784. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterToGL[ texture.minFilter ] );
  14785. } else {
  14786. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  14787. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  14788. if ( textureType === _gl.TEXTURE_3D || textureType === _gl.TEXTURE_2D_ARRAY ) {
  14789. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_R, _gl.CLAMP_TO_EDGE );
  14790. }
  14791. if ( texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping ) {
  14792. console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping.' );
  14793. }
  14794. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterFallback( texture.magFilter ) );
  14795. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterFallback( texture.minFilter ) );
  14796. if ( texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter ) {
  14797. console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.' );
  14798. }
  14799. }
  14800. if ( texture.compareFunction ) {
  14801. _gl.texParameteri( textureType, _gl.TEXTURE_COMPARE_MODE, _gl.COMPARE_REF_TO_TEXTURE );
  14802. _gl.texParameteri( textureType, _gl.TEXTURE_COMPARE_FUNC, compareToGL[ texture.compareFunction ] );
  14803. }
  14804. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  14805. if ( texture.magFilter === NearestFilter ) return;
  14806. if ( texture.minFilter !== NearestMipmapLinearFilter && texture.minFilter !== LinearMipmapLinearFilter ) return;
  14807. if ( texture.type === FloatType && extensions.has( 'OES_texture_float_linear' ) === false ) return; // verify extension for WebGL 1 and WebGL 2
  14808. if ( isWebGL2 === false && ( texture.type === HalfFloatType && extensions.has( 'OES_texture_half_float_linear' ) === false ) ) return; // verify extension for WebGL 1 only
  14809. if ( texture.anisotropy > 1 || properties.get( texture ).__currentAnisotropy ) {
  14810. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  14811. _gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, capabilities.getMaxAnisotropy() ) );
  14812. properties.get( texture ).__currentAnisotropy = texture.anisotropy;
  14813. }
  14814. }
  14815. }
  14816. function initTexture( textureProperties, texture ) {
  14817. let forceUpload = false;
  14818. if ( textureProperties.__webglInit === undefined ) {
  14819. textureProperties.__webglInit = true;
  14820. texture.addEventListener( 'dispose', onTextureDispose );
  14821. }
  14822. // create Source <-> WebGLTextures mapping if necessary
  14823. const source = texture.source;
  14824. let webglTextures = _sources.get( source );
  14825. if ( webglTextures === undefined ) {
  14826. webglTextures = {};
  14827. _sources.set( source, webglTextures );
  14828. }
  14829. // check if there is already a WebGLTexture object for the given texture parameters
  14830. const textureCacheKey = getTextureCacheKey( texture );
  14831. if ( textureCacheKey !== textureProperties.__cacheKey ) {
  14832. // if not, create a new instance of WebGLTexture
  14833. if ( webglTextures[ textureCacheKey ] === undefined ) {
  14834. // create new entry
  14835. webglTextures[ textureCacheKey ] = {
  14836. texture: _gl.createTexture(),
  14837. usedTimes: 0
  14838. };
  14839. info.memory.textures ++;
  14840. // when a new instance of WebGLTexture was created, a texture upload is required
  14841. // even if the image contents are identical
  14842. forceUpload = true;
  14843. }
  14844. webglTextures[ textureCacheKey ].usedTimes ++;
  14845. // every time the texture cache key changes, it's necessary to check if an instance of
  14846. // WebGLTexture can be deleted in order to avoid a memory leak.
  14847. const webglTexture = webglTextures[ textureProperties.__cacheKey ];
  14848. if ( webglTexture !== undefined ) {
  14849. webglTextures[ textureProperties.__cacheKey ].usedTimes --;
  14850. if ( webglTexture.usedTimes === 0 ) {
  14851. deleteTexture( texture );
  14852. }
  14853. }
  14854. // store references to cache key and WebGLTexture object
  14855. textureProperties.__cacheKey = textureCacheKey;
  14856. textureProperties.__webglTexture = webglTextures[ textureCacheKey ].texture;
  14857. }
  14858. return forceUpload;
  14859. }
  14860. function uploadTexture( textureProperties, texture, slot ) {
  14861. let textureType = _gl.TEXTURE_2D;
  14862. if ( texture.isDataArrayTexture || texture.isCompressedArrayTexture ) textureType = _gl.TEXTURE_2D_ARRAY;
  14863. if ( texture.isData3DTexture ) textureType = _gl.TEXTURE_3D;
  14864. const forceUpload = initTexture( textureProperties, texture );
  14865. const source = texture.source;
  14866. state.bindTexture( textureType, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  14867. const sourceProperties = properties.get( source );
  14868. if ( source.version !== sourceProperties.__version || forceUpload === true ) {
  14869. state.activeTexture( _gl.TEXTURE0 + slot );
  14870. const workingPrimaries = ColorManagement.getPrimaries( ColorManagement.workingColorSpace );
  14871. const texturePrimaries = texture.colorSpace === NoColorSpace ? null : ColorManagement.getPrimaries( texture.colorSpace );
  14872. const unpackConversion = texture.colorSpace === NoColorSpace || workingPrimaries === texturePrimaries ? _gl.NONE : _gl.BROWSER_DEFAULT_WEBGL;
  14873. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  14874. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  14875. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  14876. _gl.pixelStorei( _gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, unpackConversion );
  14877. const needsPowerOfTwo = textureNeedsPowerOfTwo( texture ) && isPowerOfTwo$1( texture.image ) === false;
  14878. let image = resizeImage( texture.image, needsPowerOfTwo, false, capabilities.maxTextureSize );
  14879. image = verifyColorSpace( texture, image );
  14880. const supportsMips = isPowerOfTwo$1( image ) || isWebGL2,
  14881. glFormat = utils.convert( texture.format, texture.colorSpace );
  14882. let glType = utils.convert( texture.type ),
  14883. glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace, texture.isVideoTexture );
  14884. setTextureParameters( textureType, texture, supportsMips );
  14885. let mipmap;
  14886. const mipmaps = texture.mipmaps;
  14887. const useTexStorage = ( isWebGL2 && texture.isVideoTexture !== true && glInternalFormat !== RGB_ETC1_Format );
  14888. const allocateMemory = ( sourceProperties.__version === undefined ) || ( forceUpload === true );
  14889. const dataReady = source.dataReady;
  14890. const levels = getMipLevels( texture, image, supportsMips );
  14891. if ( texture.isDepthTexture ) {
  14892. // populate depth texture with dummy data
  14893. glInternalFormat = _gl.DEPTH_COMPONENT;
  14894. if ( isWebGL2 ) {
  14895. if ( texture.type === FloatType ) {
  14896. glInternalFormat = _gl.DEPTH_COMPONENT32F;
  14897. } else if ( texture.type === UnsignedIntType ) {
  14898. glInternalFormat = _gl.DEPTH_COMPONENT24;
  14899. } else if ( texture.type === UnsignedInt248Type ) {
  14900. glInternalFormat = _gl.DEPTH24_STENCIL8;
  14901. } else {
  14902. glInternalFormat = _gl.DEPTH_COMPONENT16; // WebGL2 requires sized internalformat for glTexImage2D
  14903. }
  14904. } else {
  14905. if ( texture.type === FloatType ) {
  14906. console.error( 'WebGLRenderer: Floating point depth texture requires WebGL2.' );
  14907. }
  14908. }
  14909. // validation checks for WebGL 1
  14910. if ( texture.format === DepthFormat && glInternalFormat === _gl.DEPTH_COMPONENT ) {
  14911. // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  14912. // DEPTH_COMPONENT and type is not UNSIGNED_SHORT or UNSIGNED_INT
  14913. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  14914. if ( texture.type !== UnsignedShortType && texture.type !== UnsignedIntType ) {
  14915. console.warn( 'THREE.WebGLRenderer: Use UnsignedShortType or UnsignedIntType for DepthFormat DepthTexture.' );
  14916. texture.type = UnsignedIntType;
  14917. glType = utils.convert( texture.type );
  14918. }
  14919. }
  14920. if ( texture.format === DepthStencilFormat && glInternalFormat === _gl.DEPTH_COMPONENT ) {
  14921. // Depth stencil textures need the DEPTH_STENCIL internal format
  14922. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  14923. glInternalFormat = _gl.DEPTH_STENCIL;
  14924. // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  14925. // DEPTH_STENCIL and type is not UNSIGNED_INT_24_8_WEBGL.
  14926. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  14927. if ( texture.type !== UnsignedInt248Type ) {
  14928. console.warn( 'THREE.WebGLRenderer: Use UnsignedInt248Type for DepthStencilFormat DepthTexture.' );
  14929. texture.type = UnsignedInt248Type;
  14930. glType = utils.convert( texture.type );
  14931. }
  14932. }
  14933. //
  14934. if ( allocateMemory ) {
  14935. if ( useTexStorage ) {
  14936. state.texStorage2D( _gl.TEXTURE_2D, 1, glInternalFormat, image.width, image.height );
  14937. } else {
  14938. state.texImage2D( _gl.TEXTURE_2D, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, null );
  14939. }
  14940. }
  14941. } else if ( texture.isDataTexture ) {
  14942. // use manually created mipmaps if available
  14943. // if there are no manual mipmaps
  14944. // set 0 level mipmap and then use GL to generate other mipmap levels
  14945. if ( mipmaps.length > 0 && supportsMips ) {
  14946. if ( useTexStorage && allocateMemory ) {
  14947. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, mipmaps[ 0 ].width, mipmaps[ 0 ].height );
  14948. }
  14949. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  14950. mipmap = mipmaps[ i ];
  14951. if ( useTexStorage ) {
  14952. if ( dataReady ) {
  14953. state.texSubImage2D( _gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data );
  14954. }
  14955. } else {
  14956. state.texImage2D( _gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  14957. }
  14958. }
  14959. texture.generateMipmaps = false;
  14960. } else {
  14961. if ( useTexStorage ) {
  14962. if ( allocateMemory ) {
  14963. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, image.width, image.height );
  14964. }
  14965. if ( dataReady ) {
  14966. state.texSubImage2D( _gl.TEXTURE_2D, 0, 0, 0, image.width, image.height, glFormat, glType, image.data );
  14967. }
  14968. } else {
  14969. state.texImage2D( _gl.TEXTURE_2D, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, image.data );
  14970. }
  14971. }
  14972. } else if ( texture.isCompressedTexture ) {
  14973. if ( texture.isCompressedArrayTexture ) {
  14974. if ( useTexStorage && allocateMemory ) {
  14975. state.texStorage3D( _gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, mipmaps[ 0 ].width, mipmaps[ 0 ].height, image.depth );
  14976. }
  14977. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  14978. mipmap = mipmaps[ i ];
  14979. if ( texture.format !== RGBAFormat ) {
  14980. if ( glFormat !== null ) {
  14981. if ( useTexStorage ) {
  14982. if ( dataReady ) {
  14983. state.compressedTexSubImage3D( _gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, mipmap.data, 0, 0 );
  14984. }
  14985. } else {
  14986. state.compressedTexImage3D( _gl.TEXTURE_2D_ARRAY, i, glInternalFormat, mipmap.width, mipmap.height, image.depth, 0, mipmap.data, 0, 0 );
  14987. }
  14988. } else {
  14989. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' );
  14990. }
  14991. } else {
  14992. if ( useTexStorage ) {
  14993. if ( dataReady ) {
  14994. state.texSubImage3D( _gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, glType, mipmap.data );
  14995. }
  14996. } else {
  14997. state.texImage3D( _gl.TEXTURE_2D_ARRAY, i, glInternalFormat, mipmap.width, mipmap.height, image.depth, 0, glFormat, glType, mipmap.data );
  14998. }
  14999. }
  15000. }
  15001. } else {
  15002. if ( useTexStorage && allocateMemory ) {
  15003. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, mipmaps[ 0 ].width, mipmaps[ 0 ].height );
  15004. }
  15005. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  15006. mipmap = mipmaps[ i ];
  15007. if ( texture.format !== RGBAFormat ) {
  15008. if ( glFormat !== null ) {
  15009. if ( useTexStorage ) {
  15010. if ( dataReady ) {
  15011. state.compressedTexSubImage2D( _gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data );
  15012. }
  15013. } else {
  15014. state.compressedTexImage2D( _gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  15015. }
  15016. } else {
  15017. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' );
  15018. }
  15019. } else {
  15020. if ( useTexStorage ) {
  15021. if ( dataReady ) {
  15022. state.texSubImage2D( _gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data );
  15023. }
  15024. } else {
  15025. state.texImage2D( _gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  15026. }
  15027. }
  15028. }
  15029. }
  15030. } else if ( texture.isDataArrayTexture ) {
  15031. if ( useTexStorage ) {
  15032. if ( allocateMemory ) {
  15033. state.texStorage3D( _gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, image.width, image.height, image.depth );
  15034. }
  15035. if ( dataReady ) {
  15036. state.texSubImage3D( _gl.TEXTURE_2D_ARRAY, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  15037. }
  15038. } else {
  15039. state.texImage3D( _gl.TEXTURE_2D_ARRAY, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data );
  15040. }
  15041. } else if ( texture.isData3DTexture ) {
  15042. if ( useTexStorage ) {
  15043. if ( allocateMemory ) {
  15044. state.texStorage3D( _gl.TEXTURE_3D, levels, glInternalFormat, image.width, image.height, image.depth );
  15045. }
  15046. if ( dataReady ) {
  15047. state.texSubImage3D( _gl.TEXTURE_3D, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  15048. }
  15049. } else {
  15050. state.texImage3D( _gl.TEXTURE_3D, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data );
  15051. }
  15052. } else if ( texture.isFramebufferTexture ) {
  15053. if ( allocateMemory ) {
  15054. if ( useTexStorage ) {
  15055. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, image.width, image.height );
  15056. } else {
  15057. let width = image.width, height = image.height;
  15058. for ( let i = 0; i < levels; i ++ ) {
  15059. state.texImage2D( _gl.TEXTURE_2D, i, glInternalFormat, width, height, 0, glFormat, glType, null );
  15060. width >>= 1;
  15061. height >>= 1;
  15062. }
  15063. }
  15064. }
  15065. } else {
  15066. // regular Texture (image, video, canvas)
  15067. // use manually created mipmaps if available
  15068. // if there are no manual mipmaps
  15069. // set 0 level mipmap and then use GL to generate other mipmap levels
  15070. if ( mipmaps.length > 0 && supportsMips ) {
  15071. if ( useTexStorage && allocateMemory ) {
  15072. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, mipmaps[ 0 ].width, mipmaps[ 0 ].height );
  15073. }
  15074. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  15075. mipmap = mipmaps[ i ];
  15076. if ( useTexStorage ) {
  15077. if ( dataReady ) {
  15078. state.texSubImage2D( _gl.TEXTURE_2D, i, 0, 0, glFormat, glType, mipmap );
  15079. }
  15080. } else {
  15081. state.texImage2D( _gl.TEXTURE_2D, i, glInternalFormat, glFormat, glType, mipmap );
  15082. }
  15083. }
  15084. texture.generateMipmaps = false;
  15085. } else {
  15086. if ( useTexStorage ) {
  15087. if ( allocateMemory ) {
  15088. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, image.width, image.height );
  15089. }
  15090. if ( dataReady ) {
  15091. state.texSubImage2D( _gl.TEXTURE_2D, 0, 0, 0, glFormat, glType, image );
  15092. }
  15093. } else {
  15094. state.texImage2D( _gl.TEXTURE_2D, 0, glInternalFormat, glFormat, glType, image );
  15095. }
  15096. }
  15097. }
  15098. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {
  15099. generateMipmap( textureType );
  15100. }
  15101. sourceProperties.__version = source.version;
  15102. if ( texture.onUpdate ) texture.onUpdate( texture );
  15103. }
  15104. textureProperties.__version = texture.version;
  15105. }
  15106. function uploadCubeTexture( textureProperties, texture, slot ) {
  15107. if ( texture.image.length !== 6 ) return;
  15108. const forceUpload = initTexture( textureProperties, texture );
  15109. const source = texture.source;
  15110. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  15111. const sourceProperties = properties.get( source );
  15112. if ( source.version !== sourceProperties.__version || forceUpload === true ) {
  15113. state.activeTexture( _gl.TEXTURE0 + slot );
  15114. const workingPrimaries = ColorManagement.getPrimaries( ColorManagement.workingColorSpace );
  15115. const texturePrimaries = texture.colorSpace === NoColorSpace ? null : ColorManagement.getPrimaries( texture.colorSpace );
  15116. const unpackConversion = texture.colorSpace === NoColorSpace || workingPrimaries === texturePrimaries ? _gl.NONE : _gl.BROWSER_DEFAULT_WEBGL;
  15117. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  15118. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  15119. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  15120. _gl.pixelStorei( _gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, unpackConversion );
  15121. const isCompressed = ( texture.isCompressedTexture || texture.image[ 0 ].isCompressedTexture );
  15122. const isDataTexture = ( texture.image[ 0 ] && texture.image[ 0 ].isDataTexture );
  15123. const cubeImage = [];
  15124. for ( let i = 0; i < 6; i ++ ) {
  15125. if ( ! isCompressed && ! isDataTexture ) {
  15126. cubeImage[ i ] = resizeImage( texture.image[ i ], false, true, capabilities.maxCubemapSize );
  15127. } else {
  15128. cubeImage[ i ] = isDataTexture ? texture.image[ i ].image : texture.image[ i ];
  15129. }
  15130. cubeImage[ i ] = verifyColorSpace( texture, cubeImage[ i ] );
  15131. }
  15132. const image = cubeImage[ 0 ],
  15133. supportsMips = isPowerOfTwo$1( image ) || isWebGL2,
  15134. glFormat = utils.convert( texture.format, texture.colorSpace ),
  15135. glType = utils.convert( texture.type ),
  15136. glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace );
  15137. const useTexStorage = ( isWebGL2 && texture.isVideoTexture !== true );
  15138. const allocateMemory = ( sourceProperties.__version === undefined ) || ( forceUpload === true );
  15139. const dataReady = source.dataReady;
  15140. let levels = getMipLevels( texture, image, supportsMips );
  15141. setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture, supportsMips );
  15142. let mipmaps;
  15143. if ( isCompressed ) {
  15144. if ( useTexStorage && allocateMemory ) {
  15145. state.texStorage2D( _gl.TEXTURE_CUBE_MAP, levels, glInternalFormat, image.width, image.height );
  15146. }
  15147. for ( let i = 0; i < 6; i ++ ) {
  15148. mipmaps = cubeImage[ i ].mipmaps;
  15149. for ( let j = 0; j < mipmaps.length; j ++ ) {
  15150. const mipmap = mipmaps[ j ];
  15151. if ( texture.format !== RGBAFormat ) {
  15152. if ( glFormat !== null ) {
  15153. if ( useTexStorage ) {
  15154. if ( dataReady ) {
  15155. state.compressedTexSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data );
  15156. }
  15157. } else {
  15158. state.compressedTexImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  15159. }
  15160. } else {
  15161. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()' );
  15162. }
  15163. } else {
  15164. if ( useTexStorage ) {
  15165. if ( dataReady ) {
  15166. state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data );
  15167. }
  15168. } else {
  15169. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  15170. }
  15171. }
  15172. }
  15173. }
  15174. } else {
  15175. mipmaps = texture.mipmaps;
  15176. if ( useTexStorage && allocateMemory ) {
  15177. // TODO: Uniformly handle mipmap definitions
  15178. // Normal textures and compressed cube textures define base level + mips with their mipmap array
  15179. // Uncompressed cube textures use their mipmap array only for mips (no base level)
  15180. if ( mipmaps.length > 0 ) levels ++;
  15181. state.texStorage2D( _gl.TEXTURE_CUBE_MAP, levels, glInternalFormat, cubeImage[ 0 ].width, cubeImage[ 0 ].height );
  15182. }
  15183. for ( let i = 0; i < 6; i ++ ) {
  15184. if ( isDataTexture ) {
  15185. if ( useTexStorage ) {
  15186. if ( dataReady ) {
  15187. state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, cubeImage[ i ].width, cubeImage[ i ].height, glFormat, glType, cubeImage[ i ].data );
  15188. }
  15189. } else {
  15190. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glInternalFormat, cubeImage[ i ].width, cubeImage[ i ].height, 0, glFormat, glType, cubeImage[ i ].data );
  15191. }
  15192. for ( let j = 0; j < mipmaps.length; j ++ ) {
  15193. const mipmap = mipmaps[ j ];
  15194. const mipmapImage = mipmap.image[ i ].image;
  15195. if ( useTexStorage ) {
  15196. if ( dataReady ) {
  15197. state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, 0, 0, mipmapImage.width, mipmapImage.height, glFormat, glType, mipmapImage.data );
  15198. }
  15199. } else {
  15200. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, glInternalFormat, mipmapImage.width, mipmapImage.height, 0, glFormat, glType, mipmapImage.data );
  15201. }
  15202. }
  15203. } else {
  15204. if ( useTexStorage ) {
  15205. if ( dataReady ) {
  15206. state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, glFormat, glType, cubeImage[ i ] );
  15207. }
  15208. } else {
  15209. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glInternalFormat, glFormat, glType, cubeImage[ i ] );
  15210. }
  15211. for ( let j = 0; j < mipmaps.length; j ++ ) {
  15212. const mipmap = mipmaps[ j ];
  15213. if ( useTexStorage ) {
  15214. if ( dataReady ) {
  15215. state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, 0, 0, glFormat, glType, mipmap.image[ i ] );
  15216. }
  15217. } else {
  15218. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, glInternalFormat, glFormat, glType, mipmap.image[ i ] );
  15219. }
  15220. }
  15221. }
  15222. }
  15223. }
  15224. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {
  15225. // We assume images for cube map have the same size.
  15226. generateMipmap( _gl.TEXTURE_CUBE_MAP );
  15227. }
  15228. sourceProperties.__version = source.version;
  15229. if ( texture.onUpdate ) texture.onUpdate( texture );
  15230. }
  15231. textureProperties.__version = texture.version;
  15232. }
  15233. // Render targets
  15234. // Setup storage for target texture and bind it to correct framebuffer
  15235. function setupFrameBufferTexture( framebuffer, renderTarget, texture, attachment, textureTarget, level ) {
  15236. const glFormat = utils.convert( texture.format, texture.colorSpace );
  15237. const glType = utils.convert( texture.type );
  15238. const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace );
  15239. const renderTargetProperties = properties.get( renderTarget );
  15240. if ( ! renderTargetProperties.__hasExternalTextures ) {
  15241. const width = Math.max( 1, renderTarget.width >> level );
  15242. const height = Math.max( 1, renderTarget.height >> level );
  15243. if ( textureTarget === _gl.TEXTURE_3D || textureTarget === _gl.TEXTURE_2D_ARRAY ) {
  15244. state.texImage3D( textureTarget, level, glInternalFormat, width, height, renderTarget.depth, 0, glFormat, glType, null );
  15245. } else {
  15246. state.texImage2D( textureTarget, level, glInternalFormat, width, height, 0, glFormat, glType, null );
  15247. }
  15248. }
  15249. state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  15250. if ( useMultisampledRTT( renderTarget ) ) {
  15251. multisampledRTTExt.framebufferTexture2DMultisampleEXT( _gl.FRAMEBUFFER, attachment, textureTarget, properties.get( texture ).__webglTexture, 0, getRenderTargetSamples( renderTarget ) );
  15252. } else if ( textureTarget === _gl.TEXTURE_2D || ( textureTarget >= _gl.TEXTURE_CUBE_MAP_POSITIVE_X && textureTarget <= _gl.TEXTURE_CUBE_MAP_NEGATIVE_Z ) ) { // see #24753
  15253. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, attachment, textureTarget, properties.get( texture ).__webglTexture, level );
  15254. }
  15255. state.bindFramebuffer( _gl.FRAMEBUFFER, null );
  15256. }
  15257. // Setup storage for internal depth/stencil buffers and bind to correct framebuffer
  15258. function setupRenderBufferStorage( renderbuffer, renderTarget, isMultisample ) {
  15259. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
  15260. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  15261. let glInternalFormat = ( isWebGL2 === true ) ? _gl.DEPTH_COMPONENT24 : _gl.DEPTH_COMPONENT16;
  15262. if ( isMultisample || useMultisampledRTT( renderTarget ) ) {
  15263. const depthTexture = renderTarget.depthTexture;
  15264. if ( depthTexture && depthTexture.isDepthTexture ) {
  15265. if ( depthTexture.type === FloatType ) {
  15266. glInternalFormat = _gl.DEPTH_COMPONENT32F;
  15267. } else if ( depthTexture.type === UnsignedIntType ) {
  15268. glInternalFormat = _gl.DEPTH_COMPONENT24;
  15269. }
  15270. }
  15271. const samples = getRenderTargetSamples( renderTarget );
  15272. if ( useMultisampledRTT( renderTarget ) ) {
  15273. multisampledRTTExt.renderbufferStorageMultisampleEXT( _gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  15274. } else {
  15275. _gl.renderbufferStorageMultisample( _gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  15276. }
  15277. } else {
  15278. _gl.renderbufferStorage( _gl.RENDERBUFFER, glInternalFormat, renderTarget.width, renderTarget.height );
  15279. }
  15280. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  15281. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  15282. const samples = getRenderTargetSamples( renderTarget );
  15283. if ( isMultisample && useMultisampledRTT( renderTarget ) === false ) {
  15284. _gl.renderbufferStorageMultisample( _gl.RENDERBUFFER, samples, _gl.DEPTH24_STENCIL8, renderTarget.width, renderTarget.height );
  15285. } else if ( useMultisampledRTT( renderTarget ) ) {
  15286. multisampledRTTExt.renderbufferStorageMultisampleEXT( _gl.RENDERBUFFER, samples, _gl.DEPTH24_STENCIL8, renderTarget.width, renderTarget.height );
  15287. } else {
  15288. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_STENCIL, renderTarget.width, renderTarget.height );
  15289. }
  15290. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  15291. } else {
  15292. const textures = renderTarget.textures;
  15293. for ( let i = 0; i < textures.length; i ++ ) {
  15294. const texture = textures[ i ];
  15295. const glFormat = utils.convert( texture.format, texture.colorSpace );
  15296. const glType = utils.convert( texture.type );
  15297. const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace );
  15298. const samples = getRenderTargetSamples( renderTarget );
  15299. if ( isMultisample && useMultisampledRTT( renderTarget ) === false ) {
  15300. _gl.renderbufferStorageMultisample( _gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  15301. } else if ( useMultisampledRTT( renderTarget ) ) {
  15302. multisampledRTTExt.renderbufferStorageMultisampleEXT( _gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  15303. } else {
  15304. _gl.renderbufferStorage( _gl.RENDERBUFFER, glInternalFormat, renderTarget.width, renderTarget.height );
  15305. }
  15306. }
  15307. }
  15308. _gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
  15309. }
  15310. // Setup resources for a Depth Texture for a FBO (needs an extension)
  15311. function setupDepthTexture( framebuffer, renderTarget ) {
  15312. const isCube = ( renderTarget && renderTarget.isWebGLCubeRenderTarget );
  15313. if ( isCube ) throw new Error( 'Depth Texture with cube render targets is not supported' );
  15314. state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  15315. if ( ! ( renderTarget.depthTexture && renderTarget.depthTexture.isDepthTexture ) ) {
  15316. throw new Error( 'renderTarget.depthTexture must be an instance of THREE.DepthTexture' );
  15317. }
  15318. // upload an empty depth texture with framebuffer size
  15319. if ( ! properties.get( renderTarget.depthTexture ).__webglTexture ||
  15320. renderTarget.depthTexture.image.width !== renderTarget.width ||
  15321. renderTarget.depthTexture.image.height !== renderTarget.height ) {
  15322. renderTarget.depthTexture.image.width = renderTarget.width;
  15323. renderTarget.depthTexture.image.height = renderTarget.height;
  15324. renderTarget.depthTexture.needsUpdate = true;
  15325. }
  15326. setTexture2D( renderTarget.depthTexture, 0 );
  15327. const webglDepthTexture = properties.get( renderTarget.depthTexture ).__webglTexture;
  15328. const samples = getRenderTargetSamples( renderTarget );
  15329. if ( renderTarget.depthTexture.format === DepthFormat ) {
  15330. if ( useMultisampledRTT( renderTarget ) ) {
  15331. multisampledRTTExt.framebufferTexture2DMultisampleEXT( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0, samples );
  15332. } else {
  15333. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0 );
  15334. }
  15335. } else if ( renderTarget.depthTexture.format === DepthStencilFormat ) {
  15336. if ( useMultisampledRTT( renderTarget ) ) {
  15337. multisampledRTTExt.framebufferTexture2DMultisampleEXT( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0, samples );
  15338. } else {
  15339. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0 );
  15340. }
  15341. } else {
  15342. throw new Error( 'Unknown depthTexture format' );
  15343. }
  15344. }
  15345. // Setup GL resources for a non-texture depth buffer
  15346. function setupDepthRenderbuffer( renderTarget ) {
  15347. const renderTargetProperties = properties.get( renderTarget );
  15348. const isCube = ( renderTarget.isWebGLCubeRenderTarget === true );
  15349. if ( renderTarget.depthTexture && ! renderTargetProperties.__autoAllocateDepthBuffer ) {
  15350. if ( isCube ) throw new Error( 'target.depthTexture not supported in Cube render targets' );
  15351. setupDepthTexture( renderTargetProperties.__webglFramebuffer, renderTarget );
  15352. } else {
  15353. if ( isCube ) {
  15354. renderTargetProperties.__webglDepthbuffer = [];
  15355. for ( let i = 0; i < 6; i ++ ) {
  15356. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer[ i ] );
  15357. renderTargetProperties.__webglDepthbuffer[ i ] = _gl.createRenderbuffer();
  15358. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer[ i ], renderTarget, false );
  15359. }
  15360. } else {
  15361. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );
  15362. renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer();
  15363. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer, renderTarget, false );
  15364. }
  15365. }
  15366. state.bindFramebuffer( _gl.FRAMEBUFFER, null );
  15367. }
  15368. // rebind framebuffer with external textures
  15369. function rebindTextures( renderTarget, colorTexture, depthTexture ) {
  15370. const renderTargetProperties = properties.get( renderTarget );
  15371. if ( colorTexture !== undefined ) {
  15372. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, renderTarget.texture, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, 0 );
  15373. }
  15374. if ( depthTexture !== undefined ) {
  15375. setupDepthRenderbuffer( renderTarget );
  15376. }
  15377. }
  15378. // Set up GL resources for the render target
  15379. function setupRenderTarget( renderTarget ) {
  15380. const texture = renderTarget.texture;
  15381. const renderTargetProperties = properties.get( renderTarget );
  15382. const textureProperties = properties.get( texture );
  15383. renderTarget.addEventListener( 'dispose', onRenderTargetDispose );
  15384. const textures = renderTarget.textures;
  15385. const isCube = ( renderTarget.isWebGLCubeRenderTarget === true );
  15386. const isMultipleRenderTargets = ( textures.length > 1 );
  15387. const supportsMips = isPowerOfTwo$1( renderTarget ) || isWebGL2;
  15388. if ( ! isMultipleRenderTargets ) {
  15389. if ( textureProperties.__webglTexture === undefined ) {
  15390. textureProperties.__webglTexture = _gl.createTexture();
  15391. }
  15392. textureProperties.__version = texture.version;
  15393. info.memory.textures ++;
  15394. }
  15395. // Setup framebuffer
  15396. if ( isCube ) {
  15397. renderTargetProperties.__webglFramebuffer = [];
  15398. for ( let i = 0; i < 6; i ++ ) {
  15399. if ( isWebGL2 && texture.mipmaps && texture.mipmaps.length > 0 ) {
  15400. renderTargetProperties.__webglFramebuffer[ i ] = [];
  15401. for ( let level = 0; level < texture.mipmaps.length; level ++ ) {
  15402. renderTargetProperties.__webglFramebuffer[ i ][ level ] = _gl.createFramebuffer();
  15403. }
  15404. } else {
  15405. renderTargetProperties.__webglFramebuffer[ i ] = _gl.createFramebuffer();
  15406. }
  15407. }
  15408. } else {
  15409. if ( isWebGL2 && texture.mipmaps && texture.mipmaps.length > 0 ) {
  15410. renderTargetProperties.__webglFramebuffer = [];
  15411. for ( let level = 0; level < texture.mipmaps.length; level ++ ) {
  15412. renderTargetProperties.__webglFramebuffer[ level ] = _gl.createFramebuffer();
  15413. }
  15414. } else {
  15415. renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer();
  15416. }
  15417. if ( isMultipleRenderTargets ) {
  15418. if ( capabilities.drawBuffers ) {
  15419. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  15420. const attachmentProperties = properties.get( textures[ i ] );
  15421. if ( attachmentProperties.__webglTexture === undefined ) {
  15422. attachmentProperties.__webglTexture = _gl.createTexture();
  15423. info.memory.textures ++;
  15424. }
  15425. }
  15426. } else {
  15427. console.warn( 'THREE.WebGLRenderer: WebGLMultipleRenderTargets can only be used with WebGL2 or WEBGL_draw_buffers extension.' );
  15428. }
  15429. }
  15430. if ( ( isWebGL2 && renderTarget.samples > 0 ) && useMultisampledRTT( renderTarget ) === false ) {
  15431. renderTargetProperties.__webglMultisampledFramebuffer = _gl.createFramebuffer();
  15432. renderTargetProperties.__webglColorRenderbuffer = [];
  15433. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer );
  15434. for ( let i = 0; i < textures.length; i ++ ) {
  15435. const texture = textures[ i ];
  15436. renderTargetProperties.__webglColorRenderbuffer[ i ] = _gl.createRenderbuffer();
  15437. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[ i ] );
  15438. const glFormat = utils.convert( texture.format, texture.colorSpace );
  15439. const glType = utils.convert( texture.type );
  15440. const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace, renderTarget.isXRRenderTarget === true );
  15441. const samples = getRenderTargetSamples( renderTarget );
  15442. _gl.renderbufferStorageMultisample( _gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  15443. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[ i ] );
  15444. }
  15445. _gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
  15446. if ( renderTarget.depthBuffer ) {
  15447. renderTargetProperties.__webglDepthRenderbuffer = _gl.createRenderbuffer();
  15448. setupRenderBufferStorage( renderTargetProperties.__webglDepthRenderbuffer, renderTarget, true );
  15449. }
  15450. state.bindFramebuffer( _gl.FRAMEBUFFER, null );
  15451. }
  15452. }
  15453. // Setup color buffer
  15454. if ( isCube ) {
  15455. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture );
  15456. setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture, supportsMips );
  15457. for ( let i = 0; i < 6; i ++ ) {
  15458. if ( isWebGL2 && texture.mipmaps && texture.mipmaps.length > 0 ) {
  15459. for ( let level = 0; level < texture.mipmaps.length; level ++ ) {
  15460. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ i ][ level ], renderTarget, texture, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, level );
  15461. }
  15462. } else {
  15463. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ i ], renderTarget, texture, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0 );
  15464. }
  15465. }
  15466. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {
  15467. generateMipmap( _gl.TEXTURE_CUBE_MAP );
  15468. }
  15469. state.unbindTexture();
  15470. } else if ( isMultipleRenderTargets ) {
  15471. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  15472. const attachment = textures[ i ];
  15473. const attachmentProperties = properties.get( attachment );
  15474. state.bindTexture( _gl.TEXTURE_2D, attachmentProperties.__webglTexture );
  15475. setTextureParameters( _gl.TEXTURE_2D, attachment, supportsMips );
  15476. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, attachment, _gl.COLOR_ATTACHMENT0 + i, _gl.TEXTURE_2D, 0 );
  15477. if ( textureNeedsGenerateMipmaps( attachment, supportsMips ) ) {
  15478. generateMipmap( _gl.TEXTURE_2D );
  15479. }
  15480. }
  15481. state.unbindTexture();
  15482. } else {
  15483. let glTextureType = _gl.TEXTURE_2D;
  15484. if ( renderTarget.isWebGL3DRenderTarget || renderTarget.isWebGLArrayRenderTarget ) {
  15485. if ( isWebGL2 ) {
  15486. glTextureType = renderTarget.isWebGL3DRenderTarget ? _gl.TEXTURE_3D : _gl.TEXTURE_2D_ARRAY;
  15487. } else {
  15488. console.error( 'THREE.WebGLTextures: THREE.Data3DTexture and THREE.DataArrayTexture only supported with WebGL2.' );
  15489. }
  15490. }
  15491. state.bindTexture( glTextureType, textureProperties.__webglTexture );
  15492. setTextureParameters( glTextureType, texture, supportsMips );
  15493. if ( isWebGL2 && texture.mipmaps && texture.mipmaps.length > 0 ) {
  15494. for ( let level = 0; level < texture.mipmaps.length; level ++ ) {
  15495. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ level ], renderTarget, texture, _gl.COLOR_ATTACHMENT0, glTextureType, level );
  15496. }
  15497. } else {
  15498. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, texture, _gl.COLOR_ATTACHMENT0, glTextureType, 0 );
  15499. }
  15500. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {
  15501. generateMipmap( glTextureType );
  15502. }
  15503. state.unbindTexture();
  15504. }
  15505. // Setup depth and stencil buffers
  15506. if ( renderTarget.depthBuffer ) {
  15507. setupDepthRenderbuffer( renderTarget );
  15508. }
  15509. }
  15510. function updateRenderTargetMipmap( renderTarget ) {
  15511. const supportsMips = isPowerOfTwo$1( renderTarget ) || isWebGL2;
  15512. const textures = renderTarget.textures;
  15513. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  15514. const texture = textures[ i ];
  15515. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {
  15516. const target = renderTarget.isWebGLCubeRenderTarget ? _gl.TEXTURE_CUBE_MAP : _gl.TEXTURE_2D;
  15517. const webglTexture = properties.get( texture ).__webglTexture;
  15518. state.bindTexture( target, webglTexture );
  15519. generateMipmap( target );
  15520. state.unbindTexture();
  15521. }
  15522. }
  15523. }
  15524. function updateMultisampleRenderTarget( renderTarget ) {
  15525. if ( ( isWebGL2 && renderTarget.samples > 0 ) && useMultisampledRTT( renderTarget ) === false ) {
  15526. const textures = renderTarget.textures;
  15527. const width = renderTarget.width;
  15528. const height = renderTarget.height;
  15529. let mask = _gl.COLOR_BUFFER_BIT;
  15530. const invalidationArray = [];
  15531. const depthStyle = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT;
  15532. const renderTargetProperties = properties.get( renderTarget );
  15533. const isMultipleRenderTargets = ( textures.length > 1 );
  15534. // If MRT we need to remove FBO attachments
  15535. if ( isMultipleRenderTargets ) {
  15536. for ( let i = 0; i < textures.length; i ++ ) {
  15537. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer );
  15538. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.RENDERBUFFER, null );
  15539. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );
  15540. _gl.framebufferTexture2D( _gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.TEXTURE_2D, null, 0 );
  15541. }
  15542. }
  15543. state.bindFramebuffer( _gl.READ_FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer );
  15544. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );
  15545. for ( let i = 0; i < textures.length; i ++ ) {
  15546. invalidationArray.push( _gl.COLOR_ATTACHMENT0 + i );
  15547. if ( renderTarget.depthBuffer ) {
  15548. invalidationArray.push( depthStyle );
  15549. }
  15550. const ignoreDepthValues = ( renderTargetProperties.__ignoreDepthValues !== undefined ) ? renderTargetProperties.__ignoreDepthValues : false;
  15551. if ( ignoreDepthValues === false ) {
  15552. if ( renderTarget.depthBuffer ) mask |= _gl.DEPTH_BUFFER_BIT;
  15553. if ( renderTarget.stencilBuffer ) mask |= _gl.STENCIL_BUFFER_BIT;
  15554. }
  15555. if ( isMultipleRenderTargets ) {
  15556. _gl.framebufferRenderbuffer( _gl.READ_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[ i ] );
  15557. }
  15558. if ( ignoreDepthValues === true ) {
  15559. _gl.invalidateFramebuffer( _gl.READ_FRAMEBUFFER, [ depthStyle ] );
  15560. _gl.invalidateFramebuffer( _gl.DRAW_FRAMEBUFFER, [ depthStyle ] );
  15561. }
  15562. if ( isMultipleRenderTargets ) {
  15563. const webglTexture = properties.get( textures[ i ] ).__webglTexture;
  15564. _gl.framebufferTexture2D( _gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, webglTexture, 0 );
  15565. }
  15566. _gl.blitFramebuffer( 0, 0, width, height, 0, 0, width, height, mask, _gl.NEAREST );
  15567. if ( supportsInvalidateFramebuffer ) {
  15568. _gl.invalidateFramebuffer( _gl.READ_FRAMEBUFFER, invalidationArray );
  15569. }
  15570. }
  15571. state.bindFramebuffer( _gl.READ_FRAMEBUFFER, null );
  15572. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, null );
  15573. // If MRT since pre-blit we removed the FBO we need to reconstruct the attachments
  15574. if ( isMultipleRenderTargets ) {
  15575. for ( let i = 0; i < textures.length; i ++ ) {
  15576. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer );
  15577. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[ i ] );
  15578. const webglTexture = properties.get( textures[ i ] ).__webglTexture;
  15579. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );
  15580. _gl.framebufferTexture2D( _gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.TEXTURE_2D, webglTexture, 0 );
  15581. }
  15582. }
  15583. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer );
  15584. }
  15585. }
  15586. function getRenderTargetSamples( renderTarget ) {
  15587. return Math.min( capabilities.maxSamples, renderTarget.samples );
  15588. }
  15589. function useMultisampledRTT( renderTarget ) {
  15590. const renderTargetProperties = properties.get( renderTarget );
  15591. return isWebGL2 && renderTarget.samples > 0 && extensions.has( 'WEBGL_multisampled_render_to_texture' ) === true && renderTargetProperties.__useRenderToTexture !== false;
  15592. }
  15593. function updateVideoTexture( texture ) {
  15594. const frame = info.render.frame;
  15595. // Check the last frame we updated the VideoTexture
  15596. if ( _videoTextures.get( texture ) !== frame ) {
  15597. _videoTextures.set( texture, frame );
  15598. texture.update();
  15599. }
  15600. }
  15601. function verifyColorSpace( texture, image ) {
  15602. const colorSpace = texture.colorSpace;
  15603. const format = texture.format;
  15604. const type = texture.type;
  15605. if ( texture.isCompressedTexture === true || texture.isVideoTexture === true || texture.format === _SRGBAFormat ) return image;
  15606. if ( colorSpace !== LinearSRGBColorSpace && colorSpace !== NoColorSpace ) {
  15607. // sRGB
  15608. if ( ColorManagement.getTransfer( colorSpace ) === SRGBTransfer ) {
  15609. if ( isWebGL2 === false ) {
  15610. // in WebGL 1, try to use EXT_sRGB extension and unsized formats
  15611. if ( extensions.has( 'EXT_sRGB' ) === true && format === RGBAFormat ) {
  15612. texture.format = _SRGBAFormat;
  15613. // it's not possible to generate mips in WebGL 1 with this extension
  15614. texture.minFilter = LinearFilter;
  15615. texture.generateMipmaps = false;
  15616. } else {
  15617. // slow fallback (CPU decode)
  15618. image = ImageUtils.sRGBToLinear( image );
  15619. }
  15620. } else {
  15621. // in WebGL 2 uncompressed textures can only be sRGB encoded if they have the RGBA8 format
  15622. if ( format !== RGBAFormat || type !== UnsignedByteType ) {
  15623. console.warn( 'THREE.WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType.' );
  15624. }
  15625. }
  15626. } else {
  15627. console.error( 'THREE.WebGLTextures: Unsupported texture color space:', colorSpace );
  15628. }
  15629. }
  15630. return image;
  15631. }
  15632. //
  15633. this.allocateTextureUnit = allocateTextureUnit;
  15634. this.resetTextureUnits = resetTextureUnits;
  15635. this.setTexture2D = setTexture2D;
  15636. this.setTexture2DArray = setTexture2DArray;
  15637. this.setTexture3D = setTexture3D;
  15638. this.setTextureCube = setTextureCube;
  15639. this.rebindTextures = rebindTextures;
  15640. this.setupRenderTarget = setupRenderTarget;
  15641. this.updateRenderTargetMipmap = updateRenderTargetMipmap;
  15642. this.updateMultisampleRenderTarget = updateMultisampleRenderTarget;
  15643. this.setupDepthRenderbuffer = setupDepthRenderbuffer;
  15644. this.setupFrameBufferTexture = setupFrameBufferTexture;
  15645. this.useMultisampledRTT = useMultisampledRTT;
  15646. }
  15647. function WebGLUtils( gl, extensions, capabilities ) {
  15648. const isWebGL2 = capabilities.isWebGL2;
  15649. function convert( p, colorSpace = NoColorSpace ) {
  15650. let extension;
  15651. const transfer = ColorManagement.getTransfer( colorSpace );
  15652. if ( p === UnsignedByteType ) return gl.UNSIGNED_BYTE;
  15653. if ( p === UnsignedShort4444Type ) return gl.UNSIGNED_SHORT_4_4_4_4;
  15654. if ( p === UnsignedShort5551Type ) return gl.UNSIGNED_SHORT_5_5_5_1;
  15655. if ( p === ByteType ) return gl.BYTE;
  15656. if ( p === ShortType ) return gl.SHORT;
  15657. if ( p === UnsignedShortType ) return gl.UNSIGNED_SHORT;
  15658. if ( p === IntType ) return gl.INT;
  15659. if ( p === UnsignedIntType ) return gl.UNSIGNED_INT;
  15660. if ( p === FloatType ) return gl.FLOAT;
  15661. if ( p === HalfFloatType ) {
  15662. if ( isWebGL2 ) return gl.HALF_FLOAT;
  15663. extension = extensions.get( 'OES_texture_half_float' );
  15664. if ( extension !== null ) {
  15665. return extension.HALF_FLOAT_OES;
  15666. } else {
  15667. return null;
  15668. }
  15669. }
  15670. if ( p === AlphaFormat ) return gl.ALPHA;
  15671. if ( p === RGBAFormat ) return gl.RGBA;
  15672. if ( p === LuminanceFormat ) return gl.LUMINANCE;
  15673. if ( p === LuminanceAlphaFormat ) return gl.LUMINANCE_ALPHA;
  15674. if ( p === DepthFormat ) return gl.DEPTH_COMPONENT;
  15675. if ( p === DepthStencilFormat ) return gl.DEPTH_STENCIL;
  15676. // WebGL 1 sRGB fallback
  15677. if ( p === _SRGBAFormat ) {
  15678. extension = extensions.get( 'EXT_sRGB' );
  15679. if ( extension !== null ) {
  15680. return extension.SRGB_ALPHA_EXT;
  15681. } else {
  15682. return null;
  15683. }
  15684. }
  15685. // WebGL2 formats.
  15686. if ( p === RedFormat ) return gl.RED;
  15687. if ( p === RedIntegerFormat ) return gl.RED_INTEGER;
  15688. if ( p === RGFormat ) return gl.RG;
  15689. if ( p === RGIntegerFormat ) return gl.RG_INTEGER;
  15690. if ( p === RGBAIntegerFormat ) return gl.RGBA_INTEGER;
  15691. // S3TC
  15692. if ( p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format ) {
  15693. if ( transfer === SRGBTransfer ) {
  15694. extension = extensions.get( 'WEBGL_compressed_texture_s3tc_srgb' );
  15695. if ( extension !== null ) {
  15696. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_S3TC_DXT1_EXT;
  15697. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;
  15698. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;
  15699. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT;
  15700. } else {
  15701. return null;
  15702. }
  15703. } else {
  15704. extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
  15705. if ( extension !== null ) {
  15706. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  15707. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  15708. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  15709. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  15710. } else {
  15711. return null;
  15712. }
  15713. }
  15714. }
  15715. // PVRTC
  15716. if ( p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format ) {
  15717. extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  15718. if ( extension !== null ) {
  15719. if ( p === RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  15720. if ( p === RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  15721. if ( p === RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  15722. if ( p === RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  15723. } else {
  15724. return null;
  15725. }
  15726. }
  15727. // ETC1
  15728. if ( p === RGB_ETC1_Format ) {
  15729. extension = extensions.get( 'WEBGL_compressed_texture_etc1' );
  15730. if ( extension !== null ) {
  15731. return extension.COMPRESSED_RGB_ETC1_WEBGL;
  15732. } else {
  15733. return null;
  15734. }
  15735. }
  15736. // ETC2
  15737. if ( p === RGB_ETC2_Format || p === RGBA_ETC2_EAC_Format ) {
  15738. extension = extensions.get( 'WEBGL_compressed_texture_etc' );
  15739. if ( extension !== null ) {
  15740. if ( p === RGB_ETC2_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ETC2 : extension.COMPRESSED_RGB8_ETC2;
  15741. if ( p === RGBA_ETC2_EAC_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC : extension.COMPRESSED_RGBA8_ETC2_EAC;
  15742. } else {
  15743. return null;
  15744. }
  15745. }
  15746. // ASTC
  15747. if ( p === RGBA_ASTC_4x4_Format || p === RGBA_ASTC_5x4_Format || p === RGBA_ASTC_5x5_Format ||
  15748. p === RGBA_ASTC_6x5_Format || p === RGBA_ASTC_6x6_Format || p === RGBA_ASTC_8x5_Format ||
  15749. p === RGBA_ASTC_8x6_Format || p === RGBA_ASTC_8x8_Format || p === RGBA_ASTC_10x5_Format ||
  15750. p === RGBA_ASTC_10x6_Format || p === RGBA_ASTC_10x8_Format || p === RGBA_ASTC_10x10_Format ||
  15751. p === RGBA_ASTC_12x10_Format || p === RGBA_ASTC_12x12_Format ) {
  15752. extension = extensions.get( 'WEBGL_compressed_texture_astc' );
  15753. if ( extension !== null ) {
  15754. if ( p === RGBA_ASTC_4x4_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR : extension.COMPRESSED_RGBA_ASTC_4x4_KHR;
  15755. if ( p === RGBA_ASTC_5x4_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR : extension.COMPRESSED_RGBA_ASTC_5x4_KHR;
  15756. if ( p === RGBA_ASTC_5x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR : extension.COMPRESSED_RGBA_ASTC_5x5_KHR;
  15757. if ( p === RGBA_ASTC_6x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR : extension.COMPRESSED_RGBA_ASTC_6x5_KHR;
  15758. if ( p === RGBA_ASTC_6x6_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR : extension.COMPRESSED_RGBA_ASTC_6x6_KHR;
  15759. if ( p === RGBA_ASTC_8x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR : extension.COMPRESSED_RGBA_ASTC_8x5_KHR;
  15760. if ( p === RGBA_ASTC_8x6_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR : extension.COMPRESSED_RGBA_ASTC_8x6_KHR;
  15761. if ( p === RGBA_ASTC_8x8_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR : extension.COMPRESSED_RGBA_ASTC_8x8_KHR;
  15762. if ( p === RGBA_ASTC_10x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR : extension.COMPRESSED_RGBA_ASTC_10x5_KHR;
  15763. if ( p === RGBA_ASTC_10x6_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR : extension.COMPRESSED_RGBA_ASTC_10x6_KHR;
  15764. if ( p === RGBA_ASTC_10x8_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR : extension.COMPRESSED_RGBA_ASTC_10x8_KHR;
  15765. if ( p === RGBA_ASTC_10x10_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR : extension.COMPRESSED_RGBA_ASTC_10x10_KHR;
  15766. if ( p === RGBA_ASTC_12x10_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR : extension.COMPRESSED_RGBA_ASTC_12x10_KHR;
  15767. if ( p === RGBA_ASTC_12x12_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR : extension.COMPRESSED_RGBA_ASTC_12x12_KHR;
  15768. } else {
  15769. return null;
  15770. }
  15771. }
  15772. // BPTC
  15773. if ( p === RGBA_BPTC_Format || p === RGB_BPTC_SIGNED_Format || p === RGB_BPTC_UNSIGNED_Format ) {
  15774. extension = extensions.get( 'EXT_texture_compression_bptc' );
  15775. if ( extension !== null ) {
  15776. if ( p === RGBA_BPTC_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT : extension.COMPRESSED_RGBA_BPTC_UNORM_EXT;
  15777. if ( p === RGB_BPTC_SIGNED_Format ) return extension.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT;
  15778. if ( p === RGB_BPTC_UNSIGNED_Format ) return extension.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT;
  15779. } else {
  15780. return null;
  15781. }
  15782. }
  15783. // RGTC
  15784. if ( p === RED_RGTC1_Format || p === SIGNED_RED_RGTC1_Format || p === RED_GREEN_RGTC2_Format || p === SIGNED_RED_GREEN_RGTC2_Format ) {
  15785. extension = extensions.get( 'EXT_texture_compression_rgtc' );
  15786. if ( extension !== null ) {
  15787. if ( p === RGBA_BPTC_Format ) return extension.COMPRESSED_RED_RGTC1_EXT;
  15788. if ( p === SIGNED_RED_RGTC1_Format ) return extension.COMPRESSED_SIGNED_RED_RGTC1_EXT;
  15789. if ( p === RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_RED_GREEN_RGTC2_EXT;
  15790. if ( p === SIGNED_RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT;
  15791. } else {
  15792. return null;
  15793. }
  15794. }
  15795. //
  15796. if ( p === UnsignedInt248Type ) {
  15797. if ( isWebGL2 ) return gl.UNSIGNED_INT_24_8;
  15798. extension = extensions.get( 'WEBGL_depth_texture' );
  15799. if ( extension !== null ) {
  15800. return extension.UNSIGNED_INT_24_8_WEBGL;
  15801. } else {
  15802. return null;
  15803. }
  15804. }
  15805. // if "p" can't be resolved, assume the user defines a WebGL constant as a string (fallback/workaround for packed RGB formats)
  15806. return ( gl[ p ] !== undefined ) ? gl[ p ] : null;
  15807. }
  15808. return { convert: convert };
  15809. }
  15810. class ArrayCamera extends PerspectiveCamera {
  15811. constructor( array = [] ) {
  15812. super();
  15813. this.isArrayCamera = true;
  15814. this.cameras = array;
  15815. }
  15816. }
  15817. class Group extends Object3D {
  15818. constructor() {
  15819. super();
  15820. this.isGroup = true;
  15821. this.type = 'Group';
  15822. }
  15823. }
  15824. const _moveEvent = { type: 'move' };
  15825. class WebXRController {
  15826. constructor() {
  15827. this._targetRay = null;
  15828. this._grip = null;
  15829. this._hand = null;
  15830. }
  15831. getHandSpace() {
  15832. if ( this._hand === null ) {
  15833. this._hand = new Group();
  15834. this._hand.matrixAutoUpdate = false;
  15835. this._hand.visible = false;
  15836. this._hand.joints = {};
  15837. this._hand.inputState = { pinching: false };
  15838. }
  15839. return this._hand;
  15840. }
  15841. getTargetRaySpace() {
  15842. if ( this._targetRay === null ) {
  15843. this._targetRay = new Group();
  15844. this._targetRay.matrixAutoUpdate = false;
  15845. this._targetRay.visible = false;
  15846. this._targetRay.hasLinearVelocity = false;
  15847. this._targetRay.linearVelocity = new Vector3();
  15848. this._targetRay.hasAngularVelocity = false;
  15849. this._targetRay.angularVelocity = new Vector3();
  15850. }
  15851. return this._targetRay;
  15852. }
  15853. getGripSpace() {
  15854. if ( this._grip === null ) {
  15855. this._grip = new Group();
  15856. this._grip.matrixAutoUpdate = false;
  15857. this._grip.visible = false;
  15858. this._grip.hasLinearVelocity = false;
  15859. this._grip.linearVelocity = new Vector3();
  15860. this._grip.hasAngularVelocity = false;
  15861. this._grip.angularVelocity = new Vector3();
  15862. }
  15863. return this._grip;
  15864. }
  15865. dispatchEvent( event ) {
  15866. if ( this._targetRay !== null ) {
  15867. this._targetRay.dispatchEvent( event );
  15868. }
  15869. if ( this._grip !== null ) {
  15870. this._grip.dispatchEvent( event );
  15871. }
  15872. if ( this._hand !== null ) {
  15873. this._hand.dispatchEvent( event );
  15874. }
  15875. return this;
  15876. }
  15877. connect( inputSource ) {
  15878. if ( inputSource && inputSource.hand ) {
  15879. const hand = this._hand;
  15880. if ( hand ) {
  15881. for ( const inputjoint of inputSource.hand.values() ) {
  15882. // Initialize hand with joints when connected
  15883. this._getHandJoint( hand, inputjoint );
  15884. }
  15885. }
  15886. }
  15887. this.dispatchEvent( { type: 'connected', data: inputSource } );
  15888. return this;
  15889. }
  15890. disconnect( inputSource ) {
  15891. this.dispatchEvent( { type: 'disconnected', data: inputSource } );
  15892. if ( this._targetRay !== null ) {
  15893. this._targetRay.visible = false;
  15894. }
  15895. if ( this._grip !== null ) {
  15896. this._grip.visible = false;
  15897. }
  15898. if ( this._hand !== null ) {
  15899. this._hand.visible = false;
  15900. }
  15901. return this;
  15902. }
  15903. update( inputSource, frame, referenceSpace ) {
  15904. let inputPose = null;
  15905. let gripPose = null;
  15906. let handPose = null;
  15907. const targetRay = this._targetRay;
  15908. const grip = this._grip;
  15909. const hand = this._hand;
  15910. if ( inputSource && frame.session.visibilityState !== 'visible-blurred' ) {
  15911. if ( hand && inputSource.hand ) {
  15912. handPose = true;
  15913. for ( const inputjoint of inputSource.hand.values() ) {
  15914. // Update the joints groups with the XRJoint poses
  15915. const jointPose = frame.getJointPose( inputjoint, referenceSpace );
  15916. // The transform of this joint will be updated with the joint pose on each frame
  15917. const joint = this._getHandJoint( hand, inputjoint );
  15918. if ( jointPose !== null ) {
  15919. joint.matrix.fromArray( jointPose.transform.matrix );
  15920. joint.matrix.decompose( joint.position, joint.rotation, joint.scale );
  15921. joint.matrixWorldNeedsUpdate = true;
  15922. joint.jointRadius = jointPose.radius;
  15923. }
  15924. joint.visible = jointPose !== null;
  15925. }
  15926. // Custom events
  15927. // Check pinchz
  15928. const indexTip = hand.joints[ 'index-finger-tip' ];
  15929. const thumbTip = hand.joints[ 'thumb-tip' ];
  15930. const distance = indexTip.position.distanceTo( thumbTip.position );
  15931. const distanceToPinch = 0.02;
  15932. const threshold = 0.005;
  15933. if ( hand.inputState.pinching && distance > distanceToPinch + threshold ) {
  15934. hand.inputState.pinching = false;
  15935. this.dispatchEvent( {
  15936. type: 'pinchend',
  15937. handedness: inputSource.handedness,
  15938. target: this
  15939. } );
  15940. } else if ( ! hand.inputState.pinching && distance <= distanceToPinch - threshold ) {
  15941. hand.inputState.pinching = true;
  15942. this.dispatchEvent( {
  15943. type: 'pinchstart',
  15944. handedness: inputSource.handedness,
  15945. target: this
  15946. } );
  15947. }
  15948. } else {
  15949. if ( grip !== null && inputSource.gripSpace ) {
  15950. gripPose = frame.getPose( inputSource.gripSpace, referenceSpace );
  15951. if ( gripPose !== null ) {
  15952. grip.matrix.fromArray( gripPose.transform.matrix );
  15953. grip.matrix.decompose( grip.position, grip.rotation, grip.scale );
  15954. grip.matrixWorldNeedsUpdate = true;
  15955. if ( gripPose.linearVelocity ) {
  15956. grip.hasLinearVelocity = true;
  15957. grip.linearVelocity.copy( gripPose.linearVelocity );
  15958. } else {
  15959. grip.hasLinearVelocity = false;
  15960. }
  15961. if ( gripPose.angularVelocity ) {
  15962. grip.hasAngularVelocity = true;
  15963. grip.angularVelocity.copy( gripPose.angularVelocity );
  15964. } else {
  15965. grip.hasAngularVelocity = false;
  15966. }
  15967. }
  15968. }
  15969. }
  15970. if ( targetRay !== null ) {
  15971. inputPose = frame.getPose( inputSource.targetRaySpace, referenceSpace );
  15972. // Some runtimes (namely Vive Cosmos with Vive OpenXR Runtime) have only grip space and ray space is equal to it
  15973. if ( inputPose === null && gripPose !== null ) {
  15974. inputPose = gripPose;
  15975. }
  15976. if ( inputPose !== null ) {
  15977. targetRay.matrix.fromArray( inputPose.transform.matrix );
  15978. targetRay.matrix.decompose( targetRay.position, targetRay.rotation, targetRay.scale );
  15979. targetRay.matrixWorldNeedsUpdate = true;
  15980. if ( inputPose.linearVelocity ) {
  15981. targetRay.hasLinearVelocity = true;
  15982. targetRay.linearVelocity.copy( inputPose.linearVelocity );
  15983. } else {
  15984. targetRay.hasLinearVelocity = false;
  15985. }
  15986. if ( inputPose.angularVelocity ) {
  15987. targetRay.hasAngularVelocity = true;
  15988. targetRay.angularVelocity.copy( inputPose.angularVelocity );
  15989. } else {
  15990. targetRay.hasAngularVelocity = false;
  15991. }
  15992. this.dispatchEvent( _moveEvent );
  15993. }
  15994. }
  15995. }
  15996. if ( targetRay !== null ) {
  15997. targetRay.visible = ( inputPose !== null );
  15998. }
  15999. if ( grip !== null ) {
  16000. grip.visible = ( gripPose !== null );
  16001. }
  16002. if ( hand !== null ) {
  16003. hand.visible = ( handPose !== null );
  16004. }
  16005. return this;
  16006. }
  16007. // private method
  16008. _getHandJoint( hand, inputjoint ) {
  16009. if ( hand.joints[ inputjoint.jointName ] === undefined ) {
  16010. const joint = new Group();
  16011. joint.matrixAutoUpdate = false;
  16012. joint.visible = false;
  16013. hand.joints[ inputjoint.jointName ] = joint;
  16014. hand.add( joint );
  16015. }
  16016. return hand.joints[ inputjoint.jointName ];
  16017. }
  16018. }
  16019. const _occlusion_vertex = `
  16020. void main() {
  16021. gl_Position = vec4( position, 1.0 );
  16022. }`;
  16023. const _occlusion_fragment = `
  16024. uniform sampler2DArray depthColor;
  16025. uniform float depthWidth;
  16026. uniform float depthHeight;
  16027. void main() {
  16028. vec2 coord = vec2( gl_FragCoord.x / depthWidth, gl_FragCoord.y / depthHeight );
  16029. if ( coord.x >= 1.0 ) {
  16030. gl_FragDepthEXT = texture( depthColor, vec3( coord.x - 1.0, coord.y, 1 ) ).r;
  16031. } else {
  16032. gl_FragDepthEXT = texture( depthColor, vec3( coord.x, coord.y, 0 ) ).r;
  16033. }
  16034. }`;
  16035. class WebXRDepthSensing {
  16036. constructor() {
  16037. this.texture = null;
  16038. this.mesh = null;
  16039. this.depthNear = 0;
  16040. this.depthFar = 0;
  16041. }
  16042. init( renderer, depthData, renderState ) {
  16043. if ( this.texture === null ) {
  16044. const texture = new Texture();
  16045. const texProps = renderer.properties.get( texture );
  16046. texProps.__webglTexture = depthData.texture;
  16047. if ( ( depthData.depthNear != renderState.depthNear ) || ( depthData.depthFar != renderState.depthFar ) ) {
  16048. this.depthNear = depthData.depthNear;
  16049. this.depthFar = depthData.depthFar;
  16050. }
  16051. this.texture = texture;
  16052. }
  16053. }
  16054. render( renderer, cameraXR ) {
  16055. if ( this.texture !== null ) {
  16056. if ( this.mesh === null ) {
  16057. const viewport = cameraXR.cameras[ 0 ].viewport;
  16058. const material = new ShaderMaterial( {
  16059. extensions: { fragDepth: true },
  16060. vertexShader: _occlusion_vertex,
  16061. fragmentShader: _occlusion_fragment,
  16062. uniforms: {
  16063. depthColor: { value: this.texture },
  16064. depthWidth: { value: viewport.z },
  16065. depthHeight: { value: viewport.w }
  16066. }
  16067. } );
  16068. this.mesh = new Mesh( new PlaneGeometry( 20, 20 ), material );
  16069. }
  16070. renderer.render( this.mesh, cameraXR );
  16071. }
  16072. }
  16073. reset() {
  16074. this.texture = null;
  16075. this.mesh = null;
  16076. }
  16077. }
  16078. class WebXRManager extends EventDispatcher {
  16079. constructor( renderer, gl ) {
  16080. super();
  16081. const scope = this;
  16082. let session = null;
  16083. let framebufferScaleFactor = 1.0;
  16084. let referenceSpace = null;
  16085. let referenceSpaceType = 'local-floor';
  16086. // Set default foveation to maximum.
  16087. let foveation = 1.0;
  16088. let customReferenceSpace = null;
  16089. let pose = null;
  16090. let glBinding = null;
  16091. let glProjLayer = null;
  16092. let glBaseLayer = null;
  16093. let xrFrame = null;
  16094. const depthSensing = new WebXRDepthSensing();
  16095. const attributes = gl.getContextAttributes();
  16096. let initialRenderTarget = null;
  16097. let newRenderTarget = null;
  16098. const controllers = [];
  16099. const controllerInputSources = [];
  16100. const currentSize = new Vector2();
  16101. let currentPixelRatio = null;
  16102. //
  16103. const cameraL = new PerspectiveCamera();
  16104. cameraL.layers.enable( 1 );
  16105. cameraL.viewport = new Vector4();
  16106. const cameraR = new PerspectiveCamera();
  16107. cameraR.layers.enable( 2 );
  16108. cameraR.viewport = new Vector4();
  16109. const cameras = [ cameraL, cameraR ];
  16110. const cameraXR = new ArrayCamera();
  16111. cameraXR.layers.enable( 1 );
  16112. cameraXR.layers.enable( 2 );
  16113. let _currentDepthNear = null;
  16114. let _currentDepthFar = null;
  16115. //
  16116. this.cameraAutoUpdate = true;
  16117. this.enabled = false;
  16118. this.isPresenting = false;
  16119. this.getController = function ( index ) {
  16120. let controller = controllers[ index ];
  16121. if ( controller === undefined ) {
  16122. controller = new WebXRController();
  16123. controllers[ index ] = controller;
  16124. }
  16125. return controller.getTargetRaySpace();
  16126. };
  16127. this.getControllerGrip = function ( index ) {
  16128. let controller = controllers[ index ];
  16129. if ( controller === undefined ) {
  16130. controller = new WebXRController();
  16131. controllers[ index ] = controller;
  16132. }
  16133. return controller.getGripSpace();
  16134. };
  16135. this.getHand = function ( index ) {
  16136. let controller = controllers[ index ];
  16137. if ( controller === undefined ) {
  16138. controller = new WebXRController();
  16139. controllers[ index ] = controller;
  16140. }
  16141. return controller.getHandSpace();
  16142. };
  16143. //
  16144. function onSessionEvent( event ) {
  16145. const controllerIndex = controllerInputSources.indexOf( event.inputSource );
  16146. if ( controllerIndex === - 1 ) {
  16147. return;
  16148. }
  16149. const controller = controllers[ controllerIndex ];
  16150. if ( controller !== undefined ) {
  16151. controller.update( event.inputSource, event.frame, customReferenceSpace || referenceSpace );
  16152. controller.dispatchEvent( { type: event.type, data: event.inputSource } );
  16153. }
  16154. }
  16155. function onSessionEnd() {
  16156. session.removeEventListener( 'select', onSessionEvent );
  16157. session.removeEventListener( 'selectstart', onSessionEvent );
  16158. session.removeEventListener( 'selectend', onSessionEvent );
  16159. session.removeEventListener( 'squeeze', onSessionEvent );
  16160. session.removeEventListener( 'squeezestart', onSessionEvent );
  16161. session.removeEventListener( 'squeezeend', onSessionEvent );
  16162. session.removeEventListener( 'end', onSessionEnd );
  16163. session.removeEventListener( 'inputsourceschange', onInputSourcesChange );
  16164. for ( let i = 0; i < controllers.length; i ++ ) {
  16165. const inputSource = controllerInputSources[ i ];
  16166. if ( inputSource === null ) continue;
  16167. controllerInputSources[ i ] = null;
  16168. controllers[ i ].disconnect( inputSource );
  16169. }
  16170. _currentDepthNear = null;
  16171. _currentDepthFar = null;
  16172. depthSensing.reset();
  16173. // restore framebuffer/rendering state
  16174. renderer.setRenderTarget( initialRenderTarget );
  16175. glBaseLayer = null;
  16176. glProjLayer = null;
  16177. glBinding = null;
  16178. session = null;
  16179. newRenderTarget = null;
  16180. //
  16181. animation.stop();
  16182. scope.isPresenting = false;
  16183. renderer.setPixelRatio( currentPixelRatio );
  16184. renderer.setSize( currentSize.width, currentSize.height, false );
  16185. scope.dispatchEvent( { type: 'sessionend' } );
  16186. }
  16187. this.setFramebufferScaleFactor = function ( value ) {
  16188. framebufferScaleFactor = value;
  16189. if ( scope.isPresenting === true ) {
  16190. console.warn( 'THREE.WebXRManager: Cannot change framebuffer scale while presenting.' );
  16191. }
  16192. };
  16193. this.setReferenceSpaceType = function ( value ) {
  16194. referenceSpaceType = value;
  16195. if ( scope.isPresenting === true ) {
  16196. console.warn( 'THREE.WebXRManager: Cannot change reference space type while presenting.' );
  16197. }
  16198. };
  16199. this.getReferenceSpace = function () {
  16200. return customReferenceSpace || referenceSpace;
  16201. };
  16202. this.setReferenceSpace = function ( space ) {
  16203. customReferenceSpace = space;
  16204. };
  16205. this.getBaseLayer = function () {
  16206. return glProjLayer !== null ? glProjLayer : glBaseLayer;
  16207. };
  16208. this.getBinding = function () {
  16209. return glBinding;
  16210. };
  16211. this.getFrame = function () {
  16212. return xrFrame;
  16213. };
  16214. this.getSession = function () {
  16215. return session;
  16216. };
  16217. this.setSession = async function ( value ) {
  16218. session = value;
  16219. if ( session !== null ) {
  16220. initialRenderTarget = renderer.getRenderTarget();
  16221. session.addEventListener( 'select', onSessionEvent );
  16222. session.addEventListener( 'selectstart', onSessionEvent );
  16223. session.addEventListener( 'selectend', onSessionEvent );
  16224. session.addEventListener( 'squeeze', onSessionEvent );
  16225. session.addEventListener( 'squeezestart', onSessionEvent );
  16226. session.addEventListener( 'squeezeend', onSessionEvent );
  16227. session.addEventListener( 'end', onSessionEnd );
  16228. session.addEventListener( 'inputsourceschange', onInputSourcesChange );
  16229. if ( attributes.xrCompatible !== true ) {
  16230. await gl.makeXRCompatible();
  16231. }
  16232. currentPixelRatio = renderer.getPixelRatio();
  16233. renderer.getSize( currentSize );
  16234. if ( ( session.renderState.layers === undefined ) || ( renderer.capabilities.isWebGL2 === false ) ) {
  16235. const layerInit = {
  16236. antialias: ( session.renderState.layers === undefined ) ? attributes.antialias : true,
  16237. alpha: true,
  16238. depth: attributes.depth,
  16239. stencil: attributes.stencil,
  16240. framebufferScaleFactor: framebufferScaleFactor
  16241. };
  16242. glBaseLayer = new XRWebGLLayer( session, gl, layerInit );
  16243. session.updateRenderState( { baseLayer: glBaseLayer } );
  16244. renderer.setPixelRatio( 1 );
  16245. renderer.setSize( glBaseLayer.framebufferWidth, glBaseLayer.framebufferHeight, false );
  16246. newRenderTarget = new WebGLRenderTarget(
  16247. glBaseLayer.framebufferWidth,
  16248. glBaseLayer.framebufferHeight,
  16249. {
  16250. format: RGBAFormat,
  16251. type: UnsignedByteType,
  16252. colorSpace: renderer.outputColorSpace,
  16253. stencilBuffer: attributes.stencil
  16254. }
  16255. );
  16256. } else {
  16257. let depthFormat = null;
  16258. let depthType = null;
  16259. let glDepthFormat = null;
  16260. if ( attributes.depth ) {
  16261. glDepthFormat = attributes.stencil ? gl.DEPTH24_STENCIL8 : gl.DEPTH_COMPONENT24;
  16262. depthFormat = attributes.stencil ? DepthStencilFormat : DepthFormat;
  16263. depthType = attributes.stencil ? UnsignedInt248Type : UnsignedIntType;
  16264. }
  16265. const projectionlayerInit = {
  16266. colorFormat: gl.RGBA8,
  16267. depthFormat: glDepthFormat,
  16268. scaleFactor: framebufferScaleFactor
  16269. };
  16270. glBinding = new XRWebGLBinding( session, gl );
  16271. glProjLayer = glBinding.createProjectionLayer( projectionlayerInit );
  16272. session.updateRenderState( { layers: [ glProjLayer ] } );
  16273. renderer.setPixelRatio( 1 );
  16274. renderer.setSize( glProjLayer.textureWidth, glProjLayer.textureHeight, false );
  16275. newRenderTarget = new WebGLRenderTarget(
  16276. glProjLayer.textureWidth,
  16277. glProjLayer.textureHeight,
  16278. {
  16279. format: RGBAFormat,
  16280. type: UnsignedByteType,
  16281. depthTexture: new DepthTexture( glProjLayer.textureWidth, glProjLayer.textureHeight, depthType, undefined, undefined, undefined, undefined, undefined, undefined, depthFormat ),
  16282. stencilBuffer: attributes.stencil,
  16283. colorSpace: renderer.outputColorSpace,
  16284. samples: attributes.antialias ? 4 : 0
  16285. } );
  16286. const renderTargetProperties = renderer.properties.get( newRenderTarget );
  16287. renderTargetProperties.__ignoreDepthValues = glProjLayer.ignoreDepthValues;
  16288. }
  16289. newRenderTarget.isXRRenderTarget = true; // TODO Remove this when possible, see #23278
  16290. this.setFoveation( foveation );
  16291. customReferenceSpace = null;
  16292. referenceSpace = await session.requestReferenceSpace( referenceSpaceType );
  16293. animation.setContext( session );
  16294. animation.start();
  16295. scope.isPresenting = true;
  16296. scope.dispatchEvent( { type: 'sessionstart' } );
  16297. }
  16298. };
  16299. this.getEnvironmentBlendMode = function () {
  16300. if ( session !== null ) {
  16301. return session.environmentBlendMode;
  16302. }
  16303. };
  16304. function onInputSourcesChange( event ) {
  16305. // Notify disconnected
  16306. for ( let i = 0; i < event.removed.length; i ++ ) {
  16307. const inputSource = event.removed[ i ];
  16308. const index = controllerInputSources.indexOf( inputSource );
  16309. if ( index >= 0 ) {
  16310. controllerInputSources[ index ] = null;
  16311. controllers[ index ].disconnect( inputSource );
  16312. }
  16313. }
  16314. // Notify connected
  16315. for ( let i = 0; i < event.added.length; i ++ ) {
  16316. const inputSource = event.added[ i ];
  16317. let controllerIndex = controllerInputSources.indexOf( inputSource );
  16318. if ( controllerIndex === - 1 ) {
  16319. // Assign input source a controller that currently has no input source
  16320. for ( let i = 0; i < controllers.length; i ++ ) {
  16321. if ( i >= controllerInputSources.length ) {
  16322. controllerInputSources.push( inputSource );
  16323. controllerIndex = i;
  16324. break;
  16325. } else if ( controllerInputSources[ i ] === null ) {
  16326. controllerInputSources[ i ] = inputSource;
  16327. controllerIndex = i;
  16328. break;
  16329. }
  16330. }
  16331. // If all controllers do currently receive input we ignore new ones
  16332. if ( controllerIndex === - 1 ) break;
  16333. }
  16334. const controller = controllers[ controllerIndex ];
  16335. if ( controller ) {
  16336. controller.connect( inputSource );
  16337. }
  16338. }
  16339. }
  16340. //
  16341. const cameraLPos = new Vector3();
  16342. const cameraRPos = new Vector3();
  16343. /**
  16344. * Assumes 2 cameras that are parallel and share an X-axis, and that
  16345. * the cameras' projection and world matrices have already been set.
  16346. * And that near and far planes are identical for both cameras.
  16347. * Visualization of this technique: https://computergraphics.stackexchange.com/a/4765
  16348. */
  16349. function setProjectionFromUnion( camera, cameraL, cameraR ) {
  16350. cameraLPos.setFromMatrixPosition( cameraL.matrixWorld );
  16351. cameraRPos.setFromMatrixPosition( cameraR.matrixWorld );
  16352. const ipd = cameraLPos.distanceTo( cameraRPos );
  16353. const projL = cameraL.projectionMatrix.elements;
  16354. const projR = cameraR.projectionMatrix.elements;
  16355. // VR systems will have identical far and near planes, and
  16356. // most likely identical top and bottom frustum extents.
  16357. // Use the left camera for these values.
  16358. const near = projL[ 14 ] / ( projL[ 10 ] - 1 );
  16359. const far = projL[ 14 ] / ( projL[ 10 ] + 1 );
  16360. const topFov = ( projL[ 9 ] + 1 ) / projL[ 5 ];
  16361. const bottomFov = ( projL[ 9 ] - 1 ) / projL[ 5 ];
  16362. const leftFov = ( projL[ 8 ] - 1 ) / projL[ 0 ];
  16363. const rightFov = ( projR[ 8 ] + 1 ) / projR[ 0 ];
  16364. const left = near * leftFov;
  16365. const right = near * rightFov;
  16366. // Calculate the new camera's position offset from the
  16367. // left camera. xOffset should be roughly half `ipd`.
  16368. const zOffset = ipd / ( - leftFov + rightFov );
  16369. const xOffset = zOffset * - leftFov;
  16370. // TODO: Better way to apply this offset?
  16371. cameraL.matrixWorld.decompose( camera.position, camera.quaternion, camera.scale );
  16372. camera.translateX( xOffset );
  16373. camera.translateZ( zOffset );
  16374. camera.matrixWorld.compose( camera.position, camera.quaternion, camera.scale );
  16375. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  16376. // Find the union of the frustum values of the cameras and scale
  16377. // the values so that the near plane's position does not change in world space,
  16378. // although must now be relative to the new union camera.
  16379. const near2 = near + zOffset;
  16380. const far2 = far + zOffset;
  16381. const left2 = left - xOffset;
  16382. const right2 = right + ( ipd - xOffset );
  16383. const top2 = topFov * far / far2 * near2;
  16384. const bottom2 = bottomFov * far / far2 * near2;
  16385. camera.projectionMatrix.makePerspective( left2, right2, top2, bottom2, near2, far2 );
  16386. camera.projectionMatrixInverse.copy( camera.projectionMatrix ).invert();
  16387. }
  16388. function updateCamera( camera, parent ) {
  16389. if ( parent === null ) {
  16390. camera.matrixWorld.copy( camera.matrix );
  16391. } else {
  16392. camera.matrixWorld.multiplyMatrices( parent.matrixWorld, camera.matrix );
  16393. }
  16394. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  16395. }
  16396. this.updateCamera = function ( camera ) {
  16397. if ( session === null ) return;
  16398. if ( depthSensing.texture !== null ) {
  16399. camera.near = depthSensing.depthNear;
  16400. camera.far = depthSensing.depthFar;
  16401. }
  16402. cameraXR.near = cameraR.near = cameraL.near = camera.near;
  16403. cameraXR.far = cameraR.far = cameraL.far = camera.far;
  16404. if ( _currentDepthNear !== cameraXR.near || _currentDepthFar !== cameraXR.far ) {
  16405. // Note that the new renderState won't apply until the next frame. See #18320
  16406. session.updateRenderState( {
  16407. depthNear: cameraXR.near,
  16408. depthFar: cameraXR.far
  16409. } );
  16410. _currentDepthNear = cameraXR.near;
  16411. _currentDepthFar = cameraXR.far;
  16412. cameraL.near = _currentDepthNear;
  16413. cameraL.far = _currentDepthFar;
  16414. cameraR.near = _currentDepthNear;
  16415. cameraR.far = _currentDepthFar;
  16416. cameraL.updateProjectionMatrix();
  16417. cameraR.updateProjectionMatrix();
  16418. camera.updateProjectionMatrix();
  16419. }
  16420. const parent = camera.parent;
  16421. const cameras = cameraXR.cameras;
  16422. updateCamera( cameraXR, parent );
  16423. for ( let i = 0; i < cameras.length; i ++ ) {
  16424. updateCamera( cameras[ i ], parent );
  16425. }
  16426. // update projection matrix for proper view frustum culling
  16427. if ( cameras.length === 2 ) {
  16428. setProjectionFromUnion( cameraXR, cameraL, cameraR );
  16429. } else {
  16430. // assume single camera setup (AR)
  16431. cameraXR.projectionMatrix.copy( cameraL.projectionMatrix );
  16432. }
  16433. // update user camera and its children
  16434. updateUserCamera( camera, cameraXR, parent );
  16435. };
  16436. function updateUserCamera( camera, cameraXR, parent ) {
  16437. if ( parent === null ) {
  16438. camera.matrix.copy( cameraXR.matrixWorld );
  16439. } else {
  16440. camera.matrix.copy( parent.matrixWorld );
  16441. camera.matrix.invert();
  16442. camera.matrix.multiply( cameraXR.matrixWorld );
  16443. }
  16444. camera.matrix.decompose( camera.position, camera.quaternion, camera.scale );
  16445. camera.updateMatrixWorld( true );
  16446. camera.projectionMatrix.copy( cameraXR.projectionMatrix );
  16447. camera.projectionMatrixInverse.copy( cameraXR.projectionMatrixInverse );
  16448. if ( camera.isPerspectiveCamera ) {
  16449. camera.fov = RAD2DEG * 2 * Math.atan( 1 / camera.projectionMatrix.elements[ 5 ] );
  16450. camera.zoom = 1;
  16451. }
  16452. }
  16453. this.getCamera = function () {
  16454. return cameraXR;
  16455. };
  16456. this.getFoveation = function () {
  16457. if ( glProjLayer === null && glBaseLayer === null ) {
  16458. return undefined;
  16459. }
  16460. return foveation;
  16461. };
  16462. this.setFoveation = function ( value ) {
  16463. // 0 = no foveation = full resolution
  16464. // 1 = maximum foveation = the edges render at lower resolution
  16465. foveation = value;
  16466. if ( glProjLayer !== null ) {
  16467. glProjLayer.fixedFoveation = value;
  16468. }
  16469. if ( glBaseLayer !== null && glBaseLayer.fixedFoveation !== undefined ) {
  16470. glBaseLayer.fixedFoveation = value;
  16471. }
  16472. };
  16473. this.hasDepthSensing = function () {
  16474. return depthSensing.texture !== null;
  16475. };
  16476. // Animation Loop
  16477. let onAnimationFrameCallback = null;
  16478. function onAnimationFrame( time, frame ) {
  16479. pose = frame.getViewerPose( customReferenceSpace || referenceSpace );
  16480. xrFrame = frame;
  16481. if ( pose !== null ) {
  16482. const views = pose.views;
  16483. if ( glBaseLayer !== null ) {
  16484. renderer.setRenderTargetFramebuffer( newRenderTarget, glBaseLayer.framebuffer );
  16485. renderer.setRenderTarget( newRenderTarget );
  16486. }
  16487. let cameraXRNeedsUpdate = false;
  16488. // check if it's necessary to rebuild cameraXR's camera list
  16489. if ( views.length !== cameraXR.cameras.length ) {
  16490. cameraXR.cameras.length = 0;
  16491. cameraXRNeedsUpdate = true;
  16492. }
  16493. for ( let i = 0; i < views.length; i ++ ) {
  16494. const view = views[ i ];
  16495. let viewport = null;
  16496. if ( glBaseLayer !== null ) {
  16497. viewport = glBaseLayer.getViewport( view );
  16498. } else {
  16499. const glSubImage = glBinding.getViewSubImage( glProjLayer, view );
  16500. viewport = glSubImage.viewport;
  16501. // For side-by-side projection, we only produce a single texture for both eyes.
  16502. if ( i === 0 ) {
  16503. renderer.setRenderTargetTextures(
  16504. newRenderTarget,
  16505. glSubImage.colorTexture,
  16506. glProjLayer.ignoreDepthValues ? undefined : glSubImage.depthStencilTexture );
  16507. renderer.setRenderTarget( newRenderTarget );
  16508. }
  16509. }
  16510. let camera = cameras[ i ];
  16511. if ( camera === undefined ) {
  16512. camera = new PerspectiveCamera();
  16513. camera.layers.enable( i );
  16514. camera.viewport = new Vector4();
  16515. cameras[ i ] = camera;
  16516. }
  16517. camera.matrix.fromArray( view.transform.matrix );
  16518. camera.matrix.decompose( camera.position, camera.quaternion, camera.scale );
  16519. camera.projectionMatrix.fromArray( view.projectionMatrix );
  16520. camera.projectionMatrixInverse.copy( camera.projectionMatrix ).invert();
  16521. camera.viewport.set( viewport.x, viewport.y, viewport.width, viewport.height );
  16522. if ( i === 0 ) {
  16523. cameraXR.matrix.copy( camera.matrix );
  16524. cameraXR.matrix.decompose( cameraXR.position, cameraXR.quaternion, cameraXR.scale );
  16525. }
  16526. if ( cameraXRNeedsUpdate === true ) {
  16527. cameraXR.cameras.push( camera );
  16528. }
  16529. }
  16530. //
  16531. const enabledFeatures = session.enabledFeatures;
  16532. if ( enabledFeatures && enabledFeatures.includes( 'depth-sensing' ) ) {
  16533. const depthData = glBinding.getDepthInformation( views[ 0 ] );
  16534. if ( depthData && depthData.isValid && depthData.texture ) {
  16535. depthSensing.init( renderer, depthData, session.renderState );
  16536. }
  16537. }
  16538. }
  16539. //
  16540. for ( let i = 0; i < controllers.length; i ++ ) {
  16541. const inputSource = controllerInputSources[ i ];
  16542. const controller = controllers[ i ];
  16543. if ( inputSource !== null && controller !== undefined ) {
  16544. controller.update( inputSource, frame, customReferenceSpace || referenceSpace );
  16545. }
  16546. }
  16547. depthSensing.render( renderer, cameraXR );
  16548. if ( onAnimationFrameCallback ) onAnimationFrameCallback( time, frame );
  16549. if ( frame.detectedPlanes ) {
  16550. scope.dispatchEvent( { type: 'planesdetected', data: frame } );
  16551. }
  16552. xrFrame = null;
  16553. }
  16554. const animation = new WebGLAnimation();
  16555. animation.setAnimationLoop( onAnimationFrame );
  16556. this.setAnimationLoop = function ( callback ) {
  16557. onAnimationFrameCallback = callback;
  16558. };
  16559. this.dispose = function () {};
  16560. }
  16561. }
  16562. function WebGLMaterials( renderer, properties ) {
  16563. function refreshTransformUniform( map, uniform ) {
  16564. if ( map.matrixAutoUpdate === true ) {
  16565. map.updateMatrix();
  16566. }
  16567. uniform.value.copy( map.matrix );
  16568. }
  16569. function refreshFogUniforms( uniforms, fog ) {
  16570. fog.color.getRGB( uniforms.fogColor.value, getUnlitUniformColorSpace( renderer ) );
  16571. if ( fog.isFog ) {
  16572. uniforms.fogNear.value = fog.near;
  16573. uniforms.fogFar.value = fog.far;
  16574. } else if ( fog.isFogExp2 ) {
  16575. uniforms.fogDensity.value = fog.density;
  16576. }
  16577. }
  16578. function refreshMaterialUniforms( uniforms, material, pixelRatio, height, transmissionRenderTarget ) {
  16579. if ( material.isMeshBasicMaterial ) {
  16580. refreshUniformsCommon( uniforms, material );
  16581. } else if ( material.isMeshLambertMaterial ) {
  16582. refreshUniformsCommon( uniforms, material );
  16583. } else if ( material.isMeshToonMaterial ) {
  16584. refreshUniformsCommon( uniforms, material );
  16585. refreshUniformsToon( uniforms, material );
  16586. } else if ( material.isMeshPhongMaterial ) {
  16587. refreshUniformsCommon( uniforms, material );
  16588. refreshUniformsPhong( uniforms, material );
  16589. } else if ( material.isMeshStandardMaterial ) {
  16590. refreshUniformsCommon( uniforms, material );
  16591. refreshUniformsStandard( uniforms, material );
  16592. if ( material.isMeshPhysicalMaterial ) {
  16593. refreshUniformsPhysical( uniforms, material, transmissionRenderTarget );
  16594. }
  16595. } else if ( material.isMeshMatcapMaterial ) {
  16596. refreshUniformsCommon( uniforms, material );
  16597. refreshUniformsMatcap( uniforms, material );
  16598. } else if ( material.isMeshDepthMaterial ) {
  16599. refreshUniformsCommon( uniforms, material );
  16600. } else if ( material.isMeshDistanceMaterial ) {
  16601. refreshUniformsCommon( uniforms, material );
  16602. refreshUniformsDistance( uniforms, material );
  16603. } else if ( material.isMeshNormalMaterial ) {
  16604. refreshUniformsCommon( uniforms, material );
  16605. } else if ( material.isLineBasicMaterial ) {
  16606. refreshUniformsLine( uniforms, material );
  16607. if ( material.isLineDashedMaterial ) {
  16608. refreshUniformsDash( uniforms, material );
  16609. }
  16610. } else if ( material.isPointsMaterial ) {
  16611. refreshUniformsPoints( uniforms, material, pixelRatio, height );
  16612. } else if ( material.isSpriteMaterial ) {
  16613. refreshUniformsSprites( uniforms, material );
  16614. } else if ( material.isShadowMaterial ) {
  16615. uniforms.color.value.copy( material.color );
  16616. uniforms.opacity.value = material.opacity;
  16617. } else if ( material.isShaderMaterial ) {
  16618. material.uniformsNeedUpdate = false; // #15581
  16619. }
  16620. }
  16621. function refreshUniformsCommon( uniforms, material ) {
  16622. uniforms.opacity.value = material.opacity;
  16623. if ( material.color ) {
  16624. uniforms.diffuse.value.copy( material.color );
  16625. }
  16626. if ( material.emissive ) {
  16627. uniforms.emissive.value.copy( material.emissive ).multiplyScalar( material.emissiveIntensity );
  16628. }
  16629. if ( material.map ) {
  16630. uniforms.map.value = material.map;
  16631. refreshTransformUniform( material.map, uniforms.mapTransform );
  16632. }
  16633. if ( material.alphaMap ) {
  16634. uniforms.alphaMap.value = material.alphaMap;
  16635. refreshTransformUniform( material.alphaMap, uniforms.alphaMapTransform );
  16636. }
  16637. if ( material.bumpMap ) {
  16638. uniforms.bumpMap.value = material.bumpMap;
  16639. refreshTransformUniform( material.bumpMap, uniforms.bumpMapTransform );
  16640. uniforms.bumpScale.value = material.bumpScale;
  16641. if ( material.side === BackSide ) {
  16642. uniforms.bumpScale.value *= - 1;
  16643. }
  16644. }
  16645. if ( material.normalMap ) {
  16646. uniforms.normalMap.value = material.normalMap;
  16647. refreshTransformUniform( material.normalMap, uniforms.normalMapTransform );
  16648. uniforms.normalScale.value.copy( material.normalScale );
  16649. if ( material.side === BackSide ) {
  16650. uniforms.normalScale.value.negate();
  16651. }
  16652. }
  16653. if ( material.displacementMap ) {
  16654. uniforms.displacementMap.value = material.displacementMap;
  16655. refreshTransformUniform( material.displacementMap, uniforms.displacementMapTransform );
  16656. uniforms.displacementScale.value = material.displacementScale;
  16657. uniforms.displacementBias.value = material.displacementBias;
  16658. }
  16659. if ( material.emissiveMap ) {
  16660. uniforms.emissiveMap.value = material.emissiveMap;
  16661. refreshTransformUniform( material.emissiveMap, uniforms.emissiveMapTransform );
  16662. }
  16663. if ( material.specularMap ) {
  16664. uniforms.specularMap.value = material.specularMap;
  16665. refreshTransformUniform( material.specularMap, uniforms.specularMapTransform );
  16666. }
  16667. if ( material.alphaTest > 0 ) {
  16668. uniforms.alphaTest.value = material.alphaTest;
  16669. }
  16670. const envMap = properties.get( material ).envMap;
  16671. if ( envMap ) {
  16672. uniforms.envMap.value = envMap;
  16673. uniforms.flipEnvMap.value = ( envMap.isCubeTexture && envMap.isRenderTargetTexture === false ) ? - 1 : 1;
  16674. uniforms.reflectivity.value = material.reflectivity;
  16675. uniforms.ior.value = material.ior;
  16676. uniforms.refractionRatio.value = material.refractionRatio;
  16677. }
  16678. if ( material.lightMap ) {
  16679. uniforms.lightMap.value = material.lightMap;
  16680. // artist-friendly light intensity scaling factor
  16681. const scaleFactor = ( renderer._useLegacyLights === true ) ? Math.PI : 1;
  16682. uniforms.lightMapIntensity.value = material.lightMapIntensity * scaleFactor;
  16683. refreshTransformUniform( material.lightMap, uniforms.lightMapTransform );
  16684. }
  16685. if ( material.aoMap ) {
  16686. uniforms.aoMap.value = material.aoMap;
  16687. uniforms.aoMapIntensity.value = material.aoMapIntensity;
  16688. refreshTransformUniform( material.aoMap, uniforms.aoMapTransform );
  16689. }
  16690. }
  16691. function refreshUniformsLine( uniforms, material ) {
  16692. uniforms.diffuse.value.copy( material.color );
  16693. uniforms.opacity.value = material.opacity;
  16694. if ( material.map ) {
  16695. uniforms.map.value = material.map;
  16696. refreshTransformUniform( material.map, uniforms.mapTransform );
  16697. }
  16698. }
  16699. function refreshUniformsDash( uniforms, material ) {
  16700. uniforms.dashSize.value = material.dashSize;
  16701. uniforms.totalSize.value = material.dashSize + material.gapSize;
  16702. uniforms.scale.value = material.scale;
  16703. }
  16704. function refreshUniformsPoints( uniforms, material, pixelRatio, height ) {
  16705. uniforms.diffuse.value.copy( material.color );
  16706. uniforms.opacity.value = material.opacity;
  16707. uniforms.size.value = material.size * pixelRatio;
  16708. uniforms.scale.value = height * 0.5;
  16709. if ( material.map ) {
  16710. uniforms.map.value = material.map;
  16711. refreshTransformUniform( material.map, uniforms.uvTransform );
  16712. }
  16713. if ( material.alphaMap ) {
  16714. uniforms.alphaMap.value = material.alphaMap;
  16715. refreshTransformUniform( material.alphaMap, uniforms.alphaMapTransform );
  16716. }
  16717. if ( material.alphaTest > 0 ) {
  16718. uniforms.alphaTest.value = material.alphaTest;
  16719. }
  16720. }
  16721. function refreshUniformsSprites( uniforms, material ) {
  16722. uniforms.diffuse.value.copy( material.color );
  16723. uniforms.opacity.value = material.opacity;
  16724. uniforms.rotation.value = material.rotation;
  16725. if ( material.map ) {
  16726. uniforms.map.value = material.map;
  16727. refreshTransformUniform( material.map, uniforms.mapTransform );
  16728. }
  16729. if ( material.alphaMap ) {
  16730. uniforms.alphaMap.value = material.alphaMap;
  16731. refreshTransformUniform( material.alphaMap, uniforms.alphaMapTransform );
  16732. }
  16733. if ( material.alphaTest > 0 ) {
  16734. uniforms.alphaTest.value = material.alphaTest;
  16735. }
  16736. }
  16737. function refreshUniformsPhong( uniforms, material ) {
  16738. uniforms.specular.value.copy( material.specular );
  16739. uniforms.shininess.value = Math.max( material.shininess, 1e-4 ); // to prevent pow( 0.0, 0.0 )
  16740. }
  16741. function refreshUniformsToon( uniforms, material ) {
  16742. if ( material.gradientMap ) {
  16743. uniforms.gradientMap.value = material.gradientMap;
  16744. }
  16745. }
  16746. function refreshUniformsStandard( uniforms, material ) {
  16747. uniforms.metalness.value = material.metalness;
  16748. if ( material.metalnessMap ) {
  16749. uniforms.metalnessMap.value = material.metalnessMap;
  16750. refreshTransformUniform( material.metalnessMap, uniforms.metalnessMapTransform );
  16751. }
  16752. uniforms.roughness.value = material.roughness;
  16753. if ( material.roughnessMap ) {
  16754. uniforms.roughnessMap.value = material.roughnessMap;
  16755. refreshTransformUniform( material.roughnessMap, uniforms.roughnessMapTransform );
  16756. }
  16757. const envMap = properties.get( material ).envMap;
  16758. if ( envMap ) {
  16759. //uniforms.envMap.value = material.envMap; // part of uniforms common
  16760. uniforms.envMapIntensity.value = material.envMapIntensity;
  16761. }
  16762. }
  16763. function refreshUniformsPhysical( uniforms, material, transmissionRenderTarget ) {
  16764. uniforms.ior.value = material.ior; // also part of uniforms common
  16765. if ( material.sheen > 0 ) {
  16766. uniforms.sheenColor.value.copy( material.sheenColor ).multiplyScalar( material.sheen );
  16767. uniforms.sheenRoughness.value = material.sheenRoughness;
  16768. if ( material.sheenColorMap ) {
  16769. uniforms.sheenColorMap.value = material.sheenColorMap;
  16770. refreshTransformUniform( material.sheenColorMap, uniforms.sheenColorMapTransform );
  16771. }
  16772. if ( material.sheenRoughnessMap ) {
  16773. uniforms.sheenRoughnessMap.value = material.sheenRoughnessMap;
  16774. refreshTransformUniform( material.sheenRoughnessMap, uniforms.sheenRoughnessMapTransform );
  16775. }
  16776. }
  16777. if ( material.clearcoat > 0 ) {
  16778. uniforms.clearcoat.value = material.clearcoat;
  16779. uniforms.clearcoatRoughness.value = material.clearcoatRoughness;
  16780. if ( material.clearcoatMap ) {
  16781. uniforms.clearcoatMap.value = material.clearcoatMap;
  16782. refreshTransformUniform( material.clearcoatMap, uniforms.clearcoatMapTransform );
  16783. }
  16784. if ( material.clearcoatRoughnessMap ) {
  16785. uniforms.clearcoatRoughnessMap.value = material.clearcoatRoughnessMap;
  16786. refreshTransformUniform( material.clearcoatRoughnessMap, uniforms.clearcoatRoughnessMapTransform );
  16787. }
  16788. if ( material.clearcoatNormalMap ) {
  16789. uniforms.clearcoatNormalMap.value = material.clearcoatNormalMap;
  16790. refreshTransformUniform( material.clearcoatNormalMap, uniforms.clearcoatNormalMapTransform );
  16791. uniforms.clearcoatNormalScale.value.copy( material.clearcoatNormalScale );
  16792. if ( material.side === BackSide ) {
  16793. uniforms.clearcoatNormalScale.value.negate();
  16794. }
  16795. }
  16796. }
  16797. if ( material.iridescence > 0 ) {
  16798. uniforms.iridescence.value = material.iridescence;
  16799. uniforms.iridescenceIOR.value = material.iridescenceIOR;
  16800. uniforms.iridescenceThicknessMinimum.value = material.iridescenceThicknessRange[ 0 ];
  16801. uniforms.iridescenceThicknessMaximum.value = material.iridescenceThicknessRange[ 1 ];
  16802. if ( material.iridescenceMap ) {
  16803. uniforms.iridescenceMap.value = material.iridescenceMap;
  16804. refreshTransformUniform( material.iridescenceMap, uniforms.iridescenceMapTransform );
  16805. }
  16806. if ( material.iridescenceThicknessMap ) {
  16807. uniforms.iridescenceThicknessMap.value = material.iridescenceThicknessMap;
  16808. refreshTransformUniform( material.iridescenceThicknessMap, uniforms.iridescenceThicknessMapTransform );
  16809. }
  16810. }
  16811. if ( material.transmission > 0 ) {
  16812. uniforms.transmission.value = material.transmission;
  16813. uniforms.transmissionSamplerMap.value = transmissionRenderTarget.texture;
  16814. uniforms.transmissionSamplerSize.value.set( transmissionRenderTarget.width, transmissionRenderTarget.height );
  16815. if ( material.transmissionMap ) {
  16816. uniforms.transmissionMap.value = material.transmissionMap;
  16817. refreshTransformUniform( material.transmissionMap, uniforms.transmissionMapTransform );
  16818. }
  16819. uniforms.thickness.value = material.thickness;
  16820. if ( material.thicknessMap ) {
  16821. uniforms.thicknessMap.value = material.thicknessMap;
  16822. refreshTransformUniform( material.thicknessMap, uniforms.thicknessMapTransform );
  16823. }
  16824. uniforms.attenuationDistance.value = material.attenuationDistance;
  16825. uniforms.attenuationColor.value.copy( material.attenuationColor );
  16826. }
  16827. if ( material.anisotropy > 0 ) {
  16828. uniforms.anisotropyVector.value.set( material.anisotropy * Math.cos( material.anisotropyRotation ), material.anisotropy * Math.sin( material.anisotropyRotation ) );
  16829. if ( material.anisotropyMap ) {
  16830. uniforms.anisotropyMap.value = material.anisotropyMap;
  16831. refreshTransformUniform( material.anisotropyMap, uniforms.anisotropyMapTransform );
  16832. }
  16833. }
  16834. uniforms.specularIntensity.value = material.specularIntensity;
  16835. uniforms.specularColor.value.copy( material.specularColor );
  16836. if ( material.specularColorMap ) {
  16837. uniforms.specularColorMap.value = material.specularColorMap;
  16838. refreshTransformUniform( material.specularColorMap, uniforms.specularColorMapTransform );
  16839. }
  16840. if ( material.specularIntensityMap ) {
  16841. uniforms.specularIntensityMap.value = material.specularIntensityMap;
  16842. refreshTransformUniform( material.specularIntensityMap, uniforms.specularIntensityMapTransform );
  16843. }
  16844. }
  16845. function refreshUniformsMatcap( uniforms, material ) {
  16846. if ( material.matcap ) {
  16847. uniforms.matcap.value = material.matcap;
  16848. }
  16849. }
  16850. function refreshUniformsDistance( uniforms, material ) {
  16851. const light = properties.get( material ).light;
  16852. uniforms.referencePosition.value.setFromMatrixPosition( light.matrixWorld );
  16853. uniforms.nearDistance.value = light.shadow.camera.near;
  16854. uniforms.farDistance.value = light.shadow.camera.far;
  16855. }
  16856. return {
  16857. refreshFogUniforms: refreshFogUniforms,
  16858. refreshMaterialUniforms: refreshMaterialUniforms
  16859. };
  16860. }
  16861. function WebGLUniformsGroups( gl, info, capabilities, state ) {
  16862. let buffers = {};
  16863. let updateList = {};
  16864. let allocatedBindingPoints = [];
  16865. const maxBindingPoints = ( capabilities.isWebGL2 ) ? gl.getParameter( gl.MAX_UNIFORM_BUFFER_BINDINGS ) : 0; // binding points are global whereas block indices are per shader program
  16866. function bind( uniformsGroup, program ) {
  16867. const webglProgram = program.program;
  16868. state.uniformBlockBinding( uniformsGroup, webglProgram );
  16869. }
  16870. function update( uniformsGroup, program ) {
  16871. let buffer = buffers[ uniformsGroup.id ];
  16872. if ( buffer === undefined ) {
  16873. prepareUniformsGroup( uniformsGroup );
  16874. buffer = createBuffer( uniformsGroup );
  16875. buffers[ uniformsGroup.id ] = buffer;
  16876. uniformsGroup.addEventListener( 'dispose', onUniformsGroupsDispose );
  16877. }
  16878. // ensure to update the binding points/block indices mapping for this program
  16879. const webglProgram = program.program;
  16880. state.updateUBOMapping( uniformsGroup, webglProgram );
  16881. // update UBO once per frame
  16882. const frame = info.render.frame;
  16883. if ( updateList[ uniformsGroup.id ] !== frame ) {
  16884. updateBufferData( uniformsGroup );
  16885. updateList[ uniformsGroup.id ] = frame;
  16886. }
  16887. }
  16888. function createBuffer( uniformsGroup ) {
  16889. // the setup of an UBO is independent of a particular shader program but global
  16890. const bindingPointIndex = allocateBindingPointIndex();
  16891. uniformsGroup.__bindingPointIndex = bindingPointIndex;
  16892. const buffer = gl.createBuffer();
  16893. const size = uniformsGroup.__size;
  16894. const usage = uniformsGroup.usage;
  16895. gl.bindBuffer( gl.UNIFORM_BUFFER, buffer );
  16896. gl.bufferData( gl.UNIFORM_BUFFER, size, usage );
  16897. gl.bindBuffer( gl.UNIFORM_BUFFER, null );
  16898. gl.bindBufferBase( gl.UNIFORM_BUFFER, bindingPointIndex, buffer );
  16899. return buffer;
  16900. }
  16901. function allocateBindingPointIndex() {
  16902. for ( let i = 0; i < maxBindingPoints; i ++ ) {
  16903. if ( allocatedBindingPoints.indexOf( i ) === - 1 ) {
  16904. allocatedBindingPoints.push( i );
  16905. return i;
  16906. }
  16907. }
  16908. console.error( 'THREE.WebGLRenderer: Maximum number of simultaneously usable uniforms groups reached.' );
  16909. return 0;
  16910. }
  16911. function updateBufferData( uniformsGroup ) {
  16912. const buffer = buffers[ uniformsGroup.id ];
  16913. const uniforms = uniformsGroup.uniforms;
  16914. const cache = uniformsGroup.__cache;
  16915. gl.bindBuffer( gl.UNIFORM_BUFFER, buffer );
  16916. for ( let i = 0, il = uniforms.length; i < il; i ++ ) {
  16917. const uniformArray = Array.isArray( uniforms[ i ] ) ? uniforms[ i ] : [ uniforms[ i ] ];
  16918. for ( let j = 0, jl = uniformArray.length; j < jl; j ++ ) {
  16919. const uniform = uniformArray[ j ];
  16920. if ( hasUniformChanged( uniform, i, j, cache ) === true ) {
  16921. const offset = uniform.__offset;
  16922. const values = Array.isArray( uniform.value ) ? uniform.value : [ uniform.value ];
  16923. let arrayOffset = 0;
  16924. for ( let k = 0; k < values.length; k ++ ) {
  16925. const value = values[ k ];
  16926. const info = getUniformSize( value );
  16927. // TODO add integer and struct support
  16928. if ( typeof value === 'number' || typeof value === 'boolean' ) {
  16929. uniform.__data[ 0 ] = value;
  16930. gl.bufferSubData( gl.UNIFORM_BUFFER, offset + arrayOffset, uniform.__data );
  16931. } else if ( value.isMatrix3 ) {
  16932. // manually converting 3x3 to 3x4
  16933. uniform.__data[ 0 ] = value.elements[ 0 ];
  16934. uniform.__data[ 1 ] = value.elements[ 1 ];
  16935. uniform.__data[ 2 ] = value.elements[ 2 ];
  16936. uniform.__data[ 3 ] = 0;
  16937. uniform.__data[ 4 ] = value.elements[ 3 ];
  16938. uniform.__data[ 5 ] = value.elements[ 4 ];
  16939. uniform.__data[ 6 ] = value.elements[ 5 ];
  16940. uniform.__data[ 7 ] = 0;
  16941. uniform.__data[ 8 ] = value.elements[ 6 ];
  16942. uniform.__data[ 9 ] = value.elements[ 7 ];
  16943. uniform.__data[ 10 ] = value.elements[ 8 ];
  16944. uniform.__data[ 11 ] = 0;
  16945. } else {
  16946. value.toArray( uniform.__data, arrayOffset );
  16947. arrayOffset += info.storage / Float32Array.BYTES_PER_ELEMENT;
  16948. }
  16949. }
  16950. gl.bufferSubData( gl.UNIFORM_BUFFER, offset, uniform.__data );
  16951. }
  16952. }
  16953. }
  16954. gl.bindBuffer( gl.UNIFORM_BUFFER, null );
  16955. }
  16956. function hasUniformChanged( uniform, index, indexArray, cache ) {
  16957. const value = uniform.value;
  16958. const indexString = index + '_' + indexArray;
  16959. if ( cache[ indexString ] === undefined ) {
  16960. // cache entry does not exist so far
  16961. if ( typeof value === 'number' || typeof value === 'boolean' ) {
  16962. cache[ indexString ] = value;
  16963. } else {
  16964. cache[ indexString ] = value.clone();
  16965. }
  16966. return true;
  16967. } else {
  16968. const cachedObject = cache[ indexString ];
  16969. // compare current value with cached entry
  16970. if ( typeof value === 'number' || typeof value === 'boolean' ) {
  16971. if ( cachedObject !== value ) {
  16972. cache[ indexString ] = value;
  16973. return true;
  16974. }
  16975. } else {
  16976. if ( cachedObject.equals( value ) === false ) {
  16977. cachedObject.copy( value );
  16978. return true;
  16979. }
  16980. }
  16981. }
  16982. return false;
  16983. }
  16984. function prepareUniformsGroup( uniformsGroup ) {
  16985. // determine total buffer size according to the STD140 layout
  16986. // Hint: STD140 is the only supported layout in WebGL 2
  16987. const uniforms = uniformsGroup.uniforms;
  16988. let offset = 0; // global buffer offset in bytes
  16989. const chunkSize = 16; // size of a chunk in bytes
  16990. for ( let i = 0, l = uniforms.length; i < l; i ++ ) {
  16991. const uniformArray = Array.isArray( uniforms[ i ] ) ? uniforms[ i ] : [ uniforms[ i ] ];
  16992. for ( let j = 0, jl = uniformArray.length; j < jl; j ++ ) {
  16993. const uniform = uniformArray[ j ];
  16994. const values = Array.isArray( uniform.value ) ? uniform.value : [ uniform.value ];
  16995. for ( let k = 0, kl = values.length; k < kl; k ++ ) {
  16996. const value = values[ k ];
  16997. const info = getUniformSize( value );
  16998. // Calculate the chunk offset
  16999. const chunkOffsetUniform = offset % chunkSize;
  17000. // Check for chunk overflow
  17001. if ( chunkOffsetUniform !== 0 && ( chunkSize - chunkOffsetUniform ) < info.boundary ) {
  17002. // Add padding and adjust offset
  17003. offset += ( chunkSize - chunkOffsetUniform );
  17004. }
  17005. // the following two properties will be used for partial buffer updates
  17006. uniform.__data = new Float32Array( info.storage / Float32Array.BYTES_PER_ELEMENT );
  17007. uniform.__offset = offset;
  17008. // Update the global offset
  17009. offset += info.storage;
  17010. }
  17011. }
  17012. }
  17013. // ensure correct final padding
  17014. const chunkOffset = offset % chunkSize;
  17015. if ( chunkOffset > 0 ) offset += ( chunkSize - chunkOffset );
  17016. //
  17017. uniformsGroup.__size = offset;
  17018. uniformsGroup.__cache = {};
  17019. return this;
  17020. }
  17021. function getUniformSize( value ) {
  17022. const info = {
  17023. boundary: 0, // bytes
  17024. storage: 0 // bytes
  17025. };
  17026. // determine sizes according to STD140
  17027. if ( typeof value === 'number' || typeof value === 'boolean' ) {
  17028. // float/int/bool
  17029. info.boundary = 4;
  17030. info.storage = 4;
  17031. } else if ( value.isVector2 ) {
  17032. // vec2
  17033. info.boundary = 8;
  17034. info.storage = 8;
  17035. } else if ( value.isVector3 || value.isColor ) {
  17036. // vec3
  17037. info.boundary = 16;
  17038. info.storage = 12; // evil: vec3 must start on a 16-byte boundary but it only consumes 12 bytes
  17039. } else if ( value.isVector4 ) {
  17040. // vec4
  17041. info.boundary = 16;
  17042. info.storage = 16;
  17043. } else if ( value.isMatrix3 ) {
  17044. // mat3 (in STD140 a 3x3 matrix is represented as 3x4)
  17045. info.boundary = 48;
  17046. info.storage = 48;
  17047. } else if ( value.isMatrix4 ) {
  17048. // mat4
  17049. info.boundary = 64;
  17050. info.storage = 64;
  17051. } else if ( value.isTexture ) {
  17052. console.warn( 'THREE.WebGLRenderer: Texture samplers can not be part of an uniforms group.' );
  17053. } else {
  17054. console.warn( 'THREE.WebGLRenderer: Unsupported uniform value type.', value );
  17055. }
  17056. return info;
  17057. }
  17058. function onUniformsGroupsDispose( event ) {
  17059. const uniformsGroup = event.target;
  17060. uniformsGroup.removeEventListener( 'dispose', onUniformsGroupsDispose );
  17061. const index = allocatedBindingPoints.indexOf( uniformsGroup.__bindingPointIndex );
  17062. allocatedBindingPoints.splice( index, 1 );
  17063. gl.deleteBuffer( buffers[ uniformsGroup.id ] );
  17064. delete buffers[ uniformsGroup.id ];
  17065. delete updateList[ uniformsGroup.id ];
  17066. }
  17067. function dispose() {
  17068. for ( const id in buffers ) {
  17069. gl.deleteBuffer( buffers[ id ] );
  17070. }
  17071. allocatedBindingPoints = [];
  17072. buffers = {};
  17073. updateList = {};
  17074. }
  17075. return {
  17076. bind: bind,
  17077. update: update,
  17078. dispose: dispose
  17079. };
  17080. }
  17081. class WebGLRenderer {
  17082. constructor( parameters = {} ) {
  17083. const {
  17084. canvas = createCanvasElement(),
  17085. context = null,
  17086. depth = true,
  17087. stencil = true,
  17088. alpha = false,
  17089. antialias = false,
  17090. premultipliedAlpha = true,
  17091. preserveDrawingBuffer = false,
  17092. powerPreference = 'default',
  17093. failIfMajorPerformanceCaveat = false,
  17094. } = parameters;
  17095. this.isWebGLRenderer = true;
  17096. let _alpha;
  17097. if ( context !== null ) {
  17098. _alpha = context.getContextAttributes().alpha;
  17099. } else {
  17100. _alpha = alpha;
  17101. }
  17102. const uintClearColor = new Uint32Array( 4 );
  17103. const intClearColor = new Int32Array( 4 );
  17104. let currentRenderList = null;
  17105. let currentRenderState = null;
  17106. // render() can be called from within a callback triggered by another render.
  17107. // We track this so that the nested render call gets its list and state isolated from the parent render call.
  17108. const renderListStack = [];
  17109. const renderStateStack = [];
  17110. // public properties
  17111. this.domElement = canvas;
  17112. // Debug configuration container
  17113. this.debug = {
  17114. /**
  17115. * Enables error checking and reporting when shader programs are being compiled
  17116. * @type {boolean}
  17117. */
  17118. checkShaderErrors: true,
  17119. /**
  17120. * Callback for custom error reporting.
  17121. * @type {?Function}
  17122. */
  17123. onShaderError: null
  17124. };
  17125. // clearing
  17126. this.autoClear = true;
  17127. this.autoClearColor = true;
  17128. this.autoClearDepth = true;
  17129. this.autoClearStencil = true;
  17130. // scene graph
  17131. this.sortObjects = true;
  17132. // user-defined clipping
  17133. this.clippingPlanes = [];
  17134. this.localClippingEnabled = false;
  17135. // physically based shading
  17136. this._outputColorSpace = SRGBColorSpace;
  17137. // physical lights
  17138. this._useLegacyLights = false;
  17139. // tone mapping
  17140. this.toneMapping = NoToneMapping;
  17141. this.toneMappingExposure = 1.0;
  17142. // internal properties
  17143. const _this = this;
  17144. let _isContextLost = false;
  17145. // internal state cache
  17146. let _currentActiveCubeFace = 0;
  17147. let _currentActiveMipmapLevel = 0;
  17148. let _currentRenderTarget = null;
  17149. let _currentMaterialId = - 1;
  17150. let _currentCamera = null;
  17151. const _currentViewport = new Vector4();
  17152. const _currentScissor = new Vector4();
  17153. let _currentScissorTest = null;
  17154. const _currentClearColor = new Color( 0x000000 );
  17155. let _currentClearAlpha = 0;
  17156. //
  17157. let _width = canvas.width;
  17158. let _height = canvas.height;
  17159. let _pixelRatio = 1;
  17160. let _opaqueSort = null;
  17161. let _transparentSort = null;
  17162. const _viewport = new Vector4( 0, 0, _width, _height );
  17163. const _scissor = new Vector4( 0, 0, _width, _height );
  17164. let _scissorTest = false;
  17165. // frustum
  17166. const _frustum = new Frustum();
  17167. // clipping
  17168. let _clippingEnabled = false;
  17169. let _localClippingEnabled = false;
  17170. // transmission
  17171. let _transmissionRenderTarget = null;
  17172. // camera matrices cache
  17173. const _projScreenMatrix = new Matrix4();
  17174. const _vector2 = new Vector2();
  17175. const _vector3 = new Vector3();
  17176. const _emptyScene = { background: null, fog: null, environment: null, overrideMaterial: null, isScene: true };
  17177. function getTargetPixelRatio() {
  17178. return _currentRenderTarget === null ? _pixelRatio : 1;
  17179. }
  17180. // initialize
  17181. let _gl = context;
  17182. function getContext( contextNames, contextAttributes ) {
  17183. for ( let i = 0; i < contextNames.length; i ++ ) {
  17184. const contextName = contextNames[ i ];
  17185. const context = canvas.getContext( contextName, contextAttributes );
  17186. if ( context !== null ) return context;
  17187. }
  17188. return null;
  17189. }
  17190. try {
  17191. const contextAttributes = {
  17192. alpha: true,
  17193. depth,
  17194. stencil,
  17195. antialias,
  17196. premultipliedAlpha,
  17197. preserveDrawingBuffer,
  17198. powerPreference,
  17199. failIfMajorPerformanceCaveat,
  17200. };
  17201. // OffscreenCanvas does not have setAttribute, see #22811
  17202. if ( 'setAttribute' in canvas ) canvas.setAttribute( 'data-engine', `three.js r${REVISION}` );
  17203. // event listeners must be registered before WebGL context is created, see #12753
  17204. canvas.addEventListener( 'webglcontextlost', onContextLost, false );
  17205. canvas.addEventListener( 'webglcontextrestored', onContextRestore, false );
  17206. canvas.addEventListener( 'webglcontextcreationerror', onContextCreationError, false );
  17207. if ( _gl === null ) {
  17208. const contextNames = [ 'webgl2', 'webgl', 'experimental-webgl' ];
  17209. if ( _this.isWebGL1Renderer === true ) {
  17210. contextNames.shift();
  17211. }
  17212. _gl = getContext( contextNames, contextAttributes );
  17213. if ( _gl === null ) {
  17214. if ( getContext( contextNames ) ) {
  17215. throw new Error( 'Error creating WebGL context with your selected attributes.' );
  17216. } else {
  17217. throw new Error( 'Error creating WebGL context.' );
  17218. }
  17219. }
  17220. }
  17221. if ( typeof WebGLRenderingContext !== 'undefined' && _gl instanceof WebGLRenderingContext ) { // @deprecated, r153
  17222. console.warn( 'THREE.WebGLRenderer: WebGL 1 support was deprecated in r153 and will be removed in r163.' );
  17223. }
  17224. // Some experimental-webgl implementations do not have getShaderPrecisionFormat
  17225. if ( _gl.getShaderPrecisionFormat === undefined ) {
  17226. _gl.getShaderPrecisionFormat = function () {
  17227. return { 'rangeMin': 1, 'rangeMax': 1, 'precision': 1 };
  17228. };
  17229. }
  17230. } catch ( error ) {
  17231. console.error( 'THREE.WebGLRenderer: ' + error.message );
  17232. throw error;
  17233. }
  17234. let extensions, capabilities, state, info;
  17235. let properties, textures, cubemaps, cubeuvmaps, attributes, geometries, objects;
  17236. let programCache, materials, renderLists, renderStates, clipping, shadowMap;
  17237. let background, morphtargets, bufferRenderer, indexedBufferRenderer;
  17238. let utils, bindingStates, uniformsGroups;
  17239. function initGLContext() {
  17240. extensions = new WebGLExtensions( _gl );
  17241. capabilities = new WebGLCapabilities( _gl, extensions, parameters );
  17242. extensions.init( capabilities );
  17243. utils = new WebGLUtils( _gl, extensions, capabilities );
  17244. state = new WebGLState( _gl, extensions, capabilities );
  17245. info = new WebGLInfo( _gl );
  17246. properties = new WebGLProperties();
  17247. textures = new WebGLTextures( _gl, extensions, state, properties, capabilities, utils, info );
  17248. cubemaps = new WebGLCubeMaps( _this );
  17249. cubeuvmaps = new WebGLCubeUVMaps( _this );
  17250. attributes = new WebGLAttributes( _gl, capabilities );
  17251. bindingStates = new WebGLBindingStates( _gl, extensions, attributes, capabilities );
  17252. geometries = new WebGLGeometries( _gl, attributes, info, bindingStates );
  17253. objects = new WebGLObjects( _gl, geometries, attributes, info );
  17254. morphtargets = new WebGLMorphtargets( _gl, capabilities, textures );
  17255. clipping = new WebGLClipping( properties );
  17256. programCache = new WebGLPrograms( _this, cubemaps, cubeuvmaps, extensions, capabilities, bindingStates, clipping );
  17257. materials = new WebGLMaterials( _this, properties );
  17258. renderLists = new WebGLRenderLists();
  17259. renderStates = new WebGLRenderStates( extensions, capabilities );
  17260. background = new WebGLBackground( _this, cubemaps, cubeuvmaps, state, objects, _alpha, premultipliedAlpha );
  17261. shadowMap = new WebGLShadowMap( _this, objects, capabilities );
  17262. uniformsGroups = new WebGLUniformsGroups( _gl, info, capabilities, state );
  17263. bufferRenderer = new WebGLBufferRenderer( _gl, extensions, info, capabilities );
  17264. indexedBufferRenderer = new WebGLIndexedBufferRenderer( _gl, extensions, info, capabilities );
  17265. info.programs = programCache.programs;
  17266. _this.capabilities = capabilities;
  17267. _this.extensions = extensions;
  17268. _this.properties = properties;
  17269. _this.renderLists = renderLists;
  17270. _this.shadowMap = shadowMap;
  17271. _this.state = state;
  17272. _this.info = info;
  17273. }
  17274. initGLContext();
  17275. // xr
  17276. const xr = new WebXRManager( _this, _gl );
  17277. this.xr = xr;
  17278. // API
  17279. this.getContext = function () {
  17280. return _gl;
  17281. };
  17282. this.getContextAttributes = function () {
  17283. return _gl.getContextAttributes();
  17284. };
  17285. this.forceContextLoss = function () {
  17286. const extension = extensions.get( 'WEBGL_lose_context' );
  17287. if ( extension ) extension.loseContext();
  17288. };
  17289. this.forceContextRestore = function () {
  17290. const extension = extensions.get( 'WEBGL_lose_context' );
  17291. if ( extension ) extension.restoreContext();
  17292. };
  17293. this.getPixelRatio = function () {
  17294. return _pixelRatio;
  17295. };
  17296. this.setPixelRatio = function ( value ) {
  17297. if ( value === undefined ) return;
  17298. _pixelRatio = value;
  17299. this.setSize( _width, _height, false );
  17300. };
  17301. this.getSize = function ( target ) {
  17302. return target.set( _width, _height );
  17303. };
  17304. this.setSize = function ( width, height, updateStyle = true ) {
  17305. if ( xr.isPresenting ) {
  17306. console.warn( 'THREE.WebGLRenderer: Can\'t change size while VR device is presenting.' );
  17307. return;
  17308. }
  17309. _width = width;
  17310. _height = height;
  17311. canvas.width = Math.floor( width * _pixelRatio );
  17312. canvas.height = Math.floor( height * _pixelRatio );
  17313. if ( updateStyle === true ) {
  17314. canvas.style.width = width + 'px';
  17315. canvas.style.height = height + 'px';
  17316. }
  17317. this.setViewport( 0, 0, width, height );
  17318. };
  17319. this.getDrawingBufferSize = function ( target ) {
  17320. return target.set( _width * _pixelRatio, _height * _pixelRatio ).floor();
  17321. };
  17322. this.setDrawingBufferSize = function ( width, height, pixelRatio ) {
  17323. _width = width;
  17324. _height = height;
  17325. _pixelRatio = pixelRatio;
  17326. canvas.width = Math.floor( width * pixelRatio );
  17327. canvas.height = Math.floor( height * pixelRatio );
  17328. this.setViewport( 0, 0, width, height );
  17329. };
  17330. this.getCurrentViewport = function ( target ) {
  17331. return target.copy( _currentViewport );
  17332. };
  17333. this.getViewport = function ( target ) {
  17334. return target.copy( _viewport );
  17335. };
  17336. this.setViewport = function ( x, y, width, height ) {
  17337. if ( x.isVector4 ) {
  17338. _viewport.set( x.x, x.y, x.z, x.w );
  17339. } else {
  17340. _viewport.set( x, y, width, height );
  17341. }
  17342. state.viewport( _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).round() );
  17343. };
  17344. this.getScissor = function ( target ) {
  17345. return target.copy( _scissor );
  17346. };
  17347. this.setScissor = function ( x, y, width, height ) {
  17348. if ( x.isVector4 ) {
  17349. _scissor.set( x.x, x.y, x.z, x.w );
  17350. } else {
  17351. _scissor.set( x, y, width, height );
  17352. }
  17353. state.scissor( _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).round() );
  17354. };
  17355. this.getScissorTest = function () {
  17356. return _scissorTest;
  17357. };
  17358. this.setScissorTest = function ( boolean ) {
  17359. state.setScissorTest( _scissorTest = boolean );
  17360. };
  17361. this.setOpaqueSort = function ( method ) {
  17362. _opaqueSort = method;
  17363. };
  17364. this.setTransparentSort = function ( method ) {
  17365. _transparentSort = method;
  17366. };
  17367. // Clearing
  17368. this.getClearColor = function ( target ) {
  17369. return target.copy( background.getClearColor() );
  17370. };
  17371. this.setClearColor = function () {
  17372. background.setClearColor.apply( background, arguments );
  17373. };
  17374. this.getClearAlpha = function () {
  17375. return background.getClearAlpha();
  17376. };
  17377. this.setClearAlpha = function () {
  17378. background.setClearAlpha.apply( background, arguments );
  17379. };
  17380. this.clear = function ( color = true, depth = true, stencil = true ) {
  17381. let bits = 0;
  17382. if ( color ) {
  17383. // check if we're trying to clear an integer target
  17384. let isIntegerFormat = false;
  17385. if ( _currentRenderTarget !== null ) {
  17386. const targetFormat = _currentRenderTarget.texture.format;
  17387. isIntegerFormat = targetFormat === RGBAIntegerFormat ||
  17388. targetFormat === RGIntegerFormat ||
  17389. targetFormat === RedIntegerFormat;
  17390. }
  17391. // use the appropriate clear functions to clear the target if it's a signed
  17392. // or unsigned integer target
  17393. if ( isIntegerFormat ) {
  17394. const targetType = _currentRenderTarget.texture.type;
  17395. const isUnsignedType = targetType === UnsignedByteType ||
  17396. targetType === UnsignedIntType ||
  17397. targetType === UnsignedShortType ||
  17398. targetType === UnsignedInt248Type ||
  17399. targetType === UnsignedShort4444Type ||
  17400. targetType === UnsignedShort5551Type;
  17401. const clearColor = background.getClearColor();
  17402. const a = background.getClearAlpha();
  17403. const r = clearColor.r;
  17404. const g = clearColor.g;
  17405. const b = clearColor.b;
  17406. if ( isUnsignedType ) {
  17407. uintClearColor[ 0 ] = r;
  17408. uintClearColor[ 1 ] = g;
  17409. uintClearColor[ 2 ] = b;
  17410. uintClearColor[ 3 ] = a;
  17411. _gl.clearBufferuiv( _gl.COLOR, 0, uintClearColor );
  17412. } else {
  17413. intClearColor[ 0 ] = r;
  17414. intClearColor[ 1 ] = g;
  17415. intClearColor[ 2 ] = b;
  17416. intClearColor[ 3 ] = a;
  17417. _gl.clearBufferiv( _gl.COLOR, 0, intClearColor );
  17418. }
  17419. } else {
  17420. bits |= _gl.COLOR_BUFFER_BIT;
  17421. }
  17422. }
  17423. if ( depth ) bits |= _gl.DEPTH_BUFFER_BIT;
  17424. if ( stencil ) {
  17425. bits |= _gl.STENCIL_BUFFER_BIT;
  17426. this.state.buffers.stencil.setMask( 0xffffffff );
  17427. }
  17428. _gl.clear( bits );
  17429. };
  17430. this.clearColor = function () {
  17431. this.clear( true, false, false );
  17432. };
  17433. this.clearDepth = function () {
  17434. this.clear( false, true, false );
  17435. };
  17436. this.clearStencil = function () {
  17437. this.clear( false, false, true );
  17438. };
  17439. //
  17440. this.dispose = function () {
  17441. canvas.removeEventListener( 'webglcontextlost', onContextLost, false );
  17442. canvas.removeEventListener( 'webglcontextrestored', onContextRestore, false );
  17443. canvas.removeEventListener( 'webglcontextcreationerror', onContextCreationError, false );
  17444. renderLists.dispose();
  17445. renderStates.dispose();
  17446. properties.dispose();
  17447. cubemaps.dispose();
  17448. cubeuvmaps.dispose();
  17449. objects.dispose();
  17450. bindingStates.dispose();
  17451. uniformsGroups.dispose();
  17452. programCache.dispose();
  17453. xr.dispose();
  17454. xr.removeEventListener( 'sessionstart', onXRSessionStart );
  17455. xr.removeEventListener( 'sessionend', onXRSessionEnd );
  17456. if ( _transmissionRenderTarget ) {
  17457. _transmissionRenderTarget.dispose();
  17458. _transmissionRenderTarget = null;
  17459. }
  17460. animation.stop();
  17461. };
  17462. // Events
  17463. function onContextLost( event ) {
  17464. event.preventDefault();
  17465. console.log( 'THREE.WebGLRenderer: Context Lost.' );
  17466. _isContextLost = true;
  17467. }
  17468. function onContextRestore( /* event */ ) {
  17469. console.log( 'THREE.WebGLRenderer: Context Restored.' );
  17470. _isContextLost = false;
  17471. const infoAutoReset = info.autoReset;
  17472. const shadowMapEnabled = shadowMap.enabled;
  17473. const shadowMapAutoUpdate = shadowMap.autoUpdate;
  17474. const shadowMapNeedsUpdate = shadowMap.needsUpdate;
  17475. const shadowMapType = shadowMap.type;
  17476. initGLContext();
  17477. info.autoReset = infoAutoReset;
  17478. shadowMap.enabled = shadowMapEnabled;
  17479. shadowMap.autoUpdate = shadowMapAutoUpdate;
  17480. shadowMap.needsUpdate = shadowMapNeedsUpdate;
  17481. shadowMap.type = shadowMapType;
  17482. }
  17483. function onContextCreationError( event ) {
  17484. console.error( 'THREE.WebGLRenderer: A WebGL context could not be created. Reason: ', event.statusMessage );
  17485. }
  17486. function onMaterialDispose( event ) {
  17487. const material = event.target;
  17488. material.removeEventListener( 'dispose', onMaterialDispose );
  17489. deallocateMaterial( material );
  17490. }
  17491. // Buffer deallocation
  17492. function deallocateMaterial( material ) {
  17493. releaseMaterialProgramReferences( material );
  17494. properties.remove( material );
  17495. }
  17496. function releaseMaterialProgramReferences( material ) {
  17497. const programs = properties.get( material ).programs;
  17498. if ( programs !== undefined ) {
  17499. programs.forEach( function ( program ) {
  17500. programCache.releaseProgram( program );
  17501. } );
  17502. if ( material.isShaderMaterial ) {
  17503. programCache.releaseShaderCache( material );
  17504. }
  17505. }
  17506. }
  17507. // Buffer rendering
  17508. this.renderBufferDirect = function ( camera, scene, geometry, material, object, group ) {
  17509. if ( scene === null ) scene = _emptyScene; // renderBufferDirect second parameter used to be fog (could be null)
  17510. const frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 );
  17511. const program = setProgram( camera, scene, geometry, material, object );
  17512. state.setMaterial( material, frontFaceCW );
  17513. //
  17514. let index = geometry.index;
  17515. let rangeFactor = 1;
  17516. if ( material.wireframe === true ) {
  17517. index = geometries.getWireframeAttribute( geometry );
  17518. if ( index === undefined ) return;
  17519. rangeFactor = 2;
  17520. }
  17521. //
  17522. const drawRange = geometry.drawRange;
  17523. const position = geometry.attributes.position;
  17524. let drawStart = drawRange.start * rangeFactor;
  17525. let drawEnd = ( drawRange.start + drawRange.count ) * rangeFactor;
  17526. if ( group !== null ) {
  17527. drawStart = Math.max( drawStart, group.start * rangeFactor );
  17528. drawEnd = Math.min( drawEnd, ( group.start + group.count ) * rangeFactor );
  17529. }
  17530. if ( index !== null ) {
  17531. drawStart = Math.max( drawStart, 0 );
  17532. drawEnd = Math.min( drawEnd, index.count );
  17533. } else if ( position !== undefined && position !== null ) {
  17534. drawStart = Math.max( drawStart, 0 );
  17535. drawEnd = Math.min( drawEnd, position.count );
  17536. }
  17537. const drawCount = drawEnd - drawStart;
  17538. if ( drawCount < 0 || drawCount === Infinity ) return;
  17539. //
  17540. bindingStates.setup( object, material, program, geometry, index );
  17541. let attribute;
  17542. let renderer = bufferRenderer;
  17543. if ( index !== null ) {
  17544. attribute = attributes.get( index );
  17545. renderer = indexedBufferRenderer;
  17546. renderer.setIndex( attribute );
  17547. }
  17548. //
  17549. if ( object.isMesh ) {
  17550. if ( material.wireframe === true ) {
  17551. state.setLineWidth( material.wireframeLinewidth * getTargetPixelRatio() );
  17552. renderer.setMode( _gl.LINES );
  17553. } else {
  17554. renderer.setMode( _gl.TRIANGLES );
  17555. }
  17556. } else if ( object.isLine ) {
  17557. let lineWidth = material.linewidth;
  17558. if ( lineWidth === undefined ) lineWidth = 1; // Not using Line*Material
  17559. state.setLineWidth( lineWidth * getTargetPixelRatio() );
  17560. if ( object.isLineSegments ) {
  17561. renderer.setMode( _gl.LINES );
  17562. } else if ( object.isLineLoop ) {
  17563. renderer.setMode( _gl.LINE_LOOP );
  17564. } else {
  17565. renderer.setMode( _gl.LINE_STRIP );
  17566. }
  17567. } else if ( object.isPoints ) {
  17568. renderer.setMode( _gl.POINTS );
  17569. } else if ( object.isSprite ) {
  17570. renderer.setMode( _gl.TRIANGLES );
  17571. }
  17572. if ( object.isBatchedMesh ) {
  17573. renderer.renderMultiDraw( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount );
  17574. } else if ( object.isInstancedMesh ) {
  17575. renderer.renderInstances( drawStart, drawCount, object.count );
  17576. } else if ( geometry.isInstancedBufferGeometry ) {
  17577. const maxInstanceCount = geometry._maxInstanceCount !== undefined ? geometry._maxInstanceCount : Infinity;
  17578. const instanceCount = Math.min( geometry.instanceCount, maxInstanceCount );
  17579. renderer.renderInstances( drawStart, drawCount, instanceCount );
  17580. } else {
  17581. renderer.render( drawStart, drawCount );
  17582. }
  17583. };
  17584. // Compile
  17585. function prepareMaterial( material, scene, object ) {
  17586. if ( material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false ) {
  17587. material.side = BackSide;
  17588. material.needsUpdate = true;
  17589. getProgram( material, scene, object );
  17590. material.side = FrontSide;
  17591. material.needsUpdate = true;
  17592. getProgram( material, scene, object );
  17593. material.side = DoubleSide;
  17594. } else {
  17595. getProgram( material, scene, object );
  17596. }
  17597. }
  17598. this.compile = function ( scene, camera, targetScene = null ) {
  17599. if ( targetScene === null ) targetScene = scene;
  17600. currentRenderState = renderStates.get( targetScene );
  17601. currentRenderState.init();
  17602. renderStateStack.push( currentRenderState );
  17603. // gather lights from both the target scene and the new object that will be added to the scene.
  17604. targetScene.traverseVisible( function ( object ) {
  17605. if ( object.isLight && object.layers.test( camera.layers ) ) {
  17606. currentRenderState.pushLight( object );
  17607. if ( object.castShadow ) {
  17608. currentRenderState.pushShadow( object );
  17609. }
  17610. }
  17611. } );
  17612. if ( scene !== targetScene ) {
  17613. scene.traverseVisible( function ( object ) {
  17614. if ( object.isLight && object.layers.test( camera.layers ) ) {
  17615. currentRenderState.pushLight( object );
  17616. if ( object.castShadow ) {
  17617. currentRenderState.pushShadow( object );
  17618. }
  17619. }
  17620. } );
  17621. }
  17622. currentRenderState.setupLights( _this._useLegacyLights );
  17623. // Only initialize materials in the new scene, not the targetScene.
  17624. const materials = new Set();
  17625. scene.traverse( function ( object ) {
  17626. const material = object.material;
  17627. if ( material ) {
  17628. if ( Array.isArray( material ) ) {
  17629. for ( let i = 0; i < material.length; i ++ ) {
  17630. const material2 = material[ i ];
  17631. prepareMaterial( material2, targetScene, object );
  17632. materials.add( material2 );
  17633. }
  17634. } else {
  17635. prepareMaterial( material, targetScene, object );
  17636. materials.add( material );
  17637. }
  17638. }
  17639. } );
  17640. renderStateStack.pop();
  17641. currentRenderState = null;
  17642. return materials;
  17643. };
  17644. // compileAsync
  17645. this.compileAsync = function ( scene, camera, targetScene = null ) {
  17646. const materials = this.compile( scene, camera, targetScene );
  17647. // Wait for all the materials in the new object to indicate that they're
  17648. // ready to be used before resolving the promise.
  17649. return new Promise( ( resolve ) => {
  17650. function checkMaterialsReady() {
  17651. materials.forEach( function ( material ) {
  17652. const materialProperties = properties.get( material );
  17653. const program = materialProperties.currentProgram;
  17654. if ( program.isReady() ) {
  17655. // remove any programs that report they're ready to use from the list
  17656. materials.delete( material );
  17657. }
  17658. } );
  17659. // once the list of compiling materials is empty, call the callback
  17660. if ( materials.size === 0 ) {
  17661. resolve( scene );
  17662. return;
  17663. }
  17664. // if some materials are still not ready, wait a bit and check again
  17665. setTimeout( checkMaterialsReady, 10 );
  17666. }
  17667. if ( extensions.get( 'KHR_parallel_shader_compile' ) !== null ) {
  17668. // If we can check the compilation status of the materials without
  17669. // blocking then do so right away.
  17670. checkMaterialsReady();
  17671. } else {
  17672. // Otherwise start by waiting a bit to give the materials we just
  17673. // initialized a chance to finish.
  17674. setTimeout( checkMaterialsReady, 10 );
  17675. }
  17676. } );
  17677. };
  17678. // Animation Loop
  17679. let onAnimationFrameCallback = null;
  17680. function onAnimationFrame( time ) {
  17681. if ( onAnimationFrameCallback ) onAnimationFrameCallback( time );
  17682. }
  17683. function onXRSessionStart() {
  17684. animation.stop();
  17685. }
  17686. function onXRSessionEnd() {
  17687. animation.start();
  17688. }
  17689. const animation = new WebGLAnimation();
  17690. animation.setAnimationLoop( onAnimationFrame );
  17691. if ( typeof self !== 'undefined' ) animation.setContext( self );
  17692. this.setAnimationLoop = function ( callback ) {
  17693. onAnimationFrameCallback = callback;
  17694. xr.setAnimationLoop( callback );
  17695. ( callback === null ) ? animation.stop() : animation.start();
  17696. };
  17697. xr.addEventListener( 'sessionstart', onXRSessionStart );
  17698. xr.addEventListener( 'sessionend', onXRSessionEnd );
  17699. // Rendering
  17700. this.render = function ( scene, camera ) {
  17701. if ( camera !== undefined && camera.isCamera !== true ) {
  17702. console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
  17703. return;
  17704. }
  17705. if ( _isContextLost === true ) return;
  17706. // update scene graph
  17707. if ( scene.matrixWorldAutoUpdate === true ) scene.updateMatrixWorld();
  17708. // update camera matrices and frustum
  17709. if ( camera.parent === null && camera.matrixWorldAutoUpdate === true ) camera.updateMatrixWorld();
  17710. if ( xr.enabled === true && xr.isPresenting === true ) {
  17711. if ( xr.cameraAutoUpdate === true ) xr.updateCamera( camera );
  17712. camera = xr.getCamera(); // use XR camera for rendering
  17713. }
  17714. //
  17715. if ( scene.isScene === true ) scene.onBeforeRender( _this, scene, camera, _currentRenderTarget );
  17716. currentRenderState = renderStates.get( scene, renderStateStack.length );
  17717. currentRenderState.init();
  17718. renderStateStack.push( currentRenderState );
  17719. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  17720. _frustum.setFromProjectionMatrix( _projScreenMatrix );
  17721. _localClippingEnabled = this.localClippingEnabled;
  17722. _clippingEnabled = clipping.init( this.clippingPlanes, _localClippingEnabled );
  17723. currentRenderList = renderLists.get( scene, renderListStack.length );
  17724. currentRenderList.init();
  17725. renderListStack.push( currentRenderList );
  17726. projectObject( scene, camera, 0, _this.sortObjects );
  17727. currentRenderList.finish();
  17728. if ( _this.sortObjects === true ) {
  17729. currentRenderList.sort( _opaqueSort, _transparentSort );
  17730. }
  17731. //
  17732. this.info.render.frame ++;
  17733. if ( _clippingEnabled === true ) clipping.beginShadows();
  17734. const shadowsArray = currentRenderState.state.shadowsArray;
  17735. shadowMap.render( shadowsArray, scene, camera );
  17736. if ( _clippingEnabled === true ) clipping.endShadows();
  17737. //
  17738. if ( this.info.autoReset === true ) this.info.reset();
  17739. //
  17740. if ( xr.enabled === false || xr.isPresenting === false || xr.hasDepthSensing() === false ) {
  17741. background.render( currentRenderList, scene );
  17742. }
  17743. // render scene
  17744. currentRenderState.setupLights( _this._useLegacyLights );
  17745. if ( camera.isArrayCamera ) {
  17746. const cameras = camera.cameras;
  17747. for ( let i = 0, l = cameras.length; i < l; i ++ ) {
  17748. const camera2 = cameras[ i ];
  17749. renderScene( currentRenderList, scene, camera2, camera2.viewport );
  17750. }
  17751. } else {
  17752. renderScene( currentRenderList, scene, camera );
  17753. }
  17754. //
  17755. if ( _currentRenderTarget !== null ) {
  17756. // resolve multisample renderbuffers to a single-sample texture if necessary
  17757. textures.updateMultisampleRenderTarget( _currentRenderTarget );
  17758. // Generate mipmap if we're using any kind of mipmap filtering
  17759. textures.updateRenderTargetMipmap( _currentRenderTarget );
  17760. }
  17761. //
  17762. if ( scene.isScene === true ) scene.onAfterRender( _this, scene, camera );
  17763. // _gl.finish();
  17764. bindingStates.resetDefaultState();
  17765. _currentMaterialId = - 1;
  17766. _currentCamera = null;
  17767. renderStateStack.pop();
  17768. if ( renderStateStack.length > 0 ) {
  17769. currentRenderState = renderStateStack[ renderStateStack.length - 1 ];
  17770. } else {
  17771. currentRenderState = null;
  17772. }
  17773. renderListStack.pop();
  17774. if ( renderListStack.length > 0 ) {
  17775. currentRenderList = renderListStack[ renderListStack.length - 1 ];
  17776. } else {
  17777. currentRenderList = null;
  17778. }
  17779. };
  17780. function projectObject( object, camera, groupOrder, sortObjects ) {
  17781. if ( object.visible === false ) return;
  17782. const visible = object.layers.test( camera.layers );
  17783. if ( visible ) {
  17784. if ( object.isGroup ) {
  17785. groupOrder = object.renderOrder;
  17786. } else if ( object.isLOD ) {
  17787. if ( object.autoUpdate === true ) object.update( camera );
  17788. } else if ( object.isLight ) {
  17789. currentRenderState.pushLight( object );
  17790. if ( object.castShadow ) {
  17791. currentRenderState.pushShadow( object );
  17792. }
  17793. } else if ( object.isSprite ) {
  17794. if ( ! object.frustumCulled || _frustum.intersectsSprite( object ) ) {
  17795. if ( sortObjects ) {
  17796. _vector3.setFromMatrixPosition( object.matrixWorld )
  17797. .applyMatrix4( _projScreenMatrix );
  17798. }
  17799. const geometry = objects.update( object );
  17800. const material = object.material;
  17801. if ( material.visible ) {
  17802. currentRenderList.push( object, geometry, material, groupOrder, _vector3.z, null );
  17803. }
  17804. }
  17805. } else if ( object.isMesh || object.isLine || object.isPoints ) {
  17806. if ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) {
  17807. const geometry = objects.update( object );
  17808. const material = object.material;
  17809. if ( sortObjects ) {
  17810. if ( object.boundingSphere !== undefined ) {
  17811. if ( object.boundingSphere === null ) object.computeBoundingSphere();
  17812. _vector3.copy( object.boundingSphere.center );
  17813. } else {
  17814. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  17815. _vector3.copy( geometry.boundingSphere.center );
  17816. }
  17817. _vector3
  17818. .applyMatrix4( object.matrixWorld )
  17819. .applyMatrix4( _projScreenMatrix );
  17820. }
  17821. if ( Array.isArray( material ) ) {
  17822. const groups = geometry.groups;
  17823. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  17824. const group = groups[ i ];
  17825. const groupMaterial = material[ group.materialIndex ];
  17826. if ( groupMaterial && groupMaterial.visible ) {
  17827. currentRenderList.push( object, geometry, groupMaterial, groupOrder, _vector3.z, group );
  17828. }
  17829. }
  17830. } else if ( material.visible ) {
  17831. currentRenderList.push( object, geometry, material, groupOrder, _vector3.z, null );
  17832. }
  17833. }
  17834. }
  17835. }
  17836. const children = object.children;
  17837. for ( let i = 0, l = children.length; i < l; i ++ ) {
  17838. projectObject( children[ i ], camera, groupOrder, sortObjects );
  17839. }
  17840. }
  17841. function renderScene( currentRenderList, scene, camera, viewport ) {
  17842. const opaqueObjects = currentRenderList.opaque;
  17843. const transmissiveObjects = currentRenderList.transmissive;
  17844. const transparentObjects = currentRenderList.transparent;
  17845. currentRenderState.setupLightsView( camera );
  17846. if ( _clippingEnabled === true ) clipping.setGlobalState( _this.clippingPlanes, camera );
  17847. if ( transmissiveObjects.length > 0 ) renderTransmissionPass( opaqueObjects, transmissiveObjects, scene, camera );
  17848. if ( viewport ) state.viewport( _currentViewport.copy( viewport ) );
  17849. if ( opaqueObjects.length > 0 ) renderObjects( opaqueObjects, scene, camera );
  17850. if ( transmissiveObjects.length > 0 ) renderObjects( transmissiveObjects, scene, camera );
  17851. if ( transparentObjects.length > 0 ) renderObjects( transparentObjects, scene, camera );
  17852. // Ensure depth buffer writing is enabled so it can be cleared on next render
  17853. state.buffers.depth.setTest( true );
  17854. state.buffers.depth.setMask( true );
  17855. state.buffers.color.setMask( true );
  17856. state.setPolygonOffset( false );
  17857. }
  17858. function renderTransmissionPass( opaqueObjects, transmissiveObjects, scene, camera ) {
  17859. const overrideMaterial = scene.isScene === true ? scene.overrideMaterial : null;
  17860. if ( overrideMaterial !== null ) {
  17861. return;
  17862. }
  17863. const isWebGL2 = capabilities.isWebGL2;
  17864. if ( _transmissionRenderTarget === null ) {
  17865. _transmissionRenderTarget = new WebGLRenderTarget( 1, 1, {
  17866. generateMipmaps: true,
  17867. type: extensions.has( 'EXT_color_buffer_half_float' ) ? HalfFloatType : UnsignedByteType,
  17868. minFilter: LinearMipmapLinearFilter,
  17869. samples: ( isWebGL2 ) ? 4 : 0
  17870. } );
  17871. // debug
  17872. /*
  17873. const geometry = new PlaneGeometry();
  17874. const material = new MeshBasicMaterial( { map: _transmissionRenderTarget.texture } );
  17875. const mesh = new Mesh( geometry, material );
  17876. scene.add( mesh );
  17877. */
  17878. }
  17879. _this.getDrawingBufferSize( _vector2 );
  17880. if ( isWebGL2 ) {
  17881. _transmissionRenderTarget.setSize( _vector2.x, _vector2.y );
  17882. } else {
  17883. _transmissionRenderTarget.setSize( floorPowerOfTwo( _vector2.x ), floorPowerOfTwo( _vector2.y ) );
  17884. }
  17885. //
  17886. const currentRenderTarget = _this.getRenderTarget();
  17887. _this.setRenderTarget( _transmissionRenderTarget );
  17888. _this.getClearColor( _currentClearColor );
  17889. _currentClearAlpha = _this.getClearAlpha();
  17890. if ( _currentClearAlpha < 1 ) _this.setClearColor( 0xffffff, 0.5 );
  17891. _this.clear();
  17892. // Turn off the features which can affect the frag color for opaque objects pass.
  17893. // Otherwise they are applied twice in opaque objects pass and transmission objects pass.
  17894. const currentToneMapping = _this.toneMapping;
  17895. _this.toneMapping = NoToneMapping;
  17896. renderObjects( opaqueObjects, scene, camera );
  17897. textures.updateMultisampleRenderTarget( _transmissionRenderTarget );
  17898. textures.updateRenderTargetMipmap( _transmissionRenderTarget );
  17899. let renderTargetNeedsUpdate = false;
  17900. for ( let i = 0, l = transmissiveObjects.length; i < l; i ++ ) {
  17901. const renderItem = transmissiveObjects[ i ];
  17902. const object = renderItem.object;
  17903. const geometry = renderItem.geometry;
  17904. const material = renderItem.material;
  17905. const group = renderItem.group;
  17906. if ( material.side === DoubleSide && object.layers.test( camera.layers ) ) {
  17907. const currentSide = material.side;
  17908. material.side = BackSide;
  17909. material.needsUpdate = true;
  17910. renderObject( object, scene, camera, geometry, material, group );
  17911. material.side = currentSide;
  17912. material.needsUpdate = true;
  17913. renderTargetNeedsUpdate = true;
  17914. }
  17915. }
  17916. if ( renderTargetNeedsUpdate === true ) {
  17917. textures.updateMultisampleRenderTarget( _transmissionRenderTarget );
  17918. textures.updateRenderTargetMipmap( _transmissionRenderTarget );
  17919. }
  17920. _this.setRenderTarget( currentRenderTarget );
  17921. _this.setClearColor( _currentClearColor, _currentClearAlpha );
  17922. _this.toneMapping = currentToneMapping;
  17923. }
  17924. function renderObjects( renderList, scene, camera ) {
  17925. const overrideMaterial = scene.isScene === true ? scene.overrideMaterial : null;
  17926. for ( let i = 0, l = renderList.length; i < l; i ++ ) {
  17927. const renderItem = renderList[ i ];
  17928. const object = renderItem.object;
  17929. const geometry = renderItem.geometry;
  17930. const material = overrideMaterial === null ? renderItem.material : overrideMaterial;
  17931. const group = renderItem.group;
  17932. if ( object.layers.test( camera.layers ) ) {
  17933. renderObject( object, scene, camera, geometry, material, group );
  17934. }
  17935. }
  17936. }
  17937. function renderObject( object, scene, camera, geometry, material, group ) {
  17938. object.onBeforeRender( _this, scene, camera, geometry, material, group );
  17939. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  17940. object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  17941. material.onBeforeRender( _this, scene, camera, geometry, object, group );
  17942. if ( material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false ) {
  17943. material.side = BackSide;
  17944. material.needsUpdate = true;
  17945. _this.renderBufferDirect( camera, scene, geometry, material, object, group );
  17946. material.side = FrontSide;
  17947. material.needsUpdate = true;
  17948. _this.renderBufferDirect( camera, scene, geometry, material, object, group );
  17949. material.side = DoubleSide;
  17950. } else {
  17951. _this.renderBufferDirect( camera, scene, geometry, material, object, group );
  17952. }
  17953. object.onAfterRender( _this, scene, camera, geometry, material, group );
  17954. }
  17955. function getProgram( material, scene, object ) {
  17956. if ( scene.isScene !== true ) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...
  17957. const materialProperties = properties.get( material );
  17958. const lights = currentRenderState.state.lights;
  17959. const shadowsArray = currentRenderState.state.shadowsArray;
  17960. const lightsStateVersion = lights.state.version;
  17961. const parameters = programCache.getParameters( material, lights.state, shadowsArray, scene, object );
  17962. const programCacheKey = programCache.getProgramCacheKey( parameters );
  17963. let programs = materialProperties.programs;
  17964. // always update environment and fog - changing these trigger an getProgram call, but it's possible that the program doesn't change
  17965. materialProperties.environment = material.isMeshStandardMaterial ? scene.environment : null;
  17966. materialProperties.fog = scene.fog;
  17967. materialProperties.envMap = ( material.isMeshStandardMaterial ? cubeuvmaps : cubemaps ).get( material.envMap || materialProperties.environment );
  17968. if ( programs === undefined ) {
  17969. // new material
  17970. material.addEventListener( 'dispose', onMaterialDispose );
  17971. programs = new Map();
  17972. materialProperties.programs = programs;
  17973. }
  17974. let program = programs.get( programCacheKey );
  17975. if ( program !== undefined ) {
  17976. // early out if program and light state is identical
  17977. if ( materialProperties.currentProgram === program && materialProperties.lightsStateVersion === lightsStateVersion ) {
  17978. updateCommonMaterialProperties( material, parameters );
  17979. return program;
  17980. }
  17981. } else {
  17982. parameters.uniforms = programCache.getUniforms( material );
  17983. material.onBuild( object, parameters, _this );
  17984. material.onBeforeCompile( parameters, _this );
  17985. program = programCache.acquireProgram( parameters, programCacheKey );
  17986. programs.set( programCacheKey, program );
  17987. materialProperties.uniforms = parameters.uniforms;
  17988. }
  17989. const uniforms = materialProperties.uniforms;
  17990. if ( ( ! material.isShaderMaterial && ! material.isRawShaderMaterial ) || material.clipping === true ) {
  17991. uniforms.clippingPlanes = clipping.uniform;
  17992. }
  17993. updateCommonMaterialProperties( material, parameters );
  17994. // store the light setup it was created for
  17995. materialProperties.needsLights = materialNeedsLights( material );
  17996. materialProperties.lightsStateVersion = lightsStateVersion;
  17997. if ( materialProperties.needsLights ) {
  17998. // wire up the material to this renderer's lighting state
  17999. uniforms.ambientLightColor.value = lights.state.ambient;
  18000. uniforms.lightProbe.value = lights.state.probe;
  18001. uniforms.directionalLights.value = lights.state.directional;
  18002. uniforms.directionalLightShadows.value = lights.state.directionalShadow;
  18003. uniforms.spotLights.value = lights.state.spot;
  18004. uniforms.spotLightShadows.value = lights.state.spotShadow;
  18005. uniforms.rectAreaLights.value = lights.state.rectArea;
  18006. uniforms.ltc_1.value = lights.state.rectAreaLTC1;
  18007. uniforms.ltc_2.value = lights.state.rectAreaLTC2;
  18008. uniforms.pointLights.value = lights.state.point;
  18009. uniforms.pointLightShadows.value = lights.state.pointShadow;
  18010. uniforms.hemisphereLights.value = lights.state.hemi;
  18011. uniforms.directionalShadowMap.value = lights.state.directionalShadowMap;
  18012. uniforms.directionalShadowMatrix.value = lights.state.directionalShadowMatrix;
  18013. uniforms.spotShadowMap.value = lights.state.spotShadowMap;
  18014. uniforms.spotLightMatrix.value = lights.state.spotLightMatrix;
  18015. uniforms.spotLightMap.value = lights.state.spotLightMap;
  18016. uniforms.pointShadowMap.value = lights.state.pointShadowMap;
  18017. uniforms.pointShadowMatrix.value = lights.state.pointShadowMatrix;
  18018. // TODO (abelnation): add area lights shadow info to uniforms
  18019. }
  18020. materialProperties.currentProgram = program;
  18021. materialProperties.uniformsList = null;
  18022. return program;
  18023. }
  18024. function getUniformList( materialProperties ) {
  18025. if ( materialProperties.uniformsList === null ) {
  18026. const progUniforms = materialProperties.currentProgram.getUniforms();
  18027. materialProperties.uniformsList = WebGLUniforms.seqWithValue( progUniforms.seq, materialProperties.uniforms );
  18028. }
  18029. return materialProperties.uniformsList;
  18030. }
  18031. function updateCommonMaterialProperties( material, parameters ) {
  18032. const materialProperties = properties.get( material );
  18033. materialProperties.outputColorSpace = parameters.outputColorSpace;
  18034. materialProperties.batching = parameters.batching;
  18035. materialProperties.instancing = parameters.instancing;
  18036. materialProperties.instancingColor = parameters.instancingColor;
  18037. materialProperties.instancingMorph = parameters.instancingMorph;
  18038. materialProperties.skinning = parameters.skinning;
  18039. materialProperties.morphTargets = parameters.morphTargets;
  18040. materialProperties.morphNormals = parameters.morphNormals;
  18041. materialProperties.morphColors = parameters.morphColors;
  18042. materialProperties.morphTargetsCount = parameters.morphTargetsCount;
  18043. materialProperties.numClippingPlanes = parameters.numClippingPlanes;
  18044. materialProperties.numIntersection = parameters.numClipIntersection;
  18045. materialProperties.vertexAlphas = parameters.vertexAlphas;
  18046. materialProperties.vertexTangents = parameters.vertexTangents;
  18047. materialProperties.toneMapping = parameters.toneMapping;
  18048. }
  18049. function setProgram( camera, scene, geometry, material, object ) {
  18050. if ( scene.isScene !== true ) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...
  18051. textures.resetTextureUnits();
  18052. const fog = scene.fog;
  18053. const environment = material.isMeshStandardMaterial ? scene.environment : null;
  18054. const colorSpace = ( _currentRenderTarget === null ) ? _this.outputColorSpace : ( _currentRenderTarget.isXRRenderTarget === true ? _currentRenderTarget.texture.colorSpace : LinearSRGBColorSpace );
  18055. const envMap = ( material.isMeshStandardMaterial ? cubeuvmaps : cubemaps ).get( material.envMap || environment );
  18056. const vertexAlphas = material.vertexColors === true && !! geometry.attributes.color && geometry.attributes.color.itemSize === 4;
  18057. const vertexTangents = !! geometry.attributes.tangent && ( !! material.normalMap || material.anisotropy > 0 );
  18058. const morphTargets = !! geometry.morphAttributes.position;
  18059. const morphNormals = !! geometry.morphAttributes.normal;
  18060. const morphColors = !! geometry.morphAttributes.color;
  18061. let toneMapping = NoToneMapping;
  18062. if ( material.toneMapped ) {
  18063. if ( _currentRenderTarget === null || _currentRenderTarget.isXRRenderTarget === true ) {
  18064. toneMapping = _this.toneMapping;
  18065. }
  18066. }
  18067. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  18068. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  18069. const materialProperties = properties.get( material );
  18070. const lights = currentRenderState.state.lights;
  18071. if ( _clippingEnabled === true ) {
  18072. if ( _localClippingEnabled === true || camera !== _currentCamera ) {
  18073. const useCache =
  18074. camera === _currentCamera &&
  18075. material.id === _currentMaterialId;
  18076. // we might want to call this function with some ClippingGroup
  18077. // object instead of the material, once it becomes feasible
  18078. // (#8465, #8379)
  18079. clipping.setState( material, camera, useCache );
  18080. }
  18081. }
  18082. //
  18083. let needsProgramChange = false;
  18084. if ( material.version === materialProperties.__version ) {
  18085. if ( materialProperties.needsLights && ( materialProperties.lightsStateVersion !== lights.state.version ) ) {
  18086. needsProgramChange = true;
  18087. } else if ( materialProperties.outputColorSpace !== colorSpace ) {
  18088. needsProgramChange = true;
  18089. } else if ( object.isBatchedMesh && materialProperties.batching === false ) {
  18090. needsProgramChange = true;
  18091. } else if ( ! object.isBatchedMesh && materialProperties.batching === true ) {
  18092. needsProgramChange = true;
  18093. } else if ( object.isInstancedMesh && materialProperties.instancing === false ) {
  18094. needsProgramChange = true;
  18095. } else if ( ! object.isInstancedMesh && materialProperties.instancing === true ) {
  18096. needsProgramChange = true;
  18097. } else if ( object.isSkinnedMesh && materialProperties.skinning === false ) {
  18098. needsProgramChange = true;
  18099. } else if ( ! object.isSkinnedMesh && materialProperties.skinning === true ) {
  18100. needsProgramChange = true;
  18101. } else if ( object.isInstancedMesh && materialProperties.instancingColor === true && object.instanceColor === null ) {
  18102. needsProgramChange = true;
  18103. } else if ( object.isInstancedMesh && materialProperties.instancingColor === false && object.instanceColor !== null ) {
  18104. needsProgramChange = true;
  18105. } else if ( object.isInstancedMesh && materialProperties.instancingMorph === true && object.morphTexture === null ) {
  18106. needsProgramChange = true;
  18107. } else if ( object.isInstancedMesh && materialProperties.instancingMorph === false && object.morphTexture !== null ) {
  18108. needsProgramChange = true;
  18109. } else if ( materialProperties.envMap !== envMap ) {
  18110. needsProgramChange = true;
  18111. } else if ( material.fog === true && materialProperties.fog !== fog ) {
  18112. needsProgramChange = true;
  18113. } else if ( materialProperties.numClippingPlanes !== undefined &&
  18114. ( materialProperties.numClippingPlanes !== clipping.numPlanes ||
  18115. materialProperties.numIntersection !== clipping.numIntersection ) ) {
  18116. needsProgramChange = true;
  18117. } else if ( materialProperties.vertexAlphas !== vertexAlphas ) {
  18118. needsProgramChange = true;
  18119. } else if ( materialProperties.vertexTangents !== vertexTangents ) {
  18120. needsProgramChange = true;
  18121. } else if ( materialProperties.morphTargets !== morphTargets ) {
  18122. needsProgramChange = true;
  18123. } else if ( materialProperties.morphNormals !== morphNormals ) {
  18124. needsProgramChange = true;
  18125. } else if ( materialProperties.morphColors !== morphColors ) {
  18126. needsProgramChange = true;
  18127. } else if ( materialProperties.toneMapping !== toneMapping ) {
  18128. needsProgramChange = true;
  18129. } else if ( capabilities.isWebGL2 === true && materialProperties.morphTargetsCount !== morphTargetsCount ) {
  18130. needsProgramChange = true;
  18131. }
  18132. } else {
  18133. needsProgramChange = true;
  18134. materialProperties.__version = material.version;
  18135. }
  18136. //
  18137. let program = materialProperties.currentProgram;
  18138. if ( needsProgramChange === true ) {
  18139. program = getProgram( material, scene, object );
  18140. }
  18141. let refreshProgram = false;
  18142. let refreshMaterial = false;
  18143. let refreshLights = false;
  18144. const p_uniforms = program.getUniforms(),
  18145. m_uniforms = materialProperties.uniforms;
  18146. if ( state.useProgram( program.program ) ) {
  18147. refreshProgram = true;
  18148. refreshMaterial = true;
  18149. refreshLights = true;
  18150. }
  18151. if ( material.id !== _currentMaterialId ) {
  18152. _currentMaterialId = material.id;
  18153. refreshMaterial = true;
  18154. }
  18155. if ( refreshProgram || _currentCamera !== camera ) {
  18156. // common camera uniforms
  18157. p_uniforms.setValue( _gl, 'projectionMatrix', camera.projectionMatrix );
  18158. p_uniforms.setValue( _gl, 'viewMatrix', camera.matrixWorldInverse );
  18159. const uCamPos = p_uniforms.map.cameraPosition;
  18160. if ( uCamPos !== undefined ) {
  18161. uCamPos.setValue( _gl, _vector3.setFromMatrixPosition( camera.matrixWorld ) );
  18162. }
  18163. if ( capabilities.logarithmicDepthBuffer ) {
  18164. p_uniforms.setValue( _gl, 'logDepthBufFC',
  18165. 2.0 / ( Math.log( camera.far + 1.0 ) / Math.LN2 ) );
  18166. }
  18167. // consider moving isOrthographic to UniformLib and WebGLMaterials, see https://github.com/mrdoob/three.js/pull/26467#issuecomment-1645185067
  18168. if ( material.isMeshPhongMaterial ||
  18169. material.isMeshToonMaterial ||
  18170. material.isMeshLambertMaterial ||
  18171. material.isMeshBasicMaterial ||
  18172. material.isMeshStandardMaterial ||
  18173. material.isShaderMaterial ) {
  18174. p_uniforms.setValue( _gl, 'isOrthographic', camera.isOrthographicCamera === true );
  18175. }
  18176. if ( _currentCamera !== camera ) {
  18177. _currentCamera = camera;
  18178. // lighting uniforms depend on the camera so enforce an update
  18179. // now, in case this material supports lights - or later, when
  18180. // the next material that does gets activated:
  18181. refreshMaterial = true; // set to true on material change
  18182. refreshLights = true; // remains set until update done
  18183. }
  18184. }
  18185. // skinning and morph target uniforms must be set even if material didn't change
  18186. // auto-setting of texture unit for bone and morph texture must go before other textures
  18187. // otherwise textures used for skinning and morphing can take over texture units reserved for other material textures
  18188. if ( object.isSkinnedMesh ) {
  18189. p_uniforms.setOptional( _gl, object, 'bindMatrix' );
  18190. p_uniforms.setOptional( _gl, object, 'bindMatrixInverse' );
  18191. const skeleton = object.skeleton;
  18192. if ( skeleton ) {
  18193. if ( capabilities.floatVertexTextures ) {
  18194. if ( skeleton.boneTexture === null ) skeleton.computeBoneTexture();
  18195. p_uniforms.setValue( _gl, 'boneTexture', skeleton.boneTexture, textures );
  18196. } else {
  18197. console.warn( 'THREE.WebGLRenderer: SkinnedMesh can only be used with WebGL 2. With WebGL 1 OES_texture_float and vertex textures support is required.' );
  18198. }
  18199. }
  18200. }
  18201. if ( object.isBatchedMesh ) {
  18202. p_uniforms.setOptional( _gl, object, 'batchingTexture' );
  18203. p_uniforms.setValue( _gl, 'batchingTexture', object._matricesTexture, textures );
  18204. }
  18205. const morphAttributes = geometry.morphAttributes;
  18206. if ( morphAttributes.position !== undefined || morphAttributes.normal !== undefined || ( morphAttributes.color !== undefined && capabilities.isWebGL2 === true ) ) {
  18207. morphtargets.update( object, geometry, program );
  18208. }
  18209. if ( refreshMaterial || materialProperties.receiveShadow !== object.receiveShadow ) {
  18210. materialProperties.receiveShadow = object.receiveShadow;
  18211. p_uniforms.setValue( _gl, 'receiveShadow', object.receiveShadow );
  18212. }
  18213. // https://github.com/mrdoob/three.js/pull/24467#issuecomment-1209031512
  18214. if ( material.isMeshGouraudMaterial && material.envMap !== null ) {
  18215. m_uniforms.envMap.value = envMap;
  18216. m_uniforms.flipEnvMap.value = ( envMap.isCubeTexture && envMap.isRenderTargetTexture === false ) ? - 1 : 1;
  18217. }
  18218. if ( refreshMaterial ) {
  18219. p_uniforms.setValue( _gl, 'toneMappingExposure', _this.toneMappingExposure );
  18220. if ( materialProperties.needsLights ) {
  18221. // the current material requires lighting info
  18222. // note: all lighting uniforms are always set correctly
  18223. // they simply reference the renderer's state for their
  18224. // values
  18225. //
  18226. // use the current material's .needsUpdate flags to set
  18227. // the GL state when required
  18228. markUniformsLightsNeedsUpdate( m_uniforms, refreshLights );
  18229. }
  18230. // refresh uniforms common to several materials
  18231. if ( fog && material.fog === true ) {
  18232. materials.refreshFogUniforms( m_uniforms, fog );
  18233. }
  18234. materials.refreshMaterialUniforms( m_uniforms, material, _pixelRatio, _height, _transmissionRenderTarget );
  18235. WebGLUniforms.upload( _gl, getUniformList( materialProperties ), m_uniforms, textures );
  18236. }
  18237. if ( material.isShaderMaterial && material.uniformsNeedUpdate === true ) {
  18238. WebGLUniforms.upload( _gl, getUniformList( materialProperties ), m_uniforms, textures );
  18239. material.uniformsNeedUpdate = false;
  18240. }
  18241. if ( material.isSpriteMaterial ) {
  18242. p_uniforms.setValue( _gl, 'center', object.center );
  18243. }
  18244. // common matrices
  18245. p_uniforms.setValue( _gl, 'modelViewMatrix', object.modelViewMatrix );
  18246. p_uniforms.setValue( _gl, 'normalMatrix', object.normalMatrix );
  18247. p_uniforms.setValue( _gl, 'modelMatrix', object.matrixWorld );
  18248. // UBOs
  18249. if ( material.isShaderMaterial || material.isRawShaderMaterial ) {
  18250. const groups = material.uniformsGroups;
  18251. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  18252. if ( capabilities.isWebGL2 ) {
  18253. const group = groups[ i ];
  18254. uniformsGroups.update( group, program );
  18255. uniformsGroups.bind( group, program );
  18256. } else {
  18257. console.warn( 'THREE.WebGLRenderer: Uniform Buffer Objects can only be used with WebGL 2.' );
  18258. }
  18259. }
  18260. }
  18261. return program;
  18262. }
  18263. // If uniforms are marked as clean, they don't need to be loaded to the GPU.
  18264. function markUniformsLightsNeedsUpdate( uniforms, value ) {
  18265. uniforms.ambientLightColor.needsUpdate = value;
  18266. uniforms.lightProbe.needsUpdate = value;
  18267. uniforms.directionalLights.needsUpdate = value;
  18268. uniforms.directionalLightShadows.needsUpdate = value;
  18269. uniforms.pointLights.needsUpdate = value;
  18270. uniforms.pointLightShadows.needsUpdate = value;
  18271. uniforms.spotLights.needsUpdate = value;
  18272. uniforms.spotLightShadows.needsUpdate = value;
  18273. uniforms.rectAreaLights.needsUpdate = value;
  18274. uniforms.hemisphereLights.needsUpdate = value;
  18275. }
  18276. function materialNeedsLights( material ) {
  18277. return material.isMeshLambertMaterial || material.isMeshToonMaterial || material.isMeshPhongMaterial ||
  18278. material.isMeshStandardMaterial || material.isShadowMaterial ||
  18279. ( material.isShaderMaterial && material.lights === true );
  18280. }
  18281. this.getActiveCubeFace = function () {
  18282. return _currentActiveCubeFace;
  18283. };
  18284. this.getActiveMipmapLevel = function () {
  18285. return _currentActiveMipmapLevel;
  18286. };
  18287. this.getRenderTarget = function () {
  18288. return _currentRenderTarget;
  18289. };
  18290. this.setRenderTargetTextures = function ( renderTarget, colorTexture, depthTexture ) {
  18291. properties.get( renderTarget.texture ).__webglTexture = colorTexture;
  18292. properties.get( renderTarget.depthTexture ).__webglTexture = depthTexture;
  18293. const renderTargetProperties = properties.get( renderTarget );
  18294. renderTargetProperties.__hasExternalTextures = true;
  18295. renderTargetProperties.__autoAllocateDepthBuffer = depthTexture === undefined;
  18296. if ( ! renderTargetProperties.__autoAllocateDepthBuffer ) {
  18297. // The multisample_render_to_texture extension doesn't work properly if there
  18298. // are midframe flushes and an external depth buffer. Disable use of the extension.
  18299. if ( extensions.has( 'WEBGL_multisampled_render_to_texture' ) === true ) {
  18300. console.warn( 'THREE.WebGLRenderer: Render-to-texture extension was disabled because an external texture was provided' );
  18301. renderTargetProperties.__useRenderToTexture = false;
  18302. }
  18303. }
  18304. };
  18305. this.setRenderTargetFramebuffer = function ( renderTarget, defaultFramebuffer ) {
  18306. const renderTargetProperties = properties.get( renderTarget );
  18307. renderTargetProperties.__webglFramebuffer = defaultFramebuffer;
  18308. renderTargetProperties.__useDefaultFramebuffer = defaultFramebuffer === undefined;
  18309. };
  18310. this.setRenderTarget = function ( renderTarget, activeCubeFace = 0, activeMipmapLevel = 0 ) {
  18311. _currentRenderTarget = renderTarget;
  18312. _currentActiveCubeFace = activeCubeFace;
  18313. _currentActiveMipmapLevel = activeMipmapLevel;
  18314. let useDefaultFramebuffer = true;
  18315. let framebuffer = null;
  18316. let isCube = false;
  18317. let isRenderTarget3D = false;
  18318. if ( renderTarget ) {
  18319. const renderTargetProperties = properties.get( renderTarget );
  18320. if ( renderTargetProperties.__useDefaultFramebuffer !== undefined ) {
  18321. // We need to make sure to rebind the framebuffer.
  18322. state.bindFramebuffer( _gl.FRAMEBUFFER, null );
  18323. useDefaultFramebuffer = false;
  18324. } else if ( renderTargetProperties.__webglFramebuffer === undefined ) {
  18325. textures.setupRenderTarget( renderTarget );
  18326. } else if ( renderTargetProperties.__hasExternalTextures ) {
  18327. // Color and depth texture must be rebound in order for the swapchain to update.
  18328. textures.rebindTextures( renderTarget, properties.get( renderTarget.texture ).__webglTexture, properties.get( renderTarget.depthTexture ).__webglTexture );
  18329. }
  18330. const texture = renderTarget.texture;
  18331. if ( texture.isData3DTexture || texture.isDataArrayTexture || texture.isCompressedArrayTexture ) {
  18332. isRenderTarget3D = true;
  18333. }
  18334. const __webglFramebuffer = properties.get( renderTarget ).__webglFramebuffer;
  18335. if ( renderTarget.isWebGLCubeRenderTarget ) {
  18336. if ( Array.isArray( __webglFramebuffer[ activeCubeFace ] ) ) {
  18337. framebuffer = __webglFramebuffer[ activeCubeFace ][ activeMipmapLevel ];
  18338. } else {
  18339. framebuffer = __webglFramebuffer[ activeCubeFace ];
  18340. }
  18341. isCube = true;
  18342. } else if ( ( capabilities.isWebGL2 && renderTarget.samples > 0 ) && textures.useMultisampledRTT( renderTarget ) === false ) {
  18343. framebuffer = properties.get( renderTarget ).__webglMultisampledFramebuffer;
  18344. } else {
  18345. if ( Array.isArray( __webglFramebuffer ) ) {
  18346. framebuffer = __webglFramebuffer[ activeMipmapLevel ];
  18347. } else {
  18348. framebuffer = __webglFramebuffer;
  18349. }
  18350. }
  18351. _currentViewport.copy( renderTarget.viewport );
  18352. _currentScissor.copy( renderTarget.scissor );
  18353. _currentScissorTest = renderTarget.scissorTest;
  18354. } else {
  18355. _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).floor();
  18356. _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).floor();
  18357. _currentScissorTest = _scissorTest;
  18358. }
  18359. const framebufferBound = state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  18360. if ( framebufferBound && capabilities.drawBuffers && useDefaultFramebuffer ) {
  18361. state.drawBuffers( renderTarget, framebuffer );
  18362. }
  18363. state.viewport( _currentViewport );
  18364. state.scissor( _currentScissor );
  18365. state.setScissorTest( _currentScissorTest );
  18366. if ( isCube ) {
  18367. const textureProperties = properties.get( renderTarget.texture );
  18368. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + activeCubeFace, textureProperties.__webglTexture, activeMipmapLevel );
  18369. } else if ( isRenderTarget3D ) {
  18370. const textureProperties = properties.get( renderTarget.texture );
  18371. const layer = activeCubeFace || 0;
  18372. _gl.framebufferTextureLayer( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, textureProperties.__webglTexture, activeMipmapLevel || 0, layer );
  18373. }
  18374. _currentMaterialId = - 1; // reset current material to ensure correct uniform bindings
  18375. };
  18376. this.readRenderTargetPixels = function ( renderTarget, x, y, width, height, buffer, activeCubeFaceIndex ) {
  18377. if ( ! ( renderTarget && renderTarget.isWebGLRenderTarget ) ) {
  18378. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' );
  18379. return;
  18380. }
  18381. let framebuffer = properties.get( renderTarget ).__webglFramebuffer;
  18382. if ( renderTarget.isWebGLCubeRenderTarget && activeCubeFaceIndex !== undefined ) {
  18383. framebuffer = framebuffer[ activeCubeFaceIndex ];
  18384. }
  18385. if ( framebuffer ) {
  18386. state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  18387. try {
  18388. const texture = renderTarget.texture;
  18389. const textureFormat = texture.format;
  18390. const textureType = texture.type;
  18391. if ( textureFormat !== RGBAFormat && utils.convert( textureFormat ) !== _gl.getParameter( _gl.IMPLEMENTATION_COLOR_READ_FORMAT ) ) {
  18392. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.' );
  18393. return;
  18394. }
  18395. const halfFloatSupportedByExt = ( textureType === HalfFloatType ) && ( extensions.has( 'EXT_color_buffer_half_float' ) || ( capabilities.isWebGL2 && extensions.has( 'EXT_color_buffer_float' ) ) );
  18396. if ( textureType !== UnsignedByteType && utils.convert( textureType ) !== _gl.getParameter( _gl.IMPLEMENTATION_COLOR_READ_TYPE ) && // Edge and Chrome Mac < 52 (#9513)
  18397. ! ( textureType === FloatType && ( capabilities.isWebGL2 || extensions.has( 'OES_texture_float' ) || extensions.has( 'WEBGL_color_buffer_float' ) ) ) && // Chrome Mac >= 52 and Firefox
  18398. ! halfFloatSupportedByExt ) {
  18399. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.' );
  18400. return;
  18401. }
  18402. // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604)
  18403. if ( ( x >= 0 && x <= ( renderTarget.width - width ) ) && ( y >= 0 && y <= ( renderTarget.height - height ) ) ) {
  18404. _gl.readPixels( x, y, width, height, utils.convert( textureFormat ), utils.convert( textureType ), buffer );
  18405. }
  18406. } finally {
  18407. // restore framebuffer of current render target if necessary
  18408. const framebuffer = ( _currentRenderTarget !== null ) ? properties.get( _currentRenderTarget ).__webglFramebuffer : null;
  18409. state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  18410. }
  18411. }
  18412. };
  18413. this.copyFramebufferToTexture = function ( position, texture, level = 0 ) {
  18414. const levelScale = Math.pow( 2, - level );
  18415. const width = Math.floor( texture.image.width * levelScale );
  18416. const height = Math.floor( texture.image.height * levelScale );
  18417. textures.setTexture2D( texture, 0 );
  18418. _gl.copyTexSubImage2D( _gl.TEXTURE_2D, level, 0, 0, position.x, position.y, width, height );
  18419. state.unbindTexture();
  18420. };
  18421. this.copyTextureToTexture = function ( position, srcTexture, dstTexture, level = 0 ) {
  18422. const width = srcTexture.image.width;
  18423. const height = srcTexture.image.height;
  18424. const glFormat = utils.convert( dstTexture.format );
  18425. const glType = utils.convert( dstTexture.type );
  18426. textures.setTexture2D( dstTexture, 0 );
  18427. // As another texture upload may have changed pixelStorei
  18428. // parameters, make sure they are correct for the dstTexture
  18429. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY );
  18430. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha );
  18431. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment );
  18432. if ( srcTexture.isDataTexture ) {
  18433. _gl.texSubImage2D( _gl.TEXTURE_2D, level, position.x, position.y, width, height, glFormat, glType, srcTexture.image.data );
  18434. } else {
  18435. if ( srcTexture.isCompressedTexture ) {
  18436. _gl.compressedTexSubImage2D( _gl.TEXTURE_2D, level, position.x, position.y, srcTexture.mipmaps[ 0 ].width, srcTexture.mipmaps[ 0 ].height, glFormat, srcTexture.mipmaps[ 0 ].data );
  18437. } else {
  18438. _gl.texSubImage2D( _gl.TEXTURE_2D, level, position.x, position.y, glFormat, glType, srcTexture.image );
  18439. }
  18440. }
  18441. // Generate mipmaps only when copying level 0
  18442. if ( level === 0 && dstTexture.generateMipmaps ) _gl.generateMipmap( _gl.TEXTURE_2D );
  18443. state.unbindTexture();
  18444. };
  18445. this.copyTextureToTexture3D = function ( sourceBox, position, srcTexture, dstTexture, level = 0 ) {
  18446. if ( _this.isWebGL1Renderer ) {
  18447. console.warn( 'THREE.WebGLRenderer.copyTextureToTexture3D: can only be used with WebGL2.' );
  18448. return;
  18449. }
  18450. const width = sourceBox.max.x - sourceBox.min.x + 1;
  18451. const height = sourceBox.max.y - sourceBox.min.y + 1;
  18452. const depth = sourceBox.max.z - sourceBox.min.z + 1;
  18453. const glFormat = utils.convert( dstTexture.format );
  18454. const glType = utils.convert( dstTexture.type );
  18455. let glTarget;
  18456. if ( dstTexture.isData3DTexture ) {
  18457. textures.setTexture3D( dstTexture, 0 );
  18458. glTarget = _gl.TEXTURE_3D;
  18459. } else if ( dstTexture.isDataArrayTexture || dstTexture.isCompressedArrayTexture ) {
  18460. textures.setTexture2DArray( dstTexture, 0 );
  18461. glTarget = _gl.TEXTURE_2D_ARRAY;
  18462. } else {
  18463. console.warn( 'THREE.WebGLRenderer.copyTextureToTexture3D: only supports THREE.DataTexture3D and THREE.DataTexture2DArray.' );
  18464. return;
  18465. }
  18466. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY );
  18467. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha );
  18468. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment );
  18469. const unpackRowLen = _gl.getParameter( _gl.UNPACK_ROW_LENGTH );
  18470. const unpackImageHeight = _gl.getParameter( _gl.UNPACK_IMAGE_HEIGHT );
  18471. const unpackSkipPixels = _gl.getParameter( _gl.UNPACK_SKIP_PIXELS );
  18472. const unpackSkipRows = _gl.getParameter( _gl.UNPACK_SKIP_ROWS );
  18473. const unpackSkipImages = _gl.getParameter( _gl.UNPACK_SKIP_IMAGES );
  18474. const image = srcTexture.isCompressedTexture ? srcTexture.mipmaps[ level ] : srcTexture.image;
  18475. _gl.pixelStorei( _gl.UNPACK_ROW_LENGTH, image.width );
  18476. _gl.pixelStorei( _gl.UNPACK_IMAGE_HEIGHT, image.height );
  18477. _gl.pixelStorei( _gl.UNPACK_SKIP_PIXELS, sourceBox.min.x );
  18478. _gl.pixelStorei( _gl.UNPACK_SKIP_ROWS, sourceBox.min.y );
  18479. _gl.pixelStorei( _gl.UNPACK_SKIP_IMAGES, sourceBox.min.z );
  18480. if ( srcTexture.isDataTexture || srcTexture.isData3DTexture ) {
  18481. _gl.texSubImage3D( glTarget, level, position.x, position.y, position.z, width, height, depth, glFormat, glType, image.data );
  18482. } else {
  18483. if ( srcTexture.isCompressedArrayTexture ) {
  18484. console.warn( 'THREE.WebGLRenderer.copyTextureToTexture3D: untested support for compressed srcTexture.' );
  18485. _gl.compressedTexSubImage3D( glTarget, level, position.x, position.y, position.z, width, height, depth, glFormat, image.data );
  18486. } else {
  18487. _gl.texSubImage3D( glTarget, level, position.x, position.y, position.z, width, height, depth, glFormat, glType, image );
  18488. }
  18489. }
  18490. _gl.pixelStorei( _gl.UNPACK_ROW_LENGTH, unpackRowLen );
  18491. _gl.pixelStorei( _gl.UNPACK_IMAGE_HEIGHT, unpackImageHeight );
  18492. _gl.pixelStorei( _gl.UNPACK_SKIP_PIXELS, unpackSkipPixels );
  18493. _gl.pixelStorei( _gl.UNPACK_SKIP_ROWS, unpackSkipRows );
  18494. _gl.pixelStorei( _gl.UNPACK_SKIP_IMAGES, unpackSkipImages );
  18495. // Generate mipmaps only when copying level 0
  18496. if ( level === 0 && dstTexture.generateMipmaps ) _gl.generateMipmap( glTarget );
  18497. state.unbindTexture();
  18498. };
  18499. this.initTexture = function ( texture ) {
  18500. if ( texture.isCubeTexture ) {
  18501. textures.setTextureCube( texture, 0 );
  18502. } else if ( texture.isData3DTexture ) {
  18503. textures.setTexture3D( texture, 0 );
  18504. } else if ( texture.isDataArrayTexture || texture.isCompressedArrayTexture ) {
  18505. textures.setTexture2DArray( texture, 0 );
  18506. } else {
  18507. textures.setTexture2D( texture, 0 );
  18508. }
  18509. state.unbindTexture();
  18510. };
  18511. this.resetState = function () {
  18512. _currentActiveCubeFace = 0;
  18513. _currentActiveMipmapLevel = 0;
  18514. _currentRenderTarget = null;
  18515. state.reset();
  18516. bindingStates.reset();
  18517. };
  18518. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  18519. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) );
  18520. }
  18521. }
  18522. get coordinateSystem() {
  18523. return WebGLCoordinateSystem;
  18524. }
  18525. get outputColorSpace() {
  18526. return this._outputColorSpace;
  18527. }
  18528. set outputColorSpace( colorSpace ) {
  18529. this._outputColorSpace = colorSpace;
  18530. const gl = this.getContext();
  18531. gl.drawingBufferColorSpace = colorSpace === DisplayP3ColorSpace ? 'display-p3' : 'srgb';
  18532. gl.unpackColorSpace = ColorManagement.workingColorSpace === LinearDisplayP3ColorSpace ? 'display-p3' : 'srgb';
  18533. }
  18534. get useLegacyLights() { // @deprecated, r155
  18535. console.warn( 'THREE.WebGLRenderer: The property .useLegacyLights has been deprecated. Migrate your lighting according to the following guide: https://discourse.threejs.org/t/updates-to-lighting-in-three-js-r155/53733.' );
  18536. return this._useLegacyLights;
  18537. }
  18538. set useLegacyLights( value ) { // @deprecated, r155
  18539. console.warn( 'THREE.WebGLRenderer: The property .useLegacyLights has been deprecated. Migrate your lighting according to the following guide: https://discourse.threejs.org/t/updates-to-lighting-in-three-js-r155/53733.' );
  18540. this._useLegacyLights = value;
  18541. }
  18542. }
  18543. class WebGL1Renderer extends WebGLRenderer {}
  18544. WebGL1Renderer.prototype.isWebGL1Renderer = true;
  18545. class FogExp2 {
  18546. constructor( color, density = 0.00025 ) {
  18547. this.isFogExp2 = true;
  18548. this.name = '';
  18549. this.color = new Color( color );
  18550. this.density = density;
  18551. }
  18552. clone() {
  18553. return new FogExp2( this.color, this.density );
  18554. }
  18555. toJSON( /* meta */ ) {
  18556. return {
  18557. type: 'FogExp2',
  18558. name: this.name,
  18559. color: this.color.getHex(),
  18560. density: this.density
  18561. };
  18562. }
  18563. }
  18564. class Fog {
  18565. constructor( color, near = 1, far = 1000 ) {
  18566. this.isFog = true;
  18567. this.name = '';
  18568. this.color = new Color( color );
  18569. this.near = near;
  18570. this.far = far;
  18571. }
  18572. clone() {
  18573. return new Fog( this.color, this.near, this.far );
  18574. }
  18575. toJSON( /* meta */ ) {
  18576. return {
  18577. type: 'Fog',
  18578. name: this.name,
  18579. color: this.color.getHex(),
  18580. near: this.near,
  18581. far: this.far
  18582. };
  18583. }
  18584. }
  18585. class Scene extends Object3D {
  18586. constructor() {
  18587. super();
  18588. this.isScene = true;
  18589. this.type = 'Scene';
  18590. this.background = null;
  18591. this.environment = null;
  18592. this.fog = null;
  18593. this.backgroundBlurriness = 0;
  18594. this.backgroundIntensity = 1;
  18595. this.overrideMaterial = null;
  18596. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  18597. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) );
  18598. }
  18599. }
  18600. copy( source, recursive ) {
  18601. super.copy( source, recursive );
  18602. if ( source.background !== null ) this.background = source.background.clone();
  18603. if ( source.environment !== null ) this.environment = source.environment.clone();
  18604. if ( source.fog !== null ) this.fog = source.fog.clone();
  18605. this.backgroundBlurriness = source.backgroundBlurriness;
  18606. this.backgroundIntensity = source.backgroundIntensity;
  18607. if ( source.overrideMaterial !== null ) this.overrideMaterial = source.overrideMaterial.clone();
  18608. this.matrixAutoUpdate = source.matrixAutoUpdate;
  18609. return this;
  18610. }
  18611. toJSON( meta ) {
  18612. const data = super.toJSON( meta );
  18613. if ( this.fog !== null ) data.object.fog = this.fog.toJSON();
  18614. if ( this.backgroundBlurriness > 0 ) data.object.backgroundBlurriness = this.backgroundBlurriness;
  18615. if ( this.backgroundIntensity !== 1 ) data.object.backgroundIntensity = this.backgroundIntensity;
  18616. return data;
  18617. }
  18618. }
  18619. class InterleavedBuffer {
  18620. constructor( array, stride ) {
  18621. this.isInterleavedBuffer = true;
  18622. this.array = array;
  18623. this.stride = stride;
  18624. this.count = array !== undefined ? array.length / stride : 0;
  18625. this.usage = StaticDrawUsage;
  18626. this._updateRange = { offset: 0, count: - 1 };
  18627. this.updateRanges = [];
  18628. this.version = 0;
  18629. this.uuid = generateUUID();
  18630. }
  18631. onUploadCallback() {}
  18632. set needsUpdate( value ) {
  18633. if ( value === true ) this.version ++;
  18634. }
  18635. get updateRange() {
  18636. warnOnce( 'THREE.InterleavedBuffer: updateRange() is deprecated and will be removed in r169. Use addUpdateRange() instead.' ); // @deprecated, r159
  18637. return this._updateRange;
  18638. }
  18639. setUsage( value ) {
  18640. this.usage = value;
  18641. return this;
  18642. }
  18643. addUpdateRange( start, count ) {
  18644. this.updateRanges.push( { start, count } );
  18645. }
  18646. clearUpdateRanges() {
  18647. this.updateRanges.length = 0;
  18648. }
  18649. copy( source ) {
  18650. this.array = new source.array.constructor( source.array );
  18651. this.count = source.count;
  18652. this.stride = source.stride;
  18653. this.usage = source.usage;
  18654. return this;
  18655. }
  18656. copyAt( index1, attribute, index2 ) {
  18657. index1 *= this.stride;
  18658. index2 *= attribute.stride;
  18659. for ( let i = 0, l = this.stride; i < l; i ++ ) {
  18660. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  18661. }
  18662. return this;
  18663. }
  18664. set( value, offset = 0 ) {
  18665. this.array.set( value, offset );
  18666. return this;
  18667. }
  18668. clone( data ) {
  18669. if ( data.arrayBuffers === undefined ) {
  18670. data.arrayBuffers = {};
  18671. }
  18672. if ( this.array.buffer._uuid === undefined ) {
  18673. this.array.buffer._uuid = generateUUID();
  18674. }
  18675. if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) {
  18676. data.arrayBuffers[ this.array.buffer._uuid ] = this.array.slice( 0 ).buffer;
  18677. }
  18678. const array = new this.array.constructor( data.arrayBuffers[ this.array.buffer._uuid ] );
  18679. const ib = new this.constructor( array, this.stride );
  18680. ib.setUsage( this.usage );
  18681. return ib;
  18682. }
  18683. onUpload( callback ) {
  18684. this.onUploadCallback = callback;
  18685. return this;
  18686. }
  18687. toJSON( data ) {
  18688. if ( data.arrayBuffers === undefined ) {
  18689. data.arrayBuffers = {};
  18690. }
  18691. // generate UUID for array buffer if necessary
  18692. if ( this.array.buffer._uuid === undefined ) {
  18693. this.array.buffer._uuid = generateUUID();
  18694. }
  18695. if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) {
  18696. data.arrayBuffers[ this.array.buffer._uuid ] = Array.from( new Uint32Array( this.array.buffer ) );
  18697. }
  18698. //
  18699. return {
  18700. uuid: this.uuid,
  18701. buffer: this.array.buffer._uuid,
  18702. type: this.array.constructor.name,
  18703. stride: this.stride
  18704. };
  18705. }
  18706. }
  18707. const _vector$6 = /*@__PURE__*/ new Vector3();
  18708. class InterleavedBufferAttribute {
  18709. constructor( interleavedBuffer, itemSize, offset, normalized = false ) {
  18710. this.isInterleavedBufferAttribute = true;
  18711. this.name = '';
  18712. this.data = interleavedBuffer;
  18713. this.itemSize = itemSize;
  18714. this.offset = offset;
  18715. this.normalized = normalized;
  18716. }
  18717. get count() {
  18718. return this.data.count;
  18719. }
  18720. get array() {
  18721. return this.data.array;
  18722. }
  18723. set needsUpdate( value ) {
  18724. this.data.needsUpdate = value;
  18725. }
  18726. applyMatrix4( m ) {
  18727. for ( let i = 0, l = this.data.count; i < l; i ++ ) {
  18728. _vector$6.fromBufferAttribute( this, i );
  18729. _vector$6.applyMatrix4( m );
  18730. this.setXYZ( i, _vector$6.x, _vector$6.y, _vector$6.z );
  18731. }
  18732. return this;
  18733. }
  18734. applyNormalMatrix( m ) {
  18735. for ( let i = 0, l = this.count; i < l; i ++ ) {
  18736. _vector$6.fromBufferAttribute( this, i );
  18737. _vector$6.applyNormalMatrix( m );
  18738. this.setXYZ( i, _vector$6.x, _vector$6.y, _vector$6.z );
  18739. }
  18740. return this;
  18741. }
  18742. transformDirection( m ) {
  18743. for ( let i = 0, l = this.count; i < l; i ++ ) {
  18744. _vector$6.fromBufferAttribute( this, i );
  18745. _vector$6.transformDirection( m );
  18746. this.setXYZ( i, _vector$6.x, _vector$6.y, _vector$6.z );
  18747. }
  18748. return this;
  18749. }
  18750. getComponent( index, component ) {
  18751. let value = this.array[ index * this.data.stride + this.offset + component ];
  18752. if ( this.normalized ) value = denormalize( value, this.array );
  18753. return value;
  18754. }
  18755. setComponent( index, component, value ) {
  18756. if ( this.normalized ) value = normalize( value, this.array );
  18757. this.data.array[ index * this.data.stride + this.offset + component ] = value;
  18758. return this;
  18759. }
  18760. setX( index, x ) {
  18761. if ( this.normalized ) x = normalize( x, this.array );
  18762. this.data.array[ index * this.data.stride + this.offset ] = x;
  18763. return this;
  18764. }
  18765. setY( index, y ) {
  18766. if ( this.normalized ) y = normalize( y, this.array );
  18767. this.data.array[ index * this.data.stride + this.offset + 1 ] = y;
  18768. return this;
  18769. }
  18770. setZ( index, z ) {
  18771. if ( this.normalized ) z = normalize( z, this.array );
  18772. this.data.array[ index * this.data.stride + this.offset + 2 ] = z;
  18773. return this;
  18774. }
  18775. setW( index, w ) {
  18776. if ( this.normalized ) w = normalize( w, this.array );
  18777. this.data.array[ index * this.data.stride + this.offset + 3 ] = w;
  18778. return this;
  18779. }
  18780. getX( index ) {
  18781. let x = this.data.array[ index * this.data.stride + this.offset ];
  18782. if ( this.normalized ) x = denormalize( x, this.array );
  18783. return x;
  18784. }
  18785. getY( index ) {
  18786. let y = this.data.array[ index * this.data.stride + this.offset + 1 ];
  18787. if ( this.normalized ) y = denormalize( y, this.array );
  18788. return y;
  18789. }
  18790. getZ( index ) {
  18791. let z = this.data.array[ index * this.data.stride + this.offset + 2 ];
  18792. if ( this.normalized ) z = denormalize( z, this.array );
  18793. return z;
  18794. }
  18795. getW( index ) {
  18796. let w = this.data.array[ index * this.data.stride + this.offset + 3 ];
  18797. if ( this.normalized ) w = denormalize( w, this.array );
  18798. return w;
  18799. }
  18800. setXY( index, x, y ) {
  18801. index = index * this.data.stride + this.offset;
  18802. if ( this.normalized ) {
  18803. x = normalize( x, this.array );
  18804. y = normalize( y, this.array );
  18805. }
  18806. this.data.array[ index + 0 ] = x;
  18807. this.data.array[ index + 1 ] = y;
  18808. return this;
  18809. }
  18810. setXYZ( index, x, y, z ) {
  18811. index = index * this.data.stride + this.offset;
  18812. if ( this.normalized ) {
  18813. x = normalize( x, this.array );
  18814. y = normalize( y, this.array );
  18815. z = normalize( z, this.array );
  18816. }
  18817. this.data.array[ index + 0 ] = x;
  18818. this.data.array[ index + 1 ] = y;
  18819. this.data.array[ index + 2 ] = z;
  18820. return this;
  18821. }
  18822. setXYZW( index, x, y, z, w ) {
  18823. index = index * this.data.stride + this.offset;
  18824. if ( this.normalized ) {
  18825. x = normalize( x, this.array );
  18826. y = normalize( y, this.array );
  18827. z = normalize( z, this.array );
  18828. w = normalize( w, this.array );
  18829. }
  18830. this.data.array[ index + 0 ] = x;
  18831. this.data.array[ index + 1 ] = y;
  18832. this.data.array[ index + 2 ] = z;
  18833. this.data.array[ index + 3 ] = w;
  18834. return this;
  18835. }
  18836. clone( data ) {
  18837. if ( data === undefined ) {
  18838. console.log( 'THREE.InterleavedBufferAttribute.clone(): Cloning an interleaved buffer attribute will de-interleave buffer data.' );
  18839. const array = [];
  18840. for ( let i = 0; i < this.count; i ++ ) {
  18841. const index = i * this.data.stride + this.offset;
  18842. for ( let j = 0; j < this.itemSize; j ++ ) {
  18843. array.push( this.data.array[ index + j ] );
  18844. }
  18845. }
  18846. return new BufferAttribute( new this.array.constructor( array ), this.itemSize, this.normalized );
  18847. } else {
  18848. if ( data.interleavedBuffers === undefined ) {
  18849. data.interleavedBuffers = {};
  18850. }
  18851. if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) {
  18852. data.interleavedBuffers[ this.data.uuid ] = this.data.clone( data );
  18853. }
  18854. return new InterleavedBufferAttribute( data.interleavedBuffers[ this.data.uuid ], this.itemSize, this.offset, this.normalized );
  18855. }
  18856. }
  18857. toJSON( data ) {
  18858. if ( data === undefined ) {
  18859. console.log( 'THREE.InterleavedBufferAttribute.toJSON(): Serializing an interleaved buffer attribute will de-interleave buffer data.' );
  18860. const array = [];
  18861. for ( let i = 0; i < this.count; i ++ ) {
  18862. const index = i * this.data.stride + this.offset;
  18863. for ( let j = 0; j < this.itemSize; j ++ ) {
  18864. array.push( this.data.array[ index + j ] );
  18865. }
  18866. }
  18867. // de-interleave data and save it as an ordinary buffer attribute for now
  18868. return {
  18869. itemSize: this.itemSize,
  18870. type: this.array.constructor.name,
  18871. array: array,
  18872. normalized: this.normalized
  18873. };
  18874. } else {
  18875. // save as true interleaved attribute
  18876. if ( data.interleavedBuffers === undefined ) {
  18877. data.interleavedBuffers = {};
  18878. }
  18879. if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) {
  18880. data.interleavedBuffers[ this.data.uuid ] = this.data.toJSON( data );
  18881. }
  18882. return {
  18883. isInterleavedBufferAttribute: true,
  18884. itemSize: this.itemSize,
  18885. data: this.data.uuid,
  18886. offset: this.offset,
  18887. normalized: this.normalized
  18888. };
  18889. }
  18890. }
  18891. }
  18892. class SpriteMaterial extends Material {
  18893. constructor( parameters ) {
  18894. super();
  18895. this.isSpriteMaterial = true;
  18896. this.type = 'SpriteMaterial';
  18897. this.color = new Color( 0xffffff );
  18898. this.map = null;
  18899. this.alphaMap = null;
  18900. this.rotation = 0;
  18901. this.sizeAttenuation = true;
  18902. this.transparent = true;
  18903. this.fog = true;
  18904. this.setValues( parameters );
  18905. }
  18906. copy( source ) {
  18907. super.copy( source );
  18908. this.color.copy( source.color );
  18909. this.map = source.map;
  18910. this.alphaMap = source.alphaMap;
  18911. this.rotation = source.rotation;
  18912. this.sizeAttenuation = source.sizeAttenuation;
  18913. this.fog = source.fog;
  18914. return this;
  18915. }
  18916. }
  18917. let _geometry;
  18918. const _intersectPoint = /*@__PURE__*/ new Vector3();
  18919. const _worldScale = /*@__PURE__*/ new Vector3();
  18920. const _mvPosition = /*@__PURE__*/ new Vector3();
  18921. const _alignedPosition = /*@__PURE__*/ new Vector2();
  18922. const _rotatedPosition = /*@__PURE__*/ new Vector2();
  18923. const _viewWorldMatrix = /*@__PURE__*/ new Matrix4();
  18924. const _vA = /*@__PURE__*/ new Vector3();
  18925. const _vB = /*@__PURE__*/ new Vector3();
  18926. const _vC = /*@__PURE__*/ new Vector3();
  18927. const _uvA = /*@__PURE__*/ new Vector2();
  18928. const _uvB = /*@__PURE__*/ new Vector2();
  18929. const _uvC = /*@__PURE__*/ new Vector2();
  18930. class Sprite extends Object3D {
  18931. constructor( material = new SpriteMaterial() ) {
  18932. super();
  18933. this.isSprite = true;
  18934. this.type = 'Sprite';
  18935. if ( _geometry === undefined ) {
  18936. _geometry = new BufferGeometry();
  18937. const float32Array = new Float32Array( [
  18938. - 0.5, - 0.5, 0, 0, 0,
  18939. 0.5, - 0.5, 0, 1, 0,
  18940. 0.5, 0.5, 0, 1, 1,
  18941. - 0.5, 0.5, 0, 0, 1
  18942. ] );
  18943. const interleavedBuffer = new InterleavedBuffer( float32Array, 5 );
  18944. _geometry.setIndex( [ 0, 1, 2, 0, 2, 3 ] );
  18945. _geometry.setAttribute( 'position', new InterleavedBufferAttribute( interleavedBuffer, 3, 0, false ) );
  18946. _geometry.setAttribute( 'uv', new InterleavedBufferAttribute( interleavedBuffer, 2, 3, false ) );
  18947. }
  18948. this.geometry = _geometry;
  18949. this.material = material;
  18950. this.center = new Vector2( 0.5, 0.5 );
  18951. }
  18952. raycast( raycaster, intersects ) {
  18953. if ( raycaster.camera === null ) {
  18954. console.error( 'THREE.Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.' );
  18955. }
  18956. _worldScale.setFromMatrixScale( this.matrixWorld );
  18957. _viewWorldMatrix.copy( raycaster.camera.matrixWorld );
  18958. this.modelViewMatrix.multiplyMatrices( raycaster.camera.matrixWorldInverse, this.matrixWorld );
  18959. _mvPosition.setFromMatrixPosition( this.modelViewMatrix );
  18960. if ( raycaster.camera.isPerspectiveCamera && this.material.sizeAttenuation === false ) {
  18961. _worldScale.multiplyScalar( - _mvPosition.z );
  18962. }
  18963. const rotation = this.material.rotation;
  18964. let sin, cos;
  18965. if ( rotation !== 0 ) {
  18966. cos = Math.cos( rotation );
  18967. sin = Math.sin( rotation );
  18968. }
  18969. const center = this.center;
  18970. transformVertex( _vA.set( - 0.5, - 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  18971. transformVertex( _vB.set( 0.5, - 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  18972. transformVertex( _vC.set( 0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  18973. _uvA.set( 0, 0 );
  18974. _uvB.set( 1, 0 );
  18975. _uvC.set( 1, 1 );
  18976. // check first triangle
  18977. let intersect = raycaster.ray.intersectTriangle( _vA, _vB, _vC, false, _intersectPoint );
  18978. if ( intersect === null ) {
  18979. // check second triangle
  18980. transformVertex( _vB.set( - 0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  18981. _uvB.set( 0, 1 );
  18982. intersect = raycaster.ray.intersectTriangle( _vA, _vC, _vB, false, _intersectPoint );
  18983. if ( intersect === null ) {
  18984. return;
  18985. }
  18986. }
  18987. const distance = raycaster.ray.origin.distanceTo( _intersectPoint );
  18988. if ( distance < raycaster.near || distance > raycaster.far ) return;
  18989. intersects.push( {
  18990. distance: distance,
  18991. point: _intersectPoint.clone(),
  18992. uv: Triangle.getInterpolation( _intersectPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2() ),
  18993. face: null,
  18994. object: this
  18995. } );
  18996. }
  18997. copy( source, recursive ) {
  18998. super.copy( source, recursive );
  18999. if ( source.center !== undefined ) this.center.copy( source.center );
  19000. this.material = source.material;
  19001. return this;
  19002. }
  19003. }
  19004. function transformVertex( vertexPosition, mvPosition, center, scale, sin, cos ) {
  19005. // compute position in camera space
  19006. _alignedPosition.subVectors( vertexPosition, center ).addScalar( 0.5 ).multiply( scale );
  19007. // to check if rotation is not zero
  19008. if ( sin !== undefined ) {
  19009. _rotatedPosition.x = ( cos * _alignedPosition.x ) - ( sin * _alignedPosition.y );
  19010. _rotatedPosition.y = ( sin * _alignedPosition.x ) + ( cos * _alignedPosition.y );
  19011. } else {
  19012. _rotatedPosition.copy( _alignedPosition );
  19013. }
  19014. vertexPosition.copy( mvPosition );
  19015. vertexPosition.x += _rotatedPosition.x;
  19016. vertexPosition.y += _rotatedPosition.y;
  19017. // transform to world space
  19018. vertexPosition.applyMatrix4( _viewWorldMatrix );
  19019. }
  19020. const _v1$2 = /*@__PURE__*/ new Vector3();
  19021. const _v2$1 = /*@__PURE__*/ new Vector3();
  19022. class LOD extends Object3D {
  19023. constructor() {
  19024. super();
  19025. this._currentLevel = 0;
  19026. this.type = 'LOD';
  19027. Object.defineProperties( this, {
  19028. levels: {
  19029. enumerable: true,
  19030. value: []
  19031. },
  19032. isLOD: {
  19033. value: true,
  19034. }
  19035. } );
  19036. this.autoUpdate = true;
  19037. }
  19038. copy( source ) {
  19039. super.copy( source, false );
  19040. const levels = source.levels;
  19041. for ( let i = 0, l = levels.length; i < l; i ++ ) {
  19042. const level = levels[ i ];
  19043. this.addLevel( level.object.clone(), level.distance, level.hysteresis );
  19044. }
  19045. this.autoUpdate = source.autoUpdate;
  19046. return this;
  19047. }
  19048. addLevel( object, distance = 0, hysteresis = 0 ) {
  19049. distance = Math.abs( distance );
  19050. const levels = this.levels;
  19051. let l;
  19052. for ( l = 0; l < levels.length; l ++ ) {
  19053. if ( distance < levels[ l ].distance ) {
  19054. break;
  19055. }
  19056. }
  19057. levels.splice( l, 0, { distance: distance, hysteresis: hysteresis, object: object } );
  19058. this.add( object );
  19059. return this;
  19060. }
  19061. getCurrentLevel() {
  19062. return this._currentLevel;
  19063. }
  19064. getObjectForDistance( distance ) {
  19065. const levels = this.levels;
  19066. if ( levels.length > 0 ) {
  19067. let i, l;
  19068. for ( i = 1, l = levels.length; i < l; i ++ ) {
  19069. let levelDistance = levels[ i ].distance;
  19070. if ( levels[ i ].object.visible ) {
  19071. levelDistance -= levelDistance * levels[ i ].hysteresis;
  19072. }
  19073. if ( distance < levelDistance ) {
  19074. break;
  19075. }
  19076. }
  19077. return levels[ i - 1 ].object;
  19078. }
  19079. return null;
  19080. }
  19081. raycast( raycaster, intersects ) {
  19082. const levels = this.levels;
  19083. if ( levels.length > 0 ) {
  19084. _v1$2.setFromMatrixPosition( this.matrixWorld );
  19085. const distance = raycaster.ray.origin.distanceTo( _v1$2 );
  19086. this.getObjectForDistance( distance ).raycast( raycaster, intersects );
  19087. }
  19088. }
  19089. update( camera ) {
  19090. const levels = this.levels;
  19091. if ( levels.length > 1 ) {
  19092. _v1$2.setFromMatrixPosition( camera.matrixWorld );
  19093. _v2$1.setFromMatrixPosition( this.matrixWorld );
  19094. const distance = _v1$2.distanceTo( _v2$1 ) / camera.zoom;
  19095. levels[ 0 ].object.visible = true;
  19096. let i, l;
  19097. for ( i = 1, l = levels.length; i < l; i ++ ) {
  19098. let levelDistance = levels[ i ].distance;
  19099. if ( levels[ i ].object.visible ) {
  19100. levelDistance -= levelDistance * levels[ i ].hysteresis;
  19101. }
  19102. if ( distance >= levelDistance ) {
  19103. levels[ i - 1 ].object.visible = false;
  19104. levels[ i ].object.visible = true;
  19105. } else {
  19106. break;
  19107. }
  19108. }
  19109. this._currentLevel = i - 1;
  19110. for ( ; i < l; i ++ ) {
  19111. levels[ i ].object.visible = false;
  19112. }
  19113. }
  19114. }
  19115. toJSON( meta ) {
  19116. const data = super.toJSON( meta );
  19117. if ( this.autoUpdate === false ) data.object.autoUpdate = false;
  19118. data.object.levels = [];
  19119. const levels = this.levels;
  19120. for ( let i = 0, l = levels.length; i < l; i ++ ) {
  19121. const level = levels[ i ];
  19122. data.object.levels.push( {
  19123. object: level.object.uuid,
  19124. distance: level.distance,
  19125. hysteresis: level.hysteresis
  19126. } );
  19127. }
  19128. return data;
  19129. }
  19130. }
  19131. const _basePosition = /*@__PURE__*/ new Vector3();
  19132. const _skinIndex = /*@__PURE__*/ new Vector4();
  19133. const _skinWeight = /*@__PURE__*/ new Vector4();
  19134. const _vector3 = /*@__PURE__*/ new Vector3();
  19135. const _matrix4 = /*@__PURE__*/ new Matrix4();
  19136. const _vertex = /*@__PURE__*/ new Vector3();
  19137. const _sphere$4 = /*@__PURE__*/ new Sphere();
  19138. const _inverseMatrix$2 = /*@__PURE__*/ new Matrix4();
  19139. const _ray$2 = /*@__PURE__*/ new Ray();
  19140. class SkinnedMesh extends Mesh {
  19141. constructor( geometry, material ) {
  19142. super( geometry, material );
  19143. this.isSkinnedMesh = true;
  19144. this.type = 'SkinnedMesh';
  19145. this.bindMode = AttachedBindMode;
  19146. this.bindMatrix = new Matrix4();
  19147. this.bindMatrixInverse = new Matrix4();
  19148. this.boundingBox = null;
  19149. this.boundingSphere = null;
  19150. }
  19151. computeBoundingBox() {
  19152. const geometry = this.geometry;
  19153. if ( this.boundingBox === null ) {
  19154. this.boundingBox = new Box3();
  19155. }
  19156. this.boundingBox.makeEmpty();
  19157. const positionAttribute = geometry.getAttribute( 'position' );
  19158. for ( let i = 0; i < positionAttribute.count; i ++ ) {
  19159. this.getVertexPosition( i, _vertex );
  19160. this.boundingBox.expandByPoint( _vertex );
  19161. }
  19162. }
  19163. computeBoundingSphere() {
  19164. const geometry = this.geometry;
  19165. if ( this.boundingSphere === null ) {
  19166. this.boundingSphere = new Sphere();
  19167. }
  19168. this.boundingSphere.makeEmpty();
  19169. const positionAttribute = geometry.getAttribute( 'position' );
  19170. for ( let i = 0; i < positionAttribute.count; i ++ ) {
  19171. this.getVertexPosition( i, _vertex );
  19172. this.boundingSphere.expandByPoint( _vertex );
  19173. }
  19174. }
  19175. copy( source, recursive ) {
  19176. super.copy( source, recursive );
  19177. this.bindMode = source.bindMode;
  19178. this.bindMatrix.copy( source.bindMatrix );
  19179. this.bindMatrixInverse.copy( source.bindMatrixInverse );
  19180. this.skeleton = source.skeleton;
  19181. if ( source.boundingBox !== null ) this.boundingBox = source.boundingBox.clone();
  19182. if ( source.boundingSphere !== null ) this.boundingSphere = source.boundingSphere.clone();
  19183. return this;
  19184. }
  19185. raycast( raycaster, intersects ) {
  19186. const material = this.material;
  19187. const matrixWorld = this.matrixWorld;
  19188. if ( material === undefined ) return;
  19189. // test with bounding sphere in world space
  19190. if ( this.boundingSphere === null ) this.computeBoundingSphere();
  19191. _sphere$4.copy( this.boundingSphere );
  19192. _sphere$4.applyMatrix4( matrixWorld );
  19193. if ( raycaster.ray.intersectsSphere( _sphere$4 ) === false ) return;
  19194. // convert ray to local space of skinned mesh
  19195. _inverseMatrix$2.copy( matrixWorld ).invert();
  19196. _ray$2.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$2 );
  19197. // test with bounding box in local space
  19198. if ( this.boundingBox !== null ) {
  19199. if ( _ray$2.intersectsBox( this.boundingBox ) === false ) return;
  19200. }
  19201. // test for intersections with geometry
  19202. this._computeIntersections( raycaster, intersects, _ray$2 );
  19203. }
  19204. getVertexPosition( index, target ) {
  19205. super.getVertexPosition( index, target );
  19206. this.applyBoneTransform( index, target );
  19207. return target;
  19208. }
  19209. bind( skeleton, bindMatrix ) {
  19210. this.skeleton = skeleton;
  19211. if ( bindMatrix === undefined ) {
  19212. this.updateMatrixWorld( true );
  19213. this.skeleton.calculateInverses();
  19214. bindMatrix = this.matrixWorld;
  19215. }
  19216. this.bindMatrix.copy( bindMatrix );
  19217. this.bindMatrixInverse.copy( bindMatrix ).invert();
  19218. }
  19219. pose() {
  19220. this.skeleton.pose();
  19221. }
  19222. normalizeSkinWeights() {
  19223. const vector = new Vector4();
  19224. const skinWeight = this.geometry.attributes.skinWeight;
  19225. for ( let i = 0, l = skinWeight.count; i < l; i ++ ) {
  19226. vector.fromBufferAttribute( skinWeight, i );
  19227. const scale = 1.0 / vector.manhattanLength();
  19228. if ( scale !== Infinity ) {
  19229. vector.multiplyScalar( scale );
  19230. } else {
  19231. vector.set( 1, 0, 0, 0 ); // do something reasonable
  19232. }
  19233. skinWeight.setXYZW( i, vector.x, vector.y, vector.z, vector.w );
  19234. }
  19235. }
  19236. updateMatrixWorld( force ) {
  19237. super.updateMatrixWorld( force );
  19238. if ( this.bindMode === AttachedBindMode ) {
  19239. this.bindMatrixInverse.copy( this.matrixWorld ).invert();
  19240. } else if ( this.bindMode === DetachedBindMode ) {
  19241. this.bindMatrixInverse.copy( this.bindMatrix ).invert();
  19242. } else {
  19243. console.warn( 'THREE.SkinnedMesh: Unrecognized bindMode: ' + this.bindMode );
  19244. }
  19245. }
  19246. applyBoneTransform( index, vector ) {
  19247. const skeleton = this.skeleton;
  19248. const geometry = this.geometry;
  19249. _skinIndex.fromBufferAttribute( geometry.attributes.skinIndex, index );
  19250. _skinWeight.fromBufferAttribute( geometry.attributes.skinWeight, index );
  19251. _basePosition.copy( vector ).applyMatrix4( this.bindMatrix );
  19252. vector.set( 0, 0, 0 );
  19253. for ( let i = 0; i < 4; i ++ ) {
  19254. const weight = _skinWeight.getComponent( i );
  19255. if ( weight !== 0 ) {
  19256. const boneIndex = _skinIndex.getComponent( i );
  19257. _matrix4.multiplyMatrices( skeleton.bones[ boneIndex ].matrixWorld, skeleton.boneInverses[ boneIndex ] );
  19258. vector.addScaledVector( _vector3.copy( _basePosition ).applyMatrix4( _matrix4 ), weight );
  19259. }
  19260. }
  19261. return vector.applyMatrix4( this.bindMatrixInverse );
  19262. }
  19263. }
  19264. class Bone extends Object3D {
  19265. constructor() {
  19266. super();
  19267. this.isBone = true;
  19268. this.type = 'Bone';
  19269. }
  19270. }
  19271. class DataTexture extends Texture {
  19272. constructor( data = null, width = 1, height = 1, format, type, mapping, wrapS, wrapT, magFilter = NearestFilter, minFilter = NearestFilter, anisotropy, colorSpace ) {
  19273. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace );
  19274. this.isDataTexture = true;
  19275. this.image = { data: data, width: width, height: height };
  19276. this.generateMipmaps = false;
  19277. this.flipY = false;
  19278. this.unpackAlignment = 1;
  19279. }
  19280. }
  19281. const _offsetMatrix = /*@__PURE__*/ new Matrix4();
  19282. const _identityMatrix$1 = /*@__PURE__*/ new Matrix4();
  19283. class Skeleton {
  19284. constructor( bones = [], boneInverses = [] ) {
  19285. this.uuid = generateUUID();
  19286. this.bones = bones.slice( 0 );
  19287. this.boneInverses = boneInverses;
  19288. this.boneMatrices = null;
  19289. this.boneTexture = null;
  19290. this.init();
  19291. }
  19292. init() {
  19293. const bones = this.bones;
  19294. const boneInverses = this.boneInverses;
  19295. this.boneMatrices = new Float32Array( bones.length * 16 );
  19296. // calculate inverse bone matrices if necessary
  19297. if ( boneInverses.length === 0 ) {
  19298. this.calculateInverses();
  19299. } else {
  19300. // handle special case
  19301. if ( bones.length !== boneInverses.length ) {
  19302. console.warn( 'THREE.Skeleton: Number of inverse bone matrices does not match amount of bones.' );
  19303. this.boneInverses = [];
  19304. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  19305. this.boneInverses.push( new Matrix4() );
  19306. }
  19307. }
  19308. }
  19309. }
  19310. calculateInverses() {
  19311. this.boneInverses.length = 0;
  19312. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  19313. const inverse = new Matrix4();
  19314. if ( this.bones[ i ] ) {
  19315. inverse.copy( this.bones[ i ].matrixWorld ).invert();
  19316. }
  19317. this.boneInverses.push( inverse );
  19318. }
  19319. }
  19320. pose() {
  19321. // recover the bind-time world matrices
  19322. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  19323. const bone = this.bones[ i ];
  19324. if ( bone ) {
  19325. bone.matrixWorld.copy( this.boneInverses[ i ] ).invert();
  19326. }
  19327. }
  19328. // compute the local matrices, positions, rotations and scales
  19329. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  19330. const bone = this.bones[ i ];
  19331. if ( bone ) {
  19332. if ( bone.parent && bone.parent.isBone ) {
  19333. bone.matrix.copy( bone.parent.matrixWorld ).invert();
  19334. bone.matrix.multiply( bone.matrixWorld );
  19335. } else {
  19336. bone.matrix.copy( bone.matrixWorld );
  19337. }
  19338. bone.matrix.decompose( bone.position, bone.quaternion, bone.scale );
  19339. }
  19340. }
  19341. }
  19342. update() {
  19343. const bones = this.bones;
  19344. const boneInverses = this.boneInverses;
  19345. const boneMatrices = this.boneMatrices;
  19346. const boneTexture = this.boneTexture;
  19347. // flatten bone matrices to array
  19348. for ( let i = 0, il = bones.length; i < il; i ++ ) {
  19349. // compute the offset between the current and the original transform
  19350. const matrix = bones[ i ] ? bones[ i ].matrixWorld : _identityMatrix$1;
  19351. _offsetMatrix.multiplyMatrices( matrix, boneInverses[ i ] );
  19352. _offsetMatrix.toArray( boneMatrices, i * 16 );
  19353. }
  19354. if ( boneTexture !== null ) {
  19355. boneTexture.needsUpdate = true;
  19356. }
  19357. }
  19358. clone() {
  19359. return new Skeleton( this.bones, this.boneInverses );
  19360. }
  19361. computeBoneTexture() {
  19362. // layout (1 matrix = 4 pixels)
  19363. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  19364. // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8)
  19365. // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16)
  19366. // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32)
  19367. // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64)
  19368. let size = Math.sqrt( this.bones.length * 4 ); // 4 pixels needed for 1 matrix
  19369. size = Math.ceil( size / 4 ) * 4;
  19370. size = Math.max( size, 4 );
  19371. const boneMatrices = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel
  19372. boneMatrices.set( this.boneMatrices ); // copy current values
  19373. const boneTexture = new DataTexture( boneMatrices, size, size, RGBAFormat, FloatType );
  19374. boneTexture.needsUpdate = true;
  19375. this.boneMatrices = boneMatrices;
  19376. this.boneTexture = boneTexture;
  19377. return this;
  19378. }
  19379. getBoneByName( name ) {
  19380. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  19381. const bone = this.bones[ i ];
  19382. if ( bone.name === name ) {
  19383. return bone;
  19384. }
  19385. }
  19386. return undefined;
  19387. }
  19388. dispose( ) {
  19389. if ( this.boneTexture !== null ) {
  19390. this.boneTexture.dispose();
  19391. this.boneTexture = null;
  19392. }
  19393. }
  19394. fromJSON( json, bones ) {
  19395. this.uuid = json.uuid;
  19396. for ( let i = 0, l = json.bones.length; i < l; i ++ ) {
  19397. const uuid = json.bones[ i ];
  19398. let bone = bones[ uuid ];
  19399. if ( bone === undefined ) {
  19400. console.warn( 'THREE.Skeleton: No bone found with UUID:', uuid );
  19401. bone = new Bone();
  19402. }
  19403. this.bones.push( bone );
  19404. this.boneInverses.push( new Matrix4().fromArray( json.boneInverses[ i ] ) );
  19405. }
  19406. this.init();
  19407. return this;
  19408. }
  19409. toJSON() {
  19410. const data = {
  19411. metadata: {
  19412. version: 4.6,
  19413. type: 'Skeleton',
  19414. generator: 'Skeleton.toJSON'
  19415. },
  19416. bones: [],
  19417. boneInverses: []
  19418. };
  19419. data.uuid = this.uuid;
  19420. const bones = this.bones;
  19421. const boneInverses = this.boneInverses;
  19422. for ( let i = 0, l = bones.length; i < l; i ++ ) {
  19423. const bone = bones[ i ];
  19424. data.bones.push( bone.uuid );
  19425. const boneInverse = boneInverses[ i ];
  19426. data.boneInverses.push( boneInverse.toArray() );
  19427. }
  19428. return data;
  19429. }
  19430. }
  19431. class InstancedBufferAttribute extends BufferAttribute {
  19432. constructor( array, itemSize, normalized, meshPerAttribute = 1 ) {
  19433. super( array, itemSize, normalized );
  19434. this.isInstancedBufferAttribute = true;
  19435. this.meshPerAttribute = meshPerAttribute;
  19436. }
  19437. copy( source ) {
  19438. super.copy( source );
  19439. this.meshPerAttribute = source.meshPerAttribute;
  19440. return this;
  19441. }
  19442. toJSON() {
  19443. const data = super.toJSON();
  19444. data.meshPerAttribute = this.meshPerAttribute;
  19445. data.isInstancedBufferAttribute = true;
  19446. return data;
  19447. }
  19448. }
  19449. const _instanceLocalMatrix = /*@__PURE__*/ new Matrix4();
  19450. const _instanceWorldMatrix = /*@__PURE__*/ new Matrix4();
  19451. const _instanceIntersects = [];
  19452. const _box3 = /*@__PURE__*/ new Box3();
  19453. const _identity = /*@__PURE__*/ new Matrix4();
  19454. const _mesh$1 = /*@__PURE__*/ new Mesh();
  19455. const _sphere$3 = /*@__PURE__*/ new Sphere();
  19456. class InstancedMesh extends Mesh {
  19457. constructor( geometry, material, count ) {
  19458. super( geometry, material );
  19459. this.isInstancedMesh = true;
  19460. this.instanceMatrix = new InstancedBufferAttribute( new Float32Array( count * 16 ), 16 );
  19461. this.instanceColor = null;
  19462. this.morphTexture = null;
  19463. this.count = count;
  19464. this.boundingBox = null;
  19465. this.boundingSphere = null;
  19466. for ( let i = 0; i < count; i ++ ) {
  19467. this.setMatrixAt( i, _identity );
  19468. }
  19469. }
  19470. computeBoundingBox() {
  19471. const geometry = this.geometry;
  19472. const count = this.count;
  19473. if ( this.boundingBox === null ) {
  19474. this.boundingBox = new Box3();
  19475. }
  19476. if ( geometry.boundingBox === null ) {
  19477. geometry.computeBoundingBox();
  19478. }
  19479. this.boundingBox.makeEmpty();
  19480. for ( let i = 0; i < count; i ++ ) {
  19481. this.getMatrixAt( i, _instanceLocalMatrix );
  19482. _box3.copy( geometry.boundingBox ).applyMatrix4( _instanceLocalMatrix );
  19483. this.boundingBox.union( _box3 );
  19484. }
  19485. }
  19486. computeBoundingSphere() {
  19487. const geometry = this.geometry;
  19488. const count = this.count;
  19489. if ( this.boundingSphere === null ) {
  19490. this.boundingSphere = new Sphere();
  19491. }
  19492. if ( geometry.boundingSphere === null ) {
  19493. geometry.computeBoundingSphere();
  19494. }
  19495. this.boundingSphere.makeEmpty();
  19496. for ( let i = 0; i < count; i ++ ) {
  19497. this.getMatrixAt( i, _instanceLocalMatrix );
  19498. _sphere$3.copy( geometry.boundingSphere ).applyMatrix4( _instanceLocalMatrix );
  19499. this.boundingSphere.union( _sphere$3 );
  19500. }
  19501. }
  19502. copy( source, recursive ) {
  19503. super.copy( source, recursive );
  19504. this.instanceMatrix.copy( source.instanceMatrix );
  19505. if ( source.instanceColor !== null ) this.instanceColor = source.instanceColor.clone();
  19506. this.count = source.count;
  19507. if ( source.boundingBox !== null ) this.boundingBox = source.boundingBox.clone();
  19508. if ( source.boundingSphere !== null ) this.boundingSphere = source.boundingSphere.clone();
  19509. return this;
  19510. }
  19511. getColorAt( index, color ) {
  19512. color.fromArray( this.instanceColor.array, index * 3 );
  19513. }
  19514. getMatrixAt( index, matrix ) {
  19515. matrix.fromArray( this.instanceMatrix.array, index * 16 );
  19516. }
  19517. getMorphAt( index, object ) {
  19518. const objectInfluences = object.morphTargetInfluences;
  19519. const array = this.morphTexture.source.data.data;
  19520. const len = objectInfluences.length + 1; // All influences + the baseInfluenceSum
  19521. const dataIndex = index * len + 1; // Skip the baseInfluenceSum at the beginning
  19522. for ( let i = 0; i < objectInfluences.length; i ++ ) {
  19523. objectInfluences[ i ] = array[ dataIndex + i ];
  19524. }
  19525. }
  19526. raycast( raycaster, intersects ) {
  19527. const matrixWorld = this.matrixWorld;
  19528. const raycastTimes = this.count;
  19529. _mesh$1.geometry = this.geometry;
  19530. _mesh$1.material = this.material;
  19531. if ( _mesh$1.material === undefined ) return;
  19532. // test with bounding sphere first
  19533. if ( this.boundingSphere === null ) this.computeBoundingSphere();
  19534. _sphere$3.copy( this.boundingSphere );
  19535. _sphere$3.applyMatrix4( matrixWorld );
  19536. if ( raycaster.ray.intersectsSphere( _sphere$3 ) === false ) return;
  19537. // now test each instance
  19538. for ( let instanceId = 0; instanceId < raycastTimes; instanceId ++ ) {
  19539. // calculate the world matrix for each instance
  19540. this.getMatrixAt( instanceId, _instanceLocalMatrix );
  19541. _instanceWorldMatrix.multiplyMatrices( matrixWorld, _instanceLocalMatrix );
  19542. // the mesh represents this single instance
  19543. _mesh$1.matrixWorld = _instanceWorldMatrix;
  19544. _mesh$1.raycast( raycaster, _instanceIntersects );
  19545. // process the result of raycast
  19546. for ( let i = 0, l = _instanceIntersects.length; i < l; i ++ ) {
  19547. const intersect = _instanceIntersects[ i ];
  19548. intersect.instanceId = instanceId;
  19549. intersect.object = this;
  19550. intersects.push( intersect );
  19551. }
  19552. _instanceIntersects.length = 0;
  19553. }
  19554. }
  19555. setColorAt( index, color ) {
  19556. if ( this.instanceColor === null ) {
  19557. this.instanceColor = new InstancedBufferAttribute( new Float32Array( this.instanceMatrix.count * 3 ), 3 );
  19558. }
  19559. color.toArray( this.instanceColor.array, index * 3 );
  19560. }
  19561. setMatrixAt( index, matrix ) {
  19562. matrix.toArray( this.instanceMatrix.array, index * 16 );
  19563. }
  19564. setMorphAt( index, object ) {
  19565. const objectInfluences = object.morphTargetInfluences;
  19566. const len = objectInfluences.length + 1; // morphBaseInfluence + all influences
  19567. if ( this.morphTexture === null ) {
  19568. this.morphTexture = new DataTexture( new Float32Array( len * this.count ), len, this.count, RedFormat, FloatType );
  19569. }
  19570. const array = this.morphTexture.source.data.data;
  19571. let morphInfluencesSum = 0;
  19572. for ( let i = 0; i < objectInfluences.length; i ++ ) {
  19573. morphInfluencesSum += objectInfluences[ i ];
  19574. }
  19575. const morphBaseInfluence = this.geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
  19576. const dataIndex = len * index;
  19577. array[ dataIndex ] = morphBaseInfluence;
  19578. array.set( objectInfluences, dataIndex + 1 );
  19579. }
  19580. updateMorphTargets() {
  19581. }
  19582. dispose() {
  19583. this.dispatchEvent( { type: 'dispose' } );
  19584. }
  19585. }
  19586. function sortOpaque( a, b ) {
  19587. return a.z - b.z;
  19588. }
  19589. function sortTransparent( a, b ) {
  19590. return b.z - a.z;
  19591. }
  19592. class MultiDrawRenderList {
  19593. constructor() {
  19594. this.index = 0;
  19595. this.pool = [];
  19596. this.list = [];
  19597. }
  19598. push( drawRange, z ) {
  19599. const pool = this.pool;
  19600. const list = this.list;
  19601. if ( this.index >= pool.length ) {
  19602. pool.push( {
  19603. start: - 1,
  19604. count: - 1,
  19605. z: - 1,
  19606. } );
  19607. }
  19608. const item = pool[ this.index ];
  19609. list.push( item );
  19610. this.index ++;
  19611. item.start = drawRange.start;
  19612. item.count = drawRange.count;
  19613. item.z = z;
  19614. }
  19615. reset() {
  19616. this.list.length = 0;
  19617. this.index = 0;
  19618. }
  19619. }
  19620. const ID_ATTR_NAME = 'batchId';
  19621. const _matrix = /*@__PURE__*/ new Matrix4();
  19622. const _invMatrixWorld = /*@__PURE__*/ new Matrix4();
  19623. const _identityMatrix = /*@__PURE__*/ new Matrix4();
  19624. const _projScreenMatrix$2 = /*@__PURE__*/ new Matrix4();
  19625. const _frustum = /*@__PURE__*/ new Frustum();
  19626. const _box$1 = /*@__PURE__*/ new Box3();
  19627. const _sphere$2 = /*@__PURE__*/ new Sphere();
  19628. const _vector$5 = /*@__PURE__*/ new Vector3();
  19629. const _renderList = /*@__PURE__*/ new MultiDrawRenderList();
  19630. const _mesh = /*@__PURE__*/ new Mesh();
  19631. const _batchIntersects = [];
  19632. // @TODO: SkinnedMesh support?
  19633. // @TODO: geometry.groups support?
  19634. // @TODO: geometry.drawRange support?
  19635. // @TODO: geometry.morphAttributes support?
  19636. // @TODO: Support uniform parameter per geometry
  19637. // @TODO: Add an "optimize" function to pack geometry and remove data gaps
  19638. // copies data from attribute "src" into "target" starting at "targetOffset"
  19639. function copyAttributeData( src, target, targetOffset = 0 ) {
  19640. const itemSize = target.itemSize;
  19641. if ( src.isInterleavedBufferAttribute || src.array.constructor !== target.array.constructor ) {
  19642. // use the component getters and setters if the array data cannot
  19643. // be copied directly
  19644. const vertexCount = src.count;
  19645. for ( let i = 0; i < vertexCount; i ++ ) {
  19646. for ( let c = 0; c < itemSize; c ++ ) {
  19647. target.setComponent( i + targetOffset, c, src.getComponent( i, c ) );
  19648. }
  19649. }
  19650. } else {
  19651. // faster copy approach using typed array set function
  19652. target.array.set( src.array, targetOffset * itemSize );
  19653. }
  19654. target.needsUpdate = true;
  19655. }
  19656. class BatchedMesh extends Mesh {
  19657. get maxGeometryCount() {
  19658. return this._maxGeometryCount;
  19659. }
  19660. constructor( maxGeometryCount, maxVertexCount, maxIndexCount = maxVertexCount * 2, material ) {
  19661. super( new BufferGeometry(), material );
  19662. this.isBatchedMesh = true;
  19663. this.perObjectFrustumCulled = true;
  19664. this.sortObjects = true;
  19665. this.boundingBox = null;
  19666. this.boundingSphere = null;
  19667. this.customSort = null;
  19668. this._drawRanges = [];
  19669. this._reservedRanges = [];
  19670. this._visibility = [];
  19671. this._active = [];
  19672. this._bounds = [];
  19673. this._maxGeometryCount = maxGeometryCount;
  19674. this._maxVertexCount = maxVertexCount;
  19675. this._maxIndexCount = maxIndexCount;
  19676. this._geometryInitialized = false;
  19677. this._geometryCount = 0;
  19678. this._multiDrawCounts = new Int32Array( maxGeometryCount );
  19679. this._multiDrawStarts = new Int32Array( maxGeometryCount );
  19680. this._multiDrawCount = 0;
  19681. this._visibilityChanged = true;
  19682. // Local matrix per geometry by using data texture
  19683. this._matricesTexture = null;
  19684. this._initMatricesTexture();
  19685. }
  19686. _initMatricesTexture() {
  19687. // layout (1 matrix = 4 pixels)
  19688. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  19689. // with 8x8 pixel texture max 16 matrices * 4 pixels = (8 * 8)
  19690. // 16x16 pixel texture max 64 matrices * 4 pixels = (16 * 16)
  19691. // 32x32 pixel texture max 256 matrices * 4 pixels = (32 * 32)
  19692. // 64x64 pixel texture max 1024 matrices * 4 pixels = (64 * 64)
  19693. let size = Math.sqrt( this._maxGeometryCount * 4 ); // 4 pixels needed for 1 matrix
  19694. size = Math.ceil( size / 4 ) * 4;
  19695. size = Math.max( size, 4 );
  19696. const matricesArray = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel
  19697. const matricesTexture = new DataTexture( matricesArray, size, size, RGBAFormat, FloatType );
  19698. this._matricesTexture = matricesTexture;
  19699. }
  19700. _initializeGeometry( reference ) {
  19701. const geometry = this.geometry;
  19702. const maxVertexCount = this._maxVertexCount;
  19703. const maxGeometryCount = this._maxGeometryCount;
  19704. const maxIndexCount = this._maxIndexCount;
  19705. if ( this._geometryInitialized === false ) {
  19706. for ( const attributeName in reference.attributes ) {
  19707. const srcAttribute = reference.getAttribute( attributeName );
  19708. const { array, itemSize, normalized } = srcAttribute;
  19709. const dstArray = new array.constructor( maxVertexCount * itemSize );
  19710. const dstAttribute = new srcAttribute.constructor( dstArray, itemSize, normalized );
  19711. dstAttribute.setUsage( srcAttribute.usage );
  19712. geometry.setAttribute( attributeName, dstAttribute );
  19713. }
  19714. if ( reference.getIndex() !== null ) {
  19715. const indexArray = maxVertexCount > 65536
  19716. ? new Uint32Array( maxIndexCount )
  19717. : new Uint16Array( maxIndexCount );
  19718. geometry.setIndex( new BufferAttribute( indexArray, 1 ) );
  19719. }
  19720. const idArray = maxGeometryCount > 65536
  19721. ? new Uint32Array( maxVertexCount )
  19722. : new Uint16Array( maxVertexCount );
  19723. geometry.setAttribute( ID_ATTR_NAME, new BufferAttribute( idArray, 1 ) );
  19724. this._geometryInitialized = true;
  19725. }
  19726. }
  19727. // Make sure the geometry is compatible with the existing combined geometry atributes
  19728. _validateGeometry( geometry ) {
  19729. // check that the geometry doesn't have a version of our reserved id attribute
  19730. if ( geometry.getAttribute( ID_ATTR_NAME ) ) {
  19731. throw new Error( `BatchedMesh: Geometry cannot use attribute "${ ID_ATTR_NAME }"` );
  19732. }
  19733. // check to ensure the geometries are using consistent attributes and indices
  19734. const batchGeometry = this.geometry;
  19735. if ( Boolean( geometry.getIndex() ) !== Boolean( batchGeometry.getIndex() ) ) {
  19736. throw new Error( 'BatchedMesh: All geometries must consistently have "index".' );
  19737. }
  19738. for ( const attributeName in batchGeometry.attributes ) {
  19739. if ( attributeName === ID_ATTR_NAME ) {
  19740. continue;
  19741. }
  19742. if ( ! geometry.hasAttribute( attributeName ) ) {
  19743. throw new Error( `BatchedMesh: Added geometry missing "${ attributeName }". All geometries must have consistent attributes.` );
  19744. }
  19745. const srcAttribute = geometry.getAttribute( attributeName );
  19746. const dstAttribute = batchGeometry.getAttribute( attributeName );
  19747. if ( srcAttribute.itemSize !== dstAttribute.itemSize || srcAttribute.normalized !== dstAttribute.normalized ) {
  19748. throw new Error( 'BatchedMesh: All attributes must have a consistent itemSize and normalized value.' );
  19749. }
  19750. }
  19751. }
  19752. setCustomSort( func ) {
  19753. this.customSort = func;
  19754. return this;
  19755. }
  19756. computeBoundingBox() {
  19757. if ( this.boundingBox === null ) {
  19758. this.boundingBox = new Box3();
  19759. }
  19760. const geometryCount = this._geometryCount;
  19761. const boundingBox = this.boundingBox;
  19762. const active = this._active;
  19763. boundingBox.makeEmpty();
  19764. for ( let i = 0; i < geometryCount; i ++ ) {
  19765. if ( active[ i ] === false ) continue;
  19766. this.getMatrixAt( i, _matrix );
  19767. this.getBoundingBoxAt( i, _box$1 ).applyMatrix4( _matrix );
  19768. boundingBox.union( _box$1 );
  19769. }
  19770. }
  19771. computeBoundingSphere() {
  19772. if ( this.boundingSphere === null ) {
  19773. this.boundingSphere = new Sphere();
  19774. }
  19775. const geometryCount = this._geometryCount;
  19776. const boundingSphere = this.boundingSphere;
  19777. const active = this._active;
  19778. boundingSphere.makeEmpty();
  19779. for ( let i = 0; i < geometryCount; i ++ ) {
  19780. if ( active[ i ] === false ) continue;
  19781. this.getMatrixAt( i, _matrix );
  19782. this.getBoundingSphereAt( i, _sphere$2 ).applyMatrix4( _matrix );
  19783. boundingSphere.union( _sphere$2 );
  19784. }
  19785. }
  19786. addGeometry( geometry, vertexCount = - 1, indexCount = - 1 ) {
  19787. this._initializeGeometry( geometry );
  19788. this._validateGeometry( geometry );
  19789. // ensure we're not over geometry
  19790. if ( this._geometryCount >= this._maxGeometryCount ) {
  19791. throw new Error( 'BatchedMesh: Maximum geometry count reached.' );
  19792. }
  19793. // get the necessary range fo the geometry
  19794. const reservedRange = {
  19795. vertexStart: - 1,
  19796. vertexCount: - 1,
  19797. indexStart: - 1,
  19798. indexCount: - 1,
  19799. };
  19800. let lastRange = null;
  19801. const reservedRanges = this._reservedRanges;
  19802. const drawRanges = this._drawRanges;
  19803. const bounds = this._bounds;
  19804. if ( this._geometryCount !== 0 ) {
  19805. lastRange = reservedRanges[ reservedRanges.length - 1 ];
  19806. }
  19807. if ( vertexCount === - 1 ) {
  19808. reservedRange.vertexCount = geometry.getAttribute( 'position' ).count;
  19809. } else {
  19810. reservedRange.vertexCount = vertexCount;
  19811. }
  19812. if ( lastRange === null ) {
  19813. reservedRange.vertexStart = 0;
  19814. } else {
  19815. reservedRange.vertexStart = lastRange.vertexStart + lastRange.vertexCount;
  19816. }
  19817. const index = geometry.getIndex();
  19818. const hasIndex = index !== null;
  19819. if ( hasIndex ) {
  19820. if ( indexCount === - 1 ) {
  19821. reservedRange.indexCount = index.count;
  19822. } else {
  19823. reservedRange.indexCount = indexCount;
  19824. }
  19825. if ( lastRange === null ) {
  19826. reservedRange.indexStart = 0;
  19827. } else {
  19828. reservedRange.indexStart = lastRange.indexStart + lastRange.indexCount;
  19829. }
  19830. }
  19831. if (
  19832. reservedRange.indexStart !== - 1 &&
  19833. reservedRange.indexStart + reservedRange.indexCount > this._maxIndexCount ||
  19834. reservedRange.vertexStart + reservedRange.vertexCount > this._maxVertexCount
  19835. ) {
  19836. throw new Error( 'BatchedMesh: Reserved space request exceeds the maximum buffer size.' );
  19837. }
  19838. const visibility = this._visibility;
  19839. const active = this._active;
  19840. const matricesTexture = this._matricesTexture;
  19841. const matricesArray = this._matricesTexture.image.data;
  19842. // push new visibility states
  19843. visibility.push( true );
  19844. active.push( true );
  19845. // update id
  19846. const geometryId = this._geometryCount;
  19847. this._geometryCount ++;
  19848. // initialize matrix information
  19849. _identityMatrix.toArray( matricesArray, geometryId * 16 );
  19850. matricesTexture.needsUpdate = true;
  19851. // add the reserved range and draw range objects
  19852. reservedRanges.push( reservedRange );
  19853. drawRanges.push( {
  19854. start: hasIndex ? reservedRange.indexStart : reservedRange.vertexStart,
  19855. count: - 1
  19856. } );
  19857. bounds.push( {
  19858. boxInitialized: false,
  19859. box: new Box3(),
  19860. sphereInitialized: false,
  19861. sphere: new Sphere()
  19862. } );
  19863. // set the id for the geometry
  19864. const idAttribute = this.geometry.getAttribute( ID_ATTR_NAME );
  19865. for ( let i = 0; i < reservedRange.vertexCount; i ++ ) {
  19866. idAttribute.setX( reservedRange.vertexStart + i, geometryId );
  19867. }
  19868. idAttribute.needsUpdate = true;
  19869. // update the geometry
  19870. this.setGeometryAt( geometryId, geometry );
  19871. return geometryId;
  19872. }
  19873. setGeometryAt( id, geometry ) {
  19874. if ( id >= this._geometryCount ) {
  19875. throw new Error( 'BatchedMesh: Maximum geometry count reached.' );
  19876. }
  19877. this._validateGeometry( geometry );
  19878. const batchGeometry = this.geometry;
  19879. const hasIndex = batchGeometry.getIndex() !== null;
  19880. const dstIndex = batchGeometry.getIndex();
  19881. const srcIndex = geometry.getIndex();
  19882. const reservedRange = this._reservedRanges[ id ];
  19883. if (
  19884. hasIndex &&
  19885. srcIndex.count > reservedRange.indexCount ||
  19886. geometry.attributes.position.count > reservedRange.vertexCount
  19887. ) {
  19888. throw new Error( 'BatchedMesh: Reserved space not large enough for provided geometry.' );
  19889. }
  19890. // copy geometry over
  19891. const vertexStart = reservedRange.vertexStart;
  19892. const vertexCount = reservedRange.vertexCount;
  19893. for ( const attributeName in batchGeometry.attributes ) {
  19894. if ( attributeName === ID_ATTR_NAME ) {
  19895. continue;
  19896. }
  19897. // copy attribute data
  19898. const srcAttribute = geometry.getAttribute( attributeName );
  19899. const dstAttribute = batchGeometry.getAttribute( attributeName );
  19900. copyAttributeData( srcAttribute, dstAttribute, vertexStart );
  19901. // fill the rest in with zeroes
  19902. const itemSize = srcAttribute.itemSize;
  19903. for ( let i = srcAttribute.count, l = vertexCount; i < l; i ++ ) {
  19904. const index = vertexStart + i;
  19905. for ( let c = 0; c < itemSize; c ++ ) {
  19906. dstAttribute.setComponent( index, c, 0 );
  19907. }
  19908. }
  19909. dstAttribute.needsUpdate = true;
  19910. }
  19911. // copy index
  19912. if ( hasIndex ) {
  19913. const indexStart = reservedRange.indexStart;
  19914. // copy index data over
  19915. for ( let i = 0; i < srcIndex.count; i ++ ) {
  19916. dstIndex.setX( indexStart + i, vertexStart + srcIndex.getX( i ) );
  19917. }
  19918. // fill the rest in with zeroes
  19919. for ( let i = srcIndex.count, l = reservedRange.indexCount; i < l; i ++ ) {
  19920. dstIndex.setX( indexStart + i, vertexStart );
  19921. }
  19922. dstIndex.needsUpdate = true;
  19923. }
  19924. // store the bounding boxes
  19925. const bound = this._bounds[ id ];
  19926. if ( geometry.boundingBox !== null ) {
  19927. bound.box.copy( geometry.boundingBox );
  19928. bound.boxInitialized = true;
  19929. } else {
  19930. bound.boxInitialized = false;
  19931. }
  19932. if ( geometry.boundingSphere !== null ) {
  19933. bound.sphere.copy( geometry.boundingSphere );
  19934. bound.sphereInitialized = true;
  19935. } else {
  19936. bound.sphereInitialized = false;
  19937. }
  19938. // set drawRange count
  19939. const drawRange = this._drawRanges[ id ];
  19940. const posAttr = geometry.getAttribute( 'position' );
  19941. drawRange.count = hasIndex ? srcIndex.count : posAttr.count;
  19942. this._visibilityChanged = true;
  19943. return id;
  19944. }
  19945. deleteGeometry( geometryId ) {
  19946. // Note: User needs to call optimize() afterward to pack the data.
  19947. const active = this._active;
  19948. if ( geometryId >= active.length || active[ geometryId ] === false ) {
  19949. return this;
  19950. }
  19951. active[ geometryId ] = false;
  19952. this._visibilityChanged = true;
  19953. return this;
  19954. }
  19955. // get bounding box and compute it if it doesn't exist
  19956. getBoundingBoxAt( id, target ) {
  19957. const active = this._active;
  19958. if ( active[ id ] === false ) {
  19959. return null;
  19960. }
  19961. // compute bounding box
  19962. const bound = this._bounds[ id ];
  19963. const box = bound.box;
  19964. const geometry = this.geometry;
  19965. if ( bound.boxInitialized === false ) {
  19966. box.makeEmpty();
  19967. const index = geometry.index;
  19968. const position = geometry.attributes.position;
  19969. const drawRange = this._drawRanges[ id ];
  19970. for ( let i = drawRange.start, l = drawRange.start + drawRange.count; i < l; i ++ ) {
  19971. let iv = i;
  19972. if ( index ) {
  19973. iv = index.getX( iv );
  19974. }
  19975. box.expandByPoint( _vector$5.fromBufferAttribute( position, iv ) );
  19976. }
  19977. bound.boxInitialized = true;
  19978. }
  19979. target.copy( box );
  19980. return target;
  19981. }
  19982. // get bounding sphere and compute it if it doesn't exist
  19983. getBoundingSphereAt( id, target ) {
  19984. const active = this._active;
  19985. if ( active[ id ] === false ) {
  19986. return null;
  19987. }
  19988. // compute bounding sphere
  19989. const bound = this._bounds[ id ];
  19990. const sphere = bound.sphere;
  19991. const geometry = this.geometry;
  19992. if ( bound.sphereInitialized === false ) {
  19993. sphere.makeEmpty();
  19994. this.getBoundingBoxAt( id, _box$1 );
  19995. _box$1.getCenter( sphere.center );
  19996. const index = geometry.index;
  19997. const position = geometry.attributes.position;
  19998. const drawRange = this._drawRanges[ id ];
  19999. let maxRadiusSq = 0;
  20000. for ( let i = drawRange.start, l = drawRange.start + drawRange.count; i < l; i ++ ) {
  20001. let iv = i;
  20002. if ( index ) {
  20003. iv = index.getX( iv );
  20004. }
  20005. _vector$5.fromBufferAttribute( position, iv );
  20006. maxRadiusSq = Math.max( maxRadiusSq, sphere.center.distanceToSquared( _vector$5 ) );
  20007. }
  20008. sphere.radius = Math.sqrt( maxRadiusSq );
  20009. bound.sphereInitialized = true;
  20010. }
  20011. target.copy( sphere );
  20012. return target;
  20013. }
  20014. setMatrixAt( geometryId, matrix ) {
  20015. // @TODO: Map geometryId to index of the arrays because
  20016. // optimize() can make geometryId mismatch the index
  20017. const active = this._active;
  20018. const matricesTexture = this._matricesTexture;
  20019. const matricesArray = this._matricesTexture.image.data;
  20020. const geometryCount = this._geometryCount;
  20021. if ( geometryId >= geometryCount || active[ geometryId ] === false ) {
  20022. return this;
  20023. }
  20024. matrix.toArray( matricesArray, geometryId * 16 );
  20025. matricesTexture.needsUpdate = true;
  20026. return this;
  20027. }
  20028. getMatrixAt( geometryId, matrix ) {
  20029. const active = this._active;
  20030. const matricesArray = this._matricesTexture.image.data;
  20031. const geometryCount = this._geometryCount;
  20032. if ( geometryId >= geometryCount || active[ geometryId ] === false ) {
  20033. return null;
  20034. }
  20035. return matrix.fromArray( matricesArray, geometryId * 16 );
  20036. }
  20037. setVisibleAt( geometryId, value ) {
  20038. const visibility = this._visibility;
  20039. const active = this._active;
  20040. const geometryCount = this._geometryCount;
  20041. // if the geometry is out of range, not active, or visibility state
  20042. // does not change then return early
  20043. if (
  20044. geometryId >= geometryCount ||
  20045. active[ geometryId ] === false ||
  20046. visibility[ geometryId ] === value
  20047. ) {
  20048. return this;
  20049. }
  20050. visibility[ geometryId ] = value;
  20051. this._visibilityChanged = true;
  20052. return this;
  20053. }
  20054. getVisibleAt( geometryId ) {
  20055. const visibility = this._visibility;
  20056. const active = this._active;
  20057. const geometryCount = this._geometryCount;
  20058. // return early if the geometry is out of range or not active
  20059. if ( geometryId >= geometryCount || active[ geometryId ] === false ) {
  20060. return false;
  20061. }
  20062. return visibility[ geometryId ];
  20063. }
  20064. raycast( raycaster, intersects ) {
  20065. const visibility = this._visibility;
  20066. const active = this._active;
  20067. const drawRanges = this._drawRanges;
  20068. const geometryCount = this._geometryCount;
  20069. const matrixWorld = this.matrixWorld;
  20070. const batchGeometry = this.geometry;
  20071. // iterate over each geometry
  20072. _mesh.material = this.material;
  20073. _mesh.geometry.index = batchGeometry.index;
  20074. _mesh.geometry.attributes = batchGeometry.attributes;
  20075. if ( _mesh.geometry.boundingBox === null ) {
  20076. _mesh.geometry.boundingBox = new Box3();
  20077. }
  20078. if ( _mesh.geometry.boundingSphere === null ) {
  20079. _mesh.geometry.boundingSphere = new Sphere();
  20080. }
  20081. for ( let i = 0; i < geometryCount; i ++ ) {
  20082. if ( ! visibility[ i ] || ! active[ i ] ) {
  20083. continue;
  20084. }
  20085. const drawRange = drawRanges[ i ];
  20086. _mesh.geometry.setDrawRange( drawRange.start, drawRange.count );
  20087. // ge the intersects
  20088. this.getMatrixAt( i, _mesh.matrixWorld ).premultiply( matrixWorld );
  20089. this.getBoundingBoxAt( i, _mesh.geometry.boundingBox );
  20090. this.getBoundingSphereAt( i, _mesh.geometry.boundingSphere );
  20091. _mesh.raycast( raycaster, _batchIntersects );
  20092. // add batch id to the intersects
  20093. for ( let j = 0, l = _batchIntersects.length; j < l; j ++ ) {
  20094. const intersect = _batchIntersects[ j ];
  20095. intersect.object = this;
  20096. intersect.batchId = i;
  20097. intersects.push( intersect );
  20098. }
  20099. _batchIntersects.length = 0;
  20100. }
  20101. _mesh.material = null;
  20102. _mesh.geometry.index = null;
  20103. _mesh.geometry.attributes = {};
  20104. _mesh.geometry.setDrawRange( 0, Infinity );
  20105. }
  20106. copy( source ) {
  20107. super.copy( source );
  20108. this.geometry = source.geometry.clone();
  20109. this.perObjectFrustumCulled = source.perObjectFrustumCulled;
  20110. this.sortObjects = source.sortObjects;
  20111. this.boundingBox = source.boundingBox !== null ? source.boundingBox.clone() : null;
  20112. this.boundingSphere = source.boundingSphere !== null ? source.boundingSphere.clone() : null;
  20113. this._drawRanges = source._drawRanges.map( range => ( { ...range } ) );
  20114. this._reservedRanges = source._reservedRanges.map( range => ( { ...range } ) );
  20115. this._visibility = source._visibility.slice();
  20116. this._active = source._active.slice();
  20117. this._bounds = source._bounds.map( bound => ( {
  20118. boxInitialized: bound.boxInitialized,
  20119. box: bound.box.clone(),
  20120. sphereInitialized: bound.sphereInitialized,
  20121. sphere: bound.sphere.clone()
  20122. } ) );
  20123. this._maxGeometryCount = source._maxGeometryCount;
  20124. this._maxVertexCount = source._maxVertexCount;
  20125. this._maxIndexCount = source._maxIndexCount;
  20126. this._geometryInitialized = source._geometryInitialized;
  20127. this._geometryCount = source._geometryCount;
  20128. this._multiDrawCounts = source._multiDrawCounts.slice();
  20129. this._multiDrawStarts = source._multiDrawStarts.slice();
  20130. this._matricesTexture = source._matricesTexture.clone();
  20131. this._matricesTexture.image.data = this._matricesTexture.image.slice();
  20132. return this;
  20133. }
  20134. dispose() {
  20135. // Assuming the geometry is not shared with other meshes
  20136. this.geometry.dispose();
  20137. this._matricesTexture.dispose();
  20138. this._matricesTexture = null;
  20139. return this;
  20140. }
  20141. onBeforeRender( renderer, scene, camera, geometry, material/*, _group*/ ) {
  20142. // if visibility has not changed and frustum culling and object sorting is not required
  20143. // then skip iterating over all items
  20144. if ( ! this._visibilityChanged && ! this.perObjectFrustumCulled && ! this.sortObjects ) {
  20145. return;
  20146. }
  20147. // the indexed version of the multi draw function requires specifying the start
  20148. // offset in bytes.
  20149. const index = geometry.getIndex();
  20150. const bytesPerElement = index === null ? 1 : index.array.BYTES_PER_ELEMENT;
  20151. const active = this._active;
  20152. const visibility = this._visibility;
  20153. const multiDrawStarts = this._multiDrawStarts;
  20154. const multiDrawCounts = this._multiDrawCounts;
  20155. const drawRanges = this._drawRanges;
  20156. const perObjectFrustumCulled = this.perObjectFrustumCulled;
  20157. // prepare the frustum in the local frame
  20158. if ( perObjectFrustumCulled ) {
  20159. _projScreenMatrix$2
  20160. .multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse )
  20161. .multiply( this.matrixWorld );
  20162. _frustum.setFromProjectionMatrix(
  20163. _projScreenMatrix$2,
  20164. renderer.coordinateSystem
  20165. );
  20166. }
  20167. let count = 0;
  20168. if ( this.sortObjects ) {
  20169. // get the camera position in the local frame
  20170. _invMatrixWorld.copy( this.matrixWorld ).invert();
  20171. _vector$5.setFromMatrixPosition( camera.matrixWorld ).applyMatrix4( _invMatrixWorld );
  20172. for ( let i = 0, l = visibility.length; i < l; i ++ ) {
  20173. if ( visibility[ i ] && active[ i ] ) {
  20174. // get the bounds in world space
  20175. this.getMatrixAt( i, _matrix );
  20176. this.getBoundingSphereAt( i, _sphere$2 ).applyMatrix4( _matrix );
  20177. // determine whether the batched geometry is within the frustum
  20178. let culled = false;
  20179. if ( perObjectFrustumCulled ) {
  20180. culled = ! _frustum.intersectsSphere( _sphere$2 );
  20181. }
  20182. if ( ! culled ) {
  20183. // get the distance from camera used for sorting
  20184. const z = _vector$5.distanceTo( _sphere$2.center );
  20185. _renderList.push( drawRanges[ i ], z );
  20186. }
  20187. }
  20188. }
  20189. // Sort the draw ranges and prep for rendering
  20190. const list = _renderList.list;
  20191. const customSort = this.customSort;
  20192. if ( customSort === null ) {
  20193. list.sort( material.transparent ? sortTransparent : sortOpaque );
  20194. } else {
  20195. customSort.call( this, list, camera );
  20196. }
  20197. for ( let i = 0, l = list.length; i < l; i ++ ) {
  20198. const item = list[ i ];
  20199. multiDrawStarts[ count ] = item.start * bytesPerElement;
  20200. multiDrawCounts[ count ] = item.count;
  20201. count ++;
  20202. }
  20203. _renderList.reset();
  20204. } else {
  20205. for ( let i = 0, l = visibility.length; i < l; i ++ ) {
  20206. if ( visibility[ i ] && active[ i ] ) {
  20207. // determine whether the batched geometry is within the frustum
  20208. let culled = false;
  20209. if ( perObjectFrustumCulled ) {
  20210. // get the bounds in world space
  20211. this.getMatrixAt( i, _matrix );
  20212. this.getBoundingSphereAt( i, _sphere$2 ).applyMatrix4( _matrix );
  20213. culled = ! _frustum.intersectsSphere( _sphere$2 );
  20214. }
  20215. if ( ! culled ) {
  20216. const range = drawRanges[ i ];
  20217. multiDrawStarts[ count ] = range.start * bytesPerElement;
  20218. multiDrawCounts[ count ] = range.count;
  20219. count ++;
  20220. }
  20221. }
  20222. }
  20223. }
  20224. this._multiDrawCount = count;
  20225. this._visibilityChanged = false;
  20226. }
  20227. onBeforeShadow( renderer, object, camera, shadowCamera, geometry, depthMaterial/* , group */ ) {
  20228. this.onBeforeRender( renderer, null, shadowCamera, geometry, depthMaterial );
  20229. }
  20230. }
  20231. class LineBasicMaterial extends Material {
  20232. constructor( parameters ) {
  20233. super();
  20234. this.isLineBasicMaterial = true;
  20235. this.type = 'LineBasicMaterial';
  20236. this.color = new Color( 0xffffff );
  20237. this.map = null;
  20238. this.linewidth = 1;
  20239. this.linecap = 'round';
  20240. this.linejoin = 'round';
  20241. this.fog = true;
  20242. this.setValues( parameters );
  20243. }
  20244. copy( source ) {
  20245. super.copy( source );
  20246. this.color.copy( source.color );
  20247. this.map = source.map;
  20248. this.linewidth = source.linewidth;
  20249. this.linecap = source.linecap;
  20250. this.linejoin = source.linejoin;
  20251. this.fog = source.fog;
  20252. return this;
  20253. }
  20254. }
  20255. const _start$1 = /*@__PURE__*/ new Vector3();
  20256. const _end$1 = /*@__PURE__*/ new Vector3();
  20257. const _inverseMatrix$1 = /*@__PURE__*/ new Matrix4();
  20258. const _ray$1 = /*@__PURE__*/ new Ray();
  20259. const _sphere$1 = /*@__PURE__*/ new Sphere();
  20260. class Line extends Object3D {
  20261. constructor( geometry = new BufferGeometry(), material = new LineBasicMaterial() ) {
  20262. super();
  20263. this.isLine = true;
  20264. this.type = 'Line';
  20265. this.geometry = geometry;
  20266. this.material = material;
  20267. this.updateMorphTargets();
  20268. }
  20269. copy( source, recursive ) {
  20270. super.copy( source, recursive );
  20271. this.material = Array.isArray( source.material ) ? source.material.slice() : source.material;
  20272. this.geometry = source.geometry;
  20273. return this;
  20274. }
  20275. computeLineDistances() {
  20276. const geometry = this.geometry;
  20277. // we assume non-indexed geometry
  20278. if ( geometry.index === null ) {
  20279. const positionAttribute = geometry.attributes.position;
  20280. const lineDistances = [ 0 ];
  20281. for ( let i = 1, l = positionAttribute.count; i < l; i ++ ) {
  20282. _start$1.fromBufferAttribute( positionAttribute, i - 1 );
  20283. _end$1.fromBufferAttribute( positionAttribute, i );
  20284. lineDistances[ i ] = lineDistances[ i - 1 ];
  20285. lineDistances[ i ] += _start$1.distanceTo( _end$1 );
  20286. }
  20287. geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  20288. } else {
  20289. console.warn( 'THREE.Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  20290. }
  20291. return this;
  20292. }
  20293. raycast( raycaster, intersects ) {
  20294. const geometry = this.geometry;
  20295. const matrixWorld = this.matrixWorld;
  20296. const threshold = raycaster.params.Line.threshold;
  20297. const drawRange = geometry.drawRange;
  20298. // Checking boundingSphere distance to ray
  20299. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  20300. _sphere$1.copy( geometry.boundingSphere );
  20301. _sphere$1.applyMatrix4( matrixWorld );
  20302. _sphere$1.radius += threshold;
  20303. if ( raycaster.ray.intersectsSphere( _sphere$1 ) === false ) return;
  20304. //
  20305. _inverseMatrix$1.copy( matrixWorld ).invert();
  20306. _ray$1.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$1 );
  20307. const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  20308. const localThresholdSq = localThreshold * localThreshold;
  20309. const vStart = new Vector3();
  20310. const vEnd = new Vector3();
  20311. const interSegment = new Vector3();
  20312. const interRay = new Vector3();
  20313. const step = this.isLineSegments ? 2 : 1;
  20314. const index = geometry.index;
  20315. const attributes = geometry.attributes;
  20316. const positionAttribute = attributes.position;
  20317. if ( index !== null ) {
  20318. const start = Math.max( 0, drawRange.start );
  20319. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  20320. for ( let i = start, l = end - 1; i < l; i += step ) {
  20321. const a = index.getX( i );
  20322. const b = index.getX( i + 1 );
  20323. vStart.fromBufferAttribute( positionAttribute, a );
  20324. vEnd.fromBufferAttribute( positionAttribute, b );
  20325. const distSq = _ray$1.distanceSqToSegment( vStart, vEnd, interRay, interSegment );
  20326. if ( distSq > localThresholdSq ) continue;
  20327. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  20328. const distance = raycaster.ray.origin.distanceTo( interRay );
  20329. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  20330. intersects.push( {
  20331. distance: distance,
  20332. // What do we want? intersection point on the ray or on the segment??
  20333. // point: raycaster.ray.at( distance ),
  20334. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  20335. index: i,
  20336. face: null,
  20337. faceIndex: null,
  20338. object: this
  20339. } );
  20340. }
  20341. } else {
  20342. const start = Math.max( 0, drawRange.start );
  20343. const end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) );
  20344. for ( let i = start, l = end - 1; i < l; i += step ) {
  20345. vStart.fromBufferAttribute( positionAttribute, i );
  20346. vEnd.fromBufferAttribute( positionAttribute, i + 1 );
  20347. const distSq = _ray$1.distanceSqToSegment( vStart, vEnd, interRay, interSegment );
  20348. if ( distSq > localThresholdSq ) continue;
  20349. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  20350. const distance = raycaster.ray.origin.distanceTo( interRay );
  20351. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  20352. intersects.push( {
  20353. distance: distance,
  20354. // What do we want? intersection point on the ray or on the segment??
  20355. // point: raycaster.ray.at( distance ),
  20356. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  20357. index: i,
  20358. face: null,
  20359. faceIndex: null,
  20360. object: this
  20361. } );
  20362. }
  20363. }
  20364. }
  20365. updateMorphTargets() {
  20366. const geometry = this.geometry;
  20367. const morphAttributes = geometry.morphAttributes;
  20368. const keys = Object.keys( morphAttributes );
  20369. if ( keys.length > 0 ) {
  20370. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  20371. if ( morphAttribute !== undefined ) {
  20372. this.morphTargetInfluences = [];
  20373. this.morphTargetDictionary = {};
  20374. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  20375. const name = morphAttribute[ m ].name || String( m );
  20376. this.morphTargetInfluences.push( 0 );
  20377. this.morphTargetDictionary[ name ] = m;
  20378. }
  20379. }
  20380. }
  20381. }
  20382. }
  20383. const _start = /*@__PURE__*/ new Vector3();
  20384. const _end = /*@__PURE__*/ new Vector3();
  20385. class LineSegments extends Line {
  20386. constructor( geometry, material ) {
  20387. super( geometry, material );
  20388. this.isLineSegments = true;
  20389. this.type = 'LineSegments';
  20390. }
  20391. computeLineDistances() {
  20392. const geometry = this.geometry;
  20393. // we assume non-indexed geometry
  20394. if ( geometry.index === null ) {
  20395. const positionAttribute = geometry.attributes.position;
  20396. const lineDistances = [];
  20397. for ( let i = 0, l = positionAttribute.count; i < l; i += 2 ) {
  20398. _start.fromBufferAttribute( positionAttribute, i );
  20399. _end.fromBufferAttribute( positionAttribute, i + 1 );
  20400. lineDistances[ i ] = ( i === 0 ) ? 0 : lineDistances[ i - 1 ];
  20401. lineDistances[ i + 1 ] = lineDistances[ i ] + _start.distanceTo( _end );
  20402. }
  20403. geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  20404. } else {
  20405. console.warn( 'THREE.LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  20406. }
  20407. return this;
  20408. }
  20409. }
  20410. class LineLoop extends Line {
  20411. constructor( geometry, material ) {
  20412. super( geometry, material );
  20413. this.isLineLoop = true;
  20414. this.type = 'LineLoop';
  20415. }
  20416. }
  20417. class PointsMaterial extends Material {
  20418. constructor( parameters ) {
  20419. super();
  20420. this.isPointsMaterial = true;
  20421. this.type = 'PointsMaterial';
  20422. this.color = new Color( 0xffffff );
  20423. this.map = null;
  20424. this.alphaMap = null;
  20425. this.size = 1;
  20426. this.sizeAttenuation = true;
  20427. this.fog = true;
  20428. this.setValues( parameters );
  20429. }
  20430. copy( source ) {
  20431. super.copy( source );
  20432. this.color.copy( source.color );
  20433. this.map = source.map;
  20434. this.alphaMap = source.alphaMap;
  20435. this.size = source.size;
  20436. this.sizeAttenuation = source.sizeAttenuation;
  20437. this.fog = source.fog;
  20438. return this;
  20439. }
  20440. }
  20441. const _inverseMatrix = /*@__PURE__*/ new Matrix4();
  20442. const _ray = /*@__PURE__*/ new Ray();
  20443. const _sphere = /*@__PURE__*/ new Sphere();
  20444. const _position$2 = /*@__PURE__*/ new Vector3();
  20445. class Points extends Object3D {
  20446. constructor( geometry = new BufferGeometry(), material = new PointsMaterial() ) {
  20447. super();
  20448. this.isPoints = true;
  20449. this.type = 'Points';
  20450. this.geometry = geometry;
  20451. this.material = material;
  20452. this.updateMorphTargets();
  20453. }
  20454. copy( source, recursive ) {
  20455. super.copy( source, recursive );
  20456. this.material = Array.isArray( source.material ) ? source.material.slice() : source.material;
  20457. this.geometry = source.geometry;
  20458. return this;
  20459. }
  20460. raycast( raycaster, intersects ) {
  20461. const geometry = this.geometry;
  20462. const matrixWorld = this.matrixWorld;
  20463. const threshold = raycaster.params.Points.threshold;
  20464. const drawRange = geometry.drawRange;
  20465. // Checking boundingSphere distance to ray
  20466. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  20467. _sphere.copy( geometry.boundingSphere );
  20468. _sphere.applyMatrix4( matrixWorld );
  20469. _sphere.radius += threshold;
  20470. if ( raycaster.ray.intersectsSphere( _sphere ) === false ) return;
  20471. //
  20472. _inverseMatrix.copy( matrixWorld ).invert();
  20473. _ray.copy( raycaster.ray ).applyMatrix4( _inverseMatrix );
  20474. const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  20475. const localThresholdSq = localThreshold * localThreshold;
  20476. const index = geometry.index;
  20477. const attributes = geometry.attributes;
  20478. const positionAttribute = attributes.position;
  20479. if ( index !== null ) {
  20480. const start = Math.max( 0, drawRange.start );
  20481. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  20482. for ( let i = start, il = end; i < il; i ++ ) {
  20483. const a = index.getX( i );
  20484. _position$2.fromBufferAttribute( positionAttribute, a );
  20485. testPoint( _position$2, a, localThresholdSq, matrixWorld, raycaster, intersects, this );
  20486. }
  20487. } else {
  20488. const start = Math.max( 0, drawRange.start );
  20489. const end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) );
  20490. for ( let i = start, l = end; i < l; i ++ ) {
  20491. _position$2.fromBufferAttribute( positionAttribute, i );
  20492. testPoint( _position$2, i, localThresholdSq, matrixWorld, raycaster, intersects, this );
  20493. }
  20494. }
  20495. }
  20496. updateMorphTargets() {
  20497. const geometry = this.geometry;
  20498. const morphAttributes = geometry.morphAttributes;
  20499. const keys = Object.keys( morphAttributes );
  20500. if ( keys.length > 0 ) {
  20501. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  20502. if ( morphAttribute !== undefined ) {
  20503. this.morphTargetInfluences = [];
  20504. this.morphTargetDictionary = {};
  20505. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  20506. const name = morphAttribute[ m ].name || String( m );
  20507. this.morphTargetInfluences.push( 0 );
  20508. this.morphTargetDictionary[ name ] = m;
  20509. }
  20510. }
  20511. }
  20512. }
  20513. }
  20514. function testPoint( point, index, localThresholdSq, matrixWorld, raycaster, intersects, object ) {
  20515. const rayPointDistanceSq = _ray.distanceSqToPoint( point );
  20516. if ( rayPointDistanceSq < localThresholdSq ) {
  20517. const intersectPoint = new Vector3();
  20518. _ray.closestPointToPoint( point, intersectPoint );
  20519. intersectPoint.applyMatrix4( matrixWorld );
  20520. const distance = raycaster.ray.origin.distanceTo( intersectPoint );
  20521. if ( distance < raycaster.near || distance > raycaster.far ) return;
  20522. intersects.push( {
  20523. distance: distance,
  20524. distanceToRay: Math.sqrt( rayPointDistanceSq ),
  20525. point: intersectPoint,
  20526. index: index,
  20527. face: null,
  20528. object: object
  20529. } );
  20530. }
  20531. }
  20532. class VideoTexture extends Texture {
  20533. constructor( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  20534. super( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  20535. this.isVideoTexture = true;
  20536. this.minFilter = minFilter !== undefined ? minFilter : LinearFilter;
  20537. this.magFilter = magFilter !== undefined ? magFilter : LinearFilter;
  20538. this.generateMipmaps = false;
  20539. const scope = this;
  20540. function updateVideo() {
  20541. scope.needsUpdate = true;
  20542. video.requestVideoFrameCallback( updateVideo );
  20543. }
  20544. if ( 'requestVideoFrameCallback' in video ) {
  20545. video.requestVideoFrameCallback( updateVideo );
  20546. }
  20547. }
  20548. clone() {
  20549. return new this.constructor( this.image ).copy( this );
  20550. }
  20551. update() {
  20552. const video = this.image;
  20553. const hasVideoFrameCallback = 'requestVideoFrameCallback' in video;
  20554. if ( hasVideoFrameCallback === false && video.readyState >= video.HAVE_CURRENT_DATA ) {
  20555. this.needsUpdate = true;
  20556. }
  20557. }
  20558. }
  20559. class FramebufferTexture extends Texture {
  20560. constructor( width, height ) {
  20561. super( { width, height } );
  20562. this.isFramebufferTexture = true;
  20563. this.magFilter = NearestFilter;
  20564. this.minFilter = NearestFilter;
  20565. this.generateMipmaps = false;
  20566. this.needsUpdate = true;
  20567. }
  20568. }
  20569. class CompressedTexture extends Texture {
  20570. constructor( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, colorSpace ) {
  20571. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace );
  20572. this.isCompressedTexture = true;
  20573. this.image = { width: width, height: height };
  20574. this.mipmaps = mipmaps;
  20575. // no flipping for cube textures
  20576. // (also flipping doesn't work for compressed textures )
  20577. this.flipY = false;
  20578. // can't generate mipmaps for compressed textures
  20579. // mips must be embedded in DDS files
  20580. this.generateMipmaps = false;
  20581. }
  20582. }
  20583. class CompressedArrayTexture extends CompressedTexture {
  20584. constructor( mipmaps, width, height, depth, format, type ) {
  20585. super( mipmaps, width, height, format, type );
  20586. this.isCompressedArrayTexture = true;
  20587. this.image.depth = depth;
  20588. this.wrapR = ClampToEdgeWrapping;
  20589. }
  20590. }
  20591. class CompressedCubeTexture extends CompressedTexture {
  20592. constructor( images, format, type ) {
  20593. super( undefined, images[ 0 ].width, images[ 0 ].height, format, type, CubeReflectionMapping );
  20594. this.isCompressedCubeTexture = true;
  20595. this.isCubeTexture = true;
  20596. this.image = images;
  20597. }
  20598. }
  20599. class CanvasTexture extends Texture {
  20600. constructor( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  20601. super( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  20602. this.isCanvasTexture = true;
  20603. this.needsUpdate = true;
  20604. }
  20605. }
  20606. /**
  20607. * Extensible curve object.
  20608. *
  20609. * Some common of curve methods:
  20610. * .getPoint( t, optionalTarget ), .getTangent( t, optionalTarget )
  20611. * .getPointAt( u, optionalTarget ), .getTangentAt( u, optionalTarget )
  20612. * .getPoints(), .getSpacedPoints()
  20613. * .getLength()
  20614. * .updateArcLengths()
  20615. *
  20616. * This following curves inherit from THREE.Curve:
  20617. *
  20618. * -- 2D curves --
  20619. * THREE.ArcCurve
  20620. * THREE.CubicBezierCurve
  20621. * THREE.EllipseCurve
  20622. * THREE.LineCurve
  20623. * THREE.QuadraticBezierCurve
  20624. * THREE.SplineCurve
  20625. *
  20626. * -- 3D curves --
  20627. * THREE.CatmullRomCurve3
  20628. * THREE.CubicBezierCurve3
  20629. * THREE.LineCurve3
  20630. * THREE.QuadraticBezierCurve3
  20631. *
  20632. * A series of curves can be represented as a THREE.CurvePath.
  20633. *
  20634. **/
  20635. class Curve {
  20636. constructor() {
  20637. this.type = 'Curve';
  20638. this.arcLengthDivisions = 200;
  20639. }
  20640. // Virtual base class method to overwrite and implement in subclasses
  20641. // - t [0 .. 1]
  20642. getPoint( /* t, optionalTarget */ ) {
  20643. console.warn( 'THREE.Curve: .getPoint() not implemented.' );
  20644. return null;
  20645. }
  20646. // Get point at relative position in curve according to arc length
  20647. // - u [0 .. 1]
  20648. getPointAt( u, optionalTarget ) {
  20649. const t = this.getUtoTmapping( u );
  20650. return this.getPoint( t, optionalTarget );
  20651. }
  20652. // Get sequence of points using getPoint( t )
  20653. getPoints( divisions = 5 ) {
  20654. const points = [];
  20655. for ( let d = 0; d <= divisions; d ++ ) {
  20656. points.push( this.getPoint( d / divisions ) );
  20657. }
  20658. return points;
  20659. }
  20660. // Get sequence of points using getPointAt( u )
  20661. getSpacedPoints( divisions = 5 ) {
  20662. const points = [];
  20663. for ( let d = 0; d <= divisions; d ++ ) {
  20664. points.push( this.getPointAt( d / divisions ) );
  20665. }
  20666. return points;
  20667. }
  20668. // Get total curve arc length
  20669. getLength() {
  20670. const lengths = this.getLengths();
  20671. return lengths[ lengths.length - 1 ];
  20672. }
  20673. // Get list of cumulative segment lengths
  20674. getLengths( divisions = this.arcLengthDivisions ) {
  20675. if ( this.cacheArcLengths &&
  20676. ( this.cacheArcLengths.length === divisions + 1 ) &&
  20677. ! this.needsUpdate ) {
  20678. return this.cacheArcLengths;
  20679. }
  20680. this.needsUpdate = false;
  20681. const cache = [];
  20682. let current, last = this.getPoint( 0 );
  20683. let sum = 0;
  20684. cache.push( 0 );
  20685. for ( let p = 1; p <= divisions; p ++ ) {
  20686. current = this.getPoint( p / divisions );
  20687. sum += current.distanceTo( last );
  20688. cache.push( sum );
  20689. last = current;
  20690. }
  20691. this.cacheArcLengths = cache;
  20692. return cache; // { sums: cache, sum: sum }; Sum is in the last element.
  20693. }
  20694. updateArcLengths() {
  20695. this.needsUpdate = true;
  20696. this.getLengths();
  20697. }
  20698. // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equidistant
  20699. getUtoTmapping( u, distance ) {
  20700. const arcLengths = this.getLengths();
  20701. let i = 0;
  20702. const il = arcLengths.length;
  20703. let targetArcLength; // The targeted u distance value to get
  20704. if ( distance ) {
  20705. targetArcLength = distance;
  20706. } else {
  20707. targetArcLength = u * arcLengths[ il - 1 ];
  20708. }
  20709. // binary search for the index with largest value smaller than target u distance
  20710. let low = 0, high = il - 1, comparison;
  20711. while ( low <= high ) {
  20712. 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
  20713. comparison = arcLengths[ i ] - targetArcLength;
  20714. if ( comparison < 0 ) {
  20715. low = i + 1;
  20716. } else if ( comparison > 0 ) {
  20717. high = i - 1;
  20718. } else {
  20719. high = i;
  20720. break;
  20721. // DONE
  20722. }
  20723. }
  20724. i = high;
  20725. if ( arcLengths[ i ] === targetArcLength ) {
  20726. return i / ( il - 1 );
  20727. }
  20728. // we could get finer grain at lengths, or use simple interpolation between two points
  20729. const lengthBefore = arcLengths[ i ];
  20730. const lengthAfter = arcLengths[ i + 1 ];
  20731. const segmentLength = lengthAfter - lengthBefore;
  20732. // determine where we are between the 'before' and 'after' points
  20733. const segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  20734. // add that fractional amount to t
  20735. const t = ( i + segmentFraction ) / ( il - 1 );
  20736. return t;
  20737. }
  20738. // Returns a unit vector tangent at t
  20739. // In case any sub curve does not implement its tangent derivation,
  20740. // 2 points a small delta apart will be used to find its gradient
  20741. // which seems to give a reasonable approximation
  20742. getTangent( t, optionalTarget ) {
  20743. const delta = 0.0001;
  20744. let t1 = t - delta;
  20745. let t2 = t + delta;
  20746. // Capping in case of danger
  20747. if ( t1 < 0 ) t1 = 0;
  20748. if ( t2 > 1 ) t2 = 1;
  20749. const pt1 = this.getPoint( t1 );
  20750. const pt2 = this.getPoint( t2 );
  20751. const tangent = optionalTarget || ( ( pt1.isVector2 ) ? new Vector2() : new Vector3() );
  20752. tangent.copy( pt2 ).sub( pt1 ).normalize();
  20753. return tangent;
  20754. }
  20755. getTangentAt( u, optionalTarget ) {
  20756. const t = this.getUtoTmapping( u );
  20757. return this.getTangent( t, optionalTarget );
  20758. }
  20759. computeFrenetFrames( segments, closed ) {
  20760. // see http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  20761. const normal = new Vector3();
  20762. const tangents = [];
  20763. const normals = [];
  20764. const binormals = [];
  20765. const vec = new Vector3();
  20766. const mat = new Matrix4();
  20767. // compute the tangent vectors for each segment on the curve
  20768. for ( let i = 0; i <= segments; i ++ ) {
  20769. const u = i / segments;
  20770. tangents[ i ] = this.getTangentAt( u, new Vector3() );
  20771. }
  20772. // select an initial normal vector perpendicular to the first tangent vector,
  20773. // and in the direction of the minimum tangent xyz component
  20774. normals[ 0 ] = new Vector3();
  20775. binormals[ 0 ] = new Vector3();
  20776. let min = Number.MAX_VALUE;
  20777. const tx = Math.abs( tangents[ 0 ].x );
  20778. const ty = Math.abs( tangents[ 0 ].y );
  20779. const tz = Math.abs( tangents[ 0 ].z );
  20780. if ( tx <= min ) {
  20781. min = tx;
  20782. normal.set( 1, 0, 0 );
  20783. }
  20784. if ( ty <= min ) {
  20785. min = ty;
  20786. normal.set( 0, 1, 0 );
  20787. }
  20788. if ( tz <= min ) {
  20789. normal.set( 0, 0, 1 );
  20790. }
  20791. vec.crossVectors( tangents[ 0 ], normal ).normalize();
  20792. normals[ 0 ].crossVectors( tangents[ 0 ], vec );
  20793. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] );
  20794. // compute the slowly-varying normal and binormal vectors for each segment on the curve
  20795. for ( let i = 1; i <= segments; i ++ ) {
  20796. normals[ i ] = normals[ i - 1 ].clone();
  20797. binormals[ i ] = binormals[ i - 1 ].clone();
  20798. vec.crossVectors( tangents[ i - 1 ], tangents[ i ] );
  20799. if ( vec.length() > Number.EPSILON ) {
  20800. vec.normalize();
  20801. const theta = Math.acos( clamp( tangents[ i - 1 ].dot( tangents[ i ] ), - 1, 1 ) ); // clamp for floating pt errors
  20802. normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) );
  20803. }
  20804. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  20805. }
  20806. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  20807. if ( closed === true ) {
  20808. let theta = Math.acos( clamp( normals[ 0 ].dot( normals[ segments ] ), - 1, 1 ) );
  20809. theta /= segments;
  20810. if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ segments ] ) ) > 0 ) {
  20811. theta = - theta;
  20812. }
  20813. for ( let i = 1; i <= segments; i ++ ) {
  20814. // twist a little...
  20815. normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) );
  20816. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  20817. }
  20818. }
  20819. return {
  20820. tangents: tangents,
  20821. normals: normals,
  20822. binormals: binormals
  20823. };
  20824. }
  20825. clone() {
  20826. return new this.constructor().copy( this );
  20827. }
  20828. copy( source ) {
  20829. this.arcLengthDivisions = source.arcLengthDivisions;
  20830. return this;
  20831. }
  20832. toJSON() {
  20833. const data = {
  20834. metadata: {
  20835. version: 4.6,
  20836. type: 'Curve',
  20837. generator: 'Curve.toJSON'
  20838. }
  20839. };
  20840. data.arcLengthDivisions = this.arcLengthDivisions;
  20841. data.type = this.type;
  20842. return data;
  20843. }
  20844. fromJSON( json ) {
  20845. this.arcLengthDivisions = json.arcLengthDivisions;
  20846. return this;
  20847. }
  20848. }
  20849. class EllipseCurve extends Curve {
  20850. constructor( aX = 0, aY = 0, xRadius = 1, yRadius = 1, aStartAngle = 0, aEndAngle = Math.PI * 2, aClockwise = false, aRotation = 0 ) {
  20851. super();
  20852. this.isEllipseCurve = true;
  20853. this.type = 'EllipseCurve';
  20854. this.aX = aX;
  20855. this.aY = aY;
  20856. this.xRadius = xRadius;
  20857. this.yRadius = yRadius;
  20858. this.aStartAngle = aStartAngle;
  20859. this.aEndAngle = aEndAngle;
  20860. this.aClockwise = aClockwise;
  20861. this.aRotation = aRotation;
  20862. }
  20863. getPoint( t, optionalTarget = new Vector2() ) {
  20864. const point = optionalTarget;
  20865. const twoPi = Math.PI * 2;
  20866. let deltaAngle = this.aEndAngle - this.aStartAngle;
  20867. const samePoints = Math.abs( deltaAngle ) < Number.EPSILON;
  20868. // ensures that deltaAngle is 0 .. 2 PI
  20869. while ( deltaAngle < 0 ) deltaAngle += twoPi;
  20870. while ( deltaAngle > twoPi ) deltaAngle -= twoPi;
  20871. if ( deltaAngle < Number.EPSILON ) {
  20872. if ( samePoints ) {
  20873. deltaAngle = 0;
  20874. } else {
  20875. deltaAngle = twoPi;
  20876. }
  20877. }
  20878. if ( this.aClockwise === true && ! samePoints ) {
  20879. if ( deltaAngle === twoPi ) {
  20880. deltaAngle = - twoPi;
  20881. } else {
  20882. deltaAngle = deltaAngle - twoPi;
  20883. }
  20884. }
  20885. const angle = this.aStartAngle + t * deltaAngle;
  20886. let x = this.aX + this.xRadius * Math.cos( angle );
  20887. let y = this.aY + this.yRadius * Math.sin( angle );
  20888. if ( this.aRotation !== 0 ) {
  20889. const cos = Math.cos( this.aRotation );
  20890. const sin = Math.sin( this.aRotation );
  20891. const tx = x - this.aX;
  20892. const ty = y - this.aY;
  20893. // Rotate the point about the center of the ellipse.
  20894. x = tx * cos - ty * sin + this.aX;
  20895. y = tx * sin + ty * cos + this.aY;
  20896. }
  20897. return point.set( x, y );
  20898. }
  20899. copy( source ) {
  20900. super.copy( source );
  20901. this.aX = source.aX;
  20902. this.aY = source.aY;
  20903. this.xRadius = source.xRadius;
  20904. this.yRadius = source.yRadius;
  20905. this.aStartAngle = source.aStartAngle;
  20906. this.aEndAngle = source.aEndAngle;
  20907. this.aClockwise = source.aClockwise;
  20908. this.aRotation = source.aRotation;
  20909. return this;
  20910. }
  20911. toJSON() {
  20912. const data = super.toJSON();
  20913. data.aX = this.aX;
  20914. data.aY = this.aY;
  20915. data.xRadius = this.xRadius;
  20916. data.yRadius = this.yRadius;
  20917. data.aStartAngle = this.aStartAngle;
  20918. data.aEndAngle = this.aEndAngle;
  20919. data.aClockwise = this.aClockwise;
  20920. data.aRotation = this.aRotation;
  20921. return data;
  20922. }
  20923. fromJSON( json ) {
  20924. super.fromJSON( json );
  20925. this.aX = json.aX;
  20926. this.aY = json.aY;
  20927. this.xRadius = json.xRadius;
  20928. this.yRadius = json.yRadius;
  20929. this.aStartAngle = json.aStartAngle;
  20930. this.aEndAngle = json.aEndAngle;
  20931. this.aClockwise = json.aClockwise;
  20932. this.aRotation = json.aRotation;
  20933. return this;
  20934. }
  20935. }
  20936. class ArcCurve extends EllipseCurve {
  20937. constructor( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  20938. super( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  20939. this.isArcCurve = true;
  20940. this.type = 'ArcCurve';
  20941. }
  20942. }
  20943. /**
  20944. * Centripetal CatmullRom Curve - which is useful for avoiding
  20945. * cusps and self-intersections in non-uniform catmull rom curves.
  20946. * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf
  20947. *
  20948. * curve.type accepts centripetal(default), chordal and catmullrom
  20949. * curve.tension is used for catmullrom which defaults to 0.5
  20950. */
  20951. /*
  20952. Based on an optimized c++ solution in
  20953. - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/
  20954. - http://ideone.com/NoEbVM
  20955. This CubicPoly class could be used for reusing some variables and calculations,
  20956. but for three.js curve use, it could be possible inlined and flatten into a single function call
  20957. which can be placed in CurveUtils.
  20958. */
  20959. function CubicPoly() {
  20960. let c0 = 0, c1 = 0, c2 = 0, c3 = 0;
  20961. /*
  20962. * Compute coefficients for a cubic polynomial
  20963. * p(s) = c0 + c1*s + c2*s^2 + c3*s^3
  20964. * such that
  20965. * p(0) = x0, p(1) = x1
  20966. * and
  20967. * p'(0) = t0, p'(1) = t1.
  20968. */
  20969. function init( x0, x1, t0, t1 ) {
  20970. c0 = x0;
  20971. c1 = t0;
  20972. c2 = - 3 * x0 + 3 * x1 - 2 * t0 - t1;
  20973. c3 = 2 * x0 - 2 * x1 + t0 + t1;
  20974. }
  20975. return {
  20976. initCatmullRom: function ( x0, x1, x2, x3, tension ) {
  20977. init( x1, x2, tension * ( x2 - x0 ), tension * ( x3 - x1 ) );
  20978. },
  20979. initNonuniformCatmullRom: function ( x0, x1, x2, x3, dt0, dt1, dt2 ) {
  20980. // compute tangents when parameterized in [t1,t2]
  20981. let t1 = ( x1 - x0 ) / dt0 - ( x2 - x0 ) / ( dt0 + dt1 ) + ( x2 - x1 ) / dt1;
  20982. let t2 = ( x2 - x1 ) / dt1 - ( x3 - x1 ) / ( dt1 + dt2 ) + ( x3 - x2 ) / dt2;
  20983. // rescale tangents for parametrization in [0,1]
  20984. t1 *= dt1;
  20985. t2 *= dt1;
  20986. init( x1, x2, t1, t2 );
  20987. },
  20988. calc: function ( t ) {
  20989. const t2 = t * t;
  20990. const t3 = t2 * t;
  20991. return c0 + c1 * t + c2 * t2 + c3 * t3;
  20992. }
  20993. };
  20994. }
  20995. //
  20996. const tmp = /*@__PURE__*/ new Vector3();
  20997. const px = /*@__PURE__*/ new CubicPoly();
  20998. const py = /*@__PURE__*/ new CubicPoly();
  20999. const pz = /*@__PURE__*/ new CubicPoly();
  21000. class CatmullRomCurve3 extends Curve {
  21001. constructor( points = [], closed = false, curveType = 'centripetal', tension = 0.5 ) {
  21002. super();
  21003. this.isCatmullRomCurve3 = true;
  21004. this.type = 'CatmullRomCurve3';
  21005. this.points = points;
  21006. this.closed = closed;
  21007. this.curveType = curveType;
  21008. this.tension = tension;
  21009. }
  21010. getPoint( t, optionalTarget = new Vector3() ) {
  21011. const point = optionalTarget;
  21012. const points = this.points;
  21013. const l = points.length;
  21014. const p = ( l - ( this.closed ? 0 : 1 ) ) * t;
  21015. let intPoint = Math.floor( p );
  21016. let weight = p - intPoint;
  21017. if ( this.closed ) {
  21018. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / l ) + 1 ) * l;
  21019. } else if ( weight === 0 && intPoint === l - 1 ) {
  21020. intPoint = l - 2;
  21021. weight = 1;
  21022. }
  21023. let p0, p3; // 4 points (p1 & p2 defined below)
  21024. if ( this.closed || intPoint > 0 ) {
  21025. p0 = points[ ( intPoint - 1 ) % l ];
  21026. } else {
  21027. // extrapolate first point
  21028. tmp.subVectors( points[ 0 ], points[ 1 ] ).add( points[ 0 ] );
  21029. p0 = tmp;
  21030. }
  21031. const p1 = points[ intPoint % l ];
  21032. const p2 = points[ ( intPoint + 1 ) % l ];
  21033. if ( this.closed || intPoint + 2 < l ) {
  21034. p3 = points[ ( intPoint + 2 ) % l ];
  21035. } else {
  21036. // extrapolate last point
  21037. tmp.subVectors( points[ l - 1 ], points[ l - 2 ] ).add( points[ l - 1 ] );
  21038. p3 = tmp;
  21039. }
  21040. if ( this.curveType === 'centripetal' || this.curveType === 'chordal' ) {
  21041. // init Centripetal / Chordal Catmull-Rom
  21042. const pow = this.curveType === 'chordal' ? 0.5 : 0.25;
  21043. let dt0 = Math.pow( p0.distanceToSquared( p1 ), pow );
  21044. let dt1 = Math.pow( p1.distanceToSquared( p2 ), pow );
  21045. let dt2 = Math.pow( p2.distanceToSquared( p3 ), pow );
  21046. // safety check for repeated points
  21047. if ( dt1 < 1e-4 ) dt1 = 1.0;
  21048. if ( dt0 < 1e-4 ) dt0 = dt1;
  21049. if ( dt2 < 1e-4 ) dt2 = dt1;
  21050. px.initNonuniformCatmullRom( p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2 );
  21051. py.initNonuniformCatmullRom( p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2 );
  21052. pz.initNonuniformCatmullRom( p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2 );
  21053. } else if ( this.curveType === 'catmullrom' ) {
  21054. px.initCatmullRom( p0.x, p1.x, p2.x, p3.x, this.tension );
  21055. py.initCatmullRom( p0.y, p1.y, p2.y, p3.y, this.tension );
  21056. pz.initCatmullRom( p0.z, p1.z, p2.z, p3.z, this.tension );
  21057. }
  21058. point.set(
  21059. px.calc( weight ),
  21060. py.calc( weight ),
  21061. pz.calc( weight )
  21062. );
  21063. return point;
  21064. }
  21065. copy( source ) {
  21066. super.copy( source );
  21067. this.points = [];
  21068. for ( let i = 0, l = source.points.length; i < l; i ++ ) {
  21069. const point = source.points[ i ];
  21070. this.points.push( point.clone() );
  21071. }
  21072. this.closed = source.closed;
  21073. this.curveType = source.curveType;
  21074. this.tension = source.tension;
  21075. return this;
  21076. }
  21077. toJSON() {
  21078. const data = super.toJSON();
  21079. data.points = [];
  21080. for ( let i = 0, l = this.points.length; i < l; i ++ ) {
  21081. const point = this.points[ i ];
  21082. data.points.push( point.toArray() );
  21083. }
  21084. data.closed = this.closed;
  21085. data.curveType = this.curveType;
  21086. data.tension = this.tension;
  21087. return data;
  21088. }
  21089. fromJSON( json ) {
  21090. super.fromJSON( json );
  21091. this.points = [];
  21092. for ( let i = 0, l = json.points.length; i < l; i ++ ) {
  21093. const point = json.points[ i ];
  21094. this.points.push( new Vector3().fromArray( point ) );
  21095. }
  21096. this.closed = json.closed;
  21097. this.curveType = json.curveType;
  21098. this.tension = json.tension;
  21099. return this;
  21100. }
  21101. }
  21102. /**
  21103. * Bezier Curves formulas obtained from
  21104. * https://en.wikipedia.org/wiki/B%C3%A9zier_curve
  21105. */
  21106. function CatmullRom( t, p0, p1, p2, p3 ) {
  21107. const v0 = ( p2 - p0 ) * 0.5;
  21108. const v1 = ( p3 - p1 ) * 0.5;
  21109. const t2 = t * t;
  21110. const t3 = t * t2;
  21111. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  21112. }
  21113. //
  21114. function QuadraticBezierP0( t, p ) {
  21115. const k = 1 - t;
  21116. return k * k * p;
  21117. }
  21118. function QuadraticBezierP1( t, p ) {
  21119. return 2 * ( 1 - t ) * t * p;
  21120. }
  21121. function QuadraticBezierP2( t, p ) {
  21122. return t * t * p;
  21123. }
  21124. function QuadraticBezier( t, p0, p1, p2 ) {
  21125. return QuadraticBezierP0( t, p0 ) + QuadraticBezierP1( t, p1 ) +
  21126. QuadraticBezierP2( t, p2 );
  21127. }
  21128. //
  21129. function CubicBezierP0( t, p ) {
  21130. const k = 1 - t;
  21131. return k * k * k * p;
  21132. }
  21133. function CubicBezierP1( t, p ) {
  21134. const k = 1 - t;
  21135. return 3 * k * k * t * p;
  21136. }
  21137. function CubicBezierP2( t, p ) {
  21138. return 3 * ( 1 - t ) * t * t * p;
  21139. }
  21140. function CubicBezierP3( t, p ) {
  21141. return t * t * t * p;
  21142. }
  21143. function CubicBezier( t, p0, p1, p2, p3 ) {
  21144. return CubicBezierP0( t, p0 ) + CubicBezierP1( t, p1 ) + CubicBezierP2( t, p2 ) +
  21145. CubicBezierP3( t, p3 );
  21146. }
  21147. class CubicBezierCurve extends Curve {
  21148. constructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2(), v3 = new Vector2() ) {
  21149. super();
  21150. this.isCubicBezierCurve = true;
  21151. this.type = 'CubicBezierCurve';
  21152. this.v0 = v0;
  21153. this.v1 = v1;
  21154. this.v2 = v2;
  21155. this.v3 = v3;
  21156. }
  21157. getPoint( t, optionalTarget = new Vector2() ) {
  21158. const point = optionalTarget;
  21159. const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  21160. point.set(
  21161. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  21162. CubicBezier( t, v0.y, v1.y, v2.y, v3.y )
  21163. );
  21164. return point;
  21165. }
  21166. copy( source ) {
  21167. super.copy( source );
  21168. this.v0.copy( source.v0 );
  21169. this.v1.copy( source.v1 );
  21170. this.v2.copy( source.v2 );
  21171. this.v3.copy( source.v3 );
  21172. return this;
  21173. }
  21174. toJSON() {
  21175. const data = super.toJSON();
  21176. data.v0 = this.v0.toArray();
  21177. data.v1 = this.v1.toArray();
  21178. data.v2 = this.v2.toArray();
  21179. data.v3 = this.v3.toArray();
  21180. return data;
  21181. }
  21182. fromJSON( json ) {
  21183. super.fromJSON( json );
  21184. this.v0.fromArray( json.v0 );
  21185. this.v1.fromArray( json.v1 );
  21186. this.v2.fromArray( json.v2 );
  21187. this.v3.fromArray( json.v3 );
  21188. return this;
  21189. }
  21190. }
  21191. class CubicBezierCurve3 extends Curve {
  21192. constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3(), v3 = new Vector3() ) {
  21193. super();
  21194. this.isCubicBezierCurve3 = true;
  21195. this.type = 'CubicBezierCurve3';
  21196. this.v0 = v0;
  21197. this.v1 = v1;
  21198. this.v2 = v2;
  21199. this.v3 = v3;
  21200. }
  21201. getPoint( t, optionalTarget = new Vector3() ) {
  21202. const point = optionalTarget;
  21203. const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  21204. point.set(
  21205. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  21206. CubicBezier( t, v0.y, v1.y, v2.y, v3.y ),
  21207. CubicBezier( t, v0.z, v1.z, v2.z, v3.z )
  21208. );
  21209. return point;
  21210. }
  21211. copy( source ) {
  21212. super.copy( source );
  21213. this.v0.copy( source.v0 );
  21214. this.v1.copy( source.v1 );
  21215. this.v2.copy( source.v2 );
  21216. this.v3.copy( source.v3 );
  21217. return this;
  21218. }
  21219. toJSON() {
  21220. const data = super.toJSON();
  21221. data.v0 = this.v0.toArray();
  21222. data.v1 = this.v1.toArray();
  21223. data.v2 = this.v2.toArray();
  21224. data.v3 = this.v3.toArray();
  21225. return data;
  21226. }
  21227. fromJSON( json ) {
  21228. super.fromJSON( json );
  21229. this.v0.fromArray( json.v0 );
  21230. this.v1.fromArray( json.v1 );
  21231. this.v2.fromArray( json.v2 );
  21232. this.v3.fromArray( json.v3 );
  21233. return this;
  21234. }
  21235. }
  21236. class LineCurve extends Curve {
  21237. constructor( v1 = new Vector2(), v2 = new Vector2() ) {
  21238. super();
  21239. this.isLineCurve = true;
  21240. this.type = 'LineCurve';
  21241. this.v1 = v1;
  21242. this.v2 = v2;
  21243. }
  21244. getPoint( t, optionalTarget = new Vector2() ) {
  21245. const point = optionalTarget;
  21246. if ( t === 1 ) {
  21247. point.copy( this.v2 );
  21248. } else {
  21249. point.copy( this.v2 ).sub( this.v1 );
  21250. point.multiplyScalar( t ).add( this.v1 );
  21251. }
  21252. return point;
  21253. }
  21254. // Line curve is linear, so we can overwrite default getPointAt
  21255. getPointAt( u, optionalTarget ) {
  21256. return this.getPoint( u, optionalTarget );
  21257. }
  21258. getTangent( t, optionalTarget = new Vector2() ) {
  21259. return optionalTarget.subVectors( this.v2, this.v1 ).normalize();
  21260. }
  21261. getTangentAt( u, optionalTarget ) {
  21262. return this.getTangent( u, optionalTarget );
  21263. }
  21264. copy( source ) {
  21265. super.copy( source );
  21266. this.v1.copy( source.v1 );
  21267. this.v2.copy( source.v2 );
  21268. return this;
  21269. }
  21270. toJSON() {
  21271. const data = super.toJSON();
  21272. data.v1 = this.v1.toArray();
  21273. data.v2 = this.v2.toArray();
  21274. return data;
  21275. }
  21276. fromJSON( json ) {
  21277. super.fromJSON( json );
  21278. this.v1.fromArray( json.v1 );
  21279. this.v2.fromArray( json.v2 );
  21280. return this;
  21281. }
  21282. }
  21283. class LineCurve3 extends Curve {
  21284. constructor( v1 = new Vector3(), v2 = new Vector3() ) {
  21285. super();
  21286. this.isLineCurve3 = true;
  21287. this.type = 'LineCurve3';
  21288. this.v1 = v1;
  21289. this.v2 = v2;
  21290. }
  21291. getPoint( t, optionalTarget = new Vector3() ) {
  21292. const point = optionalTarget;
  21293. if ( t === 1 ) {
  21294. point.copy( this.v2 );
  21295. } else {
  21296. point.copy( this.v2 ).sub( this.v1 );
  21297. point.multiplyScalar( t ).add( this.v1 );
  21298. }
  21299. return point;
  21300. }
  21301. // Line curve is linear, so we can overwrite default getPointAt
  21302. getPointAt( u, optionalTarget ) {
  21303. return this.getPoint( u, optionalTarget );
  21304. }
  21305. getTangent( t, optionalTarget = new Vector3() ) {
  21306. return optionalTarget.subVectors( this.v2, this.v1 ).normalize();
  21307. }
  21308. getTangentAt( u, optionalTarget ) {
  21309. return this.getTangent( u, optionalTarget );
  21310. }
  21311. copy( source ) {
  21312. super.copy( source );
  21313. this.v1.copy( source.v1 );
  21314. this.v2.copy( source.v2 );
  21315. return this;
  21316. }
  21317. toJSON() {
  21318. const data = super.toJSON();
  21319. data.v1 = this.v1.toArray();
  21320. data.v2 = this.v2.toArray();
  21321. return data;
  21322. }
  21323. fromJSON( json ) {
  21324. super.fromJSON( json );
  21325. this.v1.fromArray( json.v1 );
  21326. this.v2.fromArray( json.v2 );
  21327. return this;
  21328. }
  21329. }
  21330. class QuadraticBezierCurve extends Curve {
  21331. constructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2() ) {
  21332. super();
  21333. this.isQuadraticBezierCurve = true;
  21334. this.type = 'QuadraticBezierCurve';
  21335. this.v0 = v0;
  21336. this.v1 = v1;
  21337. this.v2 = v2;
  21338. }
  21339. getPoint( t, optionalTarget = new Vector2() ) {
  21340. const point = optionalTarget;
  21341. const v0 = this.v0, v1 = this.v1, v2 = this.v2;
  21342. point.set(
  21343. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  21344. QuadraticBezier( t, v0.y, v1.y, v2.y )
  21345. );
  21346. return point;
  21347. }
  21348. copy( source ) {
  21349. super.copy( source );
  21350. this.v0.copy( source.v0 );
  21351. this.v1.copy( source.v1 );
  21352. this.v2.copy( source.v2 );
  21353. return this;
  21354. }
  21355. toJSON() {
  21356. const data = super.toJSON();
  21357. data.v0 = this.v0.toArray();
  21358. data.v1 = this.v1.toArray();
  21359. data.v2 = this.v2.toArray();
  21360. return data;
  21361. }
  21362. fromJSON( json ) {
  21363. super.fromJSON( json );
  21364. this.v0.fromArray( json.v0 );
  21365. this.v1.fromArray( json.v1 );
  21366. this.v2.fromArray( json.v2 );
  21367. return this;
  21368. }
  21369. }
  21370. class QuadraticBezierCurve3 extends Curve {
  21371. constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3() ) {
  21372. super();
  21373. this.isQuadraticBezierCurve3 = true;
  21374. this.type = 'QuadraticBezierCurve3';
  21375. this.v0 = v0;
  21376. this.v1 = v1;
  21377. this.v2 = v2;
  21378. }
  21379. getPoint( t, optionalTarget = new Vector3() ) {
  21380. const point = optionalTarget;
  21381. const v0 = this.v0, v1 = this.v1, v2 = this.v2;
  21382. point.set(
  21383. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  21384. QuadraticBezier( t, v0.y, v1.y, v2.y ),
  21385. QuadraticBezier( t, v0.z, v1.z, v2.z )
  21386. );
  21387. return point;
  21388. }
  21389. copy( source ) {
  21390. super.copy( source );
  21391. this.v0.copy( source.v0 );
  21392. this.v1.copy( source.v1 );
  21393. this.v2.copy( source.v2 );
  21394. return this;
  21395. }
  21396. toJSON() {
  21397. const data = super.toJSON();
  21398. data.v0 = this.v0.toArray();
  21399. data.v1 = this.v1.toArray();
  21400. data.v2 = this.v2.toArray();
  21401. return data;
  21402. }
  21403. fromJSON( json ) {
  21404. super.fromJSON( json );
  21405. this.v0.fromArray( json.v0 );
  21406. this.v1.fromArray( json.v1 );
  21407. this.v2.fromArray( json.v2 );
  21408. return this;
  21409. }
  21410. }
  21411. class SplineCurve extends Curve {
  21412. constructor( points = [] ) {
  21413. super();
  21414. this.isSplineCurve = true;
  21415. this.type = 'SplineCurve';
  21416. this.points = points;
  21417. }
  21418. getPoint( t, optionalTarget = new Vector2() ) {
  21419. const point = optionalTarget;
  21420. const points = this.points;
  21421. const p = ( points.length - 1 ) * t;
  21422. const intPoint = Math.floor( p );
  21423. const weight = p - intPoint;
  21424. const p0 = points[ intPoint === 0 ? intPoint : intPoint - 1 ];
  21425. const p1 = points[ intPoint ];
  21426. const p2 = points[ intPoint > points.length - 2 ? points.length - 1 : intPoint + 1 ];
  21427. const p3 = points[ intPoint > points.length - 3 ? points.length - 1 : intPoint + 2 ];
  21428. point.set(
  21429. CatmullRom( weight, p0.x, p1.x, p2.x, p3.x ),
  21430. CatmullRom( weight, p0.y, p1.y, p2.y, p3.y )
  21431. );
  21432. return point;
  21433. }
  21434. copy( source ) {
  21435. super.copy( source );
  21436. this.points = [];
  21437. for ( let i = 0, l = source.points.length; i < l; i ++ ) {
  21438. const point = source.points[ i ];
  21439. this.points.push( point.clone() );
  21440. }
  21441. return this;
  21442. }
  21443. toJSON() {
  21444. const data = super.toJSON();
  21445. data.points = [];
  21446. for ( let i = 0, l = this.points.length; i < l; i ++ ) {
  21447. const point = this.points[ i ];
  21448. data.points.push( point.toArray() );
  21449. }
  21450. return data;
  21451. }
  21452. fromJSON( json ) {
  21453. super.fromJSON( json );
  21454. this.points = [];
  21455. for ( let i = 0, l = json.points.length; i < l; i ++ ) {
  21456. const point = json.points[ i ];
  21457. this.points.push( new Vector2().fromArray( point ) );
  21458. }
  21459. return this;
  21460. }
  21461. }
  21462. var Curves = /*#__PURE__*/Object.freeze({
  21463. __proto__: null,
  21464. ArcCurve: ArcCurve,
  21465. CatmullRomCurve3: CatmullRomCurve3,
  21466. CubicBezierCurve: CubicBezierCurve,
  21467. CubicBezierCurve3: CubicBezierCurve3,
  21468. EllipseCurve: EllipseCurve,
  21469. LineCurve: LineCurve,
  21470. LineCurve3: LineCurve3,
  21471. QuadraticBezierCurve: QuadraticBezierCurve,
  21472. QuadraticBezierCurve3: QuadraticBezierCurve3,
  21473. SplineCurve: SplineCurve
  21474. });
  21475. /**************************************************************
  21476. * Curved Path - a curve path is simply a array of connected
  21477. * curves, but retains the api of a curve
  21478. **************************************************************/
  21479. class CurvePath extends Curve {
  21480. constructor() {
  21481. super();
  21482. this.type = 'CurvePath';
  21483. this.curves = [];
  21484. this.autoClose = false; // Automatically closes the path
  21485. }
  21486. add( curve ) {
  21487. this.curves.push( curve );
  21488. }
  21489. closePath() {
  21490. // Add a line curve if start and end of lines are not connected
  21491. const startPoint = this.curves[ 0 ].getPoint( 0 );
  21492. const endPoint = this.curves[ this.curves.length - 1 ].getPoint( 1 );
  21493. if ( ! startPoint.equals( endPoint ) ) {
  21494. const lineType = ( startPoint.isVector2 === true ) ? 'LineCurve' : 'LineCurve3';
  21495. this.curves.push( new Curves[ lineType ]( endPoint, startPoint ) );
  21496. }
  21497. return this;
  21498. }
  21499. // To get accurate point with reference to
  21500. // entire path distance at time t,
  21501. // following has to be done:
  21502. // 1. Length of each sub path have to be known
  21503. // 2. Locate and identify type of curve
  21504. // 3. Get t for the curve
  21505. // 4. Return curve.getPointAt(t')
  21506. getPoint( t, optionalTarget ) {
  21507. const d = t * this.getLength();
  21508. const curveLengths = this.getCurveLengths();
  21509. let i = 0;
  21510. // To think about boundaries points.
  21511. while ( i < curveLengths.length ) {
  21512. if ( curveLengths[ i ] >= d ) {
  21513. const diff = curveLengths[ i ] - d;
  21514. const curve = this.curves[ i ];
  21515. const segmentLength = curve.getLength();
  21516. const u = segmentLength === 0 ? 0 : 1 - diff / segmentLength;
  21517. return curve.getPointAt( u, optionalTarget );
  21518. }
  21519. i ++;
  21520. }
  21521. return null;
  21522. // loop where sum != 0, sum > d , sum+1 <d
  21523. }
  21524. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  21525. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  21526. // getPoint() depends on getLength
  21527. getLength() {
  21528. const lens = this.getCurveLengths();
  21529. return lens[ lens.length - 1 ];
  21530. }
  21531. // cacheLengths must be recalculated.
  21532. updateArcLengths() {
  21533. this.needsUpdate = true;
  21534. this.cacheLengths = null;
  21535. this.getCurveLengths();
  21536. }
  21537. // Compute lengths and cache them
  21538. // We cannot overwrite getLengths() because UtoT mapping uses it.
  21539. getCurveLengths() {
  21540. // We use cache values if curves and cache array are same length
  21541. if ( this.cacheLengths && this.cacheLengths.length === this.curves.length ) {
  21542. return this.cacheLengths;
  21543. }
  21544. // Get length of sub-curve
  21545. // Push sums into cached array
  21546. const lengths = [];
  21547. let sums = 0;
  21548. for ( let i = 0, l = this.curves.length; i < l; i ++ ) {
  21549. sums += this.curves[ i ].getLength();
  21550. lengths.push( sums );
  21551. }
  21552. this.cacheLengths = lengths;
  21553. return lengths;
  21554. }
  21555. getSpacedPoints( divisions = 40 ) {
  21556. const points = [];
  21557. for ( let i = 0; i <= divisions; i ++ ) {
  21558. points.push( this.getPoint( i / divisions ) );
  21559. }
  21560. if ( this.autoClose ) {
  21561. points.push( points[ 0 ] );
  21562. }
  21563. return points;
  21564. }
  21565. getPoints( divisions = 12 ) {
  21566. const points = [];
  21567. let last;
  21568. for ( let i = 0, curves = this.curves; i < curves.length; i ++ ) {
  21569. const curve = curves[ i ];
  21570. const resolution = curve.isEllipseCurve ? divisions * 2
  21571. : ( curve.isLineCurve || curve.isLineCurve3 ) ? 1
  21572. : curve.isSplineCurve ? divisions * curve.points.length
  21573. : divisions;
  21574. const pts = curve.getPoints( resolution );
  21575. for ( let j = 0; j < pts.length; j ++ ) {
  21576. const point = pts[ j ];
  21577. if ( last && last.equals( point ) ) continue; // ensures no consecutive points are duplicates
  21578. points.push( point );
  21579. last = point;
  21580. }
  21581. }
  21582. if ( this.autoClose && points.length > 1 && ! points[ points.length - 1 ].equals( points[ 0 ] ) ) {
  21583. points.push( points[ 0 ] );
  21584. }
  21585. return points;
  21586. }
  21587. copy( source ) {
  21588. super.copy( source );
  21589. this.curves = [];
  21590. for ( let i = 0, l = source.curves.length; i < l; i ++ ) {
  21591. const curve = source.curves[ i ];
  21592. this.curves.push( curve.clone() );
  21593. }
  21594. this.autoClose = source.autoClose;
  21595. return this;
  21596. }
  21597. toJSON() {
  21598. const data = super.toJSON();
  21599. data.autoClose = this.autoClose;
  21600. data.curves = [];
  21601. for ( let i = 0, l = this.curves.length; i < l; i ++ ) {
  21602. const curve = this.curves[ i ];
  21603. data.curves.push( curve.toJSON() );
  21604. }
  21605. return data;
  21606. }
  21607. fromJSON( json ) {
  21608. super.fromJSON( json );
  21609. this.autoClose = json.autoClose;
  21610. this.curves = [];
  21611. for ( let i = 0, l = json.curves.length; i < l; i ++ ) {
  21612. const curve = json.curves[ i ];
  21613. this.curves.push( new Curves[ curve.type ]().fromJSON( curve ) );
  21614. }
  21615. return this;
  21616. }
  21617. }
  21618. class Path extends CurvePath {
  21619. constructor( points ) {
  21620. super();
  21621. this.type = 'Path';
  21622. this.currentPoint = new Vector2();
  21623. if ( points ) {
  21624. this.setFromPoints( points );
  21625. }
  21626. }
  21627. setFromPoints( points ) {
  21628. this.moveTo( points[ 0 ].x, points[ 0 ].y );
  21629. for ( let i = 1, l = points.length; i < l; i ++ ) {
  21630. this.lineTo( points[ i ].x, points[ i ].y );
  21631. }
  21632. return this;
  21633. }
  21634. moveTo( x, y ) {
  21635. this.currentPoint.set( x, y ); // TODO consider referencing vectors instead of copying?
  21636. return this;
  21637. }
  21638. lineTo( x, y ) {
  21639. const curve = new LineCurve( this.currentPoint.clone(), new Vector2( x, y ) );
  21640. this.curves.push( curve );
  21641. this.currentPoint.set( x, y );
  21642. return this;
  21643. }
  21644. quadraticCurveTo( aCPx, aCPy, aX, aY ) {
  21645. const curve = new QuadraticBezierCurve(
  21646. this.currentPoint.clone(),
  21647. new Vector2( aCPx, aCPy ),
  21648. new Vector2( aX, aY )
  21649. );
  21650. this.curves.push( curve );
  21651. this.currentPoint.set( aX, aY );
  21652. return this;
  21653. }
  21654. bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  21655. const curve = new CubicBezierCurve(
  21656. this.currentPoint.clone(),
  21657. new Vector2( aCP1x, aCP1y ),
  21658. new Vector2( aCP2x, aCP2y ),
  21659. new Vector2( aX, aY )
  21660. );
  21661. this.curves.push( curve );
  21662. this.currentPoint.set( aX, aY );
  21663. return this;
  21664. }
  21665. splineThru( pts /*Array of Vector*/ ) {
  21666. const npts = [ this.currentPoint.clone() ].concat( pts );
  21667. const curve = new SplineCurve( npts );
  21668. this.curves.push( curve );
  21669. this.currentPoint.copy( pts[ pts.length - 1 ] );
  21670. return this;
  21671. }
  21672. arc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  21673. const x0 = this.currentPoint.x;
  21674. const y0 = this.currentPoint.y;
  21675. this.absarc( aX + x0, aY + y0, aRadius,
  21676. aStartAngle, aEndAngle, aClockwise );
  21677. return this;
  21678. }
  21679. absarc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  21680. this.absellipse( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  21681. return this;
  21682. }
  21683. ellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  21684. const x0 = this.currentPoint.x;
  21685. const y0 = this.currentPoint.y;
  21686. this.absellipse( aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  21687. return this;
  21688. }
  21689. absellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  21690. const curve = new EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  21691. if ( this.curves.length > 0 ) {
  21692. // if a previous curve is present, attempt to join
  21693. const firstPoint = curve.getPoint( 0 );
  21694. if ( ! firstPoint.equals( this.currentPoint ) ) {
  21695. this.lineTo( firstPoint.x, firstPoint.y );
  21696. }
  21697. }
  21698. this.curves.push( curve );
  21699. const lastPoint = curve.getPoint( 1 );
  21700. this.currentPoint.copy( lastPoint );
  21701. return this;
  21702. }
  21703. copy( source ) {
  21704. super.copy( source );
  21705. this.currentPoint.copy( source.currentPoint );
  21706. return this;
  21707. }
  21708. toJSON() {
  21709. const data = super.toJSON();
  21710. data.currentPoint = this.currentPoint.toArray();
  21711. return data;
  21712. }
  21713. fromJSON( json ) {
  21714. super.fromJSON( json );
  21715. this.currentPoint.fromArray( json.currentPoint );
  21716. return this;
  21717. }
  21718. }
  21719. class LatheGeometry extends BufferGeometry {
  21720. 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 ) {
  21721. super();
  21722. this.type = 'LatheGeometry';
  21723. this.parameters = {
  21724. points: points,
  21725. segments: segments,
  21726. phiStart: phiStart,
  21727. phiLength: phiLength
  21728. };
  21729. segments = Math.floor( segments );
  21730. // clamp phiLength so it's in range of [ 0, 2PI ]
  21731. phiLength = clamp( phiLength, 0, Math.PI * 2 );
  21732. // buffers
  21733. const indices = [];
  21734. const vertices = [];
  21735. const uvs = [];
  21736. const initNormals = [];
  21737. const normals = [];
  21738. // helper variables
  21739. const inverseSegments = 1.0 / segments;
  21740. const vertex = new Vector3();
  21741. const uv = new Vector2();
  21742. const normal = new Vector3();
  21743. const curNormal = new Vector3();
  21744. const prevNormal = new Vector3();
  21745. let dx = 0;
  21746. let dy = 0;
  21747. // pre-compute normals for initial "meridian"
  21748. for ( let j = 0; j <= ( points.length - 1 ); j ++ ) {
  21749. switch ( j ) {
  21750. case 0: // special handling for 1st vertex on path
  21751. dx = points[ j + 1 ].x - points[ j ].x;
  21752. dy = points[ j + 1 ].y - points[ j ].y;
  21753. normal.x = dy * 1.0;
  21754. normal.y = - dx;
  21755. normal.z = dy * 0.0;
  21756. prevNormal.copy( normal );
  21757. normal.normalize();
  21758. initNormals.push( normal.x, normal.y, normal.z );
  21759. break;
  21760. case ( points.length - 1 ): // special handling for last Vertex on path
  21761. initNormals.push( prevNormal.x, prevNormal.y, prevNormal.z );
  21762. break;
  21763. default: // default handling for all vertices in between
  21764. dx = points[ j + 1 ].x - points[ j ].x;
  21765. dy = points[ j + 1 ].y - points[ j ].y;
  21766. normal.x = dy * 1.0;
  21767. normal.y = - dx;
  21768. normal.z = dy * 0.0;
  21769. curNormal.copy( normal );
  21770. normal.x += prevNormal.x;
  21771. normal.y += prevNormal.y;
  21772. normal.z += prevNormal.z;
  21773. normal.normalize();
  21774. initNormals.push( normal.x, normal.y, normal.z );
  21775. prevNormal.copy( curNormal );
  21776. }
  21777. }
  21778. // generate vertices, uvs and normals
  21779. for ( let i = 0; i <= segments; i ++ ) {
  21780. const phi = phiStart + i * inverseSegments * phiLength;
  21781. const sin = Math.sin( phi );
  21782. const cos = Math.cos( phi );
  21783. for ( let j = 0; j <= ( points.length - 1 ); j ++ ) {
  21784. // vertex
  21785. vertex.x = points[ j ].x * sin;
  21786. vertex.y = points[ j ].y;
  21787. vertex.z = points[ j ].x * cos;
  21788. vertices.push( vertex.x, vertex.y, vertex.z );
  21789. // uv
  21790. uv.x = i / segments;
  21791. uv.y = j / ( points.length - 1 );
  21792. uvs.push( uv.x, uv.y );
  21793. // normal
  21794. const x = initNormals[ 3 * j + 0 ] * sin;
  21795. const y = initNormals[ 3 * j + 1 ];
  21796. const z = initNormals[ 3 * j + 0 ] * cos;
  21797. normals.push( x, y, z );
  21798. }
  21799. }
  21800. // indices
  21801. for ( let i = 0; i < segments; i ++ ) {
  21802. for ( let j = 0; j < ( points.length - 1 ); j ++ ) {
  21803. const base = j + i * points.length;
  21804. const a = base;
  21805. const b = base + points.length;
  21806. const c = base + points.length + 1;
  21807. const d = base + 1;
  21808. // faces
  21809. indices.push( a, b, d );
  21810. indices.push( c, d, b );
  21811. }
  21812. }
  21813. // build geometry
  21814. this.setIndex( indices );
  21815. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21816. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  21817. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  21818. }
  21819. copy( source ) {
  21820. super.copy( source );
  21821. this.parameters = Object.assign( {}, source.parameters );
  21822. return this;
  21823. }
  21824. static fromJSON( data ) {
  21825. return new LatheGeometry( data.points, data.segments, data.phiStart, data.phiLength );
  21826. }
  21827. }
  21828. class CapsuleGeometry extends LatheGeometry {
  21829. constructor( radius = 1, length = 1, capSegments = 4, radialSegments = 8 ) {
  21830. const path = new Path();
  21831. path.absarc( 0, - length / 2, radius, Math.PI * 1.5, 0 );
  21832. path.absarc( 0, length / 2, radius, 0, Math.PI * 0.5 );
  21833. super( path.getPoints( capSegments ), radialSegments );
  21834. this.type = 'CapsuleGeometry';
  21835. this.parameters = {
  21836. radius: radius,
  21837. length: length,
  21838. capSegments: capSegments,
  21839. radialSegments: radialSegments,
  21840. };
  21841. }
  21842. static fromJSON( data ) {
  21843. return new CapsuleGeometry( data.radius, data.length, data.capSegments, data.radialSegments );
  21844. }
  21845. }
  21846. class CircleGeometry extends BufferGeometry {
  21847. constructor( radius = 1, segments = 32, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  21848. super();
  21849. this.type = 'CircleGeometry';
  21850. this.parameters = {
  21851. radius: radius,
  21852. segments: segments,
  21853. thetaStart: thetaStart,
  21854. thetaLength: thetaLength
  21855. };
  21856. segments = Math.max( 3, segments );
  21857. // buffers
  21858. const indices = [];
  21859. const vertices = [];
  21860. const normals = [];
  21861. const uvs = [];
  21862. // helper variables
  21863. const vertex = new Vector3();
  21864. const uv = new Vector2();
  21865. // center point
  21866. vertices.push( 0, 0, 0 );
  21867. normals.push( 0, 0, 1 );
  21868. uvs.push( 0.5, 0.5 );
  21869. for ( let s = 0, i = 3; s <= segments; s ++, i += 3 ) {
  21870. const segment = thetaStart + s / segments * thetaLength;
  21871. // vertex
  21872. vertex.x = radius * Math.cos( segment );
  21873. vertex.y = radius * Math.sin( segment );
  21874. vertices.push( vertex.x, vertex.y, vertex.z );
  21875. // normal
  21876. normals.push( 0, 0, 1 );
  21877. // uvs
  21878. uv.x = ( vertices[ i ] / radius + 1 ) / 2;
  21879. uv.y = ( vertices[ i + 1 ] / radius + 1 ) / 2;
  21880. uvs.push( uv.x, uv.y );
  21881. }
  21882. // indices
  21883. for ( let i = 1; i <= segments; i ++ ) {
  21884. indices.push( i, i + 1, 0 );
  21885. }
  21886. // build geometry
  21887. this.setIndex( indices );
  21888. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21889. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  21890. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  21891. }
  21892. copy( source ) {
  21893. super.copy( source );
  21894. this.parameters = Object.assign( {}, source.parameters );
  21895. return this;
  21896. }
  21897. static fromJSON( data ) {
  21898. return new CircleGeometry( data.radius, data.segments, data.thetaStart, data.thetaLength );
  21899. }
  21900. }
  21901. class CylinderGeometry extends BufferGeometry {
  21902. constructor( radiusTop = 1, radiusBottom = 1, height = 1, radialSegments = 32, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  21903. super();
  21904. this.type = 'CylinderGeometry';
  21905. this.parameters = {
  21906. radiusTop: radiusTop,
  21907. radiusBottom: radiusBottom,
  21908. height: height,
  21909. radialSegments: radialSegments,
  21910. heightSegments: heightSegments,
  21911. openEnded: openEnded,
  21912. thetaStart: thetaStart,
  21913. thetaLength: thetaLength
  21914. };
  21915. const scope = this;
  21916. radialSegments = Math.floor( radialSegments );
  21917. heightSegments = Math.floor( heightSegments );
  21918. // buffers
  21919. const indices = [];
  21920. const vertices = [];
  21921. const normals = [];
  21922. const uvs = [];
  21923. // helper variables
  21924. let index = 0;
  21925. const indexArray = [];
  21926. const halfHeight = height / 2;
  21927. let groupStart = 0;
  21928. // generate geometry
  21929. generateTorso();
  21930. if ( openEnded === false ) {
  21931. if ( radiusTop > 0 ) generateCap( true );
  21932. if ( radiusBottom > 0 ) generateCap( false );
  21933. }
  21934. // build geometry
  21935. this.setIndex( indices );
  21936. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21937. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  21938. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  21939. function generateTorso() {
  21940. const normal = new Vector3();
  21941. const vertex = new Vector3();
  21942. let groupCount = 0;
  21943. // this will be used to calculate the normal
  21944. const slope = ( radiusBottom - radiusTop ) / height;
  21945. // generate vertices, normals and uvs
  21946. for ( let y = 0; y <= heightSegments; y ++ ) {
  21947. const indexRow = [];
  21948. const v = y / heightSegments;
  21949. // calculate the radius of the current row
  21950. const radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  21951. for ( let x = 0; x <= radialSegments; x ++ ) {
  21952. const u = x / radialSegments;
  21953. const theta = u * thetaLength + thetaStart;
  21954. const sinTheta = Math.sin( theta );
  21955. const cosTheta = Math.cos( theta );
  21956. // vertex
  21957. vertex.x = radius * sinTheta;
  21958. vertex.y = - v * height + halfHeight;
  21959. vertex.z = radius * cosTheta;
  21960. vertices.push( vertex.x, vertex.y, vertex.z );
  21961. // normal
  21962. normal.set( sinTheta, slope, cosTheta ).normalize();
  21963. normals.push( normal.x, normal.y, normal.z );
  21964. // uv
  21965. uvs.push( u, 1 - v );
  21966. // save index of vertex in respective row
  21967. indexRow.push( index ++ );
  21968. }
  21969. // now save vertices of the row in our index array
  21970. indexArray.push( indexRow );
  21971. }
  21972. // generate indices
  21973. for ( let x = 0; x < radialSegments; x ++ ) {
  21974. for ( let y = 0; y < heightSegments; y ++ ) {
  21975. // we use the index array to access the correct indices
  21976. const a = indexArray[ y ][ x ];
  21977. const b = indexArray[ y + 1 ][ x ];
  21978. const c = indexArray[ y + 1 ][ x + 1 ];
  21979. const d = indexArray[ y ][ x + 1 ];
  21980. // faces
  21981. indices.push( a, b, d );
  21982. indices.push( b, c, d );
  21983. // update group counter
  21984. groupCount += 6;
  21985. }
  21986. }
  21987. // add a group to the geometry. this will ensure multi material support
  21988. scope.addGroup( groupStart, groupCount, 0 );
  21989. // calculate new start value for groups
  21990. groupStart += groupCount;
  21991. }
  21992. function generateCap( top ) {
  21993. // save the index of the first center vertex
  21994. const centerIndexStart = index;
  21995. const uv = new Vector2();
  21996. const vertex = new Vector3();
  21997. let groupCount = 0;
  21998. const radius = ( top === true ) ? radiusTop : radiusBottom;
  21999. const sign = ( top === true ) ? 1 : - 1;
  22000. // first we generate the center vertex data of the cap.
  22001. // because the geometry needs one set of uvs per face,
  22002. // we must generate a center vertex per face/segment
  22003. for ( let x = 1; x <= radialSegments; x ++ ) {
  22004. // vertex
  22005. vertices.push( 0, halfHeight * sign, 0 );
  22006. // normal
  22007. normals.push( 0, sign, 0 );
  22008. // uv
  22009. uvs.push( 0.5, 0.5 );
  22010. // increase index
  22011. index ++;
  22012. }
  22013. // save the index of the last center vertex
  22014. const centerIndexEnd = index;
  22015. // now we generate the surrounding vertices, normals and uvs
  22016. for ( let x = 0; x <= radialSegments; x ++ ) {
  22017. const u = x / radialSegments;
  22018. const theta = u * thetaLength + thetaStart;
  22019. const cosTheta = Math.cos( theta );
  22020. const sinTheta = Math.sin( theta );
  22021. // vertex
  22022. vertex.x = radius * sinTheta;
  22023. vertex.y = halfHeight * sign;
  22024. vertex.z = radius * cosTheta;
  22025. vertices.push( vertex.x, vertex.y, vertex.z );
  22026. // normal
  22027. normals.push( 0, sign, 0 );
  22028. // uv
  22029. uv.x = ( cosTheta * 0.5 ) + 0.5;
  22030. uv.y = ( sinTheta * 0.5 * sign ) + 0.5;
  22031. uvs.push( uv.x, uv.y );
  22032. // increase index
  22033. index ++;
  22034. }
  22035. // generate indices
  22036. for ( let x = 0; x < radialSegments; x ++ ) {
  22037. const c = centerIndexStart + x;
  22038. const i = centerIndexEnd + x;
  22039. if ( top === true ) {
  22040. // face top
  22041. indices.push( i, i + 1, c );
  22042. } else {
  22043. // face bottom
  22044. indices.push( i + 1, i, c );
  22045. }
  22046. groupCount += 3;
  22047. }
  22048. // add a group to the geometry. this will ensure multi material support
  22049. scope.addGroup( groupStart, groupCount, top === true ? 1 : 2 );
  22050. // calculate new start value for groups
  22051. groupStart += groupCount;
  22052. }
  22053. }
  22054. copy( source ) {
  22055. super.copy( source );
  22056. this.parameters = Object.assign( {}, source.parameters );
  22057. return this;
  22058. }
  22059. static fromJSON( data ) {
  22060. return new CylinderGeometry( data.radiusTop, data.radiusBottom, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength );
  22061. }
  22062. }
  22063. class ConeGeometry extends CylinderGeometry {
  22064. constructor( radius = 1, height = 1, radialSegments = 32, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  22065. super( 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength );
  22066. this.type = 'ConeGeometry';
  22067. this.parameters = {
  22068. radius: radius,
  22069. height: height,
  22070. radialSegments: radialSegments,
  22071. heightSegments: heightSegments,
  22072. openEnded: openEnded,
  22073. thetaStart: thetaStart,
  22074. thetaLength: thetaLength
  22075. };
  22076. }
  22077. static fromJSON( data ) {
  22078. return new ConeGeometry( data.radius, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength );
  22079. }
  22080. }
  22081. class PolyhedronGeometry extends BufferGeometry {
  22082. constructor( vertices = [], indices = [], radius = 1, detail = 0 ) {
  22083. super();
  22084. this.type = 'PolyhedronGeometry';
  22085. this.parameters = {
  22086. vertices: vertices,
  22087. indices: indices,
  22088. radius: radius,
  22089. detail: detail
  22090. };
  22091. // default buffer data
  22092. const vertexBuffer = [];
  22093. const uvBuffer = [];
  22094. // the subdivision creates the vertex buffer data
  22095. subdivide( detail );
  22096. // all vertices should lie on a conceptual sphere with a given radius
  22097. applyRadius( radius );
  22098. // finally, create the uv data
  22099. generateUVs();
  22100. // build non-indexed geometry
  22101. this.setAttribute( 'position', new Float32BufferAttribute( vertexBuffer, 3 ) );
  22102. this.setAttribute( 'normal', new Float32BufferAttribute( vertexBuffer.slice(), 3 ) );
  22103. this.setAttribute( 'uv', new Float32BufferAttribute( uvBuffer, 2 ) );
  22104. if ( detail === 0 ) {
  22105. this.computeVertexNormals(); // flat normals
  22106. } else {
  22107. this.normalizeNormals(); // smooth normals
  22108. }
  22109. // helper functions
  22110. function subdivide( detail ) {
  22111. const a = new Vector3();
  22112. const b = new Vector3();
  22113. const c = new Vector3();
  22114. // iterate over all faces and apply a subdivision with the given detail value
  22115. for ( let i = 0; i < indices.length; i += 3 ) {
  22116. // get the vertices of the face
  22117. getVertexByIndex( indices[ i + 0 ], a );
  22118. getVertexByIndex( indices[ i + 1 ], b );
  22119. getVertexByIndex( indices[ i + 2 ], c );
  22120. // perform subdivision
  22121. subdivideFace( a, b, c, detail );
  22122. }
  22123. }
  22124. function subdivideFace( a, b, c, detail ) {
  22125. const cols = detail + 1;
  22126. // we use this multidimensional array as a data structure for creating the subdivision
  22127. const v = [];
  22128. // construct all of the vertices for this subdivision
  22129. for ( let i = 0; i <= cols; i ++ ) {
  22130. v[ i ] = [];
  22131. const aj = a.clone().lerp( c, i / cols );
  22132. const bj = b.clone().lerp( c, i / cols );
  22133. const rows = cols - i;
  22134. for ( let j = 0; j <= rows; j ++ ) {
  22135. if ( j === 0 && i === cols ) {
  22136. v[ i ][ j ] = aj;
  22137. } else {
  22138. v[ i ][ j ] = aj.clone().lerp( bj, j / rows );
  22139. }
  22140. }
  22141. }
  22142. // construct all of the faces
  22143. for ( let i = 0; i < cols; i ++ ) {
  22144. for ( let j = 0; j < 2 * ( cols - i ) - 1; j ++ ) {
  22145. const k = Math.floor( j / 2 );
  22146. if ( j % 2 === 0 ) {
  22147. pushVertex( v[ i ][ k + 1 ] );
  22148. pushVertex( v[ i + 1 ][ k ] );
  22149. pushVertex( v[ i ][ k ] );
  22150. } else {
  22151. pushVertex( v[ i ][ k + 1 ] );
  22152. pushVertex( v[ i + 1 ][ k + 1 ] );
  22153. pushVertex( v[ i + 1 ][ k ] );
  22154. }
  22155. }
  22156. }
  22157. }
  22158. function applyRadius( radius ) {
  22159. const vertex = new Vector3();
  22160. // iterate over the entire buffer and apply the radius to each vertex
  22161. for ( let i = 0; i < vertexBuffer.length; i += 3 ) {
  22162. vertex.x = vertexBuffer[ i + 0 ];
  22163. vertex.y = vertexBuffer[ i + 1 ];
  22164. vertex.z = vertexBuffer[ i + 2 ];
  22165. vertex.normalize().multiplyScalar( radius );
  22166. vertexBuffer[ i + 0 ] = vertex.x;
  22167. vertexBuffer[ i + 1 ] = vertex.y;
  22168. vertexBuffer[ i + 2 ] = vertex.z;
  22169. }
  22170. }
  22171. function generateUVs() {
  22172. const vertex = new Vector3();
  22173. for ( let i = 0; i < vertexBuffer.length; i += 3 ) {
  22174. vertex.x = vertexBuffer[ i + 0 ];
  22175. vertex.y = vertexBuffer[ i + 1 ];
  22176. vertex.z = vertexBuffer[ i + 2 ];
  22177. const u = azimuth( vertex ) / 2 / Math.PI + 0.5;
  22178. const v = inclination( vertex ) / Math.PI + 0.5;
  22179. uvBuffer.push( u, 1 - v );
  22180. }
  22181. correctUVs();
  22182. correctSeam();
  22183. }
  22184. function correctSeam() {
  22185. // handle case when face straddles the seam, see #3269
  22186. for ( let i = 0; i < uvBuffer.length; i += 6 ) {
  22187. // uv data of a single face
  22188. const x0 = uvBuffer[ i + 0 ];
  22189. const x1 = uvBuffer[ i + 2 ];
  22190. const x2 = uvBuffer[ i + 4 ];
  22191. const max = Math.max( x0, x1, x2 );
  22192. const min = Math.min( x0, x1, x2 );
  22193. // 0.9 is somewhat arbitrary
  22194. if ( max > 0.9 && min < 0.1 ) {
  22195. if ( x0 < 0.2 ) uvBuffer[ i + 0 ] += 1;
  22196. if ( x1 < 0.2 ) uvBuffer[ i + 2 ] += 1;
  22197. if ( x2 < 0.2 ) uvBuffer[ i + 4 ] += 1;
  22198. }
  22199. }
  22200. }
  22201. function pushVertex( vertex ) {
  22202. vertexBuffer.push( vertex.x, vertex.y, vertex.z );
  22203. }
  22204. function getVertexByIndex( index, vertex ) {
  22205. const stride = index * 3;
  22206. vertex.x = vertices[ stride + 0 ];
  22207. vertex.y = vertices[ stride + 1 ];
  22208. vertex.z = vertices[ stride + 2 ];
  22209. }
  22210. function correctUVs() {
  22211. const a = new Vector3();
  22212. const b = new Vector3();
  22213. const c = new Vector3();
  22214. const centroid = new Vector3();
  22215. const uvA = new Vector2();
  22216. const uvB = new Vector2();
  22217. const uvC = new Vector2();
  22218. for ( let i = 0, j = 0; i < vertexBuffer.length; i += 9, j += 6 ) {
  22219. a.set( vertexBuffer[ i + 0 ], vertexBuffer[ i + 1 ], vertexBuffer[ i + 2 ] );
  22220. b.set( vertexBuffer[ i + 3 ], vertexBuffer[ i + 4 ], vertexBuffer[ i + 5 ] );
  22221. c.set( vertexBuffer[ i + 6 ], vertexBuffer[ i + 7 ], vertexBuffer[ i + 8 ] );
  22222. uvA.set( uvBuffer[ j + 0 ], uvBuffer[ j + 1 ] );
  22223. uvB.set( uvBuffer[ j + 2 ], uvBuffer[ j + 3 ] );
  22224. uvC.set( uvBuffer[ j + 4 ], uvBuffer[ j + 5 ] );
  22225. centroid.copy( a ).add( b ).add( c ).divideScalar( 3 );
  22226. const azi = azimuth( centroid );
  22227. correctUV( uvA, j + 0, a, azi );
  22228. correctUV( uvB, j + 2, b, azi );
  22229. correctUV( uvC, j + 4, c, azi );
  22230. }
  22231. }
  22232. function correctUV( uv, stride, vector, azimuth ) {
  22233. if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) {
  22234. uvBuffer[ stride ] = uv.x - 1;
  22235. }
  22236. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) {
  22237. uvBuffer[ stride ] = azimuth / 2 / Math.PI + 0.5;
  22238. }
  22239. }
  22240. // Angle around the Y axis, counter-clockwise when looking from above.
  22241. function azimuth( vector ) {
  22242. return Math.atan2( vector.z, - vector.x );
  22243. }
  22244. // Angle above the XZ plane.
  22245. function inclination( vector ) {
  22246. return Math.atan2( - vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  22247. }
  22248. }
  22249. copy( source ) {
  22250. super.copy( source );
  22251. this.parameters = Object.assign( {}, source.parameters );
  22252. return this;
  22253. }
  22254. static fromJSON( data ) {
  22255. return new PolyhedronGeometry( data.vertices, data.indices, data.radius, data.details );
  22256. }
  22257. }
  22258. class DodecahedronGeometry extends PolyhedronGeometry {
  22259. constructor( radius = 1, detail = 0 ) {
  22260. const t = ( 1 + Math.sqrt( 5 ) ) / 2;
  22261. const r = 1 / t;
  22262. const vertices = [
  22263. // (±1, ±1, ±1)
  22264. - 1, - 1, - 1, - 1, - 1, 1,
  22265. - 1, 1, - 1, - 1, 1, 1,
  22266. 1, - 1, - 1, 1, - 1, 1,
  22267. 1, 1, - 1, 1, 1, 1,
  22268. // (0, ±1/φ, ±φ)
  22269. 0, - r, - t, 0, - r, t,
  22270. 0, r, - t, 0, r, t,
  22271. // (±1/φ, ±φ, 0)
  22272. - r, - t, 0, - r, t, 0,
  22273. r, - t, 0, r, t, 0,
  22274. // (±φ, 0, ±1/φ)
  22275. - t, 0, - r, t, 0, - r,
  22276. - t, 0, r, t, 0, r
  22277. ];
  22278. const indices = [
  22279. 3, 11, 7, 3, 7, 15, 3, 15, 13,
  22280. 7, 19, 17, 7, 17, 6, 7, 6, 15,
  22281. 17, 4, 8, 17, 8, 10, 17, 10, 6,
  22282. 8, 0, 16, 8, 16, 2, 8, 2, 10,
  22283. 0, 12, 1, 0, 1, 18, 0, 18, 16,
  22284. 6, 10, 2, 6, 2, 13, 6, 13, 15,
  22285. 2, 16, 18, 2, 18, 3, 2, 3, 13,
  22286. 18, 1, 9, 18, 9, 11, 18, 11, 3,
  22287. 4, 14, 12, 4, 12, 0, 4, 0, 8,
  22288. 11, 9, 5, 11, 5, 19, 11, 19, 7,
  22289. 19, 5, 14, 19, 14, 4, 19, 4, 17,
  22290. 1, 12, 14, 1, 14, 5, 1, 5, 9
  22291. ];
  22292. super( vertices, indices, radius, detail );
  22293. this.type = 'DodecahedronGeometry';
  22294. this.parameters = {
  22295. radius: radius,
  22296. detail: detail
  22297. };
  22298. }
  22299. static fromJSON( data ) {
  22300. return new DodecahedronGeometry( data.radius, data.detail );
  22301. }
  22302. }
  22303. const _v0 = /*@__PURE__*/ new Vector3();
  22304. const _v1$1 = /*@__PURE__*/ new Vector3();
  22305. const _normal = /*@__PURE__*/ new Vector3();
  22306. const _triangle = /*@__PURE__*/ new Triangle();
  22307. class EdgesGeometry extends BufferGeometry {
  22308. constructor( geometry = null, thresholdAngle = 1 ) {
  22309. super();
  22310. this.type = 'EdgesGeometry';
  22311. this.parameters = {
  22312. geometry: geometry,
  22313. thresholdAngle: thresholdAngle
  22314. };
  22315. if ( geometry !== null ) {
  22316. const precisionPoints = 4;
  22317. const precision = Math.pow( 10, precisionPoints );
  22318. const thresholdDot = Math.cos( DEG2RAD * thresholdAngle );
  22319. const indexAttr = geometry.getIndex();
  22320. const positionAttr = geometry.getAttribute( 'position' );
  22321. const indexCount = indexAttr ? indexAttr.count : positionAttr.count;
  22322. const indexArr = [ 0, 0, 0 ];
  22323. const vertKeys = [ 'a', 'b', 'c' ];
  22324. const hashes = new Array( 3 );
  22325. const edgeData = {};
  22326. const vertices = [];
  22327. for ( let i = 0; i < indexCount; i += 3 ) {
  22328. if ( indexAttr ) {
  22329. indexArr[ 0 ] = indexAttr.getX( i );
  22330. indexArr[ 1 ] = indexAttr.getX( i + 1 );
  22331. indexArr[ 2 ] = indexAttr.getX( i + 2 );
  22332. } else {
  22333. indexArr[ 0 ] = i;
  22334. indexArr[ 1 ] = i + 1;
  22335. indexArr[ 2 ] = i + 2;
  22336. }
  22337. const { a, b, c } = _triangle;
  22338. a.fromBufferAttribute( positionAttr, indexArr[ 0 ] );
  22339. b.fromBufferAttribute( positionAttr, indexArr[ 1 ] );
  22340. c.fromBufferAttribute( positionAttr, indexArr[ 2 ] );
  22341. _triangle.getNormal( _normal );
  22342. // create hashes for the edge from the vertices
  22343. hashes[ 0 ] = `${ Math.round( a.x * precision ) },${ Math.round( a.y * precision ) },${ Math.round( a.z * precision ) }`;
  22344. hashes[ 1 ] = `${ Math.round( b.x * precision ) },${ Math.round( b.y * precision ) },${ Math.round( b.z * precision ) }`;
  22345. hashes[ 2 ] = `${ Math.round( c.x * precision ) },${ Math.round( c.y * precision ) },${ Math.round( c.z * precision ) }`;
  22346. // skip degenerate triangles
  22347. if ( hashes[ 0 ] === hashes[ 1 ] || hashes[ 1 ] === hashes[ 2 ] || hashes[ 2 ] === hashes[ 0 ] ) {
  22348. continue;
  22349. }
  22350. // iterate over every edge
  22351. for ( let j = 0; j < 3; j ++ ) {
  22352. // get the first and next vertex making up the edge
  22353. const jNext = ( j + 1 ) % 3;
  22354. const vecHash0 = hashes[ j ];
  22355. const vecHash1 = hashes[ jNext ];
  22356. const v0 = _triangle[ vertKeys[ j ] ];
  22357. const v1 = _triangle[ vertKeys[ jNext ] ];
  22358. const hash = `${ vecHash0 }_${ vecHash1 }`;
  22359. const reverseHash = `${ vecHash1 }_${ vecHash0 }`;
  22360. if ( reverseHash in edgeData && edgeData[ reverseHash ] ) {
  22361. // if we found a sibling edge add it into the vertex array if
  22362. // it meets the angle threshold and delete the edge from the map.
  22363. if ( _normal.dot( edgeData[ reverseHash ].normal ) <= thresholdDot ) {
  22364. vertices.push( v0.x, v0.y, v0.z );
  22365. vertices.push( v1.x, v1.y, v1.z );
  22366. }
  22367. edgeData[ reverseHash ] = null;
  22368. } else if ( ! ( hash in edgeData ) ) {
  22369. // if we've already got an edge here then skip adding a new one
  22370. edgeData[ hash ] = {
  22371. index0: indexArr[ j ],
  22372. index1: indexArr[ jNext ],
  22373. normal: _normal.clone(),
  22374. };
  22375. }
  22376. }
  22377. }
  22378. // iterate over all remaining, unmatched edges and add them to the vertex array
  22379. for ( const key in edgeData ) {
  22380. if ( edgeData[ key ] ) {
  22381. const { index0, index1 } = edgeData[ key ];
  22382. _v0.fromBufferAttribute( positionAttr, index0 );
  22383. _v1$1.fromBufferAttribute( positionAttr, index1 );
  22384. vertices.push( _v0.x, _v0.y, _v0.z );
  22385. vertices.push( _v1$1.x, _v1$1.y, _v1$1.z );
  22386. }
  22387. }
  22388. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22389. }
  22390. }
  22391. copy( source ) {
  22392. super.copy( source );
  22393. this.parameters = Object.assign( {}, source.parameters );
  22394. return this;
  22395. }
  22396. }
  22397. class Shape extends Path {
  22398. constructor( points ) {
  22399. super( points );
  22400. this.uuid = generateUUID();
  22401. this.type = 'Shape';
  22402. this.holes = [];
  22403. }
  22404. getPointsHoles( divisions ) {
  22405. const holesPts = [];
  22406. for ( let i = 0, l = this.holes.length; i < l; i ++ ) {
  22407. holesPts[ i ] = this.holes[ i ].getPoints( divisions );
  22408. }
  22409. return holesPts;
  22410. }
  22411. // get points of shape and holes (keypoints based on segments parameter)
  22412. extractPoints( divisions ) {
  22413. return {
  22414. shape: this.getPoints( divisions ),
  22415. holes: this.getPointsHoles( divisions )
  22416. };
  22417. }
  22418. copy( source ) {
  22419. super.copy( source );
  22420. this.holes = [];
  22421. for ( let i = 0, l = source.holes.length; i < l; i ++ ) {
  22422. const hole = source.holes[ i ];
  22423. this.holes.push( hole.clone() );
  22424. }
  22425. return this;
  22426. }
  22427. toJSON() {
  22428. const data = super.toJSON();
  22429. data.uuid = this.uuid;
  22430. data.holes = [];
  22431. for ( let i = 0, l = this.holes.length; i < l; i ++ ) {
  22432. const hole = this.holes[ i ];
  22433. data.holes.push( hole.toJSON() );
  22434. }
  22435. return data;
  22436. }
  22437. fromJSON( json ) {
  22438. super.fromJSON( json );
  22439. this.uuid = json.uuid;
  22440. this.holes = [];
  22441. for ( let i = 0, l = json.holes.length; i < l; i ++ ) {
  22442. const hole = json.holes[ i ];
  22443. this.holes.push( new Path().fromJSON( hole ) );
  22444. }
  22445. return this;
  22446. }
  22447. }
  22448. /**
  22449. * Port from https://github.com/mapbox/earcut (v2.2.4)
  22450. */
  22451. const Earcut = {
  22452. triangulate: function ( data, holeIndices, dim = 2 ) {
  22453. const hasHoles = holeIndices && holeIndices.length;
  22454. const outerLen = hasHoles ? holeIndices[ 0 ] * dim : data.length;
  22455. let outerNode = linkedList( data, 0, outerLen, dim, true );
  22456. const triangles = [];
  22457. if ( ! outerNode || outerNode.next === outerNode.prev ) return triangles;
  22458. let minX, minY, maxX, maxY, x, y, invSize;
  22459. if ( hasHoles ) outerNode = eliminateHoles( data, holeIndices, outerNode, dim );
  22460. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  22461. if ( data.length > 80 * dim ) {
  22462. minX = maxX = data[ 0 ];
  22463. minY = maxY = data[ 1 ];
  22464. for ( let i = dim; i < outerLen; i += dim ) {
  22465. x = data[ i ];
  22466. y = data[ i + 1 ];
  22467. if ( x < minX ) minX = x;
  22468. if ( y < minY ) minY = y;
  22469. if ( x > maxX ) maxX = x;
  22470. if ( y > maxY ) maxY = y;
  22471. }
  22472. // minX, minY and invSize are later used to transform coords into integers for z-order calculation
  22473. invSize = Math.max( maxX - minX, maxY - minY );
  22474. invSize = invSize !== 0 ? 32767 / invSize : 0;
  22475. }
  22476. earcutLinked( outerNode, triangles, dim, minX, minY, invSize, 0 );
  22477. return triangles;
  22478. }
  22479. };
  22480. // create a circular doubly linked list from polygon points in the specified winding order
  22481. function linkedList( data, start, end, dim, clockwise ) {
  22482. let i, last;
  22483. if ( clockwise === ( signedArea( data, start, end, dim ) > 0 ) ) {
  22484. for ( i = start; i < end; i += dim ) last = insertNode( i, data[ i ], data[ i + 1 ], last );
  22485. } else {
  22486. for ( i = end - dim; i >= start; i -= dim ) last = insertNode( i, data[ i ], data[ i + 1 ], last );
  22487. }
  22488. if ( last && equals( last, last.next ) ) {
  22489. removeNode( last );
  22490. last = last.next;
  22491. }
  22492. return last;
  22493. }
  22494. // eliminate colinear or duplicate points
  22495. function filterPoints( start, end ) {
  22496. if ( ! start ) return start;
  22497. if ( ! end ) end = start;
  22498. let p = start,
  22499. again;
  22500. do {
  22501. again = false;
  22502. if ( ! p.steiner && ( equals( p, p.next ) || area( p.prev, p, p.next ) === 0 ) ) {
  22503. removeNode( p );
  22504. p = end = p.prev;
  22505. if ( p === p.next ) break;
  22506. again = true;
  22507. } else {
  22508. p = p.next;
  22509. }
  22510. } while ( again || p !== end );
  22511. return end;
  22512. }
  22513. // main ear slicing loop which triangulates a polygon (given as a linked list)
  22514. function earcutLinked( ear, triangles, dim, minX, minY, invSize, pass ) {
  22515. if ( ! ear ) return;
  22516. // interlink polygon nodes in z-order
  22517. if ( ! pass && invSize ) indexCurve( ear, minX, minY, invSize );
  22518. let stop = ear,
  22519. prev, next;
  22520. // iterate through ears, slicing them one by one
  22521. while ( ear.prev !== ear.next ) {
  22522. prev = ear.prev;
  22523. next = ear.next;
  22524. if ( invSize ? isEarHashed( ear, minX, minY, invSize ) : isEar( ear ) ) {
  22525. // cut off the triangle
  22526. triangles.push( prev.i / dim | 0 );
  22527. triangles.push( ear.i / dim | 0 );
  22528. triangles.push( next.i / dim | 0 );
  22529. removeNode( ear );
  22530. // skipping the next vertex leads to less sliver triangles
  22531. ear = next.next;
  22532. stop = next.next;
  22533. continue;
  22534. }
  22535. ear = next;
  22536. // if we looped through the whole remaining polygon and can't find any more ears
  22537. if ( ear === stop ) {
  22538. // try filtering points and slicing again
  22539. if ( ! pass ) {
  22540. earcutLinked( filterPoints( ear ), triangles, dim, minX, minY, invSize, 1 );
  22541. // if this didn't work, try curing all small self-intersections locally
  22542. } else if ( pass === 1 ) {
  22543. ear = cureLocalIntersections( filterPoints( ear ), triangles, dim );
  22544. earcutLinked( ear, triangles, dim, minX, minY, invSize, 2 );
  22545. // as a last resort, try splitting the remaining polygon into two
  22546. } else if ( pass === 2 ) {
  22547. splitEarcut( ear, triangles, dim, minX, minY, invSize );
  22548. }
  22549. break;
  22550. }
  22551. }
  22552. }
  22553. // check whether a polygon node forms a valid ear with adjacent nodes
  22554. function isEar( ear ) {
  22555. const a = ear.prev,
  22556. b = ear,
  22557. c = ear.next;
  22558. if ( area( a, b, c ) >= 0 ) return false; // reflex, can't be an ear
  22559. // now make sure we don't have other points inside the potential ear
  22560. const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y;
  22561. // triangle bbox; min & max are calculated like this for speed
  22562. const x0 = ax < bx ? ( ax < cx ? ax : cx ) : ( bx < cx ? bx : cx ),
  22563. y0 = ay < by ? ( ay < cy ? ay : cy ) : ( by < cy ? by : cy ),
  22564. x1 = ax > bx ? ( ax > cx ? ax : cx ) : ( bx > cx ? bx : cx ),
  22565. y1 = ay > by ? ( ay > cy ? ay : cy ) : ( by > cy ? by : cy );
  22566. let p = c.next;
  22567. while ( p !== a ) {
  22568. if ( p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 &&
  22569. pointInTriangle( ax, ay, bx, by, cx, cy, p.x, p.y ) &&
  22570. area( p.prev, p, p.next ) >= 0 ) return false;
  22571. p = p.next;
  22572. }
  22573. return true;
  22574. }
  22575. function isEarHashed( ear, minX, minY, invSize ) {
  22576. const a = ear.prev,
  22577. b = ear,
  22578. c = ear.next;
  22579. if ( area( a, b, c ) >= 0 ) return false; // reflex, can't be an ear
  22580. const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y;
  22581. // triangle bbox; min & max are calculated like this for speed
  22582. const x0 = ax < bx ? ( ax < cx ? ax : cx ) : ( bx < cx ? bx : cx ),
  22583. y0 = ay < by ? ( ay < cy ? ay : cy ) : ( by < cy ? by : cy ),
  22584. x1 = ax > bx ? ( ax > cx ? ax : cx ) : ( bx > cx ? bx : cx ),
  22585. y1 = ay > by ? ( ay > cy ? ay : cy ) : ( by > cy ? by : cy );
  22586. // z-order range for the current triangle bbox;
  22587. const minZ = zOrder( x0, y0, minX, minY, invSize ),
  22588. maxZ = zOrder( x1, y1, minX, minY, invSize );
  22589. let p = ear.prevZ,
  22590. n = ear.nextZ;
  22591. // look for points inside the triangle in both directions
  22592. while ( p && p.z >= minZ && n && n.z <= maxZ ) {
  22593. if ( p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c &&
  22594. pointInTriangle( ax, ay, bx, by, cx, cy, p.x, p.y ) && area( p.prev, p, p.next ) >= 0 ) return false;
  22595. p = p.prevZ;
  22596. if ( n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c &&
  22597. pointInTriangle( ax, ay, bx, by, cx, cy, n.x, n.y ) && area( n.prev, n, n.next ) >= 0 ) return false;
  22598. n = n.nextZ;
  22599. }
  22600. // look for remaining points in decreasing z-order
  22601. while ( p && p.z >= minZ ) {
  22602. if ( p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c &&
  22603. pointInTriangle( ax, ay, bx, by, cx, cy, p.x, p.y ) && area( p.prev, p, p.next ) >= 0 ) return false;
  22604. p = p.prevZ;
  22605. }
  22606. // look for remaining points in increasing z-order
  22607. while ( n && n.z <= maxZ ) {
  22608. if ( n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c &&
  22609. pointInTriangle( ax, ay, bx, by, cx, cy, n.x, n.y ) && area( n.prev, n, n.next ) >= 0 ) return false;
  22610. n = n.nextZ;
  22611. }
  22612. return true;
  22613. }
  22614. // go through all polygon nodes and cure small local self-intersections
  22615. function cureLocalIntersections( start, triangles, dim ) {
  22616. let p = start;
  22617. do {
  22618. const a = p.prev,
  22619. b = p.next.next;
  22620. if ( ! equals( a, b ) && intersects( a, p, p.next, b ) && locallyInside( a, b ) && locallyInside( b, a ) ) {
  22621. triangles.push( a.i / dim | 0 );
  22622. triangles.push( p.i / dim | 0 );
  22623. triangles.push( b.i / dim | 0 );
  22624. // remove two nodes involved
  22625. removeNode( p );
  22626. removeNode( p.next );
  22627. p = start = b;
  22628. }
  22629. p = p.next;
  22630. } while ( p !== start );
  22631. return filterPoints( p );
  22632. }
  22633. // try splitting polygon into two and triangulate them independently
  22634. function splitEarcut( start, triangles, dim, minX, minY, invSize ) {
  22635. // look for a valid diagonal that divides the polygon into two
  22636. let a = start;
  22637. do {
  22638. let b = a.next.next;
  22639. while ( b !== a.prev ) {
  22640. if ( a.i !== b.i && isValidDiagonal( a, b ) ) {
  22641. // split the polygon in two by the diagonal
  22642. let c = splitPolygon( a, b );
  22643. // filter colinear points around the cuts
  22644. a = filterPoints( a, a.next );
  22645. c = filterPoints( c, c.next );
  22646. // run earcut on each half
  22647. earcutLinked( a, triangles, dim, minX, minY, invSize, 0 );
  22648. earcutLinked( c, triangles, dim, minX, minY, invSize, 0 );
  22649. return;
  22650. }
  22651. b = b.next;
  22652. }
  22653. a = a.next;
  22654. } while ( a !== start );
  22655. }
  22656. // link every hole into the outer loop, producing a single-ring polygon without holes
  22657. function eliminateHoles( data, holeIndices, outerNode, dim ) {
  22658. const queue = [];
  22659. let i, len, start, end, list;
  22660. for ( i = 0, len = holeIndices.length; i < len; i ++ ) {
  22661. start = holeIndices[ i ] * dim;
  22662. end = i < len - 1 ? holeIndices[ i + 1 ] * dim : data.length;
  22663. list = linkedList( data, start, end, dim, false );
  22664. if ( list === list.next ) list.steiner = true;
  22665. queue.push( getLeftmost( list ) );
  22666. }
  22667. queue.sort( compareX );
  22668. // process holes from left to right
  22669. for ( i = 0; i < queue.length; i ++ ) {
  22670. outerNode = eliminateHole( queue[ i ], outerNode );
  22671. }
  22672. return outerNode;
  22673. }
  22674. function compareX( a, b ) {
  22675. return a.x - b.x;
  22676. }
  22677. // find a bridge between vertices that connects hole with an outer ring and link it
  22678. function eliminateHole( hole, outerNode ) {
  22679. const bridge = findHoleBridge( hole, outerNode );
  22680. if ( ! bridge ) {
  22681. return outerNode;
  22682. }
  22683. const bridgeReverse = splitPolygon( bridge, hole );
  22684. // filter collinear points around the cuts
  22685. filterPoints( bridgeReverse, bridgeReverse.next );
  22686. return filterPoints( bridge, bridge.next );
  22687. }
  22688. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  22689. function findHoleBridge( hole, outerNode ) {
  22690. let p = outerNode,
  22691. qx = - Infinity,
  22692. m;
  22693. const hx = hole.x, hy = hole.y;
  22694. // find a segment intersected by a ray from the hole's leftmost point to the left;
  22695. // segment's endpoint with lesser x will be potential connection point
  22696. do {
  22697. if ( hy <= p.y && hy >= p.next.y && p.next.y !== p.y ) {
  22698. const x = p.x + ( hy - p.y ) * ( p.next.x - p.x ) / ( p.next.y - p.y );
  22699. if ( x <= hx && x > qx ) {
  22700. qx = x;
  22701. m = p.x < p.next.x ? p : p.next;
  22702. if ( x === hx ) return m; // hole touches outer segment; pick leftmost endpoint
  22703. }
  22704. }
  22705. p = p.next;
  22706. } while ( p !== outerNode );
  22707. if ( ! m ) return null;
  22708. // look for points inside the triangle of hole point, segment intersection and endpoint;
  22709. // if there are no points found, we have a valid connection;
  22710. // otherwise choose the point of the minimum angle with the ray as connection point
  22711. const stop = m,
  22712. mx = m.x,
  22713. my = m.y;
  22714. let tanMin = Infinity, tan;
  22715. p = m;
  22716. do {
  22717. if ( hx >= p.x && p.x >= mx && hx !== p.x &&
  22718. pointInTriangle( hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y ) ) {
  22719. tan = Math.abs( hy - p.y ) / ( hx - p.x ); // tangential
  22720. if ( locallyInside( p, hole ) && ( tan < tanMin || ( tan === tanMin && ( p.x > m.x || ( p.x === m.x && sectorContainsSector( m, p ) ) ) ) ) ) {
  22721. m = p;
  22722. tanMin = tan;
  22723. }
  22724. }
  22725. p = p.next;
  22726. } while ( p !== stop );
  22727. return m;
  22728. }
  22729. // whether sector in vertex m contains sector in vertex p in the same coordinates
  22730. function sectorContainsSector( m, p ) {
  22731. return area( m.prev, m, p.prev ) < 0 && area( p.next, m, m.next ) < 0;
  22732. }
  22733. // interlink polygon nodes in z-order
  22734. function indexCurve( start, minX, minY, invSize ) {
  22735. let p = start;
  22736. do {
  22737. if ( p.z === 0 ) p.z = zOrder( p.x, p.y, minX, minY, invSize );
  22738. p.prevZ = p.prev;
  22739. p.nextZ = p.next;
  22740. p = p.next;
  22741. } while ( p !== start );
  22742. p.prevZ.nextZ = null;
  22743. p.prevZ = null;
  22744. sortLinked( p );
  22745. }
  22746. // Simon Tatham's linked list merge sort algorithm
  22747. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  22748. function sortLinked( list ) {
  22749. let i, p, q, e, tail, numMerges, pSize, qSize,
  22750. inSize = 1;
  22751. do {
  22752. p = list;
  22753. list = null;
  22754. tail = null;
  22755. numMerges = 0;
  22756. while ( p ) {
  22757. numMerges ++;
  22758. q = p;
  22759. pSize = 0;
  22760. for ( i = 0; i < inSize; i ++ ) {
  22761. pSize ++;
  22762. q = q.nextZ;
  22763. if ( ! q ) break;
  22764. }
  22765. qSize = inSize;
  22766. while ( pSize > 0 || ( qSize > 0 && q ) ) {
  22767. if ( pSize !== 0 && ( qSize === 0 || ! q || p.z <= q.z ) ) {
  22768. e = p;
  22769. p = p.nextZ;
  22770. pSize --;
  22771. } else {
  22772. e = q;
  22773. q = q.nextZ;
  22774. qSize --;
  22775. }
  22776. if ( tail ) tail.nextZ = e;
  22777. else list = e;
  22778. e.prevZ = tail;
  22779. tail = e;
  22780. }
  22781. p = q;
  22782. }
  22783. tail.nextZ = null;
  22784. inSize *= 2;
  22785. } while ( numMerges > 1 );
  22786. return list;
  22787. }
  22788. // z-order of a point given coords and inverse of the longer side of data bbox
  22789. function zOrder( x, y, minX, minY, invSize ) {
  22790. // coords are transformed into non-negative 15-bit integer range
  22791. x = ( x - minX ) * invSize | 0;
  22792. y = ( y - minY ) * invSize | 0;
  22793. x = ( x | ( x << 8 ) ) & 0x00FF00FF;
  22794. x = ( x | ( x << 4 ) ) & 0x0F0F0F0F;
  22795. x = ( x | ( x << 2 ) ) & 0x33333333;
  22796. x = ( x | ( x << 1 ) ) & 0x55555555;
  22797. y = ( y | ( y << 8 ) ) & 0x00FF00FF;
  22798. y = ( y | ( y << 4 ) ) & 0x0F0F0F0F;
  22799. y = ( y | ( y << 2 ) ) & 0x33333333;
  22800. y = ( y | ( y << 1 ) ) & 0x55555555;
  22801. return x | ( y << 1 );
  22802. }
  22803. // find the leftmost node of a polygon ring
  22804. function getLeftmost( start ) {
  22805. let p = start,
  22806. leftmost = start;
  22807. do {
  22808. if ( p.x < leftmost.x || ( p.x === leftmost.x && p.y < leftmost.y ) ) leftmost = p;
  22809. p = p.next;
  22810. } while ( p !== start );
  22811. return leftmost;
  22812. }
  22813. // check if a point lies within a convex triangle
  22814. function pointInTriangle( ax, ay, bx, by, cx, cy, px, py ) {
  22815. return ( cx - px ) * ( ay - py ) >= ( ax - px ) * ( cy - py ) &&
  22816. ( ax - px ) * ( by - py ) >= ( bx - px ) * ( ay - py ) &&
  22817. ( bx - px ) * ( cy - py ) >= ( cx - px ) * ( by - py );
  22818. }
  22819. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  22820. function isValidDiagonal( a, b ) {
  22821. return a.next.i !== b.i && a.prev.i !== b.i && ! intersectsPolygon( a, b ) && // dones't intersect other edges
  22822. ( locallyInside( a, b ) && locallyInside( b, a ) && middleInside( a, b ) && // locally visible
  22823. ( area( a.prev, a, b.prev ) || area( a, b.prev, b ) ) || // does not create opposite-facing sectors
  22824. equals( a, b ) && area( a.prev, a, a.next ) > 0 && area( b.prev, b, b.next ) > 0 ); // special zero-length case
  22825. }
  22826. // signed area of a triangle
  22827. function area( p, q, r ) {
  22828. return ( q.y - p.y ) * ( r.x - q.x ) - ( q.x - p.x ) * ( r.y - q.y );
  22829. }
  22830. // check if two points are equal
  22831. function equals( p1, p2 ) {
  22832. return p1.x === p2.x && p1.y === p2.y;
  22833. }
  22834. // check if two segments intersect
  22835. function intersects( p1, q1, p2, q2 ) {
  22836. const o1 = sign( area( p1, q1, p2 ) );
  22837. const o2 = sign( area( p1, q1, q2 ) );
  22838. const o3 = sign( area( p2, q2, p1 ) );
  22839. const o4 = sign( area( p2, q2, q1 ) );
  22840. if ( o1 !== o2 && o3 !== o4 ) return true; // general case
  22841. if ( o1 === 0 && onSegment( p1, p2, q1 ) ) return true; // p1, q1 and p2 are collinear and p2 lies on p1q1
  22842. if ( o2 === 0 && onSegment( p1, q2, q1 ) ) return true; // p1, q1 and q2 are collinear and q2 lies on p1q1
  22843. if ( o3 === 0 && onSegment( p2, p1, q2 ) ) return true; // p2, q2 and p1 are collinear and p1 lies on p2q2
  22844. if ( o4 === 0 && onSegment( p2, q1, q2 ) ) return true; // p2, q2 and q1 are collinear and q1 lies on p2q2
  22845. return false;
  22846. }
  22847. // for collinear points p, q, r, check if point q lies on segment pr
  22848. function onSegment( p, q, r ) {
  22849. 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 );
  22850. }
  22851. function sign( num ) {
  22852. return num > 0 ? 1 : num < 0 ? - 1 : 0;
  22853. }
  22854. // check if a polygon diagonal intersects any polygon segments
  22855. function intersectsPolygon( a, b ) {
  22856. let p = a;
  22857. do {
  22858. if ( p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i &&
  22859. intersects( p, p.next, a, b ) ) return true;
  22860. p = p.next;
  22861. } while ( p !== a );
  22862. return false;
  22863. }
  22864. // check if a polygon diagonal is locally inside the polygon
  22865. function locallyInside( a, b ) {
  22866. return area( a.prev, a, a.next ) < 0 ?
  22867. area( a, b, a.next ) >= 0 && area( a, a.prev, b ) >= 0 :
  22868. area( a, b, a.prev ) < 0 || area( a, a.next, b ) < 0;
  22869. }
  22870. // check if the middle point of a polygon diagonal is inside the polygon
  22871. function middleInside( a, b ) {
  22872. let p = a,
  22873. inside = false;
  22874. const px = ( a.x + b.x ) / 2,
  22875. py = ( a.y + b.y ) / 2;
  22876. do {
  22877. if ( ( ( p.y > py ) !== ( p.next.y > py ) ) && p.next.y !== p.y &&
  22878. ( px < ( p.next.x - p.x ) * ( py - p.y ) / ( p.next.y - p.y ) + p.x ) )
  22879. inside = ! inside;
  22880. p = p.next;
  22881. } while ( p !== a );
  22882. return inside;
  22883. }
  22884. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  22885. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  22886. function splitPolygon( a, b ) {
  22887. const a2 = new Node( a.i, a.x, a.y ),
  22888. b2 = new Node( b.i, b.x, b.y ),
  22889. an = a.next,
  22890. bp = b.prev;
  22891. a.next = b;
  22892. b.prev = a;
  22893. a2.next = an;
  22894. an.prev = a2;
  22895. b2.next = a2;
  22896. a2.prev = b2;
  22897. bp.next = b2;
  22898. b2.prev = bp;
  22899. return b2;
  22900. }
  22901. // create a node and optionally link it with previous one (in a circular doubly linked list)
  22902. function insertNode( i, x, y, last ) {
  22903. const p = new Node( i, x, y );
  22904. if ( ! last ) {
  22905. p.prev = p;
  22906. p.next = p;
  22907. } else {
  22908. p.next = last.next;
  22909. p.prev = last;
  22910. last.next.prev = p;
  22911. last.next = p;
  22912. }
  22913. return p;
  22914. }
  22915. function removeNode( p ) {
  22916. p.next.prev = p.prev;
  22917. p.prev.next = p.next;
  22918. if ( p.prevZ ) p.prevZ.nextZ = p.nextZ;
  22919. if ( p.nextZ ) p.nextZ.prevZ = p.prevZ;
  22920. }
  22921. function Node( i, x, y ) {
  22922. // vertex index in coordinates array
  22923. this.i = i;
  22924. // vertex coordinates
  22925. this.x = x;
  22926. this.y = y;
  22927. // previous and next vertex nodes in a polygon ring
  22928. this.prev = null;
  22929. this.next = null;
  22930. // z-order curve value
  22931. this.z = 0;
  22932. // previous and next nodes in z-order
  22933. this.prevZ = null;
  22934. this.nextZ = null;
  22935. // indicates whether this is a steiner point
  22936. this.steiner = false;
  22937. }
  22938. function signedArea( data, start, end, dim ) {
  22939. let sum = 0;
  22940. for ( let i = start, j = end - dim; i < end; i += dim ) {
  22941. sum += ( data[ j ] - data[ i ] ) * ( data[ i + 1 ] + data[ j + 1 ] );
  22942. j = i;
  22943. }
  22944. return sum;
  22945. }
  22946. class ShapeUtils {
  22947. // calculate area of the contour polygon
  22948. static area( contour ) {
  22949. const n = contour.length;
  22950. let a = 0.0;
  22951. for ( let p = n - 1, q = 0; q < n; p = q ++ ) {
  22952. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  22953. }
  22954. return a * 0.5;
  22955. }
  22956. static isClockWise( pts ) {
  22957. return ShapeUtils.area( pts ) < 0;
  22958. }
  22959. static triangulateShape( contour, holes ) {
  22960. const vertices = []; // flat array of vertices like [ x0,y0, x1,y1, x2,y2, ... ]
  22961. const holeIndices = []; // array of hole indices
  22962. const faces = []; // final array of vertex indices like [ [ a,b,d ], [ b,c,d ] ]
  22963. removeDupEndPts( contour );
  22964. addContour( vertices, contour );
  22965. //
  22966. let holeIndex = contour.length;
  22967. holes.forEach( removeDupEndPts );
  22968. for ( let i = 0; i < holes.length; i ++ ) {
  22969. holeIndices.push( holeIndex );
  22970. holeIndex += holes[ i ].length;
  22971. addContour( vertices, holes[ i ] );
  22972. }
  22973. //
  22974. const triangles = Earcut.triangulate( vertices, holeIndices );
  22975. //
  22976. for ( let i = 0; i < triangles.length; i += 3 ) {
  22977. faces.push( triangles.slice( i, i + 3 ) );
  22978. }
  22979. return faces;
  22980. }
  22981. }
  22982. function removeDupEndPts( points ) {
  22983. const l = points.length;
  22984. if ( l > 2 && points[ l - 1 ].equals( points[ 0 ] ) ) {
  22985. points.pop();
  22986. }
  22987. }
  22988. function addContour( vertices, contour ) {
  22989. for ( let i = 0; i < contour.length; i ++ ) {
  22990. vertices.push( contour[ i ].x );
  22991. vertices.push( contour[ i ].y );
  22992. }
  22993. }
  22994. /**
  22995. * Creates extruded geometry from a path shape.
  22996. *
  22997. * parameters = {
  22998. *
  22999. * curveSegments: <int>, // number of points on the curves
  23000. * steps: <int>, // number of points for z-side extrusions / used for subdividing segments of extrude spline too
  23001. * depth: <float>, // Depth to extrude the shape
  23002. *
  23003. * bevelEnabled: <bool>, // turn on bevel
  23004. * bevelThickness: <float>, // how deep into the original shape bevel goes
  23005. * bevelSize: <float>, // how far from shape outline (including bevelOffset) is bevel
  23006. * bevelOffset: <float>, // how far from shape outline does bevel start
  23007. * bevelSegments: <int>, // number of bevel layers
  23008. *
  23009. * extrudePath: <THREE.Curve> // curve to extrude shape along
  23010. *
  23011. * UVGenerator: <Object> // object that provides UV generator functions
  23012. *
  23013. * }
  23014. */
  23015. class ExtrudeGeometry extends BufferGeometry {
  23016. 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 = {} ) {
  23017. super();
  23018. this.type = 'ExtrudeGeometry';
  23019. this.parameters = {
  23020. shapes: shapes,
  23021. options: options
  23022. };
  23023. shapes = Array.isArray( shapes ) ? shapes : [ shapes ];
  23024. const scope = this;
  23025. const verticesArray = [];
  23026. const uvArray = [];
  23027. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  23028. const shape = shapes[ i ];
  23029. addShape( shape );
  23030. }
  23031. // build geometry
  23032. this.setAttribute( 'position', new Float32BufferAttribute( verticesArray, 3 ) );
  23033. this.setAttribute( 'uv', new Float32BufferAttribute( uvArray, 2 ) );
  23034. this.computeVertexNormals();
  23035. // functions
  23036. function addShape( shape ) {
  23037. const placeholder = [];
  23038. // options
  23039. const curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  23040. const steps = options.steps !== undefined ? options.steps : 1;
  23041. const depth = options.depth !== undefined ? options.depth : 1;
  23042. let bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true;
  23043. let bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 0.2;
  23044. let bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 0.1;
  23045. let bevelOffset = options.bevelOffset !== undefined ? options.bevelOffset : 0;
  23046. let bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  23047. const extrudePath = options.extrudePath;
  23048. const uvgen = options.UVGenerator !== undefined ? options.UVGenerator : WorldUVGenerator;
  23049. //
  23050. let extrudePts, extrudeByPath = false;
  23051. let splineTube, binormal, normal, position2;
  23052. if ( extrudePath ) {
  23053. extrudePts = extrudePath.getSpacedPoints( steps );
  23054. extrudeByPath = true;
  23055. bevelEnabled = false; // bevels not supported for path extrusion
  23056. // SETUP TNB variables
  23057. // TODO1 - have a .isClosed in spline?
  23058. splineTube = extrudePath.computeFrenetFrames( steps, false );
  23059. // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  23060. binormal = new Vector3();
  23061. normal = new Vector3();
  23062. position2 = new Vector3();
  23063. }
  23064. // Safeguards if bevels are not enabled
  23065. if ( ! bevelEnabled ) {
  23066. bevelSegments = 0;
  23067. bevelThickness = 0;
  23068. bevelSize = 0;
  23069. bevelOffset = 0;
  23070. }
  23071. // Variables initialization
  23072. const shapePoints = shape.extractPoints( curveSegments );
  23073. let vertices = shapePoints.shape;
  23074. const holes = shapePoints.holes;
  23075. const reverse = ! ShapeUtils.isClockWise( vertices );
  23076. if ( reverse ) {
  23077. vertices = vertices.reverse();
  23078. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  23079. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  23080. const ahole = holes[ h ];
  23081. if ( ShapeUtils.isClockWise( ahole ) ) {
  23082. holes[ h ] = ahole.reverse();
  23083. }
  23084. }
  23085. }
  23086. const faces = ShapeUtils.triangulateShape( vertices, holes );
  23087. /* Vertices */
  23088. const contour = vertices; // vertices has all points but contour has only points of circumference
  23089. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  23090. const ahole = holes[ h ];
  23091. vertices = vertices.concat( ahole );
  23092. }
  23093. function scalePt2( pt, vec, size ) {
  23094. if ( ! vec ) console.error( 'THREE.ExtrudeGeometry: vec does not exist' );
  23095. return pt.clone().addScaledVector( vec, size );
  23096. }
  23097. const vlen = vertices.length, flen = faces.length;
  23098. // Find directions for point movement
  23099. function getBevelVec( inPt, inPrev, inNext ) {
  23100. // computes for inPt the corresponding point inPt' on a new contour
  23101. // shifted by 1 unit (length of normalized vector) to the left
  23102. // if we walk along contour clockwise, this new contour is outside the old one
  23103. //
  23104. // inPt' is the intersection of the two lines parallel to the two
  23105. // adjacent edges of inPt at a distance of 1 unit on the left side.
  23106. let v_trans_x, v_trans_y, shrink_by; // resulting translation vector for inPt
  23107. // good reading for geometry algorithms (here: line-line intersection)
  23108. // http://geomalgorithms.com/a05-_intersect-1.html
  23109. const v_prev_x = inPt.x - inPrev.x,
  23110. v_prev_y = inPt.y - inPrev.y;
  23111. const v_next_x = inNext.x - inPt.x,
  23112. v_next_y = inNext.y - inPt.y;
  23113. const v_prev_lensq = ( v_prev_x * v_prev_x + v_prev_y * v_prev_y );
  23114. // check for collinear edges
  23115. const collinear0 = ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  23116. if ( Math.abs( collinear0 ) > Number.EPSILON ) {
  23117. // not collinear
  23118. // length of vectors for normalizing
  23119. const v_prev_len = Math.sqrt( v_prev_lensq );
  23120. const v_next_len = Math.sqrt( v_next_x * v_next_x + v_next_y * v_next_y );
  23121. // shift adjacent points by unit vectors to the left
  23122. const ptPrevShift_x = ( inPrev.x - v_prev_y / v_prev_len );
  23123. const ptPrevShift_y = ( inPrev.y + v_prev_x / v_prev_len );
  23124. const ptNextShift_x = ( inNext.x - v_next_y / v_next_len );
  23125. const ptNextShift_y = ( inNext.y + v_next_x / v_next_len );
  23126. // scaling factor for v_prev to intersection point
  23127. const sf = ( ( ptNextShift_x - ptPrevShift_x ) * v_next_y -
  23128. ( ptNextShift_y - ptPrevShift_y ) * v_next_x ) /
  23129. ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  23130. // vector from inPt to intersection point
  23131. v_trans_x = ( ptPrevShift_x + v_prev_x * sf - inPt.x );
  23132. v_trans_y = ( ptPrevShift_y + v_prev_y * sf - inPt.y );
  23133. // Don't normalize!, otherwise sharp corners become ugly
  23134. // but prevent crazy spikes
  23135. const v_trans_lensq = ( v_trans_x * v_trans_x + v_trans_y * v_trans_y );
  23136. if ( v_trans_lensq <= 2 ) {
  23137. return new Vector2( v_trans_x, v_trans_y );
  23138. } else {
  23139. shrink_by = Math.sqrt( v_trans_lensq / 2 );
  23140. }
  23141. } else {
  23142. // handle special case of collinear edges
  23143. let direction_eq = false; // assumes: opposite
  23144. if ( v_prev_x > Number.EPSILON ) {
  23145. if ( v_next_x > Number.EPSILON ) {
  23146. direction_eq = true;
  23147. }
  23148. } else {
  23149. if ( v_prev_x < - Number.EPSILON ) {
  23150. if ( v_next_x < - Number.EPSILON ) {
  23151. direction_eq = true;
  23152. }
  23153. } else {
  23154. if ( Math.sign( v_prev_y ) === Math.sign( v_next_y ) ) {
  23155. direction_eq = true;
  23156. }
  23157. }
  23158. }
  23159. if ( direction_eq ) {
  23160. // console.log("Warning: lines are a straight sequence");
  23161. v_trans_x = - v_prev_y;
  23162. v_trans_y = v_prev_x;
  23163. shrink_by = Math.sqrt( v_prev_lensq );
  23164. } else {
  23165. // console.log("Warning: lines are a straight spike");
  23166. v_trans_x = v_prev_x;
  23167. v_trans_y = v_prev_y;
  23168. shrink_by = Math.sqrt( v_prev_lensq / 2 );
  23169. }
  23170. }
  23171. return new Vector2( v_trans_x / shrink_by, v_trans_y / shrink_by );
  23172. }
  23173. const contourMovements = [];
  23174. for ( let i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  23175. if ( j === il ) j = 0;
  23176. if ( k === il ) k = 0;
  23177. // (j)---(i)---(k)
  23178. // console.log('i,j,k', i, j , k)
  23179. contourMovements[ i ] = getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  23180. }
  23181. const holesMovements = [];
  23182. let oneHoleMovements, verticesMovements = contourMovements.concat();
  23183. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  23184. const ahole = holes[ h ];
  23185. oneHoleMovements = [];
  23186. for ( let i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  23187. if ( j === il ) j = 0;
  23188. if ( k === il ) k = 0;
  23189. // (j)---(i)---(k)
  23190. oneHoleMovements[ i ] = getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  23191. }
  23192. holesMovements.push( oneHoleMovements );
  23193. verticesMovements = verticesMovements.concat( oneHoleMovements );
  23194. }
  23195. // Loop bevelSegments, 1 for the front, 1 for the back
  23196. for ( let b = 0; b < bevelSegments; b ++ ) {
  23197. //for ( b = bevelSegments; b > 0; b -- ) {
  23198. const t = b / bevelSegments;
  23199. const z = bevelThickness * Math.cos( t * Math.PI / 2 );
  23200. const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;
  23201. // contract shape
  23202. for ( let i = 0, il = contour.length; i < il; i ++ ) {
  23203. const vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  23204. v( vert.x, vert.y, - z );
  23205. }
  23206. // expand holes
  23207. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  23208. const ahole = holes[ h ];
  23209. oneHoleMovements = holesMovements[ h ];
  23210. for ( let i = 0, il = ahole.length; i < il; i ++ ) {
  23211. const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  23212. v( vert.x, vert.y, - z );
  23213. }
  23214. }
  23215. }
  23216. const bs = bevelSize + bevelOffset;
  23217. // Back facing vertices
  23218. for ( let i = 0; i < vlen; i ++ ) {
  23219. const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  23220. if ( ! extrudeByPath ) {
  23221. v( vert.x, vert.y, 0 );
  23222. } else {
  23223. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  23224. normal.copy( splineTube.normals[ 0 ] ).multiplyScalar( vert.x );
  23225. binormal.copy( splineTube.binormals[ 0 ] ).multiplyScalar( vert.y );
  23226. position2.copy( extrudePts[ 0 ] ).add( normal ).add( binormal );
  23227. v( position2.x, position2.y, position2.z );
  23228. }
  23229. }
  23230. // Add stepped vertices...
  23231. // Including front facing vertices
  23232. for ( let s = 1; s <= steps; s ++ ) {
  23233. for ( let i = 0; i < vlen; i ++ ) {
  23234. const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  23235. if ( ! extrudeByPath ) {
  23236. v( vert.x, vert.y, depth / steps * s );
  23237. } else {
  23238. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  23239. normal.copy( splineTube.normals[ s ] ).multiplyScalar( vert.x );
  23240. binormal.copy( splineTube.binormals[ s ] ).multiplyScalar( vert.y );
  23241. position2.copy( extrudePts[ s ] ).add( normal ).add( binormal );
  23242. v( position2.x, position2.y, position2.z );
  23243. }
  23244. }
  23245. }
  23246. // Add bevel segments planes
  23247. //for ( b = 1; b <= bevelSegments; b ++ ) {
  23248. for ( let b = bevelSegments - 1; b >= 0; b -- ) {
  23249. const t = b / bevelSegments;
  23250. const z = bevelThickness * Math.cos( t * Math.PI / 2 );
  23251. const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;
  23252. // contract shape
  23253. for ( let i = 0, il = contour.length; i < il; i ++ ) {
  23254. const vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  23255. v( vert.x, vert.y, depth + z );
  23256. }
  23257. // expand holes
  23258. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  23259. const ahole = holes[ h ];
  23260. oneHoleMovements = holesMovements[ h ];
  23261. for ( let i = 0, il = ahole.length; i < il; i ++ ) {
  23262. const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  23263. if ( ! extrudeByPath ) {
  23264. v( vert.x, vert.y, depth + z );
  23265. } else {
  23266. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  23267. }
  23268. }
  23269. }
  23270. }
  23271. /* Faces */
  23272. // Top and bottom faces
  23273. buildLidFaces();
  23274. // Sides faces
  23275. buildSideFaces();
  23276. ///// Internal functions
  23277. function buildLidFaces() {
  23278. const start = verticesArray.length / 3;
  23279. if ( bevelEnabled ) {
  23280. let layer = 0; // steps + 1
  23281. let offset = vlen * layer;
  23282. // Bottom faces
  23283. for ( let i = 0; i < flen; i ++ ) {
  23284. const face = faces[ i ];
  23285. f3( face[ 2 ] + offset, face[ 1 ] + offset, face[ 0 ] + offset );
  23286. }
  23287. layer = steps + bevelSegments * 2;
  23288. offset = vlen * layer;
  23289. // Top faces
  23290. for ( let i = 0; i < flen; i ++ ) {
  23291. const face = faces[ i ];
  23292. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset );
  23293. }
  23294. } else {
  23295. // Bottom faces
  23296. for ( let i = 0; i < flen; i ++ ) {
  23297. const face = faces[ i ];
  23298. f3( face[ 2 ], face[ 1 ], face[ 0 ] );
  23299. }
  23300. // Top faces
  23301. for ( let i = 0; i < flen; i ++ ) {
  23302. const face = faces[ i ];
  23303. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps );
  23304. }
  23305. }
  23306. scope.addGroup( start, verticesArray.length / 3 - start, 0 );
  23307. }
  23308. // Create faces for the z-sides of the shape
  23309. function buildSideFaces() {
  23310. const start = verticesArray.length / 3;
  23311. let layeroffset = 0;
  23312. sidewalls( contour, layeroffset );
  23313. layeroffset += contour.length;
  23314. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  23315. const ahole = holes[ h ];
  23316. sidewalls( ahole, layeroffset );
  23317. //, true
  23318. layeroffset += ahole.length;
  23319. }
  23320. scope.addGroup( start, verticesArray.length / 3 - start, 1 );
  23321. }
  23322. function sidewalls( contour, layeroffset ) {
  23323. let i = contour.length;
  23324. while ( -- i >= 0 ) {
  23325. const j = i;
  23326. let k = i - 1;
  23327. if ( k < 0 ) k = contour.length - 1;
  23328. //console.log('b', i,j, i-1, k,vertices.length);
  23329. for ( let s = 0, sl = ( steps + bevelSegments * 2 ); s < sl; s ++ ) {
  23330. const slen1 = vlen * s;
  23331. const slen2 = vlen * ( s + 1 );
  23332. const a = layeroffset + j + slen1,
  23333. b = layeroffset + k + slen1,
  23334. c = layeroffset + k + slen2,
  23335. d = layeroffset + j + slen2;
  23336. f4( a, b, c, d );
  23337. }
  23338. }
  23339. }
  23340. function v( x, y, z ) {
  23341. placeholder.push( x );
  23342. placeholder.push( y );
  23343. placeholder.push( z );
  23344. }
  23345. function f3( a, b, c ) {
  23346. addVertex( a );
  23347. addVertex( b );
  23348. addVertex( c );
  23349. const nextIndex = verticesArray.length / 3;
  23350. const uvs = uvgen.generateTopUV( scope, verticesArray, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  23351. addUV( uvs[ 0 ] );
  23352. addUV( uvs[ 1 ] );
  23353. addUV( uvs[ 2 ] );
  23354. }
  23355. function f4( a, b, c, d ) {
  23356. addVertex( a );
  23357. addVertex( b );
  23358. addVertex( d );
  23359. addVertex( b );
  23360. addVertex( c );
  23361. addVertex( d );
  23362. const nextIndex = verticesArray.length / 3;
  23363. const uvs = uvgen.generateSideWallUV( scope, verticesArray, nextIndex - 6, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  23364. addUV( uvs[ 0 ] );
  23365. addUV( uvs[ 1 ] );
  23366. addUV( uvs[ 3 ] );
  23367. addUV( uvs[ 1 ] );
  23368. addUV( uvs[ 2 ] );
  23369. addUV( uvs[ 3 ] );
  23370. }
  23371. function addVertex( index ) {
  23372. verticesArray.push( placeholder[ index * 3 + 0 ] );
  23373. verticesArray.push( placeholder[ index * 3 + 1 ] );
  23374. verticesArray.push( placeholder[ index * 3 + 2 ] );
  23375. }
  23376. function addUV( vector2 ) {
  23377. uvArray.push( vector2.x );
  23378. uvArray.push( vector2.y );
  23379. }
  23380. }
  23381. }
  23382. copy( source ) {
  23383. super.copy( source );
  23384. this.parameters = Object.assign( {}, source.parameters );
  23385. return this;
  23386. }
  23387. toJSON() {
  23388. const data = super.toJSON();
  23389. const shapes = this.parameters.shapes;
  23390. const options = this.parameters.options;
  23391. return toJSON$1( shapes, options, data );
  23392. }
  23393. static fromJSON( data, shapes ) {
  23394. const geometryShapes = [];
  23395. for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  23396. const shape = shapes[ data.shapes[ j ] ];
  23397. geometryShapes.push( shape );
  23398. }
  23399. const extrudePath = data.options.extrudePath;
  23400. if ( extrudePath !== undefined ) {
  23401. data.options.extrudePath = new Curves[ extrudePath.type ]().fromJSON( extrudePath );
  23402. }
  23403. return new ExtrudeGeometry( geometryShapes, data.options );
  23404. }
  23405. }
  23406. const WorldUVGenerator = {
  23407. generateTopUV: function ( geometry, vertices, indexA, indexB, indexC ) {
  23408. const a_x = vertices[ indexA * 3 ];
  23409. const a_y = vertices[ indexA * 3 + 1 ];
  23410. const b_x = vertices[ indexB * 3 ];
  23411. const b_y = vertices[ indexB * 3 + 1 ];
  23412. const c_x = vertices[ indexC * 3 ];
  23413. const c_y = vertices[ indexC * 3 + 1 ];
  23414. return [
  23415. new Vector2( a_x, a_y ),
  23416. new Vector2( b_x, b_y ),
  23417. new Vector2( c_x, c_y )
  23418. ];
  23419. },
  23420. generateSideWallUV: function ( geometry, vertices, indexA, indexB, indexC, indexD ) {
  23421. const a_x = vertices[ indexA * 3 ];
  23422. const a_y = vertices[ indexA * 3 + 1 ];
  23423. const a_z = vertices[ indexA * 3 + 2 ];
  23424. const b_x = vertices[ indexB * 3 ];
  23425. const b_y = vertices[ indexB * 3 + 1 ];
  23426. const b_z = vertices[ indexB * 3 + 2 ];
  23427. const c_x = vertices[ indexC * 3 ];
  23428. const c_y = vertices[ indexC * 3 + 1 ];
  23429. const c_z = vertices[ indexC * 3 + 2 ];
  23430. const d_x = vertices[ indexD * 3 ];
  23431. const d_y = vertices[ indexD * 3 + 1 ];
  23432. const d_z = vertices[ indexD * 3 + 2 ];
  23433. if ( Math.abs( a_y - b_y ) < Math.abs( a_x - b_x ) ) {
  23434. return [
  23435. new Vector2( a_x, 1 - a_z ),
  23436. new Vector2( b_x, 1 - b_z ),
  23437. new Vector2( c_x, 1 - c_z ),
  23438. new Vector2( d_x, 1 - d_z )
  23439. ];
  23440. } else {
  23441. return [
  23442. new Vector2( a_y, 1 - a_z ),
  23443. new Vector2( b_y, 1 - b_z ),
  23444. new Vector2( c_y, 1 - c_z ),
  23445. new Vector2( d_y, 1 - d_z )
  23446. ];
  23447. }
  23448. }
  23449. };
  23450. function toJSON$1( shapes, options, data ) {
  23451. data.shapes = [];
  23452. if ( Array.isArray( shapes ) ) {
  23453. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  23454. const shape = shapes[ i ];
  23455. data.shapes.push( shape.uuid );
  23456. }
  23457. } else {
  23458. data.shapes.push( shapes.uuid );
  23459. }
  23460. data.options = Object.assign( {}, options );
  23461. if ( options.extrudePath !== undefined ) data.options.extrudePath = options.extrudePath.toJSON();
  23462. return data;
  23463. }
  23464. class IcosahedronGeometry extends PolyhedronGeometry {
  23465. constructor( radius = 1, detail = 0 ) {
  23466. const t = ( 1 + Math.sqrt( 5 ) ) / 2;
  23467. const vertices = [
  23468. - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t, 0,
  23469. 0, - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t,
  23470. t, 0, - 1, t, 0, 1, - t, 0, - 1, - t, 0, 1
  23471. ];
  23472. const indices = [
  23473. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 0, 10, 11,
  23474. 1, 5, 9, 5, 11, 4, 11, 10, 2, 10, 7, 6, 7, 1, 8,
  23475. 3, 9, 4, 3, 4, 2, 3, 2, 6, 3, 6, 8, 3, 8, 9,
  23476. 4, 9, 5, 2, 4, 11, 6, 2, 10, 8, 6, 7, 9, 8, 1
  23477. ];
  23478. super( vertices, indices, radius, detail );
  23479. this.type = 'IcosahedronGeometry';
  23480. this.parameters = {
  23481. radius: radius,
  23482. detail: detail
  23483. };
  23484. }
  23485. static fromJSON( data ) {
  23486. return new IcosahedronGeometry( data.radius, data.detail );
  23487. }
  23488. }
  23489. class OctahedronGeometry extends PolyhedronGeometry {
  23490. constructor( radius = 1, detail = 0 ) {
  23491. const vertices = [
  23492. 1, 0, 0, - 1, 0, 0, 0, 1, 0,
  23493. 0, - 1, 0, 0, 0, 1, 0, 0, - 1
  23494. ];
  23495. const indices = [
  23496. 0, 2, 4, 0, 4, 3, 0, 3, 5,
  23497. 0, 5, 2, 1, 2, 5, 1, 5, 3,
  23498. 1, 3, 4, 1, 4, 2
  23499. ];
  23500. super( vertices, indices, radius, detail );
  23501. this.type = 'OctahedronGeometry';
  23502. this.parameters = {
  23503. radius: radius,
  23504. detail: detail
  23505. };
  23506. }
  23507. static fromJSON( data ) {
  23508. return new OctahedronGeometry( data.radius, data.detail );
  23509. }
  23510. }
  23511. class RingGeometry extends BufferGeometry {
  23512. constructor( innerRadius = 0.5, outerRadius = 1, thetaSegments = 32, phiSegments = 1, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  23513. super();
  23514. this.type = 'RingGeometry';
  23515. this.parameters = {
  23516. innerRadius: innerRadius,
  23517. outerRadius: outerRadius,
  23518. thetaSegments: thetaSegments,
  23519. phiSegments: phiSegments,
  23520. thetaStart: thetaStart,
  23521. thetaLength: thetaLength
  23522. };
  23523. thetaSegments = Math.max( 3, thetaSegments );
  23524. phiSegments = Math.max( 1, phiSegments );
  23525. // buffers
  23526. const indices = [];
  23527. const vertices = [];
  23528. const normals = [];
  23529. const uvs = [];
  23530. // some helper variables
  23531. let radius = innerRadius;
  23532. const radiusStep = ( ( outerRadius - innerRadius ) / phiSegments );
  23533. const vertex = new Vector3();
  23534. const uv = new Vector2();
  23535. // generate vertices, normals and uvs
  23536. for ( let j = 0; j <= phiSegments; j ++ ) {
  23537. for ( let i = 0; i <= thetaSegments; i ++ ) {
  23538. // values are generate from the inside of the ring to the outside
  23539. const segment = thetaStart + i / thetaSegments * thetaLength;
  23540. // vertex
  23541. vertex.x = radius * Math.cos( segment );
  23542. vertex.y = radius * Math.sin( segment );
  23543. vertices.push( vertex.x, vertex.y, vertex.z );
  23544. // normal
  23545. normals.push( 0, 0, 1 );
  23546. // uv
  23547. uv.x = ( vertex.x / outerRadius + 1 ) / 2;
  23548. uv.y = ( vertex.y / outerRadius + 1 ) / 2;
  23549. uvs.push( uv.x, uv.y );
  23550. }
  23551. // increase the radius for next row of vertices
  23552. radius += radiusStep;
  23553. }
  23554. // indices
  23555. for ( let j = 0; j < phiSegments; j ++ ) {
  23556. const thetaSegmentLevel = j * ( thetaSegments + 1 );
  23557. for ( let i = 0; i < thetaSegments; i ++ ) {
  23558. const segment = i + thetaSegmentLevel;
  23559. const a = segment;
  23560. const b = segment + thetaSegments + 1;
  23561. const c = segment + thetaSegments + 2;
  23562. const d = segment + 1;
  23563. // faces
  23564. indices.push( a, b, d );
  23565. indices.push( b, c, d );
  23566. }
  23567. }
  23568. // build geometry
  23569. this.setIndex( indices );
  23570. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  23571. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  23572. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  23573. }
  23574. copy( source ) {
  23575. super.copy( source );
  23576. this.parameters = Object.assign( {}, source.parameters );
  23577. return this;
  23578. }
  23579. static fromJSON( data ) {
  23580. return new RingGeometry( data.innerRadius, data.outerRadius, data.thetaSegments, data.phiSegments, data.thetaStart, data.thetaLength );
  23581. }
  23582. }
  23583. class ShapeGeometry extends BufferGeometry {
  23584. constructor( shapes = new Shape( [ new Vector2( 0, 0.5 ), new Vector2( - 0.5, - 0.5 ), new Vector2( 0.5, - 0.5 ) ] ), curveSegments = 12 ) {
  23585. super();
  23586. this.type = 'ShapeGeometry';
  23587. this.parameters = {
  23588. shapes: shapes,
  23589. curveSegments: curveSegments
  23590. };
  23591. // buffers
  23592. const indices = [];
  23593. const vertices = [];
  23594. const normals = [];
  23595. const uvs = [];
  23596. // helper variables
  23597. let groupStart = 0;
  23598. let groupCount = 0;
  23599. // allow single and array values for "shapes" parameter
  23600. if ( Array.isArray( shapes ) === false ) {
  23601. addShape( shapes );
  23602. } else {
  23603. for ( let i = 0; i < shapes.length; i ++ ) {
  23604. addShape( shapes[ i ] );
  23605. this.addGroup( groupStart, groupCount, i ); // enables MultiMaterial support
  23606. groupStart += groupCount;
  23607. groupCount = 0;
  23608. }
  23609. }
  23610. // build geometry
  23611. this.setIndex( indices );
  23612. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  23613. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  23614. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  23615. // helper functions
  23616. function addShape( shape ) {
  23617. const indexOffset = vertices.length / 3;
  23618. const points = shape.extractPoints( curveSegments );
  23619. let shapeVertices = points.shape;
  23620. const shapeHoles = points.holes;
  23621. // check direction of vertices
  23622. if ( ShapeUtils.isClockWise( shapeVertices ) === false ) {
  23623. shapeVertices = shapeVertices.reverse();
  23624. }
  23625. for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) {
  23626. const shapeHole = shapeHoles[ i ];
  23627. if ( ShapeUtils.isClockWise( shapeHole ) === true ) {
  23628. shapeHoles[ i ] = shapeHole.reverse();
  23629. }
  23630. }
  23631. const faces = ShapeUtils.triangulateShape( shapeVertices, shapeHoles );
  23632. // join vertices of inner and outer paths to a single array
  23633. for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) {
  23634. const shapeHole = shapeHoles[ i ];
  23635. shapeVertices = shapeVertices.concat( shapeHole );
  23636. }
  23637. // vertices, normals, uvs
  23638. for ( let i = 0, l = shapeVertices.length; i < l; i ++ ) {
  23639. const vertex = shapeVertices[ i ];
  23640. vertices.push( vertex.x, vertex.y, 0 );
  23641. normals.push( 0, 0, 1 );
  23642. uvs.push( vertex.x, vertex.y ); // world uvs
  23643. }
  23644. // indices
  23645. for ( let i = 0, l = faces.length; i < l; i ++ ) {
  23646. const face = faces[ i ];
  23647. const a = face[ 0 ] + indexOffset;
  23648. const b = face[ 1 ] + indexOffset;
  23649. const c = face[ 2 ] + indexOffset;
  23650. indices.push( a, b, c );
  23651. groupCount += 3;
  23652. }
  23653. }
  23654. }
  23655. copy( source ) {
  23656. super.copy( source );
  23657. this.parameters = Object.assign( {}, source.parameters );
  23658. return this;
  23659. }
  23660. toJSON() {
  23661. const data = super.toJSON();
  23662. const shapes = this.parameters.shapes;
  23663. return toJSON( shapes, data );
  23664. }
  23665. static fromJSON( data, shapes ) {
  23666. const geometryShapes = [];
  23667. for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  23668. const shape = shapes[ data.shapes[ j ] ];
  23669. geometryShapes.push( shape );
  23670. }
  23671. return new ShapeGeometry( geometryShapes, data.curveSegments );
  23672. }
  23673. }
  23674. function toJSON( shapes, data ) {
  23675. data.shapes = [];
  23676. if ( Array.isArray( shapes ) ) {
  23677. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  23678. const shape = shapes[ i ];
  23679. data.shapes.push( shape.uuid );
  23680. }
  23681. } else {
  23682. data.shapes.push( shapes.uuid );
  23683. }
  23684. return data;
  23685. }
  23686. class SphereGeometry extends BufferGeometry {
  23687. constructor( radius = 1, widthSegments = 32, heightSegments = 16, phiStart = 0, phiLength = Math.PI * 2, thetaStart = 0, thetaLength = Math.PI ) {
  23688. super();
  23689. this.type = 'SphereGeometry';
  23690. this.parameters = {
  23691. radius: radius,
  23692. widthSegments: widthSegments,
  23693. heightSegments: heightSegments,
  23694. phiStart: phiStart,
  23695. phiLength: phiLength,
  23696. thetaStart: thetaStart,
  23697. thetaLength: thetaLength
  23698. };
  23699. widthSegments = Math.max( 3, Math.floor( widthSegments ) );
  23700. heightSegments = Math.max( 2, Math.floor( heightSegments ) );
  23701. const thetaEnd = Math.min( thetaStart + thetaLength, Math.PI );
  23702. let index = 0;
  23703. const grid = [];
  23704. const vertex = new Vector3();
  23705. const normal = new Vector3();
  23706. // buffers
  23707. const indices = [];
  23708. const vertices = [];
  23709. const normals = [];
  23710. const uvs = [];
  23711. // generate vertices, normals and uvs
  23712. for ( let iy = 0; iy <= heightSegments; iy ++ ) {
  23713. const verticesRow = [];
  23714. const v = iy / heightSegments;
  23715. // special case for the poles
  23716. let uOffset = 0;
  23717. if ( iy === 0 && thetaStart === 0 ) {
  23718. uOffset = 0.5 / widthSegments;
  23719. } else if ( iy === heightSegments && thetaEnd === Math.PI ) {
  23720. uOffset = - 0.5 / widthSegments;
  23721. }
  23722. for ( let ix = 0; ix <= widthSegments; ix ++ ) {
  23723. const u = ix / widthSegments;
  23724. // vertex
  23725. vertex.x = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  23726. vertex.y = radius * Math.cos( thetaStart + v * thetaLength );
  23727. vertex.z = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  23728. vertices.push( vertex.x, vertex.y, vertex.z );
  23729. // normal
  23730. normal.copy( vertex ).normalize();
  23731. normals.push( normal.x, normal.y, normal.z );
  23732. // uv
  23733. uvs.push( u + uOffset, 1 - v );
  23734. verticesRow.push( index ++ );
  23735. }
  23736. grid.push( verticesRow );
  23737. }
  23738. // indices
  23739. for ( let iy = 0; iy < heightSegments; iy ++ ) {
  23740. for ( let ix = 0; ix < widthSegments; ix ++ ) {
  23741. const a = grid[ iy ][ ix + 1 ];
  23742. const b = grid[ iy ][ ix ];
  23743. const c = grid[ iy + 1 ][ ix ];
  23744. const d = grid[ iy + 1 ][ ix + 1 ];
  23745. if ( iy !== 0 || thetaStart > 0 ) indices.push( a, b, d );
  23746. if ( iy !== heightSegments - 1 || thetaEnd < Math.PI ) indices.push( b, c, d );
  23747. }
  23748. }
  23749. // build geometry
  23750. this.setIndex( indices );
  23751. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  23752. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  23753. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  23754. }
  23755. copy( source ) {
  23756. super.copy( source );
  23757. this.parameters = Object.assign( {}, source.parameters );
  23758. return this;
  23759. }
  23760. static fromJSON( data ) {
  23761. return new SphereGeometry( data.radius, data.widthSegments, data.heightSegments, data.phiStart, data.phiLength, data.thetaStart, data.thetaLength );
  23762. }
  23763. }
  23764. class TetrahedronGeometry extends PolyhedronGeometry {
  23765. constructor( radius = 1, detail = 0 ) {
  23766. const vertices = [
  23767. 1, 1, 1, - 1, - 1, 1, - 1, 1, - 1, 1, - 1, - 1
  23768. ];
  23769. const indices = [
  23770. 2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1
  23771. ];
  23772. super( vertices, indices, radius, detail );
  23773. this.type = 'TetrahedronGeometry';
  23774. this.parameters = {
  23775. radius: radius,
  23776. detail: detail
  23777. };
  23778. }
  23779. static fromJSON( data ) {
  23780. return new TetrahedronGeometry( data.radius, data.detail );
  23781. }
  23782. }
  23783. class TorusGeometry extends BufferGeometry {
  23784. constructor( radius = 1, tube = 0.4, radialSegments = 12, tubularSegments = 48, arc = Math.PI * 2 ) {
  23785. super();
  23786. this.type = 'TorusGeometry';
  23787. this.parameters = {
  23788. radius: radius,
  23789. tube: tube,
  23790. radialSegments: radialSegments,
  23791. tubularSegments: tubularSegments,
  23792. arc: arc
  23793. };
  23794. radialSegments = Math.floor( radialSegments );
  23795. tubularSegments = Math.floor( tubularSegments );
  23796. // buffers
  23797. const indices = [];
  23798. const vertices = [];
  23799. const normals = [];
  23800. const uvs = [];
  23801. // helper variables
  23802. const center = new Vector3();
  23803. const vertex = new Vector3();
  23804. const normal = new Vector3();
  23805. // generate vertices, normals and uvs
  23806. for ( let j = 0; j <= radialSegments; j ++ ) {
  23807. for ( let i = 0; i <= tubularSegments; i ++ ) {
  23808. const u = i / tubularSegments * arc;
  23809. const v = j / radialSegments * Math.PI * 2;
  23810. // vertex
  23811. vertex.x = ( radius + tube * Math.cos( v ) ) * Math.cos( u );
  23812. vertex.y = ( radius + tube * Math.cos( v ) ) * Math.sin( u );
  23813. vertex.z = tube * Math.sin( v );
  23814. vertices.push( vertex.x, vertex.y, vertex.z );
  23815. // normal
  23816. center.x = radius * Math.cos( u );
  23817. center.y = radius * Math.sin( u );
  23818. normal.subVectors( vertex, center ).normalize();
  23819. normals.push( normal.x, normal.y, normal.z );
  23820. // uv
  23821. uvs.push( i / tubularSegments );
  23822. uvs.push( j / radialSegments );
  23823. }
  23824. }
  23825. // generate indices
  23826. for ( let j = 1; j <= radialSegments; j ++ ) {
  23827. for ( let i = 1; i <= tubularSegments; i ++ ) {
  23828. // indices
  23829. const a = ( tubularSegments + 1 ) * j + i - 1;
  23830. const b = ( tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  23831. const c = ( tubularSegments + 1 ) * ( j - 1 ) + i;
  23832. const d = ( tubularSegments + 1 ) * j + i;
  23833. // faces
  23834. indices.push( a, b, d );
  23835. indices.push( b, c, d );
  23836. }
  23837. }
  23838. // build geometry
  23839. this.setIndex( indices );
  23840. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  23841. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  23842. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  23843. }
  23844. copy( source ) {
  23845. super.copy( source );
  23846. this.parameters = Object.assign( {}, source.parameters );
  23847. return this;
  23848. }
  23849. static fromJSON( data ) {
  23850. return new TorusGeometry( data.radius, data.tube, data.radialSegments, data.tubularSegments, data.arc );
  23851. }
  23852. }
  23853. class TorusKnotGeometry extends BufferGeometry {
  23854. constructor( radius = 1, tube = 0.4, tubularSegments = 64, radialSegments = 8, p = 2, q = 3 ) {
  23855. super();
  23856. this.type = 'TorusKnotGeometry';
  23857. this.parameters = {
  23858. radius: radius,
  23859. tube: tube,
  23860. tubularSegments: tubularSegments,
  23861. radialSegments: radialSegments,
  23862. p: p,
  23863. q: q
  23864. };
  23865. tubularSegments = Math.floor( tubularSegments );
  23866. radialSegments = Math.floor( radialSegments );
  23867. // buffers
  23868. const indices = [];
  23869. const vertices = [];
  23870. const normals = [];
  23871. const uvs = [];
  23872. // helper variables
  23873. const vertex = new Vector3();
  23874. const normal = new Vector3();
  23875. const P1 = new Vector3();
  23876. const P2 = new Vector3();
  23877. const B = new Vector3();
  23878. const T = new Vector3();
  23879. const N = new Vector3();
  23880. // generate vertices, normals and uvs
  23881. for ( let i = 0; i <= tubularSegments; ++ i ) {
  23882. // the radian "u" is used to calculate the position on the torus curve of the current tubular segment
  23883. const u = i / tubularSegments * p * Math.PI * 2;
  23884. // now we calculate two points. P1 is our current position on the curve, P2 is a little farther ahead.
  23885. // these points are used to create a special "coordinate space", which is necessary to calculate the correct vertex positions
  23886. calculatePositionOnCurve( u, p, q, radius, P1 );
  23887. calculatePositionOnCurve( u + 0.01, p, q, radius, P2 );
  23888. // calculate orthonormal basis
  23889. T.subVectors( P2, P1 );
  23890. N.addVectors( P2, P1 );
  23891. B.crossVectors( T, N );
  23892. N.crossVectors( B, T );
  23893. // normalize B, N. T can be ignored, we don't use it
  23894. B.normalize();
  23895. N.normalize();
  23896. for ( let j = 0; j <= radialSegments; ++ j ) {
  23897. // now calculate the vertices. they are nothing more than an extrusion of the torus curve.
  23898. // because we extrude a shape in the xy-plane, there is no need to calculate a z-value.
  23899. const v = j / radialSegments * Math.PI * 2;
  23900. const cx = - tube * Math.cos( v );
  23901. const cy = tube * Math.sin( v );
  23902. // now calculate the final vertex position.
  23903. // first we orient the extrusion with our basis vectors, then we add it to the current position on the curve
  23904. vertex.x = P1.x + ( cx * N.x + cy * B.x );
  23905. vertex.y = P1.y + ( cx * N.y + cy * B.y );
  23906. vertex.z = P1.z + ( cx * N.z + cy * B.z );
  23907. vertices.push( vertex.x, vertex.y, vertex.z );
  23908. // normal (P1 is always the center/origin of the extrusion, thus we can use it to calculate the normal)
  23909. normal.subVectors( vertex, P1 ).normalize();
  23910. normals.push( normal.x, normal.y, normal.z );
  23911. // uv
  23912. uvs.push( i / tubularSegments );
  23913. uvs.push( j / radialSegments );
  23914. }
  23915. }
  23916. // generate indices
  23917. for ( let j = 1; j <= tubularSegments; j ++ ) {
  23918. for ( let i = 1; i <= radialSegments; i ++ ) {
  23919. // indices
  23920. const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  23921. const b = ( radialSegments + 1 ) * j + ( i - 1 );
  23922. const c = ( radialSegments + 1 ) * j + i;
  23923. const d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  23924. // faces
  23925. indices.push( a, b, d );
  23926. indices.push( b, c, d );
  23927. }
  23928. }
  23929. // build geometry
  23930. this.setIndex( indices );
  23931. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  23932. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  23933. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  23934. // this function calculates the current position on the torus curve
  23935. function calculatePositionOnCurve( u, p, q, radius, position ) {
  23936. const cu = Math.cos( u );
  23937. const su = Math.sin( u );
  23938. const quOverP = q / p * u;
  23939. const cs = Math.cos( quOverP );
  23940. position.x = radius * ( 2 + cs ) * 0.5 * cu;
  23941. position.y = radius * ( 2 + cs ) * su * 0.5;
  23942. position.z = radius * Math.sin( quOverP ) * 0.5;
  23943. }
  23944. }
  23945. copy( source ) {
  23946. super.copy( source );
  23947. this.parameters = Object.assign( {}, source.parameters );
  23948. return this;
  23949. }
  23950. static fromJSON( data ) {
  23951. return new TorusKnotGeometry( data.radius, data.tube, data.tubularSegments, data.radialSegments, data.p, data.q );
  23952. }
  23953. }
  23954. class TubeGeometry extends BufferGeometry {
  23955. 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 ) {
  23956. super();
  23957. this.type = 'TubeGeometry';
  23958. this.parameters = {
  23959. path: path,
  23960. tubularSegments: tubularSegments,
  23961. radius: radius,
  23962. radialSegments: radialSegments,
  23963. closed: closed
  23964. };
  23965. const frames = path.computeFrenetFrames( tubularSegments, closed );
  23966. // expose internals
  23967. this.tangents = frames.tangents;
  23968. this.normals = frames.normals;
  23969. this.binormals = frames.binormals;
  23970. // helper variables
  23971. const vertex = new Vector3();
  23972. const normal = new Vector3();
  23973. const uv = new Vector2();
  23974. let P = new Vector3();
  23975. // buffer
  23976. const vertices = [];
  23977. const normals = [];
  23978. const uvs = [];
  23979. const indices = [];
  23980. // create buffer data
  23981. generateBufferData();
  23982. // build geometry
  23983. this.setIndex( indices );
  23984. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  23985. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  23986. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  23987. // functions
  23988. function generateBufferData() {
  23989. for ( let i = 0; i < tubularSegments; i ++ ) {
  23990. generateSegment( i );
  23991. }
  23992. // if the geometry is not closed, generate the last row of vertices and normals
  23993. // at the regular position on the given path
  23994. //
  23995. // if the geometry is closed, duplicate the first row of vertices and normals (uvs will differ)
  23996. generateSegment( ( closed === false ) ? tubularSegments : 0 );
  23997. // uvs are generated in a separate function.
  23998. // this makes it easy compute correct values for closed geometries
  23999. generateUVs();
  24000. // finally create faces
  24001. generateIndices();
  24002. }
  24003. function generateSegment( i ) {
  24004. // we use getPointAt to sample evenly distributed points from the given path
  24005. P = path.getPointAt( i / tubularSegments, P );
  24006. // retrieve corresponding normal and binormal
  24007. const N = frames.normals[ i ];
  24008. const B = frames.binormals[ i ];
  24009. // generate normals and vertices for the current segment
  24010. for ( let j = 0; j <= radialSegments; j ++ ) {
  24011. const v = j / radialSegments * Math.PI * 2;
  24012. const sin = Math.sin( v );
  24013. const cos = - Math.cos( v );
  24014. // normal
  24015. normal.x = ( cos * N.x + sin * B.x );
  24016. normal.y = ( cos * N.y + sin * B.y );
  24017. normal.z = ( cos * N.z + sin * B.z );
  24018. normal.normalize();
  24019. normals.push( normal.x, normal.y, normal.z );
  24020. // vertex
  24021. vertex.x = P.x + radius * normal.x;
  24022. vertex.y = P.y + radius * normal.y;
  24023. vertex.z = P.z + radius * normal.z;
  24024. vertices.push( vertex.x, vertex.y, vertex.z );
  24025. }
  24026. }
  24027. function generateIndices() {
  24028. for ( let j = 1; j <= tubularSegments; j ++ ) {
  24029. for ( let i = 1; i <= radialSegments; i ++ ) {
  24030. const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  24031. const b = ( radialSegments + 1 ) * j + ( i - 1 );
  24032. const c = ( radialSegments + 1 ) * j + i;
  24033. const d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  24034. // faces
  24035. indices.push( a, b, d );
  24036. indices.push( b, c, d );
  24037. }
  24038. }
  24039. }
  24040. function generateUVs() {
  24041. for ( let i = 0; i <= tubularSegments; i ++ ) {
  24042. for ( let j = 0; j <= radialSegments; j ++ ) {
  24043. uv.x = i / tubularSegments;
  24044. uv.y = j / radialSegments;
  24045. uvs.push( uv.x, uv.y );
  24046. }
  24047. }
  24048. }
  24049. }
  24050. copy( source ) {
  24051. super.copy( source );
  24052. this.parameters = Object.assign( {}, source.parameters );
  24053. return this;
  24054. }
  24055. toJSON() {
  24056. const data = super.toJSON();
  24057. data.path = this.parameters.path.toJSON();
  24058. return data;
  24059. }
  24060. static fromJSON( data ) {
  24061. // This only works for built-in curves (e.g. CatmullRomCurve3).
  24062. // User defined curves or instances of CurvePath will not be deserialized.
  24063. return new TubeGeometry(
  24064. new Curves[ data.path.type ]().fromJSON( data.path ),
  24065. data.tubularSegments,
  24066. data.radius,
  24067. data.radialSegments,
  24068. data.closed
  24069. );
  24070. }
  24071. }
  24072. class WireframeGeometry extends BufferGeometry {
  24073. constructor( geometry = null ) {
  24074. super();
  24075. this.type = 'WireframeGeometry';
  24076. this.parameters = {
  24077. geometry: geometry
  24078. };
  24079. if ( geometry !== null ) {
  24080. // buffer
  24081. const vertices = [];
  24082. const edges = new Set();
  24083. // helper variables
  24084. const start = new Vector3();
  24085. const end = new Vector3();
  24086. if ( geometry.index !== null ) {
  24087. // indexed BufferGeometry
  24088. const position = geometry.attributes.position;
  24089. const indices = geometry.index;
  24090. let groups = geometry.groups;
  24091. if ( groups.length === 0 ) {
  24092. groups = [ { start: 0, count: indices.count, materialIndex: 0 } ];
  24093. }
  24094. // create a data structure that contains all edges without duplicates
  24095. for ( let o = 0, ol = groups.length; o < ol; ++ o ) {
  24096. const group = groups[ o ];
  24097. const groupStart = group.start;
  24098. const groupCount = group.count;
  24099. for ( let i = groupStart, l = ( groupStart + groupCount ); i < l; i += 3 ) {
  24100. for ( let j = 0; j < 3; j ++ ) {
  24101. const index1 = indices.getX( i + j );
  24102. const index2 = indices.getX( i + ( j + 1 ) % 3 );
  24103. start.fromBufferAttribute( position, index1 );
  24104. end.fromBufferAttribute( position, index2 );
  24105. if ( isUniqueEdge( start, end, edges ) === true ) {
  24106. vertices.push( start.x, start.y, start.z );
  24107. vertices.push( end.x, end.y, end.z );
  24108. }
  24109. }
  24110. }
  24111. }
  24112. } else {
  24113. // non-indexed BufferGeometry
  24114. const position = geometry.attributes.position;
  24115. for ( let i = 0, l = ( position.count / 3 ); i < l; i ++ ) {
  24116. for ( let j = 0; j < 3; j ++ ) {
  24117. // three edges per triangle, an edge is represented as (index1, index2)
  24118. // e.g. the first triangle has the following edges: (0,1),(1,2),(2,0)
  24119. const index1 = 3 * i + j;
  24120. const index2 = 3 * i + ( ( j + 1 ) % 3 );
  24121. start.fromBufferAttribute( position, index1 );
  24122. end.fromBufferAttribute( position, index2 );
  24123. if ( isUniqueEdge( start, end, edges ) === true ) {
  24124. vertices.push( start.x, start.y, start.z );
  24125. vertices.push( end.x, end.y, end.z );
  24126. }
  24127. }
  24128. }
  24129. }
  24130. // build geometry
  24131. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  24132. }
  24133. }
  24134. copy( source ) {
  24135. super.copy( source );
  24136. this.parameters = Object.assign( {}, source.parameters );
  24137. return this;
  24138. }
  24139. }
  24140. function isUniqueEdge( start, end, edges ) {
  24141. const hash1 = `${start.x},${start.y},${start.z}-${end.x},${end.y},${end.z}`;
  24142. const hash2 = `${end.x},${end.y},${end.z}-${start.x},${start.y},${start.z}`; // coincident edge
  24143. if ( edges.has( hash1 ) === true || edges.has( hash2 ) === true ) {
  24144. return false;
  24145. } else {
  24146. edges.add( hash1 );
  24147. edges.add( hash2 );
  24148. return true;
  24149. }
  24150. }
  24151. var Geometries = /*#__PURE__*/Object.freeze({
  24152. __proto__: null,
  24153. BoxGeometry: BoxGeometry,
  24154. CapsuleGeometry: CapsuleGeometry,
  24155. CircleGeometry: CircleGeometry,
  24156. ConeGeometry: ConeGeometry,
  24157. CylinderGeometry: CylinderGeometry,
  24158. DodecahedronGeometry: DodecahedronGeometry,
  24159. EdgesGeometry: EdgesGeometry,
  24160. ExtrudeGeometry: ExtrudeGeometry,
  24161. IcosahedronGeometry: IcosahedronGeometry,
  24162. LatheGeometry: LatheGeometry,
  24163. OctahedronGeometry: OctahedronGeometry,
  24164. PlaneGeometry: PlaneGeometry,
  24165. PolyhedronGeometry: PolyhedronGeometry,
  24166. RingGeometry: RingGeometry,
  24167. ShapeGeometry: ShapeGeometry,
  24168. SphereGeometry: SphereGeometry,
  24169. TetrahedronGeometry: TetrahedronGeometry,
  24170. TorusGeometry: TorusGeometry,
  24171. TorusKnotGeometry: TorusKnotGeometry,
  24172. TubeGeometry: TubeGeometry,
  24173. WireframeGeometry: WireframeGeometry
  24174. });
  24175. class ShadowMaterial extends Material {
  24176. constructor( parameters ) {
  24177. super();
  24178. this.isShadowMaterial = true;
  24179. this.type = 'ShadowMaterial';
  24180. this.color = new Color( 0x000000 );
  24181. this.transparent = true;
  24182. this.fog = true;
  24183. this.setValues( parameters );
  24184. }
  24185. copy( source ) {
  24186. super.copy( source );
  24187. this.color.copy( source.color );
  24188. this.fog = source.fog;
  24189. return this;
  24190. }
  24191. }
  24192. class RawShaderMaterial extends ShaderMaterial {
  24193. constructor( parameters ) {
  24194. super( parameters );
  24195. this.isRawShaderMaterial = true;
  24196. this.type = 'RawShaderMaterial';
  24197. }
  24198. }
  24199. class MeshStandardMaterial extends Material {
  24200. constructor( parameters ) {
  24201. super();
  24202. this.isMeshStandardMaterial = true;
  24203. this.defines = { 'STANDARD': '' };
  24204. this.type = 'MeshStandardMaterial';
  24205. this.color = new Color( 0xffffff ); // diffuse
  24206. this.roughness = 1.0;
  24207. this.metalness = 0.0;
  24208. this.map = null;
  24209. this.lightMap = null;
  24210. this.lightMapIntensity = 1.0;
  24211. this.aoMap = null;
  24212. this.aoMapIntensity = 1.0;
  24213. this.emissive = new Color( 0x000000 );
  24214. this.emissiveIntensity = 1.0;
  24215. this.emissiveMap = null;
  24216. this.bumpMap = null;
  24217. this.bumpScale = 1;
  24218. this.normalMap = null;
  24219. this.normalMapType = TangentSpaceNormalMap;
  24220. this.normalScale = new Vector2( 1, 1 );
  24221. this.displacementMap = null;
  24222. this.displacementScale = 1;
  24223. this.displacementBias = 0;
  24224. this.roughnessMap = null;
  24225. this.metalnessMap = null;
  24226. this.alphaMap = null;
  24227. this.envMap = null;
  24228. this.envMapIntensity = 1.0;
  24229. this.wireframe = false;
  24230. this.wireframeLinewidth = 1;
  24231. this.wireframeLinecap = 'round';
  24232. this.wireframeLinejoin = 'round';
  24233. this.flatShading = false;
  24234. this.fog = true;
  24235. this.setValues( parameters );
  24236. }
  24237. copy( source ) {
  24238. super.copy( source );
  24239. this.defines = { 'STANDARD': '' };
  24240. this.color.copy( source.color );
  24241. this.roughness = source.roughness;
  24242. this.metalness = source.metalness;
  24243. this.map = source.map;
  24244. this.lightMap = source.lightMap;
  24245. this.lightMapIntensity = source.lightMapIntensity;
  24246. this.aoMap = source.aoMap;
  24247. this.aoMapIntensity = source.aoMapIntensity;
  24248. this.emissive.copy( source.emissive );
  24249. this.emissiveMap = source.emissiveMap;
  24250. this.emissiveIntensity = source.emissiveIntensity;
  24251. this.bumpMap = source.bumpMap;
  24252. this.bumpScale = source.bumpScale;
  24253. this.normalMap = source.normalMap;
  24254. this.normalMapType = source.normalMapType;
  24255. this.normalScale.copy( source.normalScale );
  24256. this.displacementMap = source.displacementMap;
  24257. this.displacementScale = source.displacementScale;
  24258. this.displacementBias = source.displacementBias;
  24259. this.roughnessMap = source.roughnessMap;
  24260. this.metalnessMap = source.metalnessMap;
  24261. this.alphaMap = source.alphaMap;
  24262. this.envMap = source.envMap;
  24263. this.envMapIntensity = source.envMapIntensity;
  24264. this.wireframe = source.wireframe;
  24265. this.wireframeLinewidth = source.wireframeLinewidth;
  24266. this.wireframeLinecap = source.wireframeLinecap;
  24267. this.wireframeLinejoin = source.wireframeLinejoin;
  24268. this.flatShading = source.flatShading;
  24269. this.fog = source.fog;
  24270. return this;
  24271. }
  24272. }
  24273. class MeshPhysicalMaterial extends MeshStandardMaterial {
  24274. constructor( parameters ) {
  24275. super();
  24276. this.isMeshPhysicalMaterial = true;
  24277. this.defines = {
  24278. 'STANDARD': '',
  24279. 'PHYSICAL': ''
  24280. };
  24281. this.type = 'MeshPhysicalMaterial';
  24282. this.anisotropyRotation = 0;
  24283. this.anisotropyMap = null;
  24284. this.clearcoatMap = null;
  24285. this.clearcoatRoughness = 0.0;
  24286. this.clearcoatRoughnessMap = null;
  24287. this.clearcoatNormalScale = new Vector2( 1, 1 );
  24288. this.clearcoatNormalMap = null;
  24289. this.ior = 1.5;
  24290. Object.defineProperty( this, 'reflectivity', {
  24291. get: function () {
  24292. return ( clamp( 2.5 * ( this.ior - 1 ) / ( this.ior + 1 ), 0, 1 ) );
  24293. },
  24294. set: function ( reflectivity ) {
  24295. this.ior = ( 1 + 0.4 * reflectivity ) / ( 1 - 0.4 * reflectivity );
  24296. }
  24297. } );
  24298. this.iridescenceMap = null;
  24299. this.iridescenceIOR = 1.3;
  24300. this.iridescenceThicknessRange = [ 100, 400 ];
  24301. this.iridescenceThicknessMap = null;
  24302. this.sheenColor = new Color( 0x000000 );
  24303. this.sheenColorMap = null;
  24304. this.sheenRoughness = 1.0;
  24305. this.sheenRoughnessMap = null;
  24306. this.transmissionMap = null;
  24307. this.thickness = 0;
  24308. this.thicknessMap = null;
  24309. this.attenuationDistance = Infinity;
  24310. this.attenuationColor = new Color( 1, 1, 1 );
  24311. this.specularIntensity = 1.0;
  24312. this.specularIntensityMap = null;
  24313. this.specularColor = new Color( 1, 1, 1 );
  24314. this.specularColorMap = null;
  24315. this._anisotropy = 0;
  24316. this._clearcoat = 0;
  24317. this._iridescence = 0;
  24318. this._sheen = 0.0;
  24319. this._transmission = 0;
  24320. this.setValues( parameters );
  24321. }
  24322. get anisotropy() {
  24323. return this._anisotropy;
  24324. }
  24325. set anisotropy( value ) {
  24326. if ( this._anisotropy > 0 !== value > 0 ) {
  24327. this.version ++;
  24328. }
  24329. this._anisotropy = value;
  24330. }
  24331. get clearcoat() {
  24332. return this._clearcoat;
  24333. }
  24334. set clearcoat( value ) {
  24335. if ( this._clearcoat > 0 !== value > 0 ) {
  24336. this.version ++;
  24337. }
  24338. this._clearcoat = value;
  24339. }
  24340. get iridescence() {
  24341. return this._iridescence;
  24342. }
  24343. set iridescence( value ) {
  24344. if ( this._iridescence > 0 !== value > 0 ) {
  24345. this.version ++;
  24346. }
  24347. this._iridescence = value;
  24348. }
  24349. get sheen() {
  24350. return this._sheen;
  24351. }
  24352. set sheen( value ) {
  24353. if ( this._sheen > 0 !== value > 0 ) {
  24354. this.version ++;
  24355. }
  24356. this._sheen = value;
  24357. }
  24358. get transmission() {
  24359. return this._transmission;
  24360. }
  24361. set transmission( value ) {
  24362. if ( this._transmission > 0 !== value > 0 ) {
  24363. this.version ++;
  24364. }
  24365. this._transmission = value;
  24366. }
  24367. copy( source ) {
  24368. super.copy( source );
  24369. this.defines = {
  24370. 'STANDARD': '',
  24371. 'PHYSICAL': ''
  24372. };
  24373. this.anisotropy = source.anisotropy;
  24374. this.anisotropyRotation = source.anisotropyRotation;
  24375. this.anisotropyMap = source.anisotropyMap;
  24376. this.clearcoat = source.clearcoat;
  24377. this.clearcoatMap = source.clearcoatMap;
  24378. this.clearcoatRoughness = source.clearcoatRoughness;
  24379. this.clearcoatRoughnessMap = source.clearcoatRoughnessMap;
  24380. this.clearcoatNormalMap = source.clearcoatNormalMap;
  24381. this.clearcoatNormalScale.copy( source.clearcoatNormalScale );
  24382. this.ior = source.ior;
  24383. this.iridescence = source.iridescence;
  24384. this.iridescenceMap = source.iridescenceMap;
  24385. this.iridescenceIOR = source.iridescenceIOR;
  24386. this.iridescenceThicknessRange = [ ...source.iridescenceThicknessRange ];
  24387. this.iridescenceThicknessMap = source.iridescenceThicknessMap;
  24388. this.sheen = source.sheen;
  24389. this.sheenColor.copy( source.sheenColor );
  24390. this.sheenColorMap = source.sheenColorMap;
  24391. this.sheenRoughness = source.sheenRoughness;
  24392. this.sheenRoughnessMap = source.sheenRoughnessMap;
  24393. this.transmission = source.transmission;
  24394. this.transmissionMap = source.transmissionMap;
  24395. this.thickness = source.thickness;
  24396. this.thicknessMap = source.thicknessMap;
  24397. this.attenuationDistance = source.attenuationDistance;
  24398. this.attenuationColor.copy( source.attenuationColor );
  24399. this.specularIntensity = source.specularIntensity;
  24400. this.specularIntensityMap = source.specularIntensityMap;
  24401. this.specularColor.copy( source.specularColor );
  24402. this.specularColorMap = source.specularColorMap;
  24403. return this;
  24404. }
  24405. }
  24406. class MeshPhongMaterial extends Material {
  24407. constructor( parameters ) {
  24408. super();
  24409. this.isMeshPhongMaterial = true;
  24410. this.type = 'MeshPhongMaterial';
  24411. this.color = new Color( 0xffffff ); // diffuse
  24412. this.specular = new Color( 0x111111 );
  24413. this.shininess = 30;
  24414. this.map = null;
  24415. this.lightMap = null;
  24416. this.lightMapIntensity = 1.0;
  24417. this.aoMap = null;
  24418. this.aoMapIntensity = 1.0;
  24419. this.emissive = new Color( 0x000000 );
  24420. this.emissiveIntensity = 1.0;
  24421. this.emissiveMap = null;
  24422. this.bumpMap = null;
  24423. this.bumpScale = 1;
  24424. this.normalMap = null;
  24425. this.normalMapType = TangentSpaceNormalMap;
  24426. this.normalScale = new Vector2( 1, 1 );
  24427. this.displacementMap = null;
  24428. this.displacementScale = 1;
  24429. this.displacementBias = 0;
  24430. this.specularMap = null;
  24431. this.alphaMap = null;
  24432. this.envMap = null;
  24433. this.combine = MultiplyOperation;
  24434. this.reflectivity = 1;
  24435. this.refractionRatio = 0.98;
  24436. this.wireframe = false;
  24437. this.wireframeLinewidth = 1;
  24438. this.wireframeLinecap = 'round';
  24439. this.wireframeLinejoin = 'round';
  24440. this.flatShading = false;
  24441. this.fog = true;
  24442. this.setValues( parameters );
  24443. }
  24444. copy( source ) {
  24445. super.copy( source );
  24446. this.color.copy( source.color );
  24447. this.specular.copy( source.specular );
  24448. this.shininess = source.shininess;
  24449. this.map = source.map;
  24450. this.lightMap = source.lightMap;
  24451. this.lightMapIntensity = source.lightMapIntensity;
  24452. this.aoMap = source.aoMap;
  24453. this.aoMapIntensity = source.aoMapIntensity;
  24454. this.emissive.copy( source.emissive );
  24455. this.emissiveMap = source.emissiveMap;
  24456. this.emissiveIntensity = source.emissiveIntensity;
  24457. this.bumpMap = source.bumpMap;
  24458. this.bumpScale = source.bumpScale;
  24459. this.normalMap = source.normalMap;
  24460. this.normalMapType = source.normalMapType;
  24461. this.normalScale.copy( source.normalScale );
  24462. this.displacementMap = source.displacementMap;
  24463. this.displacementScale = source.displacementScale;
  24464. this.displacementBias = source.displacementBias;
  24465. this.specularMap = source.specularMap;
  24466. this.alphaMap = source.alphaMap;
  24467. this.envMap = source.envMap;
  24468. this.combine = source.combine;
  24469. this.reflectivity = source.reflectivity;
  24470. this.refractionRatio = source.refractionRatio;
  24471. this.wireframe = source.wireframe;
  24472. this.wireframeLinewidth = source.wireframeLinewidth;
  24473. this.wireframeLinecap = source.wireframeLinecap;
  24474. this.wireframeLinejoin = source.wireframeLinejoin;
  24475. this.flatShading = source.flatShading;
  24476. this.fog = source.fog;
  24477. return this;
  24478. }
  24479. }
  24480. class MeshToonMaterial extends Material {
  24481. constructor( parameters ) {
  24482. super();
  24483. this.isMeshToonMaterial = true;
  24484. this.defines = { 'TOON': '' };
  24485. this.type = 'MeshToonMaterial';
  24486. this.color = new Color( 0xffffff );
  24487. this.map = null;
  24488. this.gradientMap = null;
  24489. this.lightMap = null;
  24490. this.lightMapIntensity = 1.0;
  24491. this.aoMap = null;
  24492. this.aoMapIntensity = 1.0;
  24493. this.emissive = new Color( 0x000000 );
  24494. this.emissiveIntensity = 1.0;
  24495. this.emissiveMap = null;
  24496. this.bumpMap = null;
  24497. this.bumpScale = 1;
  24498. this.normalMap = null;
  24499. this.normalMapType = TangentSpaceNormalMap;
  24500. this.normalScale = new Vector2( 1, 1 );
  24501. this.displacementMap = null;
  24502. this.displacementScale = 1;
  24503. this.displacementBias = 0;
  24504. this.alphaMap = null;
  24505. this.wireframe = false;
  24506. this.wireframeLinewidth = 1;
  24507. this.wireframeLinecap = 'round';
  24508. this.wireframeLinejoin = 'round';
  24509. this.fog = true;
  24510. this.setValues( parameters );
  24511. }
  24512. copy( source ) {
  24513. super.copy( source );
  24514. this.color.copy( source.color );
  24515. this.map = source.map;
  24516. this.gradientMap = source.gradientMap;
  24517. this.lightMap = source.lightMap;
  24518. this.lightMapIntensity = source.lightMapIntensity;
  24519. this.aoMap = source.aoMap;
  24520. this.aoMapIntensity = source.aoMapIntensity;
  24521. this.emissive.copy( source.emissive );
  24522. this.emissiveMap = source.emissiveMap;
  24523. this.emissiveIntensity = source.emissiveIntensity;
  24524. this.bumpMap = source.bumpMap;
  24525. this.bumpScale = source.bumpScale;
  24526. this.normalMap = source.normalMap;
  24527. this.normalMapType = source.normalMapType;
  24528. this.normalScale.copy( source.normalScale );
  24529. this.displacementMap = source.displacementMap;
  24530. this.displacementScale = source.displacementScale;
  24531. this.displacementBias = source.displacementBias;
  24532. this.alphaMap = source.alphaMap;
  24533. this.wireframe = source.wireframe;
  24534. this.wireframeLinewidth = source.wireframeLinewidth;
  24535. this.wireframeLinecap = source.wireframeLinecap;
  24536. this.wireframeLinejoin = source.wireframeLinejoin;
  24537. this.fog = source.fog;
  24538. return this;
  24539. }
  24540. }
  24541. class MeshNormalMaterial extends Material {
  24542. constructor( parameters ) {
  24543. super();
  24544. this.isMeshNormalMaterial = true;
  24545. this.type = 'MeshNormalMaterial';
  24546. this.bumpMap = null;
  24547. this.bumpScale = 1;
  24548. this.normalMap = null;
  24549. this.normalMapType = TangentSpaceNormalMap;
  24550. this.normalScale = new Vector2( 1, 1 );
  24551. this.displacementMap = null;
  24552. this.displacementScale = 1;
  24553. this.displacementBias = 0;
  24554. this.wireframe = false;
  24555. this.wireframeLinewidth = 1;
  24556. this.flatShading = false;
  24557. this.setValues( parameters );
  24558. }
  24559. copy( source ) {
  24560. super.copy( source );
  24561. this.bumpMap = source.bumpMap;
  24562. this.bumpScale = source.bumpScale;
  24563. this.normalMap = source.normalMap;
  24564. this.normalMapType = source.normalMapType;
  24565. this.normalScale.copy( source.normalScale );
  24566. this.displacementMap = source.displacementMap;
  24567. this.displacementScale = source.displacementScale;
  24568. this.displacementBias = source.displacementBias;
  24569. this.wireframe = source.wireframe;
  24570. this.wireframeLinewidth = source.wireframeLinewidth;
  24571. this.flatShading = source.flatShading;
  24572. return this;
  24573. }
  24574. }
  24575. class MeshLambertMaterial extends Material {
  24576. constructor( parameters ) {
  24577. super();
  24578. this.isMeshLambertMaterial = true;
  24579. this.type = 'MeshLambertMaterial';
  24580. this.color = new Color( 0xffffff ); // diffuse
  24581. this.map = null;
  24582. this.lightMap = null;
  24583. this.lightMapIntensity = 1.0;
  24584. this.aoMap = null;
  24585. this.aoMapIntensity = 1.0;
  24586. this.emissive = new Color( 0x000000 );
  24587. this.emissiveIntensity = 1.0;
  24588. this.emissiveMap = null;
  24589. this.bumpMap = null;
  24590. this.bumpScale = 1;
  24591. this.normalMap = null;
  24592. this.normalMapType = TangentSpaceNormalMap;
  24593. this.normalScale = new Vector2( 1, 1 );
  24594. this.displacementMap = null;
  24595. this.displacementScale = 1;
  24596. this.displacementBias = 0;
  24597. this.specularMap = null;
  24598. this.alphaMap = null;
  24599. this.envMap = null;
  24600. this.combine = MultiplyOperation;
  24601. this.reflectivity = 1;
  24602. this.refractionRatio = 0.98;
  24603. this.wireframe = false;
  24604. this.wireframeLinewidth = 1;
  24605. this.wireframeLinecap = 'round';
  24606. this.wireframeLinejoin = 'round';
  24607. this.flatShading = false;
  24608. this.fog = true;
  24609. this.setValues( parameters );
  24610. }
  24611. copy( source ) {
  24612. super.copy( source );
  24613. this.color.copy( source.color );
  24614. this.map = source.map;
  24615. this.lightMap = source.lightMap;
  24616. this.lightMapIntensity = source.lightMapIntensity;
  24617. this.aoMap = source.aoMap;
  24618. this.aoMapIntensity = source.aoMapIntensity;
  24619. this.emissive.copy( source.emissive );
  24620. this.emissiveMap = source.emissiveMap;
  24621. this.emissiveIntensity = source.emissiveIntensity;
  24622. this.bumpMap = source.bumpMap;
  24623. this.bumpScale = source.bumpScale;
  24624. this.normalMap = source.normalMap;
  24625. this.normalMapType = source.normalMapType;
  24626. this.normalScale.copy( source.normalScale );
  24627. this.displacementMap = source.displacementMap;
  24628. this.displacementScale = source.displacementScale;
  24629. this.displacementBias = source.displacementBias;
  24630. this.specularMap = source.specularMap;
  24631. this.alphaMap = source.alphaMap;
  24632. this.envMap = source.envMap;
  24633. this.combine = source.combine;
  24634. this.reflectivity = source.reflectivity;
  24635. this.refractionRatio = source.refractionRatio;
  24636. this.wireframe = source.wireframe;
  24637. this.wireframeLinewidth = source.wireframeLinewidth;
  24638. this.wireframeLinecap = source.wireframeLinecap;
  24639. this.wireframeLinejoin = source.wireframeLinejoin;
  24640. this.flatShading = source.flatShading;
  24641. this.fog = source.fog;
  24642. return this;
  24643. }
  24644. }
  24645. class MeshMatcapMaterial extends Material {
  24646. constructor( parameters ) {
  24647. super();
  24648. this.isMeshMatcapMaterial = true;
  24649. this.defines = { 'MATCAP': '' };
  24650. this.type = 'MeshMatcapMaterial';
  24651. this.color = new Color( 0xffffff ); // diffuse
  24652. this.matcap = null;
  24653. this.map = null;
  24654. this.bumpMap = null;
  24655. this.bumpScale = 1;
  24656. this.normalMap = null;
  24657. this.normalMapType = TangentSpaceNormalMap;
  24658. this.normalScale = new Vector2( 1, 1 );
  24659. this.displacementMap = null;
  24660. this.displacementScale = 1;
  24661. this.displacementBias = 0;
  24662. this.alphaMap = null;
  24663. this.flatShading = false;
  24664. this.fog = true;
  24665. this.setValues( parameters );
  24666. }
  24667. copy( source ) {
  24668. super.copy( source );
  24669. this.defines = { 'MATCAP': '' };
  24670. this.color.copy( source.color );
  24671. this.matcap = source.matcap;
  24672. this.map = source.map;
  24673. this.bumpMap = source.bumpMap;
  24674. this.bumpScale = source.bumpScale;
  24675. this.normalMap = source.normalMap;
  24676. this.normalMapType = source.normalMapType;
  24677. this.normalScale.copy( source.normalScale );
  24678. this.displacementMap = source.displacementMap;
  24679. this.displacementScale = source.displacementScale;
  24680. this.displacementBias = source.displacementBias;
  24681. this.alphaMap = source.alphaMap;
  24682. this.flatShading = source.flatShading;
  24683. this.fog = source.fog;
  24684. return this;
  24685. }
  24686. }
  24687. class LineDashedMaterial extends LineBasicMaterial {
  24688. constructor( parameters ) {
  24689. super();
  24690. this.isLineDashedMaterial = true;
  24691. this.type = 'LineDashedMaterial';
  24692. this.scale = 1;
  24693. this.dashSize = 3;
  24694. this.gapSize = 1;
  24695. this.setValues( parameters );
  24696. }
  24697. copy( source ) {
  24698. super.copy( source );
  24699. this.scale = source.scale;
  24700. this.dashSize = source.dashSize;
  24701. this.gapSize = source.gapSize;
  24702. return this;
  24703. }
  24704. }
  24705. // converts an array to a specific type
  24706. function convertArray( array, type, forceClone ) {
  24707. if ( ! array || // let 'undefined' and 'null' pass
  24708. ! forceClone && array.constructor === type ) return array;
  24709. if ( typeof type.BYTES_PER_ELEMENT === 'number' ) {
  24710. return new type( array ); // create typed array
  24711. }
  24712. return Array.prototype.slice.call( array ); // create Array
  24713. }
  24714. function isTypedArray( object ) {
  24715. return ArrayBuffer.isView( object ) &&
  24716. ! ( object instanceof DataView );
  24717. }
  24718. // returns an array by which times and values can be sorted
  24719. function getKeyframeOrder( times ) {
  24720. function compareTime( i, j ) {
  24721. return times[ i ] - times[ j ];
  24722. }
  24723. const n = times.length;
  24724. const result = new Array( n );
  24725. for ( let i = 0; i !== n; ++ i ) result[ i ] = i;
  24726. result.sort( compareTime );
  24727. return result;
  24728. }
  24729. // uses the array previously returned by 'getKeyframeOrder' to sort data
  24730. function sortedArray( values, stride, order ) {
  24731. const nValues = values.length;
  24732. const result = new values.constructor( nValues );
  24733. for ( let i = 0, dstOffset = 0; dstOffset !== nValues; ++ i ) {
  24734. const srcOffset = order[ i ] * stride;
  24735. for ( let j = 0; j !== stride; ++ j ) {
  24736. result[ dstOffset ++ ] = values[ srcOffset + j ];
  24737. }
  24738. }
  24739. return result;
  24740. }
  24741. // function for parsing AOS keyframe formats
  24742. function flattenJSON( jsonKeys, times, values, valuePropertyName ) {
  24743. let i = 1, key = jsonKeys[ 0 ];
  24744. while ( key !== undefined && key[ valuePropertyName ] === undefined ) {
  24745. key = jsonKeys[ i ++ ];
  24746. }
  24747. if ( key === undefined ) return; // no data
  24748. let value = key[ valuePropertyName ];
  24749. if ( value === undefined ) return; // no data
  24750. if ( Array.isArray( value ) ) {
  24751. do {
  24752. value = key[ valuePropertyName ];
  24753. if ( value !== undefined ) {
  24754. times.push( key.time );
  24755. values.push.apply( values, value ); // push all elements
  24756. }
  24757. key = jsonKeys[ i ++ ];
  24758. } while ( key !== undefined );
  24759. } else if ( value.toArray !== undefined ) {
  24760. // ...assume THREE.Math-ish
  24761. do {
  24762. value = key[ valuePropertyName ];
  24763. if ( value !== undefined ) {
  24764. times.push( key.time );
  24765. value.toArray( values, values.length );
  24766. }
  24767. key = jsonKeys[ i ++ ];
  24768. } while ( key !== undefined );
  24769. } else {
  24770. // otherwise push as-is
  24771. do {
  24772. value = key[ valuePropertyName ];
  24773. if ( value !== undefined ) {
  24774. times.push( key.time );
  24775. values.push( value );
  24776. }
  24777. key = jsonKeys[ i ++ ];
  24778. } while ( key !== undefined );
  24779. }
  24780. }
  24781. function subclip( sourceClip, name, startFrame, endFrame, fps = 30 ) {
  24782. const clip = sourceClip.clone();
  24783. clip.name = name;
  24784. const tracks = [];
  24785. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  24786. const track = clip.tracks[ i ];
  24787. const valueSize = track.getValueSize();
  24788. const times = [];
  24789. const values = [];
  24790. for ( let j = 0; j < track.times.length; ++ j ) {
  24791. const frame = track.times[ j ] * fps;
  24792. if ( frame < startFrame || frame >= endFrame ) continue;
  24793. times.push( track.times[ j ] );
  24794. for ( let k = 0; k < valueSize; ++ k ) {
  24795. values.push( track.values[ j * valueSize + k ] );
  24796. }
  24797. }
  24798. if ( times.length === 0 ) continue;
  24799. track.times = convertArray( times, track.times.constructor );
  24800. track.values = convertArray( values, track.values.constructor );
  24801. tracks.push( track );
  24802. }
  24803. clip.tracks = tracks;
  24804. // find minimum .times value across all tracks in the trimmed clip
  24805. let minStartTime = Infinity;
  24806. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  24807. if ( minStartTime > clip.tracks[ i ].times[ 0 ] ) {
  24808. minStartTime = clip.tracks[ i ].times[ 0 ];
  24809. }
  24810. }
  24811. // shift all tracks such that clip begins at t=0
  24812. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  24813. clip.tracks[ i ].shift( - 1 * minStartTime );
  24814. }
  24815. clip.resetDuration();
  24816. return clip;
  24817. }
  24818. function makeClipAdditive( targetClip, referenceFrame = 0, referenceClip = targetClip, fps = 30 ) {
  24819. if ( fps <= 0 ) fps = 30;
  24820. const numTracks = referenceClip.tracks.length;
  24821. const referenceTime = referenceFrame / fps;
  24822. // Make each track's values relative to the values at the reference frame
  24823. for ( let i = 0; i < numTracks; ++ i ) {
  24824. const referenceTrack = referenceClip.tracks[ i ];
  24825. const referenceTrackType = referenceTrack.ValueTypeName;
  24826. // Skip this track if it's non-numeric
  24827. if ( referenceTrackType === 'bool' || referenceTrackType === 'string' ) continue;
  24828. // Find the track in the target clip whose name and type matches the reference track
  24829. const targetTrack = targetClip.tracks.find( function ( track ) {
  24830. return track.name === referenceTrack.name
  24831. && track.ValueTypeName === referenceTrackType;
  24832. } );
  24833. if ( targetTrack === undefined ) continue;
  24834. let referenceOffset = 0;
  24835. const referenceValueSize = referenceTrack.getValueSize();
  24836. if ( referenceTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  24837. referenceOffset = referenceValueSize / 3;
  24838. }
  24839. let targetOffset = 0;
  24840. const targetValueSize = targetTrack.getValueSize();
  24841. if ( targetTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  24842. targetOffset = targetValueSize / 3;
  24843. }
  24844. const lastIndex = referenceTrack.times.length - 1;
  24845. let referenceValue;
  24846. // Find the value to subtract out of the track
  24847. if ( referenceTime <= referenceTrack.times[ 0 ] ) {
  24848. // Reference frame is earlier than the first keyframe, so just use the first keyframe
  24849. const startIndex = referenceOffset;
  24850. const endIndex = referenceValueSize - referenceOffset;
  24851. referenceValue = referenceTrack.values.slice( startIndex, endIndex );
  24852. } else if ( referenceTime >= referenceTrack.times[ lastIndex ] ) {
  24853. // Reference frame is after the last keyframe, so just use the last keyframe
  24854. const startIndex = lastIndex * referenceValueSize + referenceOffset;
  24855. const endIndex = startIndex + referenceValueSize - referenceOffset;
  24856. referenceValue = referenceTrack.values.slice( startIndex, endIndex );
  24857. } else {
  24858. // Interpolate to the reference value
  24859. const interpolant = referenceTrack.createInterpolant();
  24860. const startIndex = referenceOffset;
  24861. const endIndex = referenceValueSize - referenceOffset;
  24862. interpolant.evaluate( referenceTime );
  24863. referenceValue = interpolant.resultBuffer.slice( startIndex, endIndex );
  24864. }
  24865. // Conjugate the quaternion
  24866. if ( referenceTrackType === 'quaternion' ) {
  24867. const referenceQuat = new Quaternion().fromArray( referenceValue ).normalize().conjugate();
  24868. referenceQuat.toArray( referenceValue );
  24869. }
  24870. // Subtract the reference value from all of the track values
  24871. const numTimes = targetTrack.times.length;
  24872. for ( let j = 0; j < numTimes; ++ j ) {
  24873. const valueStart = j * targetValueSize + targetOffset;
  24874. if ( referenceTrackType === 'quaternion' ) {
  24875. // Multiply the conjugate for quaternion track types
  24876. Quaternion.multiplyQuaternionsFlat(
  24877. targetTrack.values,
  24878. valueStart,
  24879. referenceValue,
  24880. 0,
  24881. targetTrack.values,
  24882. valueStart
  24883. );
  24884. } else {
  24885. const valueEnd = targetValueSize - targetOffset * 2;
  24886. // Subtract each value for all other numeric track types
  24887. for ( let k = 0; k < valueEnd; ++ k ) {
  24888. targetTrack.values[ valueStart + k ] -= referenceValue[ k ];
  24889. }
  24890. }
  24891. }
  24892. }
  24893. targetClip.blendMode = AdditiveAnimationBlendMode;
  24894. return targetClip;
  24895. }
  24896. const AnimationUtils = {
  24897. convertArray: convertArray,
  24898. isTypedArray: isTypedArray,
  24899. getKeyframeOrder: getKeyframeOrder,
  24900. sortedArray: sortedArray,
  24901. flattenJSON: flattenJSON,
  24902. subclip: subclip,
  24903. makeClipAdditive: makeClipAdditive
  24904. };
  24905. /**
  24906. * Abstract base class of interpolants over parametric samples.
  24907. *
  24908. * The parameter domain is one dimensional, typically the time or a path
  24909. * along a curve defined by the data.
  24910. *
  24911. * The sample values can have any dimensionality and derived classes may
  24912. * apply special interpretations to the data.
  24913. *
  24914. * This class provides the interval seek in a Template Method, deferring
  24915. * the actual interpolation to derived classes.
  24916. *
  24917. * Time complexity is O(1) for linear access crossing at most two points
  24918. * and O(log N) for random access, where N is the number of positions.
  24919. *
  24920. * References:
  24921. *
  24922. * http://www.oodesign.com/template-method-pattern.html
  24923. *
  24924. */
  24925. class Interpolant {
  24926. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  24927. this.parameterPositions = parameterPositions;
  24928. this._cachedIndex = 0;
  24929. this.resultBuffer = resultBuffer !== undefined ?
  24930. resultBuffer : new sampleValues.constructor( sampleSize );
  24931. this.sampleValues = sampleValues;
  24932. this.valueSize = sampleSize;
  24933. this.settings = null;
  24934. this.DefaultSettings_ = {};
  24935. }
  24936. evaluate( t ) {
  24937. const pp = this.parameterPositions;
  24938. let i1 = this._cachedIndex,
  24939. t1 = pp[ i1 ],
  24940. t0 = pp[ i1 - 1 ];
  24941. validate_interval: {
  24942. seek: {
  24943. let right;
  24944. linear_scan: {
  24945. //- See http://jsperf.com/comparison-to-undefined/3
  24946. //- slower code:
  24947. //-
  24948. //- if ( t >= t1 || t1 === undefined ) {
  24949. forward_scan: if ( ! ( t < t1 ) ) {
  24950. for ( let giveUpAt = i1 + 2; ; ) {
  24951. if ( t1 === undefined ) {
  24952. if ( t < t0 ) break forward_scan;
  24953. // after end
  24954. i1 = pp.length;
  24955. this._cachedIndex = i1;
  24956. return this.copySampleValue_( i1 - 1 );
  24957. }
  24958. if ( i1 === giveUpAt ) break; // this loop
  24959. t0 = t1;
  24960. t1 = pp[ ++ i1 ];
  24961. if ( t < t1 ) {
  24962. // we have arrived at the sought interval
  24963. break seek;
  24964. }
  24965. }
  24966. // prepare binary search on the right side of the index
  24967. right = pp.length;
  24968. break linear_scan;
  24969. }
  24970. //- slower code:
  24971. //- if ( t < t0 || t0 === undefined ) {
  24972. if ( ! ( t >= t0 ) ) {
  24973. // looping?
  24974. const t1global = pp[ 1 ];
  24975. if ( t < t1global ) {
  24976. i1 = 2; // + 1, using the scan for the details
  24977. t0 = t1global;
  24978. }
  24979. // linear reverse scan
  24980. for ( let giveUpAt = i1 - 2; ; ) {
  24981. if ( t0 === undefined ) {
  24982. // before start
  24983. this._cachedIndex = 0;
  24984. return this.copySampleValue_( 0 );
  24985. }
  24986. if ( i1 === giveUpAt ) break; // this loop
  24987. t1 = t0;
  24988. t0 = pp[ -- i1 - 1 ];
  24989. if ( t >= t0 ) {
  24990. // we have arrived at the sought interval
  24991. break seek;
  24992. }
  24993. }
  24994. // prepare binary search on the left side of the index
  24995. right = i1;
  24996. i1 = 0;
  24997. break linear_scan;
  24998. }
  24999. // the interval is valid
  25000. break validate_interval;
  25001. } // linear scan
  25002. // binary search
  25003. while ( i1 < right ) {
  25004. const mid = ( i1 + right ) >>> 1;
  25005. if ( t < pp[ mid ] ) {
  25006. right = mid;
  25007. } else {
  25008. i1 = mid + 1;
  25009. }
  25010. }
  25011. t1 = pp[ i1 ];
  25012. t0 = pp[ i1 - 1 ];
  25013. // check boundary cases, again
  25014. if ( t0 === undefined ) {
  25015. this._cachedIndex = 0;
  25016. return this.copySampleValue_( 0 );
  25017. }
  25018. if ( t1 === undefined ) {
  25019. i1 = pp.length;
  25020. this._cachedIndex = i1;
  25021. return this.copySampleValue_( i1 - 1 );
  25022. }
  25023. } // seek
  25024. this._cachedIndex = i1;
  25025. this.intervalChanged_( i1, t0, t1 );
  25026. } // validate_interval
  25027. return this.interpolate_( i1, t0, t, t1 );
  25028. }
  25029. getSettings_() {
  25030. return this.settings || this.DefaultSettings_;
  25031. }
  25032. copySampleValue_( index ) {
  25033. // copies a sample value to the result buffer
  25034. const result = this.resultBuffer,
  25035. values = this.sampleValues,
  25036. stride = this.valueSize,
  25037. offset = index * stride;
  25038. for ( let i = 0; i !== stride; ++ i ) {
  25039. result[ i ] = values[ offset + i ];
  25040. }
  25041. return result;
  25042. }
  25043. // Template methods for derived classes:
  25044. interpolate_( /* i1, t0, t, t1 */ ) {
  25045. throw new Error( 'call to abstract method' );
  25046. // implementations shall return this.resultBuffer
  25047. }
  25048. intervalChanged_( /* i1, t0, t1 */ ) {
  25049. // empty
  25050. }
  25051. }
  25052. /**
  25053. * Fast and simple cubic spline interpolant.
  25054. *
  25055. * It was derived from a Hermitian construction setting the first derivative
  25056. * at each sample position to the linear slope between neighboring positions
  25057. * over their parameter interval.
  25058. */
  25059. class CubicInterpolant extends Interpolant {
  25060. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  25061. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  25062. this._weightPrev = - 0;
  25063. this._offsetPrev = - 0;
  25064. this._weightNext = - 0;
  25065. this._offsetNext = - 0;
  25066. this.DefaultSettings_ = {
  25067. endingStart: ZeroCurvatureEnding,
  25068. endingEnd: ZeroCurvatureEnding
  25069. };
  25070. }
  25071. intervalChanged_( i1, t0, t1 ) {
  25072. const pp = this.parameterPositions;
  25073. let iPrev = i1 - 2,
  25074. iNext = i1 + 1,
  25075. tPrev = pp[ iPrev ],
  25076. tNext = pp[ iNext ];
  25077. if ( tPrev === undefined ) {
  25078. switch ( this.getSettings_().endingStart ) {
  25079. case ZeroSlopeEnding:
  25080. // f'(t0) = 0
  25081. iPrev = i1;
  25082. tPrev = 2 * t0 - t1;
  25083. break;
  25084. case WrapAroundEnding:
  25085. // use the other end of the curve
  25086. iPrev = pp.length - 2;
  25087. tPrev = t0 + pp[ iPrev ] - pp[ iPrev + 1 ];
  25088. break;
  25089. default: // ZeroCurvatureEnding
  25090. // f''(t0) = 0 a.k.a. Natural Spline
  25091. iPrev = i1;
  25092. tPrev = t1;
  25093. }
  25094. }
  25095. if ( tNext === undefined ) {
  25096. switch ( this.getSettings_().endingEnd ) {
  25097. case ZeroSlopeEnding:
  25098. // f'(tN) = 0
  25099. iNext = i1;
  25100. tNext = 2 * t1 - t0;
  25101. break;
  25102. case WrapAroundEnding:
  25103. // use the other end of the curve
  25104. iNext = 1;
  25105. tNext = t1 + pp[ 1 ] - pp[ 0 ];
  25106. break;
  25107. default: // ZeroCurvatureEnding
  25108. // f''(tN) = 0, a.k.a. Natural Spline
  25109. iNext = i1 - 1;
  25110. tNext = t0;
  25111. }
  25112. }
  25113. const halfDt = ( t1 - t0 ) * 0.5,
  25114. stride = this.valueSize;
  25115. this._weightPrev = halfDt / ( t0 - tPrev );
  25116. this._weightNext = halfDt / ( tNext - t1 );
  25117. this._offsetPrev = iPrev * stride;
  25118. this._offsetNext = iNext * stride;
  25119. }
  25120. interpolate_( i1, t0, t, t1 ) {
  25121. const result = this.resultBuffer,
  25122. values = this.sampleValues,
  25123. stride = this.valueSize,
  25124. o1 = i1 * stride, o0 = o1 - stride,
  25125. oP = this._offsetPrev, oN = this._offsetNext,
  25126. wP = this._weightPrev, wN = this._weightNext,
  25127. p = ( t - t0 ) / ( t1 - t0 ),
  25128. pp = p * p,
  25129. ppp = pp * p;
  25130. // evaluate polynomials
  25131. const sP = - wP * ppp + 2 * wP * pp - wP * p;
  25132. const s0 = ( 1 + wP ) * ppp + ( - 1.5 - 2 * wP ) * pp + ( - 0.5 + wP ) * p + 1;
  25133. const s1 = ( - 1 - wN ) * ppp + ( 1.5 + wN ) * pp + 0.5 * p;
  25134. const sN = wN * ppp - wN * pp;
  25135. // combine data linearly
  25136. for ( let i = 0; i !== stride; ++ i ) {
  25137. result[ i ] =
  25138. sP * values[ oP + i ] +
  25139. s0 * values[ o0 + i ] +
  25140. s1 * values[ o1 + i ] +
  25141. sN * values[ oN + i ];
  25142. }
  25143. return result;
  25144. }
  25145. }
  25146. class LinearInterpolant extends Interpolant {
  25147. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  25148. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  25149. }
  25150. interpolate_( i1, t0, t, t1 ) {
  25151. const result = this.resultBuffer,
  25152. values = this.sampleValues,
  25153. stride = this.valueSize,
  25154. offset1 = i1 * stride,
  25155. offset0 = offset1 - stride,
  25156. weight1 = ( t - t0 ) / ( t1 - t0 ),
  25157. weight0 = 1 - weight1;
  25158. for ( let i = 0; i !== stride; ++ i ) {
  25159. result[ i ] =
  25160. values[ offset0 + i ] * weight0 +
  25161. values[ offset1 + i ] * weight1;
  25162. }
  25163. return result;
  25164. }
  25165. }
  25166. /**
  25167. *
  25168. * Interpolant that evaluates to the sample value at the position preceding
  25169. * the parameter.
  25170. */
  25171. class DiscreteInterpolant extends Interpolant {
  25172. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  25173. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  25174. }
  25175. interpolate_( i1 /*, t0, t, t1 */ ) {
  25176. return this.copySampleValue_( i1 - 1 );
  25177. }
  25178. }
  25179. class KeyframeTrack {
  25180. constructor( name, times, values, interpolation ) {
  25181. if ( name === undefined ) throw new Error( 'THREE.KeyframeTrack: track name is undefined' );
  25182. if ( times === undefined || times.length === 0 ) throw new Error( 'THREE.KeyframeTrack: no keyframes in track named ' + name );
  25183. this.name = name;
  25184. this.times = convertArray( times, this.TimeBufferType );
  25185. this.values = convertArray( values, this.ValueBufferType );
  25186. this.setInterpolation( interpolation || this.DefaultInterpolation );
  25187. }
  25188. // Serialization (in static context, because of constructor invocation
  25189. // and automatic invocation of .toJSON):
  25190. static toJSON( track ) {
  25191. const trackType = track.constructor;
  25192. let json;
  25193. // derived classes can define a static toJSON method
  25194. if ( trackType.toJSON !== this.toJSON ) {
  25195. json = trackType.toJSON( track );
  25196. } else {
  25197. // by default, we assume the data can be serialized as-is
  25198. json = {
  25199. 'name': track.name,
  25200. 'times': convertArray( track.times, Array ),
  25201. 'values': convertArray( track.values, Array )
  25202. };
  25203. const interpolation = track.getInterpolation();
  25204. if ( interpolation !== track.DefaultInterpolation ) {
  25205. json.interpolation = interpolation;
  25206. }
  25207. }
  25208. json.type = track.ValueTypeName; // mandatory
  25209. return json;
  25210. }
  25211. InterpolantFactoryMethodDiscrete( result ) {
  25212. return new DiscreteInterpolant( this.times, this.values, this.getValueSize(), result );
  25213. }
  25214. InterpolantFactoryMethodLinear( result ) {
  25215. return new LinearInterpolant( this.times, this.values, this.getValueSize(), result );
  25216. }
  25217. InterpolantFactoryMethodSmooth( result ) {
  25218. return new CubicInterpolant( this.times, this.values, this.getValueSize(), result );
  25219. }
  25220. setInterpolation( interpolation ) {
  25221. let factoryMethod;
  25222. switch ( interpolation ) {
  25223. case InterpolateDiscrete:
  25224. factoryMethod = this.InterpolantFactoryMethodDiscrete;
  25225. break;
  25226. case InterpolateLinear:
  25227. factoryMethod = this.InterpolantFactoryMethodLinear;
  25228. break;
  25229. case InterpolateSmooth:
  25230. factoryMethod = this.InterpolantFactoryMethodSmooth;
  25231. break;
  25232. }
  25233. if ( factoryMethod === undefined ) {
  25234. const message = 'unsupported interpolation for ' +
  25235. this.ValueTypeName + ' keyframe track named ' + this.name;
  25236. if ( this.createInterpolant === undefined ) {
  25237. // fall back to default, unless the default itself is messed up
  25238. if ( interpolation !== this.DefaultInterpolation ) {
  25239. this.setInterpolation( this.DefaultInterpolation );
  25240. } else {
  25241. throw new Error( message ); // fatal, in this case
  25242. }
  25243. }
  25244. console.warn( 'THREE.KeyframeTrack:', message );
  25245. return this;
  25246. }
  25247. this.createInterpolant = factoryMethod;
  25248. return this;
  25249. }
  25250. getInterpolation() {
  25251. switch ( this.createInterpolant ) {
  25252. case this.InterpolantFactoryMethodDiscrete:
  25253. return InterpolateDiscrete;
  25254. case this.InterpolantFactoryMethodLinear:
  25255. return InterpolateLinear;
  25256. case this.InterpolantFactoryMethodSmooth:
  25257. return InterpolateSmooth;
  25258. }
  25259. }
  25260. getValueSize() {
  25261. return this.values.length / this.times.length;
  25262. }
  25263. // move all keyframes either forwards or backwards in time
  25264. shift( timeOffset ) {
  25265. if ( timeOffset !== 0.0 ) {
  25266. const times = this.times;
  25267. for ( let i = 0, n = times.length; i !== n; ++ i ) {
  25268. times[ i ] += timeOffset;
  25269. }
  25270. }
  25271. return this;
  25272. }
  25273. // scale all keyframe times by a factor (useful for frame <-> seconds conversions)
  25274. scale( timeScale ) {
  25275. if ( timeScale !== 1.0 ) {
  25276. const times = this.times;
  25277. for ( let i = 0, n = times.length; i !== n; ++ i ) {
  25278. times[ i ] *= timeScale;
  25279. }
  25280. }
  25281. return this;
  25282. }
  25283. // removes keyframes before and after animation without changing any values within the range [startTime, endTime].
  25284. // IMPORTANT: We do not shift around keys to the start of the track time, because for interpolated keys this will change their values
  25285. trim( startTime, endTime ) {
  25286. const times = this.times,
  25287. nKeys = times.length;
  25288. let from = 0,
  25289. to = nKeys - 1;
  25290. while ( from !== nKeys && times[ from ] < startTime ) {
  25291. ++ from;
  25292. }
  25293. while ( to !== - 1 && times[ to ] > endTime ) {
  25294. -- to;
  25295. }
  25296. ++ to; // inclusive -> exclusive bound
  25297. if ( from !== 0 || to !== nKeys ) {
  25298. // empty tracks are forbidden, so keep at least one keyframe
  25299. if ( from >= to ) {
  25300. to = Math.max( to, 1 );
  25301. from = to - 1;
  25302. }
  25303. const stride = this.getValueSize();
  25304. this.times = times.slice( from, to );
  25305. this.values = this.values.slice( from * stride, to * stride );
  25306. }
  25307. return this;
  25308. }
  25309. // ensure we do not get a GarbageInGarbageOut situation, make sure tracks are at least minimally viable
  25310. validate() {
  25311. let valid = true;
  25312. const valueSize = this.getValueSize();
  25313. if ( valueSize - Math.floor( valueSize ) !== 0 ) {
  25314. console.error( 'THREE.KeyframeTrack: Invalid value size in track.', this );
  25315. valid = false;
  25316. }
  25317. const times = this.times,
  25318. values = this.values,
  25319. nKeys = times.length;
  25320. if ( nKeys === 0 ) {
  25321. console.error( 'THREE.KeyframeTrack: Track is empty.', this );
  25322. valid = false;
  25323. }
  25324. let prevTime = null;
  25325. for ( let i = 0; i !== nKeys; i ++ ) {
  25326. const currTime = times[ i ];
  25327. if ( typeof currTime === 'number' && isNaN( currTime ) ) {
  25328. console.error( 'THREE.KeyframeTrack: Time is not a valid number.', this, i, currTime );
  25329. valid = false;
  25330. break;
  25331. }
  25332. if ( prevTime !== null && prevTime > currTime ) {
  25333. console.error( 'THREE.KeyframeTrack: Out of order keys.', this, i, currTime, prevTime );
  25334. valid = false;
  25335. break;
  25336. }
  25337. prevTime = currTime;
  25338. }
  25339. if ( values !== undefined ) {
  25340. if ( isTypedArray( values ) ) {
  25341. for ( let i = 0, n = values.length; i !== n; ++ i ) {
  25342. const value = values[ i ];
  25343. if ( isNaN( value ) ) {
  25344. console.error( 'THREE.KeyframeTrack: Value is not a valid number.', this, i, value );
  25345. valid = false;
  25346. break;
  25347. }
  25348. }
  25349. }
  25350. }
  25351. return valid;
  25352. }
  25353. // removes equivalent sequential keys as common in morph target sequences
  25354. // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0)
  25355. optimize() {
  25356. // times or values may be shared with other tracks, so overwriting is unsafe
  25357. const times = this.times.slice(),
  25358. values = this.values.slice(),
  25359. stride = this.getValueSize(),
  25360. smoothInterpolation = this.getInterpolation() === InterpolateSmooth,
  25361. lastIndex = times.length - 1;
  25362. let writeIndex = 1;
  25363. for ( let i = 1; i < lastIndex; ++ i ) {
  25364. let keep = false;
  25365. const time = times[ i ];
  25366. const timeNext = times[ i + 1 ];
  25367. // remove adjacent keyframes scheduled at the same time
  25368. if ( time !== timeNext && ( i !== 1 || time !== times[ 0 ] ) ) {
  25369. if ( ! smoothInterpolation ) {
  25370. // remove unnecessary keyframes same as their neighbors
  25371. const offset = i * stride,
  25372. offsetP = offset - stride,
  25373. offsetN = offset + stride;
  25374. for ( let j = 0; j !== stride; ++ j ) {
  25375. const value = values[ offset + j ];
  25376. if ( value !== values[ offsetP + j ] ||
  25377. value !== values[ offsetN + j ] ) {
  25378. keep = true;
  25379. break;
  25380. }
  25381. }
  25382. } else {
  25383. keep = true;
  25384. }
  25385. }
  25386. // in-place compaction
  25387. if ( keep ) {
  25388. if ( i !== writeIndex ) {
  25389. times[ writeIndex ] = times[ i ];
  25390. const readOffset = i * stride,
  25391. writeOffset = writeIndex * stride;
  25392. for ( let j = 0; j !== stride; ++ j ) {
  25393. values[ writeOffset + j ] = values[ readOffset + j ];
  25394. }
  25395. }
  25396. ++ writeIndex;
  25397. }
  25398. }
  25399. // flush last keyframe (compaction looks ahead)
  25400. if ( lastIndex > 0 ) {
  25401. times[ writeIndex ] = times[ lastIndex ];
  25402. for ( let readOffset = lastIndex * stride, writeOffset = writeIndex * stride, j = 0; j !== stride; ++ j ) {
  25403. values[ writeOffset + j ] = values[ readOffset + j ];
  25404. }
  25405. ++ writeIndex;
  25406. }
  25407. if ( writeIndex !== times.length ) {
  25408. this.times = times.slice( 0, writeIndex );
  25409. this.values = values.slice( 0, writeIndex * stride );
  25410. } else {
  25411. this.times = times;
  25412. this.values = values;
  25413. }
  25414. return this;
  25415. }
  25416. clone() {
  25417. const times = this.times.slice();
  25418. const values = this.values.slice();
  25419. const TypedKeyframeTrack = this.constructor;
  25420. const track = new TypedKeyframeTrack( this.name, times, values );
  25421. // Interpolant argument to constructor is not saved, so copy the factory method directly.
  25422. track.createInterpolant = this.createInterpolant;
  25423. return track;
  25424. }
  25425. }
  25426. KeyframeTrack.prototype.TimeBufferType = Float32Array;
  25427. KeyframeTrack.prototype.ValueBufferType = Float32Array;
  25428. KeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear;
  25429. /**
  25430. * A Track of Boolean keyframe values.
  25431. */
  25432. class BooleanKeyframeTrack extends KeyframeTrack {}
  25433. BooleanKeyframeTrack.prototype.ValueTypeName = 'bool';
  25434. BooleanKeyframeTrack.prototype.ValueBufferType = Array;
  25435. BooleanKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  25436. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  25437. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  25438. /**
  25439. * A Track of keyframe values that represent color.
  25440. */
  25441. class ColorKeyframeTrack extends KeyframeTrack {}
  25442. ColorKeyframeTrack.prototype.ValueTypeName = 'color';
  25443. /**
  25444. * A Track of numeric keyframe values.
  25445. */
  25446. class NumberKeyframeTrack extends KeyframeTrack {}
  25447. NumberKeyframeTrack.prototype.ValueTypeName = 'number';
  25448. /**
  25449. * Spherical linear unit quaternion interpolant.
  25450. */
  25451. class QuaternionLinearInterpolant extends Interpolant {
  25452. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  25453. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  25454. }
  25455. interpolate_( i1, t0, t, t1 ) {
  25456. const result = this.resultBuffer,
  25457. values = this.sampleValues,
  25458. stride = this.valueSize,
  25459. alpha = ( t - t0 ) / ( t1 - t0 );
  25460. let offset = i1 * stride;
  25461. for ( let end = offset + stride; offset !== end; offset += 4 ) {
  25462. Quaternion.slerpFlat( result, 0, values, offset - stride, values, offset, alpha );
  25463. }
  25464. return result;
  25465. }
  25466. }
  25467. /**
  25468. * A Track of quaternion keyframe values.
  25469. */
  25470. class QuaternionKeyframeTrack extends KeyframeTrack {
  25471. InterpolantFactoryMethodLinear( result ) {
  25472. return new QuaternionLinearInterpolant( this.times, this.values, this.getValueSize(), result );
  25473. }
  25474. }
  25475. QuaternionKeyframeTrack.prototype.ValueTypeName = 'quaternion';
  25476. // ValueBufferType is inherited
  25477. QuaternionKeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear;
  25478. QuaternionKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  25479. /**
  25480. * A Track that interpolates Strings
  25481. */
  25482. class StringKeyframeTrack extends KeyframeTrack {}
  25483. StringKeyframeTrack.prototype.ValueTypeName = 'string';
  25484. StringKeyframeTrack.prototype.ValueBufferType = Array;
  25485. StringKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  25486. StringKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  25487. StringKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  25488. /**
  25489. * A Track of vectored keyframe values.
  25490. */
  25491. class VectorKeyframeTrack extends KeyframeTrack {}
  25492. VectorKeyframeTrack.prototype.ValueTypeName = 'vector';
  25493. class AnimationClip {
  25494. constructor( name, duration = - 1, tracks, blendMode = NormalAnimationBlendMode ) {
  25495. this.name = name;
  25496. this.tracks = tracks;
  25497. this.duration = duration;
  25498. this.blendMode = blendMode;
  25499. this.uuid = generateUUID();
  25500. // this means it should figure out its duration by scanning the tracks
  25501. if ( this.duration < 0 ) {
  25502. this.resetDuration();
  25503. }
  25504. }
  25505. static parse( json ) {
  25506. const tracks = [],
  25507. jsonTracks = json.tracks,
  25508. frameTime = 1.0 / ( json.fps || 1.0 );
  25509. for ( let i = 0, n = jsonTracks.length; i !== n; ++ i ) {
  25510. tracks.push( parseKeyframeTrack( jsonTracks[ i ] ).scale( frameTime ) );
  25511. }
  25512. const clip = new this( json.name, json.duration, tracks, json.blendMode );
  25513. clip.uuid = json.uuid;
  25514. return clip;
  25515. }
  25516. static toJSON( clip ) {
  25517. const tracks = [],
  25518. clipTracks = clip.tracks;
  25519. const json = {
  25520. 'name': clip.name,
  25521. 'duration': clip.duration,
  25522. 'tracks': tracks,
  25523. 'uuid': clip.uuid,
  25524. 'blendMode': clip.blendMode
  25525. };
  25526. for ( let i = 0, n = clipTracks.length; i !== n; ++ i ) {
  25527. tracks.push( KeyframeTrack.toJSON( clipTracks[ i ] ) );
  25528. }
  25529. return json;
  25530. }
  25531. static CreateFromMorphTargetSequence( name, morphTargetSequence, fps, noLoop ) {
  25532. const numMorphTargets = morphTargetSequence.length;
  25533. const tracks = [];
  25534. for ( let i = 0; i < numMorphTargets; i ++ ) {
  25535. let times = [];
  25536. let values = [];
  25537. times.push(
  25538. ( i + numMorphTargets - 1 ) % numMorphTargets,
  25539. i,
  25540. ( i + 1 ) % numMorphTargets );
  25541. values.push( 0, 1, 0 );
  25542. const order = getKeyframeOrder( times );
  25543. times = sortedArray( times, 1, order );
  25544. values = sortedArray( values, 1, order );
  25545. // if there is a key at the first frame, duplicate it as the
  25546. // last frame as well for perfect loop.
  25547. if ( ! noLoop && times[ 0 ] === 0 ) {
  25548. times.push( numMorphTargets );
  25549. values.push( values[ 0 ] );
  25550. }
  25551. tracks.push(
  25552. new NumberKeyframeTrack(
  25553. '.morphTargetInfluences[' + morphTargetSequence[ i ].name + ']',
  25554. times, values
  25555. ).scale( 1.0 / fps ) );
  25556. }
  25557. return new this( name, - 1, tracks );
  25558. }
  25559. static findByName( objectOrClipArray, name ) {
  25560. let clipArray = objectOrClipArray;
  25561. if ( ! Array.isArray( objectOrClipArray ) ) {
  25562. const o = objectOrClipArray;
  25563. clipArray = o.geometry && o.geometry.animations || o.animations;
  25564. }
  25565. for ( let i = 0; i < clipArray.length; i ++ ) {
  25566. if ( clipArray[ i ].name === name ) {
  25567. return clipArray[ i ];
  25568. }
  25569. }
  25570. return null;
  25571. }
  25572. static CreateClipsFromMorphTargetSequences( morphTargets, fps, noLoop ) {
  25573. const animationToMorphTargets = {};
  25574. // tested with https://regex101.com/ on trick sequences
  25575. // such flamingo_flyA_003, flamingo_run1_003, crdeath0059
  25576. const pattern = /^([\w-]*?)([\d]+)$/;
  25577. // sort morph target names into animation groups based
  25578. // patterns like Walk_001, Walk_002, Run_001, Run_002
  25579. for ( let i = 0, il = morphTargets.length; i < il; i ++ ) {
  25580. const morphTarget = morphTargets[ i ];
  25581. const parts = morphTarget.name.match( pattern );
  25582. if ( parts && parts.length > 1 ) {
  25583. const name = parts[ 1 ];
  25584. let animationMorphTargets = animationToMorphTargets[ name ];
  25585. if ( ! animationMorphTargets ) {
  25586. animationToMorphTargets[ name ] = animationMorphTargets = [];
  25587. }
  25588. animationMorphTargets.push( morphTarget );
  25589. }
  25590. }
  25591. const clips = [];
  25592. for ( const name in animationToMorphTargets ) {
  25593. clips.push( this.CreateFromMorphTargetSequence( name, animationToMorphTargets[ name ], fps, noLoop ) );
  25594. }
  25595. return clips;
  25596. }
  25597. // parse the animation.hierarchy format
  25598. static parseAnimation( animation, bones ) {
  25599. if ( ! animation ) {
  25600. console.error( 'THREE.AnimationClip: No animation in JSONLoader data.' );
  25601. return null;
  25602. }
  25603. const addNonemptyTrack = function ( trackType, trackName, animationKeys, propertyName, destTracks ) {
  25604. // only return track if there are actually keys.
  25605. if ( animationKeys.length !== 0 ) {
  25606. const times = [];
  25607. const values = [];
  25608. flattenJSON( animationKeys, times, values, propertyName );
  25609. // empty keys are filtered out, so check again
  25610. if ( times.length !== 0 ) {
  25611. destTracks.push( new trackType( trackName, times, values ) );
  25612. }
  25613. }
  25614. };
  25615. const tracks = [];
  25616. const clipName = animation.name || 'default';
  25617. const fps = animation.fps || 30;
  25618. const blendMode = animation.blendMode;
  25619. // automatic length determination in AnimationClip.
  25620. let duration = animation.length || - 1;
  25621. const hierarchyTracks = animation.hierarchy || [];
  25622. for ( let h = 0; h < hierarchyTracks.length; h ++ ) {
  25623. const animationKeys = hierarchyTracks[ h ].keys;
  25624. // skip empty tracks
  25625. if ( ! animationKeys || animationKeys.length === 0 ) continue;
  25626. // process morph targets
  25627. if ( animationKeys[ 0 ].morphTargets ) {
  25628. // figure out all morph targets used in this track
  25629. const morphTargetNames = {};
  25630. let k;
  25631. for ( k = 0; k < animationKeys.length; k ++ ) {
  25632. if ( animationKeys[ k ].morphTargets ) {
  25633. for ( let m = 0; m < animationKeys[ k ].morphTargets.length; m ++ ) {
  25634. morphTargetNames[ animationKeys[ k ].morphTargets[ m ] ] = - 1;
  25635. }
  25636. }
  25637. }
  25638. // create a track for each morph target with all zero
  25639. // morphTargetInfluences except for the keys in which
  25640. // the morphTarget is named.
  25641. for ( const morphTargetName in morphTargetNames ) {
  25642. const times = [];
  25643. const values = [];
  25644. for ( let m = 0; m !== animationKeys[ k ].morphTargets.length; ++ m ) {
  25645. const animationKey = animationKeys[ k ];
  25646. times.push( animationKey.time );
  25647. values.push( ( animationKey.morphTarget === morphTargetName ) ? 1 : 0 );
  25648. }
  25649. tracks.push( new NumberKeyframeTrack( '.morphTargetInfluence[' + morphTargetName + ']', times, values ) );
  25650. }
  25651. duration = morphTargetNames.length * fps;
  25652. } else {
  25653. // ...assume skeletal animation
  25654. const boneName = '.bones[' + bones[ h ].name + ']';
  25655. addNonemptyTrack(
  25656. VectorKeyframeTrack, boneName + '.position',
  25657. animationKeys, 'pos', tracks );
  25658. addNonemptyTrack(
  25659. QuaternionKeyframeTrack, boneName + '.quaternion',
  25660. animationKeys, 'rot', tracks );
  25661. addNonemptyTrack(
  25662. VectorKeyframeTrack, boneName + '.scale',
  25663. animationKeys, 'scl', tracks );
  25664. }
  25665. }
  25666. if ( tracks.length === 0 ) {
  25667. return null;
  25668. }
  25669. const clip = new this( clipName, duration, tracks, blendMode );
  25670. return clip;
  25671. }
  25672. resetDuration() {
  25673. const tracks = this.tracks;
  25674. let duration = 0;
  25675. for ( let i = 0, n = tracks.length; i !== n; ++ i ) {
  25676. const track = this.tracks[ i ];
  25677. duration = Math.max( duration, track.times[ track.times.length - 1 ] );
  25678. }
  25679. this.duration = duration;
  25680. return this;
  25681. }
  25682. trim() {
  25683. for ( let i = 0; i < this.tracks.length; i ++ ) {
  25684. this.tracks[ i ].trim( 0, this.duration );
  25685. }
  25686. return this;
  25687. }
  25688. validate() {
  25689. let valid = true;
  25690. for ( let i = 0; i < this.tracks.length; i ++ ) {
  25691. valid = valid && this.tracks[ i ].validate();
  25692. }
  25693. return valid;
  25694. }
  25695. optimize() {
  25696. for ( let i = 0; i < this.tracks.length; i ++ ) {
  25697. this.tracks[ i ].optimize();
  25698. }
  25699. return this;
  25700. }
  25701. clone() {
  25702. const tracks = [];
  25703. for ( let i = 0; i < this.tracks.length; i ++ ) {
  25704. tracks.push( this.tracks[ i ].clone() );
  25705. }
  25706. return new this.constructor( this.name, this.duration, tracks, this.blendMode );
  25707. }
  25708. toJSON() {
  25709. return this.constructor.toJSON( this );
  25710. }
  25711. }
  25712. function getTrackTypeForValueTypeName( typeName ) {
  25713. switch ( typeName.toLowerCase() ) {
  25714. case 'scalar':
  25715. case 'double':
  25716. case 'float':
  25717. case 'number':
  25718. case 'integer':
  25719. return NumberKeyframeTrack;
  25720. case 'vector':
  25721. case 'vector2':
  25722. case 'vector3':
  25723. case 'vector4':
  25724. return VectorKeyframeTrack;
  25725. case 'color':
  25726. return ColorKeyframeTrack;
  25727. case 'quaternion':
  25728. return QuaternionKeyframeTrack;
  25729. case 'bool':
  25730. case 'boolean':
  25731. return BooleanKeyframeTrack;
  25732. case 'string':
  25733. return StringKeyframeTrack;
  25734. }
  25735. throw new Error( 'THREE.KeyframeTrack: Unsupported typeName: ' + typeName );
  25736. }
  25737. function parseKeyframeTrack( json ) {
  25738. if ( json.type === undefined ) {
  25739. throw new Error( 'THREE.KeyframeTrack: track type undefined, can not parse' );
  25740. }
  25741. const trackType = getTrackTypeForValueTypeName( json.type );
  25742. if ( json.times === undefined ) {
  25743. const times = [], values = [];
  25744. flattenJSON( json.keys, times, values, 'value' );
  25745. json.times = times;
  25746. json.values = values;
  25747. }
  25748. // derived classes can define a static parse method
  25749. if ( trackType.parse !== undefined ) {
  25750. return trackType.parse( json );
  25751. } else {
  25752. // by default, we assume a constructor compatible with the base
  25753. return new trackType( json.name, json.times, json.values, json.interpolation );
  25754. }
  25755. }
  25756. const Cache = {
  25757. enabled: false,
  25758. files: {},
  25759. add: function ( key, file ) {
  25760. if ( this.enabled === false ) return;
  25761. // console.log( 'THREE.Cache', 'Adding key:', key );
  25762. this.files[ key ] = file;
  25763. },
  25764. get: function ( key ) {
  25765. if ( this.enabled === false ) return;
  25766. // console.log( 'THREE.Cache', 'Checking key:', key );
  25767. return this.files[ key ];
  25768. },
  25769. remove: function ( key ) {
  25770. delete this.files[ key ];
  25771. },
  25772. clear: function () {
  25773. this.files = {};
  25774. }
  25775. };
  25776. class LoadingManager {
  25777. constructor( onLoad, onProgress, onError ) {
  25778. const scope = this;
  25779. let isLoading = false;
  25780. let itemsLoaded = 0;
  25781. let itemsTotal = 0;
  25782. let urlModifier = undefined;
  25783. const handlers = [];
  25784. // Refer to #5689 for the reason why we don't set .onStart
  25785. // in the constructor
  25786. this.onStart = undefined;
  25787. this.onLoad = onLoad;
  25788. this.onProgress = onProgress;
  25789. this.onError = onError;
  25790. this.itemStart = function ( url ) {
  25791. itemsTotal ++;
  25792. if ( isLoading === false ) {
  25793. if ( scope.onStart !== undefined ) {
  25794. scope.onStart( url, itemsLoaded, itemsTotal );
  25795. }
  25796. }
  25797. isLoading = true;
  25798. };
  25799. this.itemEnd = function ( url ) {
  25800. itemsLoaded ++;
  25801. if ( scope.onProgress !== undefined ) {
  25802. scope.onProgress( url, itemsLoaded, itemsTotal );
  25803. }
  25804. if ( itemsLoaded === itemsTotal ) {
  25805. isLoading = false;
  25806. if ( scope.onLoad !== undefined ) {
  25807. scope.onLoad();
  25808. }
  25809. }
  25810. };
  25811. this.itemError = function ( url ) {
  25812. if ( scope.onError !== undefined ) {
  25813. scope.onError( url );
  25814. }
  25815. };
  25816. this.resolveURL = function ( url ) {
  25817. if ( urlModifier ) {
  25818. return urlModifier( url );
  25819. }
  25820. return url;
  25821. };
  25822. this.setURLModifier = function ( transform ) {
  25823. urlModifier = transform;
  25824. return this;
  25825. };
  25826. this.addHandler = function ( regex, loader ) {
  25827. handlers.push( regex, loader );
  25828. return this;
  25829. };
  25830. this.removeHandler = function ( regex ) {
  25831. const index = handlers.indexOf( regex );
  25832. if ( index !== - 1 ) {
  25833. handlers.splice( index, 2 );
  25834. }
  25835. return this;
  25836. };
  25837. this.getHandler = function ( file ) {
  25838. for ( let i = 0, l = handlers.length; i < l; i += 2 ) {
  25839. const regex = handlers[ i ];
  25840. const loader = handlers[ i + 1 ];
  25841. if ( regex.global ) regex.lastIndex = 0; // see #17920
  25842. if ( regex.test( file ) ) {
  25843. return loader;
  25844. }
  25845. }
  25846. return null;
  25847. };
  25848. }
  25849. }
  25850. const DefaultLoadingManager = /*@__PURE__*/ new LoadingManager();
  25851. class Loader {
  25852. constructor( manager ) {
  25853. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  25854. this.crossOrigin = 'anonymous';
  25855. this.withCredentials = false;
  25856. this.path = '';
  25857. this.resourcePath = '';
  25858. this.requestHeader = {};
  25859. }
  25860. load( /* url, onLoad, onProgress, onError */ ) {}
  25861. loadAsync( url, onProgress ) {
  25862. const scope = this;
  25863. return new Promise( function ( resolve, reject ) {
  25864. scope.load( url, resolve, onProgress, reject );
  25865. } );
  25866. }
  25867. parse( /* data */ ) {}
  25868. setCrossOrigin( crossOrigin ) {
  25869. this.crossOrigin = crossOrigin;
  25870. return this;
  25871. }
  25872. setWithCredentials( value ) {
  25873. this.withCredentials = value;
  25874. return this;
  25875. }
  25876. setPath( path ) {
  25877. this.path = path;
  25878. return this;
  25879. }
  25880. setResourcePath( resourcePath ) {
  25881. this.resourcePath = resourcePath;
  25882. return this;
  25883. }
  25884. setRequestHeader( requestHeader ) {
  25885. this.requestHeader = requestHeader;
  25886. return this;
  25887. }
  25888. }
  25889. Loader.DEFAULT_MATERIAL_NAME = '__DEFAULT';
  25890. const loading = {};
  25891. class HttpError extends Error {
  25892. constructor( message, response ) {
  25893. super( message );
  25894. this.response = response;
  25895. }
  25896. }
  25897. class FileLoader extends Loader {
  25898. constructor( manager ) {
  25899. super( manager );
  25900. }
  25901. load( url, onLoad, onProgress, onError ) {
  25902. if ( url === undefined ) url = '';
  25903. if ( this.path !== undefined ) url = this.path + url;
  25904. url = this.manager.resolveURL( url );
  25905. const cached = Cache.get( url );
  25906. if ( cached !== undefined ) {
  25907. this.manager.itemStart( url );
  25908. setTimeout( () => {
  25909. if ( onLoad ) onLoad( cached );
  25910. this.manager.itemEnd( url );
  25911. }, 0 );
  25912. return cached;
  25913. }
  25914. // Check if request is duplicate
  25915. if ( loading[ url ] !== undefined ) {
  25916. loading[ url ].push( {
  25917. onLoad: onLoad,
  25918. onProgress: onProgress,
  25919. onError: onError
  25920. } );
  25921. return;
  25922. }
  25923. // Initialise array for duplicate requests
  25924. loading[ url ] = [];
  25925. loading[ url ].push( {
  25926. onLoad: onLoad,
  25927. onProgress: onProgress,
  25928. onError: onError,
  25929. } );
  25930. // create request
  25931. const req = new Request( url, {
  25932. headers: new Headers( this.requestHeader ),
  25933. credentials: this.withCredentials ? 'include' : 'same-origin',
  25934. // An abort controller could be added within a future PR
  25935. } );
  25936. // record states ( avoid data race )
  25937. const mimeType = this.mimeType;
  25938. const responseType = this.responseType;
  25939. // start the fetch
  25940. fetch( req )
  25941. .then( response => {
  25942. if ( response.status === 200 || response.status === 0 ) {
  25943. // Some browsers return HTTP Status 0 when using non-http protocol
  25944. // e.g. 'file://' or 'data://'. Handle as success.
  25945. if ( response.status === 0 ) {
  25946. console.warn( 'THREE.FileLoader: HTTP Status 0 received.' );
  25947. }
  25948. // Workaround: Checking if response.body === undefined for Alipay browser #23548
  25949. if ( typeof ReadableStream === 'undefined' || response.body === undefined || response.body.getReader === undefined ) {
  25950. return response;
  25951. }
  25952. const callbacks = loading[ url ];
  25953. const reader = response.body.getReader();
  25954. // Nginx needs X-File-Size check
  25955. // https://serverfault.com/questions/482875/why-does-nginx-remove-content-length-header-for-chunked-content
  25956. const contentLength = response.headers.get( 'Content-Length' ) || response.headers.get( 'X-File-Size' );
  25957. const total = contentLength ? parseInt( contentLength ) : 0;
  25958. const lengthComputable = total !== 0;
  25959. let loaded = 0;
  25960. // periodically read data into the new stream tracking while download progress
  25961. const stream = new ReadableStream( {
  25962. start( controller ) {
  25963. readData();
  25964. function readData() {
  25965. reader.read().then( ( { done, value } ) => {
  25966. if ( done ) {
  25967. controller.close();
  25968. } else {
  25969. loaded += value.byteLength;
  25970. const event = new ProgressEvent( 'progress', { lengthComputable, loaded, total } );
  25971. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  25972. const callback = callbacks[ i ];
  25973. if ( callback.onProgress ) callback.onProgress( event );
  25974. }
  25975. controller.enqueue( value );
  25976. readData();
  25977. }
  25978. } );
  25979. }
  25980. }
  25981. } );
  25982. return new Response( stream );
  25983. } else {
  25984. throw new HttpError( `fetch for "${response.url}" responded with ${response.status}: ${response.statusText}`, response );
  25985. }
  25986. } )
  25987. .then( response => {
  25988. switch ( responseType ) {
  25989. case 'arraybuffer':
  25990. return response.arrayBuffer();
  25991. case 'blob':
  25992. return response.blob();
  25993. case 'document':
  25994. return response.text()
  25995. .then( text => {
  25996. const parser = new DOMParser();
  25997. return parser.parseFromString( text, mimeType );
  25998. } );
  25999. case 'json':
  26000. return response.json();
  26001. default:
  26002. if ( mimeType === undefined ) {
  26003. return response.text();
  26004. } else {
  26005. // sniff encoding
  26006. const re = /charset="?([^;"\s]*)"?/i;
  26007. const exec = re.exec( mimeType );
  26008. const label = exec && exec[ 1 ] ? exec[ 1 ].toLowerCase() : undefined;
  26009. const decoder = new TextDecoder( label );
  26010. return response.arrayBuffer().then( ab => decoder.decode( ab ) );
  26011. }
  26012. }
  26013. } )
  26014. .then( data => {
  26015. // Add to cache only on HTTP success, so that we do not cache
  26016. // error response bodies as proper responses to requests.
  26017. Cache.add( url, data );
  26018. const callbacks = loading[ url ];
  26019. delete loading[ url ];
  26020. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  26021. const callback = callbacks[ i ];
  26022. if ( callback.onLoad ) callback.onLoad( data );
  26023. }
  26024. } )
  26025. .catch( err => {
  26026. // Abort errors and other errors are handled the same
  26027. const callbacks = loading[ url ];
  26028. if ( callbacks === undefined ) {
  26029. // When onLoad was called and url was deleted in `loading`
  26030. this.manager.itemError( url );
  26031. throw err;
  26032. }
  26033. delete loading[ url ];
  26034. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  26035. const callback = callbacks[ i ];
  26036. if ( callback.onError ) callback.onError( err );
  26037. }
  26038. this.manager.itemError( url );
  26039. } )
  26040. .finally( () => {
  26041. this.manager.itemEnd( url );
  26042. } );
  26043. this.manager.itemStart( url );
  26044. }
  26045. setResponseType( value ) {
  26046. this.responseType = value;
  26047. return this;
  26048. }
  26049. setMimeType( value ) {
  26050. this.mimeType = value;
  26051. return this;
  26052. }
  26053. }
  26054. class AnimationLoader extends Loader {
  26055. constructor( manager ) {
  26056. super( manager );
  26057. }
  26058. load( url, onLoad, onProgress, onError ) {
  26059. const scope = this;
  26060. const loader = new FileLoader( this.manager );
  26061. loader.setPath( this.path );
  26062. loader.setRequestHeader( this.requestHeader );
  26063. loader.setWithCredentials( this.withCredentials );
  26064. loader.load( url, function ( text ) {
  26065. try {
  26066. onLoad( scope.parse( JSON.parse( text ) ) );
  26067. } catch ( e ) {
  26068. if ( onError ) {
  26069. onError( e );
  26070. } else {
  26071. console.error( e );
  26072. }
  26073. scope.manager.itemError( url );
  26074. }
  26075. }, onProgress, onError );
  26076. }
  26077. parse( json ) {
  26078. const animations = [];
  26079. for ( let i = 0; i < json.length; i ++ ) {
  26080. const clip = AnimationClip.parse( json[ i ] );
  26081. animations.push( clip );
  26082. }
  26083. return animations;
  26084. }
  26085. }
  26086. /**
  26087. * Abstract Base class to block based textures loader (dds, pvr, ...)
  26088. *
  26089. * Sub classes have to implement the parse() method which will be used in load().
  26090. */
  26091. class CompressedTextureLoader extends Loader {
  26092. constructor( manager ) {
  26093. super( manager );
  26094. }
  26095. load( url, onLoad, onProgress, onError ) {
  26096. const scope = this;
  26097. const images = [];
  26098. const texture = new CompressedTexture();
  26099. const loader = new FileLoader( this.manager );
  26100. loader.setPath( this.path );
  26101. loader.setResponseType( 'arraybuffer' );
  26102. loader.setRequestHeader( this.requestHeader );
  26103. loader.setWithCredentials( scope.withCredentials );
  26104. let loaded = 0;
  26105. function loadTexture( i ) {
  26106. loader.load( url[ i ], function ( buffer ) {
  26107. const texDatas = scope.parse( buffer, true );
  26108. images[ i ] = {
  26109. width: texDatas.width,
  26110. height: texDatas.height,
  26111. format: texDatas.format,
  26112. mipmaps: texDatas.mipmaps
  26113. };
  26114. loaded += 1;
  26115. if ( loaded === 6 ) {
  26116. if ( texDatas.mipmapCount === 1 ) texture.minFilter = LinearFilter;
  26117. texture.image = images;
  26118. texture.format = texDatas.format;
  26119. texture.needsUpdate = true;
  26120. if ( onLoad ) onLoad( texture );
  26121. }
  26122. }, onProgress, onError );
  26123. }
  26124. if ( Array.isArray( url ) ) {
  26125. for ( let i = 0, il = url.length; i < il; ++ i ) {
  26126. loadTexture( i );
  26127. }
  26128. } else {
  26129. // compressed cubemap texture stored in a single DDS file
  26130. loader.load( url, function ( buffer ) {
  26131. const texDatas = scope.parse( buffer, true );
  26132. if ( texDatas.isCubemap ) {
  26133. const faces = texDatas.mipmaps.length / texDatas.mipmapCount;
  26134. for ( let f = 0; f < faces; f ++ ) {
  26135. images[ f ] = { mipmaps: [] };
  26136. for ( let i = 0; i < texDatas.mipmapCount; i ++ ) {
  26137. images[ f ].mipmaps.push( texDatas.mipmaps[ f * texDatas.mipmapCount + i ] );
  26138. images[ f ].format = texDatas.format;
  26139. images[ f ].width = texDatas.width;
  26140. images[ f ].height = texDatas.height;
  26141. }
  26142. }
  26143. texture.image = images;
  26144. } else {
  26145. texture.image.width = texDatas.width;
  26146. texture.image.height = texDatas.height;
  26147. texture.mipmaps = texDatas.mipmaps;
  26148. }
  26149. if ( texDatas.mipmapCount === 1 ) {
  26150. texture.minFilter = LinearFilter;
  26151. }
  26152. texture.format = texDatas.format;
  26153. texture.needsUpdate = true;
  26154. if ( onLoad ) onLoad( texture );
  26155. }, onProgress, onError );
  26156. }
  26157. return texture;
  26158. }
  26159. }
  26160. class ImageLoader extends Loader {
  26161. constructor( manager ) {
  26162. super( manager );
  26163. }
  26164. load( url, onLoad, onProgress, onError ) {
  26165. if ( this.path !== undefined ) url = this.path + url;
  26166. url = this.manager.resolveURL( url );
  26167. const scope = this;
  26168. const cached = Cache.get( url );
  26169. if ( cached !== undefined ) {
  26170. scope.manager.itemStart( url );
  26171. setTimeout( function () {
  26172. if ( onLoad ) onLoad( cached );
  26173. scope.manager.itemEnd( url );
  26174. }, 0 );
  26175. return cached;
  26176. }
  26177. const image = createElementNS( 'img' );
  26178. function onImageLoad() {
  26179. removeEventListeners();
  26180. Cache.add( url, this );
  26181. if ( onLoad ) onLoad( this );
  26182. scope.manager.itemEnd( url );
  26183. }
  26184. function onImageError( event ) {
  26185. removeEventListeners();
  26186. if ( onError ) onError( event );
  26187. scope.manager.itemError( url );
  26188. scope.manager.itemEnd( url );
  26189. }
  26190. function removeEventListeners() {
  26191. image.removeEventListener( 'load', onImageLoad, false );
  26192. image.removeEventListener( 'error', onImageError, false );
  26193. }
  26194. image.addEventListener( 'load', onImageLoad, false );
  26195. image.addEventListener( 'error', onImageError, false );
  26196. if ( url.slice( 0, 5 ) !== 'data:' ) {
  26197. if ( this.crossOrigin !== undefined ) image.crossOrigin = this.crossOrigin;
  26198. }
  26199. scope.manager.itemStart( url );
  26200. image.src = url;
  26201. return image;
  26202. }
  26203. }
  26204. class CubeTextureLoader extends Loader {
  26205. constructor( manager ) {
  26206. super( manager );
  26207. }
  26208. load( urls, onLoad, onProgress, onError ) {
  26209. const texture = new CubeTexture();
  26210. texture.colorSpace = SRGBColorSpace;
  26211. const loader = new ImageLoader( this.manager );
  26212. loader.setCrossOrigin( this.crossOrigin );
  26213. loader.setPath( this.path );
  26214. let loaded = 0;
  26215. function loadTexture( i ) {
  26216. loader.load( urls[ i ], function ( image ) {
  26217. texture.images[ i ] = image;
  26218. loaded ++;
  26219. if ( loaded === 6 ) {
  26220. texture.needsUpdate = true;
  26221. if ( onLoad ) onLoad( texture );
  26222. }
  26223. }, undefined, onError );
  26224. }
  26225. for ( let i = 0; i < urls.length; ++ i ) {
  26226. loadTexture( i );
  26227. }
  26228. return texture;
  26229. }
  26230. }
  26231. /**
  26232. * Abstract Base class to load generic binary textures formats (rgbe, hdr, ...)
  26233. *
  26234. * Sub classes have to implement the parse() method which will be used in load().
  26235. */
  26236. class DataTextureLoader extends Loader {
  26237. constructor( manager ) {
  26238. super( manager );
  26239. }
  26240. load( url, onLoad, onProgress, onError ) {
  26241. const scope = this;
  26242. const texture = new DataTexture();
  26243. const loader = new FileLoader( this.manager );
  26244. loader.setResponseType( 'arraybuffer' );
  26245. loader.setRequestHeader( this.requestHeader );
  26246. loader.setPath( this.path );
  26247. loader.setWithCredentials( scope.withCredentials );
  26248. loader.load( url, function ( buffer ) {
  26249. let texData;
  26250. try {
  26251. texData = scope.parse( buffer );
  26252. } catch ( error ) {
  26253. if ( onError !== undefined ) {
  26254. onError( error );
  26255. } else {
  26256. console.error( error );
  26257. return;
  26258. }
  26259. }
  26260. if ( texData.image !== undefined ) {
  26261. texture.image = texData.image;
  26262. } else if ( texData.data !== undefined ) {
  26263. texture.image.width = texData.width;
  26264. texture.image.height = texData.height;
  26265. texture.image.data = texData.data;
  26266. }
  26267. texture.wrapS = texData.wrapS !== undefined ? texData.wrapS : ClampToEdgeWrapping;
  26268. texture.wrapT = texData.wrapT !== undefined ? texData.wrapT : ClampToEdgeWrapping;
  26269. texture.magFilter = texData.magFilter !== undefined ? texData.magFilter : LinearFilter;
  26270. texture.minFilter = texData.minFilter !== undefined ? texData.minFilter : LinearFilter;
  26271. texture.anisotropy = texData.anisotropy !== undefined ? texData.anisotropy : 1;
  26272. if ( texData.colorSpace !== undefined ) {
  26273. texture.colorSpace = texData.colorSpace;
  26274. }
  26275. if ( texData.flipY !== undefined ) {
  26276. texture.flipY = texData.flipY;
  26277. }
  26278. if ( texData.format !== undefined ) {
  26279. texture.format = texData.format;
  26280. }
  26281. if ( texData.type !== undefined ) {
  26282. texture.type = texData.type;
  26283. }
  26284. if ( texData.mipmaps !== undefined ) {
  26285. texture.mipmaps = texData.mipmaps;
  26286. texture.minFilter = LinearMipmapLinearFilter; // presumably...
  26287. }
  26288. if ( texData.mipmapCount === 1 ) {
  26289. texture.minFilter = LinearFilter;
  26290. }
  26291. if ( texData.generateMipmaps !== undefined ) {
  26292. texture.generateMipmaps = texData.generateMipmaps;
  26293. }
  26294. texture.needsUpdate = true;
  26295. if ( onLoad ) onLoad( texture, texData );
  26296. }, onProgress, onError );
  26297. return texture;
  26298. }
  26299. }
  26300. class TextureLoader extends Loader {
  26301. constructor( manager ) {
  26302. super( manager );
  26303. }
  26304. load( url, onLoad, onProgress, onError ) {
  26305. const texture = new Texture();
  26306. const loader = new ImageLoader( this.manager );
  26307. loader.setCrossOrigin( this.crossOrigin );
  26308. loader.setPath( this.path );
  26309. loader.load( url, function ( image ) {
  26310. texture.image = image;
  26311. texture.needsUpdate = true;
  26312. if ( onLoad !== undefined ) {
  26313. onLoad( texture );
  26314. }
  26315. }, onProgress, onError );
  26316. return texture;
  26317. }
  26318. }
  26319. class Light extends Object3D {
  26320. constructor( color, intensity = 1 ) {
  26321. super();
  26322. this.isLight = true;
  26323. this.type = 'Light';
  26324. this.color = new Color( color );
  26325. this.intensity = intensity;
  26326. }
  26327. dispose() {
  26328. // Empty here in base class; some subclasses override.
  26329. }
  26330. copy( source, recursive ) {
  26331. super.copy( source, recursive );
  26332. this.color.copy( source.color );
  26333. this.intensity = source.intensity;
  26334. return this;
  26335. }
  26336. toJSON( meta ) {
  26337. const data = super.toJSON( meta );
  26338. data.object.color = this.color.getHex();
  26339. data.object.intensity = this.intensity;
  26340. if ( this.groundColor !== undefined ) data.object.groundColor = this.groundColor.getHex();
  26341. if ( this.distance !== undefined ) data.object.distance = this.distance;
  26342. if ( this.angle !== undefined ) data.object.angle = this.angle;
  26343. if ( this.decay !== undefined ) data.object.decay = this.decay;
  26344. if ( this.penumbra !== undefined ) data.object.penumbra = this.penumbra;
  26345. if ( this.shadow !== undefined ) data.object.shadow = this.shadow.toJSON();
  26346. return data;
  26347. }
  26348. }
  26349. class HemisphereLight extends Light {
  26350. constructor( skyColor, groundColor, intensity ) {
  26351. super( skyColor, intensity );
  26352. this.isHemisphereLight = true;
  26353. this.type = 'HemisphereLight';
  26354. this.position.copy( Object3D.DEFAULT_UP );
  26355. this.updateMatrix();
  26356. this.groundColor = new Color( groundColor );
  26357. }
  26358. copy( source, recursive ) {
  26359. super.copy( source, recursive );
  26360. this.groundColor.copy( source.groundColor );
  26361. return this;
  26362. }
  26363. }
  26364. const _projScreenMatrix$1 = /*@__PURE__*/ new Matrix4();
  26365. const _lightPositionWorld$1 = /*@__PURE__*/ new Vector3();
  26366. const _lookTarget$1 = /*@__PURE__*/ new Vector3();
  26367. class LightShadow {
  26368. constructor( camera ) {
  26369. this.camera = camera;
  26370. this.bias = 0;
  26371. this.normalBias = 0;
  26372. this.radius = 1;
  26373. this.blurSamples = 8;
  26374. this.mapSize = new Vector2( 512, 512 );
  26375. this.map = null;
  26376. this.mapPass = null;
  26377. this.matrix = new Matrix4();
  26378. this.autoUpdate = true;
  26379. this.needsUpdate = false;
  26380. this._frustum = new Frustum();
  26381. this._frameExtents = new Vector2( 1, 1 );
  26382. this._viewportCount = 1;
  26383. this._viewports = [
  26384. new Vector4( 0, 0, 1, 1 )
  26385. ];
  26386. }
  26387. getViewportCount() {
  26388. return this._viewportCount;
  26389. }
  26390. getFrustum() {
  26391. return this._frustum;
  26392. }
  26393. updateMatrices( light ) {
  26394. const shadowCamera = this.camera;
  26395. const shadowMatrix = this.matrix;
  26396. _lightPositionWorld$1.setFromMatrixPosition( light.matrixWorld );
  26397. shadowCamera.position.copy( _lightPositionWorld$1 );
  26398. _lookTarget$1.setFromMatrixPosition( light.target.matrixWorld );
  26399. shadowCamera.lookAt( _lookTarget$1 );
  26400. shadowCamera.updateMatrixWorld();
  26401. _projScreenMatrix$1.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  26402. this._frustum.setFromProjectionMatrix( _projScreenMatrix$1 );
  26403. shadowMatrix.set(
  26404. 0.5, 0.0, 0.0, 0.5,
  26405. 0.0, 0.5, 0.0, 0.5,
  26406. 0.0, 0.0, 0.5, 0.5,
  26407. 0.0, 0.0, 0.0, 1.0
  26408. );
  26409. shadowMatrix.multiply( _projScreenMatrix$1 );
  26410. }
  26411. getViewport( viewportIndex ) {
  26412. return this._viewports[ viewportIndex ];
  26413. }
  26414. getFrameExtents() {
  26415. return this._frameExtents;
  26416. }
  26417. dispose() {
  26418. if ( this.map ) {
  26419. this.map.dispose();
  26420. }
  26421. if ( this.mapPass ) {
  26422. this.mapPass.dispose();
  26423. }
  26424. }
  26425. copy( source ) {
  26426. this.camera = source.camera.clone();
  26427. this.bias = source.bias;
  26428. this.radius = source.radius;
  26429. this.mapSize.copy( source.mapSize );
  26430. return this;
  26431. }
  26432. clone() {
  26433. return new this.constructor().copy( this );
  26434. }
  26435. toJSON() {
  26436. const object = {};
  26437. if ( this.bias !== 0 ) object.bias = this.bias;
  26438. if ( this.normalBias !== 0 ) object.normalBias = this.normalBias;
  26439. if ( this.radius !== 1 ) object.radius = this.radius;
  26440. if ( this.mapSize.x !== 512 || this.mapSize.y !== 512 ) object.mapSize = this.mapSize.toArray();
  26441. object.camera = this.camera.toJSON( false ).object;
  26442. delete object.camera.matrix;
  26443. return object;
  26444. }
  26445. }
  26446. class SpotLightShadow extends LightShadow {
  26447. constructor() {
  26448. super( new PerspectiveCamera( 50, 1, 0.5, 500 ) );
  26449. this.isSpotLightShadow = true;
  26450. this.focus = 1;
  26451. }
  26452. updateMatrices( light ) {
  26453. const camera = this.camera;
  26454. const fov = RAD2DEG * 2 * light.angle * this.focus;
  26455. const aspect = this.mapSize.width / this.mapSize.height;
  26456. const far = light.distance || camera.far;
  26457. if ( fov !== camera.fov || aspect !== camera.aspect || far !== camera.far ) {
  26458. camera.fov = fov;
  26459. camera.aspect = aspect;
  26460. camera.far = far;
  26461. camera.updateProjectionMatrix();
  26462. }
  26463. super.updateMatrices( light );
  26464. }
  26465. copy( source ) {
  26466. super.copy( source );
  26467. this.focus = source.focus;
  26468. return this;
  26469. }
  26470. }
  26471. class SpotLight extends Light {
  26472. constructor( color, intensity, distance = 0, angle = Math.PI / 3, penumbra = 0, decay = 2 ) {
  26473. super( color, intensity );
  26474. this.isSpotLight = true;
  26475. this.type = 'SpotLight';
  26476. this.position.copy( Object3D.DEFAULT_UP );
  26477. this.updateMatrix();
  26478. this.target = new Object3D();
  26479. this.distance = distance;
  26480. this.angle = angle;
  26481. this.penumbra = penumbra;
  26482. this.decay = decay;
  26483. this.map = null;
  26484. this.shadow = new SpotLightShadow();
  26485. }
  26486. get power() {
  26487. // compute the light's luminous power (in lumens) from its intensity (in candela)
  26488. // by convention for a spotlight, luminous power (lm) = π * luminous intensity (cd)
  26489. return this.intensity * Math.PI;
  26490. }
  26491. set power( power ) {
  26492. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  26493. this.intensity = power / Math.PI;
  26494. }
  26495. dispose() {
  26496. this.shadow.dispose();
  26497. }
  26498. copy( source, recursive ) {
  26499. super.copy( source, recursive );
  26500. this.distance = source.distance;
  26501. this.angle = source.angle;
  26502. this.penumbra = source.penumbra;
  26503. this.decay = source.decay;
  26504. this.target = source.target.clone();
  26505. this.shadow = source.shadow.clone();
  26506. return this;
  26507. }
  26508. }
  26509. const _projScreenMatrix = /*@__PURE__*/ new Matrix4();
  26510. const _lightPositionWorld = /*@__PURE__*/ new Vector3();
  26511. const _lookTarget = /*@__PURE__*/ new Vector3();
  26512. class PointLightShadow extends LightShadow {
  26513. constructor() {
  26514. super( new PerspectiveCamera( 90, 1, 0.5, 500 ) );
  26515. this.isPointLightShadow = true;
  26516. this._frameExtents = new Vector2( 4, 2 );
  26517. this._viewportCount = 6;
  26518. this._viewports = [
  26519. // These viewports map a cube-map onto a 2D texture with the
  26520. // following orientation:
  26521. //
  26522. // xzXZ
  26523. // y Y
  26524. //
  26525. // X - Positive x direction
  26526. // x - Negative x direction
  26527. // Y - Positive y direction
  26528. // y - Negative y direction
  26529. // Z - Positive z direction
  26530. // z - Negative z direction
  26531. // positive X
  26532. new Vector4( 2, 1, 1, 1 ),
  26533. // negative X
  26534. new Vector4( 0, 1, 1, 1 ),
  26535. // positive Z
  26536. new Vector4( 3, 1, 1, 1 ),
  26537. // negative Z
  26538. new Vector4( 1, 1, 1, 1 ),
  26539. // positive Y
  26540. new Vector4( 3, 0, 1, 1 ),
  26541. // negative Y
  26542. new Vector4( 1, 0, 1, 1 )
  26543. ];
  26544. this._cubeDirections = [
  26545. new Vector3( 1, 0, 0 ), new Vector3( - 1, 0, 0 ), new Vector3( 0, 0, 1 ),
  26546. new Vector3( 0, 0, - 1 ), new Vector3( 0, 1, 0 ), new Vector3( 0, - 1, 0 )
  26547. ];
  26548. this._cubeUps = [
  26549. new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ),
  26550. new Vector3( 0, 1, 0 ), new Vector3( 0, 0, 1 ), new Vector3( 0, 0, - 1 )
  26551. ];
  26552. }
  26553. updateMatrices( light, viewportIndex = 0 ) {
  26554. const camera = this.camera;
  26555. const shadowMatrix = this.matrix;
  26556. const far = light.distance || camera.far;
  26557. if ( far !== camera.far ) {
  26558. camera.far = far;
  26559. camera.updateProjectionMatrix();
  26560. }
  26561. _lightPositionWorld.setFromMatrixPosition( light.matrixWorld );
  26562. camera.position.copy( _lightPositionWorld );
  26563. _lookTarget.copy( camera.position );
  26564. _lookTarget.add( this._cubeDirections[ viewportIndex ] );
  26565. camera.up.copy( this._cubeUps[ viewportIndex ] );
  26566. camera.lookAt( _lookTarget );
  26567. camera.updateMatrixWorld();
  26568. shadowMatrix.makeTranslation( - _lightPositionWorld.x, - _lightPositionWorld.y, - _lightPositionWorld.z );
  26569. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  26570. this._frustum.setFromProjectionMatrix( _projScreenMatrix );
  26571. }
  26572. }
  26573. class PointLight extends Light {
  26574. constructor( color, intensity, distance = 0, decay = 2 ) {
  26575. super( color, intensity );
  26576. this.isPointLight = true;
  26577. this.type = 'PointLight';
  26578. this.distance = distance;
  26579. this.decay = decay;
  26580. this.shadow = new PointLightShadow();
  26581. }
  26582. get power() {
  26583. // compute the light's luminous power (in lumens) from its intensity (in candela)
  26584. // for an isotropic light source, luminous power (lm) = 4 π luminous intensity (cd)
  26585. return this.intensity * 4 * Math.PI;
  26586. }
  26587. set power( power ) {
  26588. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  26589. this.intensity = power / ( 4 * Math.PI );
  26590. }
  26591. dispose() {
  26592. this.shadow.dispose();
  26593. }
  26594. copy( source, recursive ) {
  26595. super.copy( source, recursive );
  26596. this.distance = source.distance;
  26597. this.decay = source.decay;
  26598. this.shadow = source.shadow.clone();
  26599. return this;
  26600. }
  26601. }
  26602. class DirectionalLightShadow extends LightShadow {
  26603. constructor() {
  26604. super( new OrthographicCamera( - 5, 5, 5, - 5, 0.5, 500 ) );
  26605. this.isDirectionalLightShadow = true;
  26606. }
  26607. }
  26608. class DirectionalLight extends Light {
  26609. constructor( color, intensity ) {
  26610. super( color, intensity );
  26611. this.isDirectionalLight = true;
  26612. this.type = 'DirectionalLight';
  26613. this.position.copy( Object3D.DEFAULT_UP );
  26614. this.updateMatrix();
  26615. this.target = new Object3D();
  26616. this.shadow = new DirectionalLightShadow();
  26617. }
  26618. dispose() {
  26619. this.shadow.dispose();
  26620. }
  26621. copy( source ) {
  26622. super.copy( source );
  26623. this.target = source.target.clone();
  26624. this.shadow = source.shadow.clone();
  26625. return this;
  26626. }
  26627. }
  26628. class AmbientLight extends Light {
  26629. constructor( color, intensity ) {
  26630. super( color, intensity );
  26631. this.isAmbientLight = true;
  26632. this.type = 'AmbientLight';
  26633. }
  26634. }
  26635. class RectAreaLight extends Light {
  26636. constructor( color, intensity, width = 10, height = 10 ) {
  26637. super( color, intensity );
  26638. this.isRectAreaLight = true;
  26639. this.type = 'RectAreaLight';
  26640. this.width = width;
  26641. this.height = height;
  26642. }
  26643. get power() {
  26644. // compute the light's luminous power (in lumens) from its intensity (in nits)
  26645. return this.intensity * this.width * this.height * Math.PI;
  26646. }
  26647. set power( power ) {
  26648. // set the light's intensity (in nits) from the desired luminous power (in lumens)
  26649. this.intensity = power / ( this.width * this.height * Math.PI );
  26650. }
  26651. copy( source ) {
  26652. super.copy( source );
  26653. this.width = source.width;
  26654. this.height = source.height;
  26655. return this;
  26656. }
  26657. toJSON( meta ) {
  26658. const data = super.toJSON( meta );
  26659. data.object.width = this.width;
  26660. data.object.height = this.height;
  26661. return data;
  26662. }
  26663. }
  26664. /**
  26665. * Primary reference:
  26666. * https://graphics.stanford.edu/papers/envmap/envmap.pdf
  26667. *
  26668. * Secondary reference:
  26669. * https://www.ppsloan.org/publications/StupidSH36.pdf
  26670. */
  26671. // 3-band SH defined by 9 coefficients
  26672. class SphericalHarmonics3 {
  26673. constructor() {
  26674. this.isSphericalHarmonics3 = true;
  26675. this.coefficients = [];
  26676. for ( let i = 0; i < 9; i ++ ) {
  26677. this.coefficients.push( new Vector3() );
  26678. }
  26679. }
  26680. set( coefficients ) {
  26681. for ( let i = 0; i < 9; i ++ ) {
  26682. this.coefficients[ i ].copy( coefficients[ i ] );
  26683. }
  26684. return this;
  26685. }
  26686. zero() {
  26687. for ( let i = 0; i < 9; i ++ ) {
  26688. this.coefficients[ i ].set( 0, 0, 0 );
  26689. }
  26690. return this;
  26691. }
  26692. // get the radiance in the direction of the normal
  26693. // target is a Vector3
  26694. getAt( normal, target ) {
  26695. // normal is assumed to be unit length
  26696. const x = normal.x, y = normal.y, z = normal.z;
  26697. const coeff = this.coefficients;
  26698. // band 0
  26699. target.copy( coeff[ 0 ] ).multiplyScalar( 0.282095 );
  26700. // band 1
  26701. target.addScaledVector( coeff[ 1 ], 0.488603 * y );
  26702. target.addScaledVector( coeff[ 2 ], 0.488603 * z );
  26703. target.addScaledVector( coeff[ 3 ], 0.488603 * x );
  26704. // band 2
  26705. target.addScaledVector( coeff[ 4 ], 1.092548 * ( x * y ) );
  26706. target.addScaledVector( coeff[ 5 ], 1.092548 * ( y * z ) );
  26707. target.addScaledVector( coeff[ 6 ], 0.315392 * ( 3.0 * z * z - 1.0 ) );
  26708. target.addScaledVector( coeff[ 7 ], 1.092548 * ( x * z ) );
  26709. target.addScaledVector( coeff[ 8 ], 0.546274 * ( x * x - y * y ) );
  26710. return target;
  26711. }
  26712. // get the irradiance (radiance convolved with cosine lobe) in the direction of the normal
  26713. // target is a Vector3
  26714. // https://graphics.stanford.edu/papers/envmap/envmap.pdf
  26715. getIrradianceAt( normal, target ) {
  26716. // normal is assumed to be unit length
  26717. const x = normal.x, y = normal.y, z = normal.z;
  26718. const coeff = this.coefficients;
  26719. // band 0
  26720. target.copy( coeff[ 0 ] ).multiplyScalar( 0.886227 ); // π * 0.282095
  26721. // band 1
  26722. target.addScaledVector( coeff[ 1 ], 2.0 * 0.511664 * y ); // ( 2 * π / 3 ) * 0.488603
  26723. target.addScaledVector( coeff[ 2 ], 2.0 * 0.511664 * z );
  26724. target.addScaledVector( coeff[ 3 ], 2.0 * 0.511664 * x );
  26725. // band 2
  26726. target.addScaledVector( coeff[ 4 ], 2.0 * 0.429043 * x * y ); // ( π / 4 ) * 1.092548
  26727. target.addScaledVector( coeff[ 5 ], 2.0 * 0.429043 * y * z );
  26728. target.addScaledVector( coeff[ 6 ], 0.743125 * z * z - 0.247708 ); // ( π / 4 ) * 0.315392 * 3
  26729. target.addScaledVector( coeff[ 7 ], 2.0 * 0.429043 * x * z );
  26730. target.addScaledVector( coeff[ 8 ], 0.429043 * ( x * x - y * y ) ); // ( π / 4 ) * 0.546274
  26731. return target;
  26732. }
  26733. add( sh ) {
  26734. for ( let i = 0; i < 9; i ++ ) {
  26735. this.coefficients[ i ].add( sh.coefficients[ i ] );
  26736. }
  26737. return this;
  26738. }
  26739. addScaledSH( sh, s ) {
  26740. for ( let i = 0; i < 9; i ++ ) {
  26741. this.coefficients[ i ].addScaledVector( sh.coefficients[ i ], s );
  26742. }
  26743. return this;
  26744. }
  26745. scale( s ) {
  26746. for ( let i = 0; i < 9; i ++ ) {
  26747. this.coefficients[ i ].multiplyScalar( s );
  26748. }
  26749. return this;
  26750. }
  26751. lerp( sh, alpha ) {
  26752. for ( let i = 0; i < 9; i ++ ) {
  26753. this.coefficients[ i ].lerp( sh.coefficients[ i ], alpha );
  26754. }
  26755. return this;
  26756. }
  26757. equals( sh ) {
  26758. for ( let i = 0; i < 9; i ++ ) {
  26759. if ( ! this.coefficients[ i ].equals( sh.coefficients[ i ] ) ) {
  26760. return false;
  26761. }
  26762. }
  26763. return true;
  26764. }
  26765. copy( sh ) {
  26766. return this.set( sh.coefficients );
  26767. }
  26768. clone() {
  26769. return new this.constructor().copy( this );
  26770. }
  26771. fromArray( array, offset = 0 ) {
  26772. const coefficients = this.coefficients;
  26773. for ( let i = 0; i < 9; i ++ ) {
  26774. coefficients[ i ].fromArray( array, offset + ( i * 3 ) );
  26775. }
  26776. return this;
  26777. }
  26778. toArray( array = [], offset = 0 ) {
  26779. const coefficients = this.coefficients;
  26780. for ( let i = 0; i < 9; i ++ ) {
  26781. coefficients[ i ].toArray( array, offset + ( i * 3 ) );
  26782. }
  26783. return array;
  26784. }
  26785. // evaluate the basis functions
  26786. // shBasis is an Array[ 9 ]
  26787. static getBasisAt( normal, shBasis ) {
  26788. // normal is assumed to be unit length
  26789. const x = normal.x, y = normal.y, z = normal.z;
  26790. // band 0
  26791. shBasis[ 0 ] = 0.282095;
  26792. // band 1
  26793. shBasis[ 1 ] = 0.488603 * y;
  26794. shBasis[ 2 ] = 0.488603 * z;
  26795. shBasis[ 3 ] = 0.488603 * x;
  26796. // band 2
  26797. shBasis[ 4 ] = 1.092548 * x * y;
  26798. shBasis[ 5 ] = 1.092548 * y * z;
  26799. shBasis[ 6 ] = 0.315392 * ( 3 * z * z - 1 );
  26800. shBasis[ 7 ] = 1.092548 * x * z;
  26801. shBasis[ 8 ] = 0.546274 * ( x * x - y * y );
  26802. }
  26803. }
  26804. class LightProbe extends Light {
  26805. constructor( sh = new SphericalHarmonics3(), intensity = 1 ) {
  26806. super( undefined, intensity );
  26807. this.isLightProbe = true;
  26808. this.sh = sh;
  26809. }
  26810. copy( source ) {
  26811. super.copy( source );
  26812. this.sh.copy( source.sh );
  26813. return this;
  26814. }
  26815. fromJSON( json ) {
  26816. this.intensity = json.intensity; // TODO: Move this bit to Light.fromJSON();
  26817. this.sh.fromArray( json.sh );
  26818. return this;
  26819. }
  26820. toJSON( meta ) {
  26821. const data = super.toJSON( meta );
  26822. data.object.sh = this.sh.toArray();
  26823. return data;
  26824. }
  26825. }
  26826. class MaterialLoader extends Loader {
  26827. constructor( manager ) {
  26828. super( manager );
  26829. this.textures = {};
  26830. }
  26831. load( url, onLoad, onProgress, onError ) {
  26832. const scope = this;
  26833. const loader = new FileLoader( scope.manager );
  26834. loader.setPath( scope.path );
  26835. loader.setRequestHeader( scope.requestHeader );
  26836. loader.setWithCredentials( scope.withCredentials );
  26837. loader.load( url, function ( text ) {
  26838. try {
  26839. onLoad( scope.parse( JSON.parse( text ) ) );
  26840. } catch ( e ) {
  26841. if ( onError ) {
  26842. onError( e );
  26843. } else {
  26844. console.error( e );
  26845. }
  26846. scope.manager.itemError( url );
  26847. }
  26848. }, onProgress, onError );
  26849. }
  26850. parse( json ) {
  26851. const textures = this.textures;
  26852. function getTexture( name ) {
  26853. if ( textures[ name ] === undefined ) {
  26854. console.warn( 'THREE.MaterialLoader: Undefined texture', name );
  26855. }
  26856. return textures[ name ];
  26857. }
  26858. const material = MaterialLoader.createMaterialFromType( json.type );
  26859. if ( json.uuid !== undefined ) material.uuid = json.uuid;
  26860. if ( json.name !== undefined ) material.name = json.name;
  26861. if ( json.color !== undefined && material.color !== undefined ) material.color.setHex( json.color );
  26862. if ( json.roughness !== undefined ) material.roughness = json.roughness;
  26863. if ( json.metalness !== undefined ) material.metalness = json.metalness;
  26864. if ( json.sheen !== undefined ) material.sheen = json.sheen;
  26865. if ( json.sheenColor !== undefined ) material.sheenColor = new Color().setHex( json.sheenColor );
  26866. if ( json.sheenRoughness !== undefined ) material.sheenRoughness = json.sheenRoughness;
  26867. if ( json.emissive !== undefined && material.emissive !== undefined ) material.emissive.setHex( json.emissive );
  26868. if ( json.specular !== undefined && material.specular !== undefined ) material.specular.setHex( json.specular );
  26869. if ( json.specularIntensity !== undefined ) material.specularIntensity = json.specularIntensity;
  26870. if ( json.specularColor !== undefined && material.specularColor !== undefined ) material.specularColor.setHex( json.specularColor );
  26871. if ( json.shininess !== undefined ) material.shininess = json.shininess;
  26872. if ( json.clearcoat !== undefined ) material.clearcoat = json.clearcoat;
  26873. if ( json.clearcoatRoughness !== undefined ) material.clearcoatRoughness = json.clearcoatRoughness;
  26874. if ( json.iridescence !== undefined ) material.iridescence = json.iridescence;
  26875. if ( json.iridescenceIOR !== undefined ) material.iridescenceIOR = json.iridescenceIOR;
  26876. if ( json.iridescenceThicknessRange !== undefined ) material.iridescenceThicknessRange = json.iridescenceThicknessRange;
  26877. if ( json.transmission !== undefined ) material.transmission = json.transmission;
  26878. if ( json.thickness !== undefined ) material.thickness = json.thickness;
  26879. if ( json.attenuationDistance !== undefined ) material.attenuationDistance = json.attenuationDistance;
  26880. if ( json.attenuationColor !== undefined && material.attenuationColor !== undefined ) material.attenuationColor.setHex( json.attenuationColor );
  26881. if ( json.anisotropy !== undefined ) material.anisotropy = json.anisotropy;
  26882. if ( json.anisotropyRotation !== undefined ) material.anisotropyRotation = json.anisotropyRotation;
  26883. if ( json.fog !== undefined ) material.fog = json.fog;
  26884. if ( json.flatShading !== undefined ) material.flatShading = json.flatShading;
  26885. if ( json.blending !== undefined ) material.blending = json.blending;
  26886. if ( json.combine !== undefined ) material.combine = json.combine;
  26887. if ( json.side !== undefined ) material.side = json.side;
  26888. if ( json.shadowSide !== undefined ) material.shadowSide = json.shadowSide;
  26889. if ( json.opacity !== undefined ) material.opacity = json.opacity;
  26890. if ( json.transparent !== undefined ) material.transparent = json.transparent;
  26891. if ( json.alphaTest !== undefined ) material.alphaTest = json.alphaTest;
  26892. if ( json.alphaHash !== undefined ) material.alphaHash = json.alphaHash;
  26893. if ( json.depthFunc !== undefined ) material.depthFunc = json.depthFunc;
  26894. if ( json.depthTest !== undefined ) material.depthTest = json.depthTest;
  26895. if ( json.depthWrite !== undefined ) material.depthWrite = json.depthWrite;
  26896. if ( json.colorWrite !== undefined ) material.colorWrite = json.colorWrite;
  26897. if ( json.blendSrc !== undefined ) material.blendSrc = json.blendSrc;
  26898. if ( json.blendDst !== undefined ) material.blendDst = json.blendDst;
  26899. if ( json.blendEquation !== undefined ) material.blendEquation = json.blendEquation;
  26900. if ( json.blendSrcAlpha !== undefined ) material.blendSrcAlpha = json.blendSrcAlpha;
  26901. if ( json.blendDstAlpha !== undefined ) material.blendDstAlpha = json.blendDstAlpha;
  26902. if ( json.blendEquationAlpha !== undefined ) material.blendEquationAlpha = json.blendEquationAlpha;
  26903. if ( json.blendColor !== undefined && material.blendColor !== undefined ) material.blendColor.setHex( json.blendColor );
  26904. if ( json.blendAlpha !== undefined ) material.blendAlpha = json.blendAlpha;
  26905. if ( json.stencilWriteMask !== undefined ) material.stencilWriteMask = json.stencilWriteMask;
  26906. if ( json.stencilFunc !== undefined ) material.stencilFunc = json.stencilFunc;
  26907. if ( json.stencilRef !== undefined ) material.stencilRef = json.stencilRef;
  26908. if ( json.stencilFuncMask !== undefined ) material.stencilFuncMask = json.stencilFuncMask;
  26909. if ( json.stencilFail !== undefined ) material.stencilFail = json.stencilFail;
  26910. if ( json.stencilZFail !== undefined ) material.stencilZFail = json.stencilZFail;
  26911. if ( json.stencilZPass !== undefined ) material.stencilZPass = json.stencilZPass;
  26912. if ( json.stencilWrite !== undefined ) material.stencilWrite = json.stencilWrite;
  26913. if ( json.wireframe !== undefined ) material.wireframe = json.wireframe;
  26914. if ( json.wireframeLinewidth !== undefined ) material.wireframeLinewidth = json.wireframeLinewidth;
  26915. if ( json.wireframeLinecap !== undefined ) material.wireframeLinecap = json.wireframeLinecap;
  26916. if ( json.wireframeLinejoin !== undefined ) material.wireframeLinejoin = json.wireframeLinejoin;
  26917. if ( json.rotation !== undefined ) material.rotation = json.rotation;
  26918. if ( json.linewidth !== undefined ) material.linewidth = json.linewidth;
  26919. if ( json.dashSize !== undefined ) material.dashSize = json.dashSize;
  26920. if ( json.gapSize !== undefined ) material.gapSize = json.gapSize;
  26921. if ( json.scale !== undefined ) material.scale = json.scale;
  26922. if ( json.polygonOffset !== undefined ) material.polygonOffset = json.polygonOffset;
  26923. if ( json.polygonOffsetFactor !== undefined ) material.polygonOffsetFactor = json.polygonOffsetFactor;
  26924. if ( json.polygonOffsetUnits !== undefined ) material.polygonOffsetUnits = json.polygonOffsetUnits;
  26925. if ( json.dithering !== undefined ) material.dithering = json.dithering;
  26926. if ( json.alphaToCoverage !== undefined ) material.alphaToCoverage = json.alphaToCoverage;
  26927. if ( json.premultipliedAlpha !== undefined ) material.premultipliedAlpha = json.premultipliedAlpha;
  26928. if ( json.forceSinglePass !== undefined ) material.forceSinglePass = json.forceSinglePass;
  26929. if ( json.visible !== undefined ) material.visible = json.visible;
  26930. if ( json.toneMapped !== undefined ) material.toneMapped = json.toneMapped;
  26931. if ( json.userData !== undefined ) material.userData = json.userData;
  26932. if ( json.vertexColors !== undefined ) {
  26933. if ( typeof json.vertexColors === 'number' ) {
  26934. material.vertexColors = ( json.vertexColors > 0 ) ? true : false;
  26935. } else {
  26936. material.vertexColors = json.vertexColors;
  26937. }
  26938. }
  26939. // Shader Material
  26940. if ( json.uniforms !== undefined ) {
  26941. for ( const name in json.uniforms ) {
  26942. const uniform = json.uniforms[ name ];
  26943. material.uniforms[ name ] = {};
  26944. switch ( uniform.type ) {
  26945. case 't':
  26946. material.uniforms[ name ].value = getTexture( uniform.value );
  26947. break;
  26948. case 'c':
  26949. material.uniforms[ name ].value = new Color().setHex( uniform.value );
  26950. break;
  26951. case 'v2':
  26952. material.uniforms[ name ].value = new Vector2().fromArray( uniform.value );
  26953. break;
  26954. case 'v3':
  26955. material.uniforms[ name ].value = new Vector3().fromArray( uniform.value );
  26956. break;
  26957. case 'v4':
  26958. material.uniforms[ name ].value = new Vector4().fromArray( uniform.value );
  26959. break;
  26960. case 'm3':
  26961. material.uniforms[ name ].value = new Matrix3().fromArray( uniform.value );
  26962. break;
  26963. case 'm4':
  26964. material.uniforms[ name ].value = new Matrix4().fromArray( uniform.value );
  26965. break;
  26966. default:
  26967. material.uniforms[ name ].value = uniform.value;
  26968. }
  26969. }
  26970. }
  26971. if ( json.defines !== undefined ) material.defines = json.defines;
  26972. if ( json.vertexShader !== undefined ) material.vertexShader = json.vertexShader;
  26973. if ( json.fragmentShader !== undefined ) material.fragmentShader = json.fragmentShader;
  26974. if ( json.glslVersion !== undefined ) material.glslVersion = json.glslVersion;
  26975. if ( json.extensions !== undefined ) {
  26976. for ( const key in json.extensions ) {
  26977. material.extensions[ key ] = json.extensions[ key ];
  26978. }
  26979. }
  26980. if ( json.lights !== undefined ) material.lights = json.lights;
  26981. if ( json.clipping !== undefined ) material.clipping = json.clipping;
  26982. // for PointsMaterial
  26983. if ( json.size !== undefined ) material.size = json.size;
  26984. if ( json.sizeAttenuation !== undefined ) material.sizeAttenuation = json.sizeAttenuation;
  26985. // maps
  26986. if ( json.map !== undefined ) material.map = getTexture( json.map );
  26987. if ( json.matcap !== undefined ) material.matcap = getTexture( json.matcap );
  26988. if ( json.alphaMap !== undefined ) material.alphaMap = getTexture( json.alphaMap );
  26989. if ( json.bumpMap !== undefined ) material.bumpMap = getTexture( json.bumpMap );
  26990. if ( json.bumpScale !== undefined ) material.bumpScale = json.bumpScale;
  26991. if ( json.normalMap !== undefined ) material.normalMap = getTexture( json.normalMap );
  26992. if ( json.normalMapType !== undefined ) material.normalMapType = json.normalMapType;
  26993. if ( json.normalScale !== undefined ) {
  26994. let normalScale = json.normalScale;
  26995. if ( Array.isArray( normalScale ) === false ) {
  26996. // Blender exporter used to export a scalar. See #7459
  26997. normalScale = [ normalScale, normalScale ];
  26998. }
  26999. material.normalScale = new Vector2().fromArray( normalScale );
  27000. }
  27001. if ( json.displacementMap !== undefined ) material.displacementMap = getTexture( json.displacementMap );
  27002. if ( json.displacementScale !== undefined ) material.displacementScale = json.displacementScale;
  27003. if ( json.displacementBias !== undefined ) material.displacementBias = json.displacementBias;
  27004. if ( json.roughnessMap !== undefined ) material.roughnessMap = getTexture( json.roughnessMap );
  27005. if ( json.metalnessMap !== undefined ) material.metalnessMap = getTexture( json.metalnessMap );
  27006. if ( json.emissiveMap !== undefined ) material.emissiveMap = getTexture( json.emissiveMap );
  27007. if ( json.emissiveIntensity !== undefined ) material.emissiveIntensity = json.emissiveIntensity;
  27008. if ( json.specularMap !== undefined ) material.specularMap = getTexture( json.specularMap );
  27009. if ( json.specularIntensityMap !== undefined ) material.specularIntensityMap = getTexture( json.specularIntensityMap );
  27010. if ( json.specularColorMap !== undefined ) material.specularColorMap = getTexture( json.specularColorMap );
  27011. if ( json.envMap !== undefined ) material.envMap = getTexture( json.envMap );
  27012. if ( json.envMapIntensity !== undefined ) material.envMapIntensity = json.envMapIntensity;
  27013. if ( json.reflectivity !== undefined ) material.reflectivity = json.reflectivity;
  27014. if ( json.refractionRatio !== undefined ) material.refractionRatio = json.refractionRatio;
  27015. if ( json.lightMap !== undefined ) material.lightMap = getTexture( json.lightMap );
  27016. if ( json.lightMapIntensity !== undefined ) material.lightMapIntensity = json.lightMapIntensity;
  27017. if ( json.aoMap !== undefined ) material.aoMap = getTexture( json.aoMap );
  27018. if ( json.aoMapIntensity !== undefined ) material.aoMapIntensity = json.aoMapIntensity;
  27019. if ( json.gradientMap !== undefined ) material.gradientMap = getTexture( json.gradientMap );
  27020. if ( json.clearcoatMap !== undefined ) material.clearcoatMap = getTexture( json.clearcoatMap );
  27021. if ( json.clearcoatRoughnessMap !== undefined ) material.clearcoatRoughnessMap = getTexture( json.clearcoatRoughnessMap );
  27022. if ( json.clearcoatNormalMap !== undefined ) material.clearcoatNormalMap = getTexture( json.clearcoatNormalMap );
  27023. if ( json.clearcoatNormalScale !== undefined ) material.clearcoatNormalScale = new Vector2().fromArray( json.clearcoatNormalScale );
  27024. if ( json.iridescenceMap !== undefined ) material.iridescenceMap = getTexture( json.iridescenceMap );
  27025. if ( json.iridescenceThicknessMap !== undefined ) material.iridescenceThicknessMap = getTexture( json.iridescenceThicknessMap );
  27026. if ( json.transmissionMap !== undefined ) material.transmissionMap = getTexture( json.transmissionMap );
  27027. if ( json.thicknessMap !== undefined ) material.thicknessMap = getTexture( json.thicknessMap );
  27028. if ( json.anisotropyMap !== undefined ) material.anisotropyMap = getTexture( json.anisotropyMap );
  27029. if ( json.sheenColorMap !== undefined ) material.sheenColorMap = getTexture( json.sheenColorMap );
  27030. if ( json.sheenRoughnessMap !== undefined ) material.sheenRoughnessMap = getTexture( json.sheenRoughnessMap );
  27031. return material;
  27032. }
  27033. setTextures( value ) {
  27034. this.textures = value;
  27035. return this;
  27036. }
  27037. static createMaterialFromType( type ) {
  27038. const materialLib = {
  27039. ShadowMaterial,
  27040. SpriteMaterial,
  27041. RawShaderMaterial,
  27042. ShaderMaterial,
  27043. PointsMaterial,
  27044. MeshPhysicalMaterial,
  27045. MeshStandardMaterial,
  27046. MeshPhongMaterial,
  27047. MeshToonMaterial,
  27048. MeshNormalMaterial,
  27049. MeshLambertMaterial,
  27050. MeshDepthMaterial,
  27051. MeshDistanceMaterial,
  27052. MeshBasicMaterial,
  27053. MeshMatcapMaterial,
  27054. LineDashedMaterial,
  27055. LineBasicMaterial,
  27056. Material
  27057. };
  27058. return new materialLib[ type ]();
  27059. }
  27060. }
  27061. class LoaderUtils {
  27062. static decodeText( array ) {
  27063. if ( typeof TextDecoder !== 'undefined' ) {
  27064. return new TextDecoder().decode( array );
  27065. }
  27066. // Avoid the String.fromCharCode.apply(null, array) shortcut, which
  27067. // throws a "maximum call stack size exceeded" error for large arrays.
  27068. let s = '';
  27069. for ( let i = 0, il = array.length; i < il; i ++ ) {
  27070. // Implicitly assumes little-endian.
  27071. s += String.fromCharCode( array[ i ] );
  27072. }
  27073. try {
  27074. // merges multi-byte utf-8 characters.
  27075. return decodeURIComponent( escape( s ) );
  27076. } catch ( e ) { // see #16358
  27077. return s;
  27078. }
  27079. }
  27080. static extractUrlBase( url ) {
  27081. const index = url.lastIndexOf( '/' );
  27082. if ( index === - 1 ) return './';
  27083. return url.slice( 0, index + 1 );
  27084. }
  27085. static resolveURL( url, path ) {
  27086. // Invalid URL
  27087. if ( typeof url !== 'string' || url === '' ) return '';
  27088. // Host Relative URL
  27089. if ( /^https?:\/\//i.test( path ) && /^\//.test( url ) ) {
  27090. path = path.replace( /(^https?:\/\/[^\/]+).*/i, '$1' );
  27091. }
  27092. // Absolute URL http://,https://,//
  27093. if ( /^(https?:)?\/\//i.test( url ) ) return url;
  27094. // Data URI
  27095. if ( /^data:.*,.*$/i.test( url ) ) return url;
  27096. // Blob URL
  27097. if ( /^blob:.*$/i.test( url ) ) return url;
  27098. // Relative URL
  27099. return path + url;
  27100. }
  27101. }
  27102. class InstancedBufferGeometry extends BufferGeometry {
  27103. constructor() {
  27104. super();
  27105. this.isInstancedBufferGeometry = true;
  27106. this.type = 'InstancedBufferGeometry';
  27107. this.instanceCount = Infinity;
  27108. }
  27109. copy( source ) {
  27110. super.copy( source );
  27111. this.instanceCount = source.instanceCount;
  27112. return this;
  27113. }
  27114. toJSON() {
  27115. const data = super.toJSON();
  27116. data.instanceCount = this.instanceCount;
  27117. data.isInstancedBufferGeometry = true;
  27118. return data;
  27119. }
  27120. }
  27121. class BufferGeometryLoader extends Loader {
  27122. constructor( manager ) {
  27123. super( manager );
  27124. }
  27125. load( url, onLoad, onProgress, onError ) {
  27126. const scope = this;
  27127. const loader = new FileLoader( scope.manager );
  27128. loader.setPath( scope.path );
  27129. loader.setRequestHeader( scope.requestHeader );
  27130. loader.setWithCredentials( scope.withCredentials );
  27131. loader.load( url, function ( text ) {
  27132. try {
  27133. onLoad( scope.parse( JSON.parse( text ) ) );
  27134. } catch ( e ) {
  27135. if ( onError ) {
  27136. onError( e );
  27137. } else {
  27138. console.error( e );
  27139. }
  27140. scope.manager.itemError( url );
  27141. }
  27142. }, onProgress, onError );
  27143. }
  27144. parse( json ) {
  27145. const interleavedBufferMap = {};
  27146. const arrayBufferMap = {};
  27147. function getInterleavedBuffer( json, uuid ) {
  27148. if ( interleavedBufferMap[ uuid ] !== undefined ) return interleavedBufferMap[ uuid ];
  27149. const interleavedBuffers = json.interleavedBuffers;
  27150. const interleavedBuffer = interleavedBuffers[ uuid ];
  27151. const buffer = getArrayBuffer( json, interleavedBuffer.buffer );
  27152. const array = getTypedArray( interleavedBuffer.type, buffer );
  27153. const ib = new InterleavedBuffer( array, interleavedBuffer.stride );
  27154. ib.uuid = interleavedBuffer.uuid;
  27155. interleavedBufferMap[ uuid ] = ib;
  27156. return ib;
  27157. }
  27158. function getArrayBuffer( json, uuid ) {
  27159. if ( arrayBufferMap[ uuid ] !== undefined ) return arrayBufferMap[ uuid ];
  27160. const arrayBuffers = json.arrayBuffers;
  27161. const arrayBuffer = arrayBuffers[ uuid ];
  27162. const ab = new Uint32Array( arrayBuffer ).buffer;
  27163. arrayBufferMap[ uuid ] = ab;
  27164. return ab;
  27165. }
  27166. const geometry = json.isInstancedBufferGeometry ? new InstancedBufferGeometry() : new BufferGeometry();
  27167. const index = json.data.index;
  27168. if ( index !== undefined ) {
  27169. const typedArray = getTypedArray( index.type, index.array );
  27170. geometry.setIndex( new BufferAttribute( typedArray, 1 ) );
  27171. }
  27172. const attributes = json.data.attributes;
  27173. for ( const key in attributes ) {
  27174. const attribute = attributes[ key ];
  27175. let bufferAttribute;
  27176. if ( attribute.isInterleavedBufferAttribute ) {
  27177. const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data );
  27178. bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized );
  27179. } else {
  27180. const typedArray = getTypedArray( attribute.type, attribute.array );
  27181. const bufferAttributeConstr = attribute.isInstancedBufferAttribute ? InstancedBufferAttribute : BufferAttribute;
  27182. bufferAttribute = new bufferAttributeConstr( typedArray, attribute.itemSize, attribute.normalized );
  27183. }
  27184. if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name;
  27185. if ( attribute.usage !== undefined ) bufferAttribute.setUsage( attribute.usage );
  27186. geometry.setAttribute( key, bufferAttribute );
  27187. }
  27188. const morphAttributes = json.data.morphAttributes;
  27189. if ( morphAttributes ) {
  27190. for ( const key in morphAttributes ) {
  27191. const attributeArray = morphAttributes[ key ];
  27192. const array = [];
  27193. for ( let i = 0, il = attributeArray.length; i < il; i ++ ) {
  27194. const attribute = attributeArray[ i ];
  27195. let bufferAttribute;
  27196. if ( attribute.isInterleavedBufferAttribute ) {
  27197. const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data );
  27198. bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized );
  27199. } else {
  27200. const typedArray = getTypedArray( attribute.type, attribute.array );
  27201. bufferAttribute = new BufferAttribute( typedArray, attribute.itemSize, attribute.normalized );
  27202. }
  27203. if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name;
  27204. array.push( bufferAttribute );
  27205. }
  27206. geometry.morphAttributes[ key ] = array;
  27207. }
  27208. }
  27209. const morphTargetsRelative = json.data.morphTargetsRelative;
  27210. if ( morphTargetsRelative ) {
  27211. geometry.morphTargetsRelative = true;
  27212. }
  27213. const groups = json.data.groups || json.data.drawcalls || json.data.offsets;
  27214. if ( groups !== undefined ) {
  27215. for ( let i = 0, n = groups.length; i !== n; ++ i ) {
  27216. const group = groups[ i ];
  27217. geometry.addGroup( group.start, group.count, group.materialIndex );
  27218. }
  27219. }
  27220. const boundingSphere = json.data.boundingSphere;
  27221. if ( boundingSphere !== undefined ) {
  27222. const center = new Vector3();
  27223. if ( boundingSphere.center !== undefined ) {
  27224. center.fromArray( boundingSphere.center );
  27225. }
  27226. geometry.boundingSphere = new Sphere( center, boundingSphere.radius );
  27227. }
  27228. if ( json.name ) geometry.name = json.name;
  27229. if ( json.userData ) geometry.userData = json.userData;
  27230. return geometry;
  27231. }
  27232. }
  27233. class ObjectLoader extends Loader {
  27234. constructor( manager ) {
  27235. super( manager );
  27236. }
  27237. load( url, onLoad, onProgress, onError ) {
  27238. const scope = this;
  27239. const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  27240. this.resourcePath = this.resourcePath || path;
  27241. const loader = new FileLoader( this.manager );
  27242. loader.setPath( this.path );
  27243. loader.setRequestHeader( this.requestHeader );
  27244. loader.setWithCredentials( this.withCredentials );
  27245. loader.load( url, function ( text ) {
  27246. let json = null;
  27247. try {
  27248. json = JSON.parse( text );
  27249. } catch ( error ) {
  27250. if ( onError !== undefined ) onError( error );
  27251. console.error( 'THREE:ObjectLoader: Can\'t parse ' + url + '.', error.message );
  27252. return;
  27253. }
  27254. const metadata = json.metadata;
  27255. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  27256. if ( onError !== undefined ) onError( new Error( 'THREE.ObjectLoader: Can\'t load ' + url ) );
  27257. console.error( 'THREE.ObjectLoader: Can\'t load ' + url );
  27258. return;
  27259. }
  27260. scope.parse( json, onLoad );
  27261. }, onProgress, onError );
  27262. }
  27263. async loadAsync( url, onProgress ) {
  27264. const scope = this;
  27265. const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  27266. this.resourcePath = this.resourcePath || path;
  27267. const loader = new FileLoader( this.manager );
  27268. loader.setPath( this.path );
  27269. loader.setRequestHeader( this.requestHeader );
  27270. loader.setWithCredentials( this.withCredentials );
  27271. const text = await loader.loadAsync( url, onProgress );
  27272. const json = JSON.parse( text );
  27273. const metadata = json.metadata;
  27274. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  27275. throw new Error( 'THREE.ObjectLoader: Can\'t load ' + url );
  27276. }
  27277. return await scope.parseAsync( json );
  27278. }
  27279. parse( json, onLoad ) {
  27280. const animations = this.parseAnimations( json.animations );
  27281. const shapes = this.parseShapes( json.shapes );
  27282. const geometries = this.parseGeometries( json.geometries, shapes );
  27283. const images = this.parseImages( json.images, function () {
  27284. if ( onLoad !== undefined ) onLoad( object );
  27285. } );
  27286. const textures = this.parseTextures( json.textures, images );
  27287. const materials = this.parseMaterials( json.materials, textures );
  27288. const object = this.parseObject( json.object, geometries, materials, textures, animations );
  27289. const skeletons = this.parseSkeletons( json.skeletons, object );
  27290. this.bindSkeletons( object, skeletons );
  27291. //
  27292. if ( onLoad !== undefined ) {
  27293. let hasImages = false;
  27294. for ( const uuid in images ) {
  27295. if ( images[ uuid ].data instanceof HTMLImageElement ) {
  27296. hasImages = true;
  27297. break;
  27298. }
  27299. }
  27300. if ( hasImages === false ) onLoad( object );
  27301. }
  27302. return object;
  27303. }
  27304. async parseAsync( json ) {
  27305. const animations = this.parseAnimations( json.animations );
  27306. const shapes = this.parseShapes( json.shapes );
  27307. const geometries = this.parseGeometries( json.geometries, shapes );
  27308. const images = await this.parseImagesAsync( json.images );
  27309. const textures = this.parseTextures( json.textures, images );
  27310. const materials = this.parseMaterials( json.materials, textures );
  27311. const object = this.parseObject( json.object, geometries, materials, textures, animations );
  27312. const skeletons = this.parseSkeletons( json.skeletons, object );
  27313. this.bindSkeletons( object, skeletons );
  27314. return object;
  27315. }
  27316. parseShapes( json ) {
  27317. const shapes = {};
  27318. if ( json !== undefined ) {
  27319. for ( let i = 0, l = json.length; i < l; i ++ ) {
  27320. const shape = new Shape().fromJSON( json[ i ] );
  27321. shapes[ shape.uuid ] = shape;
  27322. }
  27323. }
  27324. return shapes;
  27325. }
  27326. parseSkeletons( json, object ) {
  27327. const skeletons = {};
  27328. const bones = {};
  27329. // generate bone lookup table
  27330. object.traverse( function ( child ) {
  27331. if ( child.isBone ) bones[ child.uuid ] = child;
  27332. } );
  27333. // create skeletons
  27334. if ( json !== undefined ) {
  27335. for ( let i = 0, l = json.length; i < l; i ++ ) {
  27336. const skeleton = new Skeleton().fromJSON( json[ i ], bones );
  27337. skeletons[ skeleton.uuid ] = skeleton;
  27338. }
  27339. }
  27340. return skeletons;
  27341. }
  27342. parseGeometries( json, shapes ) {
  27343. const geometries = {};
  27344. if ( json !== undefined ) {
  27345. const bufferGeometryLoader = new BufferGeometryLoader();
  27346. for ( let i = 0, l = json.length; i < l; i ++ ) {
  27347. let geometry;
  27348. const data = json[ i ];
  27349. switch ( data.type ) {
  27350. case 'BufferGeometry':
  27351. case 'InstancedBufferGeometry':
  27352. geometry = bufferGeometryLoader.parse( data );
  27353. break;
  27354. default:
  27355. if ( data.type in Geometries ) {
  27356. geometry = Geometries[ data.type ].fromJSON( data, shapes );
  27357. } else {
  27358. console.warn( `THREE.ObjectLoader: Unsupported geometry type "${ data.type }"` );
  27359. }
  27360. }
  27361. geometry.uuid = data.uuid;
  27362. if ( data.name !== undefined ) geometry.name = data.name;
  27363. if ( data.userData !== undefined ) geometry.userData = data.userData;
  27364. geometries[ data.uuid ] = geometry;
  27365. }
  27366. }
  27367. return geometries;
  27368. }
  27369. parseMaterials( json, textures ) {
  27370. const cache = {}; // MultiMaterial
  27371. const materials = {};
  27372. if ( json !== undefined ) {
  27373. const loader = new MaterialLoader();
  27374. loader.setTextures( textures );
  27375. for ( let i = 0, l = json.length; i < l; i ++ ) {
  27376. const data = json[ i ];
  27377. if ( cache[ data.uuid ] === undefined ) {
  27378. cache[ data.uuid ] = loader.parse( data );
  27379. }
  27380. materials[ data.uuid ] = cache[ data.uuid ];
  27381. }
  27382. }
  27383. return materials;
  27384. }
  27385. parseAnimations( json ) {
  27386. const animations = {};
  27387. if ( json !== undefined ) {
  27388. for ( let i = 0; i < json.length; i ++ ) {
  27389. const data = json[ i ];
  27390. const clip = AnimationClip.parse( data );
  27391. animations[ clip.uuid ] = clip;
  27392. }
  27393. }
  27394. return animations;
  27395. }
  27396. parseImages( json, onLoad ) {
  27397. const scope = this;
  27398. const images = {};
  27399. let loader;
  27400. function loadImage( url ) {
  27401. scope.manager.itemStart( url );
  27402. return loader.load( url, function () {
  27403. scope.manager.itemEnd( url );
  27404. }, undefined, function () {
  27405. scope.manager.itemError( url );
  27406. scope.manager.itemEnd( url );
  27407. } );
  27408. }
  27409. function deserializeImage( image ) {
  27410. if ( typeof image === 'string' ) {
  27411. const url = image;
  27412. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url;
  27413. return loadImage( path );
  27414. } else {
  27415. if ( image.data ) {
  27416. return {
  27417. data: getTypedArray( image.type, image.data ),
  27418. width: image.width,
  27419. height: image.height
  27420. };
  27421. } else {
  27422. return null;
  27423. }
  27424. }
  27425. }
  27426. if ( json !== undefined && json.length > 0 ) {
  27427. const manager = new LoadingManager( onLoad );
  27428. loader = new ImageLoader( manager );
  27429. loader.setCrossOrigin( this.crossOrigin );
  27430. for ( let i = 0, il = json.length; i < il; i ++ ) {
  27431. const image = json[ i ];
  27432. const url = image.url;
  27433. if ( Array.isArray( url ) ) {
  27434. // load array of images e.g CubeTexture
  27435. const imageArray = [];
  27436. for ( let j = 0, jl = url.length; j < jl; j ++ ) {
  27437. const currentUrl = url[ j ];
  27438. const deserializedImage = deserializeImage( currentUrl );
  27439. if ( deserializedImage !== null ) {
  27440. if ( deserializedImage instanceof HTMLImageElement ) {
  27441. imageArray.push( deserializedImage );
  27442. } else {
  27443. // special case: handle array of data textures for cube textures
  27444. imageArray.push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) );
  27445. }
  27446. }
  27447. }
  27448. images[ image.uuid ] = new Source( imageArray );
  27449. } else {
  27450. // load single image
  27451. const deserializedImage = deserializeImage( image.url );
  27452. images[ image.uuid ] = new Source( deserializedImage );
  27453. }
  27454. }
  27455. }
  27456. return images;
  27457. }
  27458. async parseImagesAsync( json ) {
  27459. const scope = this;
  27460. const images = {};
  27461. let loader;
  27462. async function deserializeImage( image ) {
  27463. if ( typeof image === 'string' ) {
  27464. const url = image;
  27465. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url;
  27466. return await loader.loadAsync( path );
  27467. } else {
  27468. if ( image.data ) {
  27469. return {
  27470. data: getTypedArray( image.type, image.data ),
  27471. width: image.width,
  27472. height: image.height
  27473. };
  27474. } else {
  27475. return null;
  27476. }
  27477. }
  27478. }
  27479. if ( json !== undefined && json.length > 0 ) {
  27480. loader = new ImageLoader( this.manager );
  27481. loader.setCrossOrigin( this.crossOrigin );
  27482. for ( let i = 0, il = json.length; i < il; i ++ ) {
  27483. const image = json[ i ];
  27484. const url = image.url;
  27485. if ( Array.isArray( url ) ) {
  27486. // load array of images e.g CubeTexture
  27487. const imageArray = [];
  27488. for ( let j = 0, jl = url.length; j < jl; j ++ ) {
  27489. const currentUrl = url[ j ];
  27490. const deserializedImage = await deserializeImage( currentUrl );
  27491. if ( deserializedImage !== null ) {
  27492. if ( deserializedImage instanceof HTMLImageElement ) {
  27493. imageArray.push( deserializedImage );
  27494. } else {
  27495. // special case: handle array of data textures for cube textures
  27496. imageArray.push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) );
  27497. }
  27498. }
  27499. }
  27500. images[ image.uuid ] = new Source( imageArray );
  27501. } else {
  27502. // load single image
  27503. const deserializedImage = await deserializeImage( image.url );
  27504. images[ image.uuid ] = new Source( deserializedImage );
  27505. }
  27506. }
  27507. }
  27508. return images;
  27509. }
  27510. parseTextures( json, images ) {
  27511. function parseConstant( value, type ) {
  27512. if ( typeof value === 'number' ) return value;
  27513. console.warn( 'THREE.ObjectLoader.parseTexture: Constant should be in numeric form.', value );
  27514. return type[ value ];
  27515. }
  27516. const textures = {};
  27517. if ( json !== undefined ) {
  27518. for ( let i = 0, l = json.length; i < l; i ++ ) {
  27519. const data = json[ i ];
  27520. if ( data.image === undefined ) {
  27521. console.warn( 'THREE.ObjectLoader: No "image" specified for', data.uuid );
  27522. }
  27523. if ( images[ data.image ] === undefined ) {
  27524. console.warn( 'THREE.ObjectLoader: Undefined image', data.image );
  27525. }
  27526. const source = images[ data.image ];
  27527. const image = source.data;
  27528. let texture;
  27529. if ( Array.isArray( image ) ) {
  27530. texture = new CubeTexture();
  27531. if ( image.length === 6 ) texture.needsUpdate = true;
  27532. } else {
  27533. if ( image && image.data ) {
  27534. texture = new DataTexture();
  27535. } else {
  27536. texture = new Texture();
  27537. }
  27538. if ( image ) texture.needsUpdate = true; // textures can have undefined image data
  27539. }
  27540. texture.source = source;
  27541. texture.uuid = data.uuid;
  27542. if ( data.name !== undefined ) texture.name = data.name;
  27543. if ( data.mapping !== undefined ) texture.mapping = parseConstant( data.mapping, TEXTURE_MAPPING );
  27544. if ( data.channel !== undefined ) texture.channel = data.channel;
  27545. if ( data.offset !== undefined ) texture.offset.fromArray( data.offset );
  27546. if ( data.repeat !== undefined ) texture.repeat.fromArray( data.repeat );
  27547. if ( data.center !== undefined ) texture.center.fromArray( data.center );
  27548. if ( data.rotation !== undefined ) texture.rotation = data.rotation;
  27549. if ( data.wrap !== undefined ) {
  27550. texture.wrapS = parseConstant( data.wrap[ 0 ], TEXTURE_WRAPPING );
  27551. texture.wrapT = parseConstant( data.wrap[ 1 ], TEXTURE_WRAPPING );
  27552. }
  27553. if ( data.format !== undefined ) texture.format = data.format;
  27554. if ( data.internalFormat !== undefined ) texture.internalFormat = data.internalFormat;
  27555. if ( data.type !== undefined ) texture.type = data.type;
  27556. if ( data.colorSpace !== undefined ) texture.colorSpace = data.colorSpace;
  27557. if ( data.minFilter !== undefined ) texture.minFilter = parseConstant( data.minFilter, TEXTURE_FILTER );
  27558. if ( data.magFilter !== undefined ) texture.magFilter = parseConstant( data.magFilter, TEXTURE_FILTER );
  27559. if ( data.anisotropy !== undefined ) texture.anisotropy = data.anisotropy;
  27560. if ( data.flipY !== undefined ) texture.flipY = data.flipY;
  27561. if ( data.generateMipmaps !== undefined ) texture.generateMipmaps = data.generateMipmaps;
  27562. if ( data.premultiplyAlpha !== undefined ) texture.premultiplyAlpha = data.premultiplyAlpha;
  27563. if ( data.unpackAlignment !== undefined ) texture.unpackAlignment = data.unpackAlignment;
  27564. if ( data.compareFunction !== undefined ) texture.compareFunction = data.compareFunction;
  27565. if ( data.userData !== undefined ) texture.userData = data.userData;
  27566. textures[ data.uuid ] = texture;
  27567. }
  27568. }
  27569. return textures;
  27570. }
  27571. parseObject( data, geometries, materials, textures, animations ) {
  27572. let object;
  27573. function getGeometry( name ) {
  27574. if ( geometries[ name ] === undefined ) {
  27575. console.warn( 'THREE.ObjectLoader: Undefined geometry', name );
  27576. }
  27577. return geometries[ name ];
  27578. }
  27579. function getMaterial( name ) {
  27580. if ( name === undefined ) return undefined;
  27581. if ( Array.isArray( name ) ) {
  27582. const array = [];
  27583. for ( let i = 0, l = name.length; i < l; i ++ ) {
  27584. const uuid = name[ i ];
  27585. if ( materials[ uuid ] === undefined ) {
  27586. console.warn( 'THREE.ObjectLoader: Undefined material', uuid );
  27587. }
  27588. array.push( materials[ uuid ] );
  27589. }
  27590. return array;
  27591. }
  27592. if ( materials[ name ] === undefined ) {
  27593. console.warn( 'THREE.ObjectLoader: Undefined material', name );
  27594. }
  27595. return materials[ name ];
  27596. }
  27597. function getTexture( uuid ) {
  27598. if ( textures[ uuid ] === undefined ) {
  27599. console.warn( 'THREE.ObjectLoader: Undefined texture', uuid );
  27600. }
  27601. return textures[ uuid ];
  27602. }
  27603. let geometry, material;
  27604. switch ( data.type ) {
  27605. case 'Scene':
  27606. object = new Scene();
  27607. if ( data.background !== undefined ) {
  27608. if ( Number.isInteger( data.background ) ) {
  27609. object.background = new Color( data.background );
  27610. } else {
  27611. object.background = getTexture( data.background );
  27612. }
  27613. }
  27614. if ( data.environment !== undefined ) {
  27615. object.environment = getTexture( data.environment );
  27616. }
  27617. if ( data.fog !== undefined ) {
  27618. if ( data.fog.type === 'Fog' ) {
  27619. object.fog = new Fog( data.fog.color, data.fog.near, data.fog.far );
  27620. } else if ( data.fog.type === 'FogExp2' ) {
  27621. object.fog = new FogExp2( data.fog.color, data.fog.density );
  27622. }
  27623. if ( data.fog.name !== '' ) {
  27624. object.fog.name = data.fog.name;
  27625. }
  27626. }
  27627. if ( data.backgroundBlurriness !== undefined ) object.backgroundBlurriness = data.backgroundBlurriness;
  27628. if ( data.backgroundIntensity !== undefined ) object.backgroundIntensity = data.backgroundIntensity;
  27629. break;
  27630. case 'PerspectiveCamera':
  27631. object = new PerspectiveCamera( data.fov, data.aspect, data.near, data.far );
  27632. if ( data.focus !== undefined ) object.focus = data.focus;
  27633. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  27634. if ( data.filmGauge !== undefined ) object.filmGauge = data.filmGauge;
  27635. if ( data.filmOffset !== undefined ) object.filmOffset = data.filmOffset;
  27636. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  27637. break;
  27638. case 'OrthographicCamera':
  27639. object = new OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far );
  27640. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  27641. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  27642. break;
  27643. case 'AmbientLight':
  27644. object = new AmbientLight( data.color, data.intensity );
  27645. break;
  27646. case 'DirectionalLight':
  27647. object = new DirectionalLight( data.color, data.intensity );
  27648. break;
  27649. case 'PointLight':
  27650. object = new PointLight( data.color, data.intensity, data.distance, data.decay );
  27651. break;
  27652. case 'RectAreaLight':
  27653. object = new RectAreaLight( data.color, data.intensity, data.width, data.height );
  27654. break;
  27655. case 'SpotLight':
  27656. object = new SpotLight( data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay );
  27657. break;
  27658. case 'HemisphereLight':
  27659. object = new HemisphereLight( data.color, data.groundColor, data.intensity );
  27660. break;
  27661. case 'LightProbe':
  27662. object = new LightProbe().fromJSON( data );
  27663. break;
  27664. case 'SkinnedMesh':
  27665. geometry = getGeometry( data.geometry );
  27666. material = getMaterial( data.material );
  27667. object = new SkinnedMesh( geometry, material );
  27668. if ( data.bindMode !== undefined ) object.bindMode = data.bindMode;
  27669. if ( data.bindMatrix !== undefined ) object.bindMatrix.fromArray( data.bindMatrix );
  27670. if ( data.skeleton !== undefined ) object.skeleton = data.skeleton;
  27671. break;
  27672. case 'Mesh':
  27673. geometry = getGeometry( data.geometry );
  27674. material = getMaterial( data.material );
  27675. object = new Mesh( geometry, material );
  27676. break;
  27677. case 'InstancedMesh':
  27678. geometry = getGeometry( data.geometry );
  27679. material = getMaterial( data.material );
  27680. const count = data.count;
  27681. const instanceMatrix = data.instanceMatrix;
  27682. const instanceColor = data.instanceColor;
  27683. object = new InstancedMesh( geometry, material, count );
  27684. object.instanceMatrix = new InstancedBufferAttribute( new Float32Array( instanceMatrix.array ), 16 );
  27685. if ( instanceColor !== undefined ) object.instanceColor = new InstancedBufferAttribute( new Float32Array( instanceColor.array ), instanceColor.itemSize );
  27686. break;
  27687. case 'BatchedMesh':
  27688. geometry = getGeometry( data.geometry );
  27689. material = getMaterial( data.material );
  27690. object = new BatchedMesh( data.maxGeometryCount, data.maxVertexCount, data.maxIndexCount, material );
  27691. object.geometry = geometry;
  27692. object.perObjectFrustumCulled = data.perObjectFrustumCulled;
  27693. object.sortObjects = data.sortObjects;
  27694. object._drawRanges = data.drawRanges;
  27695. object._reservedRanges = data.reservedRanges;
  27696. object._visibility = data.visibility;
  27697. object._active = data.active;
  27698. object._bounds = data.bounds.map( bound => {
  27699. const box = new Box3();
  27700. box.min.fromArray( bound.boxMin );
  27701. box.max.fromArray( bound.boxMax );
  27702. const sphere = new Sphere();
  27703. sphere.radius = bound.sphereRadius;
  27704. sphere.center.fromArray( bound.sphereCenter );
  27705. return {
  27706. boxInitialized: bound.boxInitialized,
  27707. box: box,
  27708. sphereInitialized: bound.sphereInitialized,
  27709. sphere: sphere
  27710. };
  27711. } );
  27712. object._maxGeometryCount = data.maxGeometryCount;
  27713. object._maxVertexCount = data.maxVertexCount;
  27714. object._maxIndexCount = data.maxIndexCount;
  27715. object._geometryInitialized = data.geometryInitialized;
  27716. object._geometryCount = data.geometryCount;
  27717. object._matricesTexture = getTexture( data.matricesTexture.uuid );
  27718. break;
  27719. case 'LOD':
  27720. object = new LOD();
  27721. break;
  27722. case 'Line':
  27723. object = new Line( getGeometry( data.geometry ), getMaterial( data.material ) );
  27724. break;
  27725. case 'LineLoop':
  27726. object = new LineLoop( getGeometry( data.geometry ), getMaterial( data.material ) );
  27727. break;
  27728. case 'LineSegments':
  27729. object = new LineSegments( getGeometry( data.geometry ), getMaterial( data.material ) );
  27730. break;
  27731. case 'PointCloud':
  27732. case 'Points':
  27733. object = new Points( getGeometry( data.geometry ), getMaterial( data.material ) );
  27734. break;
  27735. case 'Sprite':
  27736. object = new Sprite( getMaterial( data.material ) );
  27737. break;
  27738. case 'Group':
  27739. object = new Group();
  27740. break;
  27741. case 'Bone':
  27742. object = new Bone();
  27743. break;
  27744. default:
  27745. object = new Object3D();
  27746. }
  27747. object.uuid = data.uuid;
  27748. if ( data.name !== undefined ) object.name = data.name;
  27749. if ( data.matrix !== undefined ) {
  27750. object.matrix.fromArray( data.matrix );
  27751. if ( data.matrixAutoUpdate !== undefined ) object.matrixAutoUpdate = data.matrixAutoUpdate;
  27752. if ( object.matrixAutoUpdate ) object.matrix.decompose( object.position, object.quaternion, object.scale );
  27753. } else {
  27754. if ( data.position !== undefined ) object.position.fromArray( data.position );
  27755. if ( data.rotation !== undefined ) object.rotation.fromArray( data.rotation );
  27756. if ( data.quaternion !== undefined ) object.quaternion.fromArray( data.quaternion );
  27757. if ( data.scale !== undefined ) object.scale.fromArray( data.scale );
  27758. }
  27759. if ( data.up !== undefined ) object.up.fromArray( data.up );
  27760. if ( data.castShadow !== undefined ) object.castShadow = data.castShadow;
  27761. if ( data.receiveShadow !== undefined ) object.receiveShadow = data.receiveShadow;
  27762. if ( data.shadow ) {
  27763. if ( data.shadow.bias !== undefined ) object.shadow.bias = data.shadow.bias;
  27764. if ( data.shadow.normalBias !== undefined ) object.shadow.normalBias = data.shadow.normalBias;
  27765. if ( data.shadow.radius !== undefined ) object.shadow.radius = data.shadow.radius;
  27766. if ( data.shadow.mapSize !== undefined ) object.shadow.mapSize.fromArray( data.shadow.mapSize );
  27767. if ( data.shadow.camera !== undefined ) object.shadow.camera = this.parseObject( data.shadow.camera );
  27768. }
  27769. if ( data.visible !== undefined ) object.visible = data.visible;
  27770. if ( data.frustumCulled !== undefined ) object.frustumCulled = data.frustumCulled;
  27771. if ( data.renderOrder !== undefined ) object.renderOrder = data.renderOrder;
  27772. if ( data.userData !== undefined ) object.userData = data.userData;
  27773. if ( data.layers !== undefined ) object.layers.mask = data.layers;
  27774. if ( data.children !== undefined ) {
  27775. const children = data.children;
  27776. for ( let i = 0; i < children.length; i ++ ) {
  27777. object.add( this.parseObject( children[ i ], geometries, materials, textures, animations ) );
  27778. }
  27779. }
  27780. if ( data.animations !== undefined ) {
  27781. const objectAnimations = data.animations;
  27782. for ( let i = 0; i < objectAnimations.length; i ++ ) {
  27783. const uuid = objectAnimations[ i ];
  27784. object.animations.push( animations[ uuid ] );
  27785. }
  27786. }
  27787. if ( data.type === 'LOD' ) {
  27788. if ( data.autoUpdate !== undefined ) object.autoUpdate = data.autoUpdate;
  27789. const levels = data.levels;
  27790. for ( let l = 0; l < levels.length; l ++ ) {
  27791. const level = levels[ l ];
  27792. const child = object.getObjectByProperty( 'uuid', level.object );
  27793. if ( child !== undefined ) {
  27794. object.addLevel( child, level.distance, level.hysteresis );
  27795. }
  27796. }
  27797. }
  27798. return object;
  27799. }
  27800. bindSkeletons( object, skeletons ) {
  27801. if ( Object.keys( skeletons ).length === 0 ) return;
  27802. object.traverse( function ( child ) {
  27803. if ( child.isSkinnedMesh === true && child.skeleton !== undefined ) {
  27804. const skeleton = skeletons[ child.skeleton ];
  27805. if ( skeleton === undefined ) {
  27806. console.warn( 'THREE.ObjectLoader: No skeleton found with UUID:', child.skeleton );
  27807. } else {
  27808. child.bind( skeleton, child.bindMatrix );
  27809. }
  27810. }
  27811. } );
  27812. }
  27813. }
  27814. const TEXTURE_MAPPING = {
  27815. UVMapping: UVMapping,
  27816. CubeReflectionMapping: CubeReflectionMapping,
  27817. CubeRefractionMapping: CubeRefractionMapping,
  27818. EquirectangularReflectionMapping: EquirectangularReflectionMapping,
  27819. EquirectangularRefractionMapping: EquirectangularRefractionMapping,
  27820. CubeUVReflectionMapping: CubeUVReflectionMapping
  27821. };
  27822. const TEXTURE_WRAPPING = {
  27823. RepeatWrapping: RepeatWrapping,
  27824. ClampToEdgeWrapping: ClampToEdgeWrapping,
  27825. MirroredRepeatWrapping: MirroredRepeatWrapping
  27826. };
  27827. const TEXTURE_FILTER = {
  27828. NearestFilter: NearestFilter,
  27829. NearestMipmapNearestFilter: NearestMipmapNearestFilter,
  27830. NearestMipmapLinearFilter: NearestMipmapLinearFilter,
  27831. LinearFilter: LinearFilter,
  27832. LinearMipmapNearestFilter: LinearMipmapNearestFilter,
  27833. LinearMipmapLinearFilter: LinearMipmapLinearFilter
  27834. };
  27835. class ImageBitmapLoader extends Loader {
  27836. constructor( manager ) {
  27837. super( manager );
  27838. this.isImageBitmapLoader = true;
  27839. if ( typeof createImageBitmap === 'undefined' ) {
  27840. console.warn( 'THREE.ImageBitmapLoader: createImageBitmap() not supported.' );
  27841. }
  27842. if ( typeof fetch === 'undefined' ) {
  27843. console.warn( 'THREE.ImageBitmapLoader: fetch() not supported.' );
  27844. }
  27845. this.options = { premultiplyAlpha: 'none' };
  27846. }
  27847. setOptions( options ) {
  27848. this.options = options;
  27849. return this;
  27850. }
  27851. load( url, onLoad, onProgress, onError ) {
  27852. if ( url === undefined ) url = '';
  27853. if ( this.path !== undefined ) url = this.path + url;
  27854. url = this.manager.resolveURL( url );
  27855. const scope = this;
  27856. const cached = Cache.get( url );
  27857. if ( cached !== undefined ) {
  27858. scope.manager.itemStart( url );
  27859. // If cached is a promise, wait for it to resolve
  27860. if ( cached.then ) {
  27861. cached.then( imageBitmap => {
  27862. if ( onLoad ) onLoad( imageBitmap );
  27863. scope.manager.itemEnd( url );
  27864. } ).catch( e => {
  27865. if ( onError ) onError( e );
  27866. } );
  27867. return;
  27868. }
  27869. // If cached is not a promise (i.e., it's already an imageBitmap)
  27870. setTimeout( function () {
  27871. if ( onLoad ) onLoad( cached );
  27872. scope.manager.itemEnd( url );
  27873. }, 0 );
  27874. return cached;
  27875. }
  27876. const fetchOptions = {};
  27877. fetchOptions.credentials = ( this.crossOrigin === 'anonymous' ) ? 'same-origin' : 'include';
  27878. fetchOptions.headers = this.requestHeader;
  27879. const promise = fetch( url, fetchOptions ).then( function ( res ) {
  27880. return res.blob();
  27881. } ).then( function ( blob ) {
  27882. return createImageBitmap( blob, Object.assign( scope.options, { colorSpaceConversion: 'none' } ) );
  27883. } ).then( function ( imageBitmap ) {
  27884. Cache.add( url, imageBitmap );
  27885. if ( onLoad ) onLoad( imageBitmap );
  27886. scope.manager.itemEnd( url );
  27887. return imageBitmap;
  27888. } ).catch( function ( e ) {
  27889. if ( onError ) onError( e );
  27890. Cache.remove( url );
  27891. scope.manager.itemError( url );
  27892. scope.manager.itemEnd( url );
  27893. } );
  27894. Cache.add( url, promise );
  27895. scope.manager.itemStart( url );
  27896. }
  27897. }
  27898. let _context;
  27899. class AudioContext {
  27900. static getContext() {
  27901. if ( _context === undefined ) {
  27902. _context = new ( window.AudioContext || window.webkitAudioContext )();
  27903. }
  27904. return _context;
  27905. }
  27906. static setContext( value ) {
  27907. _context = value;
  27908. }
  27909. }
  27910. class AudioLoader extends Loader {
  27911. constructor( manager ) {
  27912. super( manager );
  27913. }
  27914. load( url, onLoad, onProgress, onError ) {
  27915. const scope = this;
  27916. const loader = new FileLoader( this.manager );
  27917. loader.setResponseType( 'arraybuffer' );
  27918. loader.setPath( this.path );
  27919. loader.setRequestHeader( this.requestHeader );
  27920. loader.setWithCredentials( this.withCredentials );
  27921. loader.load( url, function ( buffer ) {
  27922. try {
  27923. // Create a copy of the buffer. The `decodeAudioData` method
  27924. // detaches the buffer when complete, preventing reuse.
  27925. const bufferCopy = buffer.slice( 0 );
  27926. const context = AudioContext.getContext();
  27927. context.decodeAudioData( bufferCopy, function ( audioBuffer ) {
  27928. onLoad( audioBuffer );
  27929. } ).catch( handleError );
  27930. } catch ( e ) {
  27931. handleError( e );
  27932. }
  27933. }, onProgress, onError );
  27934. function handleError( e ) {
  27935. if ( onError ) {
  27936. onError( e );
  27937. } else {
  27938. console.error( e );
  27939. }
  27940. scope.manager.itemError( url );
  27941. }
  27942. }
  27943. }
  27944. const _eyeRight = /*@__PURE__*/ new Matrix4();
  27945. const _eyeLeft = /*@__PURE__*/ new Matrix4();
  27946. const _projectionMatrix = /*@__PURE__*/ new Matrix4();
  27947. class StereoCamera {
  27948. constructor() {
  27949. this.type = 'StereoCamera';
  27950. this.aspect = 1;
  27951. this.eyeSep = 0.064;
  27952. this.cameraL = new PerspectiveCamera();
  27953. this.cameraL.layers.enable( 1 );
  27954. this.cameraL.matrixAutoUpdate = false;
  27955. this.cameraR = new PerspectiveCamera();
  27956. this.cameraR.layers.enable( 2 );
  27957. this.cameraR.matrixAutoUpdate = false;
  27958. this._cache = {
  27959. focus: null,
  27960. fov: null,
  27961. aspect: null,
  27962. near: null,
  27963. far: null,
  27964. zoom: null,
  27965. eyeSep: null
  27966. };
  27967. }
  27968. update( camera ) {
  27969. const cache = this._cache;
  27970. const needsUpdate = cache.focus !== camera.focus || cache.fov !== camera.fov ||
  27971. cache.aspect !== camera.aspect * this.aspect || cache.near !== camera.near ||
  27972. cache.far !== camera.far || cache.zoom !== camera.zoom || cache.eyeSep !== this.eyeSep;
  27973. if ( needsUpdate ) {
  27974. cache.focus = camera.focus;
  27975. cache.fov = camera.fov;
  27976. cache.aspect = camera.aspect * this.aspect;
  27977. cache.near = camera.near;
  27978. cache.far = camera.far;
  27979. cache.zoom = camera.zoom;
  27980. cache.eyeSep = this.eyeSep;
  27981. // Off-axis stereoscopic effect based on
  27982. // http://paulbourke.net/stereographics/stereorender/
  27983. _projectionMatrix.copy( camera.projectionMatrix );
  27984. const eyeSepHalf = cache.eyeSep / 2;
  27985. const eyeSepOnProjection = eyeSepHalf * cache.near / cache.focus;
  27986. const ymax = ( cache.near * Math.tan( DEG2RAD * cache.fov * 0.5 ) ) / cache.zoom;
  27987. let xmin, xmax;
  27988. // translate xOffset
  27989. _eyeLeft.elements[ 12 ] = - eyeSepHalf;
  27990. _eyeRight.elements[ 12 ] = eyeSepHalf;
  27991. // for left eye
  27992. xmin = - ymax * cache.aspect + eyeSepOnProjection;
  27993. xmax = ymax * cache.aspect + eyeSepOnProjection;
  27994. _projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
  27995. _projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  27996. this.cameraL.projectionMatrix.copy( _projectionMatrix );
  27997. // for right eye
  27998. xmin = - ymax * cache.aspect - eyeSepOnProjection;
  27999. xmax = ymax * cache.aspect - eyeSepOnProjection;
  28000. _projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
  28001. _projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  28002. this.cameraR.projectionMatrix.copy( _projectionMatrix );
  28003. }
  28004. this.cameraL.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeLeft );
  28005. this.cameraR.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeRight );
  28006. }
  28007. }
  28008. class Clock {
  28009. constructor( autoStart = true ) {
  28010. this.autoStart = autoStart;
  28011. this.startTime = 0;
  28012. this.oldTime = 0;
  28013. this.elapsedTime = 0;
  28014. this.running = false;
  28015. }
  28016. start() {
  28017. this.startTime = now();
  28018. this.oldTime = this.startTime;
  28019. this.elapsedTime = 0;
  28020. this.running = true;
  28021. }
  28022. stop() {
  28023. this.getElapsedTime();
  28024. this.running = false;
  28025. this.autoStart = false;
  28026. }
  28027. getElapsedTime() {
  28028. this.getDelta();
  28029. return this.elapsedTime;
  28030. }
  28031. getDelta() {
  28032. let diff = 0;
  28033. if ( this.autoStart && ! this.running ) {
  28034. this.start();
  28035. return 0;
  28036. }
  28037. if ( this.running ) {
  28038. const newTime = now();
  28039. diff = ( newTime - this.oldTime ) / 1000;
  28040. this.oldTime = newTime;
  28041. this.elapsedTime += diff;
  28042. }
  28043. return diff;
  28044. }
  28045. }
  28046. function now() {
  28047. return ( typeof performance === 'undefined' ? Date : performance ).now(); // see #10732
  28048. }
  28049. const _position$1 = /*@__PURE__*/ new Vector3();
  28050. const _quaternion$1 = /*@__PURE__*/ new Quaternion();
  28051. const _scale$1 = /*@__PURE__*/ new Vector3();
  28052. const _orientation$1 = /*@__PURE__*/ new Vector3();
  28053. class AudioListener extends Object3D {
  28054. constructor() {
  28055. super();
  28056. this.type = 'AudioListener';
  28057. this.context = AudioContext.getContext();
  28058. this.gain = this.context.createGain();
  28059. this.gain.connect( this.context.destination );
  28060. this.filter = null;
  28061. this.timeDelta = 0;
  28062. // private
  28063. this._clock = new Clock();
  28064. }
  28065. getInput() {
  28066. return this.gain;
  28067. }
  28068. removeFilter() {
  28069. if ( this.filter !== null ) {
  28070. this.gain.disconnect( this.filter );
  28071. this.filter.disconnect( this.context.destination );
  28072. this.gain.connect( this.context.destination );
  28073. this.filter = null;
  28074. }
  28075. return this;
  28076. }
  28077. getFilter() {
  28078. return this.filter;
  28079. }
  28080. setFilter( value ) {
  28081. if ( this.filter !== null ) {
  28082. this.gain.disconnect( this.filter );
  28083. this.filter.disconnect( this.context.destination );
  28084. } else {
  28085. this.gain.disconnect( this.context.destination );
  28086. }
  28087. this.filter = value;
  28088. this.gain.connect( this.filter );
  28089. this.filter.connect( this.context.destination );
  28090. return this;
  28091. }
  28092. getMasterVolume() {
  28093. return this.gain.gain.value;
  28094. }
  28095. setMasterVolume( value ) {
  28096. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  28097. return this;
  28098. }
  28099. updateMatrixWorld( force ) {
  28100. super.updateMatrixWorld( force );
  28101. const listener = this.context.listener;
  28102. const up = this.up;
  28103. this.timeDelta = this._clock.getDelta();
  28104. this.matrixWorld.decompose( _position$1, _quaternion$1, _scale$1 );
  28105. _orientation$1.set( 0, 0, - 1 ).applyQuaternion( _quaternion$1 );
  28106. if ( listener.positionX ) {
  28107. // code path for Chrome (see #14393)
  28108. const endTime = this.context.currentTime + this.timeDelta;
  28109. listener.positionX.linearRampToValueAtTime( _position$1.x, endTime );
  28110. listener.positionY.linearRampToValueAtTime( _position$1.y, endTime );
  28111. listener.positionZ.linearRampToValueAtTime( _position$1.z, endTime );
  28112. listener.forwardX.linearRampToValueAtTime( _orientation$1.x, endTime );
  28113. listener.forwardY.linearRampToValueAtTime( _orientation$1.y, endTime );
  28114. listener.forwardZ.linearRampToValueAtTime( _orientation$1.z, endTime );
  28115. listener.upX.linearRampToValueAtTime( up.x, endTime );
  28116. listener.upY.linearRampToValueAtTime( up.y, endTime );
  28117. listener.upZ.linearRampToValueAtTime( up.z, endTime );
  28118. } else {
  28119. listener.setPosition( _position$1.x, _position$1.y, _position$1.z );
  28120. listener.setOrientation( _orientation$1.x, _orientation$1.y, _orientation$1.z, up.x, up.y, up.z );
  28121. }
  28122. }
  28123. }
  28124. class Audio extends Object3D {
  28125. constructor( listener ) {
  28126. super();
  28127. this.type = 'Audio';
  28128. this.listener = listener;
  28129. this.context = listener.context;
  28130. this.gain = this.context.createGain();
  28131. this.gain.connect( listener.getInput() );
  28132. this.autoplay = false;
  28133. this.buffer = null;
  28134. this.detune = 0;
  28135. this.loop = false;
  28136. this.loopStart = 0;
  28137. this.loopEnd = 0;
  28138. this.offset = 0;
  28139. this.duration = undefined;
  28140. this.playbackRate = 1;
  28141. this.isPlaying = false;
  28142. this.hasPlaybackControl = true;
  28143. this.source = null;
  28144. this.sourceType = 'empty';
  28145. this._startedAt = 0;
  28146. this._progress = 0;
  28147. this._connected = false;
  28148. this.filters = [];
  28149. }
  28150. getOutput() {
  28151. return this.gain;
  28152. }
  28153. setNodeSource( audioNode ) {
  28154. this.hasPlaybackControl = false;
  28155. this.sourceType = 'audioNode';
  28156. this.source = audioNode;
  28157. this.connect();
  28158. return this;
  28159. }
  28160. setMediaElementSource( mediaElement ) {
  28161. this.hasPlaybackControl = false;
  28162. this.sourceType = 'mediaNode';
  28163. this.source = this.context.createMediaElementSource( mediaElement );
  28164. this.connect();
  28165. return this;
  28166. }
  28167. setMediaStreamSource( mediaStream ) {
  28168. this.hasPlaybackControl = false;
  28169. this.sourceType = 'mediaStreamNode';
  28170. this.source = this.context.createMediaStreamSource( mediaStream );
  28171. this.connect();
  28172. return this;
  28173. }
  28174. setBuffer( audioBuffer ) {
  28175. this.buffer = audioBuffer;
  28176. this.sourceType = 'buffer';
  28177. if ( this.autoplay ) this.play();
  28178. return this;
  28179. }
  28180. play( delay = 0 ) {
  28181. if ( this.isPlaying === true ) {
  28182. console.warn( 'THREE.Audio: Audio is already playing.' );
  28183. return;
  28184. }
  28185. if ( this.hasPlaybackControl === false ) {
  28186. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  28187. return;
  28188. }
  28189. this._startedAt = this.context.currentTime + delay;
  28190. const source = this.context.createBufferSource();
  28191. source.buffer = this.buffer;
  28192. source.loop = this.loop;
  28193. source.loopStart = this.loopStart;
  28194. source.loopEnd = this.loopEnd;
  28195. source.onended = this.onEnded.bind( this );
  28196. source.start( this._startedAt, this._progress + this.offset, this.duration );
  28197. this.isPlaying = true;
  28198. this.source = source;
  28199. this.setDetune( this.detune );
  28200. this.setPlaybackRate( this.playbackRate );
  28201. return this.connect();
  28202. }
  28203. pause() {
  28204. if ( this.hasPlaybackControl === false ) {
  28205. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  28206. return;
  28207. }
  28208. if ( this.isPlaying === true ) {
  28209. // update current progress
  28210. this._progress += Math.max( this.context.currentTime - this._startedAt, 0 ) * this.playbackRate;
  28211. if ( this.loop === true ) {
  28212. // ensure _progress does not exceed duration with looped audios
  28213. this._progress = this._progress % ( this.duration || this.buffer.duration );
  28214. }
  28215. this.source.stop();
  28216. this.source.onended = null;
  28217. this.isPlaying = false;
  28218. }
  28219. return this;
  28220. }
  28221. stop() {
  28222. if ( this.hasPlaybackControl === false ) {
  28223. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  28224. return;
  28225. }
  28226. this._progress = 0;
  28227. if ( this.source !== null ) {
  28228. this.source.stop();
  28229. this.source.onended = null;
  28230. }
  28231. this.isPlaying = false;
  28232. return this;
  28233. }
  28234. connect() {
  28235. if ( this.filters.length > 0 ) {
  28236. this.source.connect( this.filters[ 0 ] );
  28237. for ( let i = 1, l = this.filters.length; i < l; i ++ ) {
  28238. this.filters[ i - 1 ].connect( this.filters[ i ] );
  28239. }
  28240. this.filters[ this.filters.length - 1 ].connect( this.getOutput() );
  28241. } else {
  28242. this.source.connect( this.getOutput() );
  28243. }
  28244. this._connected = true;
  28245. return this;
  28246. }
  28247. disconnect() {
  28248. if ( this._connected === false ) {
  28249. return;
  28250. }
  28251. if ( this.filters.length > 0 ) {
  28252. this.source.disconnect( this.filters[ 0 ] );
  28253. for ( let i = 1, l = this.filters.length; i < l; i ++ ) {
  28254. this.filters[ i - 1 ].disconnect( this.filters[ i ] );
  28255. }
  28256. this.filters[ this.filters.length - 1 ].disconnect( this.getOutput() );
  28257. } else {
  28258. this.source.disconnect( this.getOutput() );
  28259. }
  28260. this._connected = false;
  28261. return this;
  28262. }
  28263. getFilters() {
  28264. return this.filters;
  28265. }
  28266. setFilters( value ) {
  28267. if ( ! value ) value = [];
  28268. if ( this._connected === true ) {
  28269. this.disconnect();
  28270. this.filters = value.slice();
  28271. this.connect();
  28272. } else {
  28273. this.filters = value.slice();
  28274. }
  28275. return this;
  28276. }
  28277. setDetune( value ) {
  28278. this.detune = value;
  28279. if ( this.isPlaying === true && this.source.detune !== undefined ) {
  28280. this.source.detune.setTargetAtTime( this.detune, this.context.currentTime, 0.01 );
  28281. }
  28282. return this;
  28283. }
  28284. getDetune() {
  28285. return this.detune;
  28286. }
  28287. getFilter() {
  28288. return this.getFilters()[ 0 ];
  28289. }
  28290. setFilter( filter ) {
  28291. return this.setFilters( filter ? [ filter ] : [] );
  28292. }
  28293. setPlaybackRate( value ) {
  28294. if ( this.hasPlaybackControl === false ) {
  28295. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  28296. return;
  28297. }
  28298. this.playbackRate = value;
  28299. if ( this.isPlaying === true ) {
  28300. this.source.playbackRate.setTargetAtTime( this.playbackRate, this.context.currentTime, 0.01 );
  28301. }
  28302. return this;
  28303. }
  28304. getPlaybackRate() {
  28305. return this.playbackRate;
  28306. }
  28307. onEnded() {
  28308. this.isPlaying = false;
  28309. }
  28310. getLoop() {
  28311. if ( this.hasPlaybackControl === false ) {
  28312. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  28313. return false;
  28314. }
  28315. return this.loop;
  28316. }
  28317. setLoop( value ) {
  28318. if ( this.hasPlaybackControl === false ) {
  28319. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  28320. return;
  28321. }
  28322. this.loop = value;
  28323. if ( this.isPlaying === true ) {
  28324. this.source.loop = this.loop;
  28325. }
  28326. return this;
  28327. }
  28328. setLoopStart( value ) {
  28329. this.loopStart = value;
  28330. return this;
  28331. }
  28332. setLoopEnd( value ) {
  28333. this.loopEnd = value;
  28334. return this;
  28335. }
  28336. getVolume() {
  28337. return this.gain.gain.value;
  28338. }
  28339. setVolume( value ) {
  28340. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  28341. return this;
  28342. }
  28343. }
  28344. const _position = /*@__PURE__*/ new Vector3();
  28345. const _quaternion = /*@__PURE__*/ new Quaternion();
  28346. const _scale = /*@__PURE__*/ new Vector3();
  28347. const _orientation = /*@__PURE__*/ new Vector3();
  28348. class PositionalAudio extends Audio {
  28349. constructor( listener ) {
  28350. super( listener );
  28351. this.panner = this.context.createPanner();
  28352. this.panner.panningModel = 'HRTF';
  28353. this.panner.connect( this.gain );
  28354. }
  28355. connect() {
  28356. super.connect();
  28357. this.panner.connect( this.gain );
  28358. }
  28359. disconnect() {
  28360. super.disconnect();
  28361. this.panner.disconnect( this.gain );
  28362. }
  28363. getOutput() {
  28364. return this.panner;
  28365. }
  28366. getRefDistance() {
  28367. return this.panner.refDistance;
  28368. }
  28369. setRefDistance( value ) {
  28370. this.panner.refDistance = value;
  28371. return this;
  28372. }
  28373. getRolloffFactor() {
  28374. return this.panner.rolloffFactor;
  28375. }
  28376. setRolloffFactor( value ) {
  28377. this.panner.rolloffFactor = value;
  28378. return this;
  28379. }
  28380. getDistanceModel() {
  28381. return this.panner.distanceModel;
  28382. }
  28383. setDistanceModel( value ) {
  28384. this.panner.distanceModel = value;
  28385. return this;
  28386. }
  28387. getMaxDistance() {
  28388. return this.panner.maxDistance;
  28389. }
  28390. setMaxDistance( value ) {
  28391. this.panner.maxDistance = value;
  28392. return this;
  28393. }
  28394. setDirectionalCone( coneInnerAngle, coneOuterAngle, coneOuterGain ) {
  28395. this.panner.coneInnerAngle = coneInnerAngle;
  28396. this.panner.coneOuterAngle = coneOuterAngle;
  28397. this.panner.coneOuterGain = coneOuterGain;
  28398. return this;
  28399. }
  28400. updateMatrixWorld( force ) {
  28401. super.updateMatrixWorld( force );
  28402. if ( this.hasPlaybackControl === true && this.isPlaying === false ) return;
  28403. this.matrixWorld.decompose( _position, _quaternion, _scale );
  28404. _orientation.set( 0, 0, 1 ).applyQuaternion( _quaternion );
  28405. const panner = this.panner;
  28406. if ( panner.positionX ) {
  28407. // code path for Chrome and Firefox (see #14393)
  28408. const endTime = this.context.currentTime + this.listener.timeDelta;
  28409. panner.positionX.linearRampToValueAtTime( _position.x, endTime );
  28410. panner.positionY.linearRampToValueAtTime( _position.y, endTime );
  28411. panner.positionZ.linearRampToValueAtTime( _position.z, endTime );
  28412. panner.orientationX.linearRampToValueAtTime( _orientation.x, endTime );
  28413. panner.orientationY.linearRampToValueAtTime( _orientation.y, endTime );
  28414. panner.orientationZ.linearRampToValueAtTime( _orientation.z, endTime );
  28415. } else {
  28416. panner.setPosition( _position.x, _position.y, _position.z );
  28417. panner.setOrientation( _orientation.x, _orientation.y, _orientation.z );
  28418. }
  28419. }
  28420. }
  28421. class AudioAnalyser {
  28422. constructor( audio, fftSize = 2048 ) {
  28423. this.analyser = audio.context.createAnalyser();
  28424. this.analyser.fftSize = fftSize;
  28425. this.data = new Uint8Array( this.analyser.frequencyBinCount );
  28426. audio.getOutput().connect( this.analyser );
  28427. }
  28428. getFrequencyData() {
  28429. this.analyser.getByteFrequencyData( this.data );
  28430. return this.data;
  28431. }
  28432. getAverageFrequency() {
  28433. let value = 0;
  28434. const data = this.getFrequencyData();
  28435. for ( let i = 0; i < data.length; i ++ ) {
  28436. value += data[ i ];
  28437. }
  28438. return value / data.length;
  28439. }
  28440. }
  28441. class PropertyMixer {
  28442. constructor( binding, typeName, valueSize ) {
  28443. this.binding = binding;
  28444. this.valueSize = valueSize;
  28445. let mixFunction,
  28446. mixFunctionAdditive,
  28447. setIdentity;
  28448. // buffer layout: [ incoming | accu0 | accu1 | orig | addAccu | (optional work) ]
  28449. //
  28450. // interpolators can use .buffer as their .result
  28451. // the data then goes to 'incoming'
  28452. //
  28453. // 'accu0' and 'accu1' are used frame-interleaved for
  28454. // the cumulative result and are compared to detect
  28455. // changes
  28456. //
  28457. // 'orig' stores the original state of the property
  28458. //
  28459. // 'add' is used for additive cumulative results
  28460. //
  28461. // 'work' is optional and is only present for quaternion types. It is used
  28462. // to store intermediate quaternion multiplication results
  28463. switch ( typeName ) {
  28464. case 'quaternion':
  28465. mixFunction = this._slerp;
  28466. mixFunctionAdditive = this._slerpAdditive;
  28467. setIdentity = this._setAdditiveIdentityQuaternion;
  28468. this.buffer = new Float64Array( valueSize * 6 );
  28469. this._workIndex = 5;
  28470. break;
  28471. case 'string':
  28472. case 'bool':
  28473. mixFunction = this._select;
  28474. // Use the regular mix function and for additive on these types,
  28475. // additive is not relevant for non-numeric types
  28476. mixFunctionAdditive = this._select;
  28477. setIdentity = this._setAdditiveIdentityOther;
  28478. this.buffer = new Array( valueSize * 5 );
  28479. break;
  28480. default:
  28481. mixFunction = this._lerp;
  28482. mixFunctionAdditive = this._lerpAdditive;
  28483. setIdentity = this._setAdditiveIdentityNumeric;
  28484. this.buffer = new Float64Array( valueSize * 5 );
  28485. }
  28486. this._mixBufferRegion = mixFunction;
  28487. this._mixBufferRegionAdditive = mixFunctionAdditive;
  28488. this._setIdentity = setIdentity;
  28489. this._origIndex = 3;
  28490. this._addIndex = 4;
  28491. this.cumulativeWeight = 0;
  28492. this.cumulativeWeightAdditive = 0;
  28493. this.useCount = 0;
  28494. this.referenceCount = 0;
  28495. }
  28496. // accumulate data in the 'incoming' region into 'accu<i>'
  28497. accumulate( accuIndex, weight ) {
  28498. // note: happily accumulating nothing when weight = 0, the caller knows
  28499. // the weight and shouldn't have made the call in the first place
  28500. const buffer = this.buffer,
  28501. stride = this.valueSize,
  28502. offset = accuIndex * stride + stride;
  28503. let currentWeight = this.cumulativeWeight;
  28504. if ( currentWeight === 0 ) {
  28505. // accuN := incoming * weight
  28506. for ( let i = 0; i !== stride; ++ i ) {
  28507. buffer[ offset + i ] = buffer[ i ];
  28508. }
  28509. currentWeight = weight;
  28510. } else {
  28511. // accuN := accuN + incoming * weight
  28512. currentWeight += weight;
  28513. const mix = weight / currentWeight;
  28514. this._mixBufferRegion( buffer, offset, 0, mix, stride );
  28515. }
  28516. this.cumulativeWeight = currentWeight;
  28517. }
  28518. // accumulate data in the 'incoming' region into 'add'
  28519. accumulateAdditive( weight ) {
  28520. const buffer = this.buffer,
  28521. stride = this.valueSize,
  28522. offset = stride * this._addIndex;
  28523. if ( this.cumulativeWeightAdditive === 0 ) {
  28524. // add = identity
  28525. this._setIdentity();
  28526. }
  28527. // add := add + incoming * weight
  28528. this._mixBufferRegionAdditive( buffer, offset, 0, weight, stride );
  28529. this.cumulativeWeightAdditive += weight;
  28530. }
  28531. // apply the state of 'accu<i>' to the binding when accus differ
  28532. apply( accuIndex ) {
  28533. const stride = this.valueSize,
  28534. buffer = this.buffer,
  28535. offset = accuIndex * stride + stride,
  28536. weight = this.cumulativeWeight,
  28537. weightAdditive = this.cumulativeWeightAdditive,
  28538. binding = this.binding;
  28539. this.cumulativeWeight = 0;
  28540. this.cumulativeWeightAdditive = 0;
  28541. if ( weight < 1 ) {
  28542. // accuN := accuN + original * ( 1 - cumulativeWeight )
  28543. const originalValueOffset = stride * this._origIndex;
  28544. this._mixBufferRegion(
  28545. buffer, offset, originalValueOffset, 1 - weight, stride );
  28546. }
  28547. if ( weightAdditive > 0 ) {
  28548. // accuN := accuN + additive accuN
  28549. this._mixBufferRegionAdditive( buffer, offset, this._addIndex * stride, 1, stride );
  28550. }
  28551. for ( let i = stride, e = stride + stride; i !== e; ++ i ) {
  28552. if ( buffer[ i ] !== buffer[ i + stride ] ) {
  28553. // value has changed -> update scene graph
  28554. binding.setValue( buffer, offset );
  28555. break;
  28556. }
  28557. }
  28558. }
  28559. // remember the state of the bound property and copy it to both accus
  28560. saveOriginalState() {
  28561. const binding = this.binding;
  28562. const buffer = this.buffer,
  28563. stride = this.valueSize,
  28564. originalValueOffset = stride * this._origIndex;
  28565. binding.getValue( buffer, originalValueOffset );
  28566. // accu[0..1] := orig -- initially detect changes against the original
  28567. for ( let i = stride, e = originalValueOffset; i !== e; ++ i ) {
  28568. buffer[ i ] = buffer[ originalValueOffset + ( i % stride ) ];
  28569. }
  28570. // Add to identity for additive
  28571. this._setIdentity();
  28572. this.cumulativeWeight = 0;
  28573. this.cumulativeWeightAdditive = 0;
  28574. }
  28575. // apply the state previously taken via 'saveOriginalState' to the binding
  28576. restoreOriginalState() {
  28577. const originalValueOffset = this.valueSize * 3;
  28578. this.binding.setValue( this.buffer, originalValueOffset );
  28579. }
  28580. _setAdditiveIdentityNumeric() {
  28581. const startIndex = this._addIndex * this.valueSize;
  28582. const endIndex = startIndex + this.valueSize;
  28583. for ( let i = startIndex; i < endIndex; i ++ ) {
  28584. this.buffer[ i ] = 0;
  28585. }
  28586. }
  28587. _setAdditiveIdentityQuaternion() {
  28588. this._setAdditiveIdentityNumeric();
  28589. this.buffer[ this._addIndex * this.valueSize + 3 ] = 1;
  28590. }
  28591. _setAdditiveIdentityOther() {
  28592. const startIndex = this._origIndex * this.valueSize;
  28593. const targetIndex = this._addIndex * this.valueSize;
  28594. for ( let i = 0; i < this.valueSize; i ++ ) {
  28595. this.buffer[ targetIndex + i ] = this.buffer[ startIndex + i ];
  28596. }
  28597. }
  28598. // mix functions
  28599. _select( buffer, dstOffset, srcOffset, t, stride ) {
  28600. if ( t >= 0.5 ) {
  28601. for ( let i = 0; i !== stride; ++ i ) {
  28602. buffer[ dstOffset + i ] = buffer[ srcOffset + i ];
  28603. }
  28604. }
  28605. }
  28606. _slerp( buffer, dstOffset, srcOffset, t ) {
  28607. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, srcOffset, t );
  28608. }
  28609. _slerpAdditive( buffer, dstOffset, srcOffset, t, stride ) {
  28610. const workOffset = this._workIndex * stride;
  28611. // Store result in intermediate buffer offset
  28612. Quaternion.multiplyQuaternionsFlat( buffer, workOffset, buffer, dstOffset, buffer, srcOffset );
  28613. // Slerp to the intermediate result
  28614. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, workOffset, t );
  28615. }
  28616. _lerp( buffer, dstOffset, srcOffset, t, stride ) {
  28617. const s = 1 - t;
  28618. for ( let i = 0; i !== stride; ++ i ) {
  28619. const j = dstOffset + i;
  28620. buffer[ j ] = buffer[ j ] * s + buffer[ srcOffset + i ] * t;
  28621. }
  28622. }
  28623. _lerpAdditive( buffer, dstOffset, srcOffset, t, stride ) {
  28624. for ( let i = 0; i !== stride; ++ i ) {
  28625. const j = dstOffset + i;
  28626. buffer[ j ] = buffer[ j ] + buffer[ srcOffset + i ] * t;
  28627. }
  28628. }
  28629. }
  28630. // Characters [].:/ are reserved for track binding syntax.
  28631. const _RESERVED_CHARS_RE = '\\[\\]\\.:\\/';
  28632. const _reservedRe = new RegExp( '[' + _RESERVED_CHARS_RE + ']', 'g' );
  28633. // Attempts to allow node names from any language. ES5's `\w` regexp matches
  28634. // only latin characters, and the unicode \p{L} is not yet supported. So
  28635. // instead, we exclude reserved characters and match everything else.
  28636. const _wordChar = '[^' + _RESERVED_CHARS_RE + ']';
  28637. const _wordCharOrDot = '[^' + _RESERVED_CHARS_RE.replace( '\\.', '' ) + ']';
  28638. // Parent directories, delimited by '/' or ':'. Currently unused, but must
  28639. // be matched to parse the rest of the track name.
  28640. const _directoryRe = /*@__PURE__*/ /((?:WC+[\/:])*)/.source.replace( 'WC', _wordChar );
  28641. // Target node. May contain word characters (a-zA-Z0-9_) and '.' or '-'.
  28642. const _nodeRe = /*@__PURE__*/ /(WCOD+)?/.source.replace( 'WCOD', _wordCharOrDot );
  28643. // Object on target node, and accessor. May not contain reserved
  28644. // characters. Accessor may contain any character except closing bracket.
  28645. const _objectRe = /*@__PURE__*/ /(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace( 'WC', _wordChar );
  28646. // Property and accessor. May not contain reserved characters. Accessor may
  28647. // contain any non-bracket characters.
  28648. const _propertyRe = /*@__PURE__*/ /\.(WC+)(?:\[(.+)\])?/.source.replace( 'WC', _wordChar );
  28649. const _trackRe = new RegExp( ''
  28650. + '^'
  28651. + _directoryRe
  28652. + _nodeRe
  28653. + _objectRe
  28654. + _propertyRe
  28655. + '$'
  28656. );
  28657. const _supportedObjectNames = [ 'material', 'materials', 'bones', 'map' ];
  28658. class Composite {
  28659. constructor( targetGroup, path, optionalParsedPath ) {
  28660. const parsedPath = optionalParsedPath || PropertyBinding.parseTrackName( path );
  28661. this._targetGroup = targetGroup;
  28662. this._bindings = targetGroup.subscribe_( path, parsedPath );
  28663. }
  28664. getValue( array, offset ) {
  28665. this.bind(); // bind all binding
  28666. const firstValidIndex = this._targetGroup.nCachedObjects_,
  28667. binding = this._bindings[ firstValidIndex ];
  28668. // and only call .getValue on the first
  28669. if ( binding !== undefined ) binding.getValue( array, offset );
  28670. }
  28671. setValue( array, offset ) {
  28672. const bindings = this._bindings;
  28673. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  28674. bindings[ i ].setValue( array, offset );
  28675. }
  28676. }
  28677. bind() {
  28678. const bindings = this._bindings;
  28679. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  28680. bindings[ i ].bind();
  28681. }
  28682. }
  28683. unbind() {
  28684. const bindings = this._bindings;
  28685. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  28686. bindings[ i ].unbind();
  28687. }
  28688. }
  28689. }
  28690. // Note: This class uses a State pattern on a per-method basis:
  28691. // 'bind' sets 'this.getValue' / 'setValue' and shadows the
  28692. // prototype version of these methods with one that represents
  28693. // the bound state. When the property is not found, the methods
  28694. // become no-ops.
  28695. class PropertyBinding {
  28696. constructor( rootNode, path, parsedPath ) {
  28697. this.path = path;
  28698. this.parsedPath = parsedPath || PropertyBinding.parseTrackName( path );
  28699. this.node = PropertyBinding.findNode( rootNode, this.parsedPath.nodeName );
  28700. this.rootNode = rootNode;
  28701. // initial state of these methods that calls 'bind'
  28702. this.getValue = this._getValue_unbound;
  28703. this.setValue = this._setValue_unbound;
  28704. }
  28705. static create( root, path, parsedPath ) {
  28706. if ( ! ( root && root.isAnimationObjectGroup ) ) {
  28707. return new PropertyBinding( root, path, parsedPath );
  28708. } else {
  28709. return new PropertyBinding.Composite( root, path, parsedPath );
  28710. }
  28711. }
  28712. /**
  28713. * Replaces spaces with underscores and removes unsupported characters from
  28714. * node names, to ensure compatibility with parseTrackName().
  28715. *
  28716. * @param {string} name Node name to be sanitized.
  28717. * @return {string}
  28718. */
  28719. static sanitizeNodeName( name ) {
  28720. return name.replace( /\s/g, '_' ).replace( _reservedRe, '' );
  28721. }
  28722. static parseTrackName( trackName ) {
  28723. const matches = _trackRe.exec( trackName );
  28724. if ( matches === null ) {
  28725. throw new Error( 'PropertyBinding: Cannot parse trackName: ' + trackName );
  28726. }
  28727. const results = {
  28728. // directoryName: matches[ 1 ], // (tschw) currently unused
  28729. nodeName: matches[ 2 ],
  28730. objectName: matches[ 3 ],
  28731. objectIndex: matches[ 4 ],
  28732. propertyName: matches[ 5 ], // required
  28733. propertyIndex: matches[ 6 ]
  28734. };
  28735. const lastDot = results.nodeName && results.nodeName.lastIndexOf( '.' );
  28736. if ( lastDot !== undefined && lastDot !== - 1 ) {
  28737. const objectName = results.nodeName.substring( lastDot + 1 );
  28738. // Object names must be checked against an allowlist. Otherwise, there
  28739. // is no way to parse 'foo.bar.baz': 'baz' must be a property, but
  28740. // 'bar' could be the objectName, or part of a nodeName (which can
  28741. // include '.' characters).
  28742. if ( _supportedObjectNames.indexOf( objectName ) !== - 1 ) {
  28743. results.nodeName = results.nodeName.substring( 0, lastDot );
  28744. results.objectName = objectName;
  28745. }
  28746. }
  28747. if ( results.propertyName === null || results.propertyName.length === 0 ) {
  28748. throw new Error( 'PropertyBinding: can not parse propertyName from trackName: ' + trackName );
  28749. }
  28750. return results;
  28751. }
  28752. static findNode( root, nodeName ) {
  28753. if ( nodeName === undefined || nodeName === '' || nodeName === '.' || nodeName === - 1 || nodeName === root.name || nodeName === root.uuid ) {
  28754. return root;
  28755. }
  28756. // search into skeleton bones.
  28757. if ( root.skeleton ) {
  28758. const bone = root.skeleton.getBoneByName( nodeName );
  28759. if ( bone !== undefined ) {
  28760. return bone;
  28761. }
  28762. }
  28763. // search into node subtree.
  28764. if ( root.children ) {
  28765. const searchNodeSubtree = function ( children ) {
  28766. for ( let i = 0; i < children.length; i ++ ) {
  28767. const childNode = children[ i ];
  28768. if ( childNode.name === nodeName || childNode.uuid === nodeName ) {
  28769. return childNode;
  28770. }
  28771. const result = searchNodeSubtree( childNode.children );
  28772. if ( result ) return result;
  28773. }
  28774. return null;
  28775. };
  28776. const subTreeNode = searchNodeSubtree( root.children );
  28777. if ( subTreeNode ) {
  28778. return subTreeNode;
  28779. }
  28780. }
  28781. return null;
  28782. }
  28783. // these are used to "bind" a nonexistent property
  28784. _getValue_unavailable() {}
  28785. _setValue_unavailable() {}
  28786. // Getters
  28787. _getValue_direct( buffer, offset ) {
  28788. buffer[ offset ] = this.targetObject[ this.propertyName ];
  28789. }
  28790. _getValue_array( buffer, offset ) {
  28791. const source = this.resolvedProperty;
  28792. for ( let i = 0, n = source.length; i !== n; ++ i ) {
  28793. buffer[ offset ++ ] = source[ i ];
  28794. }
  28795. }
  28796. _getValue_arrayElement( buffer, offset ) {
  28797. buffer[ offset ] = this.resolvedProperty[ this.propertyIndex ];
  28798. }
  28799. _getValue_toArray( buffer, offset ) {
  28800. this.resolvedProperty.toArray( buffer, offset );
  28801. }
  28802. // Direct
  28803. _setValue_direct( buffer, offset ) {
  28804. this.targetObject[ this.propertyName ] = buffer[ offset ];
  28805. }
  28806. _setValue_direct_setNeedsUpdate( buffer, offset ) {
  28807. this.targetObject[ this.propertyName ] = buffer[ offset ];
  28808. this.targetObject.needsUpdate = true;
  28809. }
  28810. _setValue_direct_setMatrixWorldNeedsUpdate( buffer, offset ) {
  28811. this.targetObject[ this.propertyName ] = buffer[ offset ];
  28812. this.targetObject.matrixWorldNeedsUpdate = true;
  28813. }
  28814. // EntireArray
  28815. _setValue_array( buffer, offset ) {
  28816. const dest = this.resolvedProperty;
  28817. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  28818. dest[ i ] = buffer[ offset ++ ];
  28819. }
  28820. }
  28821. _setValue_array_setNeedsUpdate( buffer, offset ) {
  28822. const dest = this.resolvedProperty;
  28823. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  28824. dest[ i ] = buffer[ offset ++ ];
  28825. }
  28826. this.targetObject.needsUpdate = true;
  28827. }
  28828. _setValue_array_setMatrixWorldNeedsUpdate( buffer, offset ) {
  28829. const dest = this.resolvedProperty;
  28830. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  28831. dest[ i ] = buffer[ offset ++ ];
  28832. }
  28833. this.targetObject.matrixWorldNeedsUpdate = true;
  28834. }
  28835. // ArrayElement
  28836. _setValue_arrayElement( buffer, offset ) {
  28837. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  28838. }
  28839. _setValue_arrayElement_setNeedsUpdate( buffer, offset ) {
  28840. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  28841. this.targetObject.needsUpdate = true;
  28842. }
  28843. _setValue_arrayElement_setMatrixWorldNeedsUpdate( buffer, offset ) {
  28844. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  28845. this.targetObject.matrixWorldNeedsUpdate = true;
  28846. }
  28847. // HasToFromArray
  28848. _setValue_fromArray( buffer, offset ) {
  28849. this.resolvedProperty.fromArray( buffer, offset );
  28850. }
  28851. _setValue_fromArray_setNeedsUpdate( buffer, offset ) {
  28852. this.resolvedProperty.fromArray( buffer, offset );
  28853. this.targetObject.needsUpdate = true;
  28854. }
  28855. _setValue_fromArray_setMatrixWorldNeedsUpdate( buffer, offset ) {
  28856. this.resolvedProperty.fromArray( buffer, offset );
  28857. this.targetObject.matrixWorldNeedsUpdate = true;
  28858. }
  28859. _getValue_unbound( targetArray, offset ) {
  28860. this.bind();
  28861. this.getValue( targetArray, offset );
  28862. }
  28863. _setValue_unbound( sourceArray, offset ) {
  28864. this.bind();
  28865. this.setValue( sourceArray, offset );
  28866. }
  28867. // create getter / setter pair for a property in the scene graph
  28868. bind() {
  28869. let targetObject = this.node;
  28870. const parsedPath = this.parsedPath;
  28871. const objectName = parsedPath.objectName;
  28872. const propertyName = parsedPath.propertyName;
  28873. let propertyIndex = parsedPath.propertyIndex;
  28874. if ( ! targetObject ) {
  28875. targetObject = PropertyBinding.findNode( this.rootNode, parsedPath.nodeName );
  28876. this.node = targetObject;
  28877. }
  28878. // set fail state so we can just 'return' on error
  28879. this.getValue = this._getValue_unavailable;
  28880. this.setValue = this._setValue_unavailable;
  28881. // ensure there is a value node
  28882. if ( ! targetObject ) {
  28883. console.warn( 'THREE.PropertyBinding: No target node found for track: ' + this.path + '.' );
  28884. return;
  28885. }
  28886. if ( objectName ) {
  28887. let objectIndex = parsedPath.objectIndex;
  28888. // special cases were we need to reach deeper into the hierarchy to get the face materials....
  28889. switch ( objectName ) {
  28890. case 'materials':
  28891. if ( ! targetObject.material ) {
  28892. console.error( 'THREE.PropertyBinding: Can not bind to material as node does not have a material.', this );
  28893. return;
  28894. }
  28895. if ( ! targetObject.material.materials ) {
  28896. console.error( 'THREE.PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.', this );
  28897. return;
  28898. }
  28899. targetObject = targetObject.material.materials;
  28900. break;
  28901. case 'bones':
  28902. if ( ! targetObject.skeleton ) {
  28903. console.error( 'THREE.PropertyBinding: Can not bind to bones as node does not have a skeleton.', this );
  28904. return;
  28905. }
  28906. // potential future optimization: skip this if propertyIndex is already an integer
  28907. // and convert the integer string to a true integer.
  28908. targetObject = targetObject.skeleton.bones;
  28909. // support resolving morphTarget names into indices.
  28910. for ( let i = 0; i < targetObject.length; i ++ ) {
  28911. if ( targetObject[ i ].name === objectIndex ) {
  28912. objectIndex = i;
  28913. break;
  28914. }
  28915. }
  28916. break;
  28917. case 'map':
  28918. if ( 'map' in targetObject ) {
  28919. targetObject = targetObject.map;
  28920. break;
  28921. }
  28922. if ( ! targetObject.material ) {
  28923. console.error( 'THREE.PropertyBinding: Can not bind to material as node does not have a material.', this );
  28924. return;
  28925. }
  28926. if ( ! targetObject.material.map ) {
  28927. console.error( 'THREE.PropertyBinding: Can not bind to material.map as node.material does not have a map.', this );
  28928. return;
  28929. }
  28930. targetObject = targetObject.material.map;
  28931. break;
  28932. default:
  28933. if ( targetObject[ objectName ] === undefined ) {
  28934. console.error( 'THREE.PropertyBinding: Can not bind to objectName of node undefined.', this );
  28935. return;
  28936. }
  28937. targetObject = targetObject[ objectName ];
  28938. }
  28939. if ( objectIndex !== undefined ) {
  28940. if ( targetObject[ objectIndex ] === undefined ) {
  28941. console.error( 'THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.', this, targetObject );
  28942. return;
  28943. }
  28944. targetObject = targetObject[ objectIndex ];
  28945. }
  28946. }
  28947. // resolve property
  28948. const nodeProperty = targetObject[ propertyName ];
  28949. if ( nodeProperty === undefined ) {
  28950. const nodeName = parsedPath.nodeName;
  28951. console.error( 'THREE.PropertyBinding: Trying to update property for track: ' + nodeName +
  28952. '.' + propertyName + ' but it wasn\'t found.', targetObject );
  28953. return;
  28954. }
  28955. // determine versioning scheme
  28956. let versioning = this.Versioning.None;
  28957. this.targetObject = targetObject;
  28958. if ( targetObject.needsUpdate !== undefined ) { // material
  28959. versioning = this.Versioning.NeedsUpdate;
  28960. } else if ( targetObject.matrixWorldNeedsUpdate !== undefined ) { // node transform
  28961. versioning = this.Versioning.MatrixWorldNeedsUpdate;
  28962. }
  28963. // determine how the property gets bound
  28964. let bindingType = this.BindingType.Direct;
  28965. if ( propertyIndex !== undefined ) {
  28966. // access a sub element of the property array (only primitives are supported right now)
  28967. if ( propertyName === 'morphTargetInfluences' ) {
  28968. // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer.
  28969. // support resolving morphTarget names into indices.
  28970. if ( ! targetObject.geometry ) {
  28971. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.', this );
  28972. return;
  28973. }
  28974. if ( ! targetObject.geometry.morphAttributes ) {
  28975. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.', this );
  28976. return;
  28977. }
  28978. if ( targetObject.morphTargetDictionary[ propertyIndex ] !== undefined ) {
  28979. propertyIndex = targetObject.morphTargetDictionary[ propertyIndex ];
  28980. }
  28981. }
  28982. bindingType = this.BindingType.ArrayElement;
  28983. this.resolvedProperty = nodeProperty;
  28984. this.propertyIndex = propertyIndex;
  28985. } else if ( nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined ) {
  28986. // must use copy for Object3D.Euler/Quaternion
  28987. bindingType = this.BindingType.HasFromToArray;
  28988. this.resolvedProperty = nodeProperty;
  28989. } else if ( Array.isArray( nodeProperty ) ) {
  28990. bindingType = this.BindingType.EntireArray;
  28991. this.resolvedProperty = nodeProperty;
  28992. } else {
  28993. this.propertyName = propertyName;
  28994. }
  28995. // select getter / setter
  28996. this.getValue = this.GetterByBindingType[ bindingType ];
  28997. this.setValue = this.SetterByBindingTypeAndVersioning[ bindingType ][ versioning ];
  28998. }
  28999. unbind() {
  29000. this.node = null;
  29001. // back to the prototype version of getValue / setValue
  29002. // note: avoiding to mutate the shape of 'this' via 'delete'
  29003. this.getValue = this._getValue_unbound;
  29004. this.setValue = this._setValue_unbound;
  29005. }
  29006. }
  29007. PropertyBinding.Composite = Composite;
  29008. PropertyBinding.prototype.BindingType = {
  29009. Direct: 0,
  29010. EntireArray: 1,
  29011. ArrayElement: 2,
  29012. HasFromToArray: 3
  29013. };
  29014. PropertyBinding.prototype.Versioning = {
  29015. None: 0,
  29016. NeedsUpdate: 1,
  29017. MatrixWorldNeedsUpdate: 2
  29018. };
  29019. PropertyBinding.prototype.GetterByBindingType = [
  29020. PropertyBinding.prototype._getValue_direct,
  29021. PropertyBinding.prototype._getValue_array,
  29022. PropertyBinding.prototype._getValue_arrayElement,
  29023. PropertyBinding.prototype._getValue_toArray,
  29024. ];
  29025. PropertyBinding.prototype.SetterByBindingTypeAndVersioning = [
  29026. [
  29027. // Direct
  29028. PropertyBinding.prototype._setValue_direct,
  29029. PropertyBinding.prototype._setValue_direct_setNeedsUpdate,
  29030. PropertyBinding.prototype._setValue_direct_setMatrixWorldNeedsUpdate,
  29031. ], [
  29032. // EntireArray
  29033. PropertyBinding.prototype._setValue_array,
  29034. PropertyBinding.prototype._setValue_array_setNeedsUpdate,
  29035. PropertyBinding.prototype._setValue_array_setMatrixWorldNeedsUpdate,
  29036. ], [
  29037. // ArrayElement
  29038. PropertyBinding.prototype._setValue_arrayElement,
  29039. PropertyBinding.prototype._setValue_arrayElement_setNeedsUpdate,
  29040. PropertyBinding.prototype._setValue_arrayElement_setMatrixWorldNeedsUpdate,
  29041. ], [
  29042. // HasToFromArray
  29043. PropertyBinding.prototype._setValue_fromArray,
  29044. PropertyBinding.prototype._setValue_fromArray_setNeedsUpdate,
  29045. PropertyBinding.prototype._setValue_fromArray_setMatrixWorldNeedsUpdate,
  29046. ]
  29047. ];
  29048. /**
  29049. *
  29050. * A group of objects that receives a shared animation state.
  29051. *
  29052. * Usage:
  29053. *
  29054. * - Add objects you would otherwise pass as 'root' to the
  29055. * constructor or the .clipAction method of AnimationMixer.
  29056. *
  29057. * - Instead pass this object as 'root'.
  29058. *
  29059. * - You can also add and remove objects later when the mixer
  29060. * is running.
  29061. *
  29062. * Note:
  29063. *
  29064. * Objects of this class appear as one object to the mixer,
  29065. * so cache control of the individual objects must be done
  29066. * on the group.
  29067. *
  29068. * Limitation:
  29069. *
  29070. * - The animated properties must be compatible among the
  29071. * all objects in the group.
  29072. *
  29073. * - A single property can either be controlled through a
  29074. * target group or directly, but not both.
  29075. */
  29076. class AnimationObjectGroup {
  29077. constructor() {
  29078. this.isAnimationObjectGroup = true;
  29079. this.uuid = generateUUID();
  29080. // cached objects followed by the active ones
  29081. this._objects = Array.prototype.slice.call( arguments );
  29082. this.nCachedObjects_ = 0; // threshold
  29083. // note: read by PropertyBinding.Composite
  29084. const indices = {};
  29085. this._indicesByUUID = indices; // for bookkeeping
  29086. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  29087. indices[ arguments[ i ].uuid ] = i;
  29088. }
  29089. this._paths = []; // inside: string
  29090. this._parsedPaths = []; // inside: { we don't care, here }
  29091. this._bindings = []; // inside: Array< PropertyBinding >
  29092. this._bindingsIndicesByPath = {}; // inside: indices in these arrays
  29093. const scope = this;
  29094. this.stats = {
  29095. objects: {
  29096. get total() {
  29097. return scope._objects.length;
  29098. },
  29099. get inUse() {
  29100. return this.total - scope.nCachedObjects_;
  29101. }
  29102. },
  29103. get bindingsPerObject() {
  29104. return scope._bindings.length;
  29105. }
  29106. };
  29107. }
  29108. add() {
  29109. const objects = this._objects,
  29110. indicesByUUID = this._indicesByUUID,
  29111. paths = this._paths,
  29112. parsedPaths = this._parsedPaths,
  29113. bindings = this._bindings,
  29114. nBindings = bindings.length;
  29115. let knownObject = undefined,
  29116. nObjects = objects.length,
  29117. nCachedObjects = this.nCachedObjects_;
  29118. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  29119. const object = arguments[ i ],
  29120. uuid = object.uuid;
  29121. let index = indicesByUUID[ uuid ];
  29122. if ( index === undefined ) {
  29123. // unknown object -> add it to the ACTIVE region
  29124. index = nObjects ++;
  29125. indicesByUUID[ uuid ] = index;
  29126. objects.push( object );
  29127. // accounting is done, now do the same for all bindings
  29128. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  29129. bindings[ j ].push( new PropertyBinding( object, paths[ j ], parsedPaths[ j ] ) );
  29130. }
  29131. } else if ( index < nCachedObjects ) {
  29132. knownObject = objects[ index ];
  29133. // move existing object to the ACTIVE region
  29134. const firstActiveIndex = -- nCachedObjects,
  29135. lastCachedObject = objects[ firstActiveIndex ];
  29136. indicesByUUID[ lastCachedObject.uuid ] = index;
  29137. objects[ index ] = lastCachedObject;
  29138. indicesByUUID[ uuid ] = firstActiveIndex;
  29139. objects[ firstActiveIndex ] = object;
  29140. // accounting is done, now do the same for all bindings
  29141. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  29142. const bindingsForPath = bindings[ j ],
  29143. lastCached = bindingsForPath[ firstActiveIndex ];
  29144. let binding = bindingsForPath[ index ];
  29145. bindingsForPath[ index ] = lastCached;
  29146. if ( binding === undefined ) {
  29147. // since we do not bother to create new bindings
  29148. // for objects that are cached, the binding may
  29149. // or may not exist
  29150. binding = new PropertyBinding( object, paths[ j ], parsedPaths[ j ] );
  29151. }
  29152. bindingsForPath[ firstActiveIndex ] = binding;
  29153. }
  29154. } else if ( objects[ index ] !== knownObject ) {
  29155. console.error( 'THREE.AnimationObjectGroup: Different objects with the same UUID ' +
  29156. 'detected. Clean the caches or recreate your infrastructure when reloading scenes.' );
  29157. } // else the object is already where we want it to be
  29158. } // for arguments
  29159. this.nCachedObjects_ = nCachedObjects;
  29160. }
  29161. remove() {
  29162. const objects = this._objects,
  29163. indicesByUUID = this._indicesByUUID,
  29164. bindings = this._bindings,
  29165. nBindings = bindings.length;
  29166. let nCachedObjects = this.nCachedObjects_;
  29167. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  29168. const object = arguments[ i ],
  29169. uuid = object.uuid,
  29170. index = indicesByUUID[ uuid ];
  29171. if ( index !== undefined && index >= nCachedObjects ) {
  29172. // move existing object into the CACHED region
  29173. const lastCachedIndex = nCachedObjects ++,
  29174. firstActiveObject = objects[ lastCachedIndex ];
  29175. indicesByUUID[ firstActiveObject.uuid ] = index;
  29176. objects[ index ] = firstActiveObject;
  29177. indicesByUUID[ uuid ] = lastCachedIndex;
  29178. objects[ lastCachedIndex ] = object;
  29179. // accounting is done, now do the same for all bindings
  29180. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  29181. const bindingsForPath = bindings[ j ],
  29182. firstActive = bindingsForPath[ lastCachedIndex ],
  29183. binding = bindingsForPath[ index ];
  29184. bindingsForPath[ index ] = firstActive;
  29185. bindingsForPath[ lastCachedIndex ] = binding;
  29186. }
  29187. }
  29188. } // for arguments
  29189. this.nCachedObjects_ = nCachedObjects;
  29190. }
  29191. // remove & forget
  29192. uncache() {
  29193. const objects = this._objects,
  29194. indicesByUUID = this._indicesByUUID,
  29195. bindings = this._bindings,
  29196. nBindings = bindings.length;
  29197. let nCachedObjects = this.nCachedObjects_,
  29198. nObjects = objects.length;
  29199. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  29200. const object = arguments[ i ],
  29201. uuid = object.uuid,
  29202. index = indicesByUUID[ uuid ];
  29203. if ( index !== undefined ) {
  29204. delete indicesByUUID[ uuid ];
  29205. if ( index < nCachedObjects ) {
  29206. // object is cached, shrink the CACHED region
  29207. const firstActiveIndex = -- nCachedObjects,
  29208. lastCachedObject = objects[ firstActiveIndex ],
  29209. lastIndex = -- nObjects,
  29210. lastObject = objects[ lastIndex ];
  29211. // last cached object takes this object's place
  29212. indicesByUUID[ lastCachedObject.uuid ] = index;
  29213. objects[ index ] = lastCachedObject;
  29214. // last object goes to the activated slot and pop
  29215. indicesByUUID[ lastObject.uuid ] = firstActiveIndex;
  29216. objects[ firstActiveIndex ] = lastObject;
  29217. objects.pop();
  29218. // accounting is done, now do the same for all bindings
  29219. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  29220. const bindingsForPath = bindings[ j ],
  29221. lastCached = bindingsForPath[ firstActiveIndex ],
  29222. last = bindingsForPath[ lastIndex ];
  29223. bindingsForPath[ index ] = lastCached;
  29224. bindingsForPath[ firstActiveIndex ] = last;
  29225. bindingsForPath.pop();
  29226. }
  29227. } else {
  29228. // object is active, just swap with the last and pop
  29229. const lastIndex = -- nObjects,
  29230. lastObject = objects[ lastIndex ];
  29231. if ( lastIndex > 0 ) {
  29232. indicesByUUID[ lastObject.uuid ] = index;
  29233. }
  29234. objects[ index ] = lastObject;
  29235. objects.pop();
  29236. // accounting is done, now do the same for all bindings
  29237. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  29238. const bindingsForPath = bindings[ j ];
  29239. bindingsForPath[ index ] = bindingsForPath[ lastIndex ];
  29240. bindingsForPath.pop();
  29241. }
  29242. } // cached or active
  29243. } // if object is known
  29244. } // for arguments
  29245. this.nCachedObjects_ = nCachedObjects;
  29246. }
  29247. // Internal interface used by befriended PropertyBinding.Composite:
  29248. subscribe_( path, parsedPath ) {
  29249. // returns an array of bindings for the given path that is changed
  29250. // according to the contained objects in the group
  29251. const indicesByPath = this._bindingsIndicesByPath;
  29252. let index = indicesByPath[ path ];
  29253. const bindings = this._bindings;
  29254. if ( index !== undefined ) return bindings[ index ];
  29255. const paths = this._paths,
  29256. parsedPaths = this._parsedPaths,
  29257. objects = this._objects,
  29258. nObjects = objects.length,
  29259. nCachedObjects = this.nCachedObjects_,
  29260. bindingsForPath = new Array( nObjects );
  29261. index = bindings.length;
  29262. indicesByPath[ path ] = index;
  29263. paths.push( path );
  29264. parsedPaths.push( parsedPath );
  29265. bindings.push( bindingsForPath );
  29266. for ( let i = nCachedObjects, n = objects.length; i !== n; ++ i ) {
  29267. const object = objects[ i ];
  29268. bindingsForPath[ i ] = new PropertyBinding( object, path, parsedPath );
  29269. }
  29270. return bindingsForPath;
  29271. }
  29272. unsubscribe_( path ) {
  29273. // tells the group to forget about a property path and no longer
  29274. // update the array previously obtained with 'subscribe_'
  29275. const indicesByPath = this._bindingsIndicesByPath,
  29276. index = indicesByPath[ path ];
  29277. if ( index !== undefined ) {
  29278. const paths = this._paths,
  29279. parsedPaths = this._parsedPaths,
  29280. bindings = this._bindings,
  29281. lastBindingsIndex = bindings.length - 1,
  29282. lastBindings = bindings[ lastBindingsIndex ],
  29283. lastBindingsPath = path[ lastBindingsIndex ];
  29284. indicesByPath[ lastBindingsPath ] = index;
  29285. bindings[ index ] = lastBindings;
  29286. bindings.pop();
  29287. parsedPaths[ index ] = parsedPaths[ lastBindingsIndex ];
  29288. parsedPaths.pop();
  29289. paths[ index ] = paths[ lastBindingsIndex ];
  29290. paths.pop();
  29291. }
  29292. }
  29293. }
  29294. class AnimationAction {
  29295. constructor( mixer, clip, localRoot = null, blendMode = clip.blendMode ) {
  29296. this._mixer = mixer;
  29297. this._clip = clip;
  29298. this._localRoot = localRoot;
  29299. this.blendMode = blendMode;
  29300. const tracks = clip.tracks,
  29301. nTracks = tracks.length,
  29302. interpolants = new Array( nTracks );
  29303. const interpolantSettings = {
  29304. endingStart: ZeroCurvatureEnding,
  29305. endingEnd: ZeroCurvatureEnding
  29306. };
  29307. for ( let i = 0; i !== nTracks; ++ i ) {
  29308. const interpolant = tracks[ i ].createInterpolant( null );
  29309. interpolants[ i ] = interpolant;
  29310. interpolant.settings = interpolantSettings;
  29311. }
  29312. this._interpolantSettings = interpolantSettings;
  29313. this._interpolants = interpolants; // bound by the mixer
  29314. // inside: PropertyMixer (managed by the mixer)
  29315. this._propertyBindings = new Array( nTracks );
  29316. this._cacheIndex = null; // for the memory manager
  29317. this._byClipCacheIndex = null; // for the memory manager
  29318. this._timeScaleInterpolant = null;
  29319. this._weightInterpolant = null;
  29320. this.loop = LoopRepeat;
  29321. this._loopCount = - 1;
  29322. // global mixer time when the action is to be started
  29323. // it's set back to 'null' upon start of the action
  29324. this._startTime = null;
  29325. // scaled local time of the action
  29326. // gets clamped or wrapped to 0..clip.duration according to loop
  29327. this.time = 0;
  29328. this.timeScale = 1;
  29329. this._effectiveTimeScale = 1;
  29330. this.weight = 1;
  29331. this._effectiveWeight = 1;
  29332. this.repetitions = Infinity; // no. of repetitions when looping
  29333. this.paused = false; // true -> zero effective time scale
  29334. this.enabled = true; // false -> zero effective weight
  29335. this.clampWhenFinished = false;// keep feeding the last frame?
  29336. this.zeroSlopeAtStart = true;// for smooth interpolation w/o separate
  29337. this.zeroSlopeAtEnd = true;// clips for start, loop and end
  29338. }
  29339. // State & Scheduling
  29340. play() {
  29341. this._mixer._activateAction( this );
  29342. return this;
  29343. }
  29344. stop() {
  29345. this._mixer._deactivateAction( this );
  29346. return this.reset();
  29347. }
  29348. reset() {
  29349. this.paused = false;
  29350. this.enabled = true;
  29351. this.time = 0; // restart clip
  29352. this._loopCount = - 1;// forget previous loops
  29353. this._startTime = null;// forget scheduling
  29354. return this.stopFading().stopWarping();
  29355. }
  29356. isRunning() {
  29357. return this.enabled && ! this.paused && this.timeScale !== 0 &&
  29358. this._startTime === null && this._mixer._isActiveAction( this );
  29359. }
  29360. // return true when play has been called
  29361. isScheduled() {
  29362. return this._mixer._isActiveAction( this );
  29363. }
  29364. startAt( time ) {
  29365. this._startTime = time;
  29366. return this;
  29367. }
  29368. setLoop( mode, repetitions ) {
  29369. this.loop = mode;
  29370. this.repetitions = repetitions;
  29371. return this;
  29372. }
  29373. // Weight
  29374. // set the weight stopping any scheduled fading
  29375. // although .enabled = false yields an effective weight of zero, this
  29376. // method does *not* change .enabled, because it would be confusing
  29377. setEffectiveWeight( weight ) {
  29378. this.weight = weight;
  29379. // note: same logic as when updated at runtime
  29380. this._effectiveWeight = this.enabled ? weight : 0;
  29381. return this.stopFading();
  29382. }
  29383. // return the weight considering fading and .enabled
  29384. getEffectiveWeight() {
  29385. return this._effectiveWeight;
  29386. }
  29387. fadeIn( duration ) {
  29388. return this._scheduleFading( duration, 0, 1 );
  29389. }
  29390. fadeOut( duration ) {
  29391. return this._scheduleFading( duration, 1, 0 );
  29392. }
  29393. crossFadeFrom( fadeOutAction, duration, warp ) {
  29394. fadeOutAction.fadeOut( duration );
  29395. this.fadeIn( duration );
  29396. if ( warp ) {
  29397. const fadeInDuration = this._clip.duration,
  29398. fadeOutDuration = fadeOutAction._clip.duration,
  29399. startEndRatio = fadeOutDuration / fadeInDuration,
  29400. endStartRatio = fadeInDuration / fadeOutDuration;
  29401. fadeOutAction.warp( 1.0, startEndRatio, duration );
  29402. this.warp( endStartRatio, 1.0, duration );
  29403. }
  29404. return this;
  29405. }
  29406. crossFadeTo( fadeInAction, duration, warp ) {
  29407. return fadeInAction.crossFadeFrom( this, duration, warp );
  29408. }
  29409. stopFading() {
  29410. const weightInterpolant = this._weightInterpolant;
  29411. if ( weightInterpolant !== null ) {
  29412. this._weightInterpolant = null;
  29413. this._mixer._takeBackControlInterpolant( weightInterpolant );
  29414. }
  29415. return this;
  29416. }
  29417. // Time Scale Control
  29418. // set the time scale stopping any scheduled warping
  29419. // although .paused = true yields an effective time scale of zero, this
  29420. // method does *not* change .paused, because it would be confusing
  29421. setEffectiveTimeScale( timeScale ) {
  29422. this.timeScale = timeScale;
  29423. this._effectiveTimeScale = this.paused ? 0 : timeScale;
  29424. return this.stopWarping();
  29425. }
  29426. // return the time scale considering warping and .paused
  29427. getEffectiveTimeScale() {
  29428. return this._effectiveTimeScale;
  29429. }
  29430. setDuration( duration ) {
  29431. this.timeScale = this._clip.duration / duration;
  29432. return this.stopWarping();
  29433. }
  29434. syncWith( action ) {
  29435. this.time = action.time;
  29436. this.timeScale = action.timeScale;
  29437. return this.stopWarping();
  29438. }
  29439. halt( duration ) {
  29440. return this.warp( this._effectiveTimeScale, 0, duration );
  29441. }
  29442. warp( startTimeScale, endTimeScale, duration ) {
  29443. const mixer = this._mixer,
  29444. now = mixer.time,
  29445. timeScale = this.timeScale;
  29446. let interpolant = this._timeScaleInterpolant;
  29447. if ( interpolant === null ) {
  29448. interpolant = mixer._lendControlInterpolant();
  29449. this._timeScaleInterpolant = interpolant;
  29450. }
  29451. const times = interpolant.parameterPositions,
  29452. values = interpolant.sampleValues;
  29453. times[ 0 ] = now;
  29454. times[ 1 ] = now + duration;
  29455. values[ 0 ] = startTimeScale / timeScale;
  29456. values[ 1 ] = endTimeScale / timeScale;
  29457. return this;
  29458. }
  29459. stopWarping() {
  29460. const timeScaleInterpolant = this._timeScaleInterpolant;
  29461. if ( timeScaleInterpolant !== null ) {
  29462. this._timeScaleInterpolant = null;
  29463. this._mixer._takeBackControlInterpolant( timeScaleInterpolant );
  29464. }
  29465. return this;
  29466. }
  29467. // Object Accessors
  29468. getMixer() {
  29469. return this._mixer;
  29470. }
  29471. getClip() {
  29472. return this._clip;
  29473. }
  29474. getRoot() {
  29475. return this._localRoot || this._mixer._root;
  29476. }
  29477. // Interna
  29478. _update( time, deltaTime, timeDirection, accuIndex ) {
  29479. // called by the mixer
  29480. if ( ! this.enabled ) {
  29481. // call ._updateWeight() to update ._effectiveWeight
  29482. this._updateWeight( time );
  29483. return;
  29484. }
  29485. const startTime = this._startTime;
  29486. if ( startTime !== null ) {
  29487. // check for scheduled start of action
  29488. const timeRunning = ( time - startTime ) * timeDirection;
  29489. if ( timeRunning < 0 || timeDirection === 0 ) {
  29490. deltaTime = 0;
  29491. } else {
  29492. this._startTime = null; // unschedule
  29493. deltaTime = timeDirection * timeRunning;
  29494. }
  29495. }
  29496. // apply time scale and advance time
  29497. deltaTime *= this._updateTimeScale( time );
  29498. const clipTime = this._updateTime( deltaTime );
  29499. // note: _updateTime may disable the action resulting in
  29500. // an effective weight of 0
  29501. const weight = this._updateWeight( time );
  29502. if ( weight > 0 ) {
  29503. const interpolants = this._interpolants;
  29504. const propertyMixers = this._propertyBindings;
  29505. switch ( this.blendMode ) {
  29506. case AdditiveAnimationBlendMode:
  29507. for ( let j = 0, m = interpolants.length; j !== m; ++ j ) {
  29508. interpolants[ j ].evaluate( clipTime );
  29509. propertyMixers[ j ].accumulateAdditive( weight );
  29510. }
  29511. break;
  29512. case NormalAnimationBlendMode:
  29513. default:
  29514. for ( let j = 0, m = interpolants.length; j !== m; ++ j ) {
  29515. interpolants[ j ].evaluate( clipTime );
  29516. propertyMixers[ j ].accumulate( accuIndex, weight );
  29517. }
  29518. }
  29519. }
  29520. }
  29521. _updateWeight( time ) {
  29522. let weight = 0;
  29523. if ( this.enabled ) {
  29524. weight = this.weight;
  29525. const interpolant = this._weightInterpolant;
  29526. if ( interpolant !== null ) {
  29527. const interpolantValue = interpolant.evaluate( time )[ 0 ];
  29528. weight *= interpolantValue;
  29529. if ( time > interpolant.parameterPositions[ 1 ] ) {
  29530. this.stopFading();
  29531. if ( interpolantValue === 0 ) {
  29532. // faded out, disable
  29533. this.enabled = false;
  29534. }
  29535. }
  29536. }
  29537. }
  29538. this._effectiveWeight = weight;
  29539. return weight;
  29540. }
  29541. _updateTimeScale( time ) {
  29542. let timeScale = 0;
  29543. if ( ! this.paused ) {
  29544. timeScale = this.timeScale;
  29545. const interpolant = this._timeScaleInterpolant;
  29546. if ( interpolant !== null ) {
  29547. const interpolantValue = interpolant.evaluate( time )[ 0 ];
  29548. timeScale *= interpolantValue;
  29549. if ( time > interpolant.parameterPositions[ 1 ] ) {
  29550. this.stopWarping();
  29551. if ( timeScale === 0 ) {
  29552. // motion has halted, pause
  29553. this.paused = true;
  29554. } else {
  29555. // warp done - apply final time scale
  29556. this.timeScale = timeScale;
  29557. }
  29558. }
  29559. }
  29560. }
  29561. this._effectiveTimeScale = timeScale;
  29562. return timeScale;
  29563. }
  29564. _updateTime( deltaTime ) {
  29565. const duration = this._clip.duration;
  29566. const loop = this.loop;
  29567. let time = this.time + deltaTime;
  29568. let loopCount = this._loopCount;
  29569. const pingPong = ( loop === LoopPingPong );
  29570. if ( deltaTime === 0 ) {
  29571. if ( loopCount === - 1 ) return time;
  29572. return ( pingPong && ( loopCount & 1 ) === 1 ) ? duration - time : time;
  29573. }
  29574. if ( loop === LoopOnce ) {
  29575. if ( loopCount === - 1 ) {
  29576. // just started
  29577. this._loopCount = 0;
  29578. this._setEndings( true, true, false );
  29579. }
  29580. handle_stop: {
  29581. if ( time >= duration ) {
  29582. time = duration;
  29583. } else if ( time < 0 ) {
  29584. time = 0;
  29585. } else {
  29586. this.time = time;
  29587. break handle_stop;
  29588. }
  29589. if ( this.clampWhenFinished ) this.paused = true;
  29590. else this.enabled = false;
  29591. this.time = time;
  29592. this._mixer.dispatchEvent( {
  29593. type: 'finished', action: this,
  29594. direction: deltaTime < 0 ? - 1 : 1
  29595. } );
  29596. }
  29597. } else { // repetitive Repeat or PingPong
  29598. if ( loopCount === - 1 ) {
  29599. // just started
  29600. if ( deltaTime >= 0 ) {
  29601. loopCount = 0;
  29602. this._setEndings( true, this.repetitions === 0, pingPong );
  29603. } else {
  29604. // when looping in reverse direction, the initial
  29605. // transition through zero counts as a repetition,
  29606. // so leave loopCount at -1
  29607. this._setEndings( this.repetitions === 0, true, pingPong );
  29608. }
  29609. }
  29610. if ( time >= duration || time < 0 ) {
  29611. // wrap around
  29612. const loopDelta = Math.floor( time / duration ); // signed
  29613. time -= duration * loopDelta;
  29614. loopCount += Math.abs( loopDelta );
  29615. const pending = this.repetitions - loopCount;
  29616. if ( pending <= 0 ) {
  29617. // have to stop (switch state, clamp time, fire event)
  29618. if ( this.clampWhenFinished ) this.paused = true;
  29619. else this.enabled = false;
  29620. time = deltaTime > 0 ? duration : 0;
  29621. this.time = time;
  29622. this._mixer.dispatchEvent( {
  29623. type: 'finished', action: this,
  29624. direction: deltaTime > 0 ? 1 : - 1
  29625. } );
  29626. } else {
  29627. // keep running
  29628. if ( pending === 1 ) {
  29629. // entering the last round
  29630. const atStart = deltaTime < 0;
  29631. this._setEndings( atStart, ! atStart, pingPong );
  29632. } else {
  29633. this._setEndings( false, false, pingPong );
  29634. }
  29635. this._loopCount = loopCount;
  29636. this.time = time;
  29637. this._mixer.dispatchEvent( {
  29638. type: 'loop', action: this, loopDelta: loopDelta
  29639. } );
  29640. }
  29641. } else {
  29642. this.time = time;
  29643. }
  29644. if ( pingPong && ( loopCount & 1 ) === 1 ) {
  29645. // invert time for the "pong round"
  29646. return duration - time;
  29647. }
  29648. }
  29649. return time;
  29650. }
  29651. _setEndings( atStart, atEnd, pingPong ) {
  29652. const settings = this._interpolantSettings;
  29653. if ( pingPong ) {
  29654. settings.endingStart = ZeroSlopeEnding;
  29655. settings.endingEnd = ZeroSlopeEnding;
  29656. } else {
  29657. // assuming for LoopOnce atStart == atEnd == true
  29658. if ( atStart ) {
  29659. settings.endingStart = this.zeroSlopeAtStart ? ZeroSlopeEnding : ZeroCurvatureEnding;
  29660. } else {
  29661. settings.endingStart = WrapAroundEnding;
  29662. }
  29663. if ( atEnd ) {
  29664. settings.endingEnd = this.zeroSlopeAtEnd ? ZeroSlopeEnding : ZeroCurvatureEnding;
  29665. } else {
  29666. settings.endingEnd = WrapAroundEnding;
  29667. }
  29668. }
  29669. }
  29670. _scheduleFading( duration, weightNow, weightThen ) {
  29671. const mixer = this._mixer, now = mixer.time;
  29672. let interpolant = this._weightInterpolant;
  29673. if ( interpolant === null ) {
  29674. interpolant = mixer._lendControlInterpolant();
  29675. this._weightInterpolant = interpolant;
  29676. }
  29677. const times = interpolant.parameterPositions,
  29678. values = interpolant.sampleValues;
  29679. times[ 0 ] = now;
  29680. values[ 0 ] = weightNow;
  29681. times[ 1 ] = now + duration;
  29682. values[ 1 ] = weightThen;
  29683. return this;
  29684. }
  29685. }
  29686. const _controlInterpolantsResultBuffer = new Float32Array( 1 );
  29687. class AnimationMixer extends EventDispatcher {
  29688. constructor( root ) {
  29689. super();
  29690. this._root = root;
  29691. this._initMemoryManager();
  29692. this._accuIndex = 0;
  29693. this.time = 0;
  29694. this.timeScale = 1.0;
  29695. }
  29696. _bindAction( action, prototypeAction ) {
  29697. const root = action._localRoot || this._root,
  29698. tracks = action._clip.tracks,
  29699. nTracks = tracks.length,
  29700. bindings = action._propertyBindings,
  29701. interpolants = action._interpolants,
  29702. rootUuid = root.uuid,
  29703. bindingsByRoot = this._bindingsByRootAndName;
  29704. let bindingsByName = bindingsByRoot[ rootUuid ];
  29705. if ( bindingsByName === undefined ) {
  29706. bindingsByName = {};
  29707. bindingsByRoot[ rootUuid ] = bindingsByName;
  29708. }
  29709. for ( let i = 0; i !== nTracks; ++ i ) {
  29710. const track = tracks[ i ],
  29711. trackName = track.name;
  29712. let binding = bindingsByName[ trackName ];
  29713. if ( binding !== undefined ) {
  29714. ++ binding.referenceCount;
  29715. bindings[ i ] = binding;
  29716. } else {
  29717. binding = bindings[ i ];
  29718. if ( binding !== undefined ) {
  29719. // existing binding, make sure the cache knows
  29720. if ( binding._cacheIndex === null ) {
  29721. ++ binding.referenceCount;
  29722. this._addInactiveBinding( binding, rootUuid, trackName );
  29723. }
  29724. continue;
  29725. }
  29726. const path = prototypeAction && prototypeAction.
  29727. _propertyBindings[ i ].binding.parsedPath;
  29728. binding = new PropertyMixer(
  29729. PropertyBinding.create( root, trackName, path ),
  29730. track.ValueTypeName, track.getValueSize() );
  29731. ++ binding.referenceCount;
  29732. this._addInactiveBinding( binding, rootUuid, trackName );
  29733. bindings[ i ] = binding;
  29734. }
  29735. interpolants[ i ].resultBuffer = binding.buffer;
  29736. }
  29737. }
  29738. _activateAction( action ) {
  29739. if ( ! this._isActiveAction( action ) ) {
  29740. if ( action._cacheIndex === null ) {
  29741. // this action has been forgotten by the cache, but the user
  29742. // appears to be still using it -> rebind
  29743. const rootUuid = ( action._localRoot || this._root ).uuid,
  29744. clipUuid = action._clip.uuid,
  29745. actionsForClip = this._actionsByClip[ clipUuid ];
  29746. this._bindAction( action,
  29747. actionsForClip && actionsForClip.knownActions[ 0 ] );
  29748. this._addInactiveAction( action, clipUuid, rootUuid );
  29749. }
  29750. const bindings = action._propertyBindings;
  29751. // increment reference counts / sort out state
  29752. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  29753. const binding = bindings[ i ];
  29754. if ( binding.useCount ++ === 0 ) {
  29755. this._lendBinding( binding );
  29756. binding.saveOriginalState();
  29757. }
  29758. }
  29759. this._lendAction( action );
  29760. }
  29761. }
  29762. _deactivateAction( action ) {
  29763. if ( this._isActiveAction( action ) ) {
  29764. const bindings = action._propertyBindings;
  29765. // decrement reference counts / sort out state
  29766. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  29767. const binding = bindings[ i ];
  29768. if ( -- binding.useCount === 0 ) {
  29769. binding.restoreOriginalState();
  29770. this._takeBackBinding( binding );
  29771. }
  29772. }
  29773. this._takeBackAction( action );
  29774. }
  29775. }
  29776. // Memory manager
  29777. _initMemoryManager() {
  29778. this._actions = []; // 'nActiveActions' followed by inactive ones
  29779. this._nActiveActions = 0;
  29780. this._actionsByClip = {};
  29781. // inside:
  29782. // {
  29783. // knownActions: Array< AnimationAction > - used as prototypes
  29784. // actionByRoot: AnimationAction - lookup
  29785. // }
  29786. this._bindings = []; // 'nActiveBindings' followed by inactive ones
  29787. this._nActiveBindings = 0;
  29788. this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer >
  29789. this._controlInterpolants = []; // same game as above
  29790. this._nActiveControlInterpolants = 0;
  29791. const scope = this;
  29792. this.stats = {
  29793. actions: {
  29794. get total() {
  29795. return scope._actions.length;
  29796. },
  29797. get inUse() {
  29798. return scope._nActiveActions;
  29799. }
  29800. },
  29801. bindings: {
  29802. get total() {
  29803. return scope._bindings.length;
  29804. },
  29805. get inUse() {
  29806. return scope._nActiveBindings;
  29807. }
  29808. },
  29809. controlInterpolants: {
  29810. get total() {
  29811. return scope._controlInterpolants.length;
  29812. },
  29813. get inUse() {
  29814. return scope._nActiveControlInterpolants;
  29815. }
  29816. }
  29817. };
  29818. }
  29819. // Memory management for AnimationAction objects
  29820. _isActiveAction( action ) {
  29821. const index = action._cacheIndex;
  29822. return index !== null && index < this._nActiveActions;
  29823. }
  29824. _addInactiveAction( action, clipUuid, rootUuid ) {
  29825. const actions = this._actions,
  29826. actionsByClip = this._actionsByClip;
  29827. let actionsForClip = actionsByClip[ clipUuid ];
  29828. if ( actionsForClip === undefined ) {
  29829. actionsForClip = {
  29830. knownActions: [ action ],
  29831. actionByRoot: {}
  29832. };
  29833. action._byClipCacheIndex = 0;
  29834. actionsByClip[ clipUuid ] = actionsForClip;
  29835. } else {
  29836. const knownActions = actionsForClip.knownActions;
  29837. action._byClipCacheIndex = knownActions.length;
  29838. knownActions.push( action );
  29839. }
  29840. action._cacheIndex = actions.length;
  29841. actions.push( action );
  29842. actionsForClip.actionByRoot[ rootUuid ] = action;
  29843. }
  29844. _removeInactiveAction( action ) {
  29845. const actions = this._actions,
  29846. lastInactiveAction = actions[ actions.length - 1 ],
  29847. cacheIndex = action._cacheIndex;
  29848. lastInactiveAction._cacheIndex = cacheIndex;
  29849. actions[ cacheIndex ] = lastInactiveAction;
  29850. actions.pop();
  29851. action._cacheIndex = null;
  29852. const clipUuid = action._clip.uuid,
  29853. actionsByClip = this._actionsByClip,
  29854. actionsForClip = actionsByClip[ clipUuid ],
  29855. knownActionsForClip = actionsForClip.knownActions,
  29856. lastKnownAction =
  29857. knownActionsForClip[ knownActionsForClip.length - 1 ],
  29858. byClipCacheIndex = action._byClipCacheIndex;
  29859. lastKnownAction._byClipCacheIndex = byClipCacheIndex;
  29860. knownActionsForClip[ byClipCacheIndex ] = lastKnownAction;
  29861. knownActionsForClip.pop();
  29862. action._byClipCacheIndex = null;
  29863. const actionByRoot = actionsForClip.actionByRoot,
  29864. rootUuid = ( action._localRoot || this._root ).uuid;
  29865. delete actionByRoot[ rootUuid ];
  29866. if ( knownActionsForClip.length === 0 ) {
  29867. delete actionsByClip[ clipUuid ];
  29868. }
  29869. this._removeInactiveBindingsForAction( action );
  29870. }
  29871. _removeInactiveBindingsForAction( action ) {
  29872. const bindings = action._propertyBindings;
  29873. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  29874. const binding = bindings[ i ];
  29875. if ( -- binding.referenceCount === 0 ) {
  29876. this._removeInactiveBinding( binding );
  29877. }
  29878. }
  29879. }
  29880. _lendAction( action ) {
  29881. // [ active actions | inactive actions ]
  29882. // [ active actions >| inactive actions ]
  29883. // s a
  29884. // <-swap->
  29885. // a s
  29886. const actions = this._actions,
  29887. prevIndex = action._cacheIndex,
  29888. lastActiveIndex = this._nActiveActions ++,
  29889. firstInactiveAction = actions[ lastActiveIndex ];
  29890. action._cacheIndex = lastActiveIndex;
  29891. actions[ lastActiveIndex ] = action;
  29892. firstInactiveAction._cacheIndex = prevIndex;
  29893. actions[ prevIndex ] = firstInactiveAction;
  29894. }
  29895. _takeBackAction( action ) {
  29896. // [ active actions | inactive actions ]
  29897. // [ active actions |< inactive actions ]
  29898. // a s
  29899. // <-swap->
  29900. // s a
  29901. const actions = this._actions,
  29902. prevIndex = action._cacheIndex,
  29903. firstInactiveIndex = -- this._nActiveActions,
  29904. lastActiveAction = actions[ firstInactiveIndex ];
  29905. action._cacheIndex = firstInactiveIndex;
  29906. actions[ firstInactiveIndex ] = action;
  29907. lastActiveAction._cacheIndex = prevIndex;
  29908. actions[ prevIndex ] = lastActiveAction;
  29909. }
  29910. // Memory management for PropertyMixer objects
  29911. _addInactiveBinding( binding, rootUuid, trackName ) {
  29912. const bindingsByRoot = this._bindingsByRootAndName,
  29913. bindings = this._bindings;
  29914. let bindingByName = bindingsByRoot[ rootUuid ];
  29915. if ( bindingByName === undefined ) {
  29916. bindingByName = {};
  29917. bindingsByRoot[ rootUuid ] = bindingByName;
  29918. }
  29919. bindingByName[ trackName ] = binding;
  29920. binding._cacheIndex = bindings.length;
  29921. bindings.push( binding );
  29922. }
  29923. _removeInactiveBinding( binding ) {
  29924. const bindings = this._bindings,
  29925. propBinding = binding.binding,
  29926. rootUuid = propBinding.rootNode.uuid,
  29927. trackName = propBinding.path,
  29928. bindingsByRoot = this._bindingsByRootAndName,
  29929. bindingByName = bindingsByRoot[ rootUuid ],
  29930. lastInactiveBinding = bindings[ bindings.length - 1 ],
  29931. cacheIndex = binding._cacheIndex;
  29932. lastInactiveBinding._cacheIndex = cacheIndex;
  29933. bindings[ cacheIndex ] = lastInactiveBinding;
  29934. bindings.pop();
  29935. delete bindingByName[ trackName ];
  29936. if ( Object.keys( bindingByName ).length === 0 ) {
  29937. delete bindingsByRoot[ rootUuid ];
  29938. }
  29939. }
  29940. _lendBinding( binding ) {
  29941. const bindings = this._bindings,
  29942. prevIndex = binding._cacheIndex,
  29943. lastActiveIndex = this._nActiveBindings ++,
  29944. firstInactiveBinding = bindings[ lastActiveIndex ];
  29945. binding._cacheIndex = lastActiveIndex;
  29946. bindings[ lastActiveIndex ] = binding;
  29947. firstInactiveBinding._cacheIndex = prevIndex;
  29948. bindings[ prevIndex ] = firstInactiveBinding;
  29949. }
  29950. _takeBackBinding( binding ) {
  29951. const bindings = this._bindings,
  29952. prevIndex = binding._cacheIndex,
  29953. firstInactiveIndex = -- this._nActiveBindings,
  29954. lastActiveBinding = bindings[ firstInactiveIndex ];
  29955. binding._cacheIndex = firstInactiveIndex;
  29956. bindings[ firstInactiveIndex ] = binding;
  29957. lastActiveBinding._cacheIndex = prevIndex;
  29958. bindings[ prevIndex ] = lastActiveBinding;
  29959. }
  29960. // Memory management of Interpolants for weight and time scale
  29961. _lendControlInterpolant() {
  29962. const interpolants = this._controlInterpolants,
  29963. lastActiveIndex = this._nActiveControlInterpolants ++;
  29964. let interpolant = interpolants[ lastActiveIndex ];
  29965. if ( interpolant === undefined ) {
  29966. interpolant = new LinearInterpolant(
  29967. new Float32Array( 2 ), new Float32Array( 2 ),
  29968. 1, _controlInterpolantsResultBuffer );
  29969. interpolant.__cacheIndex = lastActiveIndex;
  29970. interpolants[ lastActiveIndex ] = interpolant;
  29971. }
  29972. return interpolant;
  29973. }
  29974. _takeBackControlInterpolant( interpolant ) {
  29975. const interpolants = this._controlInterpolants,
  29976. prevIndex = interpolant.__cacheIndex,
  29977. firstInactiveIndex = -- this._nActiveControlInterpolants,
  29978. lastActiveInterpolant = interpolants[ firstInactiveIndex ];
  29979. interpolant.__cacheIndex = firstInactiveIndex;
  29980. interpolants[ firstInactiveIndex ] = interpolant;
  29981. lastActiveInterpolant.__cacheIndex = prevIndex;
  29982. interpolants[ prevIndex ] = lastActiveInterpolant;
  29983. }
  29984. // return an action for a clip optionally using a custom root target
  29985. // object (this method allocates a lot of dynamic memory in case a
  29986. // previously unknown clip/root combination is specified)
  29987. clipAction( clip, optionalRoot, blendMode ) {
  29988. const root = optionalRoot || this._root,
  29989. rootUuid = root.uuid;
  29990. let clipObject = typeof clip === 'string' ? AnimationClip.findByName( root, clip ) : clip;
  29991. const clipUuid = clipObject !== null ? clipObject.uuid : clip;
  29992. const actionsForClip = this._actionsByClip[ clipUuid ];
  29993. let prototypeAction = null;
  29994. if ( blendMode === undefined ) {
  29995. if ( clipObject !== null ) {
  29996. blendMode = clipObject.blendMode;
  29997. } else {
  29998. blendMode = NormalAnimationBlendMode;
  29999. }
  30000. }
  30001. if ( actionsForClip !== undefined ) {
  30002. const existingAction = actionsForClip.actionByRoot[ rootUuid ];
  30003. if ( existingAction !== undefined && existingAction.blendMode === blendMode ) {
  30004. return existingAction;
  30005. }
  30006. // we know the clip, so we don't have to parse all
  30007. // the bindings again but can just copy
  30008. prototypeAction = actionsForClip.knownActions[ 0 ];
  30009. // also, take the clip from the prototype action
  30010. if ( clipObject === null )
  30011. clipObject = prototypeAction._clip;
  30012. }
  30013. // clip must be known when specified via string
  30014. if ( clipObject === null ) return null;
  30015. // allocate all resources required to run it
  30016. const newAction = new AnimationAction( this, clipObject, optionalRoot, blendMode );
  30017. this._bindAction( newAction, prototypeAction );
  30018. // and make the action known to the memory manager
  30019. this._addInactiveAction( newAction, clipUuid, rootUuid );
  30020. return newAction;
  30021. }
  30022. // get an existing action
  30023. existingAction( clip, optionalRoot ) {
  30024. const root = optionalRoot || this._root,
  30025. rootUuid = root.uuid,
  30026. clipObject = typeof clip === 'string' ?
  30027. AnimationClip.findByName( root, clip ) : clip,
  30028. clipUuid = clipObject ? clipObject.uuid : clip,
  30029. actionsForClip = this._actionsByClip[ clipUuid ];
  30030. if ( actionsForClip !== undefined ) {
  30031. return actionsForClip.actionByRoot[ rootUuid ] || null;
  30032. }
  30033. return null;
  30034. }
  30035. // deactivates all previously scheduled actions
  30036. stopAllAction() {
  30037. const actions = this._actions,
  30038. nActions = this._nActiveActions;
  30039. for ( let i = nActions - 1; i >= 0; -- i ) {
  30040. actions[ i ].stop();
  30041. }
  30042. return this;
  30043. }
  30044. // advance the time and update apply the animation
  30045. update( deltaTime ) {
  30046. deltaTime *= this.timeScale;
  30047. const actions = this._actions,
  30048. nActions = this._nActiveActions,
  30049. time = this.time += deltaTime,
  30050. timeDirection = Math.sign( deltaTime ),
  30051. accuIndex = this._accuIndex ^= 1;
  30052. // run active actions
  30053. for ( let i = 0; i !== nActions; ++ i ) {
  30054. const action = actions[ i ];
  30055. action._update( time, deltaTime, timeDirection, accuIndex );
  30056. }
  30057. // update scene graph
  30058. const bindings = this._bindings,
  30059. nBindings = this._nActiveBindings;
  30060. for ( let i = 0; i !== nBindings; ++ i ) {
  30061. bindings[ i ].apply( accuIndex );
  30062. }
  30063. return this;
  30064. }
  30065. // Allows you to seek to a specific time in an animation.
  30066. setTime( timeInSeconds ) {
  30067. this.time = 0; // Zero out time attribute for AnimationMixer object;
  30068. for ( let i = 0; i < this._actions.length; i ++ ) {
  30069. this._actions[ i ].time = 0; // Zero out time attribute for all associated AnimationAction objects.
  30070. }
  30071. return this.update( timeInSeconds ); // Update used to set exact time. Returns "this" AnimationMixer object.
  30072. }
  30073. // return this mixer's root target object
  30074. getRoot() {
  30075. return this._root;
  30076. }
  30077. // free all resources specific to a particular clip
  30078. uncacheClip( clip ) {
  30079. const actions = this._actions,
  30080. clipUuid = clip.uuid,
  30081. actionsByClip = this._actionsByClip,
  30082. actionsForClip = actionsByClip[ clipUuid ];
  30083. if ( actionsForClip !== undefined ) {
  30084. // note: just calling _removeInactiveAction would mess up the
  30085. // iteration state and also require updating the state we can
  30086. // just throw away
  30087. const actionsToRemove = actionsForClip.knownActions;
  30088. for ( let i = 0, n = actionsToRemove.length; i !== n; ++ i ) {
  30089. const action = actionsToRemove[ i ];
  30090. this._deactivateAction( action );
  30091. const cacheIndex = action._cacheIndex,
  30092. lastInactiveAction = actions[ actions.length - 1 ];
  30093. action._cacheIndex = null;
  30094. action._byClipCacheIndex = null;
  30095. lastInactiveAction._cacheIndex = cacheIndex;
  30096. actions[ cacheIndex ] = lastInactiveAction;
  30097. actions.pop();
  30098. this._removeInactiveBindingsForAction( action );
  30099. }
  30100. delete actionsByClip[ clipUuid ];
  30101. }
  30102. }
  30103. // free all resources specific to a particular root target object
  30104. uncacheRoot( root ) {
  30105. const rootUuid = root.uuid,
  30106. actionsByClip = this._actionsByClip;
  30107. for ( const clipUuid in actionsByClip ) {
  30108. const actionByRoot = actionsByClip[ clipUuid ].actionByRoot,
  30109. action = actionByRoot[ rootUuid ];
  30110. if ( action !== undefined ) {
  30111. this._deactivateAction( action );
  30112. this._removeInactiveAction( action );
  30113. }
  30114. }
  30115. const bindingsByRoot = this._bindingsByRootAndName,
  30116. bindingByName = bindingsByRoot[ rootUuid ];
  30117. if ( bindingByName !== undefined ) {
  30118. for ( const trackName in bindingByName ) {
  30119. const binding = bindingByName[ trackName ];
  30120. binding.restoreOriginalState();
  30121. this._removeInactiveBinding( binding );
  30122. }
  30123. }
  30124. }
  30125. // remove a targeted clip from the cache
  30126. uncacheAction( clip, optionalRoot ) {
  30127. const action = this.existingAction( clip, optionalRoot );
  30128. if ( action !== null ) {
  30129. this._deactivateAction( action );
  30130. this._removeInactiveAction( action );
  30131. }
  30132. }
  30133. }
  30134. class Uniform {
  30135. constructor( value ) {
  30136. this.value = value;
  30137. }
  30138. clone() {
  30139. return new Uniform( this.value.clone === undefined ? this.value : this.value.clone() );
  30140. }
  30141. }
  30142. let _id = 0;
  30143. class UniformsGroup extends EventDispatcher {
  30144. constructor() {
  30145. super();
  30146. this.isUniformsGroup = true;
  30147. Object.defineProperty( this, 'id', { value: _id ++ } );
  30148. this.name = '';
  30149. this.usage = StaticDrawUsage;
  30150. this.uniforms = [];
  30151. }
  30152. add( uniform ) {
  30153. this.uniforms.push( uniform );
  30154. return this;
  30155. }
  30156. remove( uniform ) {
  30157. const index = this.uniforms.indexOf( uniform );
  30158. if ( index !== - 1 ) this.uniforms.splice( index, 1 );
  30159. return this;
  30160. }
  30161. setName( name ) {
  30162. this.name = name;
  30163. return this;
  30164. }
  30165. setUsage( value ) {
  30166. this.usage = value;
  30167. return this;
  30168. }
  30169. dispose() {
  30170. this.dispatchEvent( { type: 'dispose' } );
  30171. return this;
  30172. }
  30173. copy( source ) {
  30174. this.name = source.name;
  30175. this.usage = source.usage;
  30176. const uniformsSource = source.uniforms;
  30177. this.uniforms.length = 0;
  30178. for ( let i = 0, l = uniformsSource.length; i < l; i ++ ) {
  30179. const uniforms = Array.isArray( uniformsSource[ i ] ) ? uniformsSource[ i ] : [ uniformsSource[ i ] ];
  30180. for ( let j = 0; j < uniforms.length; j ++ ) {
  30181. this.uniforms.push( uniforms[ j ].clone() );
  30182. }
  30183. }
  30184. return this;
  30185. }
  30186. clone() {
  30187. return new this.constructor().copy( this );
  30188. }
  30189. }
  30190. class InstancedInterleavedBuffer extends InterleavedBuffer {
  30191. constructor( array, stride, meshPerAttribute = 1 ) {
  30192. super( array, stride );
  30193. this.isInstancedInterleavedBuffer = true;
  30194. this.meshPerAttribute = meshPerAttribute;
  30195. }
  30196. copy( source ) {
  30197. super.copy( source );
  30198. this.meshPerAttribute = source.meshPerAttribute;
  30199. return this;
  30200. }
  30201. clone( data ) {
  30202. const ib = super.clone( data );
  30203. ib.meshPerAttribute = this.meshPerAttribute;
  30204. return ib;
  30205. }
  30206. toJSON( data ) {
  30207. const json = super.toJSON( data );
  30208. json.isInstancedInterleavedBuffer = true;
  30209. json.meshPerAttribute = this.meshPerAttribute;
  30210. return json;
  30211. }
  30212. }
  30213. class GLBufferAttribute {
  30214. constructor( buffer, type, itemSize, elementSize, count ) {
  30215. this.isGLBufferAttribute = true;
  30216. this.name = '';
  30217. this.buffer = buffer;
  30218. this.type = type;
  30219. this.itemSize = itemSize;
  30220. this.elementSize = elementSize;
  30221. this.count = count;
  30222. this.version = 0;
  30223. }
  30224. set needsUpdate( value ) {
  30225. if ( value === true ) this.version ++;
  30226. }
  30227. setBuffer( buffer ) {
  30228. this.buffer = buffer;
  30229. return this;
  30230. }
  30231. setType( type, elementSize ) {
  30232. this.type = type;
  30233. this.elementSize = elementSize;
  30234. return this;
  30235. }
  30236. setItemSize( itemSize ) {
  30237. this.itemSize = itemSize;
  30238. return this;
  30239. }
  30240. setCount( count ) {
  30241. this.count = count;
  30242. return this;
  30243. }
  30244. }
  30245. class Raycaster {
  30246. constructor( origin, direction, near = 0, far = Infinity ) {
  30247. this.ray = new Ray( origin, direction );
  30248. // direction is assumed to be normalized (for accurate distance calculations)
  30249. this.near = near;
  30250. this.far = far;
  30251. this.camera = null;
  30252. this.layers = new Layers();
  30253. this.params = {
  30254. Mesh: {},
  30255. Line: { threshold: 1 },
  30256. LOD: {},
  30257. Points: { threshold: 1 },
  30258. Sprite: {}
  30259. };
  30260. }
  30261. set( origin, direction ) {
  30262. // direction is assumed to be normalized (for accurate distance calculations)
  30263. this.ray.set( origin, direction );
  30264. }
  30265. setFromCamera( coords, camera ) {
  30266. if ( camera.isPerspectiveCamera ) {
  30267. this.ray.origin.setFromMatrixPosition( camera.matrixWorld );
  30268. this.ray.direction.set( coords.x, coords.y, 0.5 ).unproject( camera ).sub( this.ray.origin ).normalize();
  30269. this.camera = camera;
  30270. } else if ( camera.isOrthographicCamera ) {
  30271. this.ray.origin.set( coords.x, coords.y, ( camera.near + camera.far ) / ( camera.near - camera.far ) ).unproject( camera ); // set origin in plane of camera
  30272. this.ray.direction.set( 0, 0, - 1 ).transformDirection( camera.matrixWorld );
  30273. this.camera = camera;
  30274. } else {
  30275. console.error( 'THREE.Raycaster: Unsupported camera type: ' + camera.type );
  30276. }
  30277. }
  30278. intersectObject( object, recursive = true, intersects = [] ) {
  30279. intersectObject( object, this, intersects, recursive );
  30280. intersects.sort( ascSort );
  30281. return intersects;
  30282. }
  30283. intersectObjects( objects, recursive = true, intersects = [] ) {
  30284. for ( let i = 0, l = objects.length; i < l; i ++ ) {
  30285. intersectObject( objects[ i ], this, intersects, recursive );
  30286. }
  30287. intersects.sort( ascSort );
  30288. return intersects;
  30289. }
  30290. }
  30291. function ascSort( a, b ) {
  30292. return a.distance - b.distance;
  30293. }
  30294. function intersectObject( object, raycaster, intersects, recursive ) {
  30295. if ( object.layers.test( raycaster.layers ) ) {
  30296. object.raycast( raycaster, intersects );
  30297. }
  30298. if ( recursive === true ) {
  30299. const children = object.children;
  30300. for ( let i = 0, l = children.length; i < l; i ++ ) {
  30301. intersectObject( children[ i ], raycaster, intersects, true );
  30302. }
  30303. }
  30304. }
  30305. /**
  30306. * Ref: https://en.wikipedia.org/wiki/Spherical_coordinate_system
  30307. *
  30308. * The polar angle (phi) is measured from the positive y-axis. The positive y-axis is up.
  30309. * The azimuthal angle (theta) is measured from the positive z-axis.
  30310. */
  30311. class Spherical {
  30312. constructor( radius = 1, phi = 0, theta = 0 ) {
  30313. this.radius = radius;
  30314. this.phi = phi; // polar angle
  30315. this.theta = theta; // azimuthal angle
  30316. return this;
  30317. }
  30318. set( radius, phi, theta ) {
  30319. this.radius = radius;
  30320. this.phi = phi;
  30321. this.theta = theta;
  30322. return this;
  30323. }
  30324. copy( other ) {
  30325. this.radius = other.radius;
  30326. this.phi = other.phi;
  30327. this.theta = other.theta;
  30328. return this;
  30329. }
  30330. // restrict phi to be between EPS and PI-EPS
  30331. makeSafe() {
  30332. const EPS = 0.000001;
  30333. this.phi = Math.max( EPS, Math.min( Math.PI - EPS, this.phi ) );
  30334. return this;
  30335. }
  30336. setFromVector3( v ) {
  30337. return this.setFromCartesianCoords( v.x, v.y, v.z );
  30338. }
  30339. setFromCartesianCoords( x, y, z ) {
  30340. this.radius = Math.sqrt( x * x + y * y + z * z );
  30341. if ( this.radius === 0 ) {
  30342. this.theta = 0;
  30343. this.phi = 0;
  30344. } else {
  30345. this.theta = Math.atan2( x, z );
  30346. this.phi = Math.acos( clamp( y / this.radius, - 1, 1 ) );
  30347. }
  30348. return this;
  30349. }
  30350. clone() {
  30351. return new this.constructor().copy( this );
  30352. }
  30353. }
  30354. /**
  30355. * Ref: https://en.wikipedia.org/wiki/Cylindrical_coordinate_system
  30356. */
  30357. class Cylindrical {
  30358. constructor( radius = 1, theta = 0, y = 0 ) {
  30359. this.radius = radius; // distance from the origin to a point in the x-z plane
  30360. this.theta = theta; // counterclockwise angle in the x-z plane measured in radians from the positive z-axis
  30361. this.y = y; // height above the x-z plane
  30362. return this;
  30363. }
  30364. set( radius, theta, y ) {
  30365. this.radius = radius;
  30366. this.theta = theta;
  30367. this.y = y;
  30368. return this;
  30369. }
  30370. copy( other ) {
  30371. this.radius = other.radius;
  30372. this.theta = other.theta;
  30373. this.y = other.y;
  30374. return this;
  30375. }
  30376. setFromVector3( v ) {
  30377. return this.setFromCartesianCoords( v.x, v.y, v.z );
  30378. }
  30379. setFromCartesianCoords( x, y, z ) {
  30380. this.radius = Math.sqrt( x * x + z * z );
  30381. this.theta = Math.atan2( x, z );
  30382. this.y = y;
  30383. return this;
  30384. }
  30385. clone() {
  30386. return new this.constructor().copy( this );
  30387. }
  30388. }
  30389. const _vector$4 = /*@__PURE__*/ new Vector2();
  30390. class Box2 {
  30391. constructor( min = new Vector2( + Infinity, + Infinity ), max = new Vector2( - Infinity, - Infinity ) ) {
  30392. this.isBox2 = true;
  30393. this.min = min;
  30394. this.max = max;
  30395. }
  30396. set( min, max ) {
  30397. this.min.copy( min );
  30398. this.max.copy( max );
  30399. return this;
  30400. }
  30401. setFromPoints( points ) {
  30402. this.makeEmpty();
  30403. for ( let i = 0, il = points.length; i < il; i ++ ) {
  30404. this.expandByPoint( points[ i ] );
  30405. }
  30406. return this;
  30407. }
  30408. setFromCenterAndSize( center, size ) {
  30409. const halfSize = _vector$4.copy( size ).multiplyScalar( 0.5 );
  30410. this.min.copy( center ).sub( halfSize );
  30411. this.max.copy( center ).add( halfSize );
  30412. return this;
  30413. }
  30414. clone() {
  30415. return new this.constructor().copy( this );
  30416. }
  30417. copy( box ) {
  30418. this.min.copy( box.min );
  30419. this.max.copy( box.max );
  30420. return this;
  30421. }
  30422. makeEmpty() {
  30423. this.min.x = this.min.y = + Infinity;
  30424. this.max.x = this.max.y = - Infinity;
  30425. return this;
  30426. }
  30427. isEmpty() {
  30428. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  30429. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y );
  30430. }
  30431. getCenter( target ) {
  30432. return this.isEmpty() ? target.set( 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  30433. }
  30434. getSize( target ) {
  30435. return this.isEmpty() ? target.set( 0, 0 ) : target.subVectors( this.max, this.min );
  30436. }
  30437. expandByPoint( point ) {
  30438. this.min.min( point );
  30439. this.max.max( point );
  30440. return this;
  30441. }
  30442. expandByVector( vector ) {
  30443. this.min.sub( vector );
  30444. this.max.add( vector );
  30445. return this;
  30446. }
  30447. expandByScalar( scalar ) {
  30448. this.min.addScalar( - scalar );
  30449. this.max.addScalar( scalar );
  30450. return this;
  30451. }
  30452. containsPoint( point ) {
  30453. return point.x < this.min.x || point.x > this.max.x ||
  30454. point.y < this.min.y || point.y > this.max.y ? false : true;
  30455. }
  30456. containsBox( box ) {
  30457. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  30458. this.min.y <= box.min.y && box.max.y <= this.max.y;
  30459. }
  30460. getParameter( point, target ) {
  30461. // This can potentially have a divide by zero if the box
  30462. // has a size dimension of 0.
  30463. return target.set(
  30464. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  30465. ( point.y - this.min.y ) / ( this.max.y - this.min.y )
  30466. );
  30467. }
  30468. intersectsBox( box ) {
  30469. // using 4 splitting planes to rule out intersections
  30470. return box.max.x < this.min.x || box.min.x > this.max.x ||
  30471. box.max.y < this.min.y || box.min.y > this.max.y ? false : true;
  30472. }
  30473. clampPoint( point, target ) {
  30474. return target.copy( point ).clamp( this.min, this.max );
  30475. }
  30476. distanceToPoint( point ) {
  30477. return this.clampPoint( point, _vector$4 ).distanceTo( point );
  30478. }
  30479. intersect( box ) {
  30480. this.min.max( box.min );
  30481. this.max.min( box.max );
  30482. if ( this.isEmpty() ) this.makeEmpty();
  30483. return this;
  30484. }
  30485. union( box ) {
  30486. this.min.min( box.min );
  30487. this.max.max( box.max );
  30488. return this;
  30489. }
  30490. translate( offset ) {
  30491. this.min.add( offset );
  30492. this.max.add( offset );
  30493. return this;
  30494. }
  30495. equals( box ) {
  30496. return box.min.equals( this.min ) && box.max.equals( this.max );
  30497. }
  30498. }
  30499. const _startP = /*@__PURE__*/ new Vector3();
  30500. const _startEnd = /*@__PURE__*/ new Vector3();
  30501. class Line3 {
  30502. constructor( start = new Vector3(), end = new Vector3() ) {
  30503. this.start = start;
  30504. this.end = end;
  30505. }
  30506. set( start, end ) {
  30507. this.start.copy( start );
  30508. this.end.copy( end );
  30509. return this;
  30510. }
  30511. copy( line ) {
  30512. this.start.copy( line.start );
  30513. this.end.copy( line.end );
  30514. return this;
  30515. }
  30516. getCenter( target ) {
  30517. return target.addVectors( this.start, this.end ).multiplyScalar( 0.5 );
  30518. }
  30519. delta( target ) {
  30520. return target.subVectors( this.end, this.start );
  30521. }
  30522. distanceSq() {
  30523. return this.start.distanceToSquared( this.end );
  30524. }
  30525. distance() {
  30526. return this.start.distanceTo( this.end );
  30527. }
  30528. at( t, target ) {
  30529. return this.delta( target ).multiplyScalar( t ).add( this.start );
  30530. }
  30531. closestPointToPointParameter( point, clampToLine ) {
  30532. _startP.subVectors( point, this.start );
  30533. _startEnd.subVectors( this.end, this.start );
  30534. const startEnd2 = _startEnd.dot( _startEnd );
  30535. const startEnd_startP = _startEnd.dot( _startP );
  30536. let t = startEnd_startP / startEnd2;
  30537. if ( clampToLine ) {
  30538. t = clamp( t, 0, 1 );
  30539. }
  30540. return t;
  30541. }
  30542. closestPointToPoint( point, clampToLine, target ) {
  30543. const t = this.closestPointToPointParameter( point, clampToLine );
  30544. return this.delta( target ).multiplyScalar( t ).add( this.start );
  30545. }
  30546. applyMatrix4( matrix ) {
  30547. this.start.applyMatrix4( matrix );
  30548. this.end.applyMatrix4( matrix );
  30549. return this;
  30550. }
  30551. equals( line ) {
  30552. return line.start.equals( this.start ) && line.end.equals( this.end );
  30553. }
  30554. clone() {
  30555. return new this.constructor().copy( this );
  30556. }
  30557. }
  30558. const _vector$3 = /*@__PURE__*/ new Vector3();
  30559. class SpotLightHelper extends Object3D {
  30560. constructor( light, color ) {
  30561. super();
  30562. this.light = light;
  30563. this.matrix = light.matrixWorld;
  30564. this.matrixAutoUpdate = false;
  30565. this.color = color;
  30566. this.type = 'SpotLightHelper';
  30567. const geometry = new BufferGeometry();
  30568. const positions = [
  30569. 0, 0, 0, 0, 0, 1,
  30570. 0, 0, 0, 1, 0, 1,
  30571. 0, 0, 0, - 1, 0, 1,
  30572. 0, 0, 0, 0, 1, 1,
  30573. 0, 0, 0, 0, - 1, 1
  30574. ];
  30575. for ( let i = 0, j = 1, l = 32; i < l; i ++, j ++ ) {
  30576. const p1 = ( i / l ) * Math.PI * 2;
  30577. const p2 = ( j / l ) * Math.PI * 2;
  30578. positions.push(
  30579. Math.cos( p1 ), Math.sin( p1 ), 1,
  30580. Math.cos( p2 ), Math.sin( p2 ), 1
  30581. );
  30582. }
  30583. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  30584. const material = new LineBasicMaterial( { fog: false, toneMapped: false } );
  30585. this.cone = new LineSegments( geometry, material );
  30586. this.add( this.cone );
  30587. this.update();
  30588. }
  30589. dispose() {
  30590. this.cone.geometry.dispose();
  30591. this.cone.material.dispose();
  30592. }
  30593. update() {
  30594. this.light.updateWorldMatrix( true, false );
  30595. this.light.target.updateWorldMatrix( true, false );
  30596. const coneLength = this.light.distance ? this.light.distance : 1000;
  30597. const coneWidth = coneLength * Math.tan( this.light.angle );
  30598. this.cone.scale.set( coneWidth, coneWidth, coneLength );
  30599. _vector$3.setFromMatrixPosition( this.light.target.matrixWorld );
  30600. this.cone.lookAt( _vector$3 );
  30601. if ( this.color !== undefined ) {
  30602. this.cone.material.color.set( this.color );
  30603. } else {
  30604. this.cone.material.color.copy( this.light.color );
  30605. }
  30606. }
  30607. }
  30608. const _vector$2 = /*@__PURE__*/ new Vector3();
  30609. const _boneMatrix = /*@__PURE__*/ new Matrix4();
  30610. const _matrixWorldInv = /*@__PURE__*/ new Matrix4();
  30611. class SkeletonHelper extends LineSegments {
  30612. constructor( object ) {
  30613. const bones = getBoneList( object );
  30614. const geometry = new BufferGeometry();
  30615. const vertices = [];
  30616. const colors = [];
  30617. const color1 = new Color( 0, 0, 1 );
  30618. const color2 = new Color( 0, 1, 0 );
  30619. for ( let i = 0; i < bones.length; i ++ ) {
  30620. const bone = bones[ i ];
  30621. if ( bone.parent && bone.parent.isBone ) {
  30622. vertices.push( 0, 0, 0 );
  30623. vertices.push( 0, 0, 0 );
  30624. colors.push( color1.r, color1.g, color1.b );
  30625. colors.push( color2.r, color2.g, color2.b );
  30626. }
  30627. }
  30628. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  30629. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  30630. const material = new LineBasicMaterial( { vertexColors: true, depthTest: false, depthWrite: false, toneMapped: false, transparent: true } );
  30631. super( geometry, material );
  30632. this.isSkeletonHelper = true;
  30633. this.type = 'SkeletonHelper';
  30634. this.root = object;
  30635. this.bones = bones;
  30636. this.matrix = object.matrixWorld;
  30637. this.matrixAutoUpdate = false;
  30638. }
  30639. updateMatrixWorld( force ) {
  30640. const bones = this.bones;
  30641. const geometry = this.geometry;
  30642. const position = geometry.getAttribute( 'position' );
  30643. _matrixWorldInv.copy( this.root.matrixWorld ).invert();
  30644. for ( let i = 0, j = 0; i < bones.length; i ++ ) {
  30645. const bone = bones[ i ];
  30646. if ( bone.parent && bone.parent.isBone ) {
  30647. _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.matrixWorld );
  30648. _vector$2.setFromMatrixPosition( _boneMatrix );
  30649. position.setXYZ( j, _vector$2.x, _vector$2.y, _vector$2.z );
  30650. _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.parent.matrixWorld );
  30651. _vector$2.setFromMatrixPosition( _boneMatrix );
  30652. position.setXYZ( j + 1, _vector$2.x, _vector$2.y, _vector$2.z );
  30653. j += 2;
  30654. }
  30655. }
  30656. geometry.getAttribute( 'position' ).needsUpdate = true;
  30657. super.updateMatrixWorld( force );
  30658. }
  30659. dispose() {
  30660. this.geometry.dispose();
  30661. this.material.dispose();
  30662. }
  30663. }
  30664. function getBoneList( object ) {
  30665. const boneList = [];
  30666. if ( object.isBone === true ) {
  30667. boneList.push( object );
  30668. }
  30669. for ( let i = 0; i < object.children.length; i ++ ) {
  30670. boneList.push.apply( boneList, getBoneList( object.children[ i ] ) );
  30671. }
  30672. return boneList;
  30673. }
  30674. class PointLightHelper extends Mesh {
  30675. constructor( light, sphereSize, color ) {
  30676. const geometry = new SphereGeometry( sphereSize, 4, 2 );
  30677. const material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );
  30678. super( geometry, material );
  30679. this.light = light;
  30680. this.color = color;
  30681. this.type = 'PointLightHelper';
  30682. this.matrix = this.light.matrixWorld;
  30683. this.matrixAutoUpdate = false;
  30684. this.update();
  30685. /*
  30686. // TODO: delete this comment?
  30687. const distanceGeometry = new THREE.IcosahedronGeometry( 1, 2 );
  30688. const distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  30689. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  30690. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  30691. const d = light.distance;
  30692. if ( d === 0.0 ) {
  30693. this.lightDistance.visible = false;
  30694. } else {
  30695. this.lightDistance.scale.set( d, d, d );
  30696. }
  30697. this.add( this.lightDistance );
  30698. */
  30699. }
  30700. dispose() {
  30701. this.geometry.dispose();
  30702. this.material.dispose();
  30703. }
  30704. update() {
  30705. this.light.updateWorldMatrix( true, false );
  30706. if ( this.color !== undefined ) {
  30707. this.material.color.set( this.color );
  30708. } else {
  30709. this.material.color.copy( this.light.color );
  30710. }
  30711. /*
  30712. const d = this.light.distance;
  30713. if ( d === 0.0 ) {
  30714. this.lightDistance.visible = false;
  30715. } else {
  30716. this.lightDistance.visible = true;
  30717. this.lightDistance.scale.set( d, d, d );
  30718. }
  30719. */
  30720. }
  30721. }
  30722. const _vector$1 = /*@__PURE__*/ new Vector3();
  30723. const _color1 = /*@__PURE__*/ new Color();
  30724. const _color2 = /*@__PURE__*/ new Color();
  30725. class HemisphereLightHelper extends Object3D {
  30726. constructor( light, size, color ) {
  30727. super();
  30728. this.light = light;
  30729. this.matrix = light.matrixWorld;
  30730. this.matrixAutoUpdate = false;
  30731. this.color = color;
  30732. this.type = 'HemisphereLightHelper';
  30733. const geometry = new OctahedronGeometry( size );
  30734. geometry.rotateY( Math.PI * 0.5 );
  30735. this.material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );
  30736. if ( this.color === undefined ) this.material.vertexColors = true;
  30737. const position = geometry.getAttribute( 'position' );
  30738. const colors = new Float32Array( position.count * 3 );
  30739. geometry.setAttribute( 'color', new BufferAttribute( colors, 3 ) );
  30740. this.add( new Mesh( geometry, this.material ) );
  30741. this.update();
  30742. }
  30743. dispose() {
  30744. this.children[ 0 ].geometry.dispose();
  30745. this.children[ 0 ].material.dispose();
  30746. }
  30747. update() {
  30748. const mesh = this.children[ 0 ];
  30749. if ( this.color !== undefined ) {
  30750. this.material.color.set( this.color );
  30751. } else {
  30752. const colors = mesh.geometry.getAttribute( 'color' );
  30753. _color1.copy( this.light.color );
  30754. _color2.copy( this.light.groundColor );
  30755. for ( let i = 0, l = colors.count; i < l; i ++ ) {
  30756. const color = ( i < ( l / 2 ) ) ? _color1 : _color2;
  30757. colors.setXYZ( i, color.r, color.g, color.b );
  30758. }
  30759. colors.needsUpdate = true;
  30760. }
  30761. this.light.updateWorldMatrix( true, false );
  30762. mesh.lookAt( _vector$1.setFromMatrixPosition( this.light.matrixWorld ).negate() );
  30763. }
  30764. }
  30765. class GridHelper extends LineSegments {
  30766. constructor( size = 10, divisions = 10, color1 = 0x444444, color2 = 0x888888 ) {
  30767. color1 = new Color( color1 );
  30768. color2 = new Color( color2 );
  30769. const center = divisions / 2;
  30770. const step = size / divisions;
  30771. const halfSize = size / 2;
  30772. const vertices = [], colors = [];
  30773. for ( let i = 0, j = 0, k = - halfSize; i <= divisions; i ++, k += step ) {
  30774. vertices.push( - halfSize, 0, k, halfSize, 0, k );
  30775. vertices.push( k, 0, - halfSize, k, 0, halfSize );
  30776. const color = i === center ? color1 : color2;
  30777. color.toArray( colors, j ); j += 3;
  30778. color.toArray( colors, j ); j += 3;
  30779. color.toArray( colors, j ); j += 3;
  30780. color.toArray( colors, j ); j += 3;
  30781. }
  30782. const geometry = new BufferGeometry();
  30783. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  30784. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  30785. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  30786. super( geometry, material );
  30787. this.type = 'GridHelper';
  30788. }
  30789. dispose() {
  30790. this.geometry.dispose();
  30791. this.material.dispose();
  30792. }
  30793. }
  30794. class PolarGridHelper extends LineSegments {
  30795. constructor( radius = 10, sectors = 16, rings = 8, divisions = 64, color1 = 0x444444, color2 = 0x888888 ) {
  30796. color1 = new Color( color1 );
  30797. color2 = new Color( color2 );
  30798. const vertices = [];
  30799. const colors = [];
  30800. // create the sectors
  30801. if ( sectors > 1 ) {
  30802. for ( let i = 0; i < sectors; i ++ ) {
  30803. const v = ( i / sectors ) * ( Math.PI * 2 );
  30804. const x = Math.sin( v ) * radius;
  30805. const z = Math.cos( v ) * radius;
  30806. vertices.push( 0, 0, 0 );
  30807. vertices.push( x, 0, z );
  30808. const color = ( i & 1 ) ? color1 : color2;
  30809. colors.push( color.r, color.g, color.b );
  30810. colors.push( color.r, color.g, color.b );
  30811. }
  30812. }
  30813. // create the rings
  30814. for ( let i = 0; i < rings; i ++ ) {
  30815. const color = ( i & 1 ) ? color1 : color2;
  30816. const r = radius - ( radius / rings * i );
  30817. for ( let j = 0; j < divisions; j ++ ) {
  30818. // first vertex
  30819. let v = ( j / divisions ) * ( Math.PI * 2 );
  30820. let x = Math.sin( v ) * r;
  30821. let z = Math.cos( v ) * r;
  30822. vertices.push( x, 0, z );
  30823. colors.push( color.r, color.g, color.b );
  30824. // second vertex
  30825. v = ( ( j + 1 ) / divisions ) * ( Math.PI * 2 );
  30826. x = Math.sin( v ) * r;
  30827. z = Math.cos( v ) * r;
  30828. vertices.push( x, 0, z );
  30829. colors.push( color.r, color.g, color.b );
  30830. }
  30831. }
  30832. const geometry = new BufferGeometry();
  30833. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  30834. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  30835. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  30836. super( geometry, material );
  30837. this.type = 'PolarGridHelper';
  30838. }
  30839. dispose() {
  30840. this.geometry.dispose();
  30841. this.material.dispose();
  30842. }
  30843. }
  30844. const _v1 = /*@__PURE__*/ new Vector3();
  30845. const _v2 = /*@__PURE__*/ new Vector3();
  30846. const _v3 = /*@__PURE__*/ new Vector3();
  30847. class DirectionalLightHelper extends Object3D {
  30848. constructor( light, size, color ) {
  30849. super();
  30850. this.light = light;
  30851. this.matrix = light.matrixWorld;
  30852. this.matrixAutoUpdate = false;
  30853. this.color = color;
  30854. this.type = 'DirectionalLightHelper';
  30855. if ( size === undefined ) size = 1;
  30856. let geometry = new BufferGeometry();
  30857. geometry.setAttribute( 'position', new Float32BufferAttribute( [
  30858. - size, size, 0,
  30859. size, size, 0,
  30860. size, - size, 0,
  30861. - size, - size, 0,
  30862. - size, size, 0
  30863. ], 3 ) );
  30864. const material = new LineBasicMaterial( { fog: false, toneMapped: false } );
  30865. this.lightPlane = new Line( geometry, material );
  30866. this.add( this.lightPlane );
  30867. geometry = new BufferGeometry();
  30868. geometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 0, 1 ], 3 ) );
  30869. this.targetLine = new Line( geometry, material );
  30870. this.add( this.targetLine );
  30871. this.update();
  30872. }
  30873. dispose() {
  30874. this.lightPlane.geometry.dispose();
  30875. this.lightPlane.material.dispose();
  30876. this.targetLine.geometry.dispose();
  30877. this.targetLine.material.dispose();
  30878. }
  30879. update() {
  30880. this.light.updateWorldMatrix( true, false );
  30881. this.light.target.updateWorldMatrix( true, false );
  30882. _v1.setFromMatrixPosition( this.light.matrixWorld );
  30883. _v2.setFromMatrixPosition( this.light.target.matrixWorld );
  30884. _v3.subVectors( _v2, _v1 );
  30885. this.lightPlane.lookAt( _v2 );
  30886. if ( this.color !== undefined ) {
  30887. this.lightPlane.material.color.set( this.color );
  30888. this.targetLine.material.color.set( this.color );
  30889. } else {
  30890. this.lightPlane.material.color.copy( this.light.color );
  30891. this.targetLine.material.color.copy( this.light.color );
  30892. }
  30893. this.targetLine.lookAt( _v2 );
  30894. this.targetLine.scale.z = _v3.length();
  30895. }
  30896. }
  30897. const _vector = /*@__PURE__*/ new Vector3();
  30898. const _camera = /*@__PURE__*/ new Camera();
  30899. /**
  30900. * - shows frustum, line of sight and up of the camera
  30901. * - suitable for fast updates
  30902. * - based on frustum visualization in lightgl.js shadowmap example
  30903. * https://github.com/evanw/lightgl.js/blob/master/tests/shadowmap.html
  30904. */
  30905. class CameraHelper extends LineSegments {
  30906. constructor( camera ) {
  30907. const geometry = new BufferGeometry();
  30908. const material = new LineBasicMaterial( { color: 0xffffff, vertexColors: true, toneMapped: false } );
  30909. const vertices = [];
  30910. const colors = [];
  30911. const pointMap = {};
  30912. // near
  30913. addLine( 'n1', 'n2' );
  30914. addLine( 'n2', 'n4' );
  30915. addLine( 'n4', 'n3' );
  30916. addLine( 'n3', 'n1' );
  30917. // far
  30918. addLine( 'f1', 'f2' );
  30919. addLine( 'f2', 'f4' );
  30920. addLine( 'f4', 'f3' );
  30921. addLine( 'f3', 'f1' );
  30922. // sides
  30923. addLine( 'n1', 'f1' );
  30924. addLine( 'n2', 'f2' );
  30925. addLine( 'n3', 'f3' );
  30926. addLine( 'n4', 'f4' );
  30927. // cone
  30928. addLine( 'p', 'n1' );
  30929. addLine( 'p', 'n2' );
  30930. addLine( 'p', 'n3' );
  30931. addLine( 'p', 'n4' );
  30932. // up
  30933. addLine( 'u1', 'u2' );
  30934. addLine( 'u2', 'u3' );
  30935. addLine( 'u3', 'u1' );
  30936. // target
  30937. addLine( 'c', 't' );
  30938. addLine( 'p', 'c' );
  30939. // cross
  30940. addLine( 'cn1', 'cn2' );
  30941. addLine( 'cn3', 'cn4' );
  30942. addLine( 'cf1', 'cf2' );
  30943. addLine( 'cf3', 'cf4' );
  30944. function addLine( a, b ) {
  30945. addPoint( a );
  30946. addPoint( b );
  30947. }
  30948. function addPoint( id ) {
  30949. vertices.push( 0, 0, 0 );
  30950. colors.push( 0, 0, 0 );
  30951. if ( pointMap[ id ] === undefined ) {
  30952. pointMap[ id ] = [];
  30953. }
  30954. pointMap[ id ].push( ( vertices.length / 3 ) - 1 );
  30955. }
  30956. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  30957. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  30958. super( geometry, material );
  30959. this.type = 'CameraHelper';
  30960. this.camera = camera;
  30961. if ( this.camera.updateProjectionMatrix ) this.camera.updateProjectionMatrix();
  30962. this.matrix = camera.matrixWorld;
  30963. this.matrixAutoUpdate = false;
  30964. this.pointMap = pointMap;
  30965. this.update();
  30966. // colors
  30967. const colorFrustum = new Color( 0xffaa00 );
  30968. const colorCone = new Color( 0xff0000 );
  30969. const colorUp = new Color( 0x00aaff );
  30970. const colorTarget = new Color( 0xffffff );
  30971. const colorCross = new Color( 0x333333 );
  30972. this.setColors( colorFrustum, colorCone, colorUp, colorTarget, colorCross );
  30973. }
  30974. setColors( frustum, cone, up, target, cross ) {
  30975. const geometry = this.geometry;
  30976. const colorAttribute = geometry.getAttribute( 'color' );
  30977. // near
  30978. colorAttribute.setXYZ( 0, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 1, frustum.r, frustum.g, frustum.b ); // n1, n2
  30979. colorAttribute.setXYZ( 2, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 3, frustum.r, frustum.g, frustum.b ); // n2, n4
  30980. colorAttribute.setXYZ( 4, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 5, frustum.r, frustum.g, frustum.b ); // n4, n3
  30981. colorAttribute.setXYZ( 6, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 7, frustum.r, frustum.g, frustum.b ); // n3, n1
  30982. // far
  30983. colorAttribute.setXYZ( 8, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 9, frustum.r, frustum.g, frustum.b ); // f1, f2
  30984. colorAttribute.setXYZ( 10, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 11, frustum.r, frustum.g, frustum.b ); // f2, f4
  30985. colorAttribute.setXYZ( 12, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 13, frustum.r, frustum.g, frustum.b ); // f4, f3
  30986. colorAttribute.setXYZ( 14, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 15, frustum.r, frustum.g, frustum.b ); // f3, f1
  30987. // sides
  30988. colorAttribute.setXYZ( 16, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 17, frustum.r, frustum.g, frustum.b ); // n1, f1
  30989. colorAttribute.setXYZ( 18, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 19, frustum.r, frustum.g, frustum.b ); // n2, f2
  30990. colorAttribute.setXYZ( 20, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 21, frustum.r, frustum.g, frustum.b ); // n3, f3
  30991. colorAttribute.setXYZ( 22, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 23, frustum.r, frustum.g, frustum.b ); // n4, f4
  30992. // cone
  30993. colorAttribute.setXYZ( 24, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 25, cone.r, cone.g, cone.b ); // p, n1
  30994. colorAttribute.setXYZ( 26, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 27, cone.r, cone.g, cone.b ); // p, n2
  30995. colorAttribute.setXYZ( 28, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 29, cone.r, cone.g, cone.b ); // p, n3
  30996. colorAttribute.setXYZ( 30, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 31, cone.r, cone.g, cone.b ); // p, n4
  30997. // up
  30998. colorAttribute.setXYZ( 32, up.r, up.g, up.b ); colorAttribute.setXYZ( 33, up.r, up.g, up.b ); // u1, u2
  30999. colorAttribute.setXYZ( 34, up.r, up.g, up.b ); colorAttribute.setXYZ( 35, up.r, up.g, up.b ); // u2, u3
  31000. colorAttribute.setXYZ( 36, up.r, up.g, up.b ); colorAttribute.setXYZ( 37, up.r, up.g, up.b ); // u3, u1
  31001. // target
  31002. colorAttribute.setXYZ( 38, target.r, target.g, target.b ); colorAttribute.setXYZ( 39, target.r, target.g, target.b ); // c, t
  31003. colorAttribute.setXYZ( 40, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 41, cross.r, cross.g, cross.b ); // p, c
  31004. // cross
  31005. colorAttribute.setXYZ( 42, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 43, cross.r, cross.g, cross.b ); // cn1, cn2
  31006. colorAttribute.setXYZ( 44, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 45, cross.r, cross.g, cross.b ); // cn3, cn4
  31007. colorAttribute.setXYZ( 46, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 47, cross.r, cross.g, cross.b ); // cf1, cf2
  31008. colorAttribute.setXYZ( 48, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 49, cross.r, cross.g, cross.b ); // cf3, cf4
  31009. colorAttribute.needsUpdate = true;
  31010. }
  31011. update() {
  31012. const geometry = this.geometry;
  31013. const pointMap = this.pointMap;
  31014. const w = 1, h = 1;
  31015. // we need just camera projection matrix inverse
  31016. // world matrix must be identity
  31017. _camera.projectionMatrixInverse.copy( this.camera.projectionMatrixInverse );
  31018. // center / target
  31019. setPoint( 'c', pointMap, geometry, _camera, 0, 0, - 1 );
  31020. setPoint( 't', pointMap, geometry, _camera, 0, 0, 1 );
  31021. // near
  31022. setPoint( 'n1', pointMap, geometry, _camera, - w, - h, - 1 );
  31023. setPoint( 'n2', pointMap, geometry, _camera, w, - h, - 1 );
  31024. setPoint( 'n3', pointMap, geometry, _camera, - w, h, - 1 );
  31025. setPoint( 'n4', pointMap, geometry, _camera, w, h, - 1 );
  31026. // far
  31027. setPoint( 'f1', pointMap, geometry, _camera, - w, - h, 1 );
  31028. setPoint( 'f2', pointMap, geometry, _camera, w, - h, 1 );
  31029. setPoint( 'f3', pointMap, geometry, _camera, - w, h, 1 );
  31030. setPoint( 'f4', pointMap, geometry, _camera, w, h, 1 );
  31031. // up
  31032. setPoint( 'u1', pointMap, geometry, _camera, w * 0.7, h * 1.1, - 1 );
  31033. setPoint( 'u2', pointMap, geometry, _camera, - w * 0.7, h * 1.1, - 1 );
  31034. setPoint( 'u3', pointMap, geometry, _camera, 0, h * 2, - 1 );
  31035. // cross
  31036. setPoint( 'cf1', pointMap, geometry, _camera, - w, 0, 1 );
  31037. setPoint( 'cf2', pointMap, geometry, _camera, w, 0, 1 );
  31038. setPoint( 'cf3', pointMap, geometry, _camera, 0, - h, 1 );
  31039. setPoint( 'cf4', pointMap, geometry, _camera, 0, h, 1 );
  31040. setPoint( 'cn1', pointMap, geometry, _camera, - w, 0, - 1 );
  31041. setPoint( 'cn2', pointMap, geometry, _camera, w, 0, - 1 );
  31042. setPoint( 'cn3', pointMap, geometry, _camera, 0, - h, - 1 );
  31043. setPoint( 'cn4', pointMap, geometry, _camera, 0, h, - 1 );
  31044. geometry.getAttribute( 'position' ).needsUpdate = true;
  31045. }
  31046. dispose() {
  31047. this.geometry.dispose();
  31048. this.material.dispose();
  31049. }
  31050. }
  31051. function setPoint( point, pointMap, geometry, camera, x, y, z ) {
  31052. _vector.set( x, y, z ).unproject( camera );
  31053. const points = pointMap[ point ];
  31054. if ( points !== undefined ) {
  31055. const position = geometry.getAttribute( 'position' );
  31056. for ( let i = 0, l = points.length; i < l; i ++ ) {
  31057. position.setXYZ( points[ i ], _vector.x, _vector.y, _vector.z );
  31058. }
  31059. }
  31060. }
  31061. const _box = /*@__PURE__*/ new Box3();
  31062. class BoxHelper extends LineSegments {
  31063. constructor( object, color = 0xffff00 ) {
  31064. 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 ] );
  31065. const positions = new Float32Array( 8 * 3 );
  31066. const geometry = new BufferGeometry();
  31067. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  31068. geometry.setAttribute( 'position', new BufferAttribute( positions, 3 ) );
  31069. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  31070. this.object = object;
  31071. this.type = 'BoxHelper';
  31072. this.matrixAutoUpdate = false;
  31073. this.update();
  31074. }
  31075. update( object ) {
  31076. if ( object !== undefined ) {
  31077. console.warn( 'THREE.BoxHelper: .update() has no longer arguments.' );
  31078. }
  31079. if ( this.object !== undefined ) {
  31080. _box.setFromObject( this.object );
  31081. }
  31082. if ( _box.isEmpty() ) return;
  31083. const min = _box.min;
  31084. const max = _box.max;
  31085. /*
  31086. 5____4
  31087. 1/___0/|
  31088. | 6__|_7
  31089. 2/___3/
  31090. 0: max.x, max.y, max.z
  31091. 1: min.x, max.y, max.z
  31092. 2: min.x, min.y, max.z
  31093. 3: max.x, min.y, max.z
  31094. 4: max.x, max.y, min.z
  31095. 5: min.x, max.y, min.z
  31096. 6: min.x, min.y, min.z
  31097. 7: max.x, min.y, min.z
  31098. */
  31099. const position = this.geometry.attributes.position;
  31100. const array = position.array;
  31101. array[ 0 ] = max.x; array[ 1 ] = max.y; array[ 2 ] = max.z;
  31102. array[ 3 ] = min.x; array[ 4 ] = max.y; array[ 5 ] = max.z;
  31103. array[ 6 ] = min.x; array[ 7 ] = min.y; array[ 8 ] = max.z;
  31104. array[ 9 ] = max.x; array[ 10 ] = min.y; array[ 11 ] = max.z;
  31105. array[ 12 ] = max.x; array[ 13 ] = max.y; array[ 14 ] = min.z;
  31106. array[ 15 ] = min.x; array[ 16 ] = max.y; array[ 17 ] = min.z;
  31107. array[ 18 ] = min.x; array[ 19 ] = min.y; array[ 20 ] = min.z;
  31108. array[ 21 ] = max.x; array[ 22 ] = min.y; array[ 23 ] = min.z;
  31109. position.needsUpdate = true;
  31110. this.geometry.computeBoundingSphere();
  31111. }
  31112. setFromObject( object ) {
  31113. this.object = object;
  31114. this.update();
  31115. return this;
  31116. }
  31117. copy( source, recursive ) {
  31118. super.copy( source, recursive );
  31119. this.object = source.object;
  31120. return this;
  31121. }
  31122. dispose() {
  31123. this.geometry.dispose();
  31124. this.material.dispose();
  31125. }
  31126. }
  31127. class Box3Helper extends LineSegments {
  31128. constructor( box, color = 0xffff00 ) {
  31129. 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 ] );
  31130. 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 ];
  31131. const geometry = new BufferGeometry();
  31132. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  31133. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  31134. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  31135. this.box = box;
  31136. this.type = 'Box3Helper';
  31137. this.geometry.computeBoundingSphere();
  31138. }
  31139. updateMatrixWorld( force ) {
  31140. const box = this.box;
  31141. if ( box.isEmpty() ) return;
  31142. box.getCenter( this.position );
  31143. box.getSize( this.scale );
  31144. this.scale.multiplyScalar( 0.5 );
  31145. super.updateMatrixWorld( force );
  31146. }
  31147. dispose() {
  31148. this.geometry.dispose();
  31149. this.material.dispose();
  31150. }
  31151. }
  31152. class PlaneHelper extends Line {
  31153. constructor( plane, size = 1, hex = 0xffff00 ) {
  31154. const color = hex;
  31155. const positions = [ 1, - 1, 0, - 1, 1, 0, - 1, - 1, 0, 1, 1, 0, - 1, 1, 0, - 1, - 1, 0, 1, - 1, 0, 1, 1, 0 ];
  31156. const geometry = new BufferGeometry();
  31157. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  31158. geometry.computeBoundingSphere();
  31159. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  31160. this.type = 'PlaneHelper';
  31161. this.plane = plane;
  31162. this.size = size;
  31163. const positions2 = [ 1, 1, 0, - 1, 1, 0, - 1, - 1, 0, 1, 1, 0, - 1, - 1, 0, 1, - 1, 0 ];
  31164. const geometry2 = new BufferGeometry();
  31165. geometry2.setAttribute( 'position', new Float32BufferAttribute( positions2, 3 ) );
  31166. geometry2.computeBoundingSphere();
  31167. this.add( new Mesh( geometry2, new MeshBasicMaterial( { color: color, opacity: 0.2, transparent: true, depthWrite: false, toneMapped: false } ) ) );
  31168. }
  31169. updateMatrixWorld( force ) {
  31170. this.position.set( 0, 0, 0 );
  31171. this.scale.set( 0.5 * this.size, 0.5 * this.size, 1 );
  31172. this.lookAt( this.plane.normal );
  31173. this.translateZ( - this.plane.constant );
  31174. super.updateMatrixWorld( force );
  31175. }
  31176. dispose() {
  31177. this.geometry.dispose();
  31178. this.material.dispose();
  31179. this.children[ 0 ].geometry.dispose();
  31180. this.children[ 0 ].material.dispose();
  31181. }
  31182. }
  31183. const _axis = /*@__PURE__*/ new Vector3();
  31184. let _lineGeometry, _coneGeometry;
  31185. class ArrowHelper extends Object3D {
  31186. // dir is assumed to be normalized
  31187. 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 ) {
  31188. super();
  31189. this.type = 'ArrowHelper';
  31190. if ( _lineGeometry === undefined ) {
  31191. _lineGeometry = new BufferGeometry();
  31192. _lineGeometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 1, 0 ], 3 ) );
  31193. _coneGeometry = new CylinderGeometry( 0, 0.5, 1, 5, 1 );
  31194. _coneGeometry.translate( 0, - 0.5, 0 );
  31195. }
  31196. this.position.copy( origin );
  31197. this.line = new Line( _lineGeometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  31198. this.line.matrixAutoUpdate = false;
  31199. this.add( this.line );
  31200. this.cone = new Mesh( _coneGeometry, new MeshBasicMaterial( { color: color, toneMapped: false } ) );
  31201. this.cone.matrixAutoUpdate = false;
  31202. this.add( this.cone );
  31203. this.setDirection( dir );
  31204. this.setLength( length, headLength, headWidth );
  31205. }
  31206. setDirection( dir ) {
  31207. // dir is assumed to be normalized
  31208. if ( dir.y > 0.99999 ) {
  31209. this.quaternion.set( 0, 0, 0, 1 );
  31210. } else if ( dir.y < - 0.99999 ) {
  31211. this.quaternion.set( 1, 0, 0, 0 );
  31212. } else {
  31213. _axis.set( dir.z, 0, - dir.x ).normalize();
  31214. const radians = Math.acos( dir.y );
  31215. this.quaternion.setFromAxisAngle( _axis, radians );
  31216. }
  31217. }
  31218. setLength( length, headLength = length * 0.2, headWidth = headLength * 0.2 ) {
  31219. this.line.scale.set( 1, Math.max( 0.0001, length - headLength ), 1 ); // see #17458
  31220. this.line.updateMatrix();
  31221. this.cone.scale.set( headWidth, headLength, headWidth );
  31222. this.cone.position.y = length;
  31223. this.cone.updateMatrix();
  31224. }
  31225. setColor( color ) {
  31226. this.line.material.color.set( color );
  31227. this.cone.material.color.set( color );
  31228. }
  31229. copy( source ) {
  31230. super.copy( source, false );
  31231. this.line.copy( source.line );
  31232. this.cone.copy( source.cone );
  31233. return this;
  31234. }
  31235. dispose() {
  31236. this.line.geometry.dispose();
  31237. this.line.material.dispose();
  31238. this.cone.geometry.dispose();
  31239. this.cone.material.dispose();
  31240. }
  31241. }
  31242. class AxesHelper extends LineSegments {
  31243. constructor( size = 1 ) {
  31244. const vertices = [
  31245. 0, 0, 0, size, 0, 0,
  31246. 0, 0, 0, 0, size, 0,
  31247. 0, 0, 0, 0, 0, size
  31248. ];
  31249. const colors = [
  31250. 1, 0, 0, 1, 0.6, 0,
  31251. 0, 1, 0, 0.6, 1, 0,
  31252. 0, 0, 1, 0, 0.6, 1
  31253. ];
  31254. const geometry = new BufferGeometry();
  31255. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  31256. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  31257. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  31258. super( geometry, material );
  31259. this.type = 'AxesHelper';
  31260. }
  31261. setColors( xAxisColor, yAxisColor, zAxisColor ) {
  31262. const color = new Color();
  31263. const array = this.geometry.attributes.color.array;
  31264. color.set( xAxisColor );
  31265. color.toArray( array, 0 );
  31266. color.toArray( array, 3 );
  31267. color.set( yAxisColor );
  31268. color.toArray( array, 6 );
  31269. color.toArray( array, 9 );
  31270. color.set( zAxisColor );
  31271. color.toArray( array, 12 );
  31272. color.toArray( array, 15 );
  31273. this.geometry.attributes.color.needsUpdate = true;
  31274. return this;
  31275. }
  31276. dispose() {
  31277. this.geometry.dispose();
  31278. this.material.dispose();
  31279. }
  31280. }
  31281. class ShapePath {
  31282. constructor() {
  31283. this.type = 'ShapePath';
  31284. this.color = new Color();
  31285. this.subPaths = [];
  31286. this.currentPath = null;
  31287. }
  31288. moveTo( x, y ) {
  31289. this.currentPath = new Path();
  31290. this.subPaths.push( this.currentPath );
  31291. this.currentPath.moveTo( x, y );
  31292. return this;
  31293. }
  31294. lineTo( x, y ) {
  31295. this.currentPath.lineTo( x, y );
  31296. return this;
  31297. }
  31298. quadraticCurveTo( aCPx, aCPy, aX, aY ) {
  31299. this.currentPath.quadraticCurveTo( aCPx, aCPy, aX, aY );
  31300. return this;
  31301. }
  31302. bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  31303. this.currentPath.bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY );
  31304. return this;
  31305. }
  31306. splineThru( pts ) {
  31307. this.currentPath.splineThru( pts );
  31308. return this;
  31309. }
  31310. toShapes( isCCW ) {
  31311. function toShapesNoHoles( inSubpaths ) {
  31312. const shapes = [];
  31313. for ( let i = 0, l = inSubpaths.length; i < l; i ++ ) {
  31314. const tmpPath = inSubpaths[ i ];
  31315. const tmpShape = new Shape();
  31316. tmpShape.curves = tmpPath.curves;
  31317. shapes.push( tmpShape );
  31318. }
  31319. return shapes;
  31320. }
  31321. function isPointInsidePolygon( inPt, inPolygon ) {
  31322. const polyLen = inPolygon.length;
  31323. // inPt on polygon contour => immediate success or
  31324. // toggling of inside/outside at every single! intersection point of an edge
  31325. // with the horizontal line through inPt, left of inPt
  31326. // not counting lowerY endpoints of edges and whole edges on that line
  31327. let inside = false;
  31328. for ( let p = polyLen - 1, q = 0; q < polyLen; p = q ++ ) {
  31329. let edgeLowPt = inPolygon[ p ];
  31330. let edgeHighPt = inPolygon[ q ];
  31331. let edgeDx = edgeHighPt.x - edgeLowPt.x;
  31332. let edgeDy = edgeHighPt.y - edgeLowPt.y;
  31333. if ( Math.abs( edgeDy ) > Number.EPSILON ) {
  31334. // not parallel
  31335. if ( edgeDy < 0 ) {
  31336. edgeLowPt = inPolygon[ q ]; edgeDx = - edgeDx;
  31337. edgeHighPt = inPolygon[ p ]; edgeDy = - edgeDy;
  31338. }
  31339. if ( ( inPt.y < edgeLowPt.y ) || ( inPt.y > edgeHighPt.y ) ) continue;
  31340. if ( inPt.y === edgeLowPt.y ) {
  31341. if ( inPt.x === edgeLowPt.x ) return true; // inPt is on contour ?
  31342. // continue; // no intersection or edgeLowPt => doesn't count !!!
  31343. } else {
  31344. const perpEdge = edgeDy * ( inPt.x - edgeLowPt.x ) - edgeDx * ( inPt.y - edgeLowPt.y );
  31345. if ( perpEdge === 0 ) return true; // inPt is on contour ?
  31346. if ( perpEdge < 0 ) continue;
  31347. inside = ! inside; // true intersection left of inPt
  31348. }
  31349. } else {
  31350. // parallel or collinear
  31351. if ( inPt.y !== edgeLowPt.y ) continue; // parallel
  31352. // edge lies on the same horizontal line as inPt
  31353. if ( ( ( edgeHighPt.x <= inPt.x ) && ( inPt.x <= edgeLowPt.x ) ) ||
  31354. ( ( edgeLowPt.x <= inPt.x ) && ( inPt.x <= edgeHighPt.x ) ) ) return true; // inPt: Point on contour !
  31355. // continue;
  31356. }
  31357. }
  31358. return inside;
  31359. }
  31360. const isClockWise = ShapeUtils.isClockWise;
  31361. const subPaths = this.subPaths;
  31362. if ( subPaths.length === 0 ) return [];
  31363. let solid, tmpPath, tmpShape;
  31364. const shapes = [];
  31365. if ( subPaths.length === 1 ) {
  31366. tmpPath = subPaths[ 0 ];
  31367. tmpShape = new Shape();
  31368. tmpShape.curves = tmpPath.curves;
  31369. shapes.push( tmpShape );
  31370. return shapes;
  31371. }
  31372. let holesFirst = ! isClockWise( subPaths[ 0 ].getPoints() );
  31373. holesFirst = isCCW ? ! holesFirst : holesFirst;
  31374. // console.log("Holes first", holesFirst);
  31375. const betterShapeHoles = [];
  31376. const newShapes = [];
  31377. let newShapeHoles = [];
  31378. let mainIdx = 0;
  31379. let tmpPoints;
  31380. newShapes[ mainIdx ] = undefined;
  31381. newShapeHoles[ mainIdx ] = [];
  31382. for ( let i = 0, l = subPaths.length; i < l; i ++ ) {
  31383. tmpPath = subPaths[ i ];
  31384. tmpPoints = tmpPath.getPoints();
  31385. solid = isClockWise( tmpPoints );
  31386. solid = isCCW ? ! solid : solid;
  31387. if ( solid ) {
  31388. if ( ( ! holesFirst ) && ( newShapes[ mainIdx ] ) ) mainIdx ++;
  31389. newShapes[ mainIdx ] = { s: new Shape(), p: tmpPoints };
  31390. newShapes[ mainIdx ].s.curves = tmpPath.curves;
  31391. if ( holesFirst ) mainIdx ++;
  31392. newShapeHoles[ mainIdx ] = [];
  31393. //console.log('cw', i);
  31394. } else {
  31395. newShapeHoles[ mainIdx ].push( { h: tmpPath, p: tmpPoints[ 0 ] } );
  31396. //console.log('ccw', i);
  31397. }
  31398. }
  31399. // only Holes? -> probably all Shapes with wrong orientation
  31400. if ( ! newShapes[ 0 ] ) return toShapesNoHoles( subPaths );
  31401. if ( newShapes.length > 1 ) {
  31402. let ambiguous = false;
  31403. let toChange = 0;
  31404. for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  31405. betterShapeHoles[ sIdx ] = [];
  31406. }
  31407. for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  31408. const sho = newShapeHoles[ sIdx ];
  31409. for ( let hIdx = 0; hIdx < sho.length; hIdx ++ ) {
  31410. const ho = sho[ hIdx ];
  31411. let hole_unassigned = true;
  31412. for ( let s2Idx = 0; s2Idx < newShapes.length; s2Idx ++ ) {
  31413. if ( isPointInsidePolygon( ho.p, newShapes[ s2Idx ].p ) ) {
  31414. if ( sIdx !== s2Idx ) toChange ++;
  31415. if ( hole_unassigned ) {
  31416. hole_unassigned = false;
  31417. betterShapeHoles[ s2Idx ].push( ho );
  31418. } else {
  31419. ambiguous = true;
  31420. }
  31421. }
  31422. }
  31423. if ( hole_unassigned ) {
  31424. betterShapeHoles[ sIdx ].push( ho );
  31425. }
  31426. }
  31427. }
  31428. if ( toChange > 0 && ambiguous === false ) {
  31429. newShapeHoles = betterShapeHoles;
  31430. }
  31431. }
  31432. let tmpHoles;
  31433. for ( let i = 0, il = newShapes.length; i < il; i ++ ) {
  31434. tmpShape = newShapes[ i ].s;
  31435. shapes.push( tmpShape );
  31436. tmpHoles = newShapeHoles[ i ];
  31437. for ( let j = 0, jl = tmpHoles.length; j < jl; j ++ ) {
  31438. tmpShape.holes.push( tmpHoles[ j ].h );
  31439. }
  31440. }
  31441. //console.log("shape", shapes);
  31442. return shapes;
  31443. }
  31444. }
  31445. class WebGLMultipleRenderTargets extends WebGLRenderTarget { // @deprecated, r162
  31446. constructor( width = 1, height = 1, count = 1, options = {} ) {
  31447. console.warn( 'THREE.WebGLMultipleRenderTargets has been deprecated and will be removed in r172. Use THREE.WebGLRenderTarget and set the "count" parameter to enable MRT.' );
  31448. super( width, height, { ...options, count } );
  31449. this.isWebGLMultipleRenderTargets = true;
  31450. }
  31451. get texture() {
  31452. return this.textures;
  31453. }
  31454. }
  31455. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  31456. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'register', { detail: {
  31457. revision: REVISION,
  31458. } } ) );
  31459. }
  31460. if ( typeof window !== 'undefined' ) {
  31461. if ( window.__THREE__ ) {
  31462. console.warn( 'WARNING: Multiple instances of Three.js being imported.' );
  31463. } else {
  31464. window.__THREE__ = REVISION;
  31465. }
  31466. }
  31467. exports.ACESFilmicToneMapping = ACESFilmicToneMapping;
  31468. exports.AddEquation = AddEquation;
  31469. exports.AddOperation = AddOperation;
  31470. exports.AdditiveAnimationBlendMode = AdditiveAnimationBlendMode;
  31471. exports.AdditiveBlending = AdditiveBlending;
  31472. exports.AgXToneMapping = AgXToneMapping;
  31473. exports.AlphaFormat = AlphaFormat;
  31474. exports.AlwaysCompare = AlwaysCompare;
  31475. exports.AlwaysDepth = AlwaysDepth;
  31476. exports.AlwaysStencilFunc = AlwaysStencilFunc;
  31477. exports.AmbientLight = AmbientLight;
  31478. exports.AnimationAction = AnimationAction;
  31479. exports.AnimationClip = AnimationClip;
  31480. exports.AnimationLoader = AnimationLoader;
  31481. exports.AnimationMixer = AnimationMixer;
  31482. exports.AnimationObjectGroup = AnimationObjectGroup;
  31483. exports.AnimationUtils = AnimationUtils;
  31484. exports.ArcCurve = ArcCurve;
  31485. exports.ArrayCamera = ArrayCamera;
  31486. exports.ArrowHelper = ArrowHelper;
  31487. exports.AttachedBindMode = AttachedBindMode;
  31488. exports.Audio = Audio;
  31489. exports.AudioAnalyser = AudioAnalyser;
  31490. exports.AudioContext = AudioContext;
  31491. exports.AudioListener = AudioListener;
  31492. exports.AudioLoader = AudioLoader;
  31493. exports.AxesHelper = AxesHelper;
  31494. exports.BackSide = BackSide;
  31495. exports.BasicDepthPacking = BasicDepthPacking;
  31496. exports.BasicShadowMap = BasicShadowMap;
  31497. exports.BatchedMesh = BatchedMesh;
  31498. exports.Bone = Bone;
  31499. exports.BooleanKeyframeTrack = BooleanKeyframeTrack;
  31500. exports.Box2 = Box2;
  31501. exports.Box3 = Box3;
  31502. exports.Box3Helper = Box3Helper;
  31503. exports.BoxGeometry = BoxGeometry;
  31504. exports.BoxHelper = BoxHelper;
  31505. exports.BufferAttribute = BufferAttribute;
  31506. exports.BufferGeometry = BufferGeometry;
  31507. exports.BufferGeometryLoader = BufferGeometryLoader;
  31508. exports.ByteType = ByteType;
  31509. exports.Cache = Cache;
  31510. exports.Camera = Camera;
  31511. exports.CameraHelper = CameraHelper;
  31512. exports.CanvasTexture = CanvasTexture;
  31513. exports.CapsuleGeometry = CapsuleGeometry;
  31514. exports.CatmullRomCurve3 = CatmullRomCurve3;
  31515. exports.CineonToneMapping = CineonToneMapping;
  31516. exports.CircleGeometry = CircleGeometry;
  31517. exports.ClampToEdgeWrapping = ClampToEdgeWrapping;
  31518. exports.Clock = Clock;
  31519. exports.Color = Color;
  31520. exports.ColorKeyframeTrack = ColorKeyframeTrack;
  31521. exports.ColorManagement = ColorManagement;
  31522. exports.CompressedArrayTexture = CompressedArrayTexture;
  31523. exports.CompressedCubeTexture = CompressedCubeTexture;
  31524. exports.CompressedTexture = CompressedTexture;
  31525. exports.CompressedTextureLoader = CompressedTextureLoader;
  31526. exports.ConeGeometry = ConeGeometry;
  31527. exports.ConstantAlphaFactor = ConstantAlphaFactor;
  31528. exports.ConstantColorFactor = ConstantColorFactor;
  31529. exports.CubeCamera = CubeCamera;
  31530. exports.CubeReflectionMapping = CubeReflectionMapping;
  31531. exports.CubeRefractionMapping = CubeRefractionMapping;
  31532. exports.CubeTexture = CubeTexture;
  31533. exports.CubeTextureLoader = CubeTextureLoader;
  31534. exports.CubeUVReflectionMapping = CubeUVReflectionMapping;
  31535. exports.CubicBezierCurve = CubicBezierCurve;
  31536. exports.CubicBezierCurve3 = CubicBezierCurve3;
  31537. exports.CubicInterpolant = CubicInterpolant;
  31538. exports.CullFaceBack = CullFaceBack;
  31539. exports.CullFaceFront = CullFaceFront;
  31540. exports.CullFaceFrontBack = CullFaceFrontBack;
  31541. exports.CullFaceNone = CullFaceNone;
  31542. exports.Curve = Curve;
  31543. exports.CurvePath = CurvePath;
  31544. exports.CustomBlending = CustomBlending;
  31545. exports.CustomToneMapping = CustomToneMapping;
  31546. exports.CylinderGeometry = CylinderGeometry;
  31547. exports.Cylindrical = Cylindrical;
  31548. exports.Data3DTexture = Data3DTexture;
  31549. exports.DataArrayTexture = DataArrayTexture;
  31550. exports.DataTexture = DataTexture;
  31551. exports.DataTextureLoader = DataTextureLoader;
  31552. exports.DataUtils = DataUtils;
  31553. exports.DecrementStencilOp = DecrementStencilOp;
  31554. exports.DecrementWrapStencilOp = DecrementWrapStencilOp;
  31555. exports.DefaultLoadingManager = DefaultLoadingManager;
  31556. exports.DepthFormat = DepthFormat;
  31557. exports.DepthStencilFormat = DepthStencilFormat;
  31558. exports.DepthTexture = DepthTexture;
  31559. exports.DetachedBindMode = DetachedBindMode;
  31560. exports.DirectionalLight = DirectionalLight;
  31561. exports.DirectionalLightHelper = DirectionalLightHelper;
  31562. exports.DiscreteInterpolant = DiscreteInterpolant;
  31563. exports.DisplayP3ColorSpace = DisplayP3ColorSpace;
  31564. exports.DodecahedronGeometry = DodecahedronGeometry;
  31565. exports.DoubleSide = DoubleSide;
  31566. exports.DstAlphaFactor = DstAlphaFactor;
  31567. exports.DstColorFactor = DstColorFactor;
  31568. exports.DynamicCopyUsage = DynamicCopyUsage;
  31569. exports.DynamicDrawUsage = DynamicDrawUsage;
  31570. exports.DynamicReadUsage = DynamicReadUsage;
  31571. exports.EdgesGeometry = EdgesGeometry;
  31572. exports.EllipseCurve = EllipseCurve;
  31573. exports.EqualCompare = EqualCompare;
  31574. exports.EqualDepth = EqualDepth;
  31575. exports.EqualStencilFunc = EqualStencilFunc;
  31576. exports.EquirectangularReflectionMapping = EquirectangularReflectionMapping;
  31577. exports.EquirectangularRefractionMapping = EquirectangularRefractionMapping;
  31578. exports.Euler = Euler;
  31579. exports.EventDispatcher = EventDispatcher;
  31580. exports.ExtrudeGeometry = ExtrudeGeometry;
  31581. exports.FileLoader = FileLoader;
  31582. exports.Float16BufferAttribute = Float16BufferAttribute;
  31583. exports.Float32BufferAttribute = Float32BufferAttribute;
  31584. exports.Float64BufferAttribute = Float64BufferAttribute;
  31585. exports.FloatType = FloatType;
  31586. exports.Fog = Fog;
  31587. exports.FogExp2 = FogExp2;
  31588. exports.FramebufferTexture = FramebufferTexture;
  31589. exports.FrontSide = FrontSide;
  31590. exports.Frustum = Frustum;
  31591. exports.GLBufferAttribute = GLBufferAttribute;
  31592. exports.GLSL1 = GLSL1;
  31593. exports.GLSL3 = GLSL3;
  31594. exports.GreaterCompare = GreaterCompare;
  31595. exports.GreaterDepth = GreaterDepth;
  31596. exports.GreaterEqualCompare = GreaterEqualCompare;
  31597. exports.GreaterEqualDepth = GreaterEqualDepth;
  31598. exports.GreaterEqualStencilFunc = GreaterEqualStencilFunc;
  31599. exports.GreaterStencilFunc = GreaterStencilFunc;
  31600. exports.GridHelper = GridHelper;
  31601. exports.Group = Group;
  31602. exports.HalfFloatType = HalfFloatType;
  31603. exports.HemisphereLight = HemisphereLight;
  31604. exports.HemisphereLightHelper = HemisphereLightHelper;
  31605. exports.IcosahedronGeometry = IcosahedronGeometry;
  31606. exports.ImageBitmapLoader = ImageBitmapLoader;
  31607. exports.ImageLoader = ImageLoader;
  31608. exports.ImageUtils = ImageUtils;
  31609. exports.IncrementStencilOp = IncrementStencilOp;
  31610. exports.IncrementWrapStencilOp = IncrementWrapStencilOp;
  31611. exports.InstancedBufferAttribute = InstancedBufferAttribute;
  31612. exports.InstancedBufferGeometry = InstancedBufferGeometry;
  31613. exports.InstancedInterleavedBuffer = InstancedInterleavedBuffer;
  31614. exports.InstancedMesh = InstancedMesh;
  31615. exports.Int16BufferAttribute = Int16BufferAttribute;
  31616. exports.Int32BufferAttribute = Int32BufferAttribute;
  31617. exports.Int8BufferAttribute = Int8BufferAttribute;
  31618. exports.IntType = IntType;
  31619. exports.InterleavedBuffer = InterleavedBuffer;
  31620. exports.InterleavedBufferAttribute = InterleavedBufferAttribute;
  31621. exports.Interpolant = Interpolant;
  31622. exports.InterpolateDiscrete = InterpolateDiscrete;
  31623. exports.InterpolateLinear = InterpolateLinear;
  31624. exports.InterpolateSmooth = InterpolateSmooth;
  31625. exports.InvertStencilOp = InvertStencilOp;
  31626. exports.KeepStencilOp = KeepStencilOp;
  31627. exports.KeyframeTrack = KeyframeTrack;
  31628. exports.LOD = LOD;
  31629. exports.LatheGeometry = LatheGeometry;
  31630. exports.Layers = Layers;
  31631. exports.LessCompare = LessCompare;
  31632. exports.LessDepth = LessDepth;
  31633. exports.LessEqualCompare = LessEqualCompare;
  31634. exports.LessEqualDepth = LessEqualDepth;
  31635. exports.LessEqualStencilFunc = LessEqualStencilFunc;
  31636. exports.LessStencilFunc = LessStencilFunc;
  31637. exports.Light = Light;
  31638. exports.LightProbe = LightProbe;
  31639. exports.Line = Line;
  31640. exports.Line3 = Line3;
  31641. exports.LineBasicMaterial = LineBasicMaterial;
  31642. exports.LineCurve = LineCurve;
  31643. exports.LineCurve3 = LineCurve3;
  31644. exports.LineDashedMaterial = LineDashedMaterial;
  31645. exports.LineLoop = LineLoop;
  31646. exports.LineSegments = LineSegments;
  31647. exports.LinearDisplayP3ColorSpace = LinearDisplayP3ColorSpace;
  31648. exports.LinearFilter = LinearFilter;
  31649. exports.LinearInterpolant = LinearInterpolant;
  31650. exports.LinearMipMapLinearFilter = LinearMipMapLinearFilter;
  31651. exports.LinearMipMapNearestFilter = LinearMipMapNearestFilter;
  31652. exports.LinearMipmapLinearFilter = LinearMipmapLinearFilter;
  31653. exports.LinearMipmapNearestFilter = LinearMipmapNearestFilter;
  31654. exports.LinearSRGBColorSpace = LinearSRGBColorSpace;
  31655. exports.LinearToneMapping = LinearToneMapping;
  31656. exports.LinearTransfer = LinearTransfer;
  31657. exports.Loader = Loader;
  31658. exports.LoaderUtils = LoaderUtils;
  31659. exports.LoadingManager = LoadingManager;
  31660. exports.LoopOnce = LoopOnce;
  31661. exports.LoopPingPong = LoopPingPong;
  31662. exports.LoopRepeat = LoopRepeat;
  31663. exports.LuminanceAlphaFormat = LuminanceAlphaFormat;
  31664. exports.LuminanceFormat = LuminanceFormat;
  31665. exports.MOUSE = MOUSE;
  31666. exports.Material = Material;
  31667. exports.MaterialLoader = MaterialLoader;
  31668. exports.MathUtils = MathUtils;
  31669. exports.Matrix3 = Matrix3;
  31670. exports.Matrix4 = Matrix4;
  31671. exports.MaxEquation = MaxEquation;
  31672. exports.Mesh = Mesh;
  31673. exports.MeshBasicMaterial = MeshBasicMaterial;
  31674. exports.MeshDepthMaterial = MeshDepthMaterial;
  31675. exports.MeshDistanceMaterial = MeshDistanceMaterial;
  31676. exports.MeshLambertMaterial = MeshLambertMaterial;
  31677. exports.MeshMatcapMaterial = MeshMatcapMaterial;
  31678. exports.MeshNormalMaterial = MeshNormalMaterial;
  31679. exports.MeshPhongMaterial = MeshPhongMaterial;
  31680. exports.MeshPhysicalMaterial = MeshPhysicalMaterial;
  31681. exports.MeshStandardMaterial = MeshStandardMaterial;
  31682. exports.MeshToonMaterial = MeshToonMaterial;
  31683. exports.MinEquation = MinEquation;
  31684. exports.MirroredRepeatWrapping = MirroredRepeatWrapping;
  31685. exports.MixOperation = MixOperation;
  31686. exports.MultiplyBlending = MultiplyBlending;
  31687. exports.MultiplyOperation = MultiplyOperation;
  31688. exports.NearestFilter = NearestFilter;
  31689. exports.NearestMipMapLinearFilter = NearestMipMapLinearFilter;
  31690. exports.NearestMipMapNearestFilter = NearestMipMapNearestFilter;
  31691. exports.NearestMipmapLinearFilter = NearestMipmapLinearFilter;
  31692. exports.NearestMipmapNearestFilter = NearestMipmapNearestFilter;
  31693. exports.NeutralToneMapping = NeutralToneMapping;
  31694. exports.NeverCompare = NeverCompare;
  31695. exports.NeverDepth = NeverDepth;
  31696. exports.NeverStencilFunc = NeverStencilFunc;
  31697. exports.NoBlending = NoBlending;
  31698. exports.NoColorSpace = NoColorSpace;
  31699. exports.NoToneMapping = NoToneMapping;
  31700. exports.NormalAnimationBlendMode = NormalAnimationBlendMode;
  31701. exports.NormalBlending = NormalBlending;
  31702. exports.NotEqualCompare = NotEqualCompare;
  31703. exports.NotEqualDepth = NotEqualDepth;
  31704. exports.NotEqualStencilFunc = NotEqualStencilFunc;
  31705. exports.NumberKeyframeTrack = NumberKeyframeTrack;
  31706. exports.Object3D = Object3D;
  31707. exports.ObjectLoader = ObjectLoader;
  31708. exports.ObjectSpaceNormalMap = ObjectSpaceNormalMap;
  31709. exports.OctahedronGeometry = OctahedronGeometry;
  31710. exports.OneFactor = OneFactor;
  31711. exports.OneMinusConstantAlphaFactor = OneMinusConstantAlphaFactor;
  31712. exports.OneMinusConstantColorFactor = OneMinusConstantColorFactor;
  31713. exports.OneMinusDstAlphaFactor = OneMinusDstAlphaFactor;
  31714. exports.OneMinusDstColorFactor = OneMinusDstColorFactor;
  31715. exports.OneMinusSrcAlphaFactor = OneMinusSrcAlphaFactor;
  31716. exports.OneMinusSrcColorFactor = OneMinusSrcColorFactor;
  31717. exports.OrthographicCamera = OrthographicCamera;
  31718. exports.P3Primaries = P3Primaries;
  31719. exports.PCFShadowMap = PCFShadowMap;
  31720. exports.PCFSoftShadowMap = PCFSoftShadowMap;
  31721. exports.PMREMGenerator = PMREMGenerator;
  31722. exports.Path = Path;
  31723. exports.PerspectiveCamera = PerspectiveCamera;
  31724. exports.Plane = Plane;
  31725. exports.PlaneGeometry = PlaneGeometry;
  31726. exports.PlaneHelper = PlaneHelper;
  31727. exports.PointLight = PointLight;
  31728. exports.PointLightHelper = PointLightHelper;
  31729. exports.Points = Points;
  31730. exports.PointsMaterial = PointsMaterial;
  31731. exports.PolarGridHelper = PolarGridHelper;
  31732. exports.PolyhedronGeometry = PolyhedronGeometry;
  31733. exports.PositionalAudio = PositionalAudio;
  31734. exports.PropertyBinding = PropertyBinding;
  31735. exports.PropertyMixer = PropertyMixer;
  31736. exports.QuadraticBezierCurve = QuadraticBezierCurve;
  31737. exports.QuadraticBezierCurve3 = QuadraticBezierCurve3;
  31738. exports.Quaternion = Quaternion;
  31739. exports.QuaternionKeyframeTrack = QuaternionKeyframeTrack;
  31740. exports.QuaternionLinearInterpolant = QuaternionLinearInterpolant;
  31741. exports.RED_GREEN_RGTC2_Format = RED_GREEN_RGTC2_Format;
  31742. exports.RED_RGTC1_Format = RED_RGTC1_Format;
  31743. exports.REVISION = REVISION;
  31744. exports.RGBADepthPacking = RGBADepthPacking;
  31745. exports.RGBAFormat = RGBAFormat;
  31746. exports.RGBAIntegerFormat = RGBAIntegerFormat;
  31747. exports.RGBA_ASTC_10x10_Format = RGBA_ASTC_10x10_Format;
  31748. exports.RGBA_ASTC_10x5_Format = RGBA_ASTC_10x5_Format;
  31749. exports.RGBA_ASTC_10x6_Format = RGBA_ASTC_10x6_Format;
  31750. exports.RGBA_ASTC_10x8_Format = RGBA_ASTC_10x8_Format;
  31751. exports.RGBA_ASTC_12x10_Format = RGBA_ASTC_12x10_Format;
  31752. exports.RGBA_ASTC_12x12_Format = RGBA_ASTC_12x12_Format;
  31753. exports.RGBA_ASTC_4x4_Format = RGBA_ASTC_4x4_Format;
  31754. exports.RGBA_ASTC_5x4_Format = RGBA_ASTC_5x4_Format;
  31755. exports.RGBA_ASTC_5x5_Format = RGBA_ASTC_5x5_Format;
  31756. exports.RGBA_ASTC_6x5_Format = RGBA_ASTC_6x5_Format;
  31757. exports.RGBA_ASTC_6x6_Format = RGBA_ASTC_6x6_Format;
  31758. exports.RGBA_ASTC_8x5_Format = RGBA_ASTC_8x5_Format;
  31759. exports.RGBA_ASTC_8x6_Format = RGBA_ASTC_8x6_Format;
  31760. exports.RGBA_ASTC_8x8_Format = RGBA_ASTC_8x8_Format;
  31761. exports.RGBA_BPTC_Format = RGBA_BPTC_Format;
  31762. exports.RGBA_ETC2_EAC_Format = RGBA_ETC2_EAC_Format;
  31763. exports.RGBA_PVRTC_2BPPV1_Format = RGBA_PVRTC_2BPPV1_Format;
  31764. exports.RGBA_PVRTC_4BPPV1_Format = RGBA_PVRTC_4BPPV1_Format;
  31765. exports.RGBA_S3TC_DXT1_Format = RGBA_S3TC_DXT1_Format;
  31766. exports.RGBA_S3TC_DXT3_Format = RGBA_S3TC_DXT3_Format;
  31767. exports.RGBA_S3TC_DXT5_Format = RGBA_S3TC_DXT5_Format;
  31768. exports.RGB_BPTC_SIGNED_Format = RGB_BPTC_SIGNED_Format;
  31769. exports.RGB_BPTC_UNSIGNED_Format = RGB_BPTC_UNSIGNED_Format;
  31770. exports.RGB_ETC1_Format = RGB_ETC1_Format;
  31771. exports.RGB_ETC2_Format = RGB_ETC2_Format;
  31772. exports.RGB_PVRTC_2BPPV1_Format = RGB_PVRTC_2BPPV1_Format;
  31773. exports.RGB_PVRTC_4BPPV1_Format = RGB_PVRTC_4BPPV1_Format;
  31774. exports.RGB_S3TC_DXT1_Format = RGB_S3TC_DXT1_Format;
  31775. exports.RGFormat = RGFormat;
  31776. exports.RGIntegerFormat = RGIntegerFormat;
  31777. exports.RawShaderMaterial = RawShaderMaterial;
  31778. exports.Ray = Ray;
  31779. exports.Raycaster = Raycaster;
  31780. exports.Rec709Primaries = Rec709Primaries;
  31781. exports.RectAreaLight = RectAreaLight;
  31782. exports.RedFormat = RedFormat;
  31783. exports.RedIntegerFormat = RedIntegerFormat;
  31784. exports.ReinhardToneMapping = ReinhardToneMapping;
  31785. exports.RenderTarget = RenderTarget;
  31786. exports.RepeatWrapping = RepeatWrapping;
  31787. exports.ReplaceStencilOp = ReplaceStencilOp;
  31788. exports.ReverseSubtractEquation = ReverseSubtractEquation;
  31789. exports.RingGeometry = RingGeometry;
  31790. exports.SIGNED_RED_GREEN_RGTC2_Format = SIGNED_RED_GREEN_RGTC2_Format;
  31791. exports.SIGNED_RED_RGTC1_Format = SIGNED_RED_RGTC1_Format;
  31792. exports.SRGBColorSpace = SRGBColorSpace;
  31793. exports.SRGBTransfer = SRGBTransfer;
  31794. exports.Scene = Scene;
  31795. exports.ShaderChunk = ShaderChunk;
  31796. exports.ShaderLib = ShaderLib;
  31797. exports.ShaderMaterial = ShaderMaterial;
  31798. exports.ShadowMaterial = ShadowMaterial;
  31799. exports.Shape = Shape;
  31800. exports.ShapeGeometry = ShapeGeometry;
  31801. exports.ShapePath = ShapePath;
  31802. exports.ShapeUtils = ShapeUtils;
  31803. exports.ShortType = ShortType;
  31804. exports.Skeleton = Skeleton;
  31805. exports.SkeletonHelper = SkeletonHelper;
  31806. exports.SkinnedMesh = SkinnedMesh;
  31807. exports.Source = Source;
  31808. exports.Sphere = Sphere;
  31809. exports.SphereGeometry = SphereGeometry;
  31810. exports.Spherical = Spherical;
  31811. exports.SphericalHarmonics3 = SphericalHarmonics3;
  31812. exports.SplineCurve = SplineCurve;
  31813. exports.SpotLight = SpotLight;
  31814. exports.SpotLightHelper = SpotLightHelper;
  31815. exports.Sprite = Sprite;
  31816. exports.SpriteMaterial = SpriteMaterial;
  31817. exports.SrcAlphaFactor = SrcAlphaFactor;
  31818. exports.SrcAlphaSaturateFactor = SrcAlphaSaturateFactor;
  31819. exports.SrcColorFactor = SrcColorFactor;
  31820. exports.StaticCopyUsage = StaticCopyUsage;
  31821. exports.StaticDrawUsage = StaticDrawUsage;
  31822. exports.StaticReadUsage = StaticReadUsage;
  31823. exports.StereoCamera = StereoCamera;
  31824. exports.StreamCopyUsage = StreamCopyUsage;
  31825. exports.StreamDrawUsage = StreamDrawUsage;
  31826. exports.StreamReadUsage = StreamReadUsage;
  31827. exports.StringKeyframeTrack = StringKeyframeTrack;
  31828. exports.SubtractEquation = SubtractEquation;
  31829. exports.SubtractiveBlending = SubtractiveBlending;
  31830. exports.TOUCH = TOUCH;
  31831. exports.TangentSpaceNormalMap = TangentSpaceNormalMap;
  31832. exports.TetrahedronGeometry = TetrahedronGeometry;
  31833. exports.Texture = Texture;
  31834. exports.TextureLoader = TextureLoader;
  31835. exports.TorusGeometry = TorusGeometry;
  31836. exports.TorusKnotGeometry = TorusKnotGeometry;
  31837. exports.Triangle = Triangle;
  31838. exports.TriangleFanDrawMode = TriangleFanDrawMode;
  31839. exports.TriangleStripDrawMode = TriangleStripDrawMode;
  31840. exports.TrianglesDrawMode = TrianglesDrawMode;
  31841. exports.TubeGeometry = TubeGeometry;
  31842. exports.UVMapping = UVMapping;
  31843. exports.Uint16BufferAttribute = Uint16BufferAttribute;
  31844. exports.Uint32BufferAttribute = Uint32BufferAttribute;
  31845. exports.Uint8BufferAttribute = Uint8BufferAttribute;
  31846. exports.Uint8ClampedBufferAttribute = Uint8ClampedBufferAttribute;
  31847. exports.Uniform = Uniform;
  31848. exports.UniformsGroup = UniformsGroup;
  31849. exports.UniformsLib = UniformsLib;
  31850. exports.UniformsUtils = UniformsUtils;
  31851. exports.UnsignedByteType = UnsignedByteType;
  31852. exports.UnsignedInt248Type = UnsignedInt248Type;
  31853. exports.UnsignedIntType = UnsignedIntType;
  31854. exports.UnsignedShort4444Type = UnsignedShort4444Type;
  31855. exports.UnsignedShort5551Type = UnsignedShort5551Type;
  31856. exports.UnsignedShortType = UnsignedShortType;
  31857. exports.VSMShadowMap = VSMShadowMap;
  31858. exports.Vector2 = Vector2;
  31859. exports.Vector3 = Vector3;
  31860. exports.Vector4 = Vector4;
  31861. exports.VectorKeyframeTrack = VectorKeyframeTrack;
  31862. exports.VideoTexture = VideoTexture;
  31863. exports.WebGL1Renderer = WebGL1Renderer;
  31864. exports.WebGL3DRenderTarget = WebGL3DRenderTarget;
  31865. exports.WebGLArrayRenderTarget = WebGLArrayRenderTarget;
  31866. exports.WebGLCoordinateSystem = WebGLCoordinateSystem;
  31867. exports.WebGLCubeRenderTarget = WebGLCubeRenderTarget;
  31868. exports.WebGLMultipleRenderTargets = WebGLMultipleRenderTargets;
  31869. exports.WebGLRenderTarget = WebGLRenderTarget;
  31870. exports.WebGLRenderer = WebGLRenderer;
  31871. exports.WebGLUtils = WebGLUtils;
  31872. exports.WebGPUCoordinateSystem = WebGPUCoordinateSystem;
  31873. exports.WireframeGeometry = WireframeGeometry;
  31874. exports.WrapAroundEnding = WrapAroundEnding;
  31875. exports.ZeroCurvatureEnding = ZeroCurvatureEnding;
  31876. exports.ZeroFactor = ZeroFactor;
  31877. exports.ZeroSlopeEnding = ZeroSlopeEnding;
  31878. exports.ZeroStencilOp = ZeroStencilOp;
  31879. exports._SRGBAFormat = _SRGBAFormat;
  31880. exports.createCanvasElement = createCanvasElement;