1
0

three.webgpu.js 1.6 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169431704317143172431734317443175431764317743178431794318043181431824318343184431854318643187431884318943190431914319243193431944319543196431974319843199432004320143202432034320443205432064320743208432094321043211432124321343214432154321643217432184321943220432214322243223432244322543226432274322843229432304323143232432334323443235432364323743238432394324043241432424324343244432454324643247432484324943250432514325243253432544325543256432574325843259432604326143262432634326443265432664326743268432694327043271432724327343274432754327643277432784327943280432814328243283432844328543286432874328843289432904329143292432934329443295432964329743298432994330043301433024330343304433054330643307433084330943310433114331243313433144331543316433174331843319433204332143322433234332443325433264332743328433294333043331433324333343334433354333643337433384333943340433414334243343433444334543346433474334843349433504335143352433534335443355433564335743358433594336043361433624336343364433654336643367433684336943370433714337243373433744337543376433774337843379433804338143382433834338443385433864338743388433894339043391433924339343394433954339643397433984339943400434014340243403434044340543406434074340843409434104341143412434134341443415434164341743418434194342043421434224342343424434254342643427434284342943430434314343243433434344343543436434374343843439434404344143442434434344443445434464344743448434494345043451434524345343454434554345643457434584345943460434614346243463434644346543466434674346843469434704347143472434734347443475434764347743478434794348043481434824348343484434854348643487434884348943490434914349243493434944349543496434974349843499435004350143502435034350443505435064350743508435094351043511435124351343514435154351643517435184351943520435214352243523435244352543526435274352843529435304353143532435334353443535435364353743538435394354043541435424354343544435454354643547435484354943550435514355243553435544355543556435574355843559435604356143562435634356443565435664356743568435694357043571435724357343574435754357643577435784357943580435814358243583435844358543586435874358843589435904359143592435934359443595435964359743598435994360043601436024360343604436054360643607436084360943610436114361243613436144361543616436174361843619436204362143622436234362443625436264362743628436294363043631436324363343634436354363643637436384363943640436414364243643436444364543646436474364843649436504365143652436534365443655436564365743658436594366043661436624366343664436654366643667436684366943670436714367243673436744367543676436774367843679436804368143682436834368443685436864368743688436894369043691436924369343694436954369643697436984369943700437014370243703437044370543706437074370843709437104371143712437134371443715437164371743718437194372043721437224372343724437254372643727437284372943730437314373243733437344373543736437374373843739437404374143742437434374443745437464374743748437494375043751437524375343754437554375643757437584375943760437614376243763437644376543766437674376843769437704377143772437734377443775437764377743778437794378043781437824378343784437854378643787437884378943790437914379243793437944379543796437974379843799438004380143802438034380443805438064380743808438094381043811438124381343814438154381643817438184381943820438214382243823438244382543826438274382843829438304383143832438334383443835438364383743838438394384043841438424384343844438454384643847438484384943850438514385243853438544385543856438574385843859438604386143862438634386443865438664386743868438694387043871438724387343874438754387643877438784387943880438814388243883438844388543886438874388843889438904389143892438934389443895438964389743898438994390043901439024390343904439054390643907439084390943910439114391243913439144391543916439174391843919439204392143922439234392443925439264392743928439294393043931439324393343934439354393643937439384393943940439414394243943439444394543946439474394843949439504395143952439534395443955439564395743958439594396043961439624396343964439654396643967439684396943970439714397243973439744397543976439774397843979439804398143982439834398443985439864398743988439894399043991439924399343994439954399643997439984399944000440014400244003440044400544006440074400844009440104401144012440134401444015440164401744018440194402044021440224402344024440254402644027440284402944030440314403244033440344403544036440374403844039440404404144042440434404444045440464404744048440494405044051440524405344054440554405644057440584405944060440614406244063440644406544066440674406844069440704407144072440734407444075440764407744078440794408044081440824408344084440854408644087440884408944090440914409244093440944409544096440974409844099441004410144102441034410444105441064410744108441094411044111441124411344114441154411644117441184411944120441214412244123441244412544126441274412844129441304413144132441334413444135441364413744138441394414044141441424414344144441454414644147441484414944150441514415244153441544415544156441574415844159441604416144162441634416444165441664416744168441694417044171441724417344174441754417644177441784417944180441814418244183441844418544186441874418844189441904419144192441934419444195441964419744198441994420044201442024420344204442054420644207442084420944210442114421244213442144421544216442174421844219442204422144222442234422444225442264422744228442294423044231442324423344234442354423644237442384423944240442414424244243442444424544246442474424844249442504425144252442534425444255442564425744258442594426044261442624426344264442654426644267442684426944270442714427244273442744427544276442774427844279442804428144282442834428444285442864428744288442894429044291442924429344294442954429644297442984429944300443014430244303443044430544306443074430844309443104431144312443134431444315443164431744318443194432044321443224432344324443254432644327443284432944330443314433244333443344433544336443374433844339443404434144342443434434444345443464434744348443494435044351443524435344354443554435644357443584435944360443614436244363443644436544366443674436844369443704437144372443734437444375443764437744378443794438044381443824438344384443854438644387443884438944390443914439244393443944439544396443974439844399444004440144402444034440444405444064440744408444094441044411444124441344414444154441644417444184441944420444214442244423444244442544426444274442844429444304443144432444334443444435444364443744438444394444044441444424444344444444454444644447444484444944450444514445244453444544445544456444574445844459444604446144462444634446444465444664446744468444694447044471444724447344474444754447644477444784447944480444814448244483444844448544486444874448844489444904449144492444934449444495444964449744498444994450044501445024450344504445054450644507445084450944510445114451244513445144451544516445174451844519445204452144522445234452444525445264452744528445294453044531445324453344534445354453644537445384453944540445414454244543445444454544546445474454844549445504455144552445534455444555445564455744558445594456044561445624456344564445654456644567445684456944570445714457244573445744457544576445774457844579445804458144582445834458444585445864458744588445894459044591445924459344594445954459644597445984459944600446014460244603446044460544606446074460844609446104461144612446134461444615446164461744618446194462044621446224462344624446254462644627446284462944630446314463244633446344463544636446374463844639446404464144642446434464444645446464464744648446494465044651446524465344654446554465644657446584465944660446614466244663446644466544666446674466844669446704467144672446734467444675446764467744678446794468044681446824468344684446854468644687446884468944690446914469244693446944469544696446974469844699447004470144702447034470444705447064470744708447094471044711447124471344714447154471644717447184471944720447214472244723447244472544726447274472844729447304473144732447334473444735447364473744738447394474044741447424474344744447454474644747447484474944750447514475244753447544475544756447574475844759447604476144762447634476444765447664476744768447694477044771447724477344774447754477644777447784477944780447814478244783447844478544786447874478844789447904479144792447934479444795447964479744798447994480044801448024480344804448054480644807448084480944810448114481244813448144481544816448174481844819448204482144822448234482444825448264482744828448294483044831448324483344834448354483644837448384483944840448414484244843448444484544846448474484844849448504485144852448534485444855448564485744858448594486044861448624486344864448654486644867448684486944870448714487244873448744487544876448774487844879448804488144882448834488444885448864488744888448894489044891448924489344894448954489644897448984489944900449014490244903449044490544906449074490844909449104491144912449134491444915449164491744918449194492044921449224492344924449254492644927449284492944930449314493244933449344493544936449374493844939449404494144942449434494444945449464494744948449494495044951449524495344954449554495644957449584495944960449614496244963449644496544966449674496844969449704497144972449734497444975449764497744978449794498044981449824498344984449854498644987449884498944990449914499244993449944499544996449974499844999450004500145002450034500445005450064500745008450094501045011450124501345014450154501645017450184501945020450214502245023450244502545026450274502845029450304503145032450334503445035450364503745038450394504045041450424504345044450454504645047450484504945050450514505245053450544505545056450574505845059450604506145062450634506445065450664506745068450694507045071450724507345074450754507645077450784507945080450814508245083450844508545086450874508845089450904509145092450934509445095450964509745098450994510045101451024510345104451054510645107451084510945110451114511245113451144511545116451174511845119451204512145122451234512445125451264512745128451294513045131451324513345134451354513645137451384513945140451414514245143451444514545146451474514845149451504515145152451534515445155451564515745158451594516045161451624516345164451654516645167451684516945170451714517245173451744517545176451774517845179451804518145182451834518445185451864518745188451894519045191451924519345194451954519645197451984519945200452014520245203452044520545206452074520845209452104521145212452134521445215452164521745218452194522045221452224522345224452254522645227452284522945230452314523245233452344523545236452374523845239452404524145242452434524445245452464524745248452494525045251452524525345254452554525645257452584525945260452614526245263452644526545266452674526845269452704527145272452734527445275452764527745278452794528045281452824528345284452854528645287452884528945290452914529245293452944529545296452974529845299453004530145302453034530445305453064530745308453094531045311453124531345314453154531645317453184531945320453214532245323453244532545326453274532845329453304533145332453334533445335453364533745338453394534045341453424534345344453454534645347453484534945350453514535245353453544535545356453574535845359453604536145362453634536445365453664536745368453694537045371453724537345374453754537645377453784537945380453814538245383453844538545386453874538845389453904539145392453934539445395453964539745398453994540045401454024540345404454054540645407454084540945410454114541245413454144541545416454174541845419454204542145422454234542445425454264542745428454294543045431454324543345434454354543645437454384543945440454414544245443454444544545446454474544845449454504545145452454534545445455454564545745458454594546045461454624546345464454654546645467454684546945470454714547245473454744547545476454774547845479454804548145482454834548445485454864548745488454894549045491454924549345494454954549645497454984549945500455014550245503455044550545506455074550845509455104551145512455134551445515455164551745518455194552045521455224552345524455254552645527455284552945530455314553245533455344553545536455374553845539455404554145542455434554445545455464554745548455494555045551455524555345554455554555645557455584555945560455614556245563455644556545566455674556845569455704557145572455734557445575455764557745578455794558045581455824558345584455854558645587455884558945590455914559245593455944559545596455974559845599456004560145602456034560445605456064560745608456094561045611456124561345614456154561645617456184561945620456214562245623456244562545626456274562845629456304563145632456334563445635456364563745638456394564045641456424564345644456454564645647456484564945650456514565245653456544565545656456574565845659456604566145662456634566445665456664566745668456694567045671456724567345674456754567645677456784567945680456814568245683456844568545686456874568845689456904569145692456934569445695456964569745698456994570045701457024570345704457054570645707457084570945710457114571245713457144571545716457174571845719457204572145722457234572445725457264572745728457294573045731457324573345734457354573645737457384573945740457414574245743457444574545746457474574845749457504575145752457534575445755457564575745758457594576045761457624576345764457654576645767457684576945770457714577245773457744577545776457774577845779457804578145782457834578445785457864578745788457894579045791457924579345794457954579645797457984579945800458014580245803458044580545806458074580845809458104581145812458134581445815458164581745818458194582045821458224582345824458254582645827458284582945830458314583245833458344583545836458374583845839458404584145842458434584445845458464584745848458494585045851458524585345854458554585645857458584585945860458614586245863458644586545866458674586845869458704587145872458734587445875458764587745878458794588045881458824588345884458854588645887458884588945890458914589245893458944589545896458974589845899459004590145902459034590445905459064590745908459094591045911459124591345914459154591645917459184591945920459214592245923459244592545926459274592845929459304593145932459334593445935459364593745938459394594045941459424594345944459454594645947459484594945950459514595245953459544595545956459574595845959459604596145962459634596445965459664596745968459694597045971459724597345974459754597645977459784597945980459814598245983459844598545986459874598845989459904599145992459934599445995459964599745998459994600046001460024600346004460054600646007460084600946010460114601246013460144601546016460174601846019460204602146022460234602446025460264602746028460294603046031460324603346034460354603646037460384603946040460414604246043460444604546046460474604846049460504605146052460534605446055460564605746058460594606046061460624606346064460654606646067460684606946070460714607246073460744607546076460774607846079460804608146082460834608446085460864608746088460894609046091460924609346094460954609646097460984609946100461014610246103461044610546106461074610846109461104611146112461134611446115461164611746118461194612046121461224612346124461254612646127461284612946130461314613246133461344613546136461374613846139461404614146142461434614446145461464614746148461494615046151461524615346154461554615646157461584615946160461614616246163461644616546166461674616846169461704617146172461734617446175461764617746178461794618046181461824618346184461854618646187461884618946190461914619246193461944619546196461974619846199462004620146202462034620446205462064620746208462094621046211462124621346214462154621646217462184621946220462214622246223462244622546226462274622846229462304623146232462334623446235462364623746238462394624046241462424624346244462454624646247462484624946250462514625246253462544625546256462574625846259462604626146262462634626446265462664626746268462694627046271462724627346274462754627646277462784627946280462814628246283462844628546286462874628846289462904629146292462934629446295462964629746298462994630046301463024630346304463054630646307463084630946310463114631246313463144631546316463174631846319463204632146322463234632446325463264632746328463294633046331463324633346334463354633646337463384633946340463414634246343463444634546346463474634846349463504635146352463534635446355463564635746358463594636046361463624636346364463654636646367463684636946370463714637246373463744637546376463774637846379463804638146382463834638446385463864638746388463894639046391463924639346394463954639646397463984639946400464014640246403464044640546406464074640846409464104641146412464134641446415464164641746418464194642046421464224642346424464254642646427464284642946430464314643246433464344643546436464374643846439464404644146442464434644446445464464644746448464494645046451464524645346454464554645646457464584645946460464614646246463464644646546466464674646846469464704647146472464734647446475464764647746478464794648046481464824648346484464854648646487464884648946490464914649246493464944649546496464974649846499465004650146502465034650446505465064650746508465094651046511465124651346514465154651646517465184651946520465214652246523465244652546526465274652846529465304653146532465334653446535465364653746538465394654046541465424654346544465454654646547465484654946550465514655246553465544655546556465574655846559465604656146562465634656446565465664656746568465694657046571465724657346574465754657646577465784657946580465814658246583465844658546586465874658846589465904659146592465934659446595465964659746598465994660046601466024660346604466054660646607466084660946610466114661246613466144661546616466174661846619466204662146622466234662446625466264662746628466294663046631466324663346634466354663646637466384663946640466414664246643466444664546646466474664846649466504665146652466534665446655466564665746658466594666046661466624666346664466654666646667466684666946670466714667246673466744667546676466774667846679466804668146682466834668446685466864668746688466894669046691466924669346694466954669646697466984669946700467014670246703467044670546706467074670846709467104671146712467134671446715467164671746718467194672046721467224672346724467254672646727467284672946730467314673246733467344673546736467374673846739467404674146742467434674446745467464674746748467494675046751467524675346754467554675646757467584675946760467614676246763467644676546766467674676846769467704677146772467734677446775467764677746778467794678046781467824678346784467854678646787467884678946790467914679246793467944679546796467974679846799468004680146802468034680446805468064680746808468094681046811468124681346814468154681646817468184681946820468214682246823468244682546826468274682846829468304683146832468334683446835468364683746838468394684046841468424684346844468454684646847468484684946850468514685246853468544685546856468574685846859468604686146862468634686446865468664686746868468694687046871468724687346874468754687646877468784687946880468814688246883468844688546886468874688846889468904689146892468934689446895468964689746898468994690046901469024690346904469054690646907469084690946910469114691246913469144691546916469174691846919469204692146922469234692446925469264692746928469294693046931469324693346934469354693646937469384693946940469414694246943469444694546946469474694846949469504695146952469534695446955469564695746958469594696046961469624696346964469654696646967469684696946970469714697246973469744697546976469774697846979469804698146982469834698446985469864698746988469894699046991469924699346994469954699646997469984699947000470014700247003470044700547006470074700847009470104701147012470134701447015470164701747018470194702047021470224702347024470254702647027470284702947030470314703247033470344703547036470374703847039470404704147042470434704447045470464704747048470494705047051470524705347054470554705647057470584705947060470614706247063470644706547066470674706847069470704707147072470734707447075470764707747078470794708047081470824708347084470854708647087470884708947090470914709247093470944709547096470974709847099471004710147102471034710447105471064710747108471094711047111471124711347114471154711647117471184711947120471214712247123471244712547126471274712847129471304713147132471334713447135471364713747138471394714047141471424714347144471454714647147471484714947150471514715247153471544715547156471574715847159471604716147162471634716447165471664716747168471694717047171471724717347174471754717647177471784717947180471814718247183471844718547186471874718847189471904719147192471934719447195471964719747198471994720047201472024720347204472054720647207472084720947210472114721247213472144721547216472174721847219472204722147222472234722447225472264722747228472294723047231472324723347234472354723647237472384723947240472414724247243472444724547246472474724847249472504725147252472534725447255472564725747258472594726047261472624726347264472654726647267472684726947270472714727247273472744727547276472774727847279472804728147282472834728447285472864728747288472894729047291472924729347294472954729647297472984729947300473014730247303473044730547306473074730847309473104731147312473134731447315473164731747318473194732047321473224732347324473254732647327473284732947330473314733247333473344733547336473374733847339473404734147342473434734447345473464734747348473494735047351473524735347354473554735647357473584735947360473614736247363473644736547366473674736847369473704737147372473734737447375473764737747378473794738047381473824738347384473854738647387473884738947390473914739247393473944739547396473974739847399474004740147402474034740447405474064740747408474094741047411474124741347414474154741647417474184741947420474214742247423474244742547426474274742847429474304743147432474334743447435474364743747438474394744047441474424744347444474454744647447474484744947450474514745247453474544745547456474574745847459474604746147462474634746447465474664746747468474694747047471474724747347474474754747647477474784747947480474814748247483474844748547486474874748847489474904749147492474934749447495474964749747498474994750047501475024750347504475054750647507475084750947510475114751247513475144751547516475174751847519475204752147522475234752447525475264752747528475294753047531475324753347534475354753647537475384753947540475414754247543475444754547546475474754847549475504755147552475534755447555475564755747558475594756047561475624756347564475654756647567475684756947570475714757247573475744757547576475774757847579475804758147582475834758447585475864758747588475894759047591475924759347594475954759647597475984759947600476014760247603476044760547606476074760847609476104761147612476134761447615476164761747618476194762047621476224762347624476254762647627476284762947630476314763247633476344763547636476374763847639476404764147642476434764447645476464764747648476494765047651476524765347654476554765647657476584765947660476614766247663476644766547666476674766847669476704767147672476734767447675476764767747678476794768047681476824768347684476854768647687476884768947690476914769247693476944769547696476974769847699477004770147702477034770447705477064770747708477094771047711477124771347714477154771647717477184771947720477214772247723477244772547726477274772847729477304773147732477334773447735477364773747738477394774047741477424774347744477454774647747477484774947750477514775247753477544775547756477574775847759477604776147762477634776447765477664776747768477694777047771477724777347774477754777647777477784777947780477814778247783477844778547786477874778847789477904779147792477934779447795477964779747798477994780047801478024780347804478054780647807478084780947810478114781247813478144781547816478174781847819478204782147822478234782447825478264782747828478294783047831478324783347834478354783647837478384783947840478414784247843478444784547846478474784847849478504785147852478534785447855478564785747858478594786047861478624786347864478654786647867478684786947870478714787247873478744787547876478774787847879478804788147882478834788447885478864788747888478894789047891478924789347894478954789647897478984789947900479014790247903479044790547906479074790847909479104791147912479134791447915479164791747918479194792047921479224792347924479254792647927479284792947930479314793247933479344793547936479374793847939479404794147942479434794447945479464794747948479494795047951479524795347954479554795647957479584795947960479614796247963479644796547966479674796847969479704797147972479734797447975479764797747978479794798047981479824798347984479854798647987479884798947990479914799247993479944799547996479974799847999480004800148002480034800448005480064800748008480094801048011480124801348014480154801648017480184801948020480214802248023480244802548026480274802848029480304803148032480334803448035480364803748038480394804048041480424804348044480454804648047480484804948050480514805248053480544805548056480574805848059480604806148062480634806448065480664806748068480694807048071480724807348074480754807648077480784807948080480814808248083480844808548086480874808848089480904809148092480934809448095480964809748098480994810048101481024810348104481054810648107481084810948110481114811248113481144811548116481174811848119481204812148122481234812448125481264812748128481294813048131481324813348134481354813648137481384813948140481414814248143481444814548146481474814848149481504815148152481534815448155481564815748158481594816048161481624816348164481654816648167481684816948170481714817248173481744817548176481774817848179481804818148182481834818448185481864818748188481894819048191481924819348194481954819648197481984819948200482014820248203482044820548206482074820848209482104821148212482134821448215482164821748218482194822048221482224822348224482254822648227482284822948230482314823248233482344823548236482374823848239482404824148242482434824448245482464824748248482494825048251482524825348254482554825648257482584825948260482614826248263482644826548266482674826848269482704827148272482734827448275482764827748278482794828048281482824828348284482854828648287482884828948290482914829248293482944829548296482974829848299483004830148302483034830448305483064830748308483094831048311483124831348314483154831648317483184831948320483214832248323483244832548326483274832848329483304833148332483334833448335483364833748338483394834048341483424834348344483454834648347483484834948350483514835248353483544835548356483574835848359483604836148362483634836448365483664836748368483694837048371483724837348374483754837648377483784837948380483814838248383483844838548386483874838848389483904839148392483934839448395483964839748398483994840048401484024840348404484054840648407484084840948410484114841248413484144841548416484174841848419484204842148422484234842448425484264842748428484294843048431484324843348434484354843648437484384843948440484414844248443484444844548446484474844848449484504845148452484534845448455484564845748458484594846048461484624846348464484654846648467484684846948470484714847248473484744847548476484774847848479484804848148482484834848448485484864848748488484894849048491484924849348494484954849648497484984849948500485014850248503485044850548506485074850848509485104851148512485134851448515485164851748518485194852048521485224852348524485254852648527485284852948530485314853248533485344853548536485374853848539485404854148542485434854448545485464854748548485494855048551485524855348554485554855648557485584855948560485614856248563485644856548566485674856848569485704857148572485734857448575485764857748578485794858048581485824858348584485854858648587485884858948590485914859248593485944859548596485974859848599486004860148602486034860448605486064860748608486094861048611486124861348614486154861648617486184861948620486214862248623486244862548626486274862848629486304863148632486334863448635486364863748638486394864048641486424864348644486454864648647486484864948650486514865248653486544865548656486574865848659486604866148662486634866448665486664866748668486694867048671486724867348674486754867648677486784867948680486814868248683486844868548686486874868848689486904869148692486934869448695486964869748698486994870048701487024870348704487054870648707487084870948710487114871248713487144871548716487174871848719487204872148722487234872448725487264872748728487294873048731487324873348734487354873648737487384873948740487414874248743487444874548746487474874848749487504875148752487534875448755487564875748758487594876048761487624876348764487654876648767487684876948770487714877248773487744877548776487774877848779487804878148782487834878448785487864878748788487894879048791487924879348794487954879648797487984879948800488014880248803488044880548806488074880848809488104881148812488134881448815488164881748818488194882048821488224882348824488254882648827488284882948830488314883248833488344883548836488374883848839488404884148842488434884448845488464884748848488494885048851488524885348854488554885648857488584885948860488614886248863488644886548866488674886848869488704887148872488734887448875488764887748878488794888048881488824888348884488854888648887488884888948890488914889248893488944889548896488974889848899489004890148902489034890448905489064890748908489094891048911489124891348914489154891648917489184891948920489214892248923489244892548926489274892848929489304893148932489334893448935489364893748938489394894048941489424894348944489454894648947489484894948950489514895248953489544895548956489574895848959489604896148962489634896448965489664896748968489694897048971489724897348974489754897648977489784897948980489814898248983489844898548986489874898848989489904899148992489934899448995489964899748998489994900049001490024900349004490054900649007490084900949010490114901249013490144901549016490174901849019490204902149022490234902449025490264902749028490294903049031490324903349034490354903649037490384903949040490414904249043490444904549046490474904849049490504905149052490534905449055490564905749058490594906049061490624906349064490654906649067490684906949070490714907249073490744907549076490774907849079490804908149082490834908449085490864908749088490894909049091490924909349094490954909649097490984909949100491014910249103491044910549106491074910849109491104911149112491134911449115491164911749118491194912049121491224912349124491254912649127491284912949130491314913249133491344913549136491374913849139491404914149142491434914449145491464914749148491494915049151491524915349154491554915649157491584915949160491614916249163491644916549166491674916849169491704917149172491734917449175491764917749178491794918049181491824918349184491854918649187491884918949190491914919249193491944919549196491974919849199492004920149202492034920449205492064920749208492094921049211492124921349214492154921649217492184921949220492214922249223492244922549226492274922849229492304923149232492334923449235492364923749238492394924049241492424924349244492454924649247492484924949250492514925249253492544925549256492574925849259492604926149262492634926449265492664926749268492694927049271492724927349274492754927649277492784927949280492814928249283492844928549286492874928849289492904929149292492934929449295492964929749298492994930049301493024930349304493054930649307493084930949310493114931249313493144931549316493174931849319493204932149322493234932449325493264932749328493294933049331493324933349334493354933649337493384933949340493414934249343493444934549346493474934849349493504935149352493534935449355493564935749358493594936049361493624936349364493654936649367493684936949370493714937249373493744937549376493774937849379493804938149382493834938449385493864938749388493894939049391493924939349394493954939649397493984939949400494014940249403494044940549406494074940849409494104941149412494134941449415494164941749418494194942049421494224942349424494254942649427494284942949430494314943249433494344943549436494374943849439494404944149442494434944449445494464944749448494494945049451494524945349454494554945649457494584945949460494614946249463494644946549466494674946849469494704947149472494734947449475494764947749478494794948049481494824948349484494854948649487494884948949490494914949249493494944949549496494974949849499495004950149502495034950449505495064950749508495094951049511495124951349514495154951649517495184951949520495214952249523495244952549526495274952849529495304953149532495334953449535495364953749538495394954049541495424954349544495454954649547495484954949550495514955249553495544955549556495574955849559495604956149562495634956449565495664956749568495694957049571495724957349574495754957649577495784957949580495814958249583495844958549586495874958849589495904959149592495934959449595495964959749598495994960049601496024960349604496054960649607496084960949610496114961249613496144961549616496174961849619496204962149622496234962449625496264962749628496294963049631496324963349634496354963649637496384963949640496414964249643496444964549646496474964849649496504965149652496534965449655496564965749658496594966049661496624966349664496654966649667496684966949670496714967249673496744967549676496774967849679496804968149682496834968449685496864968749688496894969049691496924969349694496954969649697496984969949700497014970249703497044970549706497074970849709497104971149712497134971449715497164971749718497194972049721497224972349724497254972649727497284972949730497314973249733497344973549736497374973849739497404974149742497434974449745497464974749748497494975049751497524975349754497554975649757497584975949760497614976249763497644976549766497674976849769497704977149772497734977449775497764977749778497794978049781497824978349784497854978649787497884978949790497914979249793497944979549796497974979849799498004980149802498034980449805498064980749808498094981049811498124981349814498154981649817498184981949820498214982249823498244982549826498274982849829498304983149832498334983449835498364983749838498394984049841498424984349844498454984649847498484984949850498514985249853498544985549856498574985849859498604986149862498634986449865498664986749868498694987049871498724987349874498754987649877498784987949880498814988249883498844988549886498874988849889498904989149892498934989449895498964989749898498994990049901499024990349904499054990649907499084990949910499114991249913499144991549916499174991849919499204992149922499234992449925499264992749928499294993049931499324993349934499354993649937499384993949940499414994249943499444994549946499474994849949499504995149952499534995449955499564995749958499594996049961499624996349964499654996649967499684996949970499714997249973499744997549976499774997849979499804998149982499834998449985499864998749988499894999049991499924999349994499954999649997499984999950000500015000250003500045000550006500075000850009500105001150012500135001450015500165001750018500195002050021500225002350024500255002650027500285002950030500315003250033500345003550036500375003850039500405004150042500435004450045500465004750048500495005050051500525005350054500555005650057500585005950060500615006250063500645006550066500675006850069500705007150072500735007450075500765007750078500795008050081500825008350084500855008650087500885008950090500915009250093500945009550096500975009850099501005010150102501035010450105501065010750108501095011050111501125011350114501155011650117501185011950120501215012250123501245012550126501275012850129501305013150132501335013450135501365013750138501395014050141501425014350144501455014650147501485014950150501515015250153501545015550156501575015850159501605016150162501635016450165501665016750168501695017050171501725017350174501755017650177501785017950180501815018250183501845018550186501875018850189501905019150192501935019450195501965019750198501995020050201502025020350204502055020650207502085020950210502115021250213502145021550216502175021850219502205022150222502235022450225502265022750228502295023050231502325023350234502355023650237502385023950240502415024250243502445024550246502475024850249502505025150252502535025450255502565025750258502595026050261502625026350264502655026650267502685026950270502715027250273502745027550276502775027850279502805028150282502835028450285502865028750288502895029050291502925029350294502955029650297502985029950300503015030250303503045030550306503075030850309503105031150312503135031450315503165031750318503195032050321503225032350324503255032650327503285032950330503315033250333503345033550336503375033850339503405034150342503435034450345503465034750348503495035050351503525035350354503555035650357503585035950360503615036250363503645036550366503675036850369503705037150372503735037450375503765037750378503795038050381503825038350384503855038650387503885038950390503915039250393503945039550396503975039850399504005040150402504035040450405504065040750408504095041050411504125041350414504155041650417504185041950420504215042250423504245042550426504275042850429504305043150432504335043450435504365043750438504395044050441504425044350444504455044650447504485044950450504515045250453504545045550456504575045850459504605046150462504635046450465504665046750468504695047050471504725047350474504755047650477504785047950480504815048250483504845048550486504875048850489504905049150492504935049450495504965049750498504995050050501505025050350504505055050650507505085050950510505115051250513505145051550516505175051850519505205052150522505235052450525505265052750528505295053050531505325053350534505355053650537505385053950540505415054250543505445054550546505475054850549505505055150552505535055450555505565055750558505595056050561505625056350564505655056650567505685056950570505715057250573505745057550576505775057850579505805058150582505835058450585505865058750588505895059050591505925059350594505955059650597505985059950600506015060250603506045060550606506075060850609506105061150612506135061450615506165061750618506195062050621506225062350624506255062650627506285062950630506315063250633506345063550636506375063850639506405064150642506435064450645506465064750648506495065050651506525065350654506555065650657506585065950660506615066250663506645066550666506675066850669506705067150672506735067450675506765067750678506795068050681506825068350684506855068650687506885068950690506915069250693506945069550696506975069850699507005070150702507035070450705507065070750708507095071050711507125071350714507155071650717507185071950720507215072250723507245072550726507275072850729507305073150732507335073450735507365073750738507395074050741507425074350744507455074650747507485074950750507515075250753507545075550756507575075850759507605076150762507635076450765507665076750768507695077050771507725077350774507755077650777507785077950780507815078250783507845078550786507875078850789507905079150792507935079450795507965079750798507995080050801508025080350804508055080650807508085080950810508115081250813508145081550816508175081850819508205082150822508235082450825508265082750828508295083050831508325083350834508355083650837508385083950840508415084250843508445084550846508475084850849508505085150852508535085450855508565085750858508595086050861508625086350864508655086650867508685086950870508715087250873508745087550876508775087850879508805088150882508835088450885508865088750888508895089050891508925089350894508955089650897508985089950900509015090250903509045090550906509075090850909509105091150912509135091450915509165091750918509195092050921509225092350924509255092650927509285092950930509315093250933509345093550936509375093850939509405094150942509435094450945509465094750948509495095050951509525095350954509555095650957509585095950960509615096250963509645096550966509675096850969509705097150972509735097450975509765097750978509795098050981509825098350984509855098650987509885098950990509915099250993509945099550996509975099850999510005100151002510035100451005510065100751008510095101051011510125101351014510155101651017510185101951020510215102251023510245102551026510275102851029510305103151032510335103451035510365103751038510395104051041510425104351044510455104651047510485104951050510515105251053510545105551056510575105851059510605106151062510635106451065510665106751068510695107051071510725107351074510755107651077510785107951080510815108251083510845108551086510875108851089510905109151092510935109451095510965109751098510995110051101511025110351104511055110651107511085110951110511115111251113511145111551116511175111851119511205112151122511235112451125511265112751128511295113051131511325113351134511355113651137511385113951140511415114251143511445114551146511475114851149511505115151152511535115451155511565115751158511595116051161511625116351164511655116651167511685116951170511715117251173511745117551176511775117851179511805118151182511835118451185511865118751188511895119051191511925119351194511955119651197511985119951200512015120251203512045120551206512075120851209512105121151212512135121451215512165121751218512195122051221512225122351224512255122651227512285122951230512315123251233512345123551236512375123851239512405124151242512435124451245512465124751248512495125051251512525125351254512555125651257512585125951260512615126251263512645126551266512675126851269512705127151272512735127451275512765127751278512795128051281512825128351284512855128651287512885128951290512915129251293512945129551296512975129851299513005130151302513035130451305513065130751308513095131051311513125131351314513155131651317513185131951320513215132251323513245132551326513275132851329513305133151332513335133451335513365133751338513395134051341513425134351344513455134651347513485134951350513515135251353513545135551356513575135851359513605136151362513635136451365513665136751368513695137051371513725137351374513755137651377513785137951380513815138251383513845138551386513875138851389513905139151392513935139451395513965139751398513995140051401514025140351404514055140651407514085140951410514115141251413514145141551416514175141851419514205142151422514235142451425514265142751428514295143051431514325143351434514355143651437514385143951440514415144251443514445144551446514475144851449514505145151452514535145451455514565145751458514595146051461514625146351464514655146651467514685146951470514715147251473514745147551476514775147851479514805148151482514835148451485514865148751488514895149051491514925149351494514955149651497514985149951500515015150251503515045150551506515075150851509515105151151512515135151451515515165151751518515195152051521515225152351524515255152651527515285152951530515315153251533515345153551536515375153851539515405154151542515435154451545515465154751548515495155051551515525155351554515555155651557515585155951560515615156251563515645156551566515675156851569515705157151572515735157451575515765157751578515795158051581515825158351584515855158651587515885158951590515915159251593515945159551596515975159851599516005160151602516035160451605516065160751608516095161051611516125161351614516155161651617516185161951620516215162251623516245162551626516275162851629516305163151632516335163451635516365163751638516395164051641516425164351644516455164651647516485164951650516515165251653516545165551656516575165851659516605166151662516635166451665516665166751668516695167051671516725167351674516755167651677516785167951680516815168251683516845168551686516875168851689516905169151692516935169451695516965169751698516995170051701517025170351704517055170651707517085170951710517115171251713517145171551716517175171851719517205172151722517235172451725517265172751728517295173051731517325173351734517355173651737517385173951740517415174251743517445174551746517475174851749517505175151752517535175451755517565175751758517595176051761517625176351764517655176651767517685176951770517715177251773517745177551776517775177851779517805178151782517835178451785517865178751788517895179051791517925179351794517955179651797517985179951800518015180251803518045180551806518075180851809518105181151812518135181451815518165181751818518195182051821518225182351824518255182651827518285182951830518315183251833518345183551836518375183851839518405184151842518435184451845518465184751848518495185051851518525185351854518555185651857518585185951860518615186251863518645186551866518675186851869518705187151872518735187451875518765187751878518795188051881518825188351884518855188651887518885188951890518915189251893518945189551896518975189851899519005190151902519035190451905519065190751908519095191051911519125191351914519155191651917519185191951920519215192251923519245192551926519275192851929519305193151932519335193451935519365193751938519395194051941519425194351944519455194651947519485194951950519515195251953519545195551956519575195851959519605196151962519635196451965519665196751968519695197051971519725197351974519755197651977519785197951980519815198251983519845198551986519875198851989519905199151992519935199451995519965199751998519995200052001520025200352004520055200652007520085200952010520115201252013520145201552016520175201852019520205202152022520235202452025520265202752028520295203052031520325203352034520355203652037520385203952040520415204252043520445204552046520475204852049520505205152052520535205452055520565205752058520595206052061520625206352064520655206652067520685206952070520715207252073520745207552076520775207852079520805208152082520835208452085520865208752088520895209052091520925209352094520955209652097520985209952100521015210252103521045210552106521075210852109521105211152112521135211452115521165211752118521195212052121521225212352124521255212652127521285212952130521315213252133521345213552136521375213852139521405214152142521435214452145521465214752148521495215052151521525215352154521555215652157521585215952160521615216252163521645216552166521675216852169521705217152172521735217452175521765217752178521795218052181521825218352184521855218652187521885218952190521915219252193521945219552196521975219852199522005220152202522035220452205522065220752208522095221052211522125221352214522155221652217522185221952220522215222252223522245222552226522275222852229522305223152232522335223452235522365223752238522395224052241522425224352244522455224652247522485224952250522515225252253522545225552256522575225852259522605226152262522635226452265522665226752268522695227052271522725227352274522755227652277522785227952280522815228252283522845228552286522875228852289522905229152292522935229452295522965229752298522995230052301523025230352304523055230652307523085230952310523115231252313523145231552316523175231852319523205232152322523235232452325523265232752328523295233052331523325233352334523355233652337523385233952340523415234252343523445234552346523475234852349523505235152352523535235452355523565235752358523595236052361523625236352364523655236652367523685236952370523715237252373523745237552376523775237852379523805238152382523835238452385523865238752388523895239052391523925239352394523955239652397523985239952400524015240252403524045240552406524075240852409524105241152412524135241452415524165241752418524195242052421524225242352424524255242652427524285242952430524315243252433524345243552436524375243852439524405244152442524435244452445524465244752448524495245052451524525245352454524555245652457524585245952460524615246252463524645246552466524675246852469524705247152472524735247452475524765247752478524795248052481524825248352484524855248652487524885248952490524915249252493524945249552496524975249852499525005250152502525035250452505525065250752508525095251052511525125251352514525155251652517525185251952520525215252252523525245252552526525275252852529525305253152532525335253452535525365253752538525395254052541525425254352544525455254652547525485254952550525515255252553525545255552556525575255852559525605256152562525635256452565525665256752568525695257052571525725257352574525755257652577525785257952580525815258252583525845258552586525875258852589525905259152592525935259452595525965259752598525995260052601526025260352604526055260652607526085260952610526115261252613526145261552616526175261852619526205262152622526235262452625526265262752628526295263052631526325263352634526355263652637526385263952640526415264252643526445264552646526475264852649526505265152652526535265452655526565265752658526595266052661526625266352664526655266652667526685266952670526715267252673526745267552676526775267852679526805268152682526835268452685526865268752688526895269052691526925269352694526955269652697526985269952700527015270252703527045270552706527075270852709527105271152712527135271452715527165271752718527195272052721527225272352724527255272652727527285272952730527315273252733527345273552736527375273852739527405274152742527435274452745527465274752748527495275052751527525275352754527555275652757527585275952760527615276252763527645276552766527675276852769527705277152772527735277452775527765277752778527795278052781527825278352784527855278652787527885278952790527915279252793527945279552796527975279852799528005280152802528035280452805528065280752808528095281052811528125281352814528155281652817528185281952820528215282252823528245282552826528275282852829528305283152832528335283452835528365283752838528395284052841528425284352844528455284652847528485284952850528515285252853528545285552856528575285852859528605286152862528635286452865528665286752868528695287052871528725287352874528755287652877528785287952880528815288252883528845288552886528875288852889528905289152892528935289452895528965289752898528995290052901529025290352904529055290652907529085290952910529115291252913529145291552916529175291852919529205292152922529235292452925529265292752928529295293052931529325293352934529355293652937529385293952940529415294252943529445294552946529475294852949529505295152952529535295452955529565295752958529595296052961529625296352964529655296652967529685296952970529715297252973529745297552976529775297852979529805298152982529835298452985529865298752988529895299052991529925299352994529955299652997529985299953000530015300253003530045300553006530075300853009530105301153012530135301453015530165301753018530195302053021530225302353024530255302653027530285302953030530315303253033530345303553036530375303853039530405304153042530435304453045530465304753048530495305053051530525305353054530555305653057530585305953060530615306253063530645306553066530675306853069530705307153072530735307453075530765307753078530795308053081530825308353084530855308653087530885308953090530915309253093530945309553096530975309853099531005310153102531035310453105531065310753108531095311053111531125311353114531155311653117531185311953120531215312253123531245312553126531275312853129531305313153132531335313453135531365313753138531395314053141531425314353144531455314653147531485314953150531515315253153531545315553156531575315853159531605316153162531635316453165531665316753168531695317053171531725317353174531755317653177531785317953180531815318253183531845318553186531875318853189531905319153192531935319453195531965319753198531995320053201532025320353204532055320653207532085320953210532115321253213532145321553216532175321853219532205322153222532235322453225532265322753228532295323053231532325323353234532355323653237532385323953240532415324253243532445324553246532475324853249532505325153252532535325453255532565325753258532595326053261532625326353264532655326653267532685326953270532715327253273532745327553276532775327853279532805328153282532835328453285532865328753288532895329053291532925329353294532955329653297532985329953300533015330253303533045330553306533075330853309533105331153312533135331453315533165331753318533195332053321533225332353324533255332653327533285332953330533315333253333533345333553336533375333853339533405334153342533435334453345533465334753348533495335053351533525335353354533555335653357533585335953360533615336253363533645336553366533675336853369533705337153372533735337453375533765337753378533795338053381533825338353384533855338653387533885338953390533915339253393533945339553396533975339853399534005340153402534035340453405534065340753408534095341053411534125341353414534155341653417534185341953420534215342253423534245342553426534275342853429534305343153432534335343453435534365343753438534395344053441534425344353444534455344653447534485344953450534515345253453534545345553456534575345853459534605346153462534635346453465534665346753468534695347053471534725347353474534755347653477534785347953480534815348253483534845348553486534875348853489534905349153492534935349453495534965349753498534995350053501535025350353504535055350653507535085350953510535115351253513535145351553516535175351853519535205352153522535235352453525535265352753528535295353053531535325353353534535355353653537535385353953540535415354253543535445354553546535475354853549535505355153552535535355453555535565355753558535595356053561535625356353564535655356653567535685356953570535715357253573535745357553576535775357853579535805358153582535835358453585535865358753588535895359053591535925359353594535955359653597535985359953600536015360253603536045360553606536075360853609536105361153612536135361453615536165361753618536195362053621536225362353624536255362653627536285362953630536315363253633536345363553636536375363853639536405364153642536435364453645536465364753648536495365053651536525365353654536555365653657536585365953660536615366253663536645366553666536675366853669536705367153672536735367453675536765367753678536795368053681536825368353684536855368653687536885368953690536915369253693536945369553696536975369853699537005370153702537035370453705537065370753708537095371053711537125371353714537155371653717537185371953720537215372253723537245372553726537275372853729537305373153732537335373453735537365373753738537395374053741537425374353744537455374653747537485374953750537515375253753537545375553756537575375853759537605376153762537635376453765537665376753768537695377053771537725377353774537755377653777537785377953780537815378253783537845378553786537875378853789537905379153792537935379453795537965379753798537995380053801538025380353804538055380653807538085380953810538115381253813538145381553816538175381853819538205382153822538235382453825538265382753828538295383053831538325383353834538355383653837538385383953840538415384253843538445384553846538475384853849538505385153852538535385453855538565385753858538595386053861538625386353864538655386653867538685386953870538715387253873538745387553876538775387853879538805388153882538835388453885538865388753888538895389053891538925389353894538955389653897538985389953900539015390253903539045390553906539075390853909539105391153912539135391453915539165391753918539195392053921539225392353924539255392653927539285392953930539315393253933539345393553936539375393853939539405394153942539435394453945539465394753948539495395053951539525395353954539555395653957539585395953960539615396253963539645396553966539675396853969539705397153972539735397453975539765397753978539795398053981539825398353984539855398653987539885398953990539915399253993539945399553996539975399853999540005400154002540035400454005540065400754008540095401054011540125401354014540155401654017540185401954020540215402254023540245402554026540275402854029540305403154032540335403454035540365403754038540395404054041540425404354044540455404654047540485404954050540515405254053540545405554056540575405854059540605406154062540635406454065540665406754068540695407054071540725407354074540755407654077540785407954080540815408254083540845408554086540875408854089540905409154092540935409454095540965409754098540995410054101541025410354104541055410654107541085410954110541115411254113541145411554116541175411854119541205412154122541235412454125541265412754128541295413054131541325413354134541355413654137541385413954140541415414254143541445414554146541475414854149541505415154152541535415454155541565415754158541595416054161541625416354164541655416654167541685416954170541715417254173541745417554176541775417854179541805418154182541835418454185541865418754188541895419054191541925419354194541955419654197541985419954200542015420254203542045420554206542075420854209542105421154212542135421454215542165421754218542195422054221542225422354224542255422654227542285422954230542315423254233542345423554236542375423854239542405424154242542435424454245542465424754248542495425054251542525425354254542555425654257542585425954260542615426254263542645426554266542675426854269542705427154272542735427454275542765427754278542795428054281542825428354284542855428654287542885428954290542915429254293542945429554296542975429854299543005430154302543035430454305543065430754308543095431054311543125431354314543155431654317543185431954320543215432254323543245432554326543275432854329543305433154332543335433454335543365433754338543395434054341543425434354344543455434654347543485434954350543515435254353543545435554356543575435854359543605436154362543635436454365543665436754368543695437054371543725437354374543755437654377543785437954380543815438254383543845438554386543875438854389543905439154392543935439454395543965439754398543995440054401544025440354404544055440654407544085440954410544115441254413544145441554416544175441854419544205442154422544235442454425544265442754428544295443054431544325443354434544355443654437544385443954440544415444254443544445444554446544475444854449544505445154452544535445454455544565445754458544595446054461544625446354464544655446654467544685446954470544715447254473544745447554476544775447854479544805448154482544835448454485544865448754488544895449054491544925449354494544955449654497544985449954500545015450254503545045450554506545075450854509545105451154512545135451454515545165451754518545195452054521545225452354524545255452654527545285452954530545315453254533545345453554536545375453854539545405454154542545435454454545545465454754548545495455054551545525455354554545555455654557545585455954560545615456254563545645456554566545675456854569545705457154572545735457454575545765457754578545795458054581545825458354584545855458654587545885458954590545915459254593545945459554596545975459854599546005460154602546035460454605546065460754608546095461054611546125461354614546155461654617546185461954620546215462254623546245462554626546275462854629546305463154632546335463454635546365463754638546395464054641546425464354644546455464654647546485464954650546515465254653546545465554656546575465854659546605466154662546635466454665546665466754668546695467054671546725467354674546755467654677546785467954680546815468254683546845468554686546875468854689546905469154692546935469454695546965469754698546995470054701547025470354704547055470654707547085470954710547115471254713547145471554716547175471854719547205472154722547235472454725547265472754728547295473054731547325473354734547355473654737547385473954740547415474254743547445474554746547475474854749547505475154752547535475454755547565475754758547595476054761547625476354764547655476654767547685476954770547715477254773547745477554776547775477854779547805478154782547835478454785547865478754788547895479054791547925479354794547955479654797547985479954800548015480254803548045480554806548075480854809548105481154812548135481454815548165481754818548195482054821548225482354824548255482654827548285482954830548315483254833548345483554836548375483854839548405484154842548435484454845548465484754848548495485054851548525485354854548555485654857548585485954860548615486254863548645486554866548675486854869548705487154872548735487454875548765487754878548795488054881548825488354884548855488654887548885488954890548915489254893548945489554896548975489854899549005490154902549035490454905549065490754908549095491054911549125491354914549155491654917549185491954920549215492254923549245492554926549275492854929549305493154932549335493454935549365493754938549395494054941549425494354944549455494654947549485494954950549515495254953549545495554956549575495854959549605496154962549635496454965549665496754968549695497054971549725497354974549755497654977549785497954980549815498254983549845498554986549875498854989549905499154992549935499454995549965499754998549995500055001550025500355004550055500655007550085500955010550115501255013550145501555016550175501855019550205502155022550235502455025550265502755028550295503055031550325503355034550355503655037550385503955040550415504255043550445504555046550475504855049550505505155052550535505455055550565505755058550595506055061550625506355064550655506655067550685506955070550715507255073550745507555076550775507855079550805508155082550835508455085550865508755088550895509055091550925509355094550955509655097550985509955100551015510255103551045510555106551075510855109551105511155112551135511455115551165511755118551195512055121551225512355124551255512655127551285512955130551315513255133551345513555136551375513855139551405514155142551435514455145551465514755148551495515055151551525515355154551555515655157551585515955160551615516255163551645516555166551675516855169551705517155172551735517455175551765517755178551795518055181551825518355184551855518655187551885518955190551915519255193551945519555196551975519855199552005520155202552035520455205552065520755208552095521055211552125521355214552155521655217552185521955220552215522255223552245522555226552275522855229552305523155232552335523455235552365523755238552395524055241552425524355244552455524655247552485524955250552515525255253552545525555256552575525855259552605526155262552635526455265552665526755268552695527055271552725527355274552755527655277552785527955280552815528255283552845528555286552875528855289552905529155292552935529455295552965529755298552995530055301553025530355304553055530655307553085530955310553115531255313553145531555316553175531855319553205532155322553235532455325553265532755328553295533055331553325533355334553355533655337553385533955340553415534255343553445534555346553475534855349553505535155352553535535455355553565535755358553595536055361553625536355364553655536655367553685536955370553715537255373553745537555376553775537855379553805538155382553835538455385553865538755388553895539055391553925539355394553955539655397553985539955400554015540255403554045540555406554075540855409554105541155412554135541455415554165541755418554195542055421554225542355424554255542655427554285542955430554315543255433554345543555436554375543855439554405544155442554435544455445554465544755448554495545055451554525545355454554555545655457554585545955460554615546255463554645546555466554675546855469554705547155472554735547455475554765547755478554795548055481554825548355484554855548655487554885548955490554915549255493554945549555496554975549855499555005550155502555035550455505555065550755508555095551055511555125551355514555155551655517555185551955520555215552255523555245552555526555275552855529555305553155532555335553455535555365553755538555395554055541555425554355544555455554655547555485554955550555515555255553555545555555556555575555855559555605556155562555635556455565555665556755568555695557055571555725557355574555755557655577555785557955580555815558255583555845558555586555875558855589555905559155592555935559455595555965559755598555995560055601556025560355604556055560655607556085560955610556115561255613556145561555616556175561855619556205562155622556235562455625556265562755628556295563055631556325563355634556355563655637556385563955640556415564255643556445564555646556475564855649556505565155652556535565455655556565565755658556595566055661556625566355664556655566655667556685566955670556715567255673556745567555676556775567855679556805568155682556835568455685556865568755688556895569055691556925569355694556955569655697556985569955700557015570255703557045570555706557075570855709557105571155712557135571455715557165571755718557195572055721557225572355724557255572655727557285572955730557315573255733557345573555736557375573855739557405574155742557435574455745557465574755748557495575055751557525575355754557555575655757557585575955760557615576255763557645576555766557675576855769557705577155772557735577455775557765577755778557795578055781557825578355784557855578655787557885578955790557915579255793557945579555796557975579855799558005580155802558035580455805558065580755808558095581055811558125581355814558155581655817558185581955820558215582255823558245582555826558275582855829558305583155832558335583455835558365583755838558395584055841558425584355844558455584655847558485584955850558515585255853558545585555856558575585855859558605586155862558635586455865558665586755868558695587055871558725587355874558755587655877558785587955880558815588255883558845588555886558875588855889558905589155892558935589455895558965589755898558995590055901559025590355904559055590655907559085590955910559115591255913559145591555916559175591855919559205592155922559235592455925559265592755928559295593055931559325593355934559355593655937559385593955940559415594255943559445594555946559475594855949559505595155952559535595455955559565595755958559595596055961559625596355964559655596655967559685596955970559715597255973559745597555976559775597855979559805598155982559835598455985559865598755988559895599055991559925599355994559955599655997559985599956000560015600256003560045600556006560075600856009560105601156012560135601456015560165601756018560195602056021560225602356024560255602656027560285602956030560315603256033560345603556036560375603856039560405604156042560435604456045560465604756048560495605056051560525605356054560555605656057560585605956060560615606256063560645606556066560675606856069560705607156072560735607456075560765607756078560795608056081560825608356084560855608656087560885608956090560915609256093560945609556096560975609856099561005610156102561035610456105561065610756108561095611056111561125611356114561155611656117561185611956120561215612256123561245612556126561275612856129561305613156132561335613456135561365613756138561395614056141561425614356144561455614656147561485614956150561515615256153561545615556156561575615856159561605616156162561635616456165561665616756168561695617056171561725617356174561755617656177561785617956180561815618256183561845618556186561875618856189561905619156192561935619456195561965619756198561995620056201562025620356204562055620656207562085620956210562115621256213562145621556216562175621856219562205622156222562235622456225562265622756228562295623056231562325623356234562355623656237562385623956240562415624256243562445624556246562475624856249562505625156252562535625456255562565625756258562595626056261562625626356264562655626656267562685626956270562715627256273562745627556276562775627856279562805628156282562835628456285562865628756288562895629056291562925629356294562955629656297562985629956300563015630256303563045630556306563075630856309563105631156312563135631456315563165631756318563195632056321563225632356324563255632656327563285632956330563315633256333563345633556336563375633856339563405634156342563435634456345563465634756348563495635056351563525635356354563555635656357563585635956360563615636256363563645636556366563675636856369563705637156372563735637456375563765637756378563795638056381563825638356384563855638656387563885638956390563915639256393563945639556396563975639856399564005640156402564035640456405564065640756408564095641056411564125641356414564155641656417564185641956420564215642256423564245642556426564275642856429564305643156432564335643456435564365643756438564395644056441564425644356444564455644656447564485644956450564515645256453564545645556456564575645856459564605646156462564635646456465564665646756468564695647056471564725647356474564755647656477564785647956480564815648256483564845648556486564875648856489564905649156492564935649456495564965649756498564995650056501565025650356504565055650656507565085650956510565115651256513565145651556516565175651856519565205652156522565235652456525565265652756528565295653056531565325653356534565355653656537565385653956540565415654256543565445654556546565475654856549565505655156552565535655456555565565655756558565595656056561565625656356564565655656656567565685656956570565715657256573565745657556576565775657856579565805658156582565835658456585565865658756588565895659056591565925659356594565955659656597565985659956600566015660256603566045660556606566075660856609566105661156612566135661456615566165661756618566195662056621566225662356624566255662656627566285662956630566315663256633566345663556636566375663856639566405664156642566435664456645566465664756648566495665056651566525665356654566555665656657566585665956660566615666256663566645666556666566675666856669566705667156672566735667456675566765667756678566795668056681566825668356684566855668656687566885668956690566915669256693566945669556696566975669856699567005670156702567035670456705567065670756708567095671056711567125671356714567155671656717567185671956720567215672256723567245672556726567275672856729567305673156732567335673456735567365673756738567395674056741567425674356744567455674656747567485674956750567515675256753567545675556756567575675856759567605676156762567635676456765567665676756768567695677056771567725677356774567755677656777567785677956780567815678256783567845678556786567875678856789567905679156792567935679456795567965679756798567995680056801568025680356804568055680656807568085680956810568115681256813568145681556816568175681856819568205682156822568235682456825568265682756828568295683056831568325683356834568355683656837568385683956840568415684256843568445684556846568475684856849568505685156852568535685456855568565685756858568595686056861568625686356864568655686656867568685686956870568715687256873568745687556876568775687856879568805688156882568835688456885568865688756888568895689056891568925689356894568955689656897568985689956900569015690256903569045690556906569075690856909569105691156912569135691456915569165691756918569195692056921569225692356924569255692656927569285692956930569315693256933569345693556936569375693856939569405694156942569435694456945569465694756948569495695056951569525695356954569555695656957569585695956960569615696256963569645696556966569675696856969569705697156972569735697456975569765697756978569795698056981569825698356984569855698656987569885698956990569915699256993569945699556996569975699856999570005700157002570035700457005570065700757008570095701057011570125701357014570155701657017570185701957020570215702257023570245702557026570275702857029570305703157032570335703457035570365703757038570395704057041570425704357044570455704657047570485704957050570515705257053570545705557056570575705857059570605706157062570635706457065570665706757068570695707057071570725707357074570755707657077570785707957080570815708257083570845708557086570875708857089570905709157092570935709457095570965709757098570995710057101571025710357104571055710657107571085710957110571115711257113571145711557116571175711857119571205712157122571235712457125571265712757128571295713057131571325713357134571355713657137571385713957140571415714257143571445714557146571475714857149571505715157152571535715457155571565715757158571595716057161571625716357164571655716657167571685716957170571715717257173571745717557176571775717857179571805718157182571835718457185571865718757188571895719057191571925719357194571955719657197571985719957200572015720257203572045720557206572075720857209572105721157212572135721457215572165721757218572195722057221572225722357224572255722657227572285722957230572315723257233572345723557236572375723857239572405724157242572435724457245572465724757248572495725057251572525725357254572555725657257572585725957260572615726257263572645726557266572675726857269572705727157272572735727457275572765727757278572795728057281572825728357284572855728657287572885728957290572915729257293572945729557296572975729857299573005730157302573035730457305573065730757308573095731057311573125731357314573155731657317573185731957320573215732257323573245732557326573275732857329573305733157332573335733457335573365733757338573395734057341573425734357344573455734657347573485734957350573515735257353573545735557356573575735857359573605736157362573635736457365573665736757368573695737057371573725737357374573755737657377573785737957380573815738257383573845738557386573875738857389573905739157392573935739457395573965739757398573995740057401574025740357404574055740657407574085740957410574115741257413574145741557416574175741857419574205742157422574235742457425574265742757428574295743057431574325743357434574355743657437574385743957440574415744257443574445744557446574475744857449574505745157452574535745457455574565745757458574595746057461574625746357464574655746657467574685746957470574715747257473574745747557476574775747857479574805748157482574835748457485574865748757488574895749057491574925749357494574955749657497574985749957500575015750257503575045750557506575075750857509575105751157512575135751457515575165751757518575195752057521575225752357524575255752657527575285752957530575315753257533575345753557536575375753857539575405754157542575435754457545575465754757548575495755057551575525755357554575555755657557575585755957560575615756257563575645756557566575675756857569575705757157572575735757457575575765757757578575795758057581575825758357584575855758657587575885758957590575915759257593575945759557596575975759857599576005760157602576035760457605576065760757608576095761057611576125761357614576155761657617576185761957620576215762257623576245762557626576275762857629576305763157632576335763457635576365763757638576395764057641576425764357644576455764657647576485764957650576515765257653576545765557656576575765857659576605766157662576635766457665576665766757668576695767057671576725767357674576755767657677576785767957680576815768257683576845768557686576875768857689576905769157692576935769457695576965769757698576995770057701577025770357704577055770657707577085770957710577115771257713577145771557716577175771857719577205772157722577235772457725577265772757728577295773057731577325773357734577355773657737577385773957740577415774257743577445774557746577475774857749577505775157752577535775457755577565775757758577595776057761577625776357764577655776657767577685776957770577715777257773577745777557776577775777857779577805778157782577835778457785577865778757788577895779057791577925779357794577955779657797577985779957800578015780257803578045780557806578075780857809578105781157812578135781457815578165781757818578195782057821578225782357824578255782657827578285782957830578315783257833578345783557836578375783857839578405784157842578435784457845578465784757848578495785057851578525785357854578555785657857578585785957860578615786257863578645786557866578675786857869578705787157872578735787457875578765787757878578795788057881578825788357884578855788657887578885788957890578915789257893578945789557896578975789857899579005790157902579035790457905579065790757908579095791057911579125791357914579155791657917579185791957920579215792257923579245792557926579275792857929579305793157932579335793457935579365793757938579395794057941579425794357944579455794657947579485794957950579515795257953579545795557956579575795857959579605796157962579635796457965579665796757968579695797057971579725797357974579755797657977579785797957980579815798257983579845798557986579875798857989579905799157992579935799457995579965799757998579995800058001580025800358004580055800658007580085800958010580115801258013580145801558016580175801858019580205802158022580235802458025580265802758028580295803058031580325803358034580355803658037580385803958040580415804258043580445804558046580475804858049580505805158052580535805458055580565805758058580595806058061580625806358064580655806658067580685806958070580715807258073580745807558076580775807858079580805808158082580835808458085580865808758088580895809058091580925809358094580955809658097580985809958100581015810258103581045810558106581075810858109581105811158112581135811458115581165811758118581195812058121581225812358124581255812658127581285812958130581315813258133581345813558136581375813858139581405814158142581435814458145581465814758148581495815058151581525815358154581555815658157581585815958160581615816258163581645816558166581675816858169581705817158172581735817458175581765817758178581795818058181581825818358184581855818658187581885818958190581915819258193581945819558196581975819858199582005820158202582035820458205582065820758208582095821058211582125821358214582155821658217582185821958220582215822258223582245822558226582275822858229582305823158232582335823458235582365823758238582395824058241582425824358244582455824658247582485824958250582515825258253582545825558256582575825858259582605826158262582635826458265582665826758268582695827058271582725827358274582755827658277582785827958280582815828258283582845828558286582875828858289582905829158292582935829458295582965829758298582995830058301583025830358304583055830658307583085830958310583115831258313583145831558316583175831858319583205832158322583235832458325583265832758328583295833058331583325833358334583355833658337583385833958340583415834258343583445834558346583475834858349583505835158352583535835458355583565835758358583595836058361583625836358364583655836658367583685836958370583715837258373583745837558376583775837858379583805838158382583835838458385583865838758388583895839058391583925839358394583955839658397583985839958400584015840258403584045840558406584075840858409584105841158412584135841458415584165841758418584195842058421584225842358424584255842658427584285842958430584315843258433584345843558436584375843858439584405844158442584435844458445584465844758448584495845058451584525845358454584555845658457584585845958460584615846258463584645846558466584675846858469584705847158472584735847458475584765847758478584795848058481584825848358484584855848658487584885848958490584915849258493584945849558496584975849858499585005850158502585035850458505585065850758508585095851058511585125851358514585155851658517585185851958520585215852258523585245852558526585275852858529585305853158532585335853458535585365853758538585395854058541585425854358544585455854658547585485854958550585515855258553585545855558556585575855858559585605856158562585635856458565585665856758568585695857058571585725857358574585755857658577585785857958580585815858258583585845858558586585875858858589585905859158592585935859458595585965859758598585995860058601586025860358604586055860658607586085860958610586115861258613586145861558616586175861858619586205862158622586235862458625586265862758628586295863058631586325863358634586355863658637586385863958640586415864258643586445864558646586475864858649586505865158652586535865458655586565865758658586595866058661586625866358664586655866658667586685866958670586715867258673586745867558676586775867858679586805868158682586835868458685586865868758688586895869058691586925869358694586955869658697586985869958700587015870258703587045870558706587075870858709587105871158712587135871458715587165871758718587195872058721587225872358724587255872658727587285872958730587315873258733587345873558736587375873858739587405874158742587435874458745587465874758748587495875058751587525875358754587555875658757587585875958760587615876258763587645876558766587675876858769587705877158772587735877458775587765877758778587795878058781587825878358784587855878658787587885878958790587915879258793587945879558796587975879858799588005880158802588035880458805588065880758808588095881058811588125881358814588155881658817588185881958820588215882258823588245882558826588275882858829588305883158832588335883458835588365883758838588395884058841588425884358844588455884658847588485884958850588515885258853588545885558856588575885858859588605886158862588635886458865588665886758868588695887058871588725887358874588755887658877588785887958880588815888258883588845888558886588875888858889588905889158892588935889458895588965889758898588995890058901589025890358904589055890658907589085890958910589115891258913589145891558916589175891858919589205892158922589235892458925589265892758928589295893058931589325893358934589355893658937589385893958940589415894258943589445894558946589475894858949589505895158952589535895458955589565895758958589595896058961589625896358964589655896658967589685896958970589715897258973589745897558976589775897858979589805898158982589835898458985589865898758988589895899058991589925899358994589955899658997589985899959000590015900259003590045900559006590075900859009590105901159012590135901459015590165901759018590195902059021590225902359024590255902659027590285902959030590315903259033590345903559036590375903859039590405904159042590435904459045590465904759048590495905059051590525905359054590555905659057590585905959060590615906259063590645906559066590675906859069590705907159072590735907459075590765907759078590795908059081590825908359084590855908659087590885908959090590915909259093590945909559096590975909859099591005910159102591035910459105591065910759108591095911059111591125911359114591155911659117591185911959120591215912259123591245912559126591275912859129591305913159132591335913459135591365913759138591395914059141591425914359144591455914659147591485914959150591515915259153591545915559156591575915859159591605916159162591635916459165591665916759168591695917059171591725917359174591755917659177591785917959180591815918259183591845918559186591875918859189591905919159192591935919459195591965919759198591995920059201592025920359204592055920659207592085920959210592115921259213592145921559216592175921859219592205922159222592235922459225592265922759228592295923059231592325923359234592355923659237592385923959240592415924259243592445924559246592475924859249592505925159252592535925459255592565925759258592595926059261592625926359264592655926659267592685926959270592715927259273592745927559276592775927859279592805928159282592835928459285592865928759288592895929059291592925929359294592955929659297592985929959300593015930259303593045930559306593075930859309593105931159312593135931459315593165931759318593195932059321593225932359324593255932659327593285932959330593315933259333593345933559336593375933859339593405934159342593435934459345593465934759348593495935059351593525935359354593555935659357593585935959360593615936259363593645936559366593675936859369593705937159372593735937459375593765937759378593795938059381593825938359384593855938659387593885938959390593915939259393593945939559396593975939859399594005940159402594035940459405594065940759408594095941059411594125941359414594155941659417594185941959420594215942259423594245942559426594275942859429594305943159432594335943459435594365943759438594395944059441594425944359444594455944659447594485944959450594515945259453594545945559456594575945859459594605946159462594635946459465594665946759468594695947059471594725947359474594755947659477594785947959480594815948259483594845948559486594875948859489594905949159492594935949459495594965949759498594995950059501595025950359504595055950659507595085950959510595115951259513595145951559516595175951859519595205952159522595235952459525595265952759528595295953059531595325953359534595355953659537595385953959540595415954259543595445954559546595475954859549595505955159552595535955459555595565955759558595595956059561595625956359564595655956659567595685956959570595715957259573595745957559576595775957859579595805958159582595835958459585595865958759588595895959059591595925959359594595955959659597595985959959600596015960259603596045960559606596075960859609596105961159612596135961459615596165961759618596195962059621596225962359624596255962659627596285962959630596315963259633596345963559636596375963859639596405964159642596435964459645596465964759648596495965059651596525965359654596555965659657596585965959660596615966259663596645966559666596675966859669596705967159672596735967459675596765967759678596795968059681596825968359684596855968659687596885968959690596915969259693596945969559696596975969859699597005970159702597035970459705597065970759708597095971059711597125971359714597155971659717597185971959720597215972259723597245972559726597275972859729597305973159732597335973459735597365973759738597395974059741597425974359744597455974659747597485974959750597515975259753597545975559756597575975859759597605976159762597635976459765597665976759768597695977059771597725977359774597755977659777597785977959780597815978259783597845978559786597875978859789597905979159792597935979459795597965979759798597995980059801598025980359804598055980659807598085980959810598115981259813598145981559816598175981859819598205982159822598235982459825598265982759828598295983059831598325983359834598355983659837598385983959840598415984259843598445984559846598475984859849598505985159852598535985459855598565985759858598595986059861598625986359864598655986659867598685986959870598715987259873598745987559876598775987859879598805988159882598835988459885598865988759888598895989059891598925989359894598955989659897598985989959900599015990259903599045990559906599075990859909599105991159912599135991459915599165991759918599195992059921599225992359924599255992659927599285992959930599315993259933599345993559936599375993859939599405994159942599435994459945599465994759948599495995059951599525995359954599555995659957599585995959960599615996259963599645996559966599675996859969599705997159972599735997459975599765997759978599795998059981599825998359984599855998659987599885998959990599915999259993599945999559996599975999859999600006000160002600036000460005600066000760008600096001060011600126001360014600156001660017600186001960020600216002260023600246002560026600276002860029600306003160032600336003460035600366003760038600396004060041600426004360044600456004660047600486004960050600516005260053600546005560056600576005860059600606006160062600636006460065600666006760068600696007060071600726007360074600756007660077600786007960080600816008260083600846008560086600876008860089600906009160092600936009460095600966009760098600996010060101601026010360104601056010660107601086010960110601116011260113601146011560116601176011860119601206012160122601236012460125601266012760128601296013060131601326013360134601356013660137601386013960140601416014260143601446014560146601476014860149601506015160152601536015460155601566015760158601596016060161601626016360164601656016660167601686016960170601716017260173601746017560176601776017860179601806018160182601836018460185601866018760188601896019060191601926019360194601956019660197601986019960200602016020260203602046020560206602076020860209602106021160212602136021460215602166021760218602196022060221602226022360224602256022660227602286022960230602316023260233602346023560236602376023860239602406024160242602436024460245602466024760248602496025060251602526025360254602556025660257602586025960260602616026260263602646026560266602676026860269602706027160272602736027460275602766027760278602796028060281602826028360284602856028660287602886028960290602916029260293602946029560296602976029860299603006030160302603036030460305603066030760308603096031060311603126031360314603156031660317603186031960320603216032260323603246032560326603276032860329603306033160332603336033460335603366033760338603396034060341603426034360344603456034660347603486034960350603516035260353603546035560356603576035860359603606036160362603636036460365603666036760368603696037060371603726037360374603756037660377603786037960380603816038260383603846038560386603876038860389603906039160392603936039460395603966039760398603996040060401604026040360404604056040660407604086040960410604116041260413604146041560416604176041860419604206042160422604236042460425604266042760428604296043060431604326043360434604356043660437604386043960440604416044260443604446044560446604476044860449604506045160452604536045460455604566045760458604596046060461604626046360464604656046660467604686046960470604716047260473604746047560476604776047860479604806048160482604836048460485604866048760488604896049060491604926049360494604956049660497604986049960500605016050260503605046050560506605076050860509605106051160512605136051460515605166051760518605196052060521605226052360524605256052660527605286052960530605316053260533605346053560536605376053860539605406054160542605436054460545605466054760548605496055060551605526055360554605556055660557605586055960560605616056260563605646056560566605676056860569605706057160572605736057460575605766057760578605796058060581605826058360584605856058660587605886058960590605916059260593605946059560596605976059860599606006060160602606036060460605606066060760608606096061060611606126061360614606156061660617606186061960620606216062260623606246062560626606276062860629606306063160632606336063460635606366063760638606396064060641606426064360644606456064660647606486064960650606516065260653606546065560656606576065860659606606066160662606636066460665606666066760668606696067060671606726067360674606756067660677606786067960680606816068260683606846068560686606876068860689606906069160692606936069460695606966069760698606996070060701607026070360704607056070660707607086070960710607116071260713607146071560716607176071860719607206072160722607236072460725607266072760728607296073060731607326073360734607356073660737607386073960740607416074260743607446074560746607476074860749607506075160752607536075460755607566075760758607596076060761607626076360764607656076660767607686076960770607716077260773607746077560776607776077860779607806078160782607836078460785607866078760788607896079060791607926079360794607956079660797607986079960800608016080260803608046080560806608076080860809608106081160812608136081460815608166081760818608196082060821608226082360824608256082660827608286082960830608316083260833608346083560836608376083860839608406084160842608436084460845608466084760848608496085060851608526085360854608556085660857608586085960860608616086260863608646086560866608676086860869608706087160872608736087460875608766087760878608796088060881608826088360884608856088660887608886088960890608916089260893608946089560896608976089860899609006090160902609036090460905609066090760908609096091060911609126091360914609156091660917609186091960920609216092260923609246092560926609276092860929609306093160932609336093460935609366093760938609396094060941609426094360944609456094660947609486094960950609516095260953609546095560956609576095860959609606096160962609636096460965609666096760968609696097060971609726097360974609756097660977609786097960980609816098260983609846098560986609876098860989609906099160992609936099460995609966099760998609996100061001610026100361004610056100661007610086100961010610116101261013610146101561016610176101861019610206102161022610236102461025610266102761028610296103061031610326103361034610356103661037610386103961040610416104261043610446104561046610476104861049610506105161052610536105461055610566105761058610596106061061610626106361064610656106661067610686106961070610716107261073610746107561076610776107861079610806108161082610836108461085610866108761088610896109061091610926109361094610956109661097610986109961100611016110261103611046110561106611076110861109611106111161112611136111461115611166111761118611196112061121611226112361124611256112661127611286112961130611316113261133611346113561136611376113861139611406114161142611436114461145611466114761148611496115061151611526115361154611556115661157611586115961160611616116261163611646116561166611676116861169611706117161172611736117461175611766117761178611796118061181611826118361184611856118661187611886118961190611916119261193611946119561196611976119861199612006120161202612036120461205612066120761208612096121061211612126121361214612156121661217612186121961220612216122261223612246122561226612276122861229612306123161232612336123461235612366123761238612396124061241612426124361244612456124661247612486124961250612516125261253612546125561256612576125861259612606126161262612636126461265612666126761268612696127061271612726127361274612756127661277612786127961280612816128261283612846128561286612876128861289612906129161292612936129461295612966129761298612996130061301613026130361304613056130661307613086130961310613116131261313613146131561316613176131861319613206132161322613236132461325613266132761328613296133061331613326133361334613356133661337613386133961340613416134261343613446134561346613476134861349613506135161352613536135461355613566135761358613596136061361613626136361364613656136661367613686136961370613716137261373613746137561376613776137861379613806138161382613836138461385613866138761388613896139061391613926139361394613956139661397613986139961400614016140261403614046140561406614076140861409614106141161412614136141461415614166141761418614196142061421614226142361424614256142661427614286142961430614316143261433614346143561436614376143861439614406144161442614436144461445614466144761448614496145061451614526145361454614556145661457614586145961460614616146261463614646146561466614676146861469614706147161472614736147461475614766147761478614796148061481614826148361484614856148661487614886148961490614916149261493614946149561496614976149861499615006150161502615036150461505615066150761508615096151061511615126151361514615156151661517615186151961520615216152261523615246152561526615276152861529615306153161532615336153461535615366153761538615396154061541615426154361544615456154661547615486154961550615516155261553615546155561556615576155861559615606156161562615636156461565615666156761568615696157061571615726157361574615756157661577615786157961580615816158261583615846158561586615876158861589615906159161592615936159461595615966159761598615996160061601616026160361604616056160661607616086160961610616116161261613616146161561616616176161861619616206162161622616236162461625616266162761628616296163061631616326163361634616356163661637616386163961640616416164261643616446164561646616476164861649616506165161652616536165461655616566165761658616596166061661616626166361664616656166661667616686166961670616716167261673616746167561676616776167861679616806168161682616836168461685616866168761688616896169061691616926169361694616956169661697616986169961700617016170261703617046170561706617076170861709617106171161712617136171461715617166171761718617196172061721617226172361724617256172661727617286172961730617316173261733617346173561736617376173861739617406174161742617436174461745617466174761748617496175061751617526175361754617556175661757617586175961760617616176261763617646176561766617676176861769617706177161772617736177461775617766177761778617796178061781617826178361784617856178661787617886178961790617916179261793617946179561796617976179861799618006180161802618036180461805618066180761808618096181061811618126181361814618156181661817618186181961820618216182261823618246182561826618276182861829618306183161832618336183461835618366183761838618396184061841618426184361844618456184661847618486184961850618516185261853618546185561856618576185861859618606186161862618636186461865618666186761868618696187061871618726187361874618756187661877618786187961880618816188261883618846188561886618876188861889618906189161892618936189461895618966189761898618996190061901619026190361904619056190661907619086190961910619116191261913619146191561916619176191861919619206192161922619236192461925619266192761928619296193061931619326193361934619356193661937619386193961940619416194261943619446194561946619476194861949619506195161952619536195461955619566195761958619596196061961619626196361964619656196661967619686196961970619716197261973619746197561976619776197861979619806198161982619836198461985619866198761988619896199061991619926199361994619956199661997619986199962000620016200262003620046200562006620076200862009620106201162012620136201462015620166201762018620196202062021620226202362024620256202662027620286202962030620316203262033620346203562036620376203862039620406204162042620436204462045620466204762048620496205062051620526205362054620556205662057620586205962060620616206262063620646206562066620676206862069620706207162072620736207462075620766207762078620796208062081620826208362084620856208662087620886208962090620916209262093620946209562096620976209862099621006210162102621036210462105621066210762108621096211062111621126211362114621156211662117621186211962120621216212262123621246212562126621276212862129621306213162132621336213462135621366213762138621396214062141621426214362144621456214662147621486214962150621516215262153621546215562156621576215862159621606216162162621636216462165621666216762168621696217062171621726217362174621756217662177621786217962180621816218262183621846218562186621876218862189621906219162192621936219462195621966219762198621996220062201622026220362204622056220662207622086220962210622116221262213622146221562216622176221862219622206222162222622236222462225622266222762228622296223062231622326223362234622356223662237622386223962240622416224262243622446224562246622476224862249622506225162252622536225462255622566225762258622596226062261622626226362264622656226662267622686226962270622716227262273622746227562276622776227862279622806228162282622836228462285622866228762288622896229062291622926229362294622956229662297622986229962300623016230262303623046230562306623076230862309623106231162312623136231462315623166231762318623196232062321623226232362324623256232662327623286232962330623316233262333623346233562336623376233862339623406234162342623436234462345623466234762348623496235062351623526235362354623556235662357623586235962360623616236262363623646236562366623676236862369623706237162372623736237462375623766237762378623796238062381623826238362384623856238662387623886238962390623916239262393623946239562396623976239862399624006240162402624036240462405624066240762408624096241062411624126241362414624156241662417624186241962420624216242262423624246242562426624276242862429624306243162432624336243462435624366243762438624396244062441624426244362444624456244662447624486244962450624516245262453624546245562456624576245862459624606246162462624636246462465624666246762468624696247062471624726247362474624756247662477624786247962480624816248262483624846248562486624876248862489624906249162492624936249462495624966249762498624996250062501625026250362504625056250662507625086250962510625116251262513625146251562516625176251862519625206252162522625236252462525625266252762528625296253062531625326253362534625356253662537625386253962540625416254262543625446254562546625476254862549625506255162552625536255462555625566255762558625596256062561625626256362564625656256662567625686256962570625716257262573625746257562576625776257862579625806258162582625836258462585625866258762588625896259062591625926259362594625956259662597625986259962600626016260262603626046260562606626076260862609626106261162612626136261462615626166261762618626196262062621626226262362624626256262662627626286262962630626316263262633626346263562636626376263862639626406264162642626436264462645626466264762648626496265062651626526265362654626556265662657626586265962660626616266262663626646266562666626676266862669626706267162672626736267462675626766267762678626796268062681626826268362684626856268662687626886268962690626916269262693626946269562696626976269862699627006270162702627036270462705627066270762708627096271062711627126271362714627156271662717627186271962720627216272262723627246272562726627276272862729627306273162732627336273462735627366273762738627396274062741627426274362744627456274662747627486274962750627516275262753627546275562756627576275862759627606276162762627636276462765627666276762768627696277062771627726277362774627756277662777627786277962780627816278262783627846278562786627876278862789627906279162792627936279462795627966279762798627996280062801628026280362804628056280662807628086280962810628116281262813628146281562816628176281862819628206282162822628236282462825628266282762828628296283062831628326283362834628356283662837628386283962840628416284262843628446284562846628476284862849628506285162852628536285462855628566285762858628596286062861628626286362864628656286662867628686286962870628716287262873628746287562876628776287862879628806288162882628836288462885628866288762888628896289062891628926289362894628956289662897628986289962900629016290262903629046290562906629076290862909629106291162912629136291462915629166291762918629196292062921629226292362924629256292662927629286292962930629316293262933629346293562936629376293862939629406294162942629436294462945629466294762948629496295062951629526295362954629556295662957629586295962960629616296262963629646296562966629676296862969629706297162972629736297462975629766297762978629796298062981629826298362984629856298662987629886298962990629916299262993629946299562996629976299862999630006300163002630036300463005630066300763008630096301063011630126301363014630156301663017630186301963020630216302263023630246302563026630276302863029630306303163032630336303463035630366303763038630396304063041630426304363044630456304663047630486304963050630516305263053630546305563056630576305863059630606306163062630636306463065630666306763068630696307063071630726307363074630756307663077630786307963080630816308263083630846308563086630876308863089630906309163092630936309463095630966309763098630996310063101631026310363104631056310663107631086310963110631116311263113631146311563116631176311863119631206312163122631236312463125631266312763128631296313063131631326313363134631356313663137631386313963140631416314263143631446314563146631476314863149631506315163152631536315463155631566315763158631596316063161631626316363164631656316663167631686316963170631716317263173631746317563176631776317863179631806318163182631836318463185631866318763188631896319063191631926319363194631956319663197631986319963200632016320263203632046320563206632076320863209632106321163212632136321463215632166321763218632196322063221632226322363224632256322663227632286322963230632316323263233632346323563236632376323863239632406324163242632436324463245632466324763248632496325063251632526325363254632556325663257632586325963260632616326263263632646326563266632676326863269632706327163272632736327463275632766327763278632796328063281632826328363284632856328663287632886328963290632916329263293632946329563296632976329863299633006330163302633036330463305633066330763308633096331063311633126331363314633156331663317633186331963320633216332263323633246332563326633276332863329633306333163332633336333463335633366333763338633396334063341633426334363344633456334663347633486334963350633516335263353633546335563356633576335863359633606336163362633636336463365633666336763368633696337063371633726337363374633756337663377633786337963380633816338263383633846338563386633876338863389633906339163392633936339463395633966339763398633996340063401634026340363404634056340663407634086340963410634116341263413634146341563416634176341863419634206342163422634236342463425634266342763428634296343063431634326343363434634356343663437634386343963440634416344263443634446344563446634476344863449634506345163452634536345463455634566345763458634596346063461634626346363464634656346663467634686346963470634716347263473634746347563476634776347863479634806348163482634836348463485634866348763488634896349063491634926349363494634956349663497634986349963500635016350263503635046350563506635076350863509635106351163512635136351463515635166351763518635196352063521635226352363524635256352663527635286352963530635316353263533635346353563536635376353863539635406354163542635436354463545635466354763548635496355063551635526355363554635556355663557635586355963560635616356263563635646356563566635676356863569635706357163572635736357463575635766357763578635796358063581635826358363584635856358663587635886358963590635916359263593635946359563596635976359863599636006360163602636036360463605636066360763608636096361063611636126361363614636156361663617636186361963620636216362263623636246362563626636276362863629636306363163632636336363463635636366363763638636396364063641636426364363644636456364663647636486364963650636516365263653636546365563656636576365863659636606366163662636636366463665636666366763668636696367063671636726367363674636756367663677636786367963680636816368263683636846368563686636876368863689636906369163692636936369463695636966369763698636996370063701637026370363704637056370663707637086370963710637116371263713637146371563716637176371863719637206372163722637236372463725637266372763728637296373063731637326373363734637356373663737637386373963740637416374263743637446374563746637476374863749637506375163752637536375463755637566375763758637596376063761637626376363764637656376663767637686376963770637716377263773637746377563776637776377863779637806378163782637836378463785637866378763788637896379063791637926379363794637956379663797637986379963800638016380263803638046380563806638076380863809638106381163812638136381463815638166381763818638196382063821638226382363824638256382663827638286382963830638316383263833638346383563836638376383863839638406384163842638436384463845638466384763848638496385063851638526385363854638556385663857638586385963860638616386263863638646386563866638676386863869638706387163872638736387463875638766387763878638796388063881638826388363884638856388663887638886388963890638916389263893638946389563896638976389863899639006390163902639036390463905639066390763908639096391063911639126391363914639156391663917639186391963920639216392263923639246392563926639276392863929639306393163932639336393463935639366393763938639396394063941639426394363944639456394663947639486394963950639516395263953639546395563956639576395863959639606396163962639636396463965639666396763968639696397063971639726397363974639756397663977639786397963980639816398263983639846398563986639876398863989639906399163992639936399463995639966399763998639996400064001640026400364004640056400664007640086400964010640116401264013640146401564016640176401864019640206402164022640236402464025640266402764028640296403064031640326403364034640356403664037640386403964040640416404264043640446404564046640476404864049640506405164052640536405464055640566405764058640596406064061640626406364064640656406664067640686406964070640716407264073640746407564076640776407864079640806408164082640836408464085640866408764088640896409064091640926409364094640956409664097640986409964100641016410264103641046410564106641076410864109641106411164112641136411464115641166411764118641196412064121641226412364124641256412664127641286412964130641316413264133641346413564136641376413864139641406414164142641436414464145641466414764148641496415064151641526415364154641556415664157641586415964160641616416264163641646416564166641676416864169641706417164172641736417464175641766417764178641796418064181641826418364184641856418664187641886418964190641916419264193641946419564196641976419864199642006420164202642036420464205642066420764208642096421064211642126421364214642156421664217642186421964220642216422264223642246422564226642276422864229642306423164232642336423464235642366423764238642396424064241642426424364244642456424664247642486424964250642516425264253642546425564256642576425864259642606426164262642636426464265642666426764268642696427064271642726427364274642756427664277642786427964280642816428264283642846428564286642876428864289642906429164292642936429464295642966429764298642996430064301643026430364304643056430664307643086430964310643116431264313643146431564316643176431864319643206432164322643236432464325643266432764328643296433064331643326433364334643356433664337643386433964340643416434264343643446434564346643476434864349643506435164352643536435464355643566435764358643596436064361643626436364364643656436664367643686436964370643716437264373643746437564376643776437864379643806438164382643836438464385643866438764388643896439064391643926439364394643956439664397643986439964400644016440264403644046440564406644076440864409644106441164412644136441464415644166441764418644196442064421644226442364424644256442664427644286442964430644316443264433644346443564436644376443864439644406444164442644436444464445644466444764448644496445064451644526445364454644556445664457644586445964460644616446264463644646446564466644676446864469644706447164472644736447464475644766447764478644796448064481644826448364484644856448664487644886448964490644916449264493644946449564496644976449864499645006450164502645036450464505645066450764508645096451064511645126451364514645156451664517645186451964520645216452264523645246452564526645276452864529645306453164532645336453464535645366453764538645396454064541645426454364544645456454664547645486454964550645516455264553645546455564556645576455864559645606456164562645636456464565645666456764568645696457064571645726457364574645756457664577645786457964580645816458264583645846458564586645876458864589645906459164592645936459464595645966459764598645996460064601646026460364604646056460664607646086460964610646116461264613646146461564616646176461864619646206462164622646236462464625646266462764628646296463064631646326463364634646356463664637646386463964640646416464264643646446464564646646476464864649646506465164652646536465464655646566465764658646596466064661646626466364664646656466664667646686466964670646716467264673646746467564676646776467864679646806468164682646836468464685646866468764688646896469064691646926469364694646956469664697646986469964700647016470264703647046470564706647076470864709647106471164712647136471464715647166471764718647196472064721647226472364724647256472664727647286472964730647316473264733647346473564736647376473864739647406474164742647436474464745647466474764748647496475064751647526475364754647556475664757647586475964760647616476264763647646476564766647676476864769647706477164772647736477464775647766477764778647796478064781647826478364784647856478664787647886478964790647916479264793647946479564796647976479864799648006480164802648036480464805648066480764808648096481064811648126481364814648156481664817648186481964820648216482264823648246482564826648276482864829648306483164832648336483464835648366483764838648396484064841648426484364844648456484664847648486484964850648516485264853648546485564856648576485864859648606486164862648636486464865648666486764868648696487064871648726487364874648756487664877648786487964880648816488264883648846488564886648876488864889648906489164892648936489464895648966489764898648996490064901649026490364904649056490664907649086490964910649116491264913649146491564916649176491864919649206492164922649236492464925649266492764928649296493064931649326493364934649356493664937649386493964940649416494264943649446494564946649476494864949649506495164952649536495464955649566495764958649596496064961649626496364964649656496664967649686496964970649716497264973649746497564976649776497864979649806498164982649836498464985649866498764988649896499064991649926499364994649956499664997649986499965000650016500265003650046500565006650076500865009650106501165012650136501465015650166501765018650196502065021650226502365024650256502665027650286502965030650316503265033650346503565036650376503865039650406504165042650436504465045650466504765048650496505065051650526505365054650556505665057650586505965060650616506265063650646506565066650676506865069650706507165072650736507465075650766507765078650796508065081650826508365084650856508665087650886508965090650916509265093650946509565096650976509865099651006510165102651036510465105651066510765108651096511065111651126511365114651156511665117651186511965120651216512265123651246512565126651276512865129651306513165132651336513465135651366513765138651396514065141651426514365144651456514665147651486514965150651516515265153651546515565156651576515865159651606516165162651636516465165651666516765168651696517065171651726517365174651756517665177651786517965180651816518265183651846518565186651876518865189651906519165192651936519465195651966519765198651996520065201652026520365204652056520665207652086520965210652116521265213652146521565216652176521865219652206522165222652236522465225652266522765228652296523065231652326523365234652356523665237652386523965240652416524265243652446524565246652476524865249652506525165252652536525465255652566525765258652596526065261652626526365264652656526665267652686526965270652716527265273652746527565276652776527865279652806528165282652836528465285652866528765288652896529065291652926529365294652956529665297652986529965300653016530265303653046530565306653076530865309653106531165312653136531465315653166531765318653196532065321653226532365324653256532665327653286532965330653316533265333653346533565336653376533865339653406534165342653436534465345653466534765348653496535065351653526535365354653556535665357653586535965360653616536265363653646536565366653676536865369653706537165372653736537465375653766537765378653796538065381653826538365384653856538665387653886538965390653916539265393653946539565396653976539865399654006540165402654036540465405654066540765408654096541065411654126541365414654156541665417654186541965420654216542265423654246542565426654276542865429654306543165432654336543465435654366543765438654396544065441654426544365444654456544665447654486544965450654516545265453654546545565456654576545865459654606546165462654636546465465654666546765468654696547065471654726547365474654756547665477654786547965480654816548265483654846548565486654876548865489654906549165492654936549465495654966549765498654996550065501655026550365504655056550665507655086550965510655116551265513655146551565516655176551865519655206552165522655236552465525655266552765528655296553065531655326553365534655356553665537655386553965540655416554265543655446554565546655476554865549655506555165552655536555465555655566555765558655596556065561655626556365564655656556665567655686556965570655716557265573655746557565576655776557865579655806558165582655836558465585655866558765588655896559065591655926559365594655956559665597655986559965600656016560265603656046560565606656076560865609656106561165612656136561465615656166561765618656196562065621656226562365624656256562665627656286562965630656316563265633656346563565636656376563865639656406564165642656436564465645656466564765648656496565065651656526565365654656556565665657656586565965660656616566265663656646566565666656676566865669656706567165672656736567465675656766567765678656796568065681656826568365684656856568665687656886568965690656916569265693656946569565696656976569865699657006570165702657036570465705657066570765708657096571065711657126571365714657156571665717657186571965720657216572265723657246572565726657276572865729657306573165732657336573465735657366573765738657396574065741657426574365744657456574665747657486574965750657516575265753657546575565756657576575865759657606576165762657636576465765657666576765768657696577065771657726577365774657756577665777657786577965780657816578265783657846578565786657876578865789657906579165792657936579465795657966579765798657996580065801658026580365804658056580665807658086580965810658116581265813658146581565816658176581865819658206582165822658236582465825658266582765828658296583065831658326583365834658356583665837658386583965840658416584265843658446584565846658476584865849658506585165852658536585465855658566585765858658596586065861658626586365864658656586665867658686586965870658716587265873658746587565876658776587865879658806588165882658836588465885658866588765888658896589065891658926589365894658956589665897658986589965900659016590265903659046590565906659076590865909659106591165912659136591465915659166591765918659196592065921659226592365924659256592665927659286592965930659316593265933659346593565936659376593865939659406594165942659436594465945659466594765948659496595065951659526595365954659556595665957659586595965960659616596265963659646596565966659676596865969659706597165972659736597465975659766597765978659796598065981659826598365984659856598665987659886598965990659916599265993659946599565996659976599865999660006600166002660036600466005660066600766008660096601066011660126601366014660156601666017660186601966020660216602266023660246602566026660276602866029660306603166032660336603466035660366603766038660396604066041660426604366044660456604666047660486604966050660516605266053660546605566056660576605866059660606606166062660636606466065660666606766068660696607066071660726607366074660756607666077660786607966080660816608266083660846608566086660876608866089660906609166092660936609466095660966609766098660996610066101661026610366104661056610666107661086610966110661116611266113661146611566116661176611866119661206612166122661236612466125661266612766128661296613066131661326613366134661356613666137661386613966140661416614266143661446614566146661476614866149661506615166152661536615466155661566615766158661596616066161661626616366164661656616666167661686616966170661716617266173661746617566176661776617866179661806618166182661836618466185661866618766188661896619066191661926619366194661956619666197661986619966200662016620266203662046620566206662076620866209662106621166212662136621466215662166621766218662196622066221662226622366224662256622666227662286622966230662316623266233662346623566236662376623866239662406624166242662436624466245662466624766248662496625066251662526625366254662556625666257662586625966260662616626266263662646626566266662676626866269662706627166272662736627466275662766627766278662796628066281662826628366284662856628666287662886628966290662916629266293662946629566296662976629866299663006630166302663036630466305663066630766308663096631066311663126631366314663156631666317663186631966320663216632266323663246632566326663276632866329663306633166332663336633466335663366633766338663396634066341663426634366344663456634666347663486634966350663516635266353663546635566356663576635866359663606636166362663636636466365663666636766368663696637066371663726637366374663756637666377663786637966380663816638266383663846638566386663876638866389663906639166392663936639466395663966639766398663996640066401664026640366404664056640666407664086640966410664116641266413664146641566416664176641866419664206642166422664236642466425664266642766428664296643066431664326643366434664356643666437664386643966440664416644266443664446644566446664476644866449664506645166452664536645466455664566645766458664596646066461664626646366464664656646666467664686646966470664716647266473664746647566476664776647866479664806648166482664836648466485664866648766488664896649066491664926649366494664956649666497664986649966500665016650266503665046650566506665076650866509665106651166512665136651466515665166651766518665196652066521665226652366524665256652666527665286652966530665316653266533665346653566536665376653866539665406654166542665436654466545665466654766548665496655066551665526655366554665556655666557665586655966560665616656266563665646656566566665676656866569665706657166572665736657466575665766657766578665796658066581665826658366584665856658666587665886658966590665916659266593665946659566596665976659866599666006660166602666036660466605666066660766608666096661066611666126661366614666156661666617666186661966620666216662266623666246662566626666276662866629666306663166632666336663466635666366663766638666396664066641666426664366644666456664666647666486664966650666516665266653666546665566656666576665866659666606666166662666636666466665666666666766668666696667066671666726667366674666756667666677666786667966680666816668266683666846668566686666876668866689666906669166692666936669466695666966669766698666996670066701667026670366704667056670666707667086670966710667116671266713667146671566716667176671866719667206672166722667236672466725667266672766728667296673066731667326673366734667356673666737667386673966740667416674266743667446674566746667476674866749667506675166752667536675466755667566675766758667596676066761667626676366764667656676666767667686676966770667716677266773667746677566776667776677866779667806678166782667836678466785667866678766788667896679066791667926679366794667956679666797667986679966800668016680266803668046680566806668076680866809668106681166812668136681466815668166681766818668196682066821668226682366824668256682666827668286682966830668316683266833668346683566836668376683866839668406684166842668436684466845668466684766848668496685066851668526685366854668556685666857668586685966860668616686266863668646686566866668676686866869668706687166872668736687466875668766687766878668796688066881668826688366884668856688666887668886688966890668916689266893668946689566896668976689866899669006690166902669036690466905669066690766908669096691066911669126691366914669156691666917669186691966920669216692266923669246692566926669276692866929669306693166932669336693466935669366693766938669396694066941669426694366944669456694666947669486694966950669516695266953669546695566956669576695866959669606696166962669636696466965669666696766968669696697066971669726697366974669756697666977669786697966980669816698266983669846698566986669876698866989669906699166992669936699466995669966699766998669996700067001670026700367004670056700667007670086700967010670116701267013670146701567016670176701867019670206702167022670236702467025670266702767028670296703067031670326703367034670356703667037670386703967040670416704267043670446704567046670476704867049670506705167052670536705467055670566705767058670596706067061670626706367064670656706667067670686706967070670716707267073670746707567076670776707867079670806708167082670836708467085670866708767088670896709067091670926709367094670956709667097670986709967100671016710267103671046710567106671076710867109671106711167112671136711467115671166711767118671196712067121671226712367124671256712667127671286712967130671316713267133671346713567136671376713867139671406714167142671436714467145671466714767148671496715067151671526715367154671556715667157671586715967160671616716267163671646716567166671676716867169671706717167172671736717467175671766717767178671796718067181671826718367184671856718667187671886718967190671916719267193671946719567196671976719867199672006720167202672036720467205672066720767208672096721067211672126721367214672156721667217672186721967220672216722267223672246722567226672276722867229672306723167232672336723467235672366723767238672396724067241672426724367244672456724667247672486724967250672516725267253672546725567256672576725867259672606726167262672636726467265672666726767268672696727067271672726727367274672756727667277672786727967280672816728267283672846728567286672876728867289672906729167292672936729467295672966729767298672996730067301673026730367304673056730667307673086730967310673116731267313673146731567316673176731867319673206732167322673236732467325673266732767328673296733067331673326733367334673356733667337673386733967340673416734267343673446734567346673476734867349673506735167352673536735467355673566735767358673596736067361673626736367364673656736667367673686736967370673716737267373673746737567376673776737867379673806738167382673836738467385673866738767388673896739067391673926739367394673956739667397673986739967400674016740267403674046740567406674076740867409674106741167412674136741467415674166741767418674196742067421674226742367424674256742667427674286742967430674316743267433674346743567436674376743867439674406744167442674436744467445674466744767448674496745067451674526745367454674556745667457674586745967460674616746267463674646746567466674676746867469674706747167472674736747467475674766747767478674796748067481674826748367484674856748667487674886748967490674916749267493674946749567496674976749867499675006750167502675036750467505675066750767508675096751067511675126751367514675156751667517675186751967520675216752267523675246752567526675276752867529675306753167532675336753467535675366753767538675396754067541675426754367544675456754667547675486754967550675516755267553675546755567556675576755867559675606756167562675636756467565675666756767568675696757067571675726757367574675756757667577675786757967580675816758267583675846758567586675876758867589675906759167592675936759467595675966759767598675996760067601676026760367604676056760667607676086760967610676116761267613676146761567616676176761867619676206762167622676236762467625676266762767628676296763067631676326763367634676356763667637676386763967640676416764267643676446764567646676476764867649676506765167652676536765467655676566765767658676596766067661676626766367664676656766667667676686766967670676716767267673676746767567676676776767867679676806768167682676836768467685676866768767688676896769067691676926769367694676956769667697676986769967700677016770267703677046770567706677076770867709677106771167712677136771467715677166771767718677196772067721677226772367724677256772667727677286772967730677316773267733677346773567736677376773867739677406774167742677436774467745677466774767748677496775067751677526775367754677556775667757677586775967760677616776267763677646776567766677676776867769677706777167772677736777467775677766777767778677796778067781677826778367784677856778667787677886778967790677916779267793677946779567796677976779867799678006780167802678036780467805678066780767808678096781067811678126781367814678156781667817678186781967820678216782267823678246782567826678276782867829678306783167832678336783467835678366783767838678396784067841678426784367844678456784667847678486784967850678516785267853678546785567856678576785867859678606786167862678636786467865678666786767868678696787067871678726787367874678756787667877678786787967880678816788267883678846788567886678876788867889678906789167892678936789467895678966789767898678996790067901679026790367904679056790667907679086790967910679116791267913679146791567916679176791867919679206792167922679236792467925679266792767928679296793067931679326793367934679356793667937679386793967940679416794267943679446794567946679476794867949679506795167952679536795467955679566795767958679596796067961679626796367964679656796667967679686796967970679716797267973679746797567976679776797867979679806798167982679836798467985679866798767988679896799067991679926799367994679956799667997679986799968000680016800268003680046800568006680076800868009680106801168012680136801468015680166801768018680196802068021680226802368024680256802668027680286802968030680316803268033680346803568036680376803868039680406804168042680436804468045680466804768048680496805068051680526805368054680556805668057680586805968060680616806268063680646806568066680676806868069680706807168072680736807468075680766807768078680796808068081680826808368084680856808668087680886808968090680916809268093680946809568096680976809868099681006810168102681036810468105681066810768108681096811068111681126811368114681156811668117681186811968120681216812268123681246812568126681276812868129681306813168132681336813468135681366813768138681396814068141681426814368144681456814668147681486814968150681516815268153681546815568156681576815868159681606816168162681636816468165681666816768168681696817068171681726817368174681756817668177681786817968180681816818268183681846818568186681876818868189681906819168192681936819468195681966819768198681996820068201682026820368204682056820668207682086820968210682116821268213682146821568216682176821868219682206822168222682236822468225682266822768228682296823068231682326823368234682356823668237682386823968240682416824268243682446824568246682476824868249682506825168252682536825468255682566825768258682596826068261682626826368264682656826668267682686826968270682716827268273682746827568276682776827868279682806828168282682836828468285682866828768288682896829068291682926829368294682956829668297682986829968300683016830268303683046830568306683076830868309683106831168312683136831468315683166831768318683196832068321683226832368324683256832668327683286832968330683316833268333683346833568336683376833868339683406834168342683436834468345683466834768348683496835068351683526835368354683556835668357683586835968360683616836268363683646836568366683676836868369683706837168372683736837468375683766837768378683796838068381683826838368384683856838668387683886838968390683916839268393683946839568396683976839868399684006840168402684036840468405684066840768408684096841068411684126841368414684156841668417684186841968420684216842268423684246842568426684276842868429684306843168432684336843468435684366843768438684396844068441684426844368444684456844668447684486844968450684516845268453684546845568456684576845868459684606846168462684636846468465684666846768468684696847068471684726847368474684756847668477684786847968480684816848268483684846848568486684876848868489684906849168492684936849468495684966849768498684996850068501685026850368504685056850668507685086850968510685116851268513685146851568516685176851868519685206852168522685236852468525685266852768528685296853068531685326853368534685356853668537685386853968540685416854268543685446854568546685476854868549685506855168552685536855468555685566855768558685596856068561685626856368564685656856668567685686856968570685716857268573685746857568576685776857868579685806858168582685836858468585685866858768588685896859068591685926859368594685956859668597685986859968600686016860268603686046860568606686076860868609686106861168612686136861468615686166861768618686196862068621686226862368624686256862668627686286862968630686316863268633686346863568636686376863868639686406864168642686436864468645686466864768648686496865068651686526865368654686556865668657686586865968660686616866268663686646866568666686676866868669686706867168672686736867468675686766867768678686796868068681686826868368684686856868668687686886868968690686916869268693686946869568696686976869868699687006870168702687036870468705687066870768708687096871068711687126871368714687156871668717687186871968720687216872268723687246872568726687276872868729687306873168732687336873468735687366873768738687396874068741687426874368744687456874668747687486874968750687516875268753687546875568756687576875868759687606876168762687636876468765687666876768768687696877068771687726877368774687756877668777687786877968780687816878268783687846878568786687876878868789687906879168792687936879468795687966879768798687996880068801688026880368804688056880668807688086880968810688116881268813688146881568816688176881868819688206882168822688236882468825688266882768828688296883068831688326883368834688356883668837688386883968840688416884268843688446884568846688476884868849688506885168852688536885468855688566885768858688596886068861688626886368864688656886668867688686886968870688716887268873688746887568876688776887868879688806888168882688836888468885688866888768888688896889068891688926889368894688956889668897688986889968900689016890268903689046890568906689076890868909689106891168912689136891468915689166891768918689196892068921689226892368924689256892668927689286892968930689316893268933689346893568936689376893868939689406894168942689436894468945689466894768948689496895068951689526895368954689556895668957689586895968960689616896268963689646896568966689676896868969689706897168972689736897468975689766897768978689796898068981689826898368984689856898668987689886898968990689916899268993689946899568996689976899868999690006900169002690036900469005690066900769008690096901069011690126901369014690156901669017690186901969020690216902269023690246902569026690276902869029690306903169032690336903469035690366903769038690396904069041690426904369044690456904669047690486904969050690516905269053690546905569056690576905869059690606906169062690636906469065690666906769068690696907069071690726907369074690756907669077690786907969080690816908269083690846908569086690876908869089690906909169092690936909469095690966909769098690996910069101691026910369104691056910669107691086910969110691116911269113691146911569116691176911869119691206912169122691236912469125691266912769128691296913069131691326913369134691356913669137691386913969140691416914269143691446914569146691476914869149691506915169152691536915469155691566915769158691596916069161691626916369164691656916669167691686916969170691716917269173691746917569176691776917869179691806918169182691836918469185691866918769188691896919069191691926919369194691956919669197691986919969200692016920269203692046920569206692076920869209692106921169212692136921469215692166921769218692196922069221692226922369224692256922669227692286922969230692316923269233692346923569236692376923869239692406924169242692436924469245692466924769248692496925069251692526925369254692556925669257692586925969260692616926269263692646926569266692676926869269692706927169272692736927469275692766927769278692796928069281692826928369284692856928669287692886928969290692916929269293692946929569296692976929869299693006930169302693036930469305693066930769308693096931069311693126931369314693156931669317693186931969320693216932269323693246932569326693276932869329693306933169332693336933469335693366933769338693396934069341693426934369344693456934669347693486934969350693516935269353693546935569356693576935869359693606936169362693636936469365693666936769368693696937069371693726937369374693756937669377693786937969380693816938269383693846938569386693876938869389693906939169392693936939469395693966939769398693996940069401694026940369404694056940669407694086940969410694116941269413694146941569416694176941869419694206942169422694236942469425694266942769428694296943069431694326943369434694356943669437694386943969440694416944269443694446944569446694476944869449694506945169452694536945469455694566945769458694596946069461694626946369464694656946669467694686946969470694716947269473694746947569476694776947869479694806948169482694836948469485694866948769488694896949069491694926949369494694956949669497694986949969500695016950269503695046950569506695076950869509695106951169512695136951469515695166951769518695196952069521695226952369524695256952669527695286952969530695316953269533695346953569536695376953869539695406954169542695436954469545695466954769548695496955069551695526955369554695556955669557695586955969560695616956269563695646956569566695676956869569695706957169572695736957469575695766957769578695796958069581695826958369584695856958669587695886958969590695916959269593695946959569596695976959869599696006960169602696036960469605696066960769608696096961069611696126961369614696156961669617696186961969620696216962269623696246962569626696276962869629696306963169632696336963469635696366963769638696396964069641696426964369644696456964669647696486964969650696516965269653696546965569656696576965869659696606966169662696636966469665696666966769668696696967069671696726967369674696756967669677696786967969680696816968269683696846968569686696876968869689696906969169692696936969469695696966969769698696996970069701697026970369704697056970669707697086970969710697116971269713697146971569716697176971869719697206972169722697236972469725697266972769728697296973069731697326973369734697356973669737697386973969740697416974269743697446974569746697476974869749697506975169752697536975469755697566975769758697596976069761697626976369764697656976669767697686976969770697716977269773697746977569776697776977869779697806978169782697836978469785697866978769788697896979069791697926979369794697956979669797697986979969800698016980269803698046980569806698076980869809698106981169812698136981469815698166981769818698196982069821698226982369824698256982669827698286982969830698316983269833698346983569836698376983869839698406984169842698436984469845698466984769848698496985069851698526985369854698556985669857698586985969860698616986269863698646986569866698676986869869698706987169872698736987469875698766987769878698796988069881698826988369884698856988669887698886988969890698916989269893698946989569896698976989869899699006990169902699036990469905699066990769908699096991069911699126991369914699156991669917699186991969920699216992269923699246992569926699276992869929699306993169932699336993469935699366993769938699396994069941699426994369944699456994669947699486994969950699516995269953699546995569956699576995869959699606996169962699636996469965699666996769968699696997069971699726997369974699756997669977699786997969980699816998269983699846998569986699876998869989699906999169992699936999469995699966999769998699997000070001700027000370004700057000670007700087000970010700117001270013700147001570016700177001870019700207002170022700237002470025700267002770028700297003070031700327003370034700357003670037700387003970040700417004270043700447004570046700477004870049700507005170052700537005470055700567005770058700597006070061700627006370064700657006670067700687006970070700717007270073700747007570076700777007870079700807008170082700837008470085700867008770088700897009070091700927009370094700957009670097700987009970100701017010270103701047010570106701077010870109701107011170112701137011470115701167011770118701197012070121701227012370124701257012670127701287012970130701317013270133701347013570136701377013870139701407014170142701437014470145701467014770148701497015070151701527015370154701557015670157701587015970160701617016270163701647016570166701677016870169701707017170172701737017470175701767017770178701797018070181701827018370184701857018670187701887018970190701917019270193701947019570196701977019870199702007020170202702037020470205702067020770208702097021070211702127021370214702157021670217702187021970220702217022270223702247022570226702277022870229702307023170232702337023470235702367023770238702397024070241702427024370244702457024670247702487024970250702517025270253702547025570256702577025870259702607026170262702637026470265702667026770268702697027070271702727027370274702757027670277702787027970280702817028270283702847028570286702877028870289702907029170292702937029470295702967029770298702997030070301703027030370304703057030670307703087030970310703117031270313703147031570316703177031870319703207032170322703237032470325703267032770328703297033070331703327033370334703357033670337703387033970340703417034270343703447034570346703477034870349703507035170352703537035470355703567035770358703597036070361703627036370364703657036670367703687036970370703717037270373703747037570376703777037870379703807038170382703837038470385703867038770388703897039070391703927039370394703957039670397703987039970400704017040270403704047040570406704077040870409704107041170412704137041470415704167041770418704197042070421704227042370424704257042670427704287042970430704317043270433704347043570436704377043870439704407044170442704437044470445704467044770448704497045070451704527045370454704557045670457704587045970460704617046270463704647046570466704677046870469704707047170472704737047470475704767047770478704797048070481704827048370484704857048670487704887048970490704917049270493704947049570496704977049870499705007050170502705037050470505705067050770508705097051070511705127051370514705157051670517705187051970520705217052270523705247052570526705277052870529705307053170532705337053470535705367053770538705397054070541705427054370544705457054670547705487054970550705517055270553705547055570556705577055870559705607056170562705637056470565705667056770568705697057070571705727057370574705757057670577705787057970580705817058270583705847058570586705877058870589705907059170592705937059470595705967059770598705997060070601706027060370604706057060670607706087060970610706117061270613706147061570616706177061870619706207062170622706237062470625706267062770628706297063070631706327063370634706357063670637706387063970640706417064270643706447064570646706477064870649706507065170652706537065470655706567065770658706597066070661706627066370664706657066670667706687066970670706717067270673706747067570676706777067870679706807068170682706837068470685706867068770688706897069070691706927069370694706957069670697706987069970700707017070270703707047070570706707077070870709707107071170712707137071470715707167071770718707197072070721707227072370724707257072670727707287072970730707317073270733707347073570736707377073870739707407074170742707437074470745707467074770748707497075070751707527075370754707557075670757707587075970760707617076270763707647076570766707677076870769707707077170772707737077470775707767077770778707797078070781707827078370784707857078670787707887078970790707917079270793707947079570796707977079870799708007080170802708037080470805708067080770808708097081070811708127081370814708157081670817708187081970820708217082270823708247082570826708277082870829708307083170832708337083470835708367083770838708397084070841708427084370844708457084670847708487084970850708517085270853708547085570856708577085870859708607086170862708637086470865708667086770868708697087070871708727087370874708757087670877708787087970880708817088270883708847088570886708877088870889708907089170892708937089470895708967089770898708997090070901709027090370904709057090670907709087090970910709117091270913709147091570916709177091870919709207092170922709237092470925709267092770928709297093070931709327093370934709357093670937709387093970940709417094270943709447094570946709477094870949709507095170952709537095470955709567095770958709597096070961709627096370964709657096670967709687096970970709717097270973709747097570976709777097870979709807098170982709837098470985709867098770988709897099070991709927099370994709957099670997709987099971000710017100271003710047100571006710077100871009710107101171012710137101471015710167101771018710197102071021710227102371024710257102671027710287102971030710317103271033710347103571036710377103871039710407104171042710437104471045710467104771048710497105071051710527105371054710557105671057710587105971060710617106271063710647106571066710677106871069710707107171072710737107471075710767107771078710797108071081710827108371084710857108671087710887108971090710917109271093710947109571096710977109871099711007110171102711037110471105711067110771108711097111071111711127111371114711157111671117711187111971120711217112271123711247112571126711277112871129711307113171132711337113471135711367113771138711397114071141711427114371144711457114671147711487114971150711517115271153711547115571156711577115871159711607116171162711637116471165711667116771168711697117071171711727117371174711757117671177711787117971180711817118271183711847118571186711877118871189711907119171192711937119471195711967119771198711997120071201712027120371204712057120671207712087120971210712117121271213712147121571216712177121871219712207122171222712237122471225712267122771228712297123071231712327123371234712357123671237712387123971240712417124271243712447124571246712477124871249712507125171252712537125471255712567125771258712597126071261712627126371264712657126671267712687126971270712717127271273712747127571276712777127871279712807128171282712837128471285712867128771288712897129071291712927129371294712957129671297712987129971300713017130271303713047130571306713077130871309713107131171312713137131471315713167131771318713197132071321713227132371324713257132671327713287132971330713317133271333713347133571336713377133871339713407134171342713437134471345713467134771348713497135071351713527135371354713557135671357713587135971360713617136271363713647136571366713677136871369713707137171372713737137471375713767137771378713797138071381713827138371384713857138671387713887138971390713917139271393713947139571396713977139871399714007140171402714037140471405714067140771408714097141071411714127141371414714157141671417714187141971420714217142271423714247142571426714277142871429714307143171432714337143471435714367143771438714397144071441714427144371444714457144671447714487144971450714517145271453714547145571456714577145871459714607146171462714637146471465714667146771468714697147071471714727147371474714757147671477714787147971480714817148271483714847148571486714877148871489714907149171492714937149471495714967149771498714997150071501715027150371504715057150671507715087150971510715117151271513715147151571516715177151871519715207152171522715237152471525715267152771528715297153071531715327153371534715357153671537715387153971540715417154271543715447154571546715477154871549715507155171552715537155471555715567155771558715597156071561715627156371564715657156671567715687156971570715717157271573715747157571576715777157871579715807158171582715837158471585715867158771588715897159071591715927159371594715957159671597715987159971600716017160271603716047160571606716077160871609716107161171612716137161471615716167161771618716197162071621716227162371624716257162671627716287162971630716317163271633716347163571636716377163871639716407164171642716437164471645716467164771648716497165071651716527165371654716557165671657716587165971660716617166271663716647166571666716677166871669716707167171672716737167471675716767167771678716797168071681716827168371684716857168671687716887168971690716917169271693716947169571696716977169871699717007170171702717037170471705717067170771708717097171071711717127171371714717157171671717717187171971720717217172271723717247172571726717277172871729717307173171732717337173471735717367173771738717397174071741717427174371744717457174671747717487174971750717517175271753717547175571756717577175871759717607176171762717637176471765717667176771768717697177071771717727177371774717757177671777717787177971780717817178271783717847178571786717877178871789717907179171792717937179471795717967179771798717997180071801718027180371804718057180671807718087180971810718117181271813718147181571816718177181871819718207182171822718237182471825718267182771828718297183071831718327183371834718357183671837718387183971840718417184271843718447184571846718477184871849718507185171852718537185471855718567185771858718597186071861718627186371864718657186671867718687186971870718717187271873718747187571876718777187871879718807188171882718837188471885718867188771888718897189071891718927189371894718957189671897718987189971900719017190271903719047190571906719077190871909719107191171912719137191471915719167191771918719197192071921719227192371924719257192671927719287192971930719317193271933719347193571936719377193871939719407194171942719437194471945719467194771948719497195071951719527195371954719557195671957719587195971960719617196271963719647196571966719677196871969719707197171972719737197471975719767197771978719797198071981719827198371984719857198671987719887198971990719917199271993719947199571996719977199871999720007200172002720037200472005720067200772008720097201072011720127201372014720157201672017720187201972020720217202272023720247202572026720277202872029720307203172032720337203472035720367203772038720397204072041720427204372044720457204672047720487204972050720517205272053720547205572056720577205872059720607206172062720637206472065720667206772068720697207072071720727207372074720757207672077720787207972080720817208272083720847208572086720877208872089720907209172092720937209472095720967209772098720997210072101721027210372104721057210672107721087210972110721117211272113721147211572116721177211872119721207212172122721237212472125721267212772128721297213072131721327213372134721357213672137721387213972140721417214272143721447214572146721477214872149721507215172152721537215472155721567215772158721597216072161721627216372164721657216672167721687216972170721717217272173721747217572176721777217872179721807218172182721837218472185721867218772188721897219072191721927219372194721957219672197721987219972200722017220272203722047220572206722077220872209722107221172212722137221472215722167221772218722197222072221722227222372224722257222672227722287222972230722317223272233722347223572236722377223872239722407224172242722437224472245722467224772248722497225072251722527225372254722557225672257722587225972260722617226272263722647226572266722677226872269722707227172272722737227472275722767227772278722797228072281722827228372284722857228672287722887228972290722917229272293722947229572296722977229872299723007230172302723037230472305723067230772308723097231072311723127231372314723157231672317723187231972320723217232272323723247232572326723277232872329723307233172332723337233472335723367233772338723397234072341723427234372344723457234672347723487234972350723517235272353723547235572356723577235872359723607236172362723637236472365723667236772368723697237072371723727237372374723757237672377723787237972380723817238272383723847238572386723877238872389723907239172392723937239472395723967239772398723997240072401724027240372404724057240672407724087240972410724117241272413724147241572416724177241872419724207242172422724237242472425724267242772428724297243072431724327243372434724357243672437724387243972440724417244272443724447244572446724477244872449724507245172452724537245472455724567245772458724597246072461724627246372464724657246672467724687246972470724717247272473724747247572476724777247872479724807248172482724837248472485724867248772488724897249072491724927249372494724957249672497724987249972500725017250272503725047250572506725077250872509725107251172512725137251472515725167251772518725197252072521725227252372524725257252672527725287252972530725317253272533725347253572536725377253872539725407254172542725437254472545725467254772548725497255072551725527255372554725557255672557725587255972560725617256272563725647256572566725677256872569725707257172572725737257472575725767257772578725797258072581725827258372584725857258672587725887258972590725917259272593725947259572596725977259872599726007260172602726037260472605726067260772608726097261072611726127261372614726157261672617726187261972620726217262272623726247262572626726277262872629726307263172632726337263472635726367263772638726397264072641726427264372644726457264672647726487264972650726517265272653726547265572656726577265872659726607266172662726637266472665726667266772668726697267072671726727267372674726757267672677726787267972680726817268272683726847268572686726877268872689726907269172692726937269472695726967269772698726997270072701727027270372704727057270672707727087270972710727117271272713727147271572716727177271872719727207272172722727237272472725727267272772728727297273072731727327273372734727357273672737727387273972740727417274272743727447274572746727477274872749727507275172752727537275472755727567275772758727597276072761727627276372764727657276672767727687276972770727717277272773727747277572776727777277872779727807278172782727837278472785727867278772788727897279072791727927279372794727957279672797727987279972800728017280272803728047280572806728077280872809728107281172812728137281472815728167281772818728197282072821728227282372824728257282672827728287282972830728317283272833728347283572836728377283872839728407284172842728437284472845728467284772848728497285072851728527285372854728557285672857728587285972860728617286272863728647286572866728677286872869728707287172872728737287472875728767287772878728797288072881728827288372884728857288672887728887288972890728917289272893728947289572896728977289872899729007290172902729037290472905729067290772908729097291072911729127291372914729157291672917729187291972920729217292272923729247292572926729277292872929729307293172932729337293472935729367293772938729397294072941729427294372944729457294672947729487294972950729517295272953729547295572956729577295872959729607296172962729637296472965729667296772968729697297072971729727297372974729757297672977729787297972980729817298272983729847298572986729877298872989729907299172992729937299472995729967299772998729997300073001730027300373004730057300673007730087300973010730117301273013730147301573016730177301873019730207302173022730237302473025730267302773028730297303073031730327303373034730357303673037730387303973040730417304273043730447304573046730477304873049730507305173052730537305473055730567305773058730597306073061730627306373064730657306673067730687306973070730717307273073730747307573076730777307873079730807308173082730837308473085730867308773088730897309073091730927309373094730957309673097730987309973100731017310273103731047310573106731077310873109731107311173112731137311473115731167311773118731197312073121731227312373124731257312673127731287312973130731317313273133731347313573136731377313873139731407314173142731437314473145731467314773148731497315073151731527315373154731557315673157731587315973160731617316273163731647316573166731677316873169731707317173172731737317473175731767317773178731797318073181731827318373184731857318673187731887318973190731917319273193731947319573196731977319873199732007320173202732037320473205732067320773208732097321073211732127321373214732157321673217732187321973220732217322273223732247322573226732277322873229732307323173232732337323473235732367323773238732397324073241732427324373244732457324673247732487324973250732517325273253732547325573256732577325873259732607326173262732637326473265732667326773268732697327073271732727327373274732757327673277732787327973280732817328273283732847328573286732877328873289732907329173292732937329473295732967329773298732997330073301733027330373304733057330673307733087330973310733117331273313733147331573316733177331873319733207332173322733237332473325733267332773328733297333073331733327333373334733357333673337733387333973340733417334273343733447334573346733477334873349733507335173352733537335473355733567335773358733597336073361733627336373364733657336673367733687336973370733717337273373733747337573376733777337873379733807338173382733837338473385733867338773388733897339073391733927339373394733957339673397733987339973400734017340273403734047340573406734077340873409734107341173412734137341473415734167341773418734197342073421734227342373424734257342673427734287342973430734317343273433734347343573436734377343873439734407344173442734437344473445734467344773448734497345073451734527345373454734557345673457734587345973460734617346273463734647346573466734677346873469734707347173472734737347473475734767347773478734797348073481734827348373484734857348673487734887348973490734917349273493734947349573496734977349873499735007350173502735037350473505735067350773508735097351073511735127351373514735157351673517735187351973520735217352273523735247352573526735277352873529735307353173532735337353473535735367353773538735397354073541735427354373544735457354673547735487354973550735517355273553735547355573556735577355873559735607356173562735637356473565735667356773568735697357073571735727357373574735757357673577735787357973580735817358273583735847358573586735877358873589735907359173592735937359473595735967359773598735997360073601736027360373604736057360673607736087360973610736117361273613736147361573616736177361873619736207362173622736237362473625736267362773628736297363073631736327363373634736357363673637736387363973640736417364273643736447364573646736477364873649736507365173652736537365473655736567365773658736597366073661736627366373664736657366673667736687366973670736717367273673736747367573676736777367873679736807368173682736837368473685736867368773688736897369073691736927369373694736957369673697736987369973700737017370273703737047370573706737077370873709737107371173712737137371473715737167371773718737197372073721737227372373724737257372673727737287372973730737317373273733737347373573736737377373873739737407374173742737437374473745737467374773748737497375073751737527375373754737557375673757737587375973760737617376273763737647376573766737677376873769737707377173772737737377473775737767377773778737797378073781737827378373784737857378673787737887378973790737917379273793737947379573796737977379873799738007380173802738037380473805738067380773808738097381073811738127381373814738157381673817738187381973820738217382273823738247382573826738277382873829738307383173832738337383473835738367383773838738397384073841738427384373844738457384673847738487384973850738517385273853738547385573856738577385873859738607386173862738637386473865738667386773868738697387073871738727387373874738757387673877738787387973880738817388273883738847388573886738877388873889738907389173892738937389473895738967389773898738997390073901739027390373904739057390673907739087390973910739117391273913739147391573916739177391873919739207392173922739237392473925739267392773928739297393073931739327393373934739357393673937739387393973940739417394273943739447394573946739477394873949739507395173952739537395473955739567395773958739597396073961739627396373964739657396673967739687396973970739717397273973739747397573976739777397873979739807398173982739837398473985739867398773988739897399073991739927399373994739957399673997739987399974000740017400274003740047400574006740077400874009740107401174012740137401474015740167401774018740197402074021740227402374024740257402674027740287402974030740317403274033740347403574036740377403874039740407404174042740437404474045740467404774048740497405074051740527405374054740557405674057740587405974060740617406274063740647406574066740677406874069740707407174072740737407474075740767407774078740797408074081740827408374084740857408674087740887408974090740917409274093740947409574096740977409874099741007410174102741037410474105741067410774108741097411074111741127411374114741157411674117741187411974120741217412274123741247412574126741277412874129741307413174132741337413474135741367413774138741397414074141741427414374144741457414674147741487414974150741517415274153741547415574156741577415874159741607416174162741637416474165741667416774168741697417074171741727417374174741757417674177741787417974180741817418274183741847418574186741877418874189741907419174192741937419474195741967419774198741997420074201742027420374204742057420674207742087420974210742117421274213742147421574216742177421874219742207422174222742237422474225742267422774228742297423074231742327423374234742357423674237742387423974240742417424274243742447424574246742477424874249742507425174252742537425474255742567425774258742597426074261742627426374264742657426674267742687426974270742717427274273742747427574276742777427874279742807428174282742837428474285742867428774288742897429074291742927429374294742957429674297742987429974300743017430274303743047430574306743077430874309743107431174312743137431474315743167431774318743197432074321743227432374324743257432674327743287432974330743317433274333743347433574336743377433874339743407434174342743437434474345743467434774348743497435074351743527435374354743557435674357743587435974360743617436274363743647436574366743677436874369743707437174372743737437474375743767437774378743797438074381743827438374384743857438674387743887438974390743917439274393743947439574396743977439874399744007440174402744037440474405744067440774408744097441074411744127441374414744157441674417744187441974420744217442274423744247442574426744277442874429744307443174432744337443474435744367443774438744397444074441744427444374444744457444674447744487444974450744517445274453744547445574456744577445874459744607446174462744637446474465744667446774468744697447074471744727447374474744757447674477744787447974480744817448274483744847448574486744877448874489744907449174492744937449474495744967449774498744997450074501745027450374504745057450674507745087450974510745117451274513745147451574516745177451874519745207452174522745237452474525745267452774528745297453074531745327453374534745357453674537745387453974540745417454274543745447454574546745477454874549745507455174552745537455474555745567455774558745597456074561745627456374564745657456674567745687456974570745717457274573745747457574576745777457874579745807458174582745837458474585745867458774588745897459074591745927459374594745957459674597745987459974600746017460274603746047460574606746077460874609746107461174612746137461474615746167461774618746197462074621746227462374624746257462674627746287462974630746317463274633746347463574636746377463874639746407464174642746437464474645746467464774648746497465074651746527465374654746557465674657746587465974660746617466274663746647466574666746677466874669746707467174672746737467474675746767467774678746797468074681746827468374684746857468674687746887468974690746917469274693746947469574696746977469874699747007470174702747037470474705747067470774708747097471074711747127471374714747157471674717747187471974720747217472274723747247472574726747277472874729747307473174732747337473474735747367473774738747397474074741747427474374744747457474674747747487474974750747517475274753747547475574756747577475874759747607476174762747637476474765747667476774768747697477074771747727477374774747757477674777747787477974780747817478274783747847478574786747877478874789747907479174792747937479474795747967479774798747997480074801748027480374804748057480674807748087480974810748117481274813748147481574816748177481874819748207482174822748237482474825748267482774828748297483074831748327483374834748357483674837748387483974840748417484274843748447484574846748477484874849748507485174852748537485474855748567485774858748597486074861748627486374864748657486674867748687486974870748717487274873748747487574876748777487874879748807488174882748837488474885748867488774888748897489074891748927489374894748957489674897748987489974900749017490274903749047490574906749077490874909749107491174912749137491474915749167491774918749197492074921749227492374924749257492674927749287492974930749317493274933749347493574936749377493874939749407494174942749437494474945749467494774948749497495074951749527495374954749557495674957749587495974960749617496274963749647496574966749677496874969749707497174972749737497474975749767497774978749797498074981749827498374984749857498674987749887498974990749917499274993749947499574996749977499874999750007500175002750037500475005750067500775008750097501075011750127501375014750157501675017750187501975020750217502275023750247502575026750277502875029750307503175032750337503475035750367503775038750397504075041750427504375044750457504675047750487504975050750517505275053750547505575056750577505875059750607506175062750637506475065750667506775068750697507075071750727507375074750757507675077750787507975080750817508275083750847508575086750877508875089750907509175092750937509475095750967509775098750997510075101751027510375104751057510675107751087510975110751117511275113751147511575116751177511875119751207512175122751237512475125751267512775128751297513075131751327513375134751357513675137751387513975140751417514275143751447514575146751477514875149751507515175152751537515475155751567515775158751597516075161751627516375164751657516675167751687516975170751717517275173751747517575176751777517875179751807518175182751837518475185751867518775188751897519075191751927519375194751957519675197751987519975200752017520275203752047520575206752077520875209752107521175212752137521475215752167521775218752197522075221752227522375224752257522675227752287522975230752317523275233752347523575236752377523875239752407524175242752437524475245752467524775248752497525075251752527525375254752557525675257752587525975260752617526275263752647526575266752677526875269752707527175272752737527475275752767527775278752797528075281752827528375284752857528675287752887528975290752917529275293752947529575296752977529875299753007530175302753037530475305753067530775308753097531075311753127531375314753157531675317753187531975320753217532275323753247532575326753277532875329753307533175332753337533475335753367533775338753397534075341753427534375344753457534675347753487534975350753517535275353753547535575356753577535875359753607536175362753637536475365753667536775368753697537075371753727537375374753757537675377753787537975380753817538275383753847538575386753877538875389753907539175392753937539475395753967539775398753997540075401754027540375404754057540675407754087540975410754117541275413754147541575416754177541875419754207542175422754237542475425754267542775428754297543075431754327543375434754357543675437754387543975440754417544275443754447544575446754477544875449754507545175452754537545475455754567545775458754597546075461754627546375464754657546675467754687546975470754717547275473754747547575476754777547875479754807548175482754837548475485754867548775488754897549075491754927549375494754957549675497754987549975500755017550275503755047550575506755077550875509755107551175512755137551475515755167551775518755197552075521755227552375524755257552675527755287552975530755317553275533755347553575536755377553875539755407554175542755437554475545755467554775548755497555075551755527555375554755557555675557755587555975560755617556275563755647556575566755677556875569755707557175572755737557475575755767557775578755797558075581755827558375584755857558675587755887558975590755917559275593755947559575596755977559875599756007560175602756037560475605756067560775608756097561075611756127561375614756157561675617756187561975620756217562275623756247562575626756277562875629756307563175632756337563475635756367563775638756397564075641756427564375644756457564675647756487564975650756517565275653756547565575656756577565875659756607566175662756637566475665756667566775668756697567075671756727567375674756757567675677756787567975680756817568275683756847568575686756877568875689756907569175692756937569475695756967569775698756997570075701757027570375704757057570675707757087570975710757117571275713757147571575716757177571875719757207572175722757237572475725757267572775728757297573075731757327573375734757357573675737757387573975740757417574275743757447574575746757477574875749757507575175752757537575475755757567575775758757597576075761757627576375764757657576675767757687576975770757717577275773757747577575776757777577875779757807578175782757837578475785757867578775788757897579075791757927579375794757957579675797757987579975800758017580275803758047580575806758077580875809758107581175812758137581475815758167581775818758197582075821758227582375824758257582675827758287582975830758317583275833758347583575836758377583875839758407584175842758437584475845758467584775848758497585075851758527585375854758557585675857758587585975860758617586275863758647586575866758677586875869758707587175872758737587475875758767587775878758797588075881758827588375884758857588675887758887588975890758917589275893758947589575896758977589875899759007590175902759037590475905759067590775908759097591075911759127591375914759157591675917759187591975920759217592275923759247592575926759277592875929759307593175932759337593475935759367593775938759397594075941759427594375944759457594675947759487594975950759517595275953759547595575956759577595875959759607596175962759637596475965759667596775968759697597075971759727597375974759757597675977759787597975980759817598275983759847598575986759877598875989759907599175992759937599475995759967599775998759997600076001760027600376004760057600676007760087600976010760117601276013760147601576016760177601876019760207602176022760237602476025760267602776028760297603076031760327603376034760357603676037760387603976040760417604276043760447604576046760477604876049760507605176052760537605476055760567605776058760597606076061760627606376064760657606676067760687606976070760717607276073760747607576076760777607876079760807608176082760837608476085760867608776088760897609076091760927609376094760957609676097760987609976100761017610276103761047610576106761077610876109761107611176112761137611476115761167611776118761197612076121761227612376124761257612676127761287612976130761317613276133761347613576136761377613876139761407614176142761437614476145761467614776148761497615076151761527615376154761557615676157761587615976160761617616276163761647616576166761677616876169761707617176172761737617476175761767617776178761797618076181761827618376184761857618676187761887618976190761917619276193761947619576196761977619876199762007620176202762037620476205762067620776208762097621076211762127621376214762157621676217762187621976220762217622276223762247622576226762277622876229762307623176232762337623476235762367623776238762397624076241762427624376244762457624676247762487624976250762517625276253762547625576256762577625876259762607626176262762637626476265762667626776268762697627076271762727627376274762757627676277762787627976280762817628276283762847628576286762877628876289762907629176292762937629476295762967629776298762997630076301763027630376304763057630676307763087630976310763117631276313763147631576316763177631876319763207632176322763237632476325763267632776328763297633076331763327633376334763357633676337763387633976340763417634276343763447634576346763477634876349763507635176352763537635476355763567635776358763597636076361763627636376364763657636676367763687636976370763717637276373763747637576376763777637876379763807638176382763837638476385763867638776388763897639076391763927639376394763957639676397763987639976400764017640276403764047640576406764077640876409764107641176412764137641476415764167641776418764197642076421764227642376424764257642676427764287642976430764317643276433764347643576436764377643876439764407644176442764437644476445764467644776448764497645076451764527645376454764557645676457764587645976460764617646276463764647646576466764677646876469764707647176472764737647476475764767647776478764797648076481764827648376484764857648676487764887648976490764917649276493764947649576496764977649876499765007650176502765037650476505765067650776508765097651076511765127651376514765157651676517765187651976520765217652276523765247652576526765277652876529765307653176532765337653476535765367653776538765397654076541765427654376544765457654676547765487654976550765517655276553765547655576556765577655876559765607656176562765637656476565765667656776568765697657076571765727657376574765757657676577765787657976580765817658276583765847658576586765877658876589765907659176592765937659476595765967659776598765997660076601766027660376604766057660676607766087660976610766117661276613766147661576616766177661876619766207662176622766237662476625766267662776628766297663076631766327663376634766357663676637766387663976640766417664276643766447664576646766477664876649766507665176652766537665476655766567665776658766597666076661766627666376664766657666676667766687666976670766717667276673766747667576676766777667876679766807668176682766837668476685766867668776688766897669076691766927669376694766957669676697766987669976700767017670276703767047670576706767077670876709767107671176712767137671476715767167671776718767197672076721767227672376724767257672676727767287672976730767317673276733767347673576736767377673876739767407674176742767437674476745767467674776748767497675076751767527675376754767557675676757767587675976760767617676276763767647676576766767677676876769767707677176772767737677476775767767677776778767797678076781767827678376784767857678676787767887678976790767917679276793767947679576796767977679876799768007680176802768037680476805768067680776808768097681076811768127681376814768157681676817768187681976820768217682276823768247682576826768277682876829768307683176832768337683476835768367683776838768397684076841768427684376844768457684676847768487684976850768517685276853768547685576856768577685876859768607686176862768637686476865768667686776868768697687076871768727687376874768757687676877768787687976880768817688276883768847688576886768877688876889768907689176892768937689476895768967689776898768997690076901769027690376904769057690676907769087690976910769117691276913769147691576916769177691876919769207692176922769237692476925769267692776928769297693076931769327693376934769357693676937769387693976940769417694276943769447694576946769477694876949769507695176952769537695476955769567695776958769597696076961769627696376964769657696676967769687696976970769717697276973769747697576976769777697876979769807698176982769837698476985769867698776988769897699076991769927699376994769957699676997769987699977000770017700277003770047700577006770077700877009770107701177012770137701477015770167701777018770197702077021770227702377024770257702677027770287702977030770317703277033770347703577036770377703877039770407704177042770437704477045770467704777048770497705077051770527705377054770557705677057770587705977060770617706277063770647706577066770677706877069770707707177072770737707477075770767707777078770797708077081770827708377084770857708677087770887708977090770917709277093770947709577096770977709877099771007710177102771037710477105771067710777108771097711077111771127711377114771157711677117771187711977120771217712277123771247712577126771277712877129771307713177132771337713477135771367713777138771397714077141771427714377144771457714677147771487714977150771517715277153771547715577156771577715877159771607716177162771637716477165771667716777168771697717077171771727717377174771757717677177771787717977180771817718277183771847718577186771877718877189771907719177192771937719477195771967719777198771997720077201772027720377204772057720677207772087720977210772117721277213772147721577216772177721877219772207722177222772237722477225772267722777228772297723077231772327723377234772357723677237772387723977240772417724277243772447724577246772477724877249772507725177252772537725477255772567725777258772597726077261772627726377264772657726677267772687726977270772717727277273772747727577276772777727877279772807728177282772837728477285772867728777288772897729077291772927729377294772957729677297772987729977300773017730277303773047730577306773077730877309773107731177312773137731477315773167731777318773197732077321773227732377324773257732677327773287732977330773317733277333773347733577336773377733877339773407734177342773437734477345773467734777348773497735077351773527735377354773557735677357773587735977360773617736277363773647736577366773677736877369773707737177372773737737477375773767737777378773797738077381773827738377384773857738677387773887738977390773917739277393773947739577396773977739877399774007740177402774037740477405774067740777408774097741077411774127741377414774157741677417774187741977420774217742277423774247742577426774277742877429774307743177432774337743477435774367743777438774397744077441774427744377444774457744677447774487744977450774517745277453774547745577456774577745877459774607746177462774637746477465774667746777468774697747077471774727747377474774757747677477774787747977480774817748277483774847748577486774877748877489774907749177492774937749477495774967749777498774997750077501775027750377504775057750677507775087750977510775117751277513775147751577516775177751877519775207752177522775237752477525775267752777528775297753077531775327753377534775357753677537775387753977540775417754277543775447754577546775477754877549775507755177552775537755477555775567755777558775597756077561775627756377564775657756677567775687756977570775717757277573775747757577576775777757877579775807758177582775837758477585775867758777588775897759077591775927759377594775957759677597775987759977600776017760277603776047760577606776077760877609776107761177612776137761477615776167761777618776197762077621776227762377624776257762677627776287762977630776317763277633776347763577636776377763877639776407764177642776437764477645776467764777648776497765077651776527765377654776557765677657776587765977660776617766277663776647766577666776677766877669776707767177672776737767477675776767767777678776797768077681776827768377684776857768677687776887768977690776917769277693776947769577696776977769877699777007770177702777037770477705777067770777708777097771077711777127771377714777157771677717777187771977720777217772277723777247772577726777277772877729777307773177732777337773477735777367773777738777397774077741777427774377744777457774677747777487774977750777517775277753777547775577756777577775877759777607776177762777637776477765777667776777768777697777077771777727777377774777757777677777777787777977780777817778277783777847778577786777877778877789777907779177792777937779477795777967779777798777997780077801778027780377804778057780677807778087780977810778117781277813778147781577816778177781877819778207782177822778237782477825778267782777828778297783077831778327783377834778357783677837778387783977840778417784277843778447784577846778477784877849778507785177852778537785477855778567785777858778597786077861778627786377864778657786677867778687786977870778717787277873778747787577876778777787877879778807788177882778837788477885
  1. /**
  2. * @license
  3. * Copyright 2010-2024 Three.js Authors
  4. * SPDX-License-Identifier: MIT
  5. */
  6. const REVISION = '170dev';
  7. const MOUSE = { LEFT: 0, MIDDLE: 1, RIGHT: 2, ROTATE: 0, DOLLY: 1, PAN: 2 };
  8. const TOUCH = { ROTATE: 0, PAN: 1, DOLLY_PAN: 2, DOLLY_ROTATE: 3 };
  9. const CullFaceNone = 0;
  10. const CullFaceBack = 1;
  11. const CullFaceFront = 2;
  12. const CullFaceFrontBack = 3;
  13. const BasicShadowMap$1 = 0;
  14. const PCFShadowMap$1 = 1;
  15. const PCFSoftShadowMap$1 = 2;
  16. const VSMShadowMap = 3;
  17. const FrontSide = 0;
  18. const BackSide = 1;
  19. const DoubleSide = 2;
  20. const NoBlending = 0;
  21. const NormalBlending = 1;
  22. const AdditiveBlending = 2;
  23. const SubtractiveBlending = 3;
  24. const MultiplyBlending = 4;
  25. const CustomBlending = 5;
  26. const AddEquation = 100;
  27. const SubtractEquation = 101;
  28. const ReverseSubtractEquation = 102;
  29. const MinEquation = 103;
  30. const MaxEquation = 104;
  31. const ZeroFactor = 200;
  32. const OneFactor = 201;
  33. const SrcColorFactor = 202;
  34. const OneMinusSrcColorFactor = 203;
  35. const SrcAlphaFactor = 204;
  36. const OneMinusSrcAlphaFactor = 205;
  37. const DstAlphaFactor = 206;
  38. const OneMinusDstAlphaFactor = 207;
  39. const DstColorFactor = 208;
  40. const OneMinusDstColorFactor = 209;
  41. const SrcAlphaSaturateFactor = 210;
  42. const ConstantColorFactor = 211;
  43. const OneMinusConstantColorFactor = 212;
  44. const ConstantAlphaFactor = 213;
  45. const OneMinusConstantAlphaFactor = 214;
  46. const NeverDepth = 0;
  47. const AlwaysDepth = 1;
  48. const LessDepth = 2;
  49. const LessEqualDepth = 3;
  50. const EqualDepth = 4;
  51. const GreaterEqualDepth = 5;
  52. const GreaterDepth = 6;
  53. const NotEqualDepth = 7;
  54. const MultiplyOperation = 0;
  55. const MixOperation = 1;
  56. const AddOperation = 2;
  57. const NoToneMapping = 0;
  58. const LinearToneMapping = 1;
  59. const ReinhardToneMapping = 2;
  60. const CineonToneMapping = 3;
  61. const ACESFilmicToneMapping = 4;
  62. const CustomToneMapping = 5;
  63. const AgXToneMapping = 6;
  64. const NeutralToneMapping = 7;
  65. const AttachedBindMode = 'attached';
  66. const DetachedBindMode = 'detached';
  67. const UVMapping = 300;
  68. const CubeReflectionMapping = 301;
  69. const CubeRefractionMapping = 302;
  70. const EquirectangularReflectionMapping = 303;
  71. const EquirectangularRefractionMapping = 304;
  72. const CubeUVReflectionMapping = 306;
  73. const RepeatWrapping = 1000;
  74. const ClampToEdgeWrapping = 1001;
  75. const MirroredRepeatWrapping = 1002;
  76. const NearestFilter = 1003;
  77. const NearestMipmapNearestFilter = 1004;
  78. const NearestMipMapNearestFilter = 1004;
  79. const NearestMipmapLinearFilter = 1005;
  80. const NearestMipMapLinearFilter = 1005;
  81. const LinearFilter = 1006;
  82. const LinearMipmapNearestFilter = 1007;
  83. const LinearMipMapNearestFilter = 1007;
  84. const LinearMipmapLinearFilter = 1008;
  85. const LinearMipMapLinearFilter = 1008;
  86. const UnsignedByteType = 1009;
  87. const ByteType = 1010;
  88. const ShortType = 1011;
  89. const UnsignedShortType = 1012;
  90. const IntType = 1013;
  91. const UnsignedIntType = 1014;
  92. const FloatType = 1015;
  93. const HalfFloatType = 1016;
  94. const UnsignedShort4444Type = 1017;
  95. const UnsignedShort5551Type = 1018;
  96. const UnsignedInt248Type = 1020;
  97. const UnsignedInt5999Type = 35902;
  98. const AlphaFormat = 1021;
  99. const RGBFormat = 1022;
  100. const RGBAFormat = 1023;
  101. const LuminanceFormat = 1024;
  102. const LuminanceAlphaFormat = 1025;
  103. const DepthFormat = 1026;
  104. const DepthStencilFormat = 1027;
  105. const RedFormat = 1028;
  106. const RedIntegerFormat = 1029;
  107. const RGFormat = 1030;
  108. const RGIntegerFormat = 1031;
  109. const RGBIntegerFormat = 1032;
  110. const RGBAIntegerFormat = 1033;
  111. const RGB_S3TC_DXT1_Format = 33776;
  112. const RGBA_S3TC_DXT1_Format = 33777;
  113. const RGBA_S3TC_DXT3_Format = 33778;
  114. const RGBA_S3TC_DXT5_Format = 33779;
  115. const RGB_PVRTC_4BPPV1_Format = 35840;
  116. const RGB_PVRTC_2BPPV1_Format = 35841;
  117. const RGBA_PVRTC_4BPPV1_Format = 35842;
  118. const RGBA_PVRTC_2BPPV1_Format = 35843;
  119. const RGB_ETC1_Format = 36196;
  120. const RGB_ETC2_Format = 37492;
  121. const RGBA_ETC2_EAC_Format = 37496;
  122. const RGBA_ASTC_4x4_Format = 37808;
  123. const RGBA_ASTC_5x4_Format = 37809;
  124. const RGBA_ASTC_5x5_Format = 37810;
  125. const RGBA_ASTC_6x5_Format = 37811;
  126. const RGBA_ASTC_6x6_Format = 37812;
  127. const RGBA_ASTC_8x5_Format = 37813;
  128. const RGBA_ASTC_8x6_Format = 37814;
  129. const RGBA_ASTC_8x8_Format = 37815;
  130. const RGBA_ASTC_10x5_Format = 37816;
  131. const RGBA_ASTC_10x6_Format = 37817;
  132. const RGBA_ASTC_10x8_Format = 37818;
  133. const RGBA_ASTC_10x10_Format = 37819;
  134. const RGBA_ASTC_12x10_Format = 37820;
  135. const RGBA_ASTC_12x12_Format = 37821;
  136. const RGBA_BPTC_Format = 36492;
  137. const RGB_BPTC_SIGNED_Format = 36494;
  138. const RGB_BPTC_UNSIGNED_Format = 36495;
  139. const RED_RGTC1_Format = 36283;
  140. const SIGNED_RED_RGTC1_Format = 36284;
  141. const RED_GREEN_RGTC2_Format = 36285;
  142. const SIGNED_RED_GREEN_RGTC2_Format = 36286;
  143. const LoopOnce = 2200;
  144. const LoopRepeat = 2201;
  145. const LoopPingPong = 2202;
  146. const InterpolateDiscrete = 2300;
  147. const InterpolateLinear = 2301;
  148. const InterpolateSmooth = 2302;
  149. const ZeroCurvatureEnding = 2400;
  150. const ZeroSlopeEnding = 2401;
  151. const WrapAroundEnding = 2402;
  152. const NormalAnimationBlendMode = 2500;
  153. const AdditiveAnimationBlendMode = 2501;
  154. const TrianglesDrawMode = 0;
  155. const TriangleStripDrawMode = 1;
  156. const TriangleFanDrawMode = 2;
  157. const BasicDepthPacking = 3200;
  158. const RGBADepthPacking = 3201;
  159. const RGBDepthPacking = 3202;
  160. const RGDepthPacking = 3203;
  161. const TangentSpaceNormalMap = 0;
  162. const ObjectSpaceNormalMap = 1;
  163. // Color space string identifiers, matching CSS Color Module Level 4 and WebGPU names where available.
  164. const NoColorSpace = '';
  165. const SRGBColorSpace = 'srgb';
  166. const LinearSRGBColorSpace = 'srgb-linear';
  167. const LinearTransfer = 'linear';
  168. const SRGBTransfer = 'srgb';
  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 WebGLCoordinateSystem = 2000;
  205. const WebGPUCoordinateSystem = 2001;
  206. /**
  207. * https://github.com/mrdoob/eventdispatcher.js/
  208. */
  209. class EventDispatcher {
  210. addEventListener( type, listener ) {
  211. if ( this._listeners === undefined ) this._listeners = {};
  212. const listeners = this._listeners;
  213. if ( listeners[ type ] === undefined ) {
  214. listeners[ type ] = [];
  215. }
  216. if ( listeners[ type ].indexOf( listener ) === - 1 ) {
  217. listeners[ type ].push( listener );
  218. }
  219. }
  220. hasEventListener( type, listener ) {
  221. if ( this._listeners === undefined ) return false;
  222. const listeners = this._listeners;
  223. return listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== - 1;
  224. }
  225. removeEventListener( type, listener ) {
  226. if ( this._listeners === undefined ) return;
  227. const listeners = this._listeners;
  228. const listenerArray = listeners[ type ];
  229. if ( listenerArray !== undefined ) {
  230. const index = listenerArray.indexOf( listener );
  231. if ( index !== - 1 ) {
  232. listenerArray.splice( index, 1 );
  233. }
  234. }
  235. }
  236. dispatchEvent( event ) {
  237. if ( this._listeners === undefined ) return;
  238. const listeners = this._listeners;
  239. const listenerArray = listeners[ event.type ];
  240. if ( listenerArray !== undefined ) {
  241. event.target = this;
  242. // Make a copy, in case listeners are removed while iterating.
  243. const array = listenerArray.slice( 0 );
  244. for ( let i = 0, l = array.length; i < l; i ++ ) {
  245. array[ i ].call( this, event );
  246. }
  247. event.target = null;
  248. }
  249. }
  250. }
  251. 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' ];
  252. let _seed = 1234567;
  253. const DEG2RAD = Math.PI / 180;
  254. const RAD2DEG = 180 / Math.PI;
  255. // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/21963136#21963136
  256. function generateUUID() {
  257. const d0 = Math.random() * 0xffffffff | 0;
  258. const d1 = Math.random() * 0xffffffff | 0;
  259. const d2 = Math.random() * 0xffffffff | 0;
  260. const d3 = Math.random() * 0xffffffff | 0;
  261. const uuid = _lut[ d0 & 0xff ] + _lut[ d0 >> 8 & 0xff ] + _lut[ d0 >> 16 & 0xff ] + _lut[ d0 >> 24 & 0xff ] + '-' +
  262. _lut[ d1 & 0xff ] + _lut[ d1 >> 8 & 0xff ] + '-' + _lut[ d1 >> 16 & 0x0f | 0x40 ] + _lut[ d1 >> 24 & 0xff ] + '-' +
  263. _lut[ d2 & 0x3f | 0x80 ] + _lut[ d2 >> 8 & 0xff ] + '-' + _lut[ d2 >> 16 & 0xff ] + _lut[ d2 >> 24 & 0xff ] +
  264. _lut[ d3 & 0xff ] + _lut[ d3 >> 8 & 0xff ] + _lut[ d3 >> 16 & 0xff ] + _lut[ d3 >> 24 & 0xff ];
  265. // .toLowerCase() here flattens concatenated strings to save heap memory space.
  266. return uuid.toLowerCase();
  267. }
  268. function clamp$1( value, min, max ) {
  269. return Math.max( min, Math.min( max, value ) );
  270. }
  271. // compute euclidean modulo of m % n
  272. // https://en.wikipedia.org/wiki/Modulo_operation
  273. function euclideanModulo( n, m ) {
  274. return ( ( n % m ) + m ) % m;
  275. }
  276. // Linear mapping from range <a1, a2> to range <b1, b2>
  277. function mapLinear( x, a1, a2, b1, b2 ) {
  278. return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
  279. }
  280. // https://www.gamedev.net/tutorials/programming/general-and-gameplay-programming/inverse-lerp-a-super-useful-yet-often-overlooked-function-r5230/
  281. function inverseLerp( x, y, value ) {
  282. if ( x !== y ) {
  283. return ( value - x ) / ( y - x );
  284. } else {
  285. return 0;
  286. }
  287. }
  288. // https://en.wikipedia.org/wiki/Linear_interpolation
  289. function lerp( x, y, t ) {
  290. return ( 1 - t ) * x + t * y;
  291. }
  292. // http://www.rorydriscoll.com/2016/03/07/frame-rate-independent-damping-using-lerp/
  293. function damp( x, y, lambda, dt ) {
  294. return lerp( x, y, 1 - Math.exp( - lambda * dt ) );
  295. }
  296. // https://www.desmos.com/calculator/vcsjnyz7x4
  297. function pingpong( x, length = 1 ) {
  298. return length - Math.abs( euclideanModulo( x, length * 2 ) - length );
  299. }
  300. // http://en.wikipedia.org/wiki/Smoothstep
  301. function smoothstep$1( x, min, max ) {
  302. if ( x <= min ) return 0;
  303. if ( x >= max ) return 1;
  304. x = ( x - min ) / ( max - min );
  305. return x * x * ( 3 - 2 * x );
  306. }
  307. function smootherstep( x, min, max ) {
  308. if ( x <= min ) return 0;
  309. if ( x >= max ) return 1;
  310. x = ( x - min ) / ( max - min );
  311. return x * x * x * ( x * ( x * 6 - 15 ) + 10 );
  312. }
  313. // Random integer from <low, high> interval
  314. function randInt( low, high ) {
  315. return low + Math.floor( Math.random() * ( high - low + 1 ) );
  316. }
  317. // Random float from <low, high> interval
  318. function randFloat( low, high ) {
  319. return low + Math.random() * ( high - low );
  320. }
  321. // Random float from <-range/2, range/2> interval
  322. function randFloatSpread( range ) {
  323. return range * ( 0.5 - Math.random() );
  324. }
  325. // Deterministic pseudo-random float in the interval [ 0, 1 ]
  326. function seededRandom( s ) {
  327. if ( s !== undefined ) _seed = s;
  328. // Mulberry32 generator
  329. let t = _seed += 0x6D2B79F5;
  330. t = Math.imul( t ^ t >>> 15, t | 1 );
  331. t ^= t + Math.imul( t ^ t >>> 7, t | 61 );
  332. return ( ( t ^ t >>> 14 ) >>> 0 ) / 4294967296;
  333. }
  334. function degToRad( degrees ) {
  335. return degrees * DEG2RAD;
  336. }
  337. function radToDeg( radians ) {
  338. return radians * RAD2DEG;
  339. }
  340. function isPowerOfTwo( value ) {
  341. return ( value & ( value - 1 ) ) === 0 && value !== 0;
  342. }
  343. function ceilPowerOfTwo( value ) {
  344. return Math.pow( 2, Math.ceil( Math.log( value ) / Math.LN2 ) );
  345. }
  346. function floorPowerOfTwo( value ) {
  347. return Math.pow( 2, Math.floor( Math.log( value ) / Math.LN2 ) );
  348. }
  349. function setQuaternionFromProperEuler( q, a, b, c, order ) {
  350. // Intrinsic Proper Euler Angles - see https://en.wikipedia.org/wiki/Euler_angles
  351. // rotations are applied to the axes in the order specified by 'order'
  352. // rotation by angle 'a' is applied first, then by angle 'b', then by angle 'c'
  353. // angles are in radians
  354. const cos = Math.cos;
  355. const sin = Math.sin;
  356. const c2 = cos( b / 2 );
  357. const s2 = sin( b / 2 );
  358. const c13 = cos( ( a + c ) / 2 );
  359. const s13 = sin( ( a + c ) / 2 );
  360. const c1_3 = cos( ( a - c ) / 2 );
  361. const s1_3 = sin( ( a - c ) / 2 );
  362. const c3_1 = cos( ( c - a ) / 2 );
  363. const s3_1 = sin( ( c - a ) / 2 );
  364. switch ( order ) {
  365. case 'XYX':
  366. q.set( c2 * s13, s2 * c1_3, s2 * s1_3, c2 * c13 );
  367. break;
  368. case 'YZY':
  369. q.set( s2 * s1_3, c2 * s13, s2 * c1_3, c2 * c13 );
  370. break;
  371. case 'ZXZ':
  372. q.set( s2 * c1_3, s2 * s1_3, c2 * s13, c2 * c13 );
  373. break;
  374. case 'XZX':
  375. q.set( c2 * s13, s2 * s3_1, s2 * c3_1, c2 * c13 );
  376. break;
  377. case 'YXY':
  378. q.set( s2 * c3_1, c2 * s13, s2 * s3_1, c2 * c13 );
  379. break;
  380. case 'ZYZ':
  381. q.set( s2 * s3_1, s2 * c3_1, c2 * s13, c2 * c13 );
  382. break;
  383. default:
  384. console.warn( 'THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: ' + order );
  385. }
  386. }
  387. function denormalize( value, array ) {
  388. switch ( array.constructor ) {
  389. case Float32Array:
  390. return value;
  391. case Uint32Array:
  392. return value / 4294967295.0;
  393. case Uint16Array:
  394. return value / 65535.0;
  395. case Uint8Array:
  396. return value / 255.0;
  397. case Int32Array:
  398. return Math.max( value / 2147483647.0, - 1.0 );
  399. case Int16Array:
  400. return Math.max( value / 32767.0, - 1.0 );
  401. case Int8Array:
  402. return Math.max( value / 127.0, - 1.0 );
  403. default:
  404. throw new Error( 'Invalid component type.' );
  405. }
  406. }
  407. function normalize$1( value, array ) {
  408. switch ( array.constructor ) {
  409. case Float32Array:
  410. return value;
  411. case Uint32Array:
  412. return Math.round( value * 4294967295.0 );
  413. case Uint16Array:
  414. return Math.round( value * 65535.0 );
  415. case Uint8Array:
  416. return Math.round( value * 255.0 );
  417. case Int32Array:
  418. return Math.round( value * 2147483647.0 );
  419. case Int16Array:
  420. return Math.round( value * 32767.0 );
  421. case Int8Array:
  422. return Math.round( value * 127.0 );
  423. default:
  424. throw new Error( 'Invalid component type.' );
  425. }
  426. }
  427. const MathUtils = {
  428. DEG2RAD: DEG2RAD,
  429. RAD2DEG: RAD2DEG,
  430. generateUUID: generateUUID,
  431. clamp: clamp$1,
  432. euclideanModulo: euclideanModulo,
  433. mapLinear: mapLinear,
  434. inverseLerp: inverseLerp,
  435. lerp: lerp,
  436. damp: damp,
  437. pingpong: pingpong,
  438. smoothstep: smoothstep$1,
  439. smootherstep: smootherstep,
  440. randInt: randInt,
  441. randFloat: randFloat,
  442. randFloatSpread: randFloatSpread,
  443. seededRandom: seededRandom,
  444. degToRad: degToRad,
  445. radToDeg: radToDeg,
  446. isPowerOfTwo: isPowerOfTwo,
  447. ceilPowerOfTwo: ceilPowerOfTwo,
  448. floorPowerOfTwo: floorPowerOfTwo,
  449. setQuaternionFromProperEuler: setQuaternionFromProperEuler,
  450. normalize: normalize$1,
  451. denormalize: denormalize
  452. };
  453. class Vector2 {
  454. constructor( x = 0, y = 0 ) {
  455. Vector2.prototype.isVector2 = true;
  456. this.x = x;
  457. this.y = y;
  458. }
  459. get width() {
  460. return this.x;
  461. }
  462. set width( value ) {
  463. this.x = value;
  464. }
  465. get height() {
  466. return this.y;
  467. }
  468. set height( value ) {
  469. this.y = value;
  470. }
  471. set( x, y ) {
  472. this.x = x;
  473. this.y = y;
  474. return this;
  475. }
  476. setScalar( scalar ) {
  477. this.x = scalar;
  478. this.y = scalar;
  479. return this;
  480. }
  481. setX( x ) {
  482. this.x = x;
  483. return this;
  484. }
  485. setY( y ) {
  486. this.y = y;
  487. return this;
  488. }
  489. setComponent( index, value ) {
  490. switch ( index ) {
  491. case 0: this.x = value; break;
  492. case 1: this.y = value; break;
  493. default: throw new Error( 'index is out of range: ' + index );
  494. }
  495. return this;
  496. }
  497. getComponent( index ) {
  498. switch ( index ) {
  499. case 0: return this.x;
  500. case 1: return this.y;
  501. default: throw new Error( 'index is out of range: ' + index );
  502. }
  503. }
  504. clone() {
  505. return new this.constructor( this.x, this.y );
  506. }
  507. copy( v ) {
  508. this.x = v.x;
  509. this.y = v.y;
  510. return this;
  511. }
  512. add( v ) {
  513. this.x += v.x;
  514. this.y += v.y;
  515. return this;
  516. }
  517. addScalar( s ) {
  518. this.x += s;
  519. this.y += s;
  520. return this;
  521. }
  522. addVectors( a, b ) {
  523. this.x = a.x + b.x;
  524. this.y = a.y + b.y;
  525. return this;
  526. }
  527. addScaledVector( v, s ) {
  528. this.x += v.x * s;
  529. this.y += v.y * s;
  530. return this;
  531. }
  532. sub( v ) {
  533. this.x -= v.x;
  534. this.y -= v.y;
  535. return this;
  536. }
  537. subScalar( s ) {
  538. this.x -= s;
  539. this.y -= s;
  540. return this;
  541. }
  542. subVectors( a, b ) {
  543. this.x = a.x - b.x;
  544. this.y = a.y - b.y;
  545. return this;
  546. }
  547. multiply( v ) {
  548. this.x *= v.x;
  549. this.y *= v.y;
  550. return this;
  551. }
  552. multiplyScalar( scalar ) {
  553. this.x *= scalar;
  554. this.y *= scalar;
  555. return this;
  556. }
  557. divide( v ) {
  558. this.x /= v.x;
  559. this.y /= v.y;
  560. return this;
  561. }
  562. divideScalar( scalar ) {
  563. return this.multiplyScalar( 1 / scalar );
  564. }
  565. applyMatrix3( m ) {
  566. const x = this.x, y = this.y;
  567. const e = m.elements;
  568. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ];
  569. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ];
  570. return this;
  571. }
  572. min( v ) {
  573. this.x = Math.min( this.x, v.x );
  574. this.y = Math.min( this.y, v.y );
  575. return this;
  576. }
  577. max( v ) {
  578. this.x = Math.max( this.x, v.x );
  579. this.y = Math.max( this.y, v.y );
  580. return this;
  581. }
  582. clamp( min, max ) {
  583. // assumes min < max, componentwise
  584. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  585. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  586. return this;
  587. }
  588. clampScalar( minVal, maxVal ) {
  589. this.x = Math.max( minVal, Math.min( maxVal, this.x ) );
  590. this.y = Math.max( minVal, Math.min( maxVal, this.y ) );
  591. return this;
  592. }
  593. clampLength( min, max ) {
  594. const length = this.length();
  595. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  596. }
  597. floor() {
  598. this.x = Math.floor( this.x );
  599. this.y = Math.floor( this.y );
  600. return this;
  601. }
  602. ceil() {
  603. this.x = Math.ceil( this.x );
  604. this.y = Math.ceil( this.y );
  605. return this;
  606. }
  607. round() {
  608. this.x = Math.round( this.x );
  609. this.y = Math.round( this.y );
  610. return this;
  611. }
  612. roundToZero() {
  613. this.x = Math.trunc( this.x );
  614. this.y = Math.trunc( this.y );
  615. return this;
  616. }
  617. negate() {
  618. this.x = - this.x;
  619. this.y = - this.y;
  620. return this;
  621. }
  622. dot( v ) {
  623. return this.x * v.x + this.y * v.y;
  624. }
  625. cross( v ) {
  626. return this.x * v.y - this.y * v.x;
  627. }
  628. lengthSq() {
  629. return this.x * this.x + this.y * this.y;
  630. }
  631. length() {
  632. return Math.sqrt( this.x * this.x + this.y * this.y );
  633. }
  634. manhattanLength() {
  635. return Math.abs( this.x ) + Math.abs( this.y );
  636. }
  637. normalize() {
  638. return this.divideScalar( this.length() || 1 );
  639. }
  640. angle() {
  641. // computes the angle in radians with respect to the positive x-axis
  642. const angle = Math.atan2( - this.y, - this.x ) + Math.PI;
  643. return angle;
  644. }
  645. angleTo( v ) {
  646. const denominator = Math.sqrt( this.lengthSq() * v.lengthSq() );
  647. if ( denominator === 0 ) return Math.PI / 2;
  648. const theta = this.dot( v ) / denominator;
  649. // clamp, to handle numerical problems
  650. return Math.acos( clamp$1( theta, - 1, 1 ) );
  651. }
  652. distanceTo( v ) {
  653. return Math.sqrt( this.distanceToSquared( v ) );
  654. }
  655. distanceToSquared( v ) {
  656. const dx = this.x - v.x, dy = this.y - v.y;
  657. return dx * dx + dy * dy;
  658. }
  659. manhattanDistanceTo( v ) {
  660. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y );
  661. }
  662. setLength( length ) {
  663. return this.normalize().multiplyScalar( length );
  664. }
  665. lerp( v, alpha ) {
  666. this.x += ( v.x - this.x ) * alpha;
  667. this.y += ( v.y - this.y ) * alpha;
  668. return this;
  669. }
  670. lerpVectors( v1, v2, alpha ) {
  671. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  672. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  673. return this;
  674. }
  675. equals( v ) {
  676. return ( ( v.x === this.x ) && ( v.y === this.y ) );
  677. }
  678. fromArray( array, offset = 0 ) {
  679. this.x = array[ offset ];
  680. this.y = array[ offset + 1 ];
  681. return this;
  682. }
  683. toArray( array = [], offset = 0 ) {
  684. array[ offset ] = this.x;
  685. array[ offset + 1 ] = this.y;
  686. return array;
  687. }
  688. fromBufferAttribute( attribute, index ) {
  689. this.x = attribute.getX( index );
  690. this.y = attribute.getY( index );
  691. return this;
  692. }
  693. rotateAround( center, angle ) {
  694. const c = Math.cos( angle ), s = Math.sin( angle );
  695. const x = this.x - center.x;
  696. const y = this.y - center.y;
  697. this.x = x * c - y * s + center.x;
  698. this.y = x * s + y * c + center.y;
  699. return this;
  700. }
  701. random() {
  702. this.x = Math.random();
  703. this.y = Math.random();
  704. return this;
  705. }
  706. *[ Symbol.iterator ]() {
  707. yield this.x;
  708. yield this.y;
  709. }
  710. }
  711. class Matrix3 {
  712. constructor( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  713. Matrix3.prototype.isMatrix3 = true;
  714. this.elements = [
  715. 1, 0, 0,
  716. 0, 1, 0,
  717. 0, 0, 1
  718. ];
  719. if ( n11 !== undefined ) {
  720. this.set( n11, n12, n13, n21, n22, n23, n31, n32, n33 );
  721. }
  722. }
  723. set( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  724. const te = this.elements;
  725. te[ 0 ] = n11; te[ 1 ] = n21; te[ 2 ] = n31;
  726. te[ 3 ] = n12; te[ 4 ] = n22; te[ 5 ] = n32;
  727. te[ 6 ] = n13; te[ 7 ] = n23; te[ 8 ] = n33;
  728. return this;
  729. }
  730. identity() {
  731. this.set(
  732. 1, 0, 0,
  733. 0, 1, 0,
  734. 0, 0, 1
  735. );
  736. return this;
  737. }
  738. copy( m ) {
  739. const te = this.elements;
  740. const me = m.elements;
  741. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ];
  742. te[ 3 ] = me[ 3 ]; te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ];
  743. te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ]; te[ 8 ] = me[ 8 ];
  744. return this;
  745. }
  746. extractBasis( xAxis, yAxis, zAxis ) {
  747. xAxis.setFromMatrix3Column( this, 0 );
  748. yAxis.setFromMatrix3Column( this, 1 );
  749. zAxis.setFromMatrix3Column( this, 2 );
  750. return this;
  751. }
  752. setFromMatrix4( m ) {
  753. const me = m.elements;
  754. this.set(
  755. me[ 0 ], me[ 4 ], me[ 8 ],
  756. me[ 1 ], me[ 5 ], me[ 9 ],
  757. me[ 2 ], me[ 6 ], me[ 10 ]
  758. );
  759. return this;
  760. }
  761. multiply( m ) {
  762. return this.multiplyMatrices( this, m );
  763. }
  764. premultiply( m ) {
  765. return this.multiplyMatrices( m, this );
  766. }
  767. multiplyMatrices( a, b ) {
  768. const ae = a.elements;
  769. const be = b.elements;
  770. const te = this.elements;
  771. const a11 = ae[ 0 ], a12 = ae[ 3 ], a13 = ae[ 6 ];
  772. const a21 = ae[ 1 ], a22 = ae[ 4 ], a23 = ae[ 7 ];
  773. const a31 = ae[ 2 ], a32 = ae[ 5 ], a33 = ae[ 8 ];
  774. const b11 = be[ 0 ], b12 = be[ 3 ], b13 = be[ 6 ];
  775. const b21 = be[ 1 ], b22 = be[ 4 ], b23 = be[ 7 ];
  776. const b31 = be[ 2 ], b32 = be[ 5 ], b33 = be[ 8 ];
  777. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31;
  778. te[ 3 ] = a11 * b12 + a12 * b22 + a13 * b32;
  779. te[ 6 ] = a11 * b13 + a12 * b23 + a13 * b33;
  780. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31;
  781. te[ 4 ] = a21 * b12 + a22 * b22 + a23 * b32;
  782. te[ 7 ] = a21 * b13 + a22 * b23 + a23 * b33;
  783. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31;
  784. te[ 5 ] = a31 * b12 + a32 * b22 + a33 * b32;
  785. te[ 8 ] = a31 * b13 + a32 * b23 + a33 * b33;
  786. return this;
  787. }
  788. multiplyScalar( s ) {
  789. const te = this.elements;
  790. te[ 0 ] *= s; te[ 3 ] *= s; te[ 6 ] *= s;
  791. te[ 1 ] *= s; te[ 4 ] *= s; te[ 7 ] *= s;
  792. te[ 2 ] *= s; te[ 5 ] *= s; te[ 8 ] *= s;
  793. return this;
  794. }
  795. determinant() {
  796. const te = this.elements;
  797. const a = te[ 0 ], b = te[ 1 ], c = te[ 2 ],
  798. d = te[ 3 ], e = te[ 4 ], f = te[ 5 ],
  799. g = te[ 6 ], h = te[ 7 ], i = te[ 8 ];
  800. return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g;
  801. }
  802. invert() {
  803. const te = this.elements,
  804. n11 = te[ 0 ], n21 = te[ 1 ], n31 = te[ 2 ],
  805. n12 = te[ 3 ], n22 = te[ 4 ], n32 = te[ 5 ],
  806. n13 = te[ 6 ], n23 = te[ 7 ], n33 = te[ 8 ],
  807. t11 = n33 * n22 - n32 * n23,
  808. t12 = n32 * n13 - n33 * n12,
  809. t13 = n23 * n12 - n22 * n13,
  810. det = n11 * t11 + n21 * t12 + n31 * t13;
  811. if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0 );
  812. const detInv = 1 / det;
  813. te[ 0 ] = t11 * detInv;
  814. te[ 1 ] = ( n31 * n23 - n33 * n21 ) * detInv;
  815. te[ 2 ] = ( n32 * n21 - n31 * n22 ) * detInv;
  816. te[ 3 ] = t12 * detInv;
  817. te[ 4 ] = ( n33 * n11 - n31 * n13 ) * detInv;
  818. te[ 5 ] = ( n31 * n12 - n32 * n11 ) * detInv;
  819. te[ 6 ] = t13 * detInv;
  820. te[ 7 ] = ( n21 * n13 - n23 * n11 ) * detInv;
  821. te[ 8 ] = ( n22 * n11 - n21 * n12 ) * detInv;
  822. return this;
  823. }
  824. transpose() {
  825. let tmp;
  826. const m = this.elements;
  827. tmp = m[ 1 ]; m[ 1 ] = m[ 3 ]; m[ 3 ] = tmp;
  828. tmp = m[ 2 ]; m[ 2 ] = m[ 6 ]; m[ 6 ] = tmp;
  829. tmp = m[ 5 ]; m[ 5 ] = m[ 7 ]; m[ 7 ] = tmp;
  830. return this;
  831. }
  832. getNormalMatrix( matrix4 ) {
  833. return this.setFromMatrix4( matrix4 ).invert().transpose();
  834. }
  835. transposeIntoArray( r ) {
  836. const m = this.elements;
  837. r[ 0 ] = m[ 0 ];
  838. r[ 1 ] = m[ 3 ];
  839. r[ 2 ] = m[ 6 ];
  840. r[ 3 ] = m[ 1 ];
  841. r[ 4 ] = m[ 4 ];
  842. r[ 5 ] = m[ 7 ];
  843. r[ 6 ] = m[ 2 ];
  844. r[ 7 ] = m[ 5 ];
  845. r[ 8 ] = m[ 8 ];
  846. return this;
  847. }
  848. setUvTransform( tx, ty, sx, sy, rotation, cx, cy ) {
  849. const c = Math.cos( rotation );
  850. const s = Math.sin( rotation );
  851. this.set(
  852. sx * c, sx * s, - sx * ( c * cx + s * cy ) + cx + tx,
  853. - sy * s, sy * c, - sy * ( - s * cx + c * cy ) + cy + ty,
  854. 0, 0, 1
  855. );
  856. return this;
  857. }
  858. //
  859. scale( sx, sy ) {
  860. this.premultiply( _m3.makeScale( sx, sy ) );
  861. return this;
  862. }
  863. rotate( theta ) {
  864. this.premultiply( _m3.makeRotation( - theta ) );
  865. return this;
  866. }
  867. translate( tx, ty ) {
  868. this.premultiply( _m3.makeTranslation( tx, ty ) );
  869. return this;
  870. }
  871. // for 2D Transforms
  872. makeTranslation( x, y ) {
  873. if ( x.isVector2 ) {
  874. this.set(
  875. 1, 0, x.x,
  876. 0, 1, x.y,
  877. 0, 0, 1
  878. );
  879. } else {
  880. this.set(
  881. 1, 0, x,
  882. 0, 1, y,
  883. 0, 0, 1
  884. );
  885. }
  886. return this;
  887. }
  888. makeRotation( theta ) {
  889. // counterclockwise
  890. const c = Math.cos( theta );
  891. const s = Math.sin( theta );
  892. this.set(
  893. c, - s, 0,
  894. s, c, 0,
  895. 0, 0, 1
  896. );
  897. return this;
  898. }
  899. makeScale( x, y ) {
  900. this.set(
  901. x, 0, 0,
  902. 0, y, 0,
  903. 0, 0, 1
  904. );
  905. return this;
  906. }
  907. //
  908. equals( matrix ) {
  909. const te = this.elements;
  910. const me = matrix.elements;
  911. for ( let i = 0; i < 9; i ++ ) {
  912. if ( te[ i ] !== me[ i ] ) return false;
  913. }
  914. return true;
  915. }
  916. fromArray( array, offset = 0 ) {
  917. for ( let i = 0; i < 9; i ++ ) {
  918. this.elements[ i ] = array[ i + offset ];
  919. }
  920. return this;
  921. }
  922. toArray( array = [], offset = 0 ) {
  923. const te = this.elements;
  924. array[ offset ] = te[ 0 ];
  925. array[ offset + 1 ] = te[ 1 ];
  926. array[ offset + 2 ] = te[ 2 ];
  927. array[ offset + 3 ] = te[ 3 ];
  928. array[ offset + 4 ] = te[ 4 ];
  929. array[ offset + 5 ] = te[ 5 ];
  930. array[ offset + 6 ] = te[ 6 ];
  931. array[ offset + 7 ] = te[ 7 ];
  932. array[ offset + 8 ] = te[ 8 ];
  933. return array;
  934. }
  935. clone() {
  936. return new this.constructor().fromArray( this.elements );
  937. }
  938. }
  939. const _m3 = /*@__PURE__*/ new Matrix3();
  940. function arrayNeedsUint32$1( array ) {
  941. // assumes larger values usually on last
  942. for ( let i = array.length - 1; i >= 0; -- i ) {
  943. if ( array[ i ] >= 65535 ) return true; // account for PRIMITIVE_RESTART_FIXED_INDEX, #24565
  944. }
  945. return false;
  946. }
  947. const TYPED_ARRAYS = {
  948. Int8Array: Int8Array,
  949. Uint8Array: Uint8Array,
  950. Uint8ClampedArray: Uint8ClampedArray,
  951. Int16Array: Int16Array,
  952. Uint16Array: Uint16Array,
  953. Int32Array: Int32Array,
  954. Uint32Array: Uint32Array,
  955. Float32Array: Float32Array,
  956. Float64Array: Float64Array
  957. };
  958. function getTypedArray( type, buffer ) {
  959. return new TYPED_ARRAYS[ type ]( buffer );
  960. }
  961. function createElementNS( name ) {
  962. return document.createElementNS( 'http://www.w3.org/1999/xhtml', name );
  963. }
  964. function createCanvasElement() {
  965. const canvas = createElementNS( 'canvas' );
  966. canvas.style.display = 'block';
  967. return canvas;
  968. }
  969. const _cache$2 = {};
  970. function warnOnce( message ) {
  971. if ( message in _cache$2 ) return;
  972. _cache$2[ message ] = true;
  973. console.warn( message );
  974. }
  975. const ColorManagement = {
  976. enabled: true,
  977. workingColorSpace: LinearSRGBColorSpace,
  978. /**
  979. * Implementations of supported color spaces.
  980. *
  981. * Required:
  982. * - primaries: chromaticity coordinates [ rx ry gx gy bx by ]
  983. * - whitePoint: reference white [ x y ]
  984. * - transfer: transfer function (pre-defined)
  985. * - toXYZ: Matrix3 RGB to XYZ transform
  986. * - fromXYZ: Matrix3 XYZ to RGB transform
  987. * - luminanceCoefficients: RGB luminance coefficients
  988. *
  989. * Optional:
  990. * - outputColorSpaceConfig: { drawingBufferColorSpace: ColorSpace }
  991. * - workingColorSpaceConfig: { unpackColorSpace: ColorSpace }
  992. *
  993. * Reference:
  994. * - https://www.russellcottrell.com/photo/matrixCalculator.htm
  995. */
  996. spaces: {},
  997. convert: function ( color, sourceColorSpace, targetColorSpace ) {
  998. if ( this.enabled === false || sourceColorSpace === targetColorSpace || ! sourceColorSpace || ! targetColorSpace ) {
  999. return color;
  1000. }
  1001. if ( this.spaces[ sourceColorSpace ].transfer === SRGBTransfer ) {
  1002. color.r = SRGBToLinear( color.r );
  1003. color.g = SRGBToLinear( color.g );
  1004. color.b = SRGBToLinear( color.b );
  1005. }
  1006. if ( this.spaces[ sourceColorSpace ].primaries !== this.spaces[ targetColorSpace ].primaries ) {
  1007. color.applyMatrix3( this.spaces[ sourceColorSpace ].toXYZ );
  1008. color.applyMatrix3( this.spaces[ targetColorSpace ].fromXYZ );
  1009. }
  1010. if ( this.spaces[ targetColorSpace ].transfer === SRGBTransfer ) {
  1011. color.r = LinearToSRGB( color.r );
  1012. color.g = LinearToSRGB( color.g );
  1013. color.b = LinearToSRGB( color.b );
  1014. }
  1015. return color;
  1016. },
  1017. fromWorkingColorSpace: function ( color, targetColorSpace ) {
  1018. return this.convert( color, this.workingColorSpace, targetColorSpace );
  1019. },
  1020. toWorkingColorSpace: function ( color, sourceColorSpace ) {
  1021. return this.convert( color, sourceColorSpace, this.workingColorSpace );
  1022. },
  1023. getPrimaries: function ( colorSpace ) {
  1024. return this.spaces[ colorSpace ].primaries;
  1025. },
  1026. getTransfer: function ( colorSpace ) {
  1027. if ( colorSpace === NoColorSpace ) return LinearTransfer;
  1028. return this.spaces[ colorSpace ].transfer;
  1029. },
  1030. getLuminanceCoefficients: function ( target, colorSpace = this.workingColorSpace ) {
  1031. return target.fromArray( this.spaces[ colorSpace ].luminanceCoefficients );
  1032. },
  1033. define: function ( colorSpaces ) {
  1034. Object.assign( this.spaces, colorSpaces );
  1035. },
  1036. // Internal APIs
  1037. _getMatrix: function ( targetMatrix, sourceColorSpace, targetColorSpace ) {
  1038. return targetMatrix
  1039. .copy( this.spaces[ sourceColorSpace ].toXYZ )
  1040. .multiply( this.spaces[ targetColorSpace ].fromXYZ );
  1041. },
  1042. _getDrawingBufferColorSpace: function ( colorSpace ) {
  1043. return this.spaces[ colorSpace ].outputColorSpaceConfig.drawingBufferColorSpace;
  1044. },
  1045. _getUnpackColorSpace: function ( colorSpace = this.workingColorSpace ) {
  1046. return this.spaces[ colorSpace ].workingColorSpaceConfig.unpackColorSpace;
  1047. }
  1048. };
  1049. function SRGBToLinear( c ) {
  1050. return ( c < 0.04045 ) ? c * 0.0773993808 : Math.pow( c * 0.9478672986 + 0.0521327014, 2.4 );
  1051. }
  1052. function LinearToSRGB( c ) {
  1053. return ( c < 0.0031308 ) ? c * 12.92 : 1.055 * ( Math.pow( c, 0.41666 ) ) - 0.055;
  1054. }
  1055. /******************************************************************************
  1056. * sRGB definitions
  1057. */
  1058. const REC709_PRIMARIES = [ 0.640, 0.330, 0.300, 0.600, 0.150, 0.060 ];
  1059. const REC709_LUMINANCE_COEFFICIENTS = [ 0.2126, 0.7152, 0.0722 ];
  1060. const D65 = [ 0.3127, 0.3290 ];
  1061. const LINEAR_REC709_TO_XYZ = /*@__PURE__*/ new Matrix3().set(
  1062. 0.4123908, 0.3575843, 0.1804808,
  1063. 0.2126390, 0.7151687, 0.0721923,
  1064. 0.0193308, 0.1191948, 0.9505322
  1065. );
  1066. const XYZ_TO_LINEAR_REC709 = /*@__PURE__*/ new Matrix3().set(
  1067. 3.2409699, - 1.5373832, - 0.4986108,
  1068. - 0.9692436, 1.8759675, 0.0415551,
  1069. 0.0556301, - 0.2039770, 1.0569715
  1070. );
  1071. ColorManagement.define( {
  1072. [ LinearSRGBColorSpace ]: {
  1073. primaries: REC709_PRIMARIES,
  1074. whitePoint: D65,
  1075. transfer: LinearTransfer,
  1076. toXYZ: LINEAR_REC709_TO_XYZ,
  1077. fromXYZ: XYZ_TO_LINEAR_REC709,
  1078. luminanceCoefficients: REC709_LUMINANCE_COEFFICIENTS,
  1079. workingColorSpaceConfig: { unpackColorSpace: SRGBColorSpace },
  1080. outputColorSpaceConfig: { drawingBufferColorSpace: SRGBColorSpace }
  1081. },
  1082. [ SRGBColorSpace ]: {
  1083. primaries: REC709_PRIMARIES,
  1084. whitePoint: D65,
  1085. transfer: SRGBTransfer,
  1086. toXYZ: LINEAR_REC709_TO_XYZ,
  1087. fromXYZ: XYZ_TO_LINEAR_REC709,
  1088. luminanceCoefficients: REC709_LUMINANCE_COEFFICIENTS,
  1089. outputColorSpaceConfig: { drawingBufferColorSpace: SRGBColorSpace }
  1090. },
  1091. } );
  1092. let _canvas;
  1093. class ImageUtils {
  1094. static getDataURL( image ) {
  1095. if ( /^data:/i.test( image.src ) ) {
  1096. return image.src;
  1097. }
  1098. if ( typeof HTMLCanvasElement === 'undefined' ) {
  1099. return image.src;
  1100. }
  1101. let canvas;
  1102. if ( image instanceof HTMLCanvasElement ) {
  1103. canvas = image;
  1104. } else {
  1105. if ( _canvas === undefined ) _canvas = createElementNS( 'canvas' );
  1106. _canvas.width = image.width;
  1107. _canvas.height = image.height;
  1108. const context = _canvas.getContext( '2d' );
  1109. if ( image instanceof ImageData ) {
  1110. context.putImageData( image, 0, 0 );
  1111. } else {
  1112. context.drawImage( image, 0, 0, image.width, image.height );
  1113. }
  1114. canvas = _canvas;
  1115. }
  1116. if ( canvas.width > 2048 || canvas.height > 2048 ) {
  1117. console.warn( 'THREE.ImageUtils.getDataURL: Image converted to jpg for performance reasons', image );
  1118. return canvas.toDataURL( 'image/jpeg', 0.6 );
  1119. } else {
  1120. return canvas.toDataURL( 'image/png' );
  1121. }
  1122. }
  1123. static sRGBToLinear( image ) {
  1124. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  1125. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  1126. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  1127. const canvas = createElementNS( 'canvas' );
  1128. canvas.width = image.width;
  1129. canvas.height = image.height;
  1130. const context = canvas.getContext( '2d' );
  1131. context.drawImage( image, 0, 0, image.width, image.height );
  1132. const imageData = context.getImageData( 0, 0, image.width, image.height );
  1133. const data = imageData.data;
  1134. for ( let i = 0; i < data.length; i ++ ) {
  1135. data[ i ] = SRGBToLinear( data[ i ] / 255 ) * 255;
  1136. }
  1137. context.putImageData( imageData, 0, 0 );
  1138. return canvas;
  1139. } else if ( image.data ) {
  1140. const data = image.data.slice( 0 );
  1141. for ( let i = 0; i < data.length; i ++ ) {
  1142. if ( data instanceof Uint8Array || data instanceof Uint8ClampedArray ) {
  1143. data[ i ] = Math.floor( SRGBToLinear( data[ i ] / 255 ) * 255 );
  1144. } else {
  1145. // assuming float
  1146. data[ i ] = SRGBToLinear( data[ i ] );
  1147. }
  1148. }
  1149. return {
  1150. data: data,
  1151. width: image.width,
  1152. height: image.height
  1153. };
  1154. } else {
  1155. console.warn( 'THREE.ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied.' );
  1156. return image;
  1157. }
  1158. }
  1159. }
  1160. let _sourceId = 0;
  1161. class Source {
  1162. constructor( data = null ) {
  1163. this.isSource = true;
  1164. Object.defineProperty( this, 'id', { value: _sourceId ++ } );
  1165. this.uuid = generateUUID();
  1166. this.data = data;
  1167. this.dataReady = true;
  1168. this.version = 0;
  1169. }
  1170. set needsUpdate( value ) {
  1171. if ( value === true ) this.version ++;
  1172. }
  1173. toJSON( meta ) {
  1174. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  1175. if ( ! isRootObject && meta.images[ this.uuid ] !== undefined ) {
  1176. return meta.images[ this.uuid ];
  1177. }
  1178. const output = {
  1179. uuid: this.uuid,
  1180. url: ''
  1181. };
  1182. const data = this.data;
  1183. if ( data !== null ) {
  1184. let url;
  1185. if ( Array.isArray( data ) ) {
  1186. // cube texture
  1187. url = [];
  1188. for ( let i = 0, l = data.length; i < l; i ++ ) {
  1189. if ( data[ i ].isDataTexture ) {
  1190. url.push( serializeImage( data[ i ].image ) );
  1191. } else {
  1192. url.push( serializeImage( data[ i ] ) );
  1193. }
  1194. }
  1195. } else {
  1196. // texture
  1197. url = serializeImage( data );
  1198. }
  1199. output.url = url;
  1200. }
  1201. if ( ! isRootObject ) {
  1202. meta.images[ this.uuid ] = output;
  1203. }
  1204. return output;
  1205. }
  1206. }
  1207. function serializeImage( image ) {
  1208. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  1209. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  1210. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  1211. // default images
  1212. return ImageUtils.getDataURL( image );
  1213. } else {
  1214. if ( image.data ) {
  1215. // images of DataTexture
  1216. return {
  1217. data: Array.from( image.data ),
  1218. width: image.width,
  1219. height: image.height,
  1220. type: image.data.constructor.name
  1221. };
  1222. } else {
  1223. console.warn( 'THREE.Texture: Unable to serialize Texture.' );
  1224. return {};
  1225. }
  1226. }
  1227. }
  1228. let _textureId = 0;
  1229. class Texture extends EventDispatcher {
  1230. 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 ) {
  1231. super();
  1232. this.isTexture = true;
  1233. Object.defineProperty( this, 'id', { value: _textureId ++ } );
  1234. this.uuid = generateUUID();
  1235. this.name = '';
  1236. this.source = new Source( image );
  1237. this.mipmaps = [];
  1238. this.mapping = mapping;
  1239. this.channel = 0;
  1240. this.wrapS = wrapS;
  1241. this.wrapT = wrapT;
  1242. this.magFilter = magFilter;
  1243. this.minFilter = minFilter;
  1244. this.anisotropy = anisotropy;
  1245. this.format = format;
  1246. this.internalFormat = null;
  1247. this.type = type;
  1248. this.offset = new Vector2( 0, 0 );
  1249. this.repeat = new Vector2( 1, 1 );
  1250. this.center = new Vector2( 0, 0 );
  1251. this.rotation = 0;
  1252. this.matrixAutoUpdate = true;
  1253. this.matrix = new Matrix3();
  1254. this.generateMipmaps = true;
  1255. this.premultiplyAlpha = false;
  1256. this.flipY = true;
  1257. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  1258. this.colorSpace = colorSpace;
  1259. this.userData = {};
  1260. this.version = 0;
  1261. this.onUpdate = null;
  1262. this.isRenderTargetTexture = false; // indicates whether a texture belongs to a render target or not
  1263. this.pmremVersion = 0; // indicates whether this texture should be processed by PMREMGenerator or not (only relevant for render target textures)
  1264. }
  1265. get image() {
  1266. return this.source.data;
  1267. }
  1268. set image( value = null ) {
  1269. this.source.data = value;
  1270. }
  1271. updateMatrix() {
  1272. this.matrix.setUvTransform( this.offset.x, this.offset.y, this.repeat.x, this.repeat.y, this.rotation, this.center.x, this.center.y );
  1273. }
  1274. clone() {
  1275. return new this.constructor().copy( this );
  1276. }
  1277. copy( source ) {
  1278. this.name = source.name;
  1279. this.source = source.source;
  1280. this.mipmaps = source.mipmaps.slice( 0 );
  1281. this.mapping = source.mapping;
  1282. this.channel = source.channel;
  1283. this.wrapS = source.wrapS;
  1284. this.wrapT = source.wrapT;
  1285. this.magFilter = source.magFilter;
  1286. this.minFilter = source.minFilter;
  1287. this.anisotropy = source.anisotropy;
  1288. this.format = source.format;
  1289. this.internalFormat = source.internalFormat;
  1290. this.type = source.type;
  1291. this.offset.copy( source.offset );
  1292. this.repeat.copy( source.repeat );
  1293. this.center.copy( source.center );
  1294. this.rotation = source.rotation;
  1295. this.matrixAutoUpdate = source.matrixAutoUpdate;
  1296. this.matrix.copy( source.matrix );
  1297. this.generateMipmaps = source.generateMipmaps;
  1298. this.premultiplyAlpha = source.premultiplyAlpha;
  1299. this.flipY = source.flipY;
  1300. this.unpackAlignment = source.unpackAlignment;
  1301. this.colorSpace = source.colorSpace;
  1302. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  1303. this.needsUpdate = true;
  1304. return this;
  1305. }
  1306. toJSON( meta ) {
  1307. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  1308. if ( ! isRootObject && meta.textures[ this.uuid ] !== undefined ) {
  1309. return meta.textures[ this.uuid ];
  1310. }
  1311. const output = {
  1312. metadata: {
  1313. version: 4.6,
  1314. type: 'Texture',
  1315. generator: 'Texture.toJSON'
  1316. },
  1317. uuid: this.uuid,
  1318. name: this.name,
  1319. image: this.source.toJSON( meta ).uuid,
  1320. mapping: this.mapping,
  1321. channel: this.channel,
  1322. repeat: [ this.repeat.x, this.repeat.y ],
  1323. offset: [ this.offset.x, this.offset.y ],
  1324. center: [ this.center.x, this.center.y ],
  1325. rotation: this.rotation,
  1326. wrap: [ this.wrapS, this.wrapT ],
  1327. format: this.format,
  1328. internalFormat: this.internalFormat,
  1329. type: this.type,
  1330. colorSpace: this.colorSpace,
  1331. minFilter: this.minFilter,
  1332. magFilter: this.magFilter,
  1333. anisotropy: this.anisotropy,
  1334. flipY: this.flipY,
  1335. generateMipmaps: this.generateMipmaps,
  1336. premultiplyAlpha: this.premultiplyAlpha,
  1337. unpackAlignment: this.unpackAlignment
  1338. };
  1339. if ( Object.keys( this.userData ).length > 0 ) output.userData = this.userData;
  1340. if ( ! isRootObject ) {
  1341. meta.textures[ this.uuid ] = output;
  1342. }
  1343. return output;
  1344. }
  1345. dispose() {
  1346. this.dispatchEvent( { type: 'dispose' } );
  1347. }
  1348. transformUv( uv ) {
  1349. if ( this.mapping !== UVMapping ) return uv;
  1350. uv.applyMatrix3( this.matrix );
  1351. if ( uv.x < 0 || uv.x > 1 ) {
  1352. switch ( this.wrapS ) {
  1353. case RepeatWrapping:
  1354. uv.x = uv.x - Math.floor( uv.x );
  1355. break;
  1356. case ClampToEdgeWrapping:
  1357. uv.x = uv.x < 0 ? 0 : 1;
  1358. break;
  1359. case MirroredRepeatWrapping:
  1360. if ( Math.abs( Math.floor( uv.x ) % 2 ) === 1 ) {
  1361. uv.x = Math.ceil( uv.x ) - uv.x;
  1362. } else {
  1363. uv.x = uv.x - Math.floor( uv.x );
  1364. }
  1365. break;
  1366. }
  1367. }
  1368. if ( uv.y < 0 || uv.y > 1 ) {
  1369. switch ( this.wrapT ) {
  1370. case RepeatWrapping:
  1371. uv.y = uv.y - Math.floor( uv.y );
  1372. break;
  1373. case ClampToEdgeWrapping:
  1374. uv.y = uv.y < 0 ? 0 : 1;
  1375. break;
  1376. case MirroredRepeatWrapping:
  1377. if ( Math.abs( Math.floor( uv.y ) % 2 ) === 1 ) {
  1378. uv.y = Math.ceil( uv.y ) - uv.y;
  1379. } else {
  1380. uv.y = uv.y - Math.floor( uv.y );
  1381. }
  1382. break;
  1383. }
  1384. }
  1385. if ( this.flipY ) {
  1386. uv.y = 1 - uv.y;
  1387. }
  1388. return uv;
  1389. }
  1390. set needsUpdate( value ) {
  1391. if ( value === true ) {
  1392. this.version ++;
  1393. this.source.needsUpdate = true;
  1394. }
  1395. }
  1396. set needsPMREMUpdate( value ) {
  1397. if ( value === true ) {
  1398. this.pmremVersion ++;
  1399. }
  1400. }
  1401. }
  1402. Texture.DEFAULT_IMAGE = null;
  1403. Texture.DEFAULT_MAPPING = UVMapping;
  1404. Texture.DEFAULT_ANISOTROPY = 1;
  1405. class Vector4 {
  1406. constructor( x = 0, y = 0, z = 0, w = 1 ) {
  1407. Vector4.prototype.isVector4 = true;
  1408. this.x = x;
  1409. this.y = y;
  1410. this.z = z;
  1411. this.w = w;
  1412. }
  1413. get width() {
  1414. return this.z;
  1415. }
  1416. set width( value ) {
  1417. this.z = value;
  1418. }
  1419. get height() {
  1420. return this.w;
  1421. }
  1422. set height( value ) {
  1423. this.w = value;
  1424. }
  1425. set( x, y, z, w ) {
  1426. this.x = x;
  1427. this.y = y;
  1428. this.z = z;
  1429. this.w = w;
  1430. return this;
  1431. }
  1432. setScalar( scalar ) {
  1433. this.x = scalar;
  1434. this.y = scalar;
  1435. this.z = scalar;
  1436. this.w = scalar;
  1437. return this;
  1438. }
  1439. setX( x ) {
  1440. this.x = x;
  1441. return this;
  1442. }
  1443. setY( y ) {
  1444. this.y = y;
  1445. return this;
  1446. }
  1447. setZ( z ) {
  1448. this.z = z;
  1449. return this;
  1450. }
  1451. setW( w ) {
  1452. this.w = w;
  1453. return this;
  1454. }
  1455. setComponent( index, value ) {
  1456. switch ( index ) {
  1457. case 0: this.x = value; break;
  1458. case 1: this.y = value; break;
  1459. case 2: this.z = value; break;
  1460. case 3: this.w = value; break;
  1461. default: throw new Error( 'index is out of range: ' + index );
  1462. }
  1463. return this;
  1464. }
  1465. getComponent( index ) {
  1466. switch ( index ) {
  1467. case 0: return this.x;
  1468. case 1: return this.y;
  1469. case 2: return this.z;
  1470. case 3: return this.w;
  1471. default: throw new Error( 'index is out of range: ' + index );
  1472. }
  1473. }
  1474. clone() {
  1475. return new this.constructor( this.x, this.y, this.z, this.w );
  1476. }
  1477. copy( v ) {
  1478. this.x = v.x;
  1479. this.y = v.y;
  1480. this.z = v.z;
  1481. this.w = ( v.w !== undefined ) ? v.w : 1;
  1482. return this;
  1483. }
  1484. add( v ) {
  1485. this.x += v.x;
  1486. this.y += v.y;
  1487. this.z += v.z;
  1488. this.w += v.w;
  1489. return this;
  1490. }
  1491. addScalar( s ) {
  1492. this.x += s;
  1493. this.y += s;
  1494. this.z += s;
  1495. this.w += s;
  1496. return this;
  1497. }
  1498. addVectors( a, b ) {
  1499. this.x = a.x + b.x;
  1500. this.y = a.y + b.y;
  1501. this.z = a.z + b.z;
  1502. this.w = a.w + b.w;
  1503. return this;
  1504. }
  1505. addScaledVector( v, s ) {
  1506. this.x += v.x * s;
  1507. this.y += v.y * s;
  1508. this.z += v.z * s;
  1509. this.w += v.w * s;
  1510. return this;
  1511. }
  1512. sub( v ) {
  1513. this.x -= v.x;
  1514. this.y -= v.y;
  1515. this.z -= v.z;
  1516. this.w -= v.w;
  1517. return this;
  1518. }
  1519. subScalar( s ) {
  1520. this.x -= s;
  1521. this.y -= s;
  1522. this.z -= s;
  1523. this.w -= s;
  1524. return this;
  1525. }
  1526. subVectors( a, b ) {
  1527. this.x = a.x - b.x;
  1528. this.y = a.y - b.y;
  1529. this.z = a.z - b.z;
  1530. this.w = a.w - b.w;
  1531. return this;
  1532. }
  1533. multiply( v ) {
  1534. this.x *= v.x;
  1535. this.y *= v.y;
  1536. this.z *= v.z;
  1537. this.w *= v.w;
  1538. return this;
  1539. }
  1540. multiplyScalar( scalar ) {
  1541. this.x *= scalar;
  1542. this.y *= scalar;
  1543. this.z *= scalar;
  1544. this.w *= scalar;
  1545. return this;
  1546. }
  1547. applyMatrix4( m ) {
  1548. const x = this.x, y = this.y, z = this.z, w = this.w;
  1549. const e = m.elements;
  1550. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] * w;
  1551. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] * w;
  1552. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] * w;
  1553. this.w = e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] * w;
  1554. return this;
  1555. }
  1556. divideScalar( scalar ) {
  1557. return this.multiplyScalar( 1 / scalar );
  1558. }
  1559. setAxisAngleFromQuaternion( q ) {
  1560. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  1561. // q is assumed to be normalized
  1562. this.w = 2 * Math.acos( q.w );
  1563. const s = Math.sqrt( 1 - q.w * q.w );
  1564. if ( s < 0.0001 ) {
  1565. this.x = 1;
  1566. this.y = 0;
  1567. this.z = 0;
  1568. } else {
  1569. this.x = q.x / s;
  1570. this.y = q.y / s;
  1571. this.z = q.z / s;
  1572. }
  1573. return this;
  1574. }
  1575. setAxisAngleFromRotationMatrix( m ) {
  1576. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  1577. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1578. let angle, x, y, z; // variables for result
  1579. const epsilon = 0.01, // margin to allow for rounding errors
  1580. epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees
  1581. te = m.elements,
  1582. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  1583. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  1584. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  1585. if ( ( Math.abs( m12 - m21 ) < epsilon ) &&
  1586. ( Math.abs( m13 - m31 ) < epsilon ) &&
  1587. ( Math.abs( m23 - m32 ) < epsilon ) ) {
  1588. // singularity found
  1589. // first check for identity matrix which must have +1 for all terms
  1590. // in leading diagonal and zero in other terms
  1591. if ( ( Math.abs( m12 + m21 ) < epsilon2 ) &&
  1592. ( Math.abs( m13 + m31 ) < epsilon2 ) &&
  1593. ( Math.abs( m23 + m32 ) < epsilon2 ) &&
  1594. ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) {
  1595. // this singularity is identity matrix so angle = 0
  1596. this.set( 1, 0, 0, 0 );
  1597. return this; // zero angle, arbitrary axis
  1598. }
  1599. // otherwise this singularity is angle = 180
  1600. angle = Math.PI;
  1601. const xx = ( m11 + 1 ) / 2;
  1602. const yy = ( m22 + 1 ) / 2;
  1603. const zz = ( m33 + 1 ) / 2;
  1604. const xy = ( m12 + m21 ) / 4;
  1605. const xz = ( m13 + m31 ) / 4;
  1606. const yz = ( m23 + m32 ) / 4;
  1607. if ( ( xx > yy ) && ( xx > zz ) ) {
  1608. // m11 is the largest diagonal term
  1609. if ( xx < epsilon ) {
  1610. x = 0;
  1611. y = 0.707106781;
  1612. z = 0.707106781;
  1613. } else {
  1614. x = Math.sqrt( xx );
  1615. y = xy / x;
  1616. z = xz / x;
  1617. }
  1618. } else if ( yy > zz ) {
  1619. // m22 is the largest diagonal term
  1620. if ( yy < epsilon ) {
  1621. x = 0.707106781;
  1622. y = 0;
  1623. z = 0.707106781;
  1624. } else {
  1625. y = Math.sqrt( yy );
  1626. x = xy / y;
  1627. z = yz / y;
  1628. }
  1629. } else {
  1630. // m33 is the largest diagonal term so base result on this
  1631. if ( zz < epsilon ) {
  1632. x = 0.707106781;
  1633. y = 0.707106781;
  1634. z = 0;
  1635. } else {
  1636. z = Math.sqrt( zz );
  1637. x = xz / z;
  1638. y = yz / z;
  1639. }
  1640. }
  1641. this.set( x, y, z, angle );
  1642. return this; // return 180 deg rotation
  1643. }
  1644. // as we have reached here there are no singularities so we can handle normally
  1645. let s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 ) +
  1646. ( m13 - m31 ) * ( m13 - m31 ) +
  1647. ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize
  1648. if ( Math.abs( s ) < 0.001 ) s = 1;
  1649. // prevent divide by zero, should not happen if matrix is orthogonal and should be
  1650. // caught by singularity test above, but I've left it in just in case
  1651. this.x = ( m32 - m23 ) / s;
  1652. this.y = ( m13 - m31 ) / s;
  1653. this.z = ( m21 - m12 ) / s;
  1654. this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 );
  1655. return this;
  1656. }
  1657. setFromMatrixPosition( m ) {
  1658. const e = m.elements;
  1659. this.x = e[ 12 ];
  1660. this.y = e[ 13 ];
  1661. this.z = e[ 14 ];
  1662. this.w = e[ 15 ];
  1663. return this;
  1664. }
  1665. min( v ) {
  1666. this.x = Math.min( this.x, v.x );
  1667. this.y = Math.min( this.y, v.y );
  1668. this.z = Math.min( this.z, v.z );
  1669. this.w = Math.min( this.w, v.w );
  1670. return this;
  1671. }
  1672. max( v ) {
  1673. this.x = Math.max( this.x, v.x );
  1674. this.y = Math.max( this.y, v.y );
  1675. this.z = Math.max( this.z, v.z );
  1676. this.w = Math.max( this.w, v.w );
  1677. return this;
  1678. }
  1679. clamp( min, max ) {
  1680. // assumes min < max, componentwise
  1681. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  1682. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  1683. this.z = Math.max( min.z, Math.min( max.z, this.z ) );
  1684. this.w = Math.max( min.w, Math.min( max.w, this.w ) );
  1685. return this;
  1686. }
  1687. clampScalar( minVal, maxVal ) {
  1688. this.x = Math.max( minVal, Math.min( maxVal, this.x ) );
  1689. this.y = Math.max( minVal, Math.min( maxVal, this.y ) );
  1690. this.z = Math.max( minVal, Math.min( maxVal, this.z ) );
  1691. this.w = Math.max( minVal, Math.min( maxVal, this.w ) );
  1692. return this;
  1693. }
  1694. clampLength( min, max ) {
  1695. const length = this.length();
  1696. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  1697. }
  1698. floor() {
  1699. this.x = Math.floor( this.x );
  1700. this.y = Math.floor( this.y );
  1701. this.z = Math.floor( this.z );
  1702. this.w = Math.floor( this.w );
  1703. return this;
  1704. }
  1705. ceil() {
  1706. this.x = Math.ceil( this.x );
  1707. this.y = Math.ceil( this.y );
  1708. this.z = Math.ceil( this.z );
  1709. this.w = Math.ceil( this.w );
  1710. return this;
  1711. }
  1712. round() {
  1713. this.x = Math.round( this.x );
  1714. this.y = Math.round( this.y );
  1715. this.z = Math.round( this.z );
  1716. this.w = Math.round( this.w );
  1717. return this;
  1718. }
  1719. roundToZero() {
  1720. this.x = Math.trunc( this.x );
  1721. this.y = Math.trunc( this.y );
  1722. this.z = Math.trunc( this.z );
  1723. this.w = Math.trunc( this.w );
  1724. return this;
  1725. }
  1726. negate() {
  1727. this.x = - this.x;
  1728. this.y = - this.y;
  1729. this.z = - this.z;
  1730. this.w = - this.w;
  1731. return this;
  1732. }
  1733. dot( v ) {
  1734. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  1735. }
  1736. lengthSq() {
  1737. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  1738. }
  1739. length() {
  1740. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  1741. }
  1742. manhattanLength() {
  1743. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w );
  1744. }
  1745. normalize() {
  1746. return this.divideScalar( this.length() || 1 );
  1747. }
  1748. setLength( length ) {
  1749. return this.normalize().multiplyScalar( length );
  1750. }
  1751. lerp( v, alpha ) {
  1752. this.x += ( v.x - this.x ) * alpha;
  1753. this.y += ( v.y - this.y ) * alpha;
  1754. this.z += ( v.z - this.z ) * alpha;
  1755. this.w += ( v.w - this.w ) * alpha;
  1756. return this;
  1757. }
  1758. lerpVectors( v1, v2, alpha ) {
  1759. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  1760. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  1761. this.z = v1.z + ( v2.z - v1.z ) * alpha;
  1762. this.w = v1.w + ( v2.w - v1.w ) * alpha;
  1763. return this;
  1764. }
  1765. equals( v ) {
  1766. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );
  1767. }
  1768. fromArray( array, offset = 0 ) {
  1769. this.x = array[ offset ];
  1770. this.y = array[ offset + 1 ];
  1771. this.z = array[ offset + 2 ];
  1772. this.w = array[ offset + 3 ];
  1773. return this;
  1774. }
  1775. toArray( array = [], offset = 0 ) {
  1776. array[ offset ] = this.x;
  1777. array[ offset + 1 ] = this.y;
  1778. array[ offset + 2 ] = this.z;
  1779. array[ offset + 3 ] = this.w;
  1780. return array;
  1781. }
  1782. fromBufferAttribute( attribute, index ) {
  1783. this.x = attribute.getX( index );
  1784. this.y = attribute.getY( index );
  1785. this.z = attribute.getZ( index );
  1786. this.w = attribute.getW( index );
  1787. return this;
  1788. }
  1789. random() {
  1790. this.x = Math.random();
  1791. this.y = Math.random();
  1792. this.z = Math.random();
  1793. this.w = Math.random();
  1794. return this;
  1795. }
  1796. *[ Symbol.iterator ]() {
  1797. yield this.x;
  1798. yield this.y;
  1799. yield this.z;
  1800. yield this.w;
  1801. }
  1802. }
  1803. /*
  1804. In options, we can specify:
  1805. * Texture parameters for an auto-generated target texture
  1806. * depthBuffer/stencilBuffer: Booleans to indicate if we should generate these buffers
  1807. */
  1808. class RenderTarget extends EventDispatcher {
  1809. constructor( width = 1, height = 1, options = {} ) {
  1810. super();
  1811. this.isRenderTarget = true;
  1812. this.width = width;
  1813. this.height = height;
  1814. this.depth = 1;
  1815. this.scissor = new Vector4( 0, 0, width, height );
  1816. this.scissorTest = false;
  1817. this.viewport = new Vector4( 0, 0, width, height );
  1818. const image = { width: width, height: height, depth: 1 };
  1819. options = Object.assign( {
  1820. generateMipmaps: false,
  1821. internalFormat: null,
  1822. minFilter: LinearFilter,
  1823. depthBuffer: true,
  1824. stencilBuffer: false,
  1825. resolveDepthBuffer: true,
  1826. resolveStencilBuffer: true,
  1827. depthTexture: null,
  1828. samples: 0,
  1829. count: 1
  1830. }, options );
  1831. const texture = new Texture( image, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.colorSpace );
  1832. texture.flipY = false;
  1833. texture.generateMipmaps = options.generateMipmaps;
  1834. texture.internalFormat = options.internalFormat;
  1835. this.textures = [];
  1836. const count = options.count;
  1837. for ( let i = 0; i < count; i ++ ) {
  1838. this.textures[ i ] = texture.clone();
  1839. this.textures[ i ].isRenderTargetTexture = true;
  1840. }
  1841. this.depthBuffer = options.depthBuffer;
  1842. this.stencilBuffer = options.stencilBuffer;
  1843. this.resolveDepthBuffer = options.resolveDepthBuffer;
  1844. this.resolveStencilBuffer = options.resolveStencilBuffer;
  1845. this.depthTexture = options.depthTexture;
  1846. this.samples = options.samples;
  1847. }
  1848. get texture() {
  1849. return this.textures[ 0 ];
  1850. }
  1851. set texture( value ) {
  1852. this.textures[ 0 ] = value;
  1853. }
  1854. setSize( width, height, depth = 1 ) {
  1855. if ( this.width !== width || this.height !== height || this.depth !== depth ) {
  1856. this.width = width;
  1857. this.height = height;
  1858. this.depth = depth;
  1859. for ( let i = 0, il = this.textures.length; i < il; i ++ ) {
  1860. this.textures[ i ].image.width = width;
  1861. this.textures[ i ].image.height = height;
  1862. this.textures[ i ].image.depth = depth;
  1863. }
  1864. this.dispose();
  1865. }
  1866. this.viewport.set( 0, 0, width, height );
  1867. this.scissor.set( 0, 0, width, height );
  1868. }
  1869. clone() {
  1870. return new this.constructor().copy( this );
  1871. }
  1872. copy( source ) {
  1873. this.width = source.width;
  1874. this.height = source.height;
  1875. this.depth = source.depth;
  1876. this.scissor.copy( source.scissor );
  1877. this.scissorTest = source.scissorTest;
  1878. this.viewport.copy( source.viewport );
  1879. this.textures.length = 0;
  1880. for ( let i = 0, il = source.textures.length; i < il; i ++ ) {
  1881. this.textures[ i ] = source.textures[ i ].clone();
  1882. this.textures[ i ].isRenderTargetTexture = true;
  1883. }
  1884. // ensure image object is not shared, see #20328
  1885. const image = Object.assign( {}, source.texture.image );
  1886. this.texture.source = new Source( image );
  1887. this.depthBuffer = source.depthBuffer;
  1888. this.stencilBuffer = source.stencilBuffer;
  1889. this.resolveDepthBuffer = source.resolveDepthBuffer;
  1890. this.resolveStencilBuffer = source.resolveStencilBuffer;
  1891. if ( source.depthTexture !== null ) this.depthTexture = source.depthTexture.clone();
  1892. this.samples = source.samples;
  1893. return this;
  1894. }
  1895. dispose() {
  1896. this.dispatchEvent( { type: 'dispose' } );
  1897. }
  1898. }
  1899. class WebGLRenderTarget extends RenderTarget {
  1900. constructor( width = 1, height = 1, options = {} ) {
  1901. super( width, height, options );
  1902. this.isWebGLRenderTarget = true;
  1903. }
  1904. }
  1905. class DataArrayTexture extends Texture {
  1906. constructor( data = null, width = 1, height = 1, depth = 1 ) {
  1907. super( null );
  1908. this.isDataArrayTexture = true;
  1909. this.image = { data, width, height, depth };
  1910. this.magFilter = NearestFilter;
  1911. this.minFilter = NearestFilter;
  1912. this.wrapR = ClampToEdgeWrapping;
  1913. this.generateMipmaps = false;
  1914. this.flipY = false;
  1915. this.unpackAlignment = 1;
  1916. this.layerUpdates = new Set();
  1917. }
  1918. addLayerUpdate( layerIndex ) {
  1919. this.layerUpdates.add( layerIndex );
  1920. }
  1921. clearLayerUpdates() {
  1922. this.layerUpdates.clear();
  1923. }
  1924. }
  1925. class WebGLArrayRenderTarget extends WebGLRenderTarget {
  1926. constructor( width = 1, height = 1, depth = 1, options = {} ) {
  1927. super( width, height, options );
  1928. this.isWebGLArrayRenderTarget = true;
  1929. this.depth = depth;
  1930. this.texture = new DataArrayTexture( null, width, height, depth );
  1931. this.texture.isRenderTargetTexture = true;
  1932. }
  1933. }
  1934. class Data3DTexture extends Texture {
  1935. constructor( data = null, width = 1, height = 1, depth = 1 ) {
  1936. // We're going to add .setXXX() methods for setting properties later.
  1937. // Users can still set in DataTexture3D directly.
  1938. //
  1939. // const texture = new THREE.DataTexture3D( data, width, height, depth );
  1940. // texture.anisotropy = 16;
  1941. //
  1942. // See #14839
  1943. super( null );
  1944. this.isData3DTexture = true;
  1945. this.image = { data, width, height, depth };
  1946. this.magFilter = NearestFilter;
  1947. this.minFilter = NearestFilter;
  1948. this.wrapR = ClampToEdgeWrapping;
  1949. this.generateMipmaps = false;
  1950. this.flipY = false;
  1951. this.unpackAlignment = 1;
  1952. }
  1953. }
  1954. class WebGL3DRenderTarget extends WebGLRenderTarget {
  1955. constructor( width = 1, height = 1, depth = 1, options = {} ) {
  1956. super( width, height, options );
  1957. this.isWebGL3DRenderTarget = true;
  1958. this.depth = depth;
  1959. this.texture = new Data3DTexture( null, width, height, depth );
  1960. this.texture.isRenderTargetTexture = true;
  1961. }
  1962. }
  1963. class Quaternion {
  1964. constructor( x = 0, y = 0, z = 0, w = 1 ) {
  1965. this.isQuaternion = true;
  1966. this._x = x;
  1967. this._y = y;
  1968. this._z = z;
  1969. this._w = w;
  1970. }
  1971. static slerpFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t ) {
  1972. // fuzz-free, array-based Quaternion SLERP operation
  1973. let x0 = src0[ srcOffset0 + 0 ],
  1974. y0 = src0[ srcOffset0 + 1 ],
  1975. z0 = src0[ srcOffset0 + 2 ],
  1976. w0 = src0[ srcOffset0 + 3 ];
  1977. const x1 = src1[ srcOffset1 + 0 ],
  1978. y1 = src1[ srcOffset1 + 1 ],
  1979. z1 = src1[ srcOffset1 + 2 ],
  1980. w1 = src1[ srcOffset1 + 3 ];
  1981. if ( t === 0 ) {
  1982. dst[ dstOffset + 0 ] = x0;
  1983. dst[ dstOffset + 1 ] = y0;
  1984. dst[ dstOffset + 2 ] = z0;
  1985. dst[ dstOffset + 3 ] = w0;
  1986. return;
  1987. }
  1988. if ( t === 1 ) {
  1989. dst[ dstOffset + 0 ] = x1;
  1990. dst[ dstOffset + 1 ] = y1;
  1991. dst[ dstOffset + 2 ] = z1;
  1992. dst[ dstOffset + 3 ] = w1;
  1993. return;
  1994. }
  1995. if ( w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1 ) {
  1996. let s = 1 - t;
  1997. const cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1,
  1998. dir = ( cos >= 0 ? 1 : - 1 ),
  1999. sqrSin = 1 - cos * cos;
  2000. // Skip the Slerp for tiny steps to avoid numeric problems:
  2001. if ( sqrSin > Number.EPSILON ) {
  2002. const sin = Math.sqrt( sqrSin ),
  2003. len = Math.atan2( sin, cos * dir );
  2004. s = Math.sin( s * len ) / sin;
  2005. t = Math.sin( t * len ) / sin;
  2006. }
  2007. const tDir = t * dir;
  2008. x0 = x0 * s + x1 * tDir;
  2009. y0 = y0 * s + y1 * tDir;
  2010. z0 = z0 * s + z1 * tDir;
  2011. w0 = w0 * s + w1 * tDir;
  2012. // Normalize in case we just did a lerp:
  2013. if ( s === 1 - t ) {
  2014. const f = 1 / Math.sqrt( x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0 );
  2015. x0 *= f;
  2016. y0 *= f;
  2017. z0 *= f;
  2018. w0 *= f;
  2019. }
  2020. }
  2021. dst[ dstOffset ] = x0;
  2022. dst[ dstOffset + 1 ] = y0;
  2023. dst[ dstOffset + 2 ] = z0;
  2024. dst[ dstOffset + 3 ] = w0;
  2025. }
  2026. static multiplyQuaternionsFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1 ) {
  2027. const x0 = src0[ srcOffset0 ];
  2028. const y0 = src0[ srcOffset0 + 1 ];
  2029. const z0 = src0[ srcOffset0 + 2 ];
  2030. const w0 = src0[ srcOffset0 + 3 ];
  2031. const x1 = src1[ srcOffset1 ];
  2032. const y1 = src1[ srcOffset1 + 1 ];
  2033. const z1 = src1[ srcOffset1 + 2 ];
  2034. const w1 = src1[ srcOffset1 + 3 ];
  2035. dst[ dstOffset ] = x0 * w1 + w0 * x1 + y0 * z1 - z0 * y1;
  2036. dst[ dstOffset + 1 ] = y0 * w1 + w0 * y1 + z0 * x1 - x0 * z1;
  2037. dst[ dstOffset + 2 ] = z0 * w1 + w0 * z1 + x0 * y1 - y0 * x1;
  2038. dst[ dstOffset + 3 ] = w0 * w1 - x0 * x1 - y0 * y1 - z0 * z1;
  2039. return dst;
  2040. }
  2041. get x() {
  2042. return this._x;
  2043. }
  2044. set x( value ) {
  2045. this._x = value;
  2046. this._onChangeCallback();
  2047. }
  2048. get y() {
  2049. return this._y;
  2050. }
  2051. set y( value ) {
  2052. this._y = value;
  2053. this._onChangeCallback();
  2054. }
  2055. get z() {
  2056. return this._z;
  2057. }
  2058. set z( value ) {
  2059. this._z = value;
  2060. this._onChangeCallback();
  2061. }
  2062. get w() {
  2063. return this._w;
  2064. }
  2065. set w( value ) {
  2066. this._w = value;
  2067. this._onChangeCallback();
  2068. }
  2069. set( x, y, z, w ) {
  2070. this._x = x;
  2071. this._y = y;
  2072. this._z = z;
  2073. this._w = w;
  2074. this._onChangeCallback();
  2075. return this;
  2076. }
  2077. clone() {
  2078. return new this.constructor( this._x, this._y, this._z, this._w );
  2079. }
  2080. copy( quaternion ) {
  2081. this._x = quaternion.x;
  2082. this._y = quaternion.y;
  2083. this._z = quaternion.z;
  2084. this._w = quaternion.w;
  2085. this._onChangeCallback();
  2086. return this;
  2087. }
  2088. setFromEuler( euler, update = true ) {
  2089. const x = euler._x, y = euler._y, z = euler._z, order = euler._order;
  2090. // http://www.mathworks.com/matlabcentral/fileexchange/
  2091. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  2092. // content/SpinCalc.m
  2093. const cos = Math.cos;
  2094. const sin = Math.sin;
  2095. const c1 = cos( x / 2 );
  2096. const c2 = cos( y / 2 );
  2097. const c3 = cos( z / 2 );
  2098. const s1 = sin( x / 2 );
  2099. const s2 = sin( y / 2 );
  2100. const s3 = sin( z / 2 );
  2101. switch ( order ) {
  2102. case 'XYZ':
  2103. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  2104. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  2105. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  2106. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  2107. break;
  2108. case 'YXZ':
  2109. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  2110. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  2111. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  2112. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  2113. break;
  2114. case 'ZXY':
  2115. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  2116. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  2117. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  2118. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  2119. break;
  2120. case 'ZYX':
  2121. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  2122. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  2123. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  2124. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  2125. break;
  2126. case 'YZX':
  2127. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  2128. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  2129. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  2130. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  2131. break;
  2132. case 'XZY':
  2133. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  2134. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  2135. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  2136. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  2137. break;
  2138. default:
  2139. console.warn( 'THREE.Quaternion: .setFromEuler() encountered an unknown order: ' + order );
  2140. }
  2141. if ( update === true ) this._onChangeCallback();
  2142. return this;
  2143. }
  2144. setFromAxisAngle( axis, angle ) {
  2145. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  2146. // assumes axis is normalized
  2147. const halfAngle = angle / 2, s = Math.sin( halfAngle );
  2148. this._x = axis.x * s;
  2149. this._y = axis.y * s;
  2150. this._z = axis.z * s;
  2151. this._w = Math.cos( halfAngle );
  2152. this._onChangeCallback();
  2153. return this;
  2154. }
  2155. setFromRotationMatrix( m ) {
  2156. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  2157. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  2158. const te = m.elements,
  2159. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  2160. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  2161. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ],
  2162. trace = m11 + m22 + m33;
  2163. if ( trace > 0 ) {
  2164. const s = 0.5 / Math.sqrt( trace + 1.0 );
  2165. this._w = 0.25 / s;
  2166. this._x = ( m32 - m23 ) * s;
  2167. this._y = ( m13 - m31 ) * s;
  2168. this._z = ( m21 - m12 ) * s;
  2169. } else if ( m11 > m22 && m11 > m33 ) {
  2170. const s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );
  2171. this._w = ( m32 - m23 ) / s;
  2172. this._x = 0.25 * s;
  2173. this._y = ( m12 + m21 ) / s;
  2174. this._z = ( m13 + m31 ) / s;
  2175. } else if ( m22 > m33 ) {
  2176. const s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );
  2177. this._w = ( m13 - m31 ) / s;
  2178. this._x = ( m12 + m21 ) / s;
  2179. this._y = 0.25 * s;
  2180. this._z = ( m23 + m32 ) / s;
  2181. } else {
  2182. const s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );
  2183. this._w = ( m21 - m12 ) / s;
  2184. this._x = ( m13 + m31 ) / s;
  2185. this._y = ( m23 + m32 ) / s;
  2186. this._z = 0.25 * s;
  2187. }
  2188. this._onChangeCallback();
  2189. return this;
  2190. }
  2191. setFromUnitVectors( vFrom, vTo ) {
  2192. // assumes direction vectors vFrom and vTo are normalized
  2193. let r = vFrom.dot( vTo ) + 1;
  2194. if ( r < Number.EPSILON ) {
  2195. // vFrom and vTo point in opposite directions
  2196. r = 0;
  2197. if ( Math.abs( vFrom.x ) > Math.abs( vFrom.z ) ) {
  2198. this._x = - vFrom.y;
  2199. this._y = vFrom.x;
  2200. this._z = 0;
  2201. this._w = r;
  2202. } else {
  2203. this._x = 0;
  2204. this._y = - vFrom.z;
  2205. this._z = vFrom.y;
  2206. this._w = r;
  2207. }
  2208. } else {
  2209. // crossVectors( vFrom, vTo ); // inlined to avoid cyclic dependency on Vector3
  2210. this._x = vFrom.y * vTo.z - vFrom.z * vTo.y;
  2211. this._y = vFrom.z * vTo.x - vFrom.x * vTo.z;
  2212. this._z = vFrom.x * vTo.y - vFrom.y * vTo.x;
  2213. this._w = r;
  2214. }
  2215. return this.normalize();
  2216. }
  2217. angleTo( q ) {
  2218. return 2 * Math.acos( Math.abs( clamp$1( this.dot( q ), - 1, 1 ) ) );
  2219. }
  2220. rotateTowards( q, step ) {
  2221. const angle = this.angleTo( q );
  2222. if ( angle === 0 ) return this;
  2223. const t = Math.min( 1, step / angle );
  2224. this.slerp( q, t );
  2225. return this;
  2226. }
  2227. identity() {
  2228. return this.set( 0, 0, 0, 1 );
  2229. }
  2230. invert() {
  2231. // quaternion is assumed to have unit length
  2232. return this.conjugate();
  2233. }
  2234. conjugate() {
  2235. this._x *= - 1;
  2236. this._y *= - 1;
  2237. this._z *= - 1;
  2238. this._onChangeCallback();
  2239. return this;
  2240. }
  2241. dot( v ) {
  2242. return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w;
  2243. }
  2244. lengthSq() {
  2245. return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  2246. }
  2247. length() {
  2248. return Math.sqrt( this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w );
  2249. }
  2250. normalize() {
  2251. let l = this.length();
  2252. if ( l === 0 ) {
  2253. this._x = 0;
  2254. this._y = 0;
  2255. this._z = 0;
  2256. this._w = 1;
  2257. } else {
  2258. l = 1 / l;
  2259. this._x = this._x * l;
  2260. this._y = this._y * l;
  2261. this._z = this._z * l;
  2262. this._w = this._w * l;
  2263. }
  2264. this._onChangeCallback();
  2265. return this;
  2266. }
  2267. multiply( q ) {
  2268. return this.multiplyQuaternions( this, q );
  2269. }
  2270. premultiply( q ) {
  2271. return this.multiplyQuaternions( q, this );
  2272. }
  2273. multiplyQuaternions( a, b ) {
  2274. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  2275. const qax = a._x, qay = a._y, qaz = a._z, qaw = a._w;
  2276. const qbx = b._x, qby = b._y, qbz = b._z, qbw = b._w;
  2277. this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  2278. this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  2279. this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  2280. this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  2281. this._onChangeCallback();
  2282. return this;
  2283. }
  2284. slerp( qb, t ) {
  2285. if ( t === 0 ) return this;
  2286. if ( t === 1 ) return this.copy( qb );
  2287. const x = this._x, y = this._y, z = this._z, w = this._w;
  2288. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  2289. let cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z;
  2290. if ( cosHalfTheta < 0 ) {
  2291. this._w = - qb._w;
  2292. this._x = - qb._x;
  2293. this._y = - qb._y;
  2294. this._z = - qb._z;
  2295. cosHalfTheta = - cosHalfTheta;
  2296. } else {
  2297. this.copy( qb );
  2298. }
  2299. if ( cosHalfTheta >= 1.0 ) {
  2300. this._w = w;
  2301. this._x = x;
  2302. this._y = y;
  2303. this._z = z;
  2304. return this;
  2305. }
  2306. const sqrSinHalfTheta = 1.0 - cosHalfTheta * cosHalfTheta;
  2307. if ( sqrSinHalfTheta <= Number.EPSILON ) {
  2308. const s = 1 - t;
  2309. this._w = s * w + t * this._w;
  2310. this._x = s * x + t * this._x;
  2311. this._y = s * y + t * this._y;
  2312. this._z = s * z + t * this._z;
  2313. this.normalize(); // normalize calls _onChangeCallback()
  2314. return this;
  2315. }
  2316. const sinHalfTheta = Math.sqrt( sqrSinHalfTheta );
  2317. const halfTheta = Math.atan2( sinHalfTheta, cosHalfTheta );
  2318. const ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta,
  2319. ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  2320. this._w = ( w * ratioA + this._w * ratioB );
  2321. this._x = ( x * ratioA + this._x * ratioB );
  2322. this._y = ( y * ratioA + this._y * ratioB );
  2323. this._z = ( z * ratioA + this._z * ratioB );
  2324. this._onChangeCallback();
  2325. return this;
  2326. }
  2327. slerpQuaternions( qa, qb, t ) {
  2328. return this.copy( qa ).slerp( qb, t );
  2329. }
  2330. random() {
  2331. // sets this quaternion to a uniform random unit quaternnion
  2332. // Ken Shoemake
  2333. // Uniform random rotations
  2334. // D. Kirk, editor, Graphics Gems III, pages 124-132. Academic Press, New York, 1992.
  2335. const theta1 = 2 * Math.PI * Math.random();
  2336. const theta2 = 2 * Math.PI * Math.random();
  2337. const x0 = Math.random();
  2338. const r1 = Math.sqrt( 1 - x0 );
  2339. const r2 = Math.sqrt( x0 );
  2340. return this.set(
  2341. r1 * Math.sin( theta1 ),
  2342. r1 * Math.cos( theta1 ),
  2343. r2 * Math.sin( theta2 ),
  2344. r2 * Math.cos( theta2 ),
  2345. );
  2346. }
  2347. equals( quaternion ) {
  2348. return ( quaternion._x === this._x ) && ( quaternion._y === this._y ) && ( quaternion._z === this._z ) && ( quaternion._w === this._w );
  2349. }
  2350. fromArray( array, offset = 0 ) {
  2351. this._x = array[ offset ];
  2352. this._y = array[ offset + 1 ];
  2353. this._z = array[ offset + 2 ];
  2354. this._w = array[ offset + 3 ];
  2355. this._onChangeCallback();
  2356. return this;
  2357. }
  2358. toArray( array = [], offset = 0 ) {
  2359. array[ offset ] = this._x;
  2360. array[ offset + 1 ] = this._y;
  2361. array[ offset + 2 ] = this._z;
  2362. array[ offset + 3 ] = this._w;
  2363. return array;
  2364. }
  2365. fromBufferAttribute( attribute, index ) {
  2366. this._x = attribute.getX( index );
  2367. this._y = attribute.getY( index );
  2368. this._z = attribute.getZ( index );
  2369. this._w = attribute.getW( index );
  2370. this._onChangeCallback();
  2371. return this;
  2372. }
  2373. toJSON() {
  2374. return this.toArray();
  2375. }
  2376. _onChange( callback ) {
  2377. this._onChangeCallback = callback;
  2378. return this;
  2379. }
  2380. _onChangeCallback() {}
  2381. *[ Symbol.iterator ]() {
  2382. yield this._x;
  2383. yield this._y;
  2384. yield this._z;
  2385. yield this._w;
  2386. }
  2387. }
  2388. class Vector3 {
  2389. constructor( x = 0, y = 0, z = 0 ) {
  2390. Vector3.prototype.isVector3 = true;
  2391. this.x = x;
  2392. this.y = y;
  2393. this.z = z;
  2394. }
  2395. set( x, y, z ) {
  2396. if ( z === undefined ) z = this.z; // sprite.scale.set(x,y)
  2397. this.x = x;
  2398. this.y = y;
  2399. this.z = z;
  2400. return this;
  2401. }
  2402. setScalar( scalar ) {
  2403. this.x = scalar;
  2404. this.y = scalar;
  2405. this.z = scalar;
  2406. return this;
  2407. }
  2408. setX( x ) {
  2409. this.x = x;
  2410. return this;
  2411. }
  2412. setY( y ) {
  2413. this.y = y;
  2414. return this;
  2415. }
  2416. setZ( z ) {
  2417. this.z = z;
  2418. return this;
  2419. }
  2420. setComponent( index, value ) {
  2421. switch ( index ) {
  2422. case 0: this.x = value; break;
  2423. case 1: this.y = value; break;
  2424. case 2: this.z = value; break;
  2425. default: throw new Error( 'index is out of range: ' + index );
  2426. }
  2427. return this;
  2428. }
  2429. getComponent( index ) {
  2430. switch ( index ) {
  2431. case 0: return this.x;
  2432. case 1: return this.y;
  2433. case 2: return this.z;
  2434. default: throw new Error( 'index is out of range: ' + index );
  2435. }
  2436. }
  2437. clone() {
  2438. return new this.constructor( this.x, this.y, this.z );
  2439. }
  2440. copy( v ) {
  2441. this.x = v.x;
  2442. this.y = v.y;
  2443. this.z = v.z;
  2444. return this;
  2445. }
  2446. add( v ) {
  2447. this.x += v.x;
  2448. this.y += v.y;
  2449. this.z += v.z;
  2450. return this;
  2451. }
  2452. addScalar( s ) {
  2453. this.x += s;
  2454. this.y += s;
  2455. this.z += s;
  2456. return this;
  2457. }
  2458. addVectors( a, b ) {
  2459. this.x = a.x + b.x;
  2460. this.y = a.y + b.y;
  2461. this.z = a.z + b.z;
  2462. return this;
  2463. }
  2464. addScaledVector( v, s ) {
  2465. this.x += v.x * s;
  2466. this.y += v.y * s;
  2467. this.z += v.z * s;
  2468. return this;
  2469. }
  2470. sub( v ) {
  2471. this.x -= v.x;
  2472. this.y -= v.y;
  2473. this.z -= v.z;
  2474. return this;
  2475. }
  2476. subScalar( s ) {
  2477. this.x -= s;
  2478. this.y -= s;
  2479. this.z -= s;
  2480. return this;
  2481. }
  2482. subVectors( a, b ) {
  2483. this.x = a.x - b.x;
  2484. this.y = a.y - b.y;
  2485. this.z = a.z - b.z;
  2486. return this;
  2487. }
  2488. multiply( v ) {
  2489. this.x *= v.x;
  2490. this.y *= v.y;
  2491. this.z *= v.z;
  2492. return this;
  2493. }
  2494. multiplyScalar( scalar ) {
  2495. this.x *= scalar;
  2496. this.y *= scalar;
  2497. this.z *= scalar;
  2498. return this;
  2499. }
  2500. multiplyVectors( a, b ) {
  2501. this.x = a.x * b.x;
  2502. this.y = a.y * b.y;
  2503. this.z = a.z * b.z;
  2504. return this;
  2505. }
  2506. applyEuler( euler ) {
  2507. return this.applyQuaternion( _quaternion$4.setFromEuler( euler ) );
  2508. }
  2509. applyAxisAngle( axis, angle ) {
  2510. return this.applyQuaternion( _quaternion$4.setFromAxisAngle( axis, angle ) );
  2511. }
  2512. applyMatrix3( m ) {
  2513. const x = this.x, y = this.y, z = this.z;
  2514. const e = m.elements;
  2515. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ] * z;
  2516. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ] * z;
  2517. this.z = e[ 2 ] * x + e[ 5 ] * y + e[ 8 ] * z;
  2518. return this;
  2519. }
  2520. applyNormalMatrix( m ) {
  2521. return this.applyMatrix3( m ).normalize();
  2522. }
  2523. applyMatrix4( m ) {
  2524. const x = this.x, y = this.y, z = this.z;
  2525. const e = m.elements;
  2526. const w = 1 / ( e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] );
  2527. this.x = ( e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] ) * w;
  2528. this.y = ( e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] ) * w;
  2529. this.z = ( e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] ) * w;
  2530. return this;
  2531. }
  2532. applyQuaternion( q ) {
  2533. // quaternion q is assumed to have unit length
  2534. const vx = this.x, vy = this.y, vz = this.z;
  2535. const qx = q.x, qy = q.y, qz = q.z, qw = q.w;
  2536. // t = 2 * cross( q.xyz, v );
  2537. const tx = 2 * ( qy * vz - qz * vy );
  2538. const ty = 2 * ( qz * vx - qx * vz );
  2539. const tz = 2 * ( qx * vy - qy * vx );
  2540. // v + q.w * t + cross( q.xyz, t );
  2541. this.x = vx + qw * tx + qy * tz - qz * ty;
  2542. this.y = vy + qw * ty + qz * tx - qx * tz;
  2543. this.z = vz + qw * tz + qx * ty - qy * tx;
  2544. return this;
  2545. }
  2546. project( camera ) {
  2547. return this.applyMatrix4( camera.matrixWorldInverse ).applyMatrix4( camera.projectionMatrix );
  2548. }
  2549. unproject( camera ) {
  2550. return this.applyMatrix4( camera.projectionMatrixInverse ).applyMatrix4( camera.matrixWorld );
  2551. }
  2552. transformDirection( m ) {
  2553. // input: THREE.Matrix4 affine matrix
  2554. // vector interpreted as a direction
  2555. const x = this.x, y = this.y, z = this.z;
  2556. const e = m.elements;
  2557. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z;
  2558. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z;
  2559. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z;
  2560. return this.normalize();
  2561. }
  2562. divide( v ) {
  2563. this.x /= v.x;
  2564. this.y /= v.y;
  2565. this.z /= v.z;
  2566. return this;
  2567. }
  2568. divideScalar( scalar ) {
  2569. return this.multiplyScalar( 1 / scalar );
  2570. }
  2571. min( v ) {
  2572. this.x = Math.min( this.x, v.x );
  2573. this.y = Math.min( this.y, v.y );
  2574. this.z = Math.min( this.z, v.z );
  2575. return this;
  2576. }
  2577. max( v ) {
  2578. this.x = Math.max( this.x, v.x );
  2579. this.y = Math.max( this.y, v.y );
  2580. this.z = Math.max( this.z, v.z );
  2581. return this;
  2582. }
  2583. clamp( min, max ) {
  2584. // assumes min < max, componentwise
  2585. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  2586. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  2587. this.z = Math.max( min.z, Math.min( max.z, this.z ) );
  2588. return this;
  2589. }
  2590. clampScalar( minVal, maxVal ) {
  2591. this.x = Math.max( minVal, Math.min( maxVal, this.x ) );
  2592. this.y = Math.max( minVal, Math.min( maxVal, this.y ) );
  2593. this.z = Math.max( minVal, Math.min( maxVal, this.z ) );
  2594. return this;
  2595. }
  2596. clampLength( min, max ) {
  2597. const length = this.length();
  2598. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  2599. }
  2600. floor() {
  2601. this.x = Math.floor( this.x );
  2602. this.y = Math.floor( this.y );
  2603. this.z = Math.floor( this.z );
  2604. return this;
  2605. }
  2606. ceil() {
  2607. this.x = Math.ceil( this.x );
  2608. this.y = Math.ceil( this.y );
  2609. this.z = Math.ceil( this.z );
  2610. return this;
  2611. }
  2612. round() {
  2613. this.x = Math.round( this.x );
  2614. this.y = Math.round( this.y );
  2615. this.z = Math.round( this.z );
  2616. return this;
  2617. }
  2618. roundToZero() {
  2619. this.x = Math.trunc( this.x );
  2620. this.y = Math.trunc( this.y );
  2621. this.z = Math.trunc( this.z );
  2622. return this;
  2623. }
  2624. negate() {
  2625. this.x = - this.x;
  2626. this.y = - this.y;
  2627. this.z = - this.z;
  2628. return this;
  2629. }
  2630. dot( v ) {
  2631. return this.x * v.x + this.y * v.y + this.z * v.z;
  2632. }
  2633. // TODO lengthSquared?
  2634. lengthSq() {
  2635. return this.x * this.x + this.y * this.y + this.z * this.z;
  2636. }
  2637. length() {
  2638. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z );
  2639. }
  2640. manhattanLength() {
  2641. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );
  2642. }
  2643. normalize() {
  2644. return this.divideScalar( this.length() || 1 );
  2645. }
  2646. setLength( length ) {
  2647. return this.normalize().multiplyScalar( length );
  2648. }
  2649. lerp( v, alpha ) {
  2650. this.x += ( v.x - this.x ) * alpha;
  2651. this.y += ( v.y - this.y ) * alpha;
  2652. this.z += ( v.z - this.z ) * alpha;
  2653. return this;
  2654. }
  2655. lerpVectors( v1, v2, alpha ) {
  2656. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  2657. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  2658. this.z = v1.z + ( v2.z - v1.z ) * alpha;
  2659. return this;
  2660. }
  2661. cross( v ) {
  2662. return this.crossVectors( this, v );
  2663. }
  2664. crossVectors( a, b ) {
  2665. const ax = a.x, ay = a.y, az = a.z;
  2666. const bx = b.x, by = b.y, bz = b.z;
  2667. this.x = ay * bz - az * by;
  2668. this.y = az * bx - ax * bz;
  2669. this.z = ax * by - ay * bx;
  2670. return this;
  2671. }
  2672. projectOnVector( v ) {
  2673. const denominator = v.lengthSq();
  2674. if ( denominator === 0 ) return this.set( 0, 0, 0 );
  2675. const scalar = v.dot( this ) / denominator;
  2676. return this.copy( v ).multiplyScalar( scalar );
  2677. }
  2678. projectOnPlane( planeNormal ) {
  2679. _vector$c.copy( this ).projectOnVector( planeNormal );
  2680. return this.sub( _vector$c );
  2681. }
  2682. reflect( normal ) {
  2683. // reflect incident vector off plane orthogonal to normal
  2684. // normal is assumed to have unit length
  2685. return this.sub( _vector$c.copy( normal ).multiplyScalar( 2 * this.dot( normal ) ) );
  2686. }
  2687. angleTo( v ) {
  2688. const denominator = Math.sqrt( this.lengthSq() * v.lengthSq() );
  2689. if ( denominator === 0 ) return Math.PI / 2;
  2690. const theta = this.dot( v ) / denominator;
  2691. // clamp, to handle numerical problems
  2692. return Math.acos( clamp$1( theta, - 1, 1 ) );
  2693. }
  2694. distanceTo( v ) {
  2695. return Math.sqrt( this.distanceToSquared( v ) );
  2696. }
  2697. distanceToSquared( v ) {
  2698. const dx = this.x - v.x, dy = this.y - v.y, dz = this.z - v.z;
  2699. return dx * dx + dy * dy + dz * dz;
  2700. }
  2701. manhattanDistanceTo( v ) {
  2702. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y ) + Math.abs( this.z - v.z );
  2703. }
  2704. setFromSpherical( s ) {
  2705. return this.setFromSphericalCoords( s.radius, s.phi, s.theta );
  2706. }
  2707. setFromSphericalCoords( radius, phi, theta ) {
  2708. const sinPhiRadius = Math.sin( phi ) * radius;
  2709. this.x = sinPhiRadius * Math.sin( theta );
  2710. this.y = Math.cos( phi ) * radius;
  2711. this.z = sinPhiRadius * Math.cos( theta );
  2712. return this;
  2713. }
  2714. setFromCylindrical( c ) {
  2715. return this.setFromCylindricalCoords( c.radius, c.theta, c.y );
  2716. }
  2717. setFromCylindricalCoords( radius, theta, y ) {
  2718. this.x = radius * Math.sin( theta );
  2719. this.y = y;
  2720. this.z = radius * Math.cos( theta );
  2721. return this;
  2722. }
  2723. setFromMatrixPosition( m ) {
  2724. const e = m.elements;
  2725. this.x = e[ 12 ];
  2726. this.y = e[ 13 ];
  2727. this.z = e[ 14 ];
  2728. return this;
  2729. }
  2730. setFromMatrixScale( m ) {
  2731. const sx = this.setFromMatrixColumn( m, 0 ).length();
  2732. const sy = this.setFromMatrixColumn( m, 1 ).length();
  2733. const sz = this.setFromMatrixColumn( m, 2 ).length();
  2734. this.x = sx;
  2735. this.y = sy;
  2736. this.z = sz;
  2737. return this;
  2738. }
  2739. setFromMatrixColumn( m, index ) {
  2740. return this.fromArray( m.elements, index * 4 );
  2741. }
  2742. setFromMatrix3Column( m, index ) {
  2743. return this.fromArray( m.elements, index * 3 );
  2744. }
  2745. setFromEuler( e ) {
  2746. this.x = e._x;
  2747. this.y = e._y;
  2748. this.z = e._z;
  2749. return this;
  2750. }
  2751. setFromColor( c ) {
  2752. this.x = c.r;
  2753. this.y = c.g;
  2754. this.z = c.b;
  2755. return this;
  2756. }
  2757. equals( v ) {
  2758. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
  2759. }
  2760. fromArray( array, offset = 0 ) {
  2761. this.x = array[ offset ];
  2762. this.y = array[ offset + 1 ];
  2763. this.z = array[ offset + 2 ];
  2764. return this;
  2765. }
  2766. toArray( array = [], offset = 0 ) {
  2767. array[ offset ] = this.x;
  2768. array[ offset + 1 ] = this.y;
  2769. array[ offset + 2 ] = this.z;
  2770. return array;
  2771. }
  2772. fromBufferAttribute( attribute, index ) {
  2773. this.x = attribute.getX( index );
  2774. this.y = attribute.getY( index );
  2775. this.z = attribute.getZ( index );
  2776. return this;
  2777. }
  2778. random() {
  2779. this.x = Math.random();
  2780. this.y = Math.random();
  2781. this.z = Math.random();
  2782. return this;
  2783. }
  2784. randomDirection() {
  2785. // https://mathworld.wolfram.com/SpherePointPicking.html
  2786. const theta = Math.random() * Math.PI * 2;
  2787. const u = Math.random() * 2 - 1;
  2788. const c = Math.sqrt( 1 - u * u );
  2789. this.x = c * Math.cos( theta );
  2790. this.y = u;
  2791. this.z = c * Math.sin( theta );
  2792. return this;
  2793. }
  2794. *[ Symbol.iterator ]() {
  2795. yield this.x;
  2796. yield this.y;
  2797. yield this.z;
  2798. }
  2799. }
  2800. const _vector$c = /*@__PURE__*/ new Vector3();
  2801. const _quaternion$4 = /*@__PURE__*/ new Quaternion();
  2802. class Box3 {
  2803. constructor( min = new Vector3( + Infinity, + Infinity, + Infinity ), max = new Vector3( - Infinity, - Infinity, - Infinity ) ) {
  2804. this.isBox3 = true;
  2805. this.min = min;
  2806. this.max = max;
  2807. }
  2808. set( min, max ) {
  2809. this.min.copy( min );
  2810. this.max.copy( max );
  2811. return this;
  2812. }
  2813. setFromArray( array ) {
  2814. this.makeEmpty();
  2815. for ( let i = 0, il = array.length; i < il; i += 3 ) {
  2816. this.expandByPoint( _vector$b.fromArray( array, i ) );
  2817. }
  2818. return this;
  2819. }
  2820. setFromBufferAttribute( attribute ) {
  2821. this.makeEmpty();
  2822. for ( let i = 0, il = attribute.count; i < il; i ++ ) {
  2823. this.expandByPoint( _vector$b.fromBufferAttribute( attribute, i ) );
  2824. }
  2825. return this;
  2826. }
  2827. setFromPoints( points ) {
  2828. this.makeEmpty();
  2829. for ( let i = 0, il = points.length; i < il; i ++ ) {
  2830. this.expandByPoint( points[ i ] );
  2831. }
  2832. return this;
  2833. }
  2834. setFromCenterAndSize( center, size ) {
  2835. const halfSize = _vector$b.copy( size ).multiplyScalar( 0.5 );
  2836. this.min.copy( center ).sub( halfSize );
  2837. this.max.copy( center ).add( halfSize );
  2838. return this;
  2839. }
  2840. setFromObject( object, precise = false ) {
  2841. this.makeEmpty();
  2842. return this.expandByObject( object, precise );
  2843. }
  2844. clone() {
  2845. return new this.constructor().copy( this );
  2846. }
  2847. copy( box ) {
  2848. this.min.copy( box.min );
  2849. this.max.copy( box.max );
  2850. return this;
  2851. }
  2852. makeEmpty() {
  2853. this.min.x = this.min.y = this.min.z = + Infinity;
  2854. this.max.x = this.max.y = this.max.z = - Infinity;
  2855. return this;
  2856. }
  2857. isEmpty() {
  2858. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  2859. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z );
  2860. }
  2861. getCenter( target ) {
  2862. return this.isEmpty() ? target.set( 0, 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  2863. }
  2864. getSize( target ) {
  2865. return this.isEmpty() ? target.set( 0, 0, 0 ) : target.subVectors( this.max, this.min );
  2866. }
  2867. expandByPoint( point ) {
  2868. this.min.min( point );
  2869. this.max.max( point );
  2870. return this;
  2871. }
  2872. expandByVector( vector ) {
  2873. this.min.sub( vector );
  2874. this.max.add( vector );
  2875. return this;
  2876. }
  2877. expandByScalar( scalar ) {
  2878. this.min.addScalar( - scalar );
  2879. this.max.addScalar( scalar );
  2880. return this;
  2881. }
  2882. expandByObject( object, precise = false ) {
  2883. // Computes the world-axis-aligned bounding box of an object (including its children),
  2884. // accounting for both the object's, and children's, world transforms
  2885. object.updateWorldMatrix( false, false );
  2886. const geometry = object.geometry;
  2887. if ( geometry !== undefined ) {
  2888. const positionAttribute = geometry.getAttribute( 'position' );
  2889. // precise AABB computation based on vertex data requires at least a position attribute.
  2890. // instancing isn't supported so far and uses the normal (conservative) code path.
  2891. if ( precise === true && positionAttribute !== undefined && object.isInstancedMesh !== true ) {
  2892. for ( let i = 0, l = positionAttribute.count; i < l; i ++ ) {
  2893. if ( object.isMesh === true ) {
  2894. object.getVertexPosition( i, _vector$b );
  2895. } else {
  2896. _vector$b.fromBufferAttribute( positionAttribute, i );
  2897. }
  2898. _vector$b.applyMatrix4( object.matrixWorld );
  2899. this.expandByPoint( _vector$b );
  2900. }
  2901. } else {
  2902. if ( object.boundingBox !== undefined ) {
  2903. // object-level bounding box
  2904. if ( object.boundingBox === null ) {
  2905. object.computeBoundingBox();
  2906. }
  2907. _box$4.copy( object.boundingBox );
  2908. } else {
  2909. // geometry-level bounding box
  2910. if ( geometry.boundingBox === null ) {
  2911. geometry.computeBoundingBox();
  2912. }
  2913. _box$4.copy( geometry.boundingBox );
  2914. }
  2915. _box$4.applyMatrix4( object.matrixWorld );
  2916. this.union( _box$4 );
  2917. }
  2918. }
  2919. const children = object.children;
  2920. for ( let i = 0, l = children.length; i < l; i ++ ) {
  2921. this.expandByObject( children[ i ], precise );
  2922. }
  2923. return this;
  2924. }
  2925. containsPoint( point ) {
  2926. return point.x >= this.min.x && point.x <= this.max.x &&
  2927. point.y >= this.min.y && point.y <= this.max.y &&
  2928. point.z >= this.min.z && point.z <= this.max.z;
  2929. }
  2930. containsBox( box ) {
  2931. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  2932. this.min.y <= box.min.y && box.max.y <= this.max.y &&
  2933. this.min.z <= box.min.z && box.max.z <= this.max.z;
  2934. }
  2935. getParameter( point, target ) {
  2936. // This can potentially have a divide by zero if the box
  2937. // has a size dimension of 0.
  2938. return target.set(
  2939. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  2940. ( point.y - this.min.y ) / ( this.max.y - this.min.y ),
  2941. ( point.z - this.min.z ) / ( this.max.z - this.min.z )
  2942. );
  2943. }
  2944. intersectsBox( box ) {
  2945. // using 6 splitting planes to rule out intersections.
  2946. return box.max.x >= this.min.x && box.min.x <= this.max.x &&
  2947. box.max.y >= this.min.y && box.min.y <= this.max.y &&
  2948. box.max.z >= this.min.z && box.min.z <= this.max.z;
  2949. }
  2950. intersectsSphere( sphere ) {
  2951. // Find the point on the AABB closest to the sphere center.
  2952. this.clampPoint( sphere.center, _vector$b );
  2953. // If that point is inside the sphere, the AABB and sphere intersect.
  2954. return _vector$b.distanceToSquared( sphere.center ) <= ( sphere.radius * sphere.radius );
  2955. }
  2956. intersectsPlane( plane ) {
  2957. // We compute the minimum and maximum dot product values. If those values
  2958. // are on the same side (back or front) of the plane, then there is no intersection.
  2959. let min, max;
  2960. if ( plane.normal.x > 0 ) {
  2961. min = plane.normal.x * this.min.x;
  2962. max = plane.normal.x * this.max.x;
  2963. } else {
  2964. min = plane.normal.x * this.max.x;
  2965. max = plane.normal.x * this.min.x;
  2966. }
  2967. if ( plane.normal.y > 0 ) {
  2968. min += plane.normal.y * this.min.y;
  2969. max += plane.normal.y * this.max.y;
  2970. } else {
  2971. min += plane.normal.y * this.max.y;
  2972. max += plane.normal.y * this.min.y;
  2973. }
  2974. if ( plane.normal.z > 0 ) {
  2975. min += plane.normal.z * this.min.z;
  2976. max += plane.normal.z * this.max.z;
  2977. } else {
  2978. min += plane.normal.z * this.max.z;
  2979. max += plane.normal.z * this.min.z;
  2980. }
  2981. return ( min <= - plane.constant && max >= - plane.constant );
  2982. }
  2983. intersectsTriangle( triangle ) {
  2984. if ( this.isEmpty() ) {
  2985. return false;
  2986. }
  2987. // compute box center and extents
  2988. this.getCenter( _center );
  2989. _extents.subVectors( this.max, _center );
  2990. // translate triangle to aabb origin
  2991. _v0$2.subVectors( triangle.a, _center );
  2992. _v1$7.subVectors( triangle.b, _center );
  2993. _v2$4.subVectors( triangle.c, _center );
  2994. // compute edge vectors for triangle
  2995. _f0.subVectors( _v1$7, _v0$2 );
  2996. _f1.subVectors( _v2$4, _v1$7 );
  2997. _f2.subVectors( _v0$2, _v2$4 );
  2998. // test against axes that are given by cross product combinations of the edges of the triangle and the edges of the aabb
  2999. // 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
  3000. // axis_ij = u_i x f_j (u0, u1, u2 = face normals of aabb = x,y,z axes vectors since aabb is axis aligned)
  3001. let axes = [
  3002. 0, - _f0.z, _f0.y, 0, - _f1.z, _f1.y, 0, - _f2.z, _f2.y,
  3003. _f0.z, 0, - _f0.x, _f1.z, 0, - _f1.x, _f2.z, 0, - _f2.x,
  3004. - _f0.y, _f0.x, 0, - _f1.y, _f1.x, 0, - _f2.y, _f2.x, 0
  3005. ];
  3006. if ( ! satForAxes( axes, _v0$2, _v1$7, _v2$4, _extents ) ) {
  3007. return false;
  3008. }
  3009. // test 3 face normals from the aabb
  3010. axes = [ 1, 0, 0, 0, 1, 0, 0, 0, 1 ];
  3011. if ( ! satForAxes( axes, _v0$2, _v1$7, _v2$4, _extents ) ) {
  3012. return false;
  3013. }
  3014. // finally testing the face normal of the triangle
  3015. // use already existing triangle edge vectors here
  3016. _triangleNormal.crossVectors( _f0, _f1 );
  3017. axes = [ _triangleNormal.x, _triangleNormal.y, _triangleNormal.z ];
  3018. return satForAxes( axes, _v0$2, _v1$7, _v2$4, _extents );
  3019. }
  3020. clampPoint( point, target ) {
  3021. return target.copy( point ).clamp( this.min, this.max );
  3022. }
  3023. distanceToPoint( point ) {
  3024. return this.clampPoint( point, _vector$b ).distanceTo( point );
  3025. }
  3026. getBoundingSphere( target ) {
  3027. if ( this.isEmpty() ) {
  3028. target.makeEmpty();
  3029. } else {
  3030. this.getCenter( target.center );
  3031. target.radius = this.getSize( _vector$b ).length() * 0.5;
  3032. }
  3033. return target;
  3034. }
  3035. intersect( box ) {
  3036. this.min.max( box.min );
  3037. this.max.min( box.max );
  3038. // 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.
  3039. if ( this.isEmpty() ) this.makeEmpty();
  3040. return this;
  3041. }
  3042. union( box ) {
  3043. this.min.min( box.min );
  3044. this.max.max( box.max );
  3045. return this;
  3046. }
  3047. applyMatrix4( matrix ) {
  3048. // transform of empty box is an empty box.
  3049. if ( this.isEmpty() ) return this;
  3050. // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  3051. _points[ 0 ].set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 000
  3052. _points[ 1 ].set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 001
  3053. _points[ 2 ].set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 010
  3054. _points[ 3 ].set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 011
  3055. _points[ 4 ].set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 100
  3056. _points[ 5 ].set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 101
  3057. _points[ 6 ].set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 110
  3058. _points[ 7 ].set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 111
  3059. this.setFromPoints( _points );
  3060. return this;
  3061. }
  3062. translate( offset ) {
  3063. this.min.add( offset );
  3064. this.max.add( offset );
  3065. return this;
  3066. }
  3067. equals( box ) {
  3068. return box.min.equals( this.min ) && box.max.equals( this.max );
  3069. }
  3070. }
  3071. const _points = [
  3072. /*@__PURE__*/ new Vector3(),
  3073. /*@__PURE__*/ new Vector3(),
  3074. /*@__PURE__*/ new Vector3(),
  3075. /*@__PURE__*/ new Vector3(),
  3076. /*@__PURE__*/ new Vector3(),
  3077. /*@__PURE__*/ new Vector3(),
  3078. /*@__PURE__*/ new Vector3(),
  3079. /*@__PURE__*/ new Vector3()
  3080. ];
  3081. const _vector$b = /*@__PURE__*/ new Vector3();
  3082. const _box$4 = /*@__PURE__*/ new Box3();
  3083. // triangle centered vertices
  3084. const _v0$2 = /*@__PURE__*/ new Vector3();
  3085. const _v1$7 = /*@__PURE__*/ new Vector3();
  3086. const _v2$4 = /*@__PURE__*/ new Vector3();
  3087. // triangle edge vectors
  3088. const _f0 = /*@__PURE__*/ new Vector3();
  3089. const _f1 = /*@__PURE__*/ new Vector3();
  3090. const _f2 = /*@__PURE__*/ new Vector3();
  3091. const _center = /*@__PURE__*/ new Vector3();
  3092. const _extents = /*@__PURE__*/ new Vector3();
  3093. const _triangleNormal = /*@__PURE__*/ new Vector3();
  3094. const _testAxis = /*@__PURE__*/ new Vector3();
  3095. function satForAxes( axes, v0, v1, v2, extents ) {
  3096. for ( let i = 0, j = axes.length - 3; i <= j; i += 3 ) {
  3097. _testAxis.fromArray( axes, i );
  3098. // project the aabb onto the separating axis
  3099. const r = extents.x * Math.abs( _testAxis.x ) + extents.y * Math.abs( _testAxis.y ) + extents.z * Math.abs( _testAxis.z );
  3100. // project all 3 vertices of the triangle onto the separating axis
  3101. const p0 = v0.dot( _testAxis );
  3102. const p1 = v1.dot( _testAxis );
  3103. const p2 = v2.dot( _testAxis );
  3104. // actual test, basically see if either of the most extreme of the triangle points intersects r
  3105. if ( Math.max( - Math.max( p0, p1, p2 ), Math.min( p0, p1, p2 ) ) > r ) {
  3106. // points of the projected triangle are outside the projected half-length of the aabb
  3107. // the axis is separating and we can exit
  3108. return false;
  3109. }
  3110. }
  3111. return true;
  3112. }
  3113. const _box$3 = /*@__PURE__*/ new Box3();
  3114. const _v1$6 = /*@__PURE__*/ new Vector3();
  3115. const _v2$3 = /*@__PURE__*/ new Vector3();
  3116. class Sphere {
  3117. constructor( center = new Vector3(), radius = - 1 ) {
  3118. this.isSphere = true;
  3119. this.center = center;
  3120. this.radius = radius;
  3121. }
  3122. set( center, radius ) {
  3123. this.center.copy( center );
  3124. this.radius = radius;
  3125. return this;
  3126. }
  3127. setFromPoints( points, optionalCenter ) {
  3128. const center = this.center;
  3129. if ( optionalCenter !== undefined ) {
  3130. center.copy( optionalCenter );
  3131. } else {
  3132. _box$3.setFromPoints( points ).getCenter( center );
  3133. }
  3134. let maxRadiusSq = 0;
  3135. for ( let i = 0, il = points.length; i < il; i ++ ) {
  3136. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( points[ i ] ) );
  3137. }
  3138. this.radius = Math.sqrt( maxRadiusSq );
  3139. return this;
  3140. }
  3141. copy( sphere ) {
  3142. this.center.copy( sphere.center );
  3143. this.radius = sphere.radius;
  3144. return this;
  3145. }
  3146. isEmpty() {
  3147. return ( this.radius < 0 );
  3148. }
  3149. makeEmpty() {
  3150. this.center.set( 0, 0, 0 );
  3151. this.radius = - 1;
  3152. return this;
  3153. }
  3154. containsPoint( point ) {
  3155. return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) );
  3156. }
  3157. distanceToPoint( point ) {
  3158. return ( point.distanceTo( this.center ) - this.radius );
  3159. }
  3160. intersectsSphere( sphere ) {
  3161. const radiusSum = this.radius + sphere.radius;
  3162. return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum );
  3163. }
  3164. intersectsBox( box ) {
  3165. return box.intersectsSphere( this );
  3166. }
  3167. intersectsPlane( plane ) {
  3168. return Math.abs( plane.distanceToPoint( this.center ) ) <= this.radius;
  3169. }
  3170. clampPoint( point, target ) {
  3171. const deltaLengthSq = this.center.distanceToSquared( point );
  3172. target.copy( point );
  3173. if ( deltaLengthSq > ( this.radius * this.radius ) ) {
  3174. target.sub( this.center ).normalize();
  3175. target.multiplyScalar( this.radius ).add( this.center );
  3176. }
  3177. return target;
  3178. }
  3179. getBoundingBox( target ) {
  3180. if ( this.isEmpty() ) {
  3181. // Empty sphere produces empty bounding box
  3182. target.makeEmpty();
  3183. return target;
  3184. }
  3185. target.set( this.center, this.center );
  3186. target.expandByScalar( this.radius );
  3187. return target;
  3188. }
  3189. applyMatrix4( matrix ) {
  3190. this.center.applyMatrix4( matrix );
  3191. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  3192. return this;
  3193. }
  3194. translate( offset ) {
  3195. this.center.add( offset );
  3196. return this;
  3197. }
  3198. expandByPoint( point ) {
  3199. if ( this.isEmpty() ) {
  3200. this.center.copy( point );
  3201. this.radius = 0;
  3202. return this;
  3203. }
  3204. _v1$6.subVectors( point, this.center );
  3205. const lengthSq = _v1$6.lengthSq();
  3206. if ( lengthSq > ( this.radius * this.radius ) ) {
  3207. // calculate the minimal sphere
  3208. const length = Math.sqrt( lengthSq );
  3209. const delta = ( length - this.radius ) * 0.5;
  3210. this.center.addScaledVector( _v1$6, delta / length );
  3211. this.radius += delta;
  3212. }
  3213. return this;
  3214. }
  3215. union( sphere ) {
  3216. if ( sphere.isEmpty() ) {
  3217. return this;
  3218. }
  3219. if ( this.isEmpty() ) {
  3220. this.copy( sphere );
  3221. return this;
  3222. }
  3223. if ( this.center.equals( sphere.center ) === true ) {
  3224. this.radius = Math.max( this.radius, sphere.radius );
  3225. } else {
  3226. _v2$3.subVectors( sphere.center, this.center ).setLength( sphere.radius );
  3227. this.expandByPoint( _v1$6.copy( sphere.center ).add( _v2$3 ) );
  3228. this.expandByPoint( _v1$6.copy( sphere.center ).sub( _v2$3 ) );
  3229. }
  3230. return this;
  3231. }
  3232. equals( sphere ) {
  3233. return sphere.center.equals( this.center ) && ( sphere.radius === this.radius );
  3234. }
  3235. clone() {
  3236. return new this.constructor().copy( this );
  3237. }
  3238. }
  3239. const _vector$a = /*@__PURE__*/ new Vector3();
  3240. const _segCenter = /*@__PURE__*/ new Vector3();
  3241. const _segDir = /*@__PURE__*/ new Vector3();
  3242. const _diff = /*@__PURE__*/ new Vector3();
  3243. const _edge1 = /*@__PURE__*/ new Vector3();
  3244. const _edge2 = /*@__PURE__*/ new Vector3();
  3245. const _normal$2 = /*@__PURE__*/ new Vector3();
  3246. class Ray {
  3247. constructor( origin = new Vector3(), direction = new Vector3( 0, 0, - 1 ) ) {
  3248. this.origin = origin;
  3249. this.direction = direction;
  3250. }
  3251. set( origin, direction ) {
  3252. this.origin.copy( origin );
  3253. this.direction.copy( direction );
  3254. return this;
  3255. }
  3256. copy( ray ) {
  3257. this.origin.copy( ray.origin );
  3258. this.direction.copy( ray.direction );
  3259. return this;
  3260. }
  3261. at( t, target ) {
  3262. return target.copy( this.origin ).addScaledVector( this.direction, t );
  3263. }
  3264. lookAt( v ) {
  3265. this.direction.copy( v ).sub( this.origin ).normalize();
  3266. return this;
  3267. }
  3268. recast( t ) {
  3269. this.origin.copy( this.at( t, _vector$a ) );
  3270. return this;
  3271. }
  3272. closestPointToPoint( point, target ) {
  3273. target.subVectors( point, this.origin );
  3274. const directionDistance = target.dot( this.direction );
  3275. if ( directionDistance < 0 ) {
  3276. return target.copy( this.origin );
  3277. }
  3278. return target.copy( this.origin ).addScaledVector( this.direction, directionDistance );
  3279. }
  3280. distanceToPoint( point ) {
  3281. return Math.sqrt( this.distanceSqToPoint( point ) );
  3282. }
  3283. distanceSqToPoint( point ) {
  3284. const directionDistance = _vector$a.subVectors( point, this.origin ).dot( this.direction );
  3285. // point behind the ray
  3286. if ( directionDistance < 0 ) {
  3287. return this.origin.distanceToSquared( point );
  3288. }
  3289. _vector$a.copy( this.origin ).addScaledVector( this.direction, directionDistance );
  3290. return _vector$a.distanceToSquared( point );
  3291. }
  3292. distanceSqToSegment( v0, v1, optionalPointOnRay, optionalPointOnSegment ) {
  3293. // from https://github.com/pmjoniak/GeometricTools/blob/master/GTEngine/Include/Mathematics/GteDistRaySegment.h
  3294. // It returns the min distance between the ray and the segment
  3295. // defined by v0 and v1
  3296. // It can also set two optional targets :
  3297. // - The closest point on the ray
  3298. // - The closest point on the segment
  3299. _segCenter.copy( v0 ).add( v1 ).multiplyScalar( 0.5 );
  3300. _segDir.copy( v1 ).sub( v0 ).normalize();
  3301. _diff.copy( this.origin ).sub( _segCenter );
  3302. const segExtent = v0.distanceTo( v1 ) * 0.5;
  3303. const a01 = - this.direction.dot( _segDir );
  3304. const b0 = _diff.dot( this.direction );
  3305. const b1 = - _diff.dot( _segDir );
  3306. const c = _diff.lengthSq();
  3307. const det = Math.abs( 1 - a01 * a01 );
  3308. let s0, s1, sqrDist, extDet;
  3309. if ( det > 0 ) {
  3310. // The ray and segment are not parallel.
  3311. s0 = a01 * b1 - b0;
  3312. s1 = a01 * b0 - b1;
  3313. extDet = segExtent * det;
  3314. if ( s0 >= 0 ) {
  3315. if ( s1 >= - extDet ) {
  3316. if ( s1 <= extDet ) {
  3317. // region 0
  3318. // Minimum at interior points of ray and segment.
  3319. const invDet = 1 / det;
  3320. s0 *= invDet;
  3321. s1 *= invDet;
  3322. sqrDist = s0 * ( s0 + a01 * s1 + 2 * b0 ) + s1 * ( a01 * s0 + s1 + 2 * b1 ) + c;
  3323. } else {
  3324. // region 1
  3325. s1 = segExtent;
  3326. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3327. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3328. }
  3329. } else {
  3330. // region 5
  3331. s1 = - segExtent;
  3332. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3333. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3334. }
  3335. } else {
  3336. if ( s1 <= - extDet ) {
  3337. // region 4
  3338. s0 = Math.max( 0, - ( - a01 * segExtent + b0 ) );
  3339. s1 = ( s0 > 0 ) ? - segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3340. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3341. } else if ( s1 <= extDet ) {
  3342. // region 3
  3343. s0 = 0;
  3344. s1 = Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3345. sqrDist = s1 * ( s1 + 2 * b1 ) + c;
  3346. } else {
  3347. // region 2
  3348. s0 = Math.max( 0, - ( a01 * segExtent + b0 ) );
  3349. s1 = ( s0 > 0 ) ? segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3350. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3351. }
  3352. }
  3353. } else {
  3354. // Ray and segment are parallel.
  3355. s1 = ( a01 > 0 ) ? - segExtent : segExtent;
  3356. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3357. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3358. }
  3359. if ( optionalPointOnRay ) {
  3360. optionalPointOnRay.copy( this.origin ).addScaledVector( this.direction, s0 );
  3361. }
  3362. if ( optionalPointOnSegment ) {
  3363. optionalPointOnSegment.copy( _segCenter ).addScaledVector( _segDir, s1 );
  3364. }
  3365. return sqrDist;
  3366. }
  3367. intersectSphere( sphere, target ) {
  3368. _vector$a.subVectors( sphere.center, this.origin );
  3369. const tca = _vector$a.dot( this.direction );
  3370. const d2 = _vector$a.dot( _vector$a ) - tca * tca;
  3371. const radius2 = sphere.radius * sphere.radius;
  3372. if ( d2 > radius2 ) return null;
  3373. const thc = Math.sqrt( radius2 - d2 );
  3374. // t0 = first intersect point - entrance on front of sphere
  3375. const t0 = tca - thc;
  3376. // t1 = second intersect point - exit point on back of sphere
  3377. const t1 = tca + thc;
  3378. // test to see if t1 is behind the ray - if so, return null
  3379. if ( t1 < 0 ) return null;
  3380. // test to see if t0 is behind the ray:
  3381. // if it is, the ray is inside the sphere, so return the second exit point scaled by t1,
  3382. // in order to always return an intersect point that is in front of the ray.
  3383. if ( t0 < 0 ) return this.at( t1, target );
  3384. // else t0 is in front of the ray, so return the first collision point scaled by t0
  3385. return this.at( t0, target );
  3386. }
  3387. intersectsSphere( sphere ) {
  3388. return this.distanceSqToPoint( sphere.center ) <= ( sphere.radius * sphere.radius );
  3389. }
  3390. distanceToPlane( plane ) {
  3391. const denominator = plane.normal.dot( this.direction );
  3392. if ( denominator === 0 ) {
  3393. // line is coplanar, return origin
  3394. if ( plane.distanceToPoint( this.origin ) === 0 ) {
  3395. return 0;
  3396. }
  3397. // Null is preferable to undefined since undefined means.... it is undefined
  3398. return null;
  3399. }
  3400. const t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator;
  3401. // Return if the ray never intersects the plane
  3402. return t >= 0 ? t : null;
  3403. }
  3404. intersectPlane( plane, target ) {
  3405. const t = this.distanceToPlane( plane );
  3406. if ( t === null ) {
  3407. return null;
  3408. }
  3409. return this.at( t, target );
  3410. }
  3411. intersectsPlane( plane ) {
  3412. // check if the ray lies on the plane first
  3413. const distToPoint = plane.distanceToPoint( this.origin );
  3414. if ( distToPoint === 0 ) {
  3415. return true;
  3416. }
  3417. const denominator = plane.normal.dot( this.direction );
  3418. if ( denominator * distToPoint < 0 ) {
  3419. return true;
  3420. }
  3421. // ray origin is behind the plane (and is pointing behind it)
  3422. return false;
  3423. }
  3424. intersectBox( box, target ) {
  3425. let tmin, tmax, tymin, tymax, tzmin, tzmax;
  3426. const invdirx = 1 / this.direction.x,
  3427. invdiry = 1 / this.direction.y,
  3428. invdirz = 1 / this.direction.z;
  3429. const origin = this.origin;
  3430. if ( invdirx >= 0 ) {
  3431. tmin = ( box.min.x - origin.x ) * invdirx;
  3432. tmax = ( box.max.x - origin.x ) * invdirx;
  3433. } else {
  3434. tmin = ( box.max.x - origin.x ) * invdirx;
  3435. tmax = ( box.min.x - origin.x ) * invdirx;
  3436. }
  3437. if ( invdiry >= 0 ) {
  3438. tymin = ( box.min.y - origin.y ) * invdiry;
  3439. tymax = ( box.max.y - origin.y ) * invdiry;
  3440. } else {
  3441. tymin = ( box.max.y - origin.y ) * invdiry;
  3442. tymax = ( box.min.y - origin.y ) * invdiry;
  3443. }
  3444. if ( ( tmin > tymax ) || ( tymin > tmax ) ) return null;
  3445. if ( tymin > tmin || isNaN( tmin ) ) tmin = tymin;
  3446. if ( tymax < tmax || isNaN( tmax ) ) tmax = tymax;
  3447. if ( invdirz >= 0 ) {
  3448. tzmin = ( box.min.z - origin.z ) * invdirz;
  3449. tzmax = ( box.max.z - origin.z ) * invdirz;
  3450. } else {
  3451. tzmin = ( box.max.z - origin.z ) * invdirz;
  3452. tzmax = ( box.min.z - origin.z ) * invdirz;
  3453. }
  3454. if ( ( tmin > tzmax ) || ( tzmin > tmax ) ) return null;
  3455. if ( tzmin > tmin || tmin !== tmin ) tmin = tzmin;
  3456. if ( tzmax < tmax || tmax !== tmax ) tmax = tzmax;
  3457. //return point closest to the ray (positive side)
  3458. if ( tmax < 0 ) return null;
  3459. return this.at( tmin >= 0 ? tmin : tmax, target );
  3460. }
  3461. intersectsBox( box ) {
  3462. return this.intersectBox( box, _vector$a ) !== null;
  3463. }
  3464. intersectTriangle( a, b, c, backfaceCulling, target ) {
  3465. // Compute the offset origin, edges, and normal.
  3466. // from https://github.com/pmjoniak/GeometricTools/blob/master/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h
  3467. _edge1.subVectors( b, a );
  3468. _edge2.subVectors( c, a );
  3469. _normal$2.crossVectors( _edge1, _edge2 );
  3470. // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  3471. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  3472. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  3473. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  3474. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  3475. let DdN = this.direction.dot( _normal$2 );
  3476. let sign;
  3477. if ( DdN > 0 ) {
  3478. if ( backfaceCulling ) return null;
  3479. sign = 1;
  3480. } else if ( DdN < 0 ) {
  3481. sign = - 1;
  3482. DdN = - DdN;
  3483. } else {
  3484. return null;
  3485. }
  3486. _diff.subVectors( this.origin, a );
  3487. const DdQxE2 = sign * this.direction.dot( _edge2.crossVectors( _diff, _edge2 ) );
  3488. // b1 < 0, no intersection
  3489. if ( DdQxE2 < 0 ) {
  3490. return null;
  3491. }
  3492. const DdE1xQ = sign * this.direction.dot( _edge1.cross( _diff ) );
  3493. // b2 < 0, no intersection
  3494. if ( DdE1xQ < 0 ) {
  3495. return null;
  3496. }
  3497. // b1+b2 > 1, no intersection
  3498. if ( DdQxE2 + DdE1xQ > DdN ) {
  3499. return null;
  3500. }
  3501. // Line intersects triangle, check if ray does.
  3502. const QdN = - sign * _diff.dot( _normal$2 );
  3503. // t < 0, no intersection
  3504. if ( QdN < 0 ) {
  3505. return null;
  3506. }
  3507. // Ray intersects triangle.
  3508. return this.at( QdN / DdN, target );
  3509. }
  3510. applyMatrix4( matrix4 ) {
  3511. this.origin.applyMatrix4( matrix4 );
  3512. this.direction.transformDirection( matrix4 );
  3513. return this;
  3514. }
  3515. equals( ray ) {
  3516. return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction );
  3517. }
  3518. clone() {
  3519. return new this.constructor().copy( this );
  3520. }
  3521. }
  3522. class Matrix4 {
  3523. constructor( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  3524. Matrix4.prototype.isMatrix4 = true;
  3525. this.elements = [
  3526. 1, 0, 0, 0,
  3527. 0, 1, 0, 0,
  3528. 0, 0, 1, 0,
  3529. 0, 0, 0, 1
  3530. ];
  3531. if ( n11 !== undefined ) {
  3532. this.set( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 );
  3533. }
  3534. }
  3535. set( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  3536. const te = this.elements;
  3537. te[ 0 ] = n11; te[ 4 ] = n12; te[ 8 ] = n13; te[ 12 ] = n14;
  3538. te[ 1 ] = n21; te[ 5 ] = n22; te[ 9 ] = n23; te[ 13 ] = n24;
  3539. te[ 2 ] = n31; te[ 6 ] = n32; te[ 10 ] = n33; te[ 14 ] = n34;
  3540. te[ 3 ] = n41; te[ 7 ] = n42; te[ 11 ] = n43; te[ 15 ] = n44;
  3541. return this;
  3542. }
  3543. identity() {
  3544. this.set(
  3545. 1, 0, 0, 0,
  3546. 0, 1, 0, 0,
  3547. 0, 0, 1, 0,
  3548. 0, 0, 0, 1
  3549. );
  3550. return this;
  3551. }
  3552. clone() {
  3553. return new Matrix4().fromArray( this.elements );
  3554. }
  3555. copy( m ) {
  3556. const te = this.elements;
  3557. const me = m.elements;
  3558. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ]; te[ 3 ] = me[ 3 ];
  3559. te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ]; te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ];
  3560. te[ 8 ] = me[ 8 ]; te[ 9 ] = me[ 9 ]; te[ 10 ] = me[ 10 ]; te[ 11 ] = me[ 11 ];
  3561. te[ 12 ] = me[ 12 ]; te[ 13 ] = me[ 13 ]; te[ 14 ] = me[ 14 ]; te[ 15 ] = me[ 15 ];
  3562. return this;
  3563. }
  3564. copyPosition( m ) {
  3565. const te = this.elements, me = m.elements;
  3566. te[ 12 ] = me[ 12 ];
  3567. te[ 13 ] = me[ 13 ];
  3568. te[ 14 ] = me[ 14 ];
  3569. return this;
  3570. }
  3571. setFromMatrix3( m ) {
  3572. const me = m.elements;
  3573. this.set(
  3574. me[ 0 ], me[ 3 ], me[ 6 ], 0,
  3575. me[ 1 ], me[ 4 ], me[ 7 ], 0,
  3576. me[ 2 ], me[ 5 ], me[ 8 ], 0,
  3577. 0, 0, 0, 1
  3578. );
  3579. return this;
  3580. }
  3581. extractBasis( xAxis, yAxis, zAxis ) {
  3582. xAxis.setFromMatrixColumn( this, 0 );
  3583. yAxis.setFromMatrixColumn( this, 1 );
  3584. zAxis.setFromMatrixColumn( this, 2 );
  3585. return this;
  3586. }
  3587. makeBasis( xAxis, yAxis, zAxis ) {
  3588. this.set(
  3589. xAxis.x, yAxis.x, zAxis.x, 0,
  3590. xAxis.y, yAxis.y, zAxis.y, 0,
  3591. xAxis.z, yAxis.z, zAxis.z, 0,
  3592. 0, 0, 0, 1
  3593. );
  3594. return this;
  3595. }
  3596. extractRotation( m ) {
  3597. // this method does not support reflection matrices
  3598. const te = this.elements;
  3599. const me = m.elements;
  3600. const scaleX = 1 / _v1$5.setFromMatrixColumn( m, 0 ).length();
  3601. const scaleY = 1 / _v1$5.setFromMatrixColumn( m, 1 ).length();
  3602. const scaleZ = 1 / _v1$5.setFromMatrixColumn( m, 2 ).length();
  3603. te[ 0 ] = me[ 0 ] * scaleX;
  3604. te[ 1 ] = me[ 1 ] * scaleX;
  3605. te[ 2 ] = me[ 2 ] * scaleX;
  3606. te[ 3 ] = 0;
  3607. te[ 4 ] = me[ 4 ] * scaleY;
  3608. te[ 5 ] = me[ 5 ] * scaleY;
  3609. te[ 6 ] = me[ 6 ] * scaleY;
  3610. te[ 7 ] = 0;
  3611. te[ 8 ] = me[ 8 ] * scaleZ;
  3612. te[ 9 ] = me[ 9 ] * scaleZ;
  3613. te[ 10 ] = me[ 10 ] * scaleZ;
  3614. te[ 11 ] = 0;
  3615. te[ 12 ] = 0;
  3616. te[ 13 ] = 0;
  3617. te[ 14 ] = 0;
  3618. te[ 15 ] = 1;
  3619. return this;
  3620. }
  3621. makeRotationFromEuler( euler ) {
  3622. const te = this.elements;
  3623. const x = euler.x, y = euler.y, z = euler.z;
  3624. const a = Math.cos( x ), b = Math.sin( x );
  3625. const c = Math.cos( y ), d = Math.sin( y );
  3626. const e = Math.cos( z ), f = Math.sin( z );
  3627. if ( euler.order === 'XYZ' ) {
  3628. const ae = a * e, af = a * f, be = b * e, bf = b * f;
  3629. te[ 0 ] = c * e;
  3630. te[ 4 ] = - c * f;
  3631. te[ 8 ] = d;
  3632. te[ 1 ] = af + be * d;
  3633. te[ 5 ] = ae - bf * d;
  3634. te[ 9 ] = - b * c;
  3635. te[ 2 ] = bf - ae * d;
  3636. te[ 6 ] = be + af * d;
  3637. te[ 10 ] = a * c;
  3638. } else if ( euler.order === 'YXZ' ) {
  3639. const ce = c * e, cf = c * f, de = d * e, df = d * f;
  3640. te[ 0 ] = ce + df * b;
  3641. te[ 4 ] = de * b - cf;
  3642. te[ 8 ] = a * d;
  3643. te[ 1 ] = a * f;
  3644. te[ 5 ] = a * e;
  3645. te[ 9 ] = - b;
  3646. te[ 2 ] = cf * b - de;
  3647. te[ 6 ] = df + ce * b;
  3648. te[ 10 ] = a * c;
  3649. } else if ( euler.order === 'ZXY' ) {
  3650. const ce = c * e, cf = c * f, de = d * e, df = d * f;
  3651. te[ 0 ] = ce - df * b;
  3652. te[ 4 ] = - a * f;
  3653. te[ 8 ] = de + cf * b;
  3654. te[ 1 ] = cf + de * b;
  3655. te[ 5 ] = a * e;
  3656. te[ 9 ] = df - ce * b;
  3657. te[ 2 ] = - a * d;
  3658. te[ 6 ] = b;
  3659. te[ 10 ] = a * c;
  3660. } else if ( euler.order === 'ZYX' ) {
  3661. const ae = a * e, af = a * f, be = b * e, bf = b * f;
  3662. te[ 0 ] = c * e;
  3663. te[ 4 ] = be * d - af;
  3664. te[ 8 ] = ae * d + bf;
  3665. te[ 1 ] = c * f;
  3666. te[ 5 ] = bf * d + ae;
  3667. te[ 9 ] = af * d - be;
  3668. te[ 2 ] = - d;
  3669. te[ 6 ] = b * c;
  3670. te[ 10 ] = a * c;
  3671. } else if ( euler.order === 'YZX' ) {
  3672. const ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  3673. te[ 0 ] = c * e;
  3674. te[ 4 ] = bd - ac * f;
  3675. te[ 8 ] = bc * f + ad;
  3676. te[ 1 ] = f;
  3677. te[ 5 ] = a * e;
  3678. te[ 9 ] = - b * e;
  3679. te[ 2 ] = - d * e;
  3680. te[ 6 ] = ad * f + bc;
  3681. te[ 10 ] = ac - bd * f;
  3682. } else if ( euler.order === 'XZY' ) {
  3683. const ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  3684. te[ 0 ] = c * e;
  3685. te[ 4 ] = - f;
  3686. te[ 8 ] = d * e;
  3687. te[ 1 ] = ac * f + bd;
  3688. te[ 5 ] = a * e;
  3689. te[ 9 ] = ad * f - bc;
  3690. te[ 2 ] = bc * f - ad;
  3691. te[ 6 ] = b * e;
  3692. te[ 10 ] = bd * f + ac;
  3693. }
  3694. // bottom row
  3695. te[ 3 ] = 0;
  3696. te[ 7 ] = 0;
  3697. te[ 11 ] = 0;
  3698. // last column
  3699. te[ 12 ] = 0;
  3700. te[ 13 ] = 0;
  3701. te[ 14 ] = 0;
  3702. te[ 15 ] = 1;
  3703. return this;
  3704. }
  3705. makeRotationFromQuaternion( q ) {
  3706. return this.compose( _zero, q, _one );
  3707. }
  3708. lookAt( eye, target, up ) {
  3709. const te = this.elements;
  3710. _z.subVectors( eye, target );
  3711. if ( _z.lengthSq() === 0 ) {
  3712. // eye and target are in the same position
  3713. _z.z = 1;
  3714. }
  3715. _z.normalize();
  3716. _x.crossVectors( up, _z );
  3717. if ( _x.lengthSq() === 0 ) {
  3718. // up and z are parallel
  3719. if ( Math.abs( up.z ) === 1 ) {
  3720. _z.x += 0.0001;
  3721. } else {
  3722. _z.z += 0.0001;
  3723. }
  3724. _z.normalize();
  3725. _x.crossVectors( up, _z );
  3726. }
  3727. _x.normalize();
  3728. _y.crossVectors( _z, _x );
  3729. te[ 0 ] = _x.x; te[ 4 ] = _y.x; te[ 8 ] = _z.x;
  3730. te[ 1 ] = _x.y; te[ 5 ] = _y.y; te[ 9 ] = _z.y;
  3731. te[ 2 ] = _x.z; te[ 6 ] = _y.z; te[ 10 ] = _z.z;
  3732. return this;
  3733. }
  3734. multiply( m ) {
  3735. return this.multiplyMatrices( this, m );
  3736. }
  3737. premultiply( m ) {
  3738. return this.multiplyMatrices( m, this );
  3739. }
  3740. multiplyMatrices( a, b ) {
  3741. const ae = a.elements;
  3742. const be = b.elements;
  3743. const te = this.elements;
  3744. const a11 = ae[ 0 ], a12 = ae[ 4 ], a13 = ae[ 8 ], a14 = ae[ 12 ];
  3745. const a21 = ae[ 1 ], a22 = ae[ 5 ], a23 = ae[ 9 ], a24 = ae[ 13 ];
  3746. const a31 = ae[ 2 ], a32 = ae[ 6 ], a33 = ae[ 10 ], a34 = ae[ 14 ];
  3747. const a41 = ae[ 3 ], a42 = ae[ 7 ], a43 = ae[ 11 ], a44 = ae[ 15 ];
  3748. const b11 = be[ 0 ], b12 = be[ 4 ], b13 = be[ 8 ], b14 = be[ 12 ];
  3749. const b21 = be[ 1 ], b22 = be[ 5 ], b23 = be[ 9 ], b24 = be[ 13 ];
  3750. const b31 = be[ 2 ], b32 = be[ 6 ], b33 = be[ 10 ], b34 = be[ 14 ];
  3751. const b41 = be[ 3 ], b42 = be[ 7 ], b43 = be[ 11 ], b44 = be[ 15 ];
  3752. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  3753. te[ 4 ] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  3754. te[ 8 ] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  3755. te[ 12 ] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  3756. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  3757. te[ 5 ] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  3758. te[ 9 ] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  3759. te[ 13 ] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  3760. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  3761. te[ 6 ] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  3762. te[ 10 ] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  3763. te[ 14 ] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  3764. te[ 3 ] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  3765. te[ 7 ] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  3766. te[ 11 ] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  3767. te[ 15 ] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  3768. return this;
  3769. }
  3770. multiplyScalar( s ) {
  3771. const te = this.elements;
  3772. te[ 0 ] *= s; te[ 4 ] *= s; te[ 8 ] *= s; te[ 12 ] *= s;
  3773. te[ 1 ] *= s; te[ 5 ] *= s; te[ 9 ] *= s; te[ 13 ] *= s;
  3774. te[ 2 ] *= s; te[ 6 ] *= s; te[ 10 ] *= s; te[ 14 ] *= s;
  3775. te[ 3 ] *= s; te[ 7 ] *= s; te[ 11 ] *= s; te[ 15 ] *= s;
  3776. return this;
  3777. }
  3778. determinant() {
  3779. const te = this.elements;
  3780. const n11 = te[ 0 ], n12 = te[ 4 ], n13 = te[ 8 ], n14 = te[ 12 ];
  3781. const n21 = te[ 1 ], n22 = te[ 5 ], n23 = te[ 9 ], n24 = te[ 13 ];
  3782. const n31 = te[ 2 ], n32 = te[ 6 ], n33 = te[ 10 ], n34 = te[ 14 ];
  3783. const n41 = te[ 3 ], n42 = te[ 7 ], n43 = te[ 11 ], n44 = te[ 15 ];
  3784. //TODO: make this more efficient
  3785. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  3786. return (
  3787. n41 * (
  3788. + n14 * n23 * n32
  3789. - n13 * n24 * n32
  3790. - n14 * n22 * n33
  3791. + n12 * n24 * n33
  3792. + n13 * n22 * n34
  3793. - n12 * n23 * n34
  3794. ) +
  3795. n42 * (
  3796. + n11 * n23 * n34
  3797. - n11 * n24 * n33
  3798. + n14 * n21 * n33
  3799. - n13 * n21 * n34
  3800. + n13 * n24 * n31
  3801. - n14 * n23 * n31
  3802. ) +
  3803. n43 * (
  3804. + n11 * n24 * n32
  3805. - n11 * n22 * n34
  3806. - n14 * n21 * n32
  3807. + n12 * n21 * n34
  3808. + n14 * n22 * n31
  3809. - n12 * n24 * n31
  3810. ) +
  3811. n44 * (
  3812. - n13 * n22 * n31
  3813. - n11 * n23 * n32
  3814. + n11 * n22 * n33
  3815. + n13 * n21 * n32
  3816. - n12 * n21 * n33
  3817. + n12 * n23 * n31
  3818. )
  3819. );
  3820. }
  3821. transpose() {
  3822. const te = this.elements;
  3823. let tmp;
  3824. tmp = te[ 1 ]; te[ 1 ] = te[ 4 ]; te[ 4 ] = tmp;
  3825. tmp = te[ 2 ]; te[ 2 ] = te[ 8 ]; te[ 8 ] = tmp;
  3826. tmp = te[ 6 ]; te[ 6 ] = te[ 9 ]; te[ 9 ] = tmp;
  3827. tmp = te[ 3 ]; te[ 3 ] = te[ 12 ]; te[ 12 ] = tmp;
  3828. tmp = te[ 7 ]; te[ 7 ] = te[ 13 ]; te[ 13 ] = tmp;
  3829. tmp = te[ 11 ]; te[ 11 ] = te[ 14 ]; te[ 14 ] = tmp;
  3830. return this;
  3831. }
  3832. setPosition( x, y, z ) {
  3833. const te = this.elements;
  3834. if ( x.isVector3 ) {
  3835. te[ 12 ] = x.x;
  3836. te[ 13 ] = x.y;
  3837. te[ 14 ] = x.z;
  3838. } else {
  3839. te[ 12 ] = x;
  3840. te[ 13 ] = y;
  3841. te[ 14 ] = z;
  3842. }
  3843. return this;
  3844. }
  3845. invert() {
  3846. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  3847. const te = this.elements,
  3848. n11 = te[ 0 ], n21 = te[ 1 ], n31 = te[ 2 ], n41 = te[ 3 ],
  3849. n12 = te[ 4 ], n22 = te[ 5 ], n32 = te[ 6 ], n42 = te[ 7 ],
  3850. n13 = te[ 8 ], n23 = te[ 9 ], n33 = te[ 10 ], n43 = te[ 11 ],
  3851. n14 = te[ 12 ], n24 = te[ 13 ], n34 = te[ 14 ], n44 = te[ 15 ],
  3852. t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44,
  3853. t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44,
  3854. t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44,
  3855. t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34;
  3856. const det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14;
  3857. if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 );
  3858. const detInv = 1 / det;
  3859. te[ 0 ] = t11 * detInv;
  3860. te[ 1 ] = ( n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44 ) * detInv;
  3861. te[ 2 ] = ( n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44 ) * detInv;
  3862. te[ 3 ] = ( n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43 ) * detInv;
  3863. te[ 4 ] = t12 * detInv;
  3864. te[ 5 ] = ( n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44 ) * detInv;
  3865. te[ 6 ] = ( n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44 ) * detInv;
  3866. te[ 7 ] = ( n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43 ) * detInv;
  3867. te[ 8 ] = t13 * detInv;
  3868. te[ 9 ] = ( n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44 ) * detInv;
  3869. te[ 10 ] = ( n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44 ) * detInv;
  3870. te[ 11 ] = ( n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43 ) * detInv;
  3871. te[ 12 ] = t14 * detInv;
  3872. te[ 13 ] = ( n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34 ) * detInv;
  3873. te[ 14 ] = ( n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34 ) * detInv;
  3874. te[ 15 ] = ( n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33 ) * detInv;
  3875. return this;
  3876. }
  3877. scale( v ) {
  3878. const te = this.elements;
  3879. const x = v.x, y = v.y, z = v.z;
  3880. te[ 0 ] *= x; te[ 4 ] *= y; te[ 8 ] *= z;
  3881. te[ 1 ] *= x; te[ 5 ] *= y; te[ 9 ] *= z;
  3882. te[ 2 ] *= x; te[ 6 ] *= y; te[ 10 ] *= z;
  3883. te[ 3 ] *= x; te[ 7 ] *= y; te[ 11 ] *= z;
  3884. return this;
  3885. }
  3886. getMaxScaleOnAxis() {
  3887. const te = this.elements;
  3888. const scaleXSq = te[ 0 ] * te[ 0 ] + te[ 1 ] * te[ 1 ] + te[ 2 ] * te[ 2 ];
  3889. const scaleYSq = te[ 4 ] * te[ 4 ] + te[ 5 ] * te[ 5 ] + te[ 6 ] * te[ 6 ];
  3890. const scaleZSq = te[ 8 ] * te[ 8 ] + te[ 9 ] * te[ 9 ] + te[ 10 ] * te[ 10 ];
  3891. return Math.sqrt( Math.max( scaleXSq, scaleYSq, scaleZSq ) );
  3892. }
  3893. makeTranslation( x, y, z ) {
  3894. if ( x.isVector3 ) {
  3895. this.set(
  3896. 1, 0, 0, x.x,
  3897. 0, 1, 0, x.y,
  3898. 0, 0, 1, x.z,
  3899. 0, 0, 0, 1
  3900. );
  3901. } else {
  3902. this.set(
  3903. 1, 0, 0, x,
  3904. 0, 1, 0, y,
  3905. 0, 0, 1, z,
  3906. 0, 0, 0, 1
  3907. );
  3908. }
  3909. return this;
  3910. }
  3911. makeRotationX( theta ) {
  3912. const c = Math.cos( theta ), s = Math.sin( theta );
  3913. this.set(
  3914. 1, 0, 0, 0,
  3915. 0, c, - s, 0,
  3916. 0, s, c, 0,
  3917. 0, 0, 0, 1
  3918. );
  3919. return this;
  3920. }
  3921. makeRotationY( theta ) {
  3922. const c = Math.cos( theta ), s = Math.sin( theta );
  3923. this.set(
  3924. c, 0, s, 0,
  3925. 0, 1, 0, 0,
  3926. - s, 0, c, 0,
  3927. 0, 0, 0, 1
  3928. );
  3929. return this;
  3930. }
  3931. makeRotationZ( theta ) {
  3932. const c = Math.cos( theta ), s = Math.sin( theta );
  3933. this.set(
  3934. c, - s, 0, 0,
  3935. s, c, 0, 0,
  3936. 0, 0, 1, 0,
  3937. 0, 0, 0, 1
  3938. );
  3939. return this;
  3940. }
  3941. makeRotationAxis( axis, angle ) {
  3942. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  3943. const c = Math.cos( angle );
  3944. const s = Math.sin( angle );
  3945. const t = 1 - c;
  3946. const x = axis.x, y = axis.y, z = axis.z;
  3947. const tx = t * x, ty = t * y;
  3948. this.set(
  3949. tx * x + c, tx * y - s * z, tx * z + s * y, 0,
  3950. tx * y + s * z, ty * y + c, ty * z - s * x, 0,
  3951. tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
  3952. 0, 0, 0, 1
  3953. );
  3954. return this;
  3955. }
  3956. makeScale( x, y, z ) {
  3957. this.set(
  3958. x, 0, 0, 0,
  3959. 0, y, 0, 0,
  3960. 0, 0, z, 0,
  3961. 0, 0, 0, 1
  3962. );
  3963. return this;
  3964. }
  3965. makeShear( xy, xz, yx, yz, zx, zy ) {
  3966. this.set(
  3967. 1, yx, zx, 0,
  3968. xy, 1, zy, 0,
  3969. xz, yz, 1, 0,
  3970. 0, 0, 0, 1
  3971. );
  3972. return this;
  3973. }
  3974. compose( position, quaternion, scale ) {
  3975. const te = this.elements;
  3976. const x = quaternion._x, y = quaternion._y, z = quaternion._z, w = quaternion._w;
  3977. const x2 = x + x, y2 = y + y, z2 = z + z;
  3978. const xx = x * x2, xy = x * y2, xz = x * z2;
  3979. const yy = y * y2, yz = y * z2, zz = z * z2;
  3980. const wx = w * x2, wy = w * y2, wz = w * z2;
  3981. const sx = scale.x, sy = scale.y, sz = scale.z;
  3982. te[ 0 ] = ( 1 - ( yy + zz ) ) * sx;
  3983. te[ 1 ] = ( xy + wz ) * sx;
  3984. te[ 2 ] = ( xz - wy ) * sx;
  3985. te[ 3 ] = 0;
  3986. te[ 4 ] = ( xy - wz ) * sy;
  3987. te[ 5 ] = ( 1 - ( xx + zz ) ) * sy;
  3988. te[ 6 ] = ( yz + wx ) * sy;
  3989. te[ 7 ] = 0;
  3990. te[ 8 ] = ( xz + wy ) * sz;
  3991. te[ 9 ] = ( yz - wx ) * sz;
  3992. te[ 10 ] = ( 1 - ( xx + yy ) ) * sz;
  3993. te[ 11 ] = 0;
  3994. te[ 12 ] = position.x;
  3995. te[ 13 ] = position.y;
  3996. te[ 14 ] = position.z;
  3997. te[ 15 ] = 1;
  3998. return this;
  3999. }
  4000. decompose( position, quaternion, scale ) {
  4001. const te = this.elements;
  4002. let sx = _v1$5.set( te[ 0 ], te[ 1 ], te[ 2 ] ).length();
  4003. const sy = _v1$5.set( te[ 4 ], te[ 5 ], te[ 6 ] ).length();
  4004. const sz = _v1$5.set( te[ 8 ], te[ 9 ], te[ 10 ] ).length();
  4005. // if determine is negative, we need to invert one scale
  4006. const det = this.determinant();
  4007. if ( det < 0 ) sx = - sx;
  4008. position.x = te[ 12 ];
  4009. position.y = te[ 13 ];
  4010. position.z = te[ 14 ];
  4011. // scale the rotation part
  4012. _m1$2.copy( this );
  4013. const invSX = 1 / sx;
  4014. const invSY = 1 / sy;
  4015. const invSZ = 1 / sz;
  4016. _m1$2.elements[ 0 ] *= invSX;
  4017. _m1$2.elements[ 1 ] *= invSX;
  4018. _m1$2.elements[ 2 ] *= invSX;
  4019. _m1$2.elements[ 4 ] *= invSY;
  4020. _m1$2.elements[ 5 ] *= invSY;
  4021. _m1$2.elements[ 6 ] *= invSY;
  4022. _m1$2.elements[ 8 ] *= invSZ;
  4023. _m1$2.elements[ 9 ] *= invSZ;
  4024. _m1$2.elements[ 10 ] *= invSZ;
  4025. quaternion.setFromRotationMatrix( _m1$2 );
  4026. scale.x = sx;
  4027. scale.y = sy;
  4028. scale.z = sz;
  4029. return this;
  4030. }
  4031. makePerspective( left, right, top, bottom, near, far, coordinateSystem = WebGLCoordinateSystem ) {
  4032. const te = this.elements;
  4033. const x = 2 * near / ( right - left );
  4034. const y = 2 * near / ( top - bottom );
  4035. const a = ( right + left ) / ( right - left );
  4036. const b = ( top + bottom ) / ( top - bottom );
  4037. let c, d;
  4038. if ( coordinateSystem === WebGLCoordinateSystem ) {
  4039. c = - ( far + near ) / ( far - near );
  4040. d = ( - 2 * far * near ) / ( far - near );
  4041. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  4042. c = - far / ( far - near );
  4043. d = ( - far * near ) / ( far - near );
  4044. } else {
  4045. throw new Error( 'THREE.Matrix4.makePerspective(): Invalid coordinate system: ' + coordinateSystem );
  4046. }
  4047. te[ 0 ] = x; te[ 4 ] = 0; te[ 8 ] = a; te[ 12 ] = 0;
  4048. te[ 1 ] = 0; te[ 5 ] = y; te[ 9 ] = b; te[ 13 ] = 0;
  4049. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = c; te[ 14 ] = d;
  4050. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = - 1; te[ 15 ] = 0;
  4051. return this;
  4052. }
  4053. makeOrthographic( left, right, top, bottom, near, far, coordinateSystem = WebGLCoordinateSystem ) {
  4054. const te = this.elements;
  4055. const w = 1.0 / ( right - left );
  4056. const h = 1.0 / ( top - bottom );
  4057. const p = 1.0 / ( far - near );
  4058. const x = ( right + left ) * w;
  4059. const y = ( top + bottom ) * h;
  4060. let z, zInv;
  4061. if ( coordinateSystem === WebGLCoordinateSystem ) {
  4062. z = ( far + near ) * p;
  4063. zInv = - 2 * p;
  4064. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  4065. z = near * p;
  4066. zInv = - 1 * p;
  4067. } else {
  4068. throw new Error( 'THREE.Matrix4.makeOrthographic(): Invalid coordinate system: ' + coordinateSystem );
  4069. }
  4070. te[ 0 ] = 2 * w; te[ 4 ] = 0; te[ 8 ] = 0; te[ 12 ] = - x;
  4071. te[ 1 ] = 0; te[ 5 ] = 2 * h; te[ 9 ] = 0; te[ 13 ] = - y;
  4072. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = zInv; te[ 14 ] = - z;
  4073. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = 0; te[ 15 ] = 1;
  4074. return this;
  4075. }
  4076. equals( matrix ) {
  4077. const te = this.elements;
  4078. const me = matrix.elements;
  4079. for ( let i = 0; i < 16; i ++ ) {
  4080. if ( te[ i ] !== me[ i ] ) return false;
  4081. }
  4082. return true;
  4083. }
  4084. fromArray( array, offset = 0 ) {
  4085. for ( let i = 0; i < 16; i ++ ) {
  4086. this.elements[ i ] = array[ i + offset ];
  4087. }
  4088. return this;
  4089. }
  4090. toArray( array = [], offset = 0 ) {
  4091. const te = this.elements;
  4092. array[ offset ] = te[ 0 ];
  4093. array[ offset + 1 ] = te[ 1 ];
  4094. array[ offset + 2 ] = te[ 2 ];
  4095. array[ offset + 3 ] = te[ 3 ];
  4096. array[ offset + 4 ] = te[ 4 ];
  4097. array[ offset + 5 ] = te[ 5 ];
  4098. array[ offset + 6 ] = te[ 6 ];
  4099. array[ offset + 7 ] = te[ 7 ];
  4100. array[ offset + 8 ] = te[ 8 ];
  4101. array[ offset + 9 ] = te[ 9 ];
  4102. array[ offset + 10 ] = te[ 10 ];
  4103. array[ offset + 11 ] = te[ 11 ];
  4104. array[ offset + 12 ] = te[ 12 ];
  4105. array[ offset + 13 ] = te[ 13 ];
  4106. array[ offset + 14 ] = te[ 14 ];
  4107. array[ offset + 15 ] = te[ 15 ];
  4108. return array;
  4109. }
  4110. }
  4111. const _v1$5 = /*@__PURE__*/ new Vector3();
  4112. const _m1$2 = /*@__PURE__*/ new Matrix4();
  4113. const _zero = /*@__PURE__*/ new Vector3( 0, 0, 0 );
  4114. const _one = /*@__PURE__*/ new Vector3( 1, 1, 1 );
  4115. const _x = /*@__PURE__*/ new Vector3();
  4116. const _y = /*@__PURE__*/ new Vector3();
  4117. const _z = /*@__PURE__*/ new Vector3();
  4118. const _matrix$2 = /*@__PURE__*/ new Matrix4();
  4119. const _quaternion$3 = /*@__PURE__*/ new Quaternion();
  4120. class Euler {
  4121. constructor( x = 0, y = 0, z = 0, order = Euler.DEFAULT_ORDER ) {
  4122. this.isEuler = true;
  4123. this._x = x;
  4124. this._y = y;
  4125. this._z = z;
  4126. this._order = order;
  4127. }
  4128. get x() {
  4129. return this._x;
  4130. }
  4131. set x( value ) {
  4132. this._x = value;
  4133. this._onChangeCallback();
  4134. }
  4135. get y() {
  4136. return this._y;
  4137. }
  4138. set y( value ) {
  4139. this._y = value;
  4140. this._onChangeCallback();
  4141. }
  4142. get z() {
  4143. return this._z;
  4144. }
  4145. set z( value ) {
  4146. this._z = value;
  4147. this._onChangeCallback();
  4148. }
  4149. get order() {
  4150. return this._order;
  4151. }
  4152. set order( value ) {
  4153. this._order = value;
  4154. this._onChangeCallback();
  4155. }
  4156. set( x, y, z, order = this._order ) {
  4157. this._x = x;
  4158. this._y = y;
  4159. this._z = z;
  4160. this._order = order;
  4161. this._onChangeCallback();
  4162. return this;
  4163. }
  4164. clone() {
  4165. return new this.constructor( this._x, this._y, this._z, this._order );
  4166. }
  4167. copy( euler ) {
  4168. this._x = euler._x;
  4169. this._y = euler._y;
  4170. this._z = euler._z;
  4171. this._order = euler._order;
  4172. this._onChangeCallback();
  4173. return this;
  4174. }
  4175. setFromRotationMatrix( m, order = this._order, update = true ) {
  4176. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  4177. const te = m.elements;
  4178. const m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ];
  4179. const m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ];
  4180. const m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  4181. switch ( order ) {
  4182. case 'XYZ':
  4183. this._y = Math.asin( clamp$1( m13, - 1, 1 ) );
  4184. if ( Math.abs( m13 ) < 0.9999999 ) {
  4185. this._x = Math.atan2( - m23, m33 );
  4186. this._z = Math.atan2( - m12, m11 );
  4187. } else {
  4188. this._x = Math.atan2( m32, m22 );
  4189. this._z = 0;
  4190. }
  4191. break;
  4192. case 'YXZ':
  4193. this._x = Math.asin( - clamp$1( m23, - 1, 1 ) );
  4194. if ( Math.abs( m23 ) < 0.9999999 ) {
  4195. this._y = Math.atan2( m13, m33 );
  4196. this._z = Math.atan2( m21, m22 );
  4197. } else {
  4198. this._y = Math.atan2( - m31, m11 );
  4199. this._z = 0;
  4200. }
  4201. break;
  4202. case 'ZXY':
  4203. this._x = Math.asin( clamp$1( m32, - 1, 1 ) );
  4204. if ( Math.abs( m32 ) < 0.9999999 ) {
  4205. this._y = Math.atan2( - m31, m33 );
  4206. this._z = Math.atan2( - m12, m22 );
  4207. } else {
  4208. this._y = 0;
  4209. this._z = Math.atan2( m21, m11 );
  4210. }
  4211. break;
  4212. case 'ZYX':
  4213. this._y = Math.asin( - clamp$1( m31, - 1, 1 ) );
  4214. if ( Math.abs( m31 ) < 0.9999999 ) {
  4215. this._x = Math.atan2( m32, m33 );
  4216. this._z = Math.atan2( m21, m11 );
  4217. } else {
  4218. this._x = 0;
  4219. this._z = Math.atan2( - m12, m22 );
  4220. }
  4221. break;
  4222. case 'YZX':
  4223. this._z = Math.asin( clamp$1( m21, - 1, 1 ) );
  4224. if ( Math.abs( m21 ) < 0.9999999 ) {
  4225. this._x = Math.atan2( - m23, m22 );
  4226. this._y = Math.atan2( - m31, m11 );
  4227. } else {
  4228. this._x = 0;
  4229. this._y = Math.atan2( m13, m33 );
  4230. }
  4231. break;
  4232. case 'XZY':
  4233. this._z = Math.asin( - clamp$1( m12, - 1, 1 ) );
  4234. if ( Math.abs( m12 ) < 0.9999999 ) {
  4235. this._x = Math.atan2( m32, m22 );
  4236. this._y = Math.atan2( m13, m11 );
  4237. } else {
  4238. this._x = Math.atan2( - m23, m33 );
  4239. this._y = 0;
  4240. }
  4241. break;
  4242. default:
  4243. console.warn( 'THREE.Euler: .setFromRotationMatrix() encountered an unknown order: ' + order );
  4244. }
  4245. this._order = order;
  4246. if ( update === true ) this._onChangeCallback();
  4247. return this;
  4248. }
  4249. setFromQuaternion( q, order, update ) {
  4250. _matrix$2.makeRotationFromQuaternion( q );
  4251. return this.setFromRotationMatrix( _matrix$2, order, update );
  4252. }
  4253. setFromVector3( v, order = this._order ) {
  4254. return this.set( v.x, v.y, v.z, order );
  4255. }
  4256. reorder( newOrder ) {
  4257. // WARNING: this discards revolution information -bhouston
  4258. _quaternion$3.setFromEuler( this );
  4259. return this.setFromQuaternion( _quaternion$3, newOrder );
  4260. }
  4261. equals( euler ) {
  4262. return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order );
  4263. }
  4264. fromArray( array ) {
  4265. this._x = array[ 0 ];
  4266. this._y = array[ 1 ];
  4267. this._z = array[ 2 ];
  4268. if ( array[ 3 ] !== undefined ) this._order = array[ 3 ];
  4269. this._onChangeCallback();
  4270. return this;
  4271. }
  4272. toArray( array = [], offset = 0 ) {
  4273. array[ offset ] = this._x;
  4274. array[ offset + 1 ] = this._y;
  4275. array[ offset + 2 ] = this._z;
  4276. array[ offset + 3 ] = this._order;
  4277. return array;
  4278. }
  4279. _onChange( callback ) {
  4280. this._onChangeCallback = callback;
  4281. return this;
  4282. }
  4283. _onChangeCallback() {}
  4284. *[ Symbol.iterator ]() {
  4285. yield this._x;
  4286. yield this._y;
  4287. yield this._z;
  4288. yield this._order;
  4289. }
  4290. }
  4291. Euler.DEFAULT_ORDER = 'XYZ';
  4292. class Layers {
  4293. constructor() {
  4294. this.mask = 1 | 0;
  4295. }
  4296. set( channel ) {
  4297. this.mask = ( 1 << channel | 0 ) >>> 0;
  4298. }
  4299. enable( channel ) {
  4300. this.mask |= 1 << channel | 0;
  4301. }
  4302. enableAll() {
  4303. this.mask = 0xffffffff | 0;
  4304. }
  4305. toggle( channel ) {
  4306. this.mask ^= 1 << channel | 0;
  4307. }
  4308. disable( channel ) {
  4309. this.mask &= ~ ( 1 << channel | 0 );
  4310. }
  4311. disableAll() {
  4312. this.mask = 0;
  4313. }
  4314. test( layers ) {
  4315. return ( this.mask & layers.mask ) !== 0;
  4316. }
  4317. isEnabled( channel ) {
  4318. return ( this.mask & ( 1 << channel | 0 ) ) !== 0;
  4319. }
  4320. }
  4321. let _object3DId = 0;
  4322. const _v1$4 = /*@__PURE__*/ new Vector3();
  4323. const _q1 = /*@__PURE__*/ new Quaternion();
  4324. const _m1$1 = /*@__PURE__*/ new Matrix4();
  4325. const _target$1 = /*@__PURE__*/ new Vector3();
  4326. const _position$3 = /*@__PURE__*/ new Vector3();
  4327. const _scale$2 = /*@__PURE__*/ new Vector3();
  4328. const _quaternion$2 = /*@__PURE__*/ new Quaternion();
  4329. const _xAxis = /*@__PURE__*/ new Vector3( 1, 0, 0 );
  4330. const _yAxis = /*@__PURE__*/ new Vector3( 0, 1, 0 );
  4331. const _zAxis = /*@__PURE__*/ new Vector3( 0, 0, 1 );
  4332. const _addedEvent = { type: 'added' };
  4333. const _removedEvent = { type: 'removed' };
  4334. const _childaddedEvent = { type: 'childadded', child: null };
  4335. const _childremovedEvent = { type: 'childremoved', child: null };
  4336. class Object3D extends EventDispatcher {
  4337. constructor() {
  4338. super();
  4339. this.isObject3D = true;
  4340. Object.defineProperty( this, 'id', { value: _object3DId ++ } );
  4341. this.uuid = generateUUID();
  4342. this.name = '';
  4343. this.type = 'Object3D';
  4344. this.parent = null;
  4345. this.children = [];
  4346. this.up = Object3D.DEFAULT_UP.clone();
  4347. const position = new Vector3();
  4348. const rotation = new Euler();
  4349. const quaternion = new Quaternion();
  4350. const scale = new Vector3( 1, 1, 1 );
  4351. function onRotationChange() {
  4352. quaternion.setFromEuler( rotation, false );
  4353. }
  4354. function onQuaternionChange() {
  4355. rotation.setFromQuaternion( quaternion, undefined, false );
  4356. }
  4357. rotation._onChange( onRotationChange );
  4358. quaternion._onChange( onQuaternionChange );
  4359. Object.defineProperties( this, {
  4360. position: {
  4361. configurable: true,
  4362. enumerable: true,
  4363. value: position
  4364. },
  4365. rotation: {
  4366. configurable: true,
  4367. enumerable: true,
  4368. value: rotation
  4369. },
  4370. quaternion: {
  4371. configurable: true,
  4372. enumerable: true,
  4373. value: quaternion
  4374. },
  4375. scale: {
  4376. configurable: true,
  4377. enumerable: true,
  4378. value: scale
  4379. },
  4380. modelViewMatrix: {
  4381. value: new Matrix4()
  4382. },
  4383. normalMatrix: {
  4384. value: new Matrix3()
  4385. }
  4386. } );
  4387. this.matrix = new Matrix4();
  4388. this.matrixWorld = new Matrix4();
  4389. this.matrixAutoUpdate = Object3D.DEFAULT_MATRIX_AUTO_UPDATE;
  4390. this.matrixWorldAutoUpdate = Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE; // checked by the renderer
  4391. this.matrixWorldNeedsUpdate = false;
  4392. this.layers = new Layers();
  4393. this.visible = true;
  4394. this.castShadow = false;
  4395. this.receiveShadow = false;
  4396. this.frustumCulled = true;
  4397. this.renderOrder = 0;
  4398. this.animations = [];
  4399. this.userData = {};
  4400. }
  4401. onBeforeShadow( /* renderer, object, camera, shadowCamera, geometry, depthMaterial, group */ ) {}
  4402. onAfterShadow( /* renderer, object, camera, shadowCamera, geometry, depthMaterial, group */ ) {}
  4403. onBeforeRender( /* renderer, scene, camera, geometry, material, group */ ) {}
  4404. onAfterRender( /* renderer, scene, camera, geometry, material, group */ ) {}
  4405. applyMatrix4( matrix ) {
  4406. if ( this.matrixAutoUpdate ) this.updateMatrix();
  4407. this.matrix.premultiply( matrix );
  4408. this.matrix.decompose( this.position, this.quaternion, this.scale );
  4409. }
  4410. applyQuaternion( q ) {
  4411. this.quaternion.premultiply( q );
  4412. return this;
  4413. }
  4414. setRotationFromAxisAngle( axis, angle ) {
  4415. // assumes axis is normalized
  4416. this.quaternion.setFromAxisAngle( axis, angle );
  4417. }
  4418. setRotationFromEuler( euler ) {
  4419. this.quaternion.setFromEuler( euler, true );
  4420. }
  4421. setRotationFromMatrix( m ) {
  4422. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  4423. this.quaternion.setFromRotationMatrix( m );
  4424. }
  4425. setRotationFromQuaternion( q ) {
  4426. // assumes q is normalized
  4427. this.quaternion.copy( q );
  4428. }
  4429. rotateOnAxis( axis, angle ) {
  4430. // rotate object on axis in object space
  4431. // axis is assumed to be normalized
  4432. _q1.setFromAxisAngle( axis, angle );
  4433. this.quaternion.multiply( _q1 );
  4434. return this;
  4435. }
  4436. rotateOnWorldAxis( axis, angle ) {
  4437. // rotate object on axis in world space
  4438. // axis is assumed to be normalized
  4439. // method assumes no rotated parent
  4440. _q1.setFromAxisAngle( axis, angle );
  4441. this.quaternion.premultiply( _q1 );
  4442. return this;
  4443. }
  4444. rotateX( angle ) {
  4445. return this.rotateOnAxis( _xAxis, angle );
  4446. }
  4447. rotateY( angle ) {
  4448. return this.rotateOnAxis( _yAxis, angle );
  4449. }
  4450. rotateZ( angle ) {
  4451. return this.rotateOnAxis( _zAxis, angle );
  4452. }
  4453. translateOnAxis( axis, distance ) {
  4454. // translate object by distance along axis in object space
  4455. // axis is assumed to be normalized
  4456. _v1$4.copy( axis ).applyQuaternion( this.quaternion );
  4457. this.position.add( _v1$4.multiplyScalar( distance ) );
  4458. return this;
  4459. }
  4460. translateX( distance ) {
  4461. return this.translateOnAxis( _xAxis, distance );
  4462. }
  4463. translateY( distance ) {
  4464. return this.translateOnAxis( _yAxis, distance );
  4465. }
  4466. translateZ( distance ) {
  4467. return this.translateOnAxis( _zAxis, distance );
  4468. }
  4469. localToWorld( vector ) {
  4470. this.updateWorldMatrix( true, false );
  4471. return vector.applyMatrix4( this.matrixWorld );
  4472. }
  4473. worldToLocal( vector ) {
  4474. this.updateWorldMatrix( true, false );
  4475. return vector.applyMatrix4( _m1$1.copy( this.matrixWorld ).invert() );
  4476. }
  4477. lookAt( x, y, z ) {
  4478. // This method does not support objects having non-uniformly-scaled parent(s)
  4479. if ( x.isVector3 ) {
  4480. _target$1.copy( x );
  4481. } else {
  4482. _target$1.set( x, y, z );
  4483. }
  4484. const parent = this.parent;
  4485. this.updateWorldMatrix( true, false );
  4486. _position$3.setFromMatrixPosition( this.matrixWorld );
  4487. if ( this.isCamera || this.isLight ) {
  4488. _m1$1.lookAt( _position$3, _target$1, this.up );
  4489. } else {
  4490. _m1$1.lookAt( _target$1, _position$3, this.up );
  4491. }
  4492. this.quaternion.setFromRotationMatrix( _m1$1 );
  4493. if ( parent ) {
  4494. _m1$1.extractRotation( parent.matrixWorld );
  4495. _q1.setFromRotationMatrix( _m1$1 );
  4496. this.quaternion.premultiply( _q1.invert() );
  4497. }
  4498. }
  4499. add( object ) {
  4500. if ( arguments.length > 1 ) {
  4501. for ( let i = 0; i < arguments.length; i ++ ) {
  4502. this.add( arguments[ i ] );
  4503. }
  4504. return this;
  4505. }
  4506. if ( object === this ) {
  4507. console.error( 'THREE.Object3D.add: object can\'t be added as a child of itself.', object );
  4508. return this;
  4509. }
  4510. if ( object && object.isObject3D ) {
  4511. object.removeFromParent();
  4512. object.parent = this;
  4513. this.children.push( object );
  4514. object.dispatchEvent( _addedEvent );
  4515. _childaddedEvent.child = object;
  4516. this.dispatchEvent( _childaddedEvent );
  4517. _childaddedEvent.child = null;
  4518. } else {
  4519. console.error( 'THREE.Object3D.add: object not an instance of THREE.Object3D.', object );
  4520. }
  4521. return this;
  4522. }
  4523. remove( object ) {
  4524. if ( arguments.length > 1 ) {
  4525. for ( let i = 0; i < arguments.length; i ++ ) {
  4526. this.remove( arguments[ i ] );
  4527. }
  4528. return this;
  4529. }
  4530. const index = this.children.indexOf( object );
  4531. if ( index !== - 1 ) {
  4532. object.parent = null;
  4533. this.children.splice( index, 1 );
  4534. object.dispatchEvent( _removedEvent );
  4535. _childremovedEvent.child = object;
  4536. this.dispatchEvent( _childremovedEvent );
  4537. _childremovedEvent.child = null;
  4538. }
  4539. return this;
  4540. }
  4541. removeFromParent() {
  4542. const parent = this.parent;
  4543. if ( parent !== null ) {
  4544. parent.remove( this );
  4545. }
  4546. return this;
  4547. }
  4548. clear() {
  4549. return this.remove( ... this.children );
  4550. }
  4551. attach( object ) {
  4552. // adds object as a child of this, while maintaining the object's world transform
  4553. // Note: This method does not support scene graphs having non-uniformly-scaled nodes(s)
  4554. this.updateWorldMatrix( true, false );
  4555. _m1$1.copy( this.matrixWorld ).invert();
  4556. if ( object.parent !== null ) {
  4557. object.parent.updateWorldMatrix( true, false );
  4558. _m1$1.multiply( object.parent.matrixWorld );
  4559. }
  4560. object.applyMatrix4( _m1$1 );
  4561. object.removeFromParent();
  4562. object.parent = this;
  4563. this.children.push( object );
  4564. object.updateWorldMatrix( false, true );
  4565. object.dispatchEvent( _addedEvent );
  4566. _childaddedEvent.child = object;
  4567. this.dispatchEvent( _childaddedEvent );
  4568. _childaddedEvent.child = null;
  4569. return this;
  4570. }
  4571. getObjectById( id ) {
  4572. return this.getObjectByProperty( 'id', id );
  4573. }
  4574. getObjectByName( name ) {
  4575. return this.getObjectByProperty( 'name', name );
  4576. }
  4577. getObjectByProperty( name, value ) {
  4578. if ( this[ name ] === value ) return this;
  4579. for ( let i = 0, l = this.children.length; i < l; i ++ ) {
  4580. const child = this.children[ i ];
  4581. const object = child.getObjectByProperty( name, value );
  4582. if ( object !== undefined ) {
  4583. return object;
  4584. }
  4585. }
  4586. return undefined;
  4587. }
  4588. getObjectsByProperty( name, value, result = [] ) {
  4589. if ( this[ name ] === value ) result.push( this );
  4590. const children = this.children;
  4591. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4592. children[ i ].getObjectsByProperty( name, value, result );
  4593. }
  4594. return result;
  4595. }
  4596. getWorldPosition( target ) {
  4597. this.updateWorldMatrix( true, false );
  4598. return target.setFromMatrixPosition( this.matrixWorld );
  4599. }
  4600. getWorldQuaternion( target ) {
  4601. this.updateWorldMatrix( true, false );
  4602. this.matrixWorld.decompose( _position$3, target, _scale$2 );
  4603. return target;
  4604. }
  4605. getWorldScale( target ) {
  4606. this.updateWorldMatrix( true, false );
  4607. this.matrixWorld.decompose( _position$3, _quaternion$2, target );
  4608. return target;
  4609. }
  4610. getWorldDirection( target ) {
  4611. this.updateWorldMatrix( true, false );
  4612. const e = this.matrixWorld.elements;
  4613. return target.set( e[ 8 ], e[ 9 ], e[ 10 ] ).normalize();
  4614. }
  4615. raycast( /* raycaster, intersects */ ) {}
  4616. traverse( callback ) {
  4617. callback( this );
  4618. const children = this.children;
  4619. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4620. children[ i ].traverse( callback );
  4621. }
  4622. }
  4623. traverseVisible( callback ) {
  4624. if ( this.visible === false ) return;
  4625. callback( this );
  4626. const children = this.children;
  4627. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4628. children[ i ].traverseVisible( callback );
  4629. }
  4630. }
  4631. traverseAncestors( callback ) {
  4632. const parent = this.parent;
  4633. if ( parent !== null ) {
  4634. callback( parent );
  4635. parent.traverseAncestors( callback );
  4636. }
  4637. }
  4638. updateMatrix() {
  4639. this.matrix.compose( this.position, this.quaternion, this.scale );
  4640. this.matrixWorldNeedsUpdate = true;
  4641. }
  4642. updateMatrixWorld( force ) {
  4643. if ( this.matrixAutoUpdate ) this.updateMatrix();
  4644. if ( this.matrixWorldNeedsUpdate || force ) {
  4645. if ( this.matrixWorldAutoUpdate === true ) {
  4646. if ( this.parent === null ) {
  4647. this.matrixWorld.copy( this.matrix );
  4648. } else {
  4649. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  4650. }
  4651. }
  4652. this.matrixWorldNeedsUpdate = false;
  4653. force = true;
  4654. }
  4655. // make sure descendants are updated if required
  4656. const children = this.children;
  4657. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4658. const child = children[ i ];
  4659. child.updateMatrixWorld( force );
  4660. }
  4661. }
  4662. updateWorldMatrix( updateParents, updateChildren ) {
  4663. const parent = this.parent;
  4664. if ( updateParents === true && parent !== null ) {
  4665. parent.updateWorldMatrix( true, false );
  4666. }
  4667. if ( this.matrixAutoUpdate ) this.updateMatrix();
  4668. if ( this.matrixWorldAutoUpdate === true ) {
  4669. if ( this.parent === null ) {
  4670. this.matrixWorld.copy( this.matrix );
  4671. } else {
  4672. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  4673. }
  4674. }
  4675. // make sure descendants are updated
  4676. if ( updateChildren === true ) {
  4677. const children = this.children;
  4678. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4679. const child = children[ i ];
  4680. child.updateWorldMatrix( false, true );
  4681. }
  4682. }
  4683. }
  4684. toJSON( meta ) {
  4685. // meta is a string when called from JSON.stringify
  4686. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  4687. const output = {};
  4688. // meta is a hash used to collect geometries, materials.
  4689. // not providing it implies that this is the root object
  4690. // being serialized.
  4691. if ( isRootObject ) {
  4692. // initialize meta obj
  4693. meta = {
  4694. geometries: {},
  4695. materials: {},
  4696. textures: {},
  4697. images: {},
  4698. shapes: {},
  4699. skeletons: {},
  4700. animations: {},
  4701. nodes: {}
  4702. };
  4703. output.metadata = {
  4704. version: 4.6,
  4705. type: 'Object',
  4706. generator: 'Object3D.toJSON'
  4707. };
  4708. }
  4709. // standard Object3D serialization
  4710. const object = {};
  4711. object.uuid = this.uuid;
  4712. object.type = this.type;
  4713. if ( this.name !== '' ) object.name = this.name;
  4714. if ( this.castShadow === true ) object.castShadow = true;
  4715. if ( this.receiveShadow === true ) object.receiveShadow = true;
  4716. if ( this.visible === false ) object.visible = false;
  4717. if ( this.frustumCulled === false ) object.frustumCulled = false;
  4718. if ( this.renderOrder !== 0 ) object.renderOrder = this.renderOrder;
  4719. if ( Object.keys( this.userData ).length > 0 ) object.userData = this.userData;
  4720. object.layers = this.layers.mask;
  4721. object.matrix = this.matrix.toArray();
  4722. object.up = this.up.toArray();
  4723. if ( this.matrixAutoUpdate === false ) object.matrixAutoUpdate = false;
  4724. // object specific properties
  4725. if ( this.isInstancedMesh ) {
  4726. object.type = 'InstancedMesh';
  4727. object.count = this.count;
  4728. object.instanceMatrix = this.instanceMatrix.toJSON();
  4729. if ( this.instanceColor !== null ) object.instanceColor = this.instanceColor.toJSON();
  4730. }
  4731. if ( this.isBatchedMesh ) {
  4732. object.type = 'BatchedMesh';
  4733. object.perObjectFrustumCulled = this.perObjectFrustumCulled;
  4734. object.sortObjects = this.sortObjects;
  4735. object.drawRanges = this._drawRanges;
  4736. object.reservedRanges = this._reservedRanges;
  4737. object.visibility = this._visibility;
  4738. object.active = this._active;
  4739. object.bounds = this._bounds.map( bound => ( {
  4740. boxInitialized: bound.boxInitialized,
  4741. boxMin: bound.box.min.toArray(),
  4742. boxMax: bound.box.max.toArray(),
  4743. sphereInitialized: bound.sphereInitialized,
  4744. sphereRadius: bound.sphere.radius,
  4745. sphereCenter: bound.sphere.center.toArray()
  4746. } ) );
  4747. object.maxInstanceCount = this._maxInstanceCount;
  4748. object.maxVertexCount = this._maxVertexCount;
  4749. object.maxIndexCount = this._maxIndexCount;
  4750. object.geometryInitialized = this._geometryInitialized;
  4751. object.geometryCount = this._geometryCount;
  4752. object.matricesTexture = this._matricesTexture.toJSON( meta );
  4753. if ( this._colorsTexture !== null ) object.colorsTexture = this._colorsTexture.toJSON( meta );
  4754. if ( this.boundingSphere !== null ) {
  4755. object.boundingSphere = {
  4756. center: object.boundingSphere.center.toArray(),
  4757. radius: object.boundingSphere.radius
  4758. };
  4759. }
  4760. if ( this.boundingBox !== null ) {
  4761. object.boundingBox = {
  4762. min: object.boundingBox.min.toArray(),
  4763. max: object.boundingBox.max.toArray()
  4764. };
  4765. }
  4766. }
  4767. //
  4768. function serialize( library, element ) {
  4769. if ( library[ element.uuid ] === undefined ) {
  4770. library[ element.uuid ] = element.toJSON( meta );
  4771. }
  4772. return element.uuid;
  4773. }
  4774. if ( this.isScene ) {
  4775. if ( this.background ) {
  4776. if ( this.background.isColor ) {
  4777. object.background = this.background.toJSON();
  4778. } else if ( this.background.isTexture ) {
  4779. object.background = this.background.toJSON( meta ).uuid;
  4780. }
  4781. }
  4782. if ( this.environment && this.environment.isTexture && this.environment.isRenderTargetTexture !== true ) {
  4783. object.environment = this.environment.toJSON( meta ).uuid;
  4784. }
  4785. } else if ( this.isMesh || this.isLine || this.isPoints ) {
  4786. object.geometry = serialize( meta.geometries, this.geometry );
  4787. const parameters = this.geometry.parameters;
  4788. if ( parameters !== undefined && parameters.shapes !== undefined ) {
  4789. const shapes = parameters.shapes;
  4790. if ( Array.isArray( shapes ) ) {
  4791. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  4792. const shape = shapes[ i ];
  4793. serialize( meta.shapes, shape );
  4794. }
  4795. } else {
  4796. serialize( meta.shapes, shapes );
  4797. }
  4798. }
  4799. }
  4800. if ( this.isSkinnedMesh ) {
  4801. object.bindMode = this.bindMode;
  4802. object.bindMatrix = this.bindMatrix.toArray();
  4803. if ( this.skeleton !== undefined ) {
  4804. serialize( meta.skeletons, this.skeleton );
  4805. object.skeleton = this.skeleton.uuid;
  4806. }
  4807. }
  4808. if ( this.material !== undefined ) {
  4809. if ( Array.isArray( this.material ) ) {
  4810. const uuids = [];
  4811. for ( let i = 0, l = this.material.length; i < l; i ++ ) {
  4812. uuids.push( serialize( meta.materials, this.material[ i ] ) );
  4813. }
  4814. object.material = uuids;
  4815. } else {
  4816. object.material = serialize( meta.materials, this.material );
  4817. }
  4818. }
  4819. //
  4820. if ( this.children.length > 0 ) {
  4821. object.children = [];
  4822. for ( let i = 0; i < this.children.length; i ++ ) {
  4823. object.children.push( this.children[ i ].toJSON( meta ).object );
  4824. }
  4825. }
  4826. //
  4827. if ( this.animations.length > 0 ) {
  4828. object.animations = [];
  4829. for ( let i = 0; i < this.animations.length; i ++ ) {
  4830. const animation = this.animations[ i ];
  4831. object.animations.push( serialize( meta.animations, animation ) );
  4832. }
  4833. }
  4834. if ( isRootObject ) {
  4835. const geometries = extractFromCache( meta.geometries );
  4836. const materials = extractFromCache( meta.materials );
  4837. const textures = extractFromCache( meta.textures );
  4838. const images = extractFromCache( meta.images );
  4839. const shapes = extractFromCache( meta.shapes );
  4840. const skeletons = extractFromCache( meta.skeletons );
  4841. const animations = extractFromCache( meta.animations );
  4842. const nodes = extractFromCache( meta.nodes );
  4843. if ( geometries.length > 0 ) output.geometries = geometries;
  4844. if ( materials.length > 0 ) output.materials = materials;
  4845. if ( textures.length > 0 ) output.textures = textures;
  4846. if ( images.length > 0 ) output.images = images;
  4847. if ( shapes.length > 0 ) output.shapes = shapes;
  4848. if ( skeletons.length > 0 ) output.skeletons = skeletons;
  4849. if ( animations.length > 0 ) output.animations = animations;
  4850. if ( nodes.length > 0 ) output.nodes = nodes;
  4851. }
  4852. output.object = object;
  4853. return output;
  4854. // extract data from the cache hash
  4855. // remove metadata on each item
  4856. // and return as array
  4857. function extractFromCache( cache ) {
  4858. const values = [];
  4859. for ( const key in cache ) {
  4860. const data = cache[ key ];
  4861. delete data.metadata;
  4862. values.push( data );
  4863. }
  4864. return values;
  4865. }
  4866. }
  4867. clone( recursive ) {
  4868. return new this.constructor().copy( this, recursive );
  4869. }
  4870. copy( source, recursive = true ) {
  4871. this.name = source.name;
  4872. this.up.copy( source.up );
  4873. this.position.copy( source.position );
  4874. this.rotation.order = source.rotation.order;
  4875. this.quaternion.copy( source.quaternion );
  4876. this.scale.copy( source.scale );
  4877. this.matrix.copy( source.matrix );
  4878. this.matrixWorld.copy( source.matrixWorld );
  4879. this.matrixAutoUpdate = source.matrixAutoUpdate;
  4880. this.matrixWorldAutoUpdate = source.matrixWorldAutoUpdate;
  4881. this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;
  4882. this.layers.mask = source.layers.mask;
  4883. this.visible = source.visible;
  4884. this.castShadow = source.castShadow;
  4885. this.receiveShadow = source.receiveShadow;
  4886. this.frustumCulled = source.frustumCulled;
  4887. this.renderOrder = source.renderOrder;
  4888. this.animations = source.animations.slice();
  4889. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  4890. if ( recursive === true ) {
  4891. for ( let i = 0; i < source.children.length; i ++ ) {
  4892. const child = source.children[ i ];
  4893. this.add( child.clone() );
  4894. }
  4895. }
  4896. return this;
  4897. }
  4898. }
  4899. Object3D.DEFAULT_UP = /*@__PURE__*/ new Vector3( 0, 1, 0 );
  4900. Object3D.DEFAULT_MATRIX_AUTO_UPDATE = true;
  4901. Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE = true;
  4902. const _v0$1 = /*@__PURE__*/ new Vector3();
  4903. const _v1$3 = /*@__PURE__*/ new Vector3();
  4904. const _v2$2 = /*@__PURE__*/ new Vector3();
  4905. const _v3$2 = /*@__PURE__*/ new Vector3();
  4906. const _vab = /*@__PURE__*/ new Vector3();
  4907. const _vac = /*@__PURE__*/ new Vector3();
  4908. const _vbc = /*@__PURE__*/ new Vector3();
  4909. const _vap = /*@__PURE__*/ new Vector3();
  4910. const _vbp = /*@__PURE__*/ new Vector3();
  4911. const _vcp = /*@__PURE__*/ new Vector3();
  4912. const _v40 = /*@__PURE__*/ new Vector4();
  4913. const _v41 = /*@__PURE__*/ new Vector4();
  4914. const _v42 = /*@__PURE__*/ new Vector4();
  4915. class Triangle {
  4916. constructor( a = new Vector3(), b = new Vector3(), c = new Vector3() ) {
  4917. this.a = a;
  4918. this.b = b;
  4919. this.c = c;
  4920. }
  4921. static getNormal( a, b, c, target ) {
  4922. target.subVectors( c, b );
  4923. _v0$1.subVectors( a, b );
  4924. target.cross( _v0$1 );
  4925. const targetLengthSq = target.lengthSq();
  4926. if ( targetLengthSq > 0 ) {
  4927. return target.multiplyScalar( 1 / Math.sqrt( targetLengthSq ) );
  4928. }
  4929. return target.set( 0, 0, 0 );
  4930. }
  4931. // static/instance method to calculate barycentric coordinates
  4932. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  4933. static getBarycoord( point, a, b, c, target ) {
  4934. _v0$1.subVectors( c, a );
  4935. _v1$3.subVectors( b, a );
  4936. _v2$2.subVectors( point, a );
  4937. const dot00 = _v0$1.dot( _v0$1 );
  4938. const dot01 = _v0$1.dot( _v1$3 );
  4939. const dot02 = _v0$1.dot( _v2$2 );
  4940. const dot11 = _v1$3.dot( _v1$3 );
  4941. const dot12 = _v1$3.dot( _v2$2 );
  4942. const denom = ( dot00 * dot11 - dot01 * dot01 );
  4943. // collinear or singular triangle
  4944. if ( denom === 0 ) {
  4945. target.set( 0, 0, 0 );
  4946. return null;
  4947. }
  4948. const invDenom = 1 / denom;
  4949. const u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  4950. const v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  4951. // barycentric coordinates must always sum to 1
  4952. return target.set( 1 - u - v, v, u );
  4953. }
  4954. static containsPoint( point, a, b, c ) {
  4955. // if the triangle is degenerate then we can't contain a point
  4956. if ( this.getBarycoord( point, a, b, c, _v3$2 ) === null ) {
  4957. return false;
  4958. }
  4959. return ( _v3$2.x >= 0 ) && ( _v3$2.y >= 0 ) && ( ( _v3$2.x + _v3$2.y ) <= 1 );
  4960. }
  4961. static getInterpolation( point, p1, p2, p3, v1, v2, v3, target ) {
  4962. if ( this.getBarycoord( point, p1, p2, p3, _v3$2 ) === null ) {
  4963. target.x = 0;
  4964. target.y = 0;
  4965. if ( 'z' in target ) target.z = 0;
  4966. if ( 'w' in target ) target.w = 0;
  4967. return null;
  4968. }
  4969. target.setScalar( 0 );
  4970. target.addScaledVector( v1, _v3$2.x );
  4971. target.addScaledVector( v2, _v3$2.y );
  4972. target.addScaledVector( v3, _v3$2.z );
  4973. return target;
  4974. }
  4975. static getInterpolatedAttribute( attr, i1, i2, i3, barycoord, target ) {
  4976. _v40.setScalar( 0 );
  4977. _v41.setScalar( 0 );
  4978. _v42.setScalar( 0 );
  4979. _v40.fromBufferAttribute( attr, i1 );
  4980. _v41.fromBufferAttribute( attr, i2 );
  4981. _v42.fromBufferAttribute( attr, i3 );
  4982. target.setScalar( 0 );
  4983. target.addScaledVector( _v40, barycoord.x );
  4984. target.addScaledVector( _v41, barycoord.y );
  4985. target.addScaledVector( _v42, barycoord.z );
  4986. return target;
  4987. }
  4988. static isFrontFacing( a, b, c, direction ) {
  4989. _v0$1.subVectors( c, b );
  4990. _v1$3.subVectors( a, b );
  4991. // strictly front facing
  4992. return ( _v0$1.cross( _v1$3 ).dot( direction ) < 0 ) ? true : false;
  4993. }
  4994. set( a, b, c ) {
  4995. this.a.copy( a );
  4996. this.b.copy( b );
  4997. this.c.copy( c );
  4998. return this;
  4999. }
  5000. setFromPointsAndIndices( points, i0, i1, i2 ) {
  5001. this.a.copy( points[ i0 ] );
  5002. this.b.copy( points[ i1 ] );
  5003. this.c.copy( points[ i2 ] );
  5004. return this;
  5005. }
  5006. setFromAttributeAndIndices( attribute, i0, i1, i2 ) {
  5007. this.a.fromBufferAttribute( attribute, i0 );
  5008. this.b.fromBufferAttribute( attribute, i1 );
  5009. this.c.fromBufferAttribute( attribute, i2 );
  5010. return this;
  5011. }
  5012. clone() {
  5013. return new this.constructor().copy( this );
  5014. }
  5015. copy( triangle ) {
  5016. this.a.copy( triangle.a );
  5017. this.b.copy( triangle.b );
  5018. this.c.copy( triangle.c );
  5019. return this;
  5020. }
  5021. getArea() {
  5022. _v0$1.subVectors( this.c, this.b );
  5023. _v1$3.subVectors( this.a, this.b );
  5024. return _v0$1.cross( _v1$3 ).length() * 0.5;
  5025. }
  5026. getMidpoint( target ) {
  5027. return target.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 );
  5028. }
  5029. getNormal( target ) {
  5030. return Triangle.getNormal( this.a, this.b, this.c, target );
  5031. }
  5032. getPlane( target ) {
  5033. return target.setFromCoplanarPoints( this.a, this.b, this.c );
  5034. }
  5035. getBarycoord( point, target ) {
  5036. return Triangle.getBarycoord( point, this.a, this.b, this.c, target );
  5037. }
  5038. getInterpolation( point, v1, v2, v3, target ) {
  5039. return Triangle.getInterpolation( point, this.a, this.b, this.c, v1, v2, v3, target );
  5040. }
  5041. containsPoint( point ) {
  5042. return Triangle.containsPoint( point, this.a, this.b, this.c );
  5043. }
  5044. isFrontFacing( direction ) {
  5045. return Triangle.isFrontFacing( this.a, this.b, this.c, direction );
  5046. }
  5047. intersectsBox( box ) {
  5048. return box.intersectsTriangle( this );
  5049. }
  5050. closestPointToPoint( p, target ) {
  5051. const a = this.a, b = this.b, c = this.c;
  5052. let v, w;
  5053. // algorithm thanks to Real-Time Collision Detection by Christer Ericson,
  5054. // published by Morgan Kaufmann Publishers, (c) 2005 Elsevier Inc.,
  5055. // under the accompanying license; see chapter 5.1.5 for detailed explanation.
  5056. // basically, we're distinguishing which of the voronoi regions of the triangle
  5057. // the point lies in with the minimum amount of redundant computation.
  5058. _vab.subVectors( b, a );
  5059. _vac.subVectors( c, a );
  5060. _vap.subVectors( p, a );
  5061. const d1 = _vab.dot( _vap );
  5062. const d2 = _vac.dot( _vap );
  5063. if ( d1 <= 0 && d2 <= 0 ) {
  5064. // vertex region of A; barycentric coords (1, 0, 0)
  5065. return target.copy( a );
  5066. }
  5067. _vbp.subVectors( p, b );
  5068. const d3 = _vab.dot( _vbp );
  5069. const d4 = _vac.dot( _vbp );
  5070. if ( d3 >= 0 && d4 <= d3 ) {
  5071. // vertex region of B; barycentric coords (0, 1, 0)
  5072. return target.copy( b );
  5073. }
  5074. const vc = d1 * d4 - d3 * d2;
  5075. if ( vc <= 0 && d1 >= 0 && d3 <= 0 ) {
  5076. v = d1 / ( d1 - d3 );
  5077. // edge region of AB; barycentric coords (1-v, v, 0)
  5078. return target.copy( a ).addScaledVector( _vab, v );
  5079. }
  5080. _vcp.subVectors( p, c );
  5081. const d5 = _vab.dot( _vcp );
  5082. const d6 = _vac.dot( _vcp );
  5083. if ( d6 >= 0 && d5 <= d6 ) {
  5084. // vertex region of C; barycentric coords (0, 0, 1)
  5085. return target.copy( c );
  5086. }
  5087. const vb = d5 * d2 - d1 * d6;
  5088. if ( vb <= 0 && d2 >= 0 && d6 <= 0 ) {
  5089. w = d2 / ( d2 - d6 );
  5090. // edge region of AC; barycentric coords (1-w, 0, w)
  5091. return target.copy( a ).addScaledVector( _vac, w );
  5092. }
  5093. const va = d3 * d6 - d5 * d4;
  5094. if ( va <= 0 && ( d4 - d3 ) >= 0 && ( d5 - d6 ) >= 0 ) {
  5095. _vbc.subVectors( c, b );
  5096. w = ( d4 - d3 ) / ( ( d4 - d3 ) + ( d5 - d6 ) );
  5097. // edge region of BC; barycentric coords (0, 1-w, w)
  5098. return target.copy( b ).addScaledVector( _vbc, w ); // edge region of BC
  5099. }
  5100. // face region
  5101. const denom = 1 / ( va + vb + vc );
  5102. // u = va * denom
  5103. v = vb * denom;
  5104. w = vc * denom;
  5105. return target.copy( a ).addScaledVector( _vab, v ).addScaledVector( _vac, w );
  5106. }
  5107. equals( triangle ) {
  5108. return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c );
  5109. }
  5110. }
  5111. const _colorKeywords = { 'aliceblue': 0xF0F8FF, 'antiquewhite': 0xFAEBD7, 'aqua': 0x00FFFF, 'aquamarine': 0x7FFFD4, 'azure': 0xF0FFFF,
  5112. 'beige': 0xF5F5DC, 'bisque': 0xFFE4C4, 'black': 0x000000, 'blanchedalmond': 0xFFEBCD, 'blue': 0x0000FF, 'blueviolet': 0x8A2BE2,
  5113. 'brown': 0xA52A2A, 'burlywood': 0xDEB887, 'cadetblue': 0x5F9EA0, 'chartreuse': 0x7FFF00, 'chocolate': 0xD2691E, 'coral': 0xFF7F50,
  5114. 'cornflowerblue': 0x6495ED, 'cornsilk': 0xFFF8DC, 'crimson': 0xDC143C, 'cyan': 0x00FFFF, 'darkblue': 0x00008B, 'darkcyan': 0x008B8B,
  5115. 'darkgoldenrod': 0xB8860B, 'darkgray': 0xA9A9A9, 'darkgreen': 0x006400, 'darkgrey': 0xA9A9A9, 'darkkhaki': 0xBDB76B, 'darkmagenta': 0x8B008B,
  5116. 'darkolivegreen': 0x556B2F, 'darkorange': 0xFF8C00, 'darkorchid': 0x9932CC, 'darkred': 0x8B0000, 'darksalmon': 0xE9967A, 'darkseagreen': 0x8FBC8F,
  5117. 'darkslateblue': 0x483D8B, 'darkslategray': 0x2F4F4F, 'darkslategrey': 0x2F4F4F, 'darkturquoise': 0x00CED1, 'darkviolet': 0x9400D3,
  5118. 'deeppink': 0xFF1493, 'deepskyblue': 0x00BFFF, 'dimgray': 0x696969, 'dimgrey': 0x696969, 'dodgerblue': 0x1E90FF, 'firebrick': 0xB22222,
  5119. 'floralwhite': 0xFFFAF0, 'forestgreen': 0x228B22, 'fuchsia': 0xFF00FF, 'gainsboro': 0xDCDCDC, 'ghostwhite': 0xF8F8FF, 'gold': 0xFFD700,
  5120. 'goldenrod': 0xDAA520, 'gray': 0x808080, 'green': 0x008000, 'greenyellow': 0xADFF2F, 'grey': 0x808080, 'honeydew': 0xF0FFF0, 'hotpink': 0xFF69B4,
  5121. 'indianred': 0xCD5C5C, 'indigo': 0x4B0082, 'ivory': 0xFFFFF0, 'khaki': 0xF0E68C, 'lavender': 0xE6E6FA, 'lavenderblush': 0xFFF0F5, 'lawngreen': 0x7CFC00,
  5122. 'lemonchiffon': 0xFFFACD, 'lightblue': 0xADD8E6, 'lightcoral': 0xF08080, 'lightcyan': 0xE0FFFF, 'lightgoldenrodyellow': 0xFAFAD2, 'lightgray': 0xD3D3D3,
  5123. 'lightgreen': 0x90EE90, 'lightgrey': 0xD3D3D3, 'lightpink': 0xFFB6C1, 'lightsalmon': 0xFFA07A, 'lightseagreen': 0x20B2AA, 'lightskyblue': 0x87CEFA,
  5124. 'lightslategray': 0x778899, 'lightslategrey': 0x778899, 'lightsteelblue': 0xB0C4DE, 'lightyellow': 0xFFFFE0, 'lime': 0x00FF00, 'limegreen': 0x32CD32,
  5125. 'linen': 0xFAF0E6, 'magenta': 0xFF00FF, 'maroon': 0x800000, 'mediumaquamarine': 0x66CDAA, 'mediumblue': 0x0000CD, 'mediumorchid': 0xBA55D3,
  5126. 'mediumpurple': 0x9370DB, 'mediumseagreen': 0x3CB371, 'mediumslateblue': 0x7B68EE, 'mediumspringgreen': 0x00FA9A, 'mediumturquoise': 0x48D1CC,
  5127. 'mediumvioletred': 0xC71585, 'midnightblue': 0x191970, 'mintcream': 0xF5FFFA, 'mistyrose': 0xFFE4E1, 'moccasin': 0xFFE4B5, 'navajowhite': 0xFFDEAD,
  5128. 'navy': 0x000080, 'oldlace': 0xFDF5E6, 'olive': 0x808000, 'olivedrab': 0x6B8E23, 'orange': 0xFFA500, 'orangered': 0xFF4500, 'orchid': 0xDA70D6,
  5129. 'palegoldenrod': 0xEEE8AA, 'palegreen': 0x98FB98, 'paleturquoise': 0xAFEEEE, 'palevioletred': 0xDB7093, 'papayawhip': 0xFFEFD5, 'peachpuff': 0xFFDAB9,
  5130. 'peru': 0xCD853F, 'pink': 0xFFC0CB, 'plum': 0xDDA0DD, 'powderblue': 0xB0E0E6, 'purple': 0x800080, 'rebeccapurple': 0x663399, 'red': 0xFF0000, 'rosybrown': 0xBC8F8F,
  5131. 'royalblue': 0x4169E1, 'saddlebrown': 0x8B4513, 'salmon': 0xFA8072, 'sandybrown': 0xF4A460, 'seagreen': 0x2E8B57, 'seashell': 0xFFF5EE,
  5132. 'sienna': 0xA0522D, 'silver': 0xC0C0C0, 'skyblue': 0x87CEEB, 'slateblue': 0x6A5ACD, 'slategray': 0x708090, 'slategrey': 0x708090, 'snow': 0xFFFAFA,
  5133. 'springgreen': 0x00FF7F, 'steelblue': 0x4682B4, 'tan': 0xD2B48C, 'teal': 0x008080, 'thistle': 0xD8BFD8, 'tomato': 0xFF6347, 'turquoise': 0x40E0D0,
  5134. 'violet': 0xEE82EE, 'wheat': 0xF5DEB3, 'white': 0xFFFFFF, 'whitesmoke': 0xF5F5F5, 'yellow': 0xFFFF00, 'yellowgreen': 0x9ACD32 };
  5135. const _hslA = { h: 0, s: 0, l: 0 };
  5136. const _hslB = { h: 0, s: 0, l: 0 };
  5137. function hue2rgb( p, q, t ) {
  5138. if ( t < 0 ) t += 1;
  5139. if ( t > 1 ) t -= 1;
  5140. if ( t < 1 / 6 ) return p + ( q - p ) * 6 * t;
  5141. if ( t < 1 / 2 ) return q;
  5142. if ( t < 2 / 3 ) return p + ( q - p ) * 6 * ( 2 / 3 - t );
  5143. return p;
  5144. }
  5145. class Color {
  5146. constructor( r, g, b ) {
  5147. this.isColor = true;
  5148. this.r = 1;
  5149. this.g = 1;
  5150. this.b = 1;
  5151. return this.set( r, g, b );
  5152. }
  5153. set( r, g, b ) {
  5154. if ( g === undefined && b === undefined ) {
  5155. // r is THREE.Color, hex or string
  5156. const value = r;
  5157. if ( value && value.isColor ) {
  5158. this.copy( value );
  5159. } else if ( typeof value === 'number' ) {
  5160. this.setHex( value );
  5161. } else if ( typeof value === 'string' ) {
  5162. this.setStyle( value );
  5163. }
  5164. } else {
  5165. this.setRGB( r, g, b );
  5166. }
  5167. return this;
  5168. }
  5169. setScalar( scalar ) {
  5170. this.r = scalar;
  5171. this.g = scalar;
  5172. this.b = scalar;
  5173. return this;
  5174. }
  5175. setHex( hex, colorSpace = SRGBColorSpace ) {
  5176. hex = Math.floor( hex );
  5177. this.r = ( hex >> 16 & 255 ) / 255;
  5178. this.g = ( hex >> 8 & 255 ) / 255;
  5179. this.b = ( hex & 255 ) / 255;
  5180. ColorManagement.toWorkingColorSpace( this, colorSpace );
  5181. return this;
  5182. }
  5183. setRGB( r, g, b, colorSpace = ColorManagement.workingColorSpace ) {
  5184. this.r = r;
  5185. this.g = g;
  5186. this.b = b;
  5187. ColorManagement.toWorkingColorSpace( this, colorSpace );
  5188. return this;
  5189. }
  5190. setHSL( h, s, l, colorSpace = ColorManagement.workingColorSpace ) {
  5191. // h,s,l ranges are in 0.0 - 1.0
  5192. h = euclideanModulo( h, 1 );
  5193. s = clamp$1( s, 0, 1 );
  5194. l = clamp$1( l, 0, 1 );
  5195. if ( s === 0 ) {
  5196. this.r = this.g = this.b = l;
  5197. } else {
  5198. const p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s );
  5199. const q = ( 2 * l ) - p;
  5200. this.r = hue2rgb( q, p, h + 1 / 3 );
  5201. this.g = hue2rgb( q, p, h );
  5202. this.b = hue2rgb( q, p, h - 1 / 3 );
  5203. }
  5204. ColorManagement.toWorkingColorSpace( this, colorSpace );
  5205. return this;
  5206. }
  5207. setStyle( style, colorSpace = SRGBColorSpace ) {
  5208. function handleAlpha( string ) {
  5209. if ( string === undefined ) return;
  5210. if ( parseFloat( string ) < 1 ) {
  5211. console.warn( 'THREE.Color: Alpha component of ' + style + ' will be ignored.' );
  5212. }
  5213. }
  5214. let m;
  5215. if ( m = /^(\w+)\(([^\)]*)\)/.exec( style ) ) {
  5216. // rgb / hsl
  5217. let color;
  5218. const name = m[ 1 ];
  5219. const components = m[ 2 ];
  5220. switch ( name ) {
  5221. case 'rgb':
  5222. case 'rgba':
  5223. if ( color = /^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  5224. // rgb(255,0,0) rgba(255,0,0,0.5)
  5225. handleAlpha( color[ 4 ] );
  5226. return this.setRGB(
  5227. Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255,
  5228. Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255,
  5229. Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255,
  5230. colorSpace
  5231. );
  5232. }
  5233. if ( color = /^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  5234. // rgb(100%,0%,0%) rgba(100%,0%,0%,0.5)
  5235. handleAlpha( color[ 4 ] );
  5236. return this.setRGB(
  5237. Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100,
  5238. Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100,
  5239. Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100,
  5240. colorSpace
  5241. );
  5242. }
  5243. break;
  5244. case 'hsl':
  5245. case 'hsla':
  5246. if ( color = /^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  5247. // hsl(120,50%,50%) hsla(120,50%,50%,0.5)
  5248. handleAlpha( color[ 4 ] );
  5249. return this.setHSL(
  5250. parseFloat( color[ 1 ] ) / 360,
  5251. parseFloat( color[ 2 ] ) / 100,
  5252. parseFloat( color[ 3 ] ) / 100,
  5253. colorSpace
  5254. );
  5255. }
  5256. break;
  5257. default:
  5258. console.warn( 'THREE.Color: Unknown color model ' + style );
  5259. }
  5260. } else if ( m = /^\#([A-Fa-f\d]+)$/.exec( style ) ) {
  5261. // hex color
  5262. const hex = m[ 1 ];
  5263. const size = hex.length;
  5264. if ( size === 3 ) {
  5265. // #ff0
  5266. return this.setRGB(
  5267. parseInt( hex.charAt( 0 ), 16 ) / 15,
  5268. parseInt( hex.charAt( 1 ), 16 ) / 15,
  5269. parseInt( hex.charAt( 2 ), 16 ) / 15,
  5270. colorSpace
  5271. );
  5272. } else if ( size === 6 ) {
  5273. // #ff0000
  5274. return this.setHex( parseInt( hex, 16 ), colorSpace );
  5275. } else {
  5276. console.warn( 'THREE.Color: Invalid hex color ' + style );
  5277. }
  5278. } else if ( style && style.length > 0 ) {
  5279. return this.setColorName( style, colorSpace );
  5280. }
  5281. return this;
  5282. }
  5283. setColorName( style, colorSpace = SRGBColorSpace ) {
  5284. // color keywords
  5285. const hex = _colorKeywords[ style.toLowerCase() ];
  5286. if ( hex !== undefined ) {
  5287. // red
  5288. this.setHex( hex, colorSpace );
  5289. } else {
  5290. // unknown color
  5291. console.warn( 'THREE.Color: Unknown color ' + style );
  5292. }
  5293. return this;
  5294. }
  5295. clone() {
  5296. return new this.constructor( this.r, this.g, this.b );
  5297. }
  5298. copy( color ) {
  5299. this.r = color.r;
  5300. this.g = color.g;
  5301. this.b = color.b;
  5302. return this;
  5303. }
  5304. copySRGBToLinear( color ) {
  5305. this.r = SRGBToLinear( color.r );
  5306. this.g = SRGBToLinear( color.g );
  5307. this.b = SRGBToLinear( color.b );
  5308. return this;
  5309. }
  5310. copyLinearToSRGB( color ) {
  5311. this.r = LinearToSRGB( color.r );
  5312. this.g = LinearToSRGB( color.g );
  5313. this.b = LinearToSRGB( color.b );
  5314. return this;
  5315. }
  5316. convertSRGBToLinear() {
  5317. this.copySRGBToLinear( this );
  5318. return this;
  5319. }
  5320. convertLinearToSRGB() {
  5321. this.copyLinearToSRGB( this );
  5322. return this;
  5323. }
  5324. getHex( colorSpace = SRGBColorSpace ) {
  5325. ColorManagement.fromWorkingColorSpace( _color.copy( this ), colorSpace );
  5326. return Math.round( clamp$1( _color.r * 255, 0, 255 ) ) * 65536 + Math.round( clamp$1( _color.g * 255, 0, 255 ) ) * 256 + Math.round( clamp$1( _color.b * 255, 0, 255 ) );
  5327. }
  5328. getHexString( colorSpace = SRGBColorSpace ) {
  5329. return ( '000000' + this.getHex( colorSpace ).toString( 16 ) ).slice( - 6 );
  5330. }
  5331. getHSL( target, colorSpace = ColorManagement.workingColorSpace ) {
  5332. // h,s,l ranges are in 0.0 - 1.0
  5333. ColorManagement.fromWorkingColorSpace( _color.copy( this ), colorSpace );
  5334. const r = _color.r, g = _color.g, b = _color.b;
  5335. const max = Math.max( r, g, b );
  5336. const min = Math.min( r, g, b );
  5337. let hue, saturation;
  5338. const lightness = ( min + max ) / 2.0;
  5339. if ( min === max ) {
  5340. hue = 0;
  5341. saturation = 0;
  5342. } else {
  5343. const delta = max - min;
  5344. saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min );
  5345. switch ( max ) {
  5346. case r: hue = ( g - b ) / delta + ( g < b ? 6 : 0 ); break;
  5347. case g: hue = ( b - r ) / delta + 2; break;
  5348. case b: hue = ( r - g ) / delta + 4; break;
  5349. }
  5350. hue /= 6;
  5351. }
  5352. target.h = hue;
  5353. target.s = saturation;
  5354. target.l = lightness;
  5355. return target;
  5356. }
  5357. getRGB( target, colorSpace = ColorManagement.workingColorSpace ) {
  5358. ColorManagement.fromWorkingColorSpace( _color.copy( this ), colorSpace );
  5359. target.r = _color.r;
  5360. target.g = _color.g;
  5361. target.b = _color.b;
  5362. return target;
  5363. }
  5364. getStyle( colorSpace = SRGBColorSpace ) {
  5365. ColorManagement.fromWorkingColorSpace( _color.copy( this ), colorSpace );
  5366. const r = _color.r, g = _color.g, b = _color.b;
  5367. if ( colorSpace !== SRGBColorSpace ) {
  5368. // Requires CSS Color Module Level 4 (https://www.w3.org/TR/css-color-4/).
  5369. return `color(${ colorSpace } ${ r.toFixed( 3 ) } ${ g.toFixed( 3 ) } ${ b.toFixed( 3 ) })`;
  5370. }
  5371. return `rgb(${ Math.round( r * 255 ) },${ Math.round( g * 255 ) },${ Math.round( b * 255 ) })`;
  5372. }
  5373. offsetHSL( h, s, l ) {
  5374. this.getHSL( _hslA );
  5375. return this.setHSL( _hslA.h + h, _hslA.s + s, _hslA.l + l );
  5376. }
  5377. add( color ) {
  5378. this.r += color.r;
  5379. this.g += color.g;
  5380. this.b += color.b;
  5381. return this;
  5382. }
  5383. addColors( color1, color2 ) {
  5384. this.r = color1.r + color2.r;
  5385. this.g = color1.g + color2.g;
  5386. this.b = color1.b + color2.b;
  5387. return this;
  5388. }
  5389. addScalar( s ) {
  5390. this.r += s;
  5391. this.g += s;
  5392. this.b += s;
  5393. return this;
  5394. }
  5395. sub( color ) {
  5396. this.r = Math.max( 0, this.r - color.r );
  5397. this.g = Math.max( 0, this.g - color.g );
  5398. this.b = Math.max( 0, this.b - color.b );
  5399. return this;
  5400. }
  5401. multiply( color ) {
  5402. this.r *= color.r;
  5403. this.g *= color.g;
  5404. this.b *= color.b;
  5405. return this;
  5406. }
  5407. multiplyScalar( s ) {
  5408. this.r *= s;
  5409. this.g *= s;
  5410. this.b *= s;
  5411. return this;
  5412. }
  5413. lerp( color, alpha ) {
  5414. this.r += ( color.r - this.r ) * alpha;
  5415. this.g += ( color.g - this.g ) * alpha;
  5416. this.b += ( color.b - this.b ) * alpha;
  5417. return this;
  5418. }
  5419. lerpColors( color1, color2, alpha ) {
  5420. this.r = color1.r + ( color2.r - color1.r ) * alpha;
  5421. this.g = color1.g + ( color2.g - color1.g ) * alpha;
  5422. this.b = color1.b + ( color2.b - color1.b ) * alpha;
  5423. return this;
  5424. }
  5425. lerpHSL( color, alpha ) {
  5426. this.getHSL( _hslA );
  5427. color.getHSL( _hslB );
  5428. const h = lerp( _hslA.h, _hslB.h, alpha );
  5429. const s = lerp( _hslA.s, _hslB.s, alpha );
  5430. const l = lerp( _hslA.l, _hslB.l, alpha );
  5431. this.setHSL( h, s, l );
  5432. return this;
  5433. }
  5434. setFromVector3( v ) {
  5435. this.r = v.x;
  5436. this.g = v.y;
  5437. this.b = v.z;
  5438. return this;
  5439. }
  5440. applyMatrix3( m ) {
  5441. const r = this.r, g = this.g, b = this.b;
  5442. const e = m.elements;
  5443. this.r = e[ 0 ] * r + e[ 3 ] * g + e[ 6 ] * b;
  5444. this.g = e[ 1 ] * r + e[ 4 ] * g + e[ 7 ] * b;
  5445. this.b = e[ 2 ] * r + e[ 5 ] * g + e[ 8 ] * b;
  5446. return this;
  5447. }
  5448. equals( c ) {
  5449. return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b );
  5450. }
  5451. fromArray( array, offset = 0 ) {
  5452. this.r = array[ offset ];
  5453. this.g = array[ offset + 1 ];
  5454. this.b = array[ offset + 2 ];
  5455. return this;
  5456. }
  5457. toArray( array = [], offset = 0 ) {
  5458. array[ offset ] = this.r;
  5459. array[ offset + 1 ] = this.g;
  5460. array[ offset + 2 ] = this.b;
  5461. return array;
  5462. }
  5463. fromBufferAttribute( attribute, index ) {
  5464. this.r = attribute.getX( index );
  5465. this.g = attribute.getY( index );
  5466. this.b = attribute.getZ( index );
  5467. return this;
  5468. }
  5469. toJSON() {
  5470. return this.getHex();
  5471. }
  5472. *[ Symbol.iterator ]() {
  5473. yield this.r;
  5474. yield this.g;
  5475. yield this.b;
  5476. }
  5477. }
  5478. const _color = /*@__PURE__*/ new Color();
  5479. Color.NAMES = _colorKeywords;
  5480. let _materialId = 0;
  5481. class Material extends EventDispatcher {
  5482. static get type() {
  5483. return 'Material';
  5484. }
  5485. get type() {
  5486. return this.constructor.type;
  5487. }
  5488. set type( _value ) { /* */ }
  5489. constructor() {
  5490. super();
  5491. this.isMaterial = true;
  5492. Object.defineProperty( this, 'id', { value: _materialId ++ } );
  5493. this.uuid = generateUUID();
  5494. this.name = '';
  5495. this.blending = NormalBlending;
  5496. this.side = FrontSide;
  5497. this.vertexColors = false;
  5498. this.opacity = 1;
  5499. this.transparent = false;
  5500. this.alphaHash = false;
  5501. this.blendSrc = SrcAlphaFactor;
  5502. this.blendDst = OneMinusSrcAlphaFactor;
  5503. this.blendEquation = AddEquation;
  5504. this.blendSrcAlpha = null;
  5505. this.blendDstAlpha = null;
  5506. this.blendEquationAlpha = null;
  5507. this.blendColor = new Color( 0, 0, 0 );
  5508. this.blendAlpha = 0;
  5509. this.depthFunc = LessEqualDepth;
  5510. this.depthTest = true;
  5511. this.depthWrite = true;
  5512. this.stencilWriteMask = 0xff;
  5513. this.stencilFunc = AlwaysStencilFunc;
  5514. this.stencilRef = 0;
  5515. this.stencilFuncMask = 0xff;
  5516. this.stencilFail = KeepStencilOp;
  5517. this.stencilZFail = KeepStencilOp;
  5518. this.stencilZPass = KeepStencilOp;
  5519. this.stencilWrite = false;
  5520. this.clippingPlanes = null;
  5521. this.clipIntersection = false;
  5522. this.clipShadows = false;
  5523. this.shadowSide = null;
  5524. this.colorWrite = true;
  5525. this.precision = null; // override the renderer's default precision for this material
  5526. this.polygonOffset = false;
  5527. this.polygonOffsetFactor = 0;
  5528. this.polygonOffsetUnits = 0;
  5529. this.dithering = false;
  5530. this.alphaToCoverage = false;
  5531. this.premultipliedAlpha = false;
  5532. this.forceSinglePass = false;
  5533. this.visible = true;
  5534. this.toneMapped = true;
  5535. this.userData = {};
  5536. this.version = 0;
  5537. this._alphaTest = 0;
  5538. }
  5539. get alphaTest() {
  5540. return this._alphaTest;
  5541. }
  5542. set alphaTest( value ) {
  5543. if ( this._alphaTest > 0 !== value > 0 ) {
  5544. this.version ++;
  5545. }
  5546. this._alphaTest = value;
  5547. }
  5548. // onBeforeRender and onBeforeCompile only supported in WebGLRenderer
  5549. onBeforeRender( /* renderer, scene, camera, geometry, object, group */ ) {}
  5550. onBeforeCompile( /* shaderobject, renderer */ ) {}
  5551. customProgramCacheKey() {
  5552. return this.onBeforeCompile.toString();
  5553. }
  5554. setValues( values ) {
  5555. if ( values === undefined ) return;
  5556. for ( const key in values ) {
  5557. const newValue = values[ key ];
  5558. if ( newValue === undefined ) {
  5559. console.warn( `THREE.Material: parameter '${ key }' has value of undefined.` );
  5560. continue;
  5561. }
  5562. const currentValue = this[ key ];
  5563. if ( currentValue === undefined ) {
  5564. console.warn( `THREE.Material: '${ key }' is not a property of THREE.${ this.type }.` );
  5565. continue;
  5566. }
  5567. if ( currentValue && currentValue.isColor ) {
  5568. currentValue.set( newValue );
  5569. } else if ( ( currentValue && currentValue.isVector3 ) && ( newValue && newValue.isVector3 ) ) {
  5570. currentValue.copy( newValue );
  5571. } else {
  5572. this[ key ] = newValue;
  5573. }
  5574. }
  5575. }
  5576. toJSON( meta ) {
  5577. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  5578. if ( isRootObject ) {
  5579. meta = {
  5580. textures: {},
  5581. images: {}
  5582. };
  5583. }
  5584. const data = {
  5585. metadata: {
  5586. version: 4.6,
  5587. type: 'Material',
  5588. generator: 'Material.toJSON'
  5589. }
  5590. };
  5591. // standard Material serialization
  5592. data.uuid = this.uuid;
  5593. data.type = this.type;
  5594. if ( this.name !== '' ) data.name = this.name;
  5595. if ( this.color && this.color.isColor ) data.color = this.color.getHex();
  5596. if ( this.roughness !== undefined ) data.roughness = this.roughness;
  5597. if ( this.metalness !== undefined ) data.metalness = this.metalness;
  5598. if ( this.sheen !== undefined ) data.sheen = this.sheen;
  5599. if ( this.sheenColor && this.sheenColor.isColor ) data.sheenColor = this.sheenColor.getHex();
  5600. if ( this.sheenRoughness !== undefined ) data.sheenRoughness = this.sheenRoughness;
  5601. if ( this.emissive && this.emissive.isColor ) data.emissive = this.emissive.getHex();
  5602. if ( this.emissiveIntensity !== undefined && this.emissiveIntensity !== 1 ) data.emissiveIntensity = this.emissiveIntensity;
  5603. if ( this.specular && this.specular.isColor ) data.specular = this.specular.getHex();
  5604. if ( this.specularIntensity !== undefined ) data.specularIntensity = this.specularIntensity;
  5605. if ( this.specularColor && this.specularColor.isColor ) data.specularColor = this.specularColor.getHex();
  5606. if ( this.shininess !== undefined ) data.shininess = this.shininess;
  5607. if ( this.clearcoat !== undefined ) data.clearcoat = this.clearcoat;
  5608. if ( this.clearcoatRoughness !== undefined ) data.clearcoatRoughness = this.clearcoatRoughness;
  5609. if ( this.clearcoatMap && this.clearcoatMap.isTexture ) {
  5610. data.clearcoatMap = this.clearcoatMap.toJSON( meta ).uuid;
  5611. }
  5612. if ( this.clearcoatRoughnessMap && this.clearcoatRoughnessMap.isTexture ) {
  5613. data.clearcoatRoughnessMap = this.clearcoatRoughnessMap.toJSON( meta ).uuid;
  5614. }
  5615. if ( this.clearcoatNormalMap && this.clearcoatNormalMap.isTexture ) {
  5616. data.clearcoatNormalMap = this.clearcoatNormalMap.toJSON( meta ).uuid;
  5617. data.clearcoatNormalScale = this.clearcoatNormalScale.toArray();
  5618. }
  5619. if ( this.dispersion !== undefined ) data.dispersion = this.dispersion;
  5620. if ( this.iridescence !== undefined ) data.iridescence = this.iridescence;
  5621. if ( this.iridescenceIOR !== undefined ) data.iridescenceIOR = this.iridescenceIOR;
  5622. if ( this.iridescenceThicknessRange !== undefined ) data.iridescenceThicknessRange = this.iridescenceThicknessRange;
  5623. if ( this.iridescenceMap && this.iridescenceMap.isTexture ) {
  5624. data.iridescenceMap = this.iridescenceMap.toJSON( meta ).uuid;
  5625. }
  5626. if ( this.iridescenceThicknessMap && this.iridescenceThicknessMap.isTexture ) {
  5627. data.iridescenceThicknessMap = this.iridescenceThicknessMap.toJSON( meta ).uuid;
  5628. }
  5629. if ( this.anisotropy !== undefined ) data.anisotropy = this.anisotropy;
  5630. if ( this.anisotropyRotation !== undefined ) data.anisotropyRotation = this.anisotropyRotation;
  5631. if ( this.anisotropyMap && this.anisotropyMap.isTexture ) {
  5632. data.anisotropyMap = this.anisotropyMap.toJSON( meta ).uuid;
  5633. }
  5634. if ( this.map && this.map.isTexture ) data.map = this.map.toJSON( meta ).uuid;
  5635. if ( this.matcap && this.matcap.isTexture ) data.matcap = this.matcap.toJSON( meta ).uuid;
  5636. if ( this.alphaMap && this.alphaMap.isTexture ) data.alphaMap = this.alphaMap.toJSON( meta ).uuid;
  5637. if ( this.lightMap && this.lightMap.isTexture ) {
  5638. data.lightMap = this.lightMap.toJSON( meta ).uuid;
  5639. data.lightMapIntensity = this.lightMapIntensity;
  5640. }
  5641. if ( this.aoMap && this.aoMap.isTexture ) {
  5642. data.aoMap = this.aoMap.toJSON( meta ).uuid;
  5643. data.aoMapIntensity = this.aoMapIntensity;
  5644. }
  5645. if ( this.bumpMap && this.bumpMap.isTexture ) {
  5646. data.bumpMap = this.bumpMap.toJSON( meta ).uuid;
  5647. data.bumpScale = this.bumpScale;
  5648. }
  5649. if ( this.normalMap && this.normalMap.isTexture ) {
  5650. data.normalMap = this.normalMap.toJSON( meta ).uuid;
  5651. data.normalMapType = this.normalMapType;
  5652. data.normalScale = this.normalScale.toArray();
  5653. }
  5654. if ( this.displacementMap && this.displacementMap.isTexture ) {
  5655. data.displacementMap = this.displacementMap.toJSON( meta ).uuid;
  5656. data.displacementScale = this.displacementScale;
  5657. data.displacementBias = this.displacementBias;
  5658. }
  5659. if ( this.roughnessMap && this.roughnessMap.isTexture ) data.roughnessMap = this.roughnessMap.toJSON( meta ).uuid;
  5660. if ( this.metalnessMap && this.metalnessMap.isTexture ) data.metalnessMap = this.metalnessMap.toJSON( meta ).uuid;
  5661. if ( this.emissiveMap && this.emissiveMap.isTexture ) data.emissiveMap = this.emissiveMap.toJSON( meta ).uuid;
  5662. if ( this.specularMap && this.specularMap.isTexture ) data.specularMap = this.specularMap.toJSON( meta ).uuid;
  5663. if ( this.specularIntensityMap && this.specularIntensityMap.isTexture ) data.specularIntensityMap = this.specularIntensityMap.toJSON( meta ).uuid;
  5664. if ( this.specularColorMap && this.specularColorMap.isTexture ) data.specularColorMap = this.specularColorMap.toJSON( meta ).uuid;
  5665. if ( this.envMap && this.envMap.isTexture ) {
  5666. data.envMap = this.envMap.toJSON( meta ).uuid;
  5667. if ( this.combine !== undefined ) data.combine = this.combine;
  5668. }
  5669. if ( this.envMapRotation !== undefined ) data.envMapRotation = this.envMapRotation.toArray();
  5670. if ( this.envMapIntensity !== undefined ) data.envMapIntensity = this.envMapIntensity;
  5671. if ( this.reflectivity !== undefined ) data.reflectivity = this.reflectivity;
  5672. if ( this.refractionRatio !== undefined ) data.refractionRatio = this.refractionRatio;
  5673. if ( this.gradientMap && this.gradientMap.isTexture ) {
  5674. data.gradientMap = this.gradientMap.toJSON( meta ).uuid;
  5675. }
  5676. if ( this.transmission !== undefined ) data.transmission = this.transmission;
  5677. if ( this.transmissionMap && this.transmissionMap.isTexture ) data.transmissionMap = this.transmissionMap.toJSON( meta ).uuid;
  5678. if ( this.thickness !== undefined ) data.thickness = this.thickness;
  5679. if ( this.thicknessMap && this.thicknessMap.isTexture ) data.thicknessMap = this.thicknessMap.toJSON( meta ).uuid;
  5680. if ( this.attenuationDistance !== undefined && this.attenuationDistance !== Infinity ) data.attenuationDistance = this.attenuationDistance;
  5681. if ( this.attenuationColor !== undefined ) data.attenuationColor = this.attenuationColor.getHex();
  5682. if ( this.size !== undefined ) data.size = this.size;
  5683. if ( this.shadowSide !== null ) data.shadowSide = this.shadowSide;
  5684. if ( this.sizeAttenuation !== undefined ) data.sizeAttenuation = this.sizeAttenuation;
  5685. if ( this.blending !== NormalBlending ) data.blending = this.blending;
  5686. if ( this.side !== FrontSide ) data.side = this.side;
  5687. if ( this.vertexColors === true ) data.vertexColors = true;
  5688. if ( this.opacity < 1 ) data.opacity = this.opacity;
  5689. if ( this.transparent === true ) data.transparent = true;
  5690. if ( this.blendSrc !== SrcAlphaFactor ) data.blendSrc = this.blendSrc;
  5691. if ( this.blendDst !== OneMinusSrcAlphaFactor ) data.blendDst = this.blendDst;
  5692. if ( this.blendEquation !== AddEquation ) data.blendEquation = this.blendEquation;
  5693. if ( this.blendSrcAlpha !== null ) data.blendSrcAlpha = this.blendSrcAlpha;
  5694. if ( this.blendDstAlpha !== null ) data.blendDstAlpha = this.blendDstAlpha;
  5695. if ( this.blendEquationAlpha !== null ) data.blendEquationAlpha = this.blendEquationAlpha;
  5696. if ( this.blendColor && this.blendColor.isColor ) data.blendColor = this.blendColor.getHex();
  5697. if ( this.blendAlpha !== 0 ) data.blendAlpha = this.blendAlpha;
  5698. if ( this.depthFunc !== LessEqualDepth ) data.depthFunc = this.depthFunc;
  5699. if ( this.depthTest === false ) data.depthTest = this.depthTest;
  5700. if ( this.depthWrite === false ) data.depthWrite = this.depthWrite;
  5701. if ( this.colorWrite === false ) data.colorWrite = this.colorWrite;
  5702. if ( this.stencilWriteMask !== 0xff ) data.stencilWriteMask = this.stencilWriteMask;
  5703. if ( this.stencilFunc !== AlwaysStencilFunc ) data.stencilFunc = this.stencilFunc;
  5704. if ( this.stencilRef !== 0 ) data.stencilRef = this.stencilRef;
  5705. if ( this.stencilFuncMask !== 0xff ) data.stencilFuncMask = this.stencilFuncMask;
  5706. if ( this.stencilFail !== KeepStencilOp ) data.stencilFail = this.stencilFail;
  5707. if ( this.stencilZFail !== KeepStencilOp ) data.stencilZFail = this.stencilZFail;
  5708. if ( this.stencilZPass !== KeepStencilOp ) data.stencilZPass = this.stencilZPass;
  5709. if ( this.stencilWrite === true ) data.stencilWrite = this.stencilWrite;
  5710. // rotation (SpriteMaterial)
  5711. if ( this.rotation !== undefined && this.rotation !== 0 ) data.rotation = this.rotation;
  5712. if ( this.polygonOffset === true ) data.polygonOffset = true;
  5713. if ( this.polygonOffsetFactor !== 0 ) data.polygonOffsetFactor = this.polygonOffsetFactor;
  5714. if ( this.polygonOffsetUnits !== 0 ) data.polygonOffsetUnits = this.polygonOffsetUnits;
  5715. if ( this.linewidth !== undefined && this.linewidth !== 1 ) data.linewidth = this.linewidth;
  5716. if ( this.dashSize !== undefined ) data.dashSize = this.dashSize;
  5717. if ( this.gapSize !== undefined ) data.gapSize = this.gapSize;
  5718. if ( this.scale !== undefined ) data.scale = this.scale;
  5719. if ( this.dithering === true ) data.dithering = true;
  5720. if ( this.alphaTest > 0 ) data.alphaTest = this.alphaTest;
  5721. if ( this.alphaHash === true ) data.alphaHash = true;
  5722. if ( this.alphaToCoverage === true ) data.alphaToCoverage = true;
  5723. if ( this.premultipliedAlpha === true ) data.premultipliedAlpha = true;
  5724. if ( this.forceSinglePass === true ) data.forceSinglePass = true;
  5725. if ( this.wireframe === true ) data.wireframe = true;
  5726. if ( this.wireframeLinewidth > 1 ) data.wireframeLinewidth = this.wireframeLinewidth;
  5727. if ( this.wireframeLinecap !== 'round' ) data.wireframeLinecap = this.wireframeLinecap;
  5728. if ( this.wireframeLinejoin !== 'round' ) data.wireframeLinejoin = this.wireframeLinejoin;
  5729. if ( this.flatShading === true ) data.flatShading = true;
  5730. if ( this.visible === false ) data.visible = false;
  5731. if ( this.toneMapped === false ) data.toneMapped = false;
  5732. if ( this.fog === false ) data.fog = false;
  5733. if ( Object.keys( this.userData ).length > 0 ) data.userData = this.userData;
  5734. // TODO: Copied from Object3D.toJSON
  5735. function extractFromCache( cache ) {
  5736. const values = [];
  5737. for ( const key in cache ) {
  5738. const data = cache[ key ];
  5739. delete data.metadata;
  5740. values.push( data );
  5741. }
  5742. return values;
  5743. }
  5744. if ( isRootObject ) {
  5745. const textures = extractFromCache( meta.textures );
  5746. const images = extractFromCache( meta.images );
  5747. if ( textures.length > 0 ) data.textures = textures;
  5748. if ( images.length > 0 ) data.images = images;
  5749. }
  5750. return data;
  5751. }
  5752. clone() {
  5753. return new this.constructor().copy( this );
  5754. }
  5755. copy( source ) {
  5756. this.name = source.name;
  5757. this.blending = source.blending;
  5758. this.side = source.side;
  5759. this.vertexColors = source.vertexColors;
  5760. this.opacity = source.opacity;
  5761. this.transparent = source.transparent;
  5762. this.blendSrc = source.blendSrc;
  5763. this.blendDst = source.blendDst;
  5764. this.blendEquation = source.blendEquation;
  5765. this.blendSrcAlpha = source.blendSrcAlpha;
  5766. this.blendDstAlpha = source.blendDstAlpha;
  5767. this.blendEquationAlpha = source.blendEquationAlpha;
  5768. this.blendColor.copy( source.blendColor );
  5769. this.blendAlpha = source.blendAlpha;
  5770. this.depthFunc = source.depthFunc;
  5771. this.depthTest = source.depthTest;
  5772. this.depthWrite = source.depthWrite;
  5773. this.stencilWriteMask = source.stencilWriteMask;
  5774. this.stencilFunc = source.stencilFunc;
  5775. this.stencilRef = source.stencilRef;
  5776. this.stencilFuncMask = source.stencilFuncMask;
  5777. this.stencilFail = source.stencilFail;
  5778. this.stencilZFail = source.stencilZFail;
  5779. this.stencilZPass = source.stencilZPass;
  5780. this.stencilWrite = source.stencilWrite;
  5781. const srcPlanes = source.clippingPlanes;
  5782. let dstPlanes = null;
  5783. if ( srcPlanes !== null ) {
  5784. const n = srcPlanes.length;
  5785. dstPlanes = new Array( n );
  5786. for ( let i = 0; i !== n; ++ i ) {
  5787. dstPlanes[ i ] = srcPlanes[ i ].clone();
  5788. }
  5789. }
  5790. this.clippingPlanes = dstPlanes;
  5791. this.clipIntersection = source.clipIntersection;
  5792. this.clipShadows = source.clipShadows;
  5793. this.shadowSide = source.shadowSide;
  5794. this.colorWrite = source.colorWrite;
  5795. this.precision = source.precision;
  5796. this.polygonOffset = source.polygonOffset;
  5797. this.polygonOffsetFactor = source.polygonOffsetFactor;
  5798. this.polygonOffsetUnits = source.polygonOffsetUnits;
  5799. this.dithering = source.dithering;
  5800. this.alphaTest = source.alphaTest;
  5801. this.alphaHash = source.alphaHash;
  5802. this.alphaToCoverage = source.alphaToCoverage;
  5803. this.premultipliedAlpha = source.premultipliedAlpha;
  5804. this.forceSinglePass = source.forceSinglePass;
  5805. this.visible = source.visible;
  5806. this.toneMapped = source.toneMapped;
  5807. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  5808. return this;
  5809. }
  5810. dispose() {
  5811. this.dispatchEvent( { type: 'dispose' } );
  5812. }
  5813. set needsUpdate( value ) {
  5814. if ( value === true ) this.version ++;
  5815. }
  5816. onBuild( /* shaderobject, renderer */ ) {
  5817. console.warn( 'Material: onBuild() has been removed.' ); // @deprecated, r166
  5818. }
  5819. }
  5820. class MeshBasicMaterial extends Material {
  5821. static get type() {
  5822. return 'MeshBasicMaterial';
  5823. }
  5824. constructor( parameters ) {
  5825. super();
  5826. this.isMeshBasicMaterial = true;
  5827. this.color = new Color( 0xffffff ); // emissive
  5828. this.map = null;
  5829. this.lightMap = null;
  5830. this.lightMapIntensity = 1.0;
  5831. this.aoMap = null;
  5832. this.aoMapIntensity = 1.0;
  5833. this.specularMap = null;
  5834. this.alphaMap = null;
  5835. this.envMap = null;
  5836. this.envMapRotation = new Euler();
  5837. this.combine = MultiplyOperation;
  5838. this.reflectivity = 1;
  5839. this.refractionRatio = 0.98;
  5840. this.wireframe = false;
  5841. this.wireframeLinewidth = 1;
  5842. this.wireframeLinecap = 'round';
  5843. this.wireframeLinejoin = 'round';
  5844. this.fog = true;
  5845. this.setValues( parameters );
  5846. }
  5847. copy( source ) {
  5848. super.copy( source );
  5849. this.color.copy( source.color );
  5850. this.map = source.map;
  5851. this.lightMap = source.lightMap;
  5852. this.lightMapIntensity = source.lightMapIntensity;
  5853. this.aoMap = source.aoMap;
  5854. this.aoMapIntensity = source.aoMapIntensity;
  5855. this.specularMap = source.specularMap;
  5856. this.alphaMap = source.alphaMap;
  5857. this.envMap = source.envMap;
  5858. this.envMapRotation.copy( source.envMapRotation );
  5859. this.combine = source.combine;
  5860. this.reflectivity = source.reflectivity;
  5861. this.refractionRatio = source.refractionRatio;
  5862. this.wireframe = source.wireframe;
  5863. this.wireframeLinewidth = source.wireframeLinewidth;
  5864. this.wireframeLinecap = source.wireframeLinecap;
  5865. this.wireframeLinejoin = source.wireframeLinejoin;
  5866. this.fog = source.fog;
  5867. return this;
  5868. }
  5869. }
  5870. // Fast Half Float Conversions, http://www.fox-toolkit.org/ftp/fasthalffloatconversion.pdf
  5871. const _tables = /*@__PURE__*/ _generateTables();
  5872. function _generateTables() {
  5873. // float32 to float16 helpers
  5874. const buffer = new ArrayBuffer( 4 );
  5875. const floatView = new Float32Array( buffer );
  5876. const uint32View = new Uint32Array( buffer );
  5877. const baseTable = new Uint32Array( 512 );
  5878. const shiftTable = new Uint32Array( 512 );
  5879. for ( let i = 0; i < 256; ++ i ) {
  5880. const e = i - 127;
  5881. // very small number (0, -0)
  5882. if ( e < - 27 ) {
  5883. baseTable[ i ] = 0x0000;
  5884. baseTable[ i | 0x100 ] = 0x8000;
  5885. shiftTable[ i ] = 24;
  5886. shiftTable[ i | 0x100 ] = 24;
  5887. // small number (denorm)
  5888. } else if ( e < - 14 ) {
  5889. baseTable[ i ] = 0x0400 >> ( - e - 14 );
  5890. baseTable[ i | 0x100 ] = ( 0x0400 >> ( - e - 14 ) ) | 0x8000;
  5891. shiftTable[ i ] = - e - 1;
  5892. shiftTable[ i | 0x100 ] = - e - 1;
  5893. // normal number
  5894. } else if ( e <= 15 ) {
  5895. baseTable[ i ] = ( e + 15 ) << 10;
  5896. baseTable[ i | 0x100 ] = ( ( e + 15 ) << 10 ) | 0x8000;
  5897. shiftTable[ i ] = 13;
  5898. shiftTable[ i | 0x100 ] = 13;
  5899. // large number (Infinity, -Infinity)
  5900. } else if ( e < 128 ) {
  5901. baseTable[ i ] = 0x7c00;
  5902. baseTable[ i | 0x100 ] = 0xfc00;
  5903. shiftTable[ i ] = 24;
  5904. shiftTable[ i | 0x100 ] = 24;
  5905. // stay (NaN, Infinity, -Infinity)
  5906. } else {
  5907. baseTable[ i ] = 0x7c00;
  5908. baseTable[ i | 0x100 ] = 0xfc00;
  5909. shiftTable[ i ] = 13;
  5910. shiftTable[ i | 0x100 ] = 13;
  5911. }
  5912. }
  5913. // float16 to float32 helpers
  5914. const mantissaTable = new Uint32Array( 2048 );
  5915. const exponentTable = new Uint32Array( 64 );
  5916. const offsetTable = new Uint32Array( 64 );
  5917. for ( let i = 1; i < 1024; ++ i ) {
  5918. let m = i << 13; // zero pad mantissa bits
  5919. let e = 0; // zero exponent
  5920. // normalized
  5921. while ( ( m & 0x00800000 ) === 0 ) {
  5922. m <<= 1;
  5923. e -= 0x00800000; // decrement exponent
  5924. }
  5925. m &= ~ 0x00800000; // clear leading 1 bit
  5926. e += 0x38800000; // adjust bias
  5927. mantissaTable[ i ] = m | e;
  5928. }
  5929. for ( let i = 1024; i < 2048; ++ i ) {
  5930. mantissaTable[ i ] = 0x38000000 + ( ( i - 1024 ) << 13 );
  5931. }
  5932. for ( let i = 1; i < 31; ++ i ) {
  5933. exponentTable[ i ] = i << 23;
  5934. }
  5935. exponentTable[ 31 ] = 0x47800000;
  5936. exponentTable[ 32 ] = 0x80000000;
  5937. for ( let i = 33; i < 63; ++ i ) {
  5938. exponentTable[ i ] = 0x80000000 + ( ( i - 32 ) << 23 );
  5939. }
  5940. exponentTable[ 63 ] = 0xc7800000;
  5941. for ( let i = 1; i < 64; ++ i ) {
  5942. if ( i !== 32 ) {
  5943. offsetTable[ i ] = 1024;
  5944. }
  5945. }
  5946. return {
  5947. floatView: floatView,
  5948. uint32View: uint32View,
  5949. baseTable: baseTable,
  5950. shiftTable: shiftTable,
  5951. mantissaTable: mantissaTable,
  5952. exponentTable: exponentTable,
  5953. offsetTable: offsetTable
  5954. };
  5955. }
  5956. // float32 to float16
  5957. function toHalfFloat( val ) {
  5958. if ( Math.abs( val ) > 65504 ) console.warn( 'THREE.DataUtils.toHalfFloat(): Value out of range.' );
  5959. val = clamp$1( val, - 65504, 65504 );
  5960. _tables.floatView[ 0 ] = val;
  5961. const f = _tables.uint32View[ 0 ];
  5962. const e = ( f >> 23 ) & 0x1ff;
  5963. return _tables.baseTable[ e ] + ( ( f & 0x007fffff ) >> _tables.shiftTable[ e ] );
  5964. }
  5965. // float16 to float32
  5966. function fromHalfFloat( val ) {
  5967. const m = val >> 10;
  5968. _tables.uint32View[ 0 ] = _tables.mantissaTable[ _tables.offsetTable[ m ] + ( val & 0x3ff ) ] + _tables.exponentTable[ m ];
  5969. return _tables.floatView[ 0 ];
  5970. }
  5971. const DataUtils = {
  5972. toHalfFloat: toHalfFloat,
  5973. fromHalfFloat: fromHalfFloat,
  5974. };
  5975. const _vector$9 = /*@__PURE__*/ new Vector3();
  5976. const _vector2$1 = /*@__PURE__*/ new Vector2();
  5977. class BufferAttribute {
  5978. constructor( array, itemSize, normalized = false ) {
  5979. if ( Array.isArray( array ) ) {
  5980. throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' );
  5981. }
  5982. this.isBufferAttribute = true;
  5983. this.name = '';
  5984. this.array = array;
  5985. this.itemSize = itemSize;
  5986. this.count = array !== undefined ? array.length / itemSize : 0;
  5987. this.normalized = normalized;
  5988. this.usage = StaticDrawUsage;
  5989. this.updateRanges = [];
  5990. this.gpuType = FloatType;
  5991. this.version = 0;
  5992. }
  5993. onUploadCallback() {}
  5994. set needsUpdate( value ) {
  5995. if ( value === true ) this.version ++;
  5996. }
  5997. setUsage( value ) {
  5998. this.usage = value;
  5999. return this;
  6000. }
  6001. addUpdateRange( start, count ) {
  6002. this.updateRanges.push( { start, count } );
  6003. }
  6004. clearUpdateRanges() {
  6005. this.updateRanges.length = 0;
  6006. }
  6007. copy( source ) {
  6008. this.name = source.name;
  6009. this.array = new source.array.constructor( source.array );
  6010. this.itemSize = source.itemSize;
  6011. this.count = source.count;
  6012. this.normalized = source.normalized;
  6013. this.usage = source.usage;
  6014. this.gpuType = source.gpuType;
  6015. return this;
  6016. }
  6017. copyAt( index1, attribute, index2 ) {
  6018. index1 *= this.itemSize;
  6019. index2 *= attribute.itemSize;
  6020. for ( let i = 0, l = this.itemSize; i < l; i ++ ) {
  6021. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  6022. }
  6023. return this;
  6024. }
  6025. copyArray( array ) {
  6026. this.array.set( array );
  6027. return this;
  6028. }
  6029. applyMatrix3( m ) {
  6030. if ( this.itemSize === 2 ) {
  6031. for ( let i = 0, l = this.count; i < l; i ++ ) {
  6032. _vector2$1.fromBufferAttribute( this, i );
  6033. _vector2$1.applyMatrix3( m );
  6034. this.setXY( i, _vector2$1.x, _vector2$1.y );
  6035. }
  6036. } else if ( this.itemSize === 3 ) {
  6037. for ( let i = 0, l = this.count; i < l; i ++ ) {
  6038. _vector$9.fromBufferAttribute( this, i );
  6039. _vector$9.applyMatrix3( m );
  6040. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  6041. }
  6042. }
  6043. return this;
  6044. }
  6045. applyMatrix4( m ) {
  6046. for ( let i = 0, l = this.count; i < l; i ++ ) {
  6047. _vector$9.fromBufferAttribute( this, i );
  6048. _vector$9.applyMatrix4( m );
  6049. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  6050. }
  6051. return this;
  6052. }
  6053. applyNormalMatrix( m ) {
  6054. for ( let i = 0, l = this.count; i < l; i ++ ) {
  6055. _vector$9.fromBufferAttribute( this, i );
  6056. _vector$9.applyNormalMatrix( m );
  6057. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  6058. }
  6059. return this;
  6060. }
  6061. transformDirection( m ) {
  6062. for ( let i = 0, l = this.count; i < l; i ++ ) {
  6063. _vector$9.fromBufferAttribute( this, i );
  6064. _vector$9.transformDirection( m );
  6065. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  6066. }
  6067. return this;
  6068. }
  6069. set( value, offset = 0 ) {
  6070. // Matching BufferAttribute constructor, do not normalize the array.
  6071. this.array.set( value, offset );
  6072. return this;
  6073. }
  6074. getComponent( index, component ) {
  6075. let value = this.array[ index * this.itemSize + component ];
  6076. if ( this.normalized ) value = denormalize( value, this.array );
  6077. return value;
  6078. }
  6079. setComponent( index, component, value ) {
  6080. if ( this.normalized ) value = normalize$1( value, this.array );
  6081. this.array[ index * this.itemSize + component ] = value;
  6082. return this;
  6083. }
  6084. getX( index ) {
  6085. let x = this.array[ index * this.itemSize ];
  6086. if ( this.normalized ) x = denormalize( x, this.array );
  6087. return x;
  6088. }
  6089. setX( index, x ) {
  6090. if ( this.normalized ) x = normalize$1( x, this.array );
  6091. this.array[ index * this.itemSize ] = x;
  6092. return this;
  6093. }
  6094. getY( index ) {
  6095. let y = this.array[ index * this.itemSize + 1 ];
  6096. if ( this.normalized ) y = denormalize( y, this.array );
  6097. return y;
  6098. }
  6099. setY( index, y ) {
  6100. if ( this.normalized ) y = normalize$1( y, this.array );
  6101. this.array[ index * this.itemSize + 1 ] = y;
  6102. return this;
  6103. }
  6104. getZ( index ) {
  6105. let z = this.array[ index * this.itemSize + 2 ];
  6106. if ( this.normalized ) z = denormalize( z, this.array );
  6107. return z;
  6108. }
  6109. setZ( index, z ) {
  6110. if ( this.normalized ) z = normalize$1( z, this.array );
  6111. this.array[ index * this.itemSize + 2 ] = z;
  6112. return this;
  6113. }
  6114. getW( index ) {
  6115. let w = this.array[ index * this.itemSize + 3 ];
  6116. if ( this.normalized ) w = denormalize( w, this.array );
  6117. return w;
  6118. }
  6119. setW( index, w ) {
  6120. if ( this.normalized ) w = normalize$1( w, this.array );
  6121. this.array[ index * this.itemSize + 3 ] = w;
  6122. return this;
  6123. }
  6124. setXY( index, x, y ) {
  6125. index *= this.itemSize;
  6126. if ( this.normalized ) {
  6127. x = normalize$1( x, this.array );
  6128. y = normalize$1( y, this.array );
  6129. }
  6130. this.array[ index + 0 ] = x;
  6131. this.array[ index + 1 ] = y;
  6132. return this;
  6133. }
  6134. setXYZ( index, x, y, z ) {
  6135. index *= this.itemSize;
  6136. if ( this.normalized ) {
  6137. x = normalize$1( x, this.array );
  6138. y = normalize$1( y, this.array );
  6139. z = normalize$1( z, this.array );
  6140. }
  6141. this.array[ index + 0 ] = x;
  6142. this.array[ index + 1 ] = y;
  6143. this.array[ index + 2 ] = z;
  6144. return this;
  6145. }
  6146. setXYZW( index, x, y, z, w ) {
  6147. index *= this.itemSize;
  6148. if ( this.normalized ) {
  6149. x = normalize$1( x, this.array );
  6150. y = normalize$1( y, this.array );
  6151. z = normalize$1( z, this.array );
  6152. w = normalize$1( w, this.array );
  6153. }
  6154. this.array[ index + 0 ] = x;
  6155. this.array[ index + 1 ] = y;
  6156. this.array[ index + 2 ] = z;
  6157. this.array[ index + 3 ] = w;
  6158. return this;
  6159. }
  6160. onUpload( callback ) {
  6161. this.onUploadCallback = callback;
  6162. return this;
  6163. }
  6164. clone() {
  6165. return new this.constructor( this.array, this.itemSize ).copy( this );
  6166. }
  6167. toJSON() {
  6168. const data = {
  6169. itemSize: this.itemSize,
  6170. type: this.array.constructor.name,
  6171. array: Array.from( this.array ),
  6172. normalized: this.normalized
  6173. };
  6174. if ( this.name !== '' ) data.name = this.name;
  6175. if ( this.usage !== StaticDrawUsage ) data.usage = this.usage;
  6176. return data;
  6177. }
  6178. }
  6179. //
  6180. class Int8BufferAttribute extends BufferAttribute {
  6181. constructor( array, itemSize, normalized ) {
  6182. super( new Int8Array( array ), itemSize, normalized );
  6183. }
  6184. }
  6185. class Uint8BufferAttribute extends BufferAttribute {
  6186. constructor( array, itemSize, normalized ) {
  6187. super( new Uint8Array( array ), itemSize, normalized );
  6188. }
  6189. }
  6190. class Uint8ClampedBufferAttribute extends BufferAttribute {
  6191. constructor( array, itemSize, normalized ) {
  6192. super( new Uint8ClampedArray( array ), itemSize, normalized );
  6193. }
  6194. }
  6195. class Int16BufferAttribute extends BufferAttribute {
  6196. constructor( array, itemSize, normalized ) {
  6197. super( new Int16Array( array ), itemSize, normalized );
  6198. }
  6199. }
  6200. class Uint16BufferAttribute extends BufferAttribute {
  6201. constructor( array, itemSize, normalized ) {
  6202. super( new Uint16Array( array ), itemSize, normalized );
  6203. }
  6204. }
  6205. class Int32BufferAttribute extends BufferAttribute {
  6206. constructor( array, itemSize, normalized ) {
  6207. super( new Int32Array( array ), itemSize, normalized );
  6208. }
  6209. }
  6210. class Uint32BufferAttribute extends BufferAttribute {
  6211. constructor( array, itemSize, normalized ) {
  6212. super( new Uint32Array( array ), itemSize, normalized );
  6213. }
  6214. }
  6215. class Float16BufferAttribute extends BufferAttribute {
  6216. constructor( array, itemSize, normalized ) {
  6217. super( new Uint16Array( array ), itemSize, normalized );
  6218. this.isFloat16BufferAttribute = true;
  6219. }
  6220. getX( index ) {
  6221. let x = fromHalfFloat( this.array[ index * this.itemSize ] );
  6222. if ( this.normalized ) x = denormalize( x, this.array );
  6223. return x;
  6224. }
  6225. setX( index, x ) {
  6226. if ( this.normalized ) x = normalize$1( x, this.array );
  6227. this.array[ index * this.itemSize ] = toHalfFloat( x );
  6228. return this;
  6229. }
  6230. getY( index ) {
  6231. let y = fromHalfFloat( this.array[ index * this.itemSize + 1 ] );
  6232. if ( this.normalized ) y = denormalize( y, this.array );
  6233. return y;
  6234. }
  6235. setY( index, y ) {
  6236. if ( this.normalized ) y = normalize$1( y, this.array );
  6237. this.array[ index * this.itemSize + 1 ] = toHalfFloat( y );
  6238. return this;
  6239. }
  6240. getZ( index ) {
  6241. let z = fromHalfFloat( this.array[ index * this.itemSize + 2 ] );
  6242. if ( this.normalized ) z = denormalize( z, this.array );
  6243. return z;
  6244. }
  6245. setZ( index, z ) {
  6246. if ( this.normalized ) z = normalize$1( z, this.array );
  6247. this.array[ index * this.itemSize + 2 ] = toHalfFloat( z );
  6248. return this;
  6249. }
  6250. getW( index ) {
  6251. let w = fromHalfFloat( this.array[ index * this.itemSize + 3 ] );
  6252. if ( this.normalized ) w = denormalize( w, this.array );
  6253. return w;
  6254. }
  6255. setW( index, w ) {
  6256. if ( this.normalized ) w = normalize$1( w, this.array );
  6257. this.array[ index * this.itemSize + 3 ] = toHalfFloat( w );
  6258. return this;
  6259. }
  6260. setXY( index, x, y ) {
  6261. index *= this.itemSize;
  6262. if ( this.normalized ) {
  6263. x = normalize$1( x, this.array );
  6264. y = normalize$1( y, this.array );
  6265. }
  6266. this.array[ index + 0 ] = toHalfFloat( x );
  6267. this.array[ index + 1 ] = toHalfFloat( y );
  6268. return this;
  6269. }
  6270. setXYZ( index, x, y, z ) {
  6271. index *= this.itemSize;
  6272. if ( this.normalized ) {
  6273. x = normalize$1( x, this.array );
  6274. y = normalize$1( y, this.array );
  6275. z = normalize$1( z, this.array );
  6276. }
  6277. this.array[ index + 0 ] = toHalfFloat( x );
  6278. this.array[ index + 1 ] = toHalfFloat( y );
  6279. this.array[ index + 2 ] = toHalfFloat( z );
  6280. return this;
  6281. }
  6282. setXYZW( index, x, y, z, w ) {
  6283. index *= this.itemSize;
  6284. if ( this.normalized ) {
  6285. x = normalize$1( x, this.array );
  6286. y = normalize$1( y, this.array );
  6287. z = normalize$1( z, this.array );
  6288. w = normalize$1( w, this.array );
  6289. }
  6290. this.array[ index + 0 ] = toHalfFloat( x );
  6291. this.array[ index + 1 ] = toHalfFloat( y );
  6292. this.array[ index + 2 ] = toHalfFloat( z );
  6293. this.array[ index + 3 ] = toHalfFloat( w );
  6294. return this;
  6295. }
  6296. }
  6297. class Float32BufferAttribute extends BufferAttribute {
  6298. constructor( array, itemSize, normalized ) {
  6299. super( new Float32Array( array ), itemSize, normalized );
  6300. }
  6301. }
  6302. let _id$9 = 0;
  6303. const _m1 = /*@__PURE__*/ new Matrix4();
  6304. const _obj = /*@__PURE__*/ new Object3D();
  6305. const _offset = /*@__PURE__*/ new Vector3();
  6306. const _box$2 = /*@__PURE__*/ new Box3();
  6307. const _boxMorphTargets = /*@__PURE__*/ new Box3();
  6308. const _vector$8 = /*@__PURE__*/ new Vector3();
  6309. class BufferGeometry extends EventDispatcher {
  6310. constructor() {
  6311. super();
  6312. this.isBufferGeometry = true;
  6313. Object.defineProperty( this, 'id', { value: _id$9 ++ } );
  6314. this.uuid = generateUUID();
  6315. this.name = '';
  6316. this.type = 'BufferGeometry';
  6317. this.index = null;
  6318. this.indirect = null;
  6319. this.attributes = {};
  6320. this.morphAttributes = {};
  6321. this.morphTargetsRelative = false;
  6322. this.groups = [];
  6323. this.boundingBox = null;
  6324. this.boundingSphere = null;
  6325. this.drawRange = { start: 0, count: Infinity };
  6326. this.userData = {};
  6327. }
  6328. getIndex() {
  6329. return this.index;
  6330. }
  6331. setIndex( index ) {
  6332. if ( Array.isArray( index ) ) {
  6333. this.index = new ( arrayNeedsUint32$1( index ) ? Uint32BufferAttribute : Uint16BufferAttribute )( index, 1 );
  6334. } else {
  6335. this.index = index;
  6336. }
  6337. return this;
  6338. }
  6339. setIndirect( indirect ) {
  6340. this.indirect = indirect;
  6341. return this;
  6342. }
  6343. getIndirect() {
  6344. return this.indirect;
  6345. }
  6346. getAttribute( name ) {
  6347. return this.attributes[ name ];
  6348. }
  6349. setAttribute( name, attribute ) {
  6350. this.attributes[ name ] = attribute;
  6351. return this;
  6352. }
  6353. deleteAttribute( name ) {
  6354. delete this.attributes[ name ];
  6355. return this;
  6356. }
  6357. hasAttribute( name ) {
  6358. return this.attributes[ name ] !== undefined;
  6359. }
  6360. addGroup( start, count, materialIndex = 0 ) {
  6361. this.groups.push( {
  6362. start: start,
  6363. count: count,
  6364. materialIndex: materialIndex
  6365. } );
  6366. }
  6367. clearGroups() {
  6368. this.groups = [];
  6369. }
  6370. setDrawRange( start, count ) {
  6371. this.drawRange.start = start;
  6372. this.drawRange.count = count;
  6373. }
  6374. applyMatrix4( matrix ) {
  6375. const position = this.attributes.position;
  6376. if ( position !== undefined ) {
  6377. position.applyMatrix4( matrix );
  6378. position.needsUpdate = true;
  6379. }
  6380. const normal = this.attributes.normal;
  6381. if ( normal !== undefined ) {
  6382. const normalMatrix = new Matrix3().getNormalMatrix( matrix );
  6383. normal.applyNormalMatrix( normalMatrix );
  6384. normal.needsUpdate = true;
  6385. }
  6386. const tangent = this.attributes.tangent;
  6387. if ( tangent !== undefined ) {
  6388. tangent.transformDirection( matrix );
  6389. tangent.needsUpdate = true;
  6390. }
  6391. if ( this.boundingBox !== null ) {
  6392. this.computeBoundingBox();
  6393. }
  6394. if ( this.boundingSphere !== null ) {
  6395. this.computeBoundingSphere();
  6396. }
  6397. return this;
  6398. }
  6399. applyQuaternion( q ) {
  6400. _m1.makeRotationFromQuaternion( q );
  6401. this.applyMatrix4( _m1 );
  6402. return this;
  6403. }
  6404. rotateX( angle ) {
  6405. // rotate geometry around world x-axis
  6406. _m1.makeRotationX( angle );
  6407. this.applyMatrix4( _m1 );
  6408. return this;
  6409. }
  6410. rotateY( angle ) {
  6411. // rotate geometry around world y-axis
  6412. _m1.makeRotationY( angle );
  6413. this.applyMatrix4( _m1 );
  6414. return this;
  6415. }
  6416. rotateZ( angle ) {
  6417. // rotate geometry around world z-axis
  6418. _m1.makeRotationZ( angle );
  6419. this.applyMatrix4( _m1 );
  6420. return this;
  6421. }
  6422. translate( x, y, z ) {
  6423. // translate geometry
  6424. _m1.makeTranslation( x, y, z );
  6425. this.applyMatrix4( _m1 );
  6426. return this;
  6427. }
  6428. scale( x, y, z ) {
  6429. // scale geometry
  6430. _m1.makeScale( x, y, z );
  6431. this.applyMatrix4( _m1 );
  6432. return this;
  6433. }
  6434. lookAt( vector ) {
  6435. _obj.lookAt( vector );
  6436. _obj.updateMatrix();
  6437. this.applyMatrix4( _obj.matrix );
  6438. return this;
  6439. }
  6440. center() {
  6441. this.computeBoundingBox();
  6442. this.boundingBox.getCenter( _offset ).negate();
  6443. this.translate( _offset.x, _offset.y, _offset.z );
  6444. return this;
  6445. }
  6446. setFromPoints( points ) {
  6447. const position = [];
  6448. for ( let i = 0, l = points.length; i < l; i ++ ) {
  6449. const point = points[ i ];
  6450. position.push( point.x, point.y, point.z || 0 );
  6451. }
  6452. this.setAttribute( 'position', new Float32BufferAttribute( position, 3 ) );
  6453. return this;
  6454. }
  6455. computeBoundingBox() {
  6456. if ( this.boundingBox === null ) {
  6457. this.boundingBox = new Box3();
  6458. }
  6459. const position = this.attributes.position;
  6460. const morphAttributesPosition = this.morphAttributes.position;
  6461. if ( position && position.isGLBufferAttribute ) {
  6462. console.error( 'THREE.BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.', this );
  6463. this.boundingBox.set(
  6464. new Vector3( - Infinity, - Infinity, - Infinity ),
  6465. new Vector3( + Infinity, + Infinity, + Infinity )
  6466. );
  6467. return;
  6468. }
  6469. if ( position !== undefined ) {
  6470. this.boundingBox.setFromBufferAttribute( position );
  6471. // process morph attributes if present
  6472. if ( morphAttributesPosition ) {
  6473. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  6474. const morphAttribute = morphAttributesPosition[ i ];
  6475. _box$2.setFromBufferAttribute( morphAttribute );
  6476. if ( this.morphTargetsRelative ) {
  6477. _vector$8.addVectors( this.boundingBox.min, _box$2.min );
  6478. this.boundingBox.expandByPoint( _vector$8 );
  6479. _vector$8.addVectors( this.boundingBox.max, _box$2.max );
  6480. this.boundingBox.expandByPoint( _vector$8 );
  6481. } else {
  6482. this.boundingBox.expandByPoint( _box$2.min );
  6483. this.boundingBox.expandByPoint( _box$2.max );
  6484. }
  6485. }
  6486. }
  6487. } else {
  6488. this.boundingBox.makeEmpty();
  6489. }
  6490. if ( isNaN( this.boundingBox.min.x ) || isNaN( this.boundingBox.min.y ) || isNaN( this.boundingBox.min.z ) ) {
  6491. console.error( 'THREE.BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this );
  6492. }
  6493. }
  6494. computeBoundingSphere() {
  6495. if ( this.boundingSphere === null ) {
  6496. this.boundingSphere = new Sphere();
  6497. }
  6498. const position = this.attributes.position;
  6499. const morphAttributesPosition = this.morphAttributes.position;
  6500. if ( position && position.isGLBufferAttribute ) {
  6501. console.error( 'THREE.BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere.', this );
  6502. this.boundingSphere.set( new Vector3(), Infinity );
  6503. return;
  6504. }
  6505. if ( position ) {
  6506. // first, find the center of the bounding sphere
  6507. const center = this.boundingSphere.center;
  6508. _box$2.setFromBufferAttribute( position );
  6509. // process morph attributes if present
  6510. if ( morphAttributesPosition ) {
  6511. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  6512. const morphAttribute = morphAttributesPosition[ i ];
  6513. _boxMorphTargets.setFromBufferAttribute( morphAttribute );
  6514. if ( this.morphTargetsRelative ) {
  6515. _vector$8.addVectors( _box$2.min, _boxMorphTargets.min );
  6516. _box$2.expandByPoint( _vector$8 );
  6517. _vector$8.addVectors( _box$2.max, _boxMorphTargets.max );
  6518. _box$2.expandByPoint( _vector$8 );
  6519. } else {
  6520. _box$2.expandByPoint( _boxMorphTargets.min );
  6521. _box$2.expandByPoint( _boxMorphTargets.max );
  6522. }
  6523. }
  6524. }
  6525. _box$2.getCenter( center );
  6526. // second, try to find a boundingSphere with a radius smaller than the
  6527. // boundingSphere of the boundingBox: sqrt(3) smaller in the best case
  6528. let maxRadiusSq = 0;
  6529. for ( let i = 0, il = position.count; i < il; i ++ ) {
  6530. _vector$8.fromBufferAttribute( position, i );
  6531. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$8 ) );
  6532. }
  6533. // process morph attributes if present
  6534. if ( morphAttributesPosition ) {
  6535. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  6536. const morphAttribute = morphAttributesPosition[ i ];
  6537. const morphTargetsRelative = this.morphTargetsRelative;
  6538. for ( let j = 0, jl = morphAttribute.count; j < jl; j ++ ) {
  6539. _vector$8.fromBufferAttribute( morphAttribute, j );
  6540. if ( morphTargetsRelative ) {
  6541. _offset.fromBufferAttribute( position, j );
  6542. _vector$8.add( _offset );
  6543. }
  6544. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$8 ) );
  6545. }
  6546. }
  6547. }
  6548. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  6549. if ( isNaN( this.boundingSphere.radius ) ) {
  6550. console.error( 'THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this );
  6551. }
  6552. }
  6553. }
  6554. computeTangents() {
  6555. const index = this.index;
  6556. const attributes = this.attributes;
  6557. // based on http://www.terathon.com/code/tangent.html
  6558. // (per vertex tangents)
  6559. if ( index === null ||
  6560. attributes.position === undefined ||
  6561. attributes.normal === undefined ||
  6562. attributes.uv === undefined ) {
  6563. console.error( 'THREE.BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)' );
  6564. return;
  6565. }
  6566. const positionAttribute = attributes.position;
  6567. const normalAttribute = attributes.normal;
  6568. const uvAttribute = attributes.uv;
  6569. if ( this.hasAttribute( 'tangent' ) === false ) {
  6570. this.setAttribute( 'tangent', new BufferAttribute( new Float32Array( 4 * positionAttribute.count ), 4 ) );
  6571. }
  6572. const tangentAttribute = this.getAttribute( 'tangent' );
  6573. const tan1 = [], tan2 = [];
  6574. for ( let i = 0; i < positionAttribute.count; i ++ ) {
  6575. tan1[ i ] = new Vector3();
  6576. tan2[ i ] = new Vector3();
  6577. }
  6578. const vA = new Vector3(),
  6579. vB = new Vector3(),
  6580. vC = new Vector3(),
  6581. uvA = new Vector2(),
  6582. uvB = new Vector2(),
  6583. uvC = new Vector2(),
  6584. sdir = new Vector3(),
  6585. tdir = new Vector3();
  6586. function handleTriangle( a, b, c ) {
  6587. vA.fromBufferAttribute( positionAttribute, a );
  6588. vB.fromBufferAttribute( positionAttribute, b );
  6589. vC.fromBufferAttribute( positionAttribute, c );
  6590. uvA.fromBufferAttribute( uvAttribute, a );
  6591. uvB.fromBufferAttribute( uvAttribute, b );
  6592. uvC.fromBufferAttribute( uvAttribute, c );
  6593. vB.sub( vA );
  6594. vC.sub( vA );
  6595. uvB.sub( uvA );
  6596. uvC.sub( uvA );
  6597. const r = 1.0 / ( uvB.x * uvC.y - uvC.x * uvB.y );
  6598. // silently ignore degenerate uv triangles having coincident or colinear vertices
  6599. if ( ! isFinite( r ) ) return;
  6600. sdir.copy( vB ).multiplyScalar( uvC.y ).addScaledVector( vC, - uvB.y ).multiplyScalar( r );
  6601. tdir.copy( vC ).multiplyScalar( uvB.x ).addScaledVector( vB, - uvC.x ).multiplyScalar( r );
  6602. tan1[ a ].add( sdir );
  6603. tan1[ b ].add( sdir );
  6604. tan1[ c ].add( sdir );
  6605. tan2[ a ].add( tdir );
  6606. tan2[ b ].add( tdir );
  6607. tan2[ c ].add( tdir );
  6608. }
  6609. let groups = this.groups;
  6610. if ( groups.length === 0 ) {
  6611. groups = [ {
  6612. start: 0,
  6613. count: index.count
  6614. } ];
  6615. }
  6616. for ( let i = 0, il = groups.length; i < il; ++ i ) {
  6617. const group = groups[ i ];
  6618. const start = group.start;
  6619. const count = group.count;
  6620. for ( let j = start, jl = start + count; j < jl; j += 3 ) {
  6621. handleTriangle(
  6622. index.getX( j + 0 ),
  6623. index.getX( j + 1 ),
  6624. index.getX( j + 2 )
  6625. );
  6626. }
  6627. }
  6628. const tmp = new Vector3(), tmp2 = new Vector3();
  6629. const n = new Vector3(), n2 = new Vector3();
  6630. function handleVertex( v ) {
  6631. n.fromBufferAttribute( normalAttribute, v );
  6632. n2.copy( n );
  6633. const t = tan1[ v ];
  6634. // Gram-Schmidt orthogonalize
  6635. tmp.copy( t );
  6636. tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize();
  6637. // Calculate handedness
  6638. tmp2.crossVectors( n2, t );
  6639. const test = tmp2.dot( tan2[ v ] );
  6640. const w = ( test < 0.0 ) ? - 1.0 : 1.0;
  6641. tangentAttribute.setXYZW( v, tmp.x, tmp.y, tmp.z, w );
  6642. }
  6643. for ( let i = 0, il = groups.length; i < il; ++ i ) {
  6644. const group = groups[ i ];
  6645. const start = group.start;
  6646. const count = group.count;
  6647. for ( let j = start, jl = start + count; j < jl; j += 3 ) {
  6648. handleVertex( index.getX( j + 0 ) );
  6649. handleVertex( index.getX( j + 1 ) );
  6650. handleVertex( index.getX( j + 2 ) );
  6651. }
  6652. }
  6653. }
  6654. computeVertexNormals() {
  6655. const index = this.index;
  6656. const positionAttribute = this.getAttribute( 'position' );
  6657. if ( positionAttribute !== undefined ) {
  6658. let normalAttribute = this.getAttribute( 'normal' );
  6659. if ( normalAttribute === undefined ) {
  6660. normalAttribute = new BufferAttribute( new Float32Array( positionAttribute.count * 3 ), 3 );
  6661. this.setAttribute( 'normal', normalAttribute );
  6662. } else {
  6663. // reset existing normals to zero
  6664. for ( let i = 0, il = normalAttribute.count; i < il; i ++ ) {
  6665. normalAttribute.setXYZ( i, 0, 0, 0 );
  6666. }
  6667. }
  6668. const pA = new Vector3(), pB = new Vector3(), pC = new Vector3();
  6669. const nA = new Vector3(), nB = new Vector3(), nC = new Vector3();
  6670. const cb = new Vector3(), ab = new Vector3();
  6671. // indexed elements
  6672. if ( index ) {
  6673. for ( let i = 0, il = index.count; i < il; i += 3 ) {
  6674. const vA = index.getX( i + 0 );
  6675. const vB = index.getX( i + 1 );
  6676. const vC = index.getX( i + 2 );
  6677. pA.fromBufferAttribute( positionAttribute, vA );
  6678. pB.fromBufferAttribute( positionAttribute, vB );
  6679. pC.fromBufferAttribute( positionAttribute, vC );
  6680. cb.subVectors( pC, pB );
  6681. ab.subVectors( pA, pB );
  6682. cb.cross( ab );
  6683. nA.fromBufferAttribute( normalAttribute, vA );
  6684. nB.fromBufferAttribute( normalAttribute, vB );
  6685. nC.fromBufferAttribute( normalAttribute, vC );
  6686. nA.add( cb );
  6687. nB.add( cb );
  6688. nC.add( cb );
  6689. normalAttribute.setXYZ( vA, nA.x, nA.y, nA.z );
  6690. normalAttribute.setXYZ( vB, nB.x, nB.y, nB.z );
  6691. normalAttribute.setXYZ( vC, nC.x, nC.y, nC.z );
  6692. }
  6693. } else {
  6694. // non-indexed elements (unconnected triangle soup)
  6695. for ( let i = 0, il = positionAttribute.count; i < il; i += 3 ) {
  6696. pA.fromBufferAttribute( positionAttribute, i + 0 );
  6697. pB.fromBufferAttribute( positionAttribute, i + 1 );
  6698. pC.fromBufferAttribute( positionAttribute, i + 2 );
  6699. cb.subVectors( pC, pB );
  6700. ab.subVectors( pA, pB );
  6701. cb.cross( ab );
  6702. normalAttribute.setXYZ( i + 0, cb.x, cb.y, cb.z );
  6703. normalAttribute.setXYZ( i + 1, cb.x, cb.y, cb.z );
  6704. normalAttribute.setXYZ( i + 2, cb.x, cb.y, cb.z );
  6705. }
  6706. }
  6707. this.normalizeNormals();
  6708. normalAttribute.needsUpdate = true;
  6709. }
  6710. }
  6711. normalizeNormals() {
  6712. const normals = this.attributes.normal;
  6713. for ( let i = 0, il = normals.count; i < il; i ++ ) {
  6714. _vector$8.fromBufferAttribute( normals, i );
  6715. _vector$8.normalize();
  6716. normals.setXYZ( i, _vector$8.x, _vector$8.y, _vector$8.z );
  6717. }
  6718. }
  6719. toNonIndexed() {
  6720. function convertBufferAttribute( attribute, indices ) {
  6721. const array = attribute.array;
  6722. const itemSize = attribute.itemSize;
  6723. const normalized = attribute.normalized;
  6724. const array2 = new array.constructor( indices.length * itemSize );
  6725. let index = 0, index2 = 0;
  6726. for ( let i = 0, l = indices.length; i < l; i ++ ) {
  6727. if ( attribute.isInterleavedBufferAttribute ) {
  6728. index = indices[ i ] * attribute.data.stride + attribute.offset;
  6729. } else {
  6730. index = indices[ i ] * itemSize;
  6731. }
  6732. for ( let j = 0; j < itemSize; j ++ ) {
  6733. array2[ index2 ++ ] = array[ index ++ ];
  6734. }
  6735. }
  6736. return new BufferAttribute( array2, itemSize, normalized );
  6737. }
  6738. //
  6739. if ( this.index === null ) {
  6740. console.warn( 'THREE.BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed.' );
  6741. return this;
  6742. }
  6743. const geometry2 = new BufferGeometry();
  6744. const indices = this.index.array;
  6745. const attributes = this.attributes;
  6746. // attributes
  6747. for ( const name in attributes ) {
  6748. const attribute = attributes[ name ];
  6749. const newAttribute = convertBufferAttribute( attribute, indices );
  6750. geometry2.setAttribute( name, newAttribute );
  6751. }
  6752. // morph attributes
  6753. const morphAttributes = this.morphAttributes;
  6754. for ( const name in morphAttributes ) {
  6755. const morphArray = [];
  6756. const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  6757. for ( let i = 0, il = morphAttribute.length; i < il; i ++ ) {
  6758. const attribute = morphAttribute[ i ];
  6759. const newAttribute = convertBufferAttribute( attribute, indices );
  6760. morphArray.push( newAttribute );
  6761. }
  6762. geometry2.morphAttributes[ name ] = morphArray;
  6763. }
  6764. geometry2.morphTargetsRelative = this.morphTargetsRelative;
  6765. // groups
  6766. const groups = this.groups;
  6767. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  6768. const group = groups[ i ];
  6769. geometry2.addGroup( group.start, group.count, group.materialIndex );
  6770. }
  6771. return geometry2;
  6772. }
  6773. toJSON() {
  6774. const data = {
  6775. metadata: {
  6776. version: 4.6,
  6777. type: 'BufferGeometry',
  6778. generator: 'BufferGeometry.toJSON'
  6779. }
  6780. };
  6781. // standard BufferGeometry serialization
  6782. data.uuid = this.uuid;
  6783. data.type = this.type;
  6784. if ( this.name !== '' ) data.name = this.name;
  6785. if ( Object.keys( this.userData ).length > 0 ) data.userData = this.userData;
  6786. if ( this.parameters !== undefined ) {
  6787. const parameters = this.parameters;
  6788. for ( const key in parameters ) {
  6789. if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ];
  6790. }
  6791. return data;
  6792. }
  6793. // for simplicity the code assumes attributes are not shared across geometries, see #15811
  6794. data.data = { attributes: {} };
  6795. const index = this.index;
  6796. if ( index !== null ) {
  6797. data.data.index = {
  6798. type: index.array.constructor.name,
  6799. array: Array.prototype.slice.call( index.array )
  6800. };
  6801. }
  6802. const attributes = this.attributes;
  6803. for ( const key in attributes ) {
  6804. const attribute = attributes[ key ];
  6805. data.data.attributes[ key ] = attribute.toJSON( data.data );
  6806. }
  6807. const morphAttributes = {};
  6808. let hasMorphAttributes = false;
  6809. for ( const key in this.morphAttributes ) {
  6810. const attributeArray = this.morphAttributes[ key ];
  6811. const array = [];
  6812. for ( let i = 0, il = attributeArray.length; i < il; i ++ ) {
  6813. const attribute = attributeArray[ i ];
  6814. array.push( attribute.toJSON( data.data ) );
  6815. }
  6816. if ( array.length > 0 ) {
  6817. morphAttributes[ key ] = array;
  6818. hasMorphAttributes = true;
  6819. }
  6820. }
  6821. if ( hasMorphAttributes ) {
  6822. data.data.morphAttributes = morphAttributes;
  6823. data.data.morphTargetsRelative = this.morphTargetsRelative;
  6824. }
  6825. const groups = this.groups;
  6826. if ( groups.length > 0 ) {
  6827. data.data.groups = JSON.parse( JSON.stringify( groups ) );
  6828. }
  6829. const boundingSphere = this.boundingSphere;
  6830. if ( boundingSphere !== null ) {
  6831. data.data.boundingSphere = {
  6832. center: boundingSphere.center.toArray(),
  6833. radius: boundingSphere.radius
  6834. };
  6835. }
  6836. return data;
  6837. }
  6838. clone() {
  6839. return new this.constructor().copy( this );
  6840. }
  6841. copy( source ) {
  6842. // reset
  6843. this.index = null;
  6844. this.attributes = {};
  6845. this.morphAttributes = {};
  6846. this.groups = [];
  6847. this.boundingBox = null;
  6848. this.boundingSphere = null;
  6849. // used for storing cloned, shared data
  6850. const data = {};
  6851. // name
  6852. this.name = source.name;
  6853. // index
  6854. const index = source.index;
  6855. if ( index !== null ) {
  6856. this.setIndex( index.clone( data ) );
  6857. }
  6858. // attributes
  6859. const attributes = source.attributes;
  6860. for ( const name in attributes ) {
  6861. const attribute = attributes[ name ];
  6862. this.setAttribute( name, attribute.clone( data ) );
  6863. }
  6864. // morph attributes
  6865. const morphAttributes = source.morphAttributes;
  6866. for ( const name in morphAttributes ) {
  6867. const array = [];
  6868. const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  6869. for ( let i = 0, l = morphAttribute.length; i < l; i ++ ) {
  6870. array.push( morphAttribute[ i ].clone( data ) );
  6871. }
  6872. this.morphAttributes[ name ] = array;
  6873. }
  6874. this.morphTargetsRelative = source.morphTargetsRelative;
  6875. // groups
  6876. const groups = source.groups;
  6877. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  6878. const group = groups[ i ];
  6879. this.addGroup( group.start, group.count, group.materialIndex );
  6880. }
  6881. // bounding box
  6882. const boundingBox = source.boundingBox;
  6883. if ( boundingBox !== null ) {
  6884. this.boundingBox = boundingBox.clone();
  6885. }
  6886. // bounding sphere
  6887. const boundingSphere = source.boundingSphere;
  6888. if ( boundingSphere !== null ) {
  6889. this.boundingSphere = boundingSphere.clone();
  6890. }
  6891. // draw range
  6892. this.drawRange.start = source.drawRange.start;
  6893. this.drawRange.count = source.drawRange.count;
  6894. // user data
  6895. this.userData = source.userData;
  6896. return this;
  6897. }
  6898. dispose() {
  6899. this.dispatchEvent( { type: 'dispose' } );
  6900. }
  6901. }
  6902. const _inverseMatrix$3 = /*@__PURE__*/ new Matrix4();
  6903. const _ray$3 = /*@__PURE__*/ new Ray();
  6904. const _sphere$6 = /*@__PURE__*/ new Sphere();
  6905. const _sphereHitAt = /*@__PURE__*/ new Vector3();
  6906. const _vA$1 = /*@__PURE__*/ new Vector3();
  6907. const _vB$1 = /*@__PURE__*/ new Vector3();
  6908. const _vC$1 = /*@__PURE__*/ new Vector3();
  6909. const _tempA = /*@__PURE__*/ new Vector3();
  6910. const _morphA = /*@__PURE__*/ new Vector3();
  6911. const _intersectionPoint = /*@__PURE__*/ new Vector3();
  6912. const _intersectionPointWorld = /*@__PURE__*/ new Vector3();
  6913. class Mesh extends Object3D {
  6914. constructor( geometry = new BufferGeometry(), material = new MeshBasicMaterial() ) {
  6915. super();
  6916. this.isMesh = true;
  6917. this.type = 'Mesh';
  6918. this.geometry = geometry;
  6919. this.material = material;
  6920. this.updateMorphTargets();
  6921. }
  6922. copy( source, recursive ) {
  6923. super.copy( source, recursive );
  6924. if ( source.morphTargetInfluences !== undefined ) {
  6925. this.morphTargetInfluences = source.morphTargetInfluences.slice();
  6926. }
  6927. if ( source.morphTargetDictionary !== undefined ) {
  6928. this.morphTargetDictionary = Object.assign( {}, source.morphTargetDictionary );
  6929. }
  6930. this.material = Array.isArray( source.material ) ? source.material.slice() : source.material;
  6931. this.geometry = source.geometry;
  6932. return this;
  6933. }
  6934. updateMorphTargets() {
  6935. const geometry = this.geometry;
  6936. const morphAttributes = geometry.morphAttributes;
  6937. const keys = Object.keys( morphAttributes );
  6938. if ( keys.length > 0 ) {
  6939. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  6940. if ( morphAttribute !== undefined ) {
  6941. this.morphTargetInfluences = [];
  6942. this.morphTargetDictionary = {};
  6943. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  6944. const name = morphAttribute[ m ].name || String( m );
  6945. this.morphTargetInfluences.push( 0 );
  6946. this.morphTargetDictionary[ name ] = m;
  6947. }
  6948. }
  6949. }
  6950. }
  6951. getVertexPosition( index, target ) {
  6952. const geometry = this.geometry;
  6953. const position = geometry.attributes.position;
  6954. const morphPosition = geometry.morphAttributes.position;
  6955. const morphTargetsRelative = geometry.morphTargetsRelative;
  6956. target.fromBufferAttribute( position, index );
  6957. const morphInfluences = this.morphTargetInfluences;
  6958. if ( morphPosition && morphInfluences ) {
  6959. _morphA.set( 0, 0, 0 );
  6960. for ( let i = 0, il = morphPosition.length; i < il; i ++ ) {
  6961. const influence = morphInfluences[ i ];
  6962. const morphAttribute = morphPosition[ i ];
  6963. if ( influence === 0 ) continue;
  6964. _tempA.fromBufferAttribute( morphAttribute, index );
  6965. if ( morphTargetsRelative ) {
  6966. _morphA.addScaledVector( _tempA, influence );
  6967. } else {
  6968. _morphA.addScaledVector( _tempA.sub( target ), influence );
  6969. }
  6970. }
  6971. target.add( _morphA );
  6972. }
  6973. return target;
  6974. }
  6975. raycast( raycaster, intersects ) {
  6976. const geometry = this.geometry;
  6977. const material = this.material;
  6978. const matrixWorld = this.matrixWorld;
  6979. if ( material === undefined ) return;
  6980. // test with bounding sphere in world space
  6981. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  6982. _sphere$6.copy( geometry.boundingSphere );
  6983. _sphere$6.applyMatrix4( matrixWorld );
  6984. // check distance from ray origin to bounding sphere
  6985. _ray$3.copy( raycaster.ray ).recast( raycaster.near );
  6986. if ( _sphere$6.containsPoint( _ray$3.origin ) === false ) {
  6987. if ( _ray$3.intersectSphere( _sphere$6, _sphereHitAt ) === null ) return;
  6988. if ( _ray$3.origin.distanceToSquared( _sphereHitAt ) > ( raycaster.far - raycaster.near ) ** 2 ) return;
  6989. }
  6990. // convert ray to local space of mesh
  6991. _inverseMatrix$3.copy( matrixWorld ).invert();
  6992. _ray$3.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$3 );
  6993. // test with bounding box in local space
  6994. if ( geometry.boundingBox !== null ) {
  6995. if ( _ray$3.intersectsBox( geometry.boundingBox ) === false ) return;
  6996. }
  6997. // test for intersections with geometry
  6998. this._computeIntersections( raycaster, intersects, _ray$3 );
  6999. }
  7000. _computeIntersections( raycaster, intersects, rayLocalSpace ) {
  7001. let intersection;
  7002. const geometry = this.geometry;
  7003. const material = this.material;
  7004. const index = geometry.index;
  7005. const position = geometry.attributes.position;
  7006. const uv = geometry.attributes.uv;
  7007. const uv1 = geometry.attributes.uv1;
  7008. const normal = geometry.attributes.normal;
  7009. const groups = geometry.groups;
  7010. const drawRange = geometry.drawRange;
  7011. if ( index !== null ) {
  7012. // indexed buffer geometry
  7013. if ( Array.isArray( material ) ) {
  7014. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  7015. const group = groups[ i ];
  7016. const groupMaterial = material[ group.materialIndex ];
  7017. const start = Math.max( group.start, drawRange.start );
  7018. const end = Math.min( index.count, Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ) );
  7019. for ( let j = start, jl = end; j < jl; j += 3 ) {
  7020. const a = index.getX( j );
  7021. const b = index.getX( j + 1 );
  7022. const c = index.getX( j + 2 );
  7023. intersection = checkGeometryIntersection( this, groupMaterial, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  7024. if ( intersection ) {
  7025. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in indexed buffer semantics
  7026. intersection.face.materialIndex = group.materialIndex;
  7027. intersects.push( intersection );
  7028. }
  7029. }
  7030. }
  7031. } else {
  7032. const start = Math.max( 0, drawRange.start );
  7033. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  7034. for ( let i = start, il = end; i < il; i += 3 ) {
  7035. const a = index.getX( i );
  7036. const b = index.getX( i + 1 );
  7037. const c = index.getX( i + 2 );
  7038. intersection = checkGeometryIntersection( this, material, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  7039. if ( intersection ) {
  7040. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in indexed buffer semantics
  7041. intersects.push( intersection );
  7042. }
  7043. }
  7044. }
  7045. } else if ( position !== undefined ) {
  7046. // non-indexed buffer geometry
  7047. if ( Array.isArray( material ) ) {
  7048. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  7049. const group = groups[ i ];
  7050. const groupMaterial = material[ group.materialIndex ];
  7051. const start = Math.max( group.start, drawRange.start );
  7052. const end = Math.min( position.count, Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ) );
  7053. for ( let j = start, jl = end; j < jl; j += 3 ) {
  7054. const a = j;
  7055. const b = j + 1;
  7056. const c = j + 2;
  7057. intersection = checkGeometryIntersection( this, groupMaterial, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  7058. if ( intersection ) {
  7059. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in non-indexed buffer semantics
  7060. intersection.face.materialIndex = group.materialIndex;
  7061. intersects.push( intersection );
  7062. }
  7063. }
  7064. }
  7065. } else {
  7066. const start = Math.max( 0, drawRange.start );
  7067. const end = Math.min( position.count, ( drawRange.start + drawRange.count ) );
  7068. for ( let i = start, il = end; i < il; i += 3 ) {
  7069. const a = i;
  7070. const b = i + 1;
  7071. const c = i + 2;
  7072. intersection = checkGeometryIntersection( this, material, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  7073. if ( intersection ) {
  7074. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in non-indexed buffer semantics
  7075. intersects.push( intersection );
  7076. }
  7077. }
  7078. }
  7079. }
  7080. }
  7081. }
  7082. function checkIntersection$1( object, material, raycaster, ray, pA, pB, pC, point ) {
  7083. let intersect;
  7084. if ( material.side === BackSide ) {
  7085. intersect = ray.intersectTriangle( pC, pB, pA, true, point );
  7086. } else {
  7087. intersect = ray.intersectTriangle( pA, pB, pC, ( material.side === FrontSide ), point );
  7088. }
  7089. if ( intersect === null ) return null;
  7090. _intersectionPointWorld.copy( point );
  7091. _intersectionPointWorld.applyMatrix4( object.matrixWorld );
  7092. const distance = raycaster.ray.origin.distanceTo( _intersectionPointWorld );
  7093. if ( distance < raycaster.near || distance > raycaster.far ) return null;
  7094. return {
  7095. distance: distance,
  7096. point: _intersectionPointWorld.clone(),
  7097. object: object
  7098. };
  7099. }
  7100. function checkGeometryIntersection( object, material, raycaster, ray, uv, uv1, normal, a, b, c ) {
  7101. object.getVertexPosition( a, _vA$1 );
  7102. object.getVertexPosition( b, _vB$1 );
  7103. object.getVertexPosition( c, _vC$1 );
  7104. const intersection = checkIntersection$1( object, material, raycaster, ray, _vA$1, _vB$1, _vC$1, _intersectionPoint );
  7105. if ( intersection ) {
  7106. const barycoord = new Vector3();
  7107. Triangle.getBarycoord( _intersectionPoint, _vA$1, _vB$1, _vC$1, barycoord );
  7108. if ( uv ) {
  7109. intersection.uv = Triangle.getInterpolatedAttribute( uv, a, b, c, barycoord, new Vector2() );
  7110. }
  7111. if ( uv1 ) {
  7112. intersection.uv1 = Triangle.getInterpolatedAttribute( uv1, a, b, c, barycoord, new Vector2() );
  7113. }
  7114. if ( normal ) {
  7115. intersection.normal = Triangle.getInterpolatedAttribute( normal, a, b, c, barycoord, new Vector3() );
  7116. if ( intersection.normal.dot( ray.direction ) > 0 ) {
  7117. intersection.normal.multiplyScalar( - 1 );
  7118. }
  7119. }
  7120. const face = {
  7121. a: a,
  7122. b: b,
  7123. c: c,
  7124. normal: new Vector3(),
  7125. materialIndex: 0
  7126. };
  7127. Triangle.getNormal( _vA$1, _vB$1, _vC$1, face.normal );
  7128. intersection.face = face;
  7129. intersection.barycoord = barycoord;
  7130. }
  7131. return intersection;
  7132. }
  7133. class BoxGeometry extends BufferGeometry {
  7134. constructor( width = 1, height = 1, depth = 1, widthSegments = 1, heightSegments = 1, depthSegments = 1 ) {
  7135. super();
  7136. this.type = 'BoxGeometry';
  7137. this.parameters = {
  7138. width: width,
  7139. height: height,
  7140. depth: depth,
  7141. widthSegments: widthSegments,
  7142. heightSegments: heightSegments,
  7143. depthSegments: depthSegments
  7144. };
  7145. const scope = this;
  7146. // segments
  7147. widthSegments = Math.floor( widthSegments );
  7148. heightSegments = Math.floor( heightSegments );
  7149. depthSegments = Math.floor( depthSegments );
  7150. // buffers
  7151. const indices = [];
  7152. const vertices = [];
  7153. const normals = [];
  7154. const uvs = [];
  7155. // helper variables
  7156. let numberOfVertices = 0;
  7157. let groupStart = 0;
  7158. // build each side of the box geometry
  7159. buildPlane( 'z', 'y', 'x', - 1, - 1, depth, height, width, depthSegments, heightSegments, 0 ); // px
  7160. buildPlane( 'z', 'y', 'x', 1, - 1, depth, height, - width, depthSegments, heightSegments, 1 ); // nx
  7161. buildPlane( 'x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2 ); // py
  7162. buildPlane( 'x', 'z', 'y', 1, - 1, width, depth, - height, widthSegments, depthSegments, 3 ); // ny
  7163. buildPlane( 'x', 'y', 'z', 1, - 1, width, height, depth, widthSegments, heightSegments, 4 ); // pz
  7164. buildPlane( 'x', 'y', 'z', - 1, - 1, width, height, - depth, widthSegments, heightSegments, 5 ); // nz
  7165. // build geometry
  7166. this.setIndex( indices );
  7167. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  7168. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  7169. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  7170. function buildPlane( u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex ) {
  7171. const segmentWidth = width / gridX;
  7172. const segmentHeight = height / gridY;
  7173. const widthHalf = width / 2;
  7174. const heightHalf = height / 2;
  7175. const depthHalf = depth / 2;
  7176. const gridX1 = gridX + 1;
  7177. const gridY1 = gridY + 1;
  7178. let vertexCounter = 0;
  7179. let groupCount = 0;
  7180. const vector = new Vector3();
  7181. // generate vertices, normals and uvs
  7182. for ( let iy = 0; iy < gridY1; iy ++ ) {
  7183. const y = iy * segmentHeight - heightHalf;
  7184. for ( let ix = 0; ix < gridX1; ix ++ ) {
  7185. const x = ix * segmentWidth - widthHalf;
  7186. // set values to correct vector component
  7187. vector[ u ] = x * udir;
  7188. vector[ v ] = y * vdir;
  7189. vector[ w ] = depthHalf;
  7190. // now apply vector to vertex buffer
  7191. vertices.push( vector.x, vector.y, vector.z );
  7192. // set values to correct vector component
  7193. vector[ u ] = 0;
  7194. vector[ v ] = 0;
  7195. vector[ w ] = depth > 0 ? 1 : - 1;
  7196. // now apply vector to normal buffer
  7197. normals.push( vector.x, vector.y, vector.z );
  7198. // uvs
  7199. uvs.push( ix / gridX );
  7200. uvs.push( 1 - ( iy / gridY ) );
  7201. // counters
  7202. vertexCounter += 1;
  7203. }
  7204. }
  7205. // indices
  7206. // 1. you need three indices to draw a single face
  7207. // 2. a single segment consists of two faces
  7208. // 3. so we need to generate six (2*3) indices per segment
  7209. for ( let iy = 0; iy < gridY; iy ++ ) {
  7210. for ( let ix = 0; ix < gridX; ix ++ ) {
  7211. const a = numberOfVertices + ix + gridX1 * iy;
  7212. const b = numberOfVertices + ix + gridX1 * ( iy + 1 );
  7213. const c = numberOfVertices + ( ix + 1 ) + gridX1 * ( iy + 1 );
  7214. const d = numberOfVertices + ( ix + 1 ) + gridX1 * iy;
  7215. // faces
  7216. indices.push( a, b, d );
  7217. indices.push( b, c, d );
  7218. // increase counter
  7219. groupCount += 6;
  7220. }
  7221. }
  7222. // add a group to the geometry. this will ensure multi material support
  7223. scope.addGroup( groupStart, groupCount, materialIndex );
  7224. // calculate new start value for groups
  7225. groupStart += groupCount;
  7226. // update total number of vertices
  7227. numberOfVertices += vertexCounter;
  7228. }
  7229. }
  7230. copy( source ) {
  7231. super.copy( source );
  7232. this.parameters = Object.assign( {}, source.parameters );
  7233. return this;
  7234. }
  7235. static fromJSON( data ) {
  7236. return new BoxGeometry( data.width, data.height, data.depth, data.widthSegments, data.heightSegments, data.depthSegments );
  7237. }
  7238. }
  7239. /**
  7240. * Uniform Utilities
  7241. */
  7242. function cloneUniforms( src ) {
  7243. const dst = {};
  7244. for ( const u in src ) {
  7245. dst[ u ] = {};
  7246. for ( const p in src[ u ] ) {
  7247. const property = src[ u ][ p ];
  7248. if ( property && ( property.isColor ||
  7249. property.isMatrix3 || property.isMatrix4 ||
  7250. property.isVector2 || property.isVector3 || property.isVector4 ||
  7251. property.isTexture || property.isQuaternion ) ) {
  7252. if ( property.isRenderTargetTexture ) {
  7253. console.warn( 'UniformsUtils: Textures of render targets cannot be cloned via cloneUniforms() or mergeUniforms().' );
  7254. dst[ u ][ p ] = null;
  7255. } else {
  7256. dst[ u ][ p ] = property.clone();
  7257. }
  7258. } else if ( Array.isArray( property ) ) {
  7259. dst[ u ][ p ] = property.slice();
  7260. } else {
  7261. dst[ u ][ p ] = property;
  7262. }
  7263. }
  7264. }
  7265. return dst;
  7266. }
  7267. function cloneUniformsGroups( src ) {
  7268. const dst = [];
  7269. for ( let u = 0; u < src.length; u ++ ) {
  7270. dst.push( src[ u ].clone() );
  7271. }
  7272. return dst;
  7273. }
  7274. var default_vertex = /* glsl */`
  7275. void main() {
  7276. gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
  7277. }
  7278. `;
  7279. var default_fragment = /* glsl */`
  7280. void main() {
  7281. gl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );
  7282. }
  7283. `;
  7284. class ShaderMaterial extends Material {
  7285. static get type() {
  7286. return 'ShaderMaterial';
  7287. }
  7288. constructor( parameters ) {
  7289. super();
  7290. this.isShaderMaterial = true;
  7291. this.defines = {};
  7292. this.uniforms = {};
  7293. this.uniformsGroups = [];
  7294. this.vertexShader = default_vertex;
  7295. this.fragmentShader = default_fragment;
  7296. this.linewidth = 1;
  7297. this.wireframe = false;
  7298. this.wireframeLinewidth = 1;
  7299. this.fog = false; // set to use scene fog
  7300. this.lights = false; // set to use scene lights
  7301. this.clipping = false; // set to use user-defined clipping planes
  7302. this.forceSinglePass = true;
  7303. this.extensions = {
  7304. clipCullDistance: false, // set to use vertex shader clipping
  7305. multiDraw: false // set to use vertex shader multi_draw / enable gl_DrawID
  7306. };
  7307. // When rendered geometry doesn't include these attributes but the material does,
  7308. // use these default values in WebGL. This avoids errors when buffer data is missing.
  7309. this.defaultAttributeValues = {
  7310. 'color': [ 1, 1, 1 ],
  7311. 'uv': [ 0, 0 ],
  7312. 'uv1': [ 0, 0 ]
  7313. };
  7314. this.index0AttributeName = undefined;
  7315. this.uniformsNeedUpdate = false;
  7316. this.glslVersion = null;
  7317. if ( parameters !== undefined ) {
  7318. this.setValues( parameters );
  7319. }
  7320. }
  7321. copy( source ) {
  7322. super.copy( source );
  7323. this.fragmentShader = source.fragmentShader;
  7324. this.vertexShader = source.vertexShader;
  7325. this.uniforms = cloneUniforms( source.uniforms );
  7326. this.uniformsGroups = cloneUniformsGroups( source.uniformsGroups );
  7327. this.defines = Object.assign( {}, source.defines );
  7328. this.wireframe = source.wireframe;
  7329. this.wireframeLinewidth = source.wireframeLinewidth;
  7330. this.fog = source.fog;
  7331. this.lights = source.lights;
  7332. this.clipping = source.clipping;
  7333. this.extensions = Object.assign( {}, source.extensions );
  7334. this.glslVersion = source.glslVersion;
  7335. return this;
  7336. }
  7337. toJSON( meta ) {
  7338. const data = super.toJSON( meta );
  7339. data.glslVersion = this.glslVersion;
  7340. data.uniforms = {};
  7341. for ( const name in this.uniforms ) {
  7342. const uniform = this.uniforms[ name ];
  7343. const value = uniform.value;
  7344. if ( value && value.isTexture ) {
  7345. data.uniforms[ name ] = {
  7346. type: 't',
  7347. value: value.toJSON( meta ).uuid
  7348. };
  7349. } else if ( value && value.isColor ) {
  7350. data.uniforms[ name ] = {
  7351. type: 'c',
  7352. value: value.getHex()
  7353. };
  7354. } else if ( value && value.isVector2 ) {
  7355. data.uniforms[ name ] = {
  7356. type: 'v2',
  7357. value: value.toArray()
  7358. };
  7359. } else if ( value && value.isVector3 ) {
  7360. data.uniforms[ name ] = {
  7361. type: 'v3',
  7362. value: value.toArray()
  7363. };
  7364. } else if ( value && value.isVector4 ) {
  7365. data.uniforms[ name ] = {
  7366. type: 'v4',
  7367. value: value.toArray()
  7368. };
  7369. } else if ( value && value.isMatrix3 ) {
  7370. data.uniforms[ name ] = {
  7371. type: 'm3',
  7372. value: value.toArray()
  7373. };
  7374. } else if ( value && value.isMatrix4 ) {
  7375. data.uniforms[ name ] = {
  7376. type: 'm4',
  7377. value: value.toArray()
  7378. };
  7379. } else {
  7380. data.uniforms[ name ] = {
  7381. value: value
  7382. };
  7383. // note: the array variants v2v, v3v, v4v, m4v and tv are not supported so far
  7384. }
  7385. }
  7386. if ( Object.keys( this.defines ).length > 0 ) data.defines = this.defines;
  7387. data.vertexShader = this.vertexShader;
  7388. data.fragmentShader = this.fragmentShader;
  7389. data.lights = this.lights;
  7390. data.clipping = this.clipping;
  7391. const extensions = {};
  7392. for ( const key in this.extensions ) {
  7393. if ( this.extensions[ key ] === true ) extensions[ key ] = true;
  7394. }
  7395. if ( Object.keys( extensions ).length > 0 ) data.extensions = extensions;
  7396. return data;
  7397. }
  7398. }
  7399. class Camera extends Object3D {
  7400. constructor() {
  7401. super();
  7402. this.isCamera = true;
  7403. this.type = 'Camera';
  7404. this.matrixWorldInverse = new Matrix4();
  7405. this.projectionMatrix = new Matrix4();
  7406. this.projectionMatrixInverse = new Matrix4();
  7407. this.coordinateSystem = WebGLCoordinateSystem;
  7408. }
  7409. copy( source, recursive ) {
  7410. super.copy( source, recursive );
  7411. this.matrixWorldInverse.copy( source.matrixWorldInverse );
  7412. this.projectionMatrix.copy( source.projectionMatrix );
  7413. this.projectionMatrixInverse.copy( source.projectionMatrixInverse );
  7414. this.coordinateSystem = source.coordinateSystem;
  7415. return this;
  7416. }
  7417. getWorldDirection( target ) {
  7418. return super.getWorldDirection( target ).negate();
  7419. }
  7420. updateMatrixWorld( force ) {
  7421. super.updateMatrixWorld( force );
  7422. this.matrixWorldInverse.copy( this.matrixWorld ).invert();
  7423. }
  7424. updateWorldMatrix( updateParents, updateChildren ) {
  7425. super.updateWorldMatrix( updateParents, updateChildren );
  7426. this.matrixWorldInverse.copy( this.matrixWorld ).invert();
  7427. }
  7428. clone() {
  7429. return new this.constructor().copy( this );
  7430. }
  7431. }
  7432. const _v3$1 = /*@__PURE__*/ new Vector3();
  7433. const _minTarget = /*@__PURE__*/ new Vector2();
  7434. const _maxTarget = /*@__PURE__*/ new Vector2();
  7435. class PerspectiveCamera extends Camera {
  7436. constructor( fov = 50, aspect = 1, near = 0.1, far = 2000 ) {
  7437. super();
  7438. this.isPerspectiveCamera = true;
  7439. this.type = 'PerspectiveCamera';
  7440. this.fov = fov;
  7441. this.zoom = 1;
  7442. this.near = near;
  7443. this.far = far;
  7444. this.focus = 10;
  7445. this.aspect = aspect;
  7446. this.view = null;
  7447. this.filmGauge = 35; // width of the film (default in millimeters)
  7448. this.filmOffset = 0; // horizontal film offset (same unit as gauge)
  7449. this.updateProjectionMatrix();
  7450. }
  7451. copy( source, recursive ) {
  7452. super.copy( source, recursive );
  7453. this.fov = source.fov;
  7454. this.zoom = source.zoom;
  7455. this.near = source.near;
  7456. this.far = source.far;
  7457. this.focus = source.focus;
  7458. this.aspect = source.aspect;
  7459. this.view = source.view === null ? null : Object.assign( {}, source.view );
  7460. this.filmGauge = source.filmGauge;
  7461. this.filmOffset = source.filmOffset;
  7462. return this;
  7463. }
  7464. /**
  7465. * Sets the FOV by focal length in respect to the current .filmGauge.
  7466. *
  7467. * The default film gauge is 35, so that the focal length can be specified for
  7468. * a 35mm (full frame) camera.
  7469. *
  7470. * Values for focal length and film gauge must have the same unit.
  7471. */
  7472. setFocalLength( focalLength ) {
  7473. /** see {@link http://www.bobatkins.com/photography/technical/field_of_view.html} */
  7474. const vExtentSlope = 0.5 * this.getFilmHeight() / focalLength;
  7475. this.fov = RAD2DEG * 2 * Math.atan( vExtentSlope );
  7476. this.updateProjectionMatrix();
  7477. }
  7478. /**
  7479. * Calculates the focal length from the current .fov and .filmGauge.
  7480. */
  7481. getFocalLength() {
  7482. const vExtentSlope = Math.tan( DEG2RAD * 0.5 * this.fov );
  7483. return 0.5 * this.getFilmHeight() / vExtentSlope;
  7484. }
  7485. getEffectiveFOV() {
  7486. return RAD2DEG * 2 * Math.atan(
  7487. Math.tan( DEG2RAD * 0.5 * this.fov ) / this.zoom );
  7488. }
  7489. getFilmWidth() {
  7490. // film not completely covered in portrait format (aspect < 1)
  7491. return this.filmGauge * Math.min( this.aspect, 1 );
  7492. }
  7493. getFilmHeight() {
  7494. // film not completely covered in landscape format (aspect > 1)
  7495. return this.filmGauge / Math.max( this.aspect, 1 );
  7496. }
  7497. /**
  7498. * Computes the 2D bounds of the camera's viewable rectangle at a given distance along the viewing direction.
  7499. * Sets minTarget and maxTarget to the coordinates of the lower-left and upper-right corners of the view rectangle.
  7500. */
  7501. getViewBounds( distance, minTarget, maxTarget ) {
  7502. _v3$1.set( - 1, - 1, 0.5 ).applyMatrix4( this.projectionMatrixInverse );
  7503. minTarget.set( _v3$1.x, _v3$1.y ).multiplyScalar( - distance / _v3$1.z );
  7504. _v3$1.set( 1, 1, 0.5 ).applyMatrix4( this.projectionMatrixInverse );
  7505. maxTarget.set( _v3$1.x, _v3$1.y ).multiplyScalar( - distance / _v3$1.z );
  7506. }
  7507. /**
  7508. * Computes the width and height of the camera's viewable rectangle at a given distance along the viewing direction.
  7509. * Copies the result into the target Vector2, where x is width and y is height.
  7510. */
  7511. getViewSize( distance, target ) {
  7512. this.getViewBounds( distance, _minTarget, _maxTarget );
  7513. return target.subVectors( _maxTarget, _minTarget );
  7514. }
  7515. /**
  7516. * Sets an offset in a larger frustum. This is useful for multi-window or
  7517. * multi-monitor/multi-machine setups.
  7518. *
  7519. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  7520. * the monitors are in grid like this
  7521. *
  7522. * +---+---+---+
  7523. * | A | B | C |
  7524. * +---+---+---+
  7525. * | D | E | F |
  7526. * +---+---+---+
  7527. *
  7528. * then for each monitor you would call it like this
  7529. *
  7530. * const w = 1920;
  7531. * const h = 1080;
  7532. * const fullWidth = w * 3;
  7533. * const fullHeight = h * 2;
  7534. *
  7535. * --A--
  7536. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  7537. * --B--
  7538. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  7539. * --C--
  7540. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  7541. * --D--
  7542. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  7543. * --E--
  7544. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  7545. * --F--
  7546. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  7547. *
  7548. * Note there is no reason monitors have to be the same size or in a grid.
  7549. */
  7550. setViewOffset( fullWidth, fullHeight, x, y, width, height ) {
  7551. this.aspect = fullWidth / fullHeight;
  7552. if ( this.view === null ) {
  7553. this.view = {
  7554. enabled: true,
  7555. fullWidth: 1,
  7556. fullHeight: 1,
  7557. offsetX: 0,
  7558. offsetY: 0,
  7559. width: 1,
  7560. height: 1
  7561. };
  7562. }
  7563. this.view.enabled = true;
  7564. this.view.fullWidth = fullWidth;
  7565. this.view.fullHeight = fullHeight;
  7566. this.view.offsetX = x;
  7567. this.view.offsetY = y;
  7568. this.view.width = width;
  7569. this.view.height = height;
  7570. this.updateProjectionMatrix();
  7571. }
  7572. clearViewOffset() {
  7573. if ( this.view !== null ) {
  7574. this.view.enabled = false;
  7575. }
  7576. this.updateProjectionMatrix();
  7577. }
  7578. updateProjectionMatrix() {
  7579. const near = this.near;
  7580. let top = near * Math.tan( DEG2RAD * 0.5 * this.fov ) / this.zoom;
  7581. let height = 2 * top;
  7582. let width = this.aspect * height;
  7583. let left = - 0.5 * width;
  7584. const view = this.view;
  7585. if ( this.view !== null && this.view.enabled ) {
  7586. const fullWidth = view.fullWidth,
  7587. fullHeight = view.fullHeight;
  7588. left += view.offsetX * width / fullWidth;
  7589. top -= view.offsetY * height / fullHeight;
  7590. width *= view.width / fullWidth;
  7591. height *= view.height / fullHeight;
  7592. }
  7593. const skew = this.filmOffset;
  7594. if ( skew !== 0 ) left += near * skew / this.getFilmWidth();
  7595. this.projectionMatrix.makePerspective( left, left + width, top, top - height, near, this.far, this.coordinateSystem );
  7596. this.projectionMatrixInverse.copy( this.projectionMatrix ).invert();
  7597. }
  7598. toJSON( meta ) {
  7599. const data = super.toJSON( meta );
  7600. data.object.fov = this.fov;
  7601. data.object.zoom = this.zoom;
  7602. data.object.near = this.near;
  7603. data.object.far = this.far;
  7604. data.object.focus = this.focus;
  7605. data.object.aspect = this.aspect;
  7606. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  7607. data.object.filmGauge = this.filmGauge;
  7608. data.object.filmOffset = this.filmOffset;
  7609. return data;
  7610. }
  7611. }
  7612. const fov = - 90; // negative fov is not an error
  7613. const aspect = 1;
  7614. class CubeCamera extends Object3D {
  7615. constructor( near, far, renderTarget ) {
  7616. super();
  7617. this.type = 'CubeCamera';
  7618. this.renderTarget = renderTarget;
  7619. this.coordinateSystem = null;
  7620. this.activeMipmapLevel = 0;
  7621. const cameraPX = new PerspectiveCamera( fov, aspect, near, far );
  7622. cameraPX.layers = this.layers;
  7623. this.add( cameraPX );
  7624. const cameraNX = new PerspectiveCamera( fov, aspect, near, far );
  7625. cameraNX.layers = this.layers;
  7626. this.add( cameraNX );
  7627. const cameraPY = new PerspectiveCamera( fov, aspect, near, far );
  7628. cameraPY.layers = this.layers;
  7629. this.add( cameraPY );
  7630. const cameraNY = new PerspectiveCamera( fov, aspect, near, far );
  7631. cameraNY.layers = this.layers;
  7632. this.add( cameraNY );
  7633. const cameraPZ = new PerspectiveCamera( fov, aspect, near, far );
  7634. cameraPZ.layers = this.layers;
  7635. this.add( cameraPZ );
  7636. const cameraNZ = new PerspectiveCamera( fov, aspect, near, far );
  7637. cameraNZ.layers = this.layers;
  7638. this.add( cameraNZ );
  7639. }
  7640. updateCoordinateSystem() {
  7641. const coordinateSystem = this.coordinateSystem;
  7642. const cameras = this.children.concat();
  7643. const [ cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ ] = cameras;
  7644. for ( const camera of cameras ) this.remove( camera );
  7645. if ( coordinateSystem === WebGLCoordinateSystem ) {
  7646. cameraPX.up.set( 0, 1, 0 );
  7647. cameraPX.lookAt( 1, 0, 0 );
  7648. cameraNX.up.set( 0, 1, 0 );
  7649. cameraNX.lookAt( - 1, 0, 0 );
  7650. cameraPY.up.set( 0, 0, - 1 );
  7651. cameraPY.lookAt( 0, 1, 0 );
  7652. cameraNY.up.set( 0, 0, 1 );
  7653. cameraNY.lookAt( 0, - 1, 0 );
  7654. cameraPZ.up.set( 0, 1, 0 );
  7655. cameraPZ.lookAt( 0, 0, 1 );
  7656. cameraNZ.up.set( 0, 1, 0 );
  7657. cameraNZ.lookAt( 0, 0, - 1 );
  7658. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  7659. cameraPX.up.set( 0, - 1, 0 );
  7660. cameraPX.lookAt( - 1, 0, 0 );
  7661. cameraNX.up.set( 0, - 1, 0 );
  7662. cameraNX.lookAt( 1, 0, 0 );
  7663. cameraPY.up.set( 0, 0, 1 );
  7664. cameraPY.lookAt( 0, 1, 0 );
  7665. cameraNY.up.set( 0, 0, - 1 );
  7666. cameraNY.lookAt( 0, - 1, 0 );
  7667. cameraPZ.up.set( 0, - 1, 0 );
  7668. cameraPZ.lookAt( 0, 0, 1 );
  7669. cameraNZ.up.set( 0, - 1, 0 );
  7670. cameraNZ.lookAt( 0, 0, - 1 );
  7671. } else {
  7672. throw new Error( 'THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: ' + coordinateSystem );
  7673. }
  7674. for ( const camera of cameras ) {
  7675. this.add( camera );
  7676. camera.updateMatrixWorld();
  7677. }
  7678. }
  7679. update( renderer, scene ) {
  7680. if ( this.parent === null ) this.updateMatrixWorld();
  7681. const { renderTarget, activeMipmapLevel } = this;
  7682. if ( this.coordinateSystem !== renderer.coordinateSystem ) {
  7683. this.coordinateSystem = renderer.coordinateSystem;
  7684. this.updateCoordinateSystem();
  7685. }
  7686. const [ cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ ] = this.children;
  7687. const currentRenderTarget = renderer.getRenderTarget();
  7688. const currentActiveCubeFace = renderer.getActiveCubeFace();
  7689. const currentActiveMipmapLevel = renderer.getActiveMipmapLevel();
  7690. const currentXrEnabled = renderer.xr.enabled;
  7691. renderer.xr.enabled = false;
  7692. const generateMipmaps = renderTarget.texture.generateMipmaps;
  7693. renderTarget.texture.generateMipmaps = false;
  7694. renderer.setRenderTarget( renderTarget, 0, activeMipmapLevel );
  7695. renderer.render( scene, cameraPX );
  7696. renderer.setRenderTarget( renderTarget, 1, activeMipmapLevel );
  7697. renderer.render( scene, cameraNX );
  7698. renderer.setRenderTarget( renderTarget, 2, activeMipmapLevel );
  7699. renderer.render( scene, cameraPY );
  7700. renderer.setRenderTarget( renderTarget, 3, activeMipmapLevel );
  7701. renderer.render( scene, cameraNY );
  7702. renderer.setRenderTarget( renderTarget, 4, activeMipmapLevel );
  7703. renderer.render( scene, cameraPZ );
  7704. // mipmaps are generated during the last call of render()
  7705. // at this point, all sides of the cube render target are defined
  7706. renderTarget.texture.generateMipmaps = generateMipmaps;
  7707. renderer.setRenderTarget( renderTarget, 5, activeMipmapLevel );
  7708. renderer.render( scene, cameraNZ );
  7709. renderer.setRenderTarget( currentRenderTarget, currentActiveCubeFace, currentActiveMipmapLevel );
  7710. renderer.xr.enabled = currentXrEnabled;
  7711. renderTarget.texture.needsPMREMUpdate = true;
  7712. }
  7713. }
  7714. class CubeTexture extends Texture {
  7715. constructor( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace ) {
  7716. images = images !== undefined ? images : [];
  7717. mapping = mapping !== undefined ? mapping : CubeReflectionMapping;
  7718. super( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace );
  7719. this.isCubeTexture = true;
  7720. this.flipY = false;
  7721. }
  7722. get images() {
  7723. return this.image;
  7724. }
  7725. set images( value ) {
  7726. this.image = value;
  7727. }
  7728. }
  7729. class WebGLCubeRenderTarget extends WebGLRenderTarget {
  7730. constructor( size = 1, options = {} ) {
  7731. super( size, size, options );
  7732. this.isWebGLCubeRenderTarget = true;
  7733. const image = { width: size, height: size, depth: 1 };
  7734. const images = [ image, image, image, image, image, image ];
  7735. this.texture = new CubeTexture( images, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.colorSpace );
  7736. // By convention -- likely based on the RenderMan spec from the 1990's -- cube maps are specified by WebGL (and three.js)
  7737. // in a coordinate system in which positive-x is to the right when looking up the positive-z axis -- in other words,
  7738. // in a left-handed coordinate system. By continuing this convention, preexisting cube maps continued to render correctly.
  7739. // three.js uses a right-handed coordinate system. So environment maps used in three.js appear to have px and nx swapped
  7740. // and the flag isRenderTargetTexture controls this conversion. The flip is not required when using WebGLCubeRenderTarget.texture
  7741. // as a cube texture (this is detected when isRenderTargetTexture is set to true for cube textures).
  7742. this.texture.isRenderTargetTexture = true;
  7743. this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false;
  7744. this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter;
  7745. }
  7746. fromEquirectangularTexture( renderer, texture ) {
  7747. this.texture.type = texture.type;
  7748. this.texture.colorSpace = texture.colorSpace;
  7749. this.texture.generateMipmaps = texture.generateMipmaps;
  7750. this.texture.minFilter = texture.minFilter;
  7751. this.texture.magFilter = texture.magFilter;
  7752. const shader = {
  7753. uniforms: {
  7754. tEquirect: { value: null },
  7755. },
  7756. vertexShader: /* glsl */`
  7757. varying vec3 vWorldDirection;
  7758. vec3 transformDirection( in vec3 dir, in mat4 matrix ) {
  7759. return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );
  7760. }
  7761. void main() {
  7762. vWorldDirection = transformDirection( position, modelMatrix );
  7763. #include <begin_vertex>
  7764. #include <project_vertex>
  7765. }
  7766. `,
  7767. fragmentShader: /* glsl */`
  7768. uniform sampler2D tEquirect;
  7769. varying vec3 vWorldDirection;
  7770. #include <common>
  7771. void main() {
  7772. vec3 direction = normalize( vWorldDirection );
  7773. vec2 sampleUV = equirectUv( direction );
  7774. gl_FragColor = texture2D( tEquirect, sampleUV );
  7775. }
  7776. `
  7777. };
  7778. const geometry = new BoxGeometry( 5, 5, 5 );
  7779. const material = new ShaderMaterial( {
  7780. name: 'CubemapFromEquirect',
  7781. uniforms: cloneUniforms( shader.uniforms ),
  7782. vertexShader: shader.vertexShader,
  7783. fragmentShader: shader.fragmentShader,
  7784. side: BackSide,
  7785. blending: NoBlending
  7786. } );
  7787. material.uniforms.tEquirect.value = texture;
  7788. const mesh = new Mesh( geometry, material );
  7789. const currentMinFilter = texture.minFilter;
  7790. // Avoid blurred poles
  7791. if ( texture.minFilter === LinearMipmapLinearFilter ) texture.minFilter = LinearFilter;
  7792. const camera = new CubeCamera( 1, 10, this );
  7793. camera.update( renderer, mesh );
  7794. texture.minFilter = currentMinFilter;
  7795. mesh.geometry.dispose();
  7796. mesh.material.dispose();
  7797. return this;
  7798. }
  7799. clear( renderer, color, depth, stencil ) {
  7800. const currentRenderTarget = renderer.getRenderTarget();
  7801. for ( let i = 0; i < 6; i ++ ) {
  7802. renderer.setRenderTarget( this, i );
  7803. renderer.clear( color, depth, stencil );
  7804. }
  7805. renderer.setRenderTarget( currentRenderTarget );
  7806. }
  7807. }
  7808. class FogExp2 {
  7809. constructor( color, density = 0.00025 ) {
  7810. this.isFogExp2 = true;
  7811. this.name = '';
  7812. this.color = new Color( color );
  7813. this.density = density;
  7814. }
  7815. clone() {
  7816. return new FogExp2( this.color, this.density );
  7817. }
  7818. toJSON( /* meta */ ) {
  7819. return {
  7820. type: 'FogExp2',
  7821. name: this.name,
  7822. color: this.color.getHex(),
  7823. density: this.density
  7824. };
  7825. }
  7826. }
  7827. class Fog {
  7828. constructor( color, near = 1, far = 1000 ) {
  7829. this.isFog = true;
  7830. this.name = '';
  7831. this.color = new Color( color );
  7832. this.near = near;
  7833. this.far = far;
  7834. }
  7835. clone() {
  7836. return new Fog( this.color, this.near, this.far );
  7837. }
  7838. toJSON( /* meta */ ) {
  7839. return {
  7840. type: 'Fog',
  7841. name: this.name,
  7842. color: this.color.getHex(),
  7843. near: this.near,
  7844. far: this.far
  7845. };
  7846. }
  7847. }
  7848. class Scene extends Object3D {
  7849. constructor() {
  7850. super();
  7851. this.isScene = true;
  7852. this.type = 'Scene';
  7853. this.background = null;
  7854. this.environment = null;
  7855. this.fog = null;
  7856. this.backgroundBlurriness = 0;
  7857. this.backgroundIntensity = 1;
  7858. this.backgroundRotation = new Euler();
  7859. this.environmentIntensity = 1;
  7860. this.environmentRotation = new Euler();
  7861. this.overrideMaterial = null;
  7862. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  7863. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) );
  7864. }
  7865. }
  7866. copy( source, recursive ) {
  7867. super.copy( source, recursive );
  7868. if ( source.background !== null ) this.background = source.background.clone();
  7869. if ( source.environment !== null ) this.environment = source.environment.clone();
  7870. if ( source.fog !== null ) this.fog = source.fog.clone();
  7871. this.backgroundBlurriness = source.backgroundBlurriness;
  7872. this.backgroundIntensity = source.backgroundIntensity;
  7873. this.backgroundRotation.copy( source.backgroundRotation );
  7874. this.environmentIntensity = source.environmentIntensity;
  7875. this.environmentRotation.copy( source.environmentRotation );
  7876. if ( source.overrideMaterial !== null ) this.overrideMaterial = source.overrideMaterial.clone();
  7877. this.matrixAutoUpdate = source.matrixAutoUpdate;
  7878. return this;
  7879. }
  7880. toJSON( meta ) {
  7881. const data = super.toJSON( meta );
  7882. if ( this.fog !== null ) data.object.fog = this.fog.toJSON();
  7883. if ( this.backgroundBlurriness > 0 ) data.object.backgroundBlurriness = this.backgroundBlurriness;
  7884. if ( this.backgroundIntensity !== 1 ) data.object.backgroundIntensity = this.backgroundIntensity;
  7885. data.object.backgroundRotation = this.backgroundRotation.toArray();
  7886. if ( this.environmentIntensity !== 1 ) data.object.environmentIntensity = this.environmentIntensity;
  7887. data.object.environmentRotation = this.environmentRotation.toArray();
  7888. return data;
  7889. }
  7890. }
  7891. class InterleavedBuffer {
  7892. constructor( array, stride ) {
  7893. this.isInterleavedBuffer = true;
  7894. this.array = array;
  7895. this.stride = stride;
  7896. this.count = array !== undefined ? array.length / stride : 0;
  7897. this.usage = StaticDrawUsage;
  7898. this.updateRanges = [];
  7899. this.version = 0;
  7900. this.uuid = generateUUID();
  7901. }
  7902. onUploadCallback() {}
  7903. set needsUpdate( value ) {
  7904. if ( value === true ) this.version ++;
  7905. }
  7906. setUsage( value ) {
  7907. this.usage = value;
  7908. return this;
  7909. }
  7910. addUpdateRange( start, count ) {
  7911. this.updateRanges.push( { start, count } );
  7912. }
  7913. clearUpdateRanges() {
  7914. this.updateRanges.length = 0;
  7915. }
  7916. copy( source ) {
  7917. this.array = new source.array.constructor( source.array );
  7918. this.count = source.count;
  7919. this.stride = source.stride;
  7920. this.usage = source.usage;
  7921. return this;
  7922. }
  7923. copyAt( index1, attribute, index2 ) {
  7924. index1 *= this.stride;
  7925. index2 *= attribute.stride;
  7926. for ( let i = 0, l = this.stride; i < l; i ++ ) {
  7927. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  7928. }
  7929. return this;
  7930. }
  7931. set( value, offset = 0 ) {
  7932. this.array.set( value, offset );
  7933. return this;
  7934. }
  7935. clone( data ) {
  7936. if ( data.arrayBuffers === undefined ) {
  7937. data.arrayBuffers = {};
  7938. }
  7939. if ( this.array.buffer._uuid === undefined ) {
  7940. this.array.buffer._uuid = generateUUID();
  7941. }
  7942. if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) {
  7943. data.arrayBuffers[ this.array.buffer._uuid ] = this.array.slice( 0 ).buffer;
  7944. }
  7945. const array = new this.array.constructor( data.arrayBuffers[ this.array.buffer._uuid ] );
  7946. const ib = new this.constructor( array, this.stride );
  7947. ib.setUsage( this.usage );
  7948. return ib;
  7949. }
  7950. onUpload( callback ) {
  7951. this.onUploadCallback = callback;
  7952. return this;
  7953. }
  7954. toJSON( data ) {
  7955. if ( data.arrayBuffers === undefined ) {
  7956. data.arrayBuffers = {};
  7957. }
  7958. // generate UUID for array buffer if necessary
  7959. if ( this.array.buffer._uuid === undefined ) {
  7960. this.array.buffer._uuid = generateUUID();
  7961. }
  7962. if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) {
  7963. data.arrayBuffers[ this.array.buffer._uuid ] = Array.from( new Uint32Array( this.array.buffer ) );
  7964. }
  7965. //
  7966. return {
  7967. uuid: this.uuid,
  7968. buffer: this.array.buffer._uuid,
  7969. type: this.array.constructor.name,
  7970. stride: this.stride
  7971. };
  7972. }
  7973. }
  7974. const _vector$7 = /*@__PURE__*/ new Vector3();
  7975. class InterleavedBufferAttribute {
  7976. constructor( interleavedBuffer, itemSize, offset, normalized = false ) {
  7977. this.isInterleavedBufferAttribute = true;
  7978. this.name = '';
  7979. this.data = interleavedBuffer;
  7980. this.itemSize = itemSize;
  7981. this.offset = offset;
  7982. this.normalized = normalized;
  7983. }
  7984. get count() {
  7985. return this.data.count;
  7986. }
  7987. get array() {
  7988. return this.data.array;
  7989. }
  7990. set needsUpdate( value ) {
  7991. this.data.needsUpdate = value;
  7992. }
  7993. applyMatrix4( m ) {
  7994. for ( let i = 0, l = this.data.count; i < l; i ++ ) {
  7995. _vector$7.fromBufferAttribute( this, i );
  7996. _vector$7.applyMatrix4( m );
  7997. this.setXYZ( i, _vector$7.x, _vector$7.y, _vector$7.z );
  7998. }
  7999. return this;
  8000. }
  8001. applyNormalMatrix( m ) {
  8002. for ( let i = 0, l = this.count; i < l; i ++ ) {
  8003. _vector$7.fromBufferAttribute( this, i );
  8004. _vector$7.applyNormalMatrix( m );
  8005. this.setXYZ( i, _vector$7.x, _vector$7.y, _vector$7.z );
  8006. }
  8007. return this;
  8008. }
  8009. transformDirection( m ) {
  8010. for ( let i = 0, l = this.count; i < l; i ++ ) {
  8011. _vector$7.fromBufferAttribute( this, i );
  8012. _vector$7.transformDirection( m );
  8013. this.setXYZ( i, _vector$7.x, _vector$7.y, _vector$7.z );
  8014. }
  8015. return this;
  8016. }
  8017. getComponent( index, component ) {
  8018. let value = this.array[ index * this.data.stride + this.offset + component ];
  8019. if ( this.normalized ) value = denormalize( value, this.array );
  8020. return value;
  8021. }
  8022. setComponent( index, component, value ) {
  8023. if ( this.normalized ) value = normalize$1( value, this.array );
  8024. this.data.array[ index * this.data.stride + this.offset + component ] = value;
  8025. return this;
  8026. }
  8027. setX( index, x ) {
  8028. if ( this.normalized ) x = normalize$1( x, this.array );
  8029. this.data.array[ index * this.data.stride + this.offset ] = x;
  8030. return this;
  8031. }
  8032. setY( index, y ) {
  8033. if ( this.normalized ) y = normalize$1( y, this.array );
  8034. this.data.array[ index * this.data.stride + this.offset + 1 ] = y;
  8035. return this;
  8036. }
  8037. setZ( index, z ) {
  8038. if ( this.normalized ) z = normalize$1( z, this.array );
  8039. this.data.array[ index * this.data.stride + this.offset + 2 ] = z;
  8040. return this;
  8041. }
  8042. setW( index, w ) {
  8043. if ( this.normalized ) w = normalize$1( w, this.array );
  8044. this.data.array[ index * this.data.stride + this.offset + 3 ] = w;
  8045. return this;
  8046. }
  8047. getX( index ) {
  8048. let x = this.data.array[ index * this.data.stride + this.offset ];
  8049. if ( this.normalized ) x = denormalize( x, this.array );
  8050. return x;
  8051. }
  8052. getY( index ) {
  8053. let y = this.data.array[ index * this.data.stride + this.offset + 1 ];
  8054. if ( this.normalized ) y = denormalize( y, this.array );
  8055. return y;
  8056. }
  8057. getZ( index ) {
  8058. let z = this.data.array[ index * this.data.stride + this.offset + 2 ];
  8059. if ( this.normalized ) z = denormalize( z, this.array );
  8060. return z;
  8061. }
  8062. getW( index ) {
  8063. let w = this.data.array[ index * this.data.stride + this.offset + 3 ];
  8064. if ( this.normalized ) w = denormalize( w, this.array );
  8065. return w;
  8066. }
  8067. setXY( index, x, y ) {
  8068. index = index * this.data.stride + this.offset;
  8069. if ( this.normalized ) {
  8070. x = normalize$1( x, this.array );
  8071. y = normalize$1( y, this.array );
  8072. }
  8073. this.data.array[ index + 0 ] = x;
  8074. this.data.array[ index + 1 ] = y;
  8075. return this;
  8076. }
  8077. setXYZ( index, x, y, z ) {
  8078. index = index * this.data.stride + this.offset;
  8079. if ( this.normalized ) {
  8080. x = normalize$1( x, this.array );
  8081. y = normalize$1( y, this.array );
  8082. z = normalize$1( z, this.array );
  8083. }
  8084. this.data.array[ index + 0 ] = x;
  8085. this.data.array[ index + 1 ] = y;
  8086. this.data.array[ index + 2 ] = z;
  8087. return this;
  8088. }
  8089. setXYZW( index, x, y, z, w ) {
  8090. index = index * this.data.stride + this.offset;
  8091. if ( this.normalized ) {
  8092. x = normalize$1( x, this.array );
  8093. y = normalize$1( y, this.array );
  8094. z = normalize$1( z, this.array );
  8095. w = normalize$1( w, this.array );
  8096. }
  8097. this.data.array[ index + 0 ] = x;
  8098. this.data.array[ index + 1 ] = y;
  8099. this.data.array[ index + 2 ] = z;
  8100. this.data.array[ index + 3 ] = w;
  8101. return this;
  8102. }
  8103. clone( data ) {
  8104. if ( data === undefined ) {
  8105. console.log( 'THREE.InterleavedBufferAttribute.clone(): Cloning an interleaved buffer attribute will de-interleave buffer data.' );
  8106. const array = [];
  8107. for ( let i = 0; i < this.count; i ++ ) {
  8108. const index = i * this.data.stride + this.offset;
  8109. for ( let j = 0; j < this.itemSize; j ++ ) {
  8110. array.push( this.data.array[ index + j ] );
  8111. }
  8112. }
  8113. return new BufferAttribute( new this.array.constructor( array ), this.itemSize, this.normalized );
  8114. } else {
  8115. if ( data.interleavedBuffers === undefined ) {
  8116. data.interleavedBuffers = {};
  8117. }
  8118. if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) {
  8119. data.interleavedBuffers[ this.data.uuid ] = this.data.clone( data );
  8120. }
  8121. return new InterleavedBufferAttribute( data.interleavedBuffers[ this.data.uuid ], this.itemSize, this.offset, this.normalized );
  8122. }
  8123. }
  8124. toJSON( data ) {
  8125. if ( data === undefined ) {
  8126. console.log( 'THREE.InterleavedBufferAttribute.toJSON(): Serializing an interleaved buffer attribute will de-interleave buffer data.' );
  8127. const array = [];
  8128. for ( let i = 0; i < this.count; i ++ ) {
  8129. const index = i * this.data.stride + this.offset;
  8130. for ( let j = 0; j < this.itemSize; j ++ ) {
  8131. array.push( this.data.array[ index + j ] );
  8132. }
  8133. }
  8134. // de-interleave data and save it as an ordinary buffer attribute for now
  8135. return {
  8136. itemSize: this.itemSize,
  8137. type: this.array.constructor.name,
  8138. array: array,
  8139. normalized: this.normalized
  8140. };
  8141. } else {
  8142. // save as true interleaved attribute
  8143. if ( data.interleavedBuffers === undefined ) {
  8144. data.interleavedBuffers = {};
  8145. }
  8146. if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) {
  8147. data.interleavedBuffers[ this.data.uuid ] = this.data.toJSON( data );
  8148. }
  8149. return {
  8150. isInterleavedBufferAttribute: true,
  8151. itemSize: this.itemSize,
  8152. data: this.data.uuid,
  8153. offset: this.offset,
  8154. normalized: this.normalized
  8155. };
  8156. }
  8157. }
  8158. }
  8159. class SpriteMaterial extends Material {
  8160. static get type() {
  8161. return 'SpriteMaterial';
  8162. }
  8163. constructor( parameters ) {
  8164. super();
  8165. this.isSpriteMaterial = true;
  8166. this.color = new Color( 0xffffff );
  8167. this.map = null;
  8168. this.alphaMap = null;
  8169. this.rotation = 0;
  8170. this.sizeAttenuation = true;
  8171. this.transparent = true;
  8172. this.fog = true;
  8173. this.setValues( parameters );
  8174. }
  8175. copy( source ) {
  8176. super.copy( source );
  8177. this.color.copy( source.color );
  8178. this.map = source.map;
  8179. this.alphaMap = source.alphaMap;
  8180. this.rotation = source.rotation;
  8181. this.sizeAttenuation = source.sizeAttenuation;
  8182. this.fog = source.fog;
  8183. return this;
  8184. }
  8185. }
  8186. let _geometry$1;
  8187. const _intersectPoint = /*@__PURE__*/ new Vector3();
  8188. const _worldScale = /*@__PURE__*/ new Vector3();
  8189. const _mvPosition = /*@__PURE__*/ new Vector3();
  8190. const _alignedPosition = /*@__PURE__*/ new Vector2();
  8191. const _rotatedPosition = /*@__PURE__*/ new Vector2();
  8192. const _viewWorldMatrix = /*@__PURE__*/ new Matrix4();
  8193. const _vA = /*@__PURE__*/ new Vector3();
  8194. const _vB = /*@__PURE__*/ new Vector3();
  8195. const _vC = /*@__PURE__*/ new Vector3();
  8196. const _uvA = /*@__PURE__*/ new Vector2();
  8197. const _uvB = /*@__PURE__*/ new Vector2();
  8198. const _uvC = /*@__PURE__*/ new Vector2();
  8199. class Sprite extends Object3D {
  8200. constructor( material = new SpriteMaterial() ) {
  8201. super();
  8202. this.isSprite = true;
  8203. this.type = 'Sprite';
  8204. if ( _geometry$1 === undefined ) {
  8205. _geometry$1 = new BufferGeometry();
  8206. const float32Array = new Float32Array( [
  8207. - 0.5, - 0.5, 0, 0, 0,
  8208. 0.5, - 0.5, 0, 1, 0,
  8209. 0.5, 0.5, 0, 1, 1,
  8210. - 0.5, 0.5, 0, 0, 1
  8211. ] );
  8212. const interleavedBuffer = new InterleavedBuffer( float32Array, 5 );
  8213. _geometry$1.setIndex( [ 0, 1, 2, 0, 2, 3 ] );
  8214. _geometry$1.setAttribute( 'position', new InterleavedBufferAttribute( interleavedBuffer, 3, 0, false ) );
  8215. _geometry$1.setAttribute( 'uv', new InterleavedBufferAttribute( interleavedBuffer, 2, 3, false ) );
  8216. }
  8217. this.geometry = _geometry$1;
  8218. this.material = material;
  8219. this.center = new Vector2( 0.5, 0.5 );
  8220. }
  8221. raycast( raycaster, intersects ) {
  8222. if ( raycaster.camera === null ) {
  8223. console.error( 'THREE.Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.' );
  8224. }
  8225. _worldScale.setFromMatrixScale( this.matrixWorld );
  8226. _viewWorldMatrix.copy( raycaster.camera.matrixWorld );
  8227. this.modelViewMatrix.multiplyMatrices( raycaster.camera.matrixWorldInverse, this.matrixWorld );
  8228. _mvPosition.setFromMatrixPosition( this.modelViewMatrix );
  8229. if ( raycaster.camera.isPerspectiveCamera && this.material.sizeAttenuation === false ) {
  8230. _worldScale.multiplyScalar( - _mvPosition.z );
  8231. }
  8232. const rotation = this.material.rotation;
  8233. let sin, cos;
  8234. if ( rotation !== 0 ) {
  8235. cos = Math.cos( rotation );
  8236. sin = Math.sin( rotation );
  8237. }
  8238. const center = this.center;
  8239. transformVertex( _vA.set( - 0.5, - 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  8240. transformVertex( _vB.set( 0.5, - 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  8241. transformVertex( _vC.set( 0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  8242. _uvA.set( 0, 0 );
  8243. _uvB.set( 1, 0 );
  8244. _uvC.set( 1, 1 );
  8245. // check first triangle
  8246. let intersect = raycaster.ray.intersectTriangle( _vA, _vB, _vC, false, _intersectPoint );
  8247. if ( intersect === null ) {
  8248. // check second triangle
  8249. transformVertex( _vB.set( - 0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  8250. _uvB.set( 0, 1 );
  8251. intersect = raycaster.ray.intersectTriangle( _vA, _vC, _vB, false, _intersectPoint );
  8252. if ( intersect === null ) {
  8253. return;
  8254. }
  8255. }
  8256. const distance = raycaster.ray.origin.distanceTo( _intersectPoint );
  8257. if ( distance < raycaster.near || distance > raycaster.far ) return;
  8258. intersects.push( {
  8259. distance: distance,
  8260. point: _intersectPoint.clone(),
  8261. uv: Triangle.getInterpolation( _intersectPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2() ),
  8262. face: null,
  8263. object: this
  8264. } );
  8265. }
  8266. copy( source, recursive ) {
  8267. super.copy( source, recursive );
  8268. if ( source.center !== undefined ) this.center.copy( source.center );
  8269. this.material = source.material;
  8270. return this;
  8271. }
  8272. }
  8273. function transformVertex( vertexPosition, mvPosition, center, scale, sin, cos ) {
  8274. // compute position in camera space
  8275. _alignedPosition.subVectors( vertexPosition, center ).addScalar( 0.5 ).multiply( scale );
  8276. // to check if rotation is not zero
  8277. if ( sin !== undefined ) {
  8278. _rotatedPosition.x = ( cos * _alignedPosition.x ) - ( sin * _alignedPosition.y );
  8279. _rotatedPosition.y = ( sin * _alignedPosition.x ) + ( cos * _alignedPosition.y );
  8280. } else {
  8281. _rotatedPosition.copy( _alignedPosition );
  8282. }
  8283. vertexPosition.copy( mvPosition );
  8284. vertexPosition.x += _rotatedPosition.x;
  8285. vertexPosition.y += _rotatedPosition.y;
  8286. // transform to world space
  8287. vertexPosition.applyMatrix4( _viewWorldMatrix );
  8288. }
  8289. const _v1$2 = /*@__PURE__*/ new Vector3();
  8290. const _v2$1 = /*@__PURE__*/ new Vector3();
  8291. class LOD extends Object3D {
  8292. constructor() {
  8293. super();
  8294. this._currentLevel = 0;
  8295. this.type = 'LOD';
  8296. Object.defineProperties( this, {
  8297. levels: {
  8298. enumerable: true,
  8299. value: []
  8300. },
  8301. isLOD: {
  8302. value: true,
  8303. }
  8304. } );
  8305. this.autoUpdate = true;
  8306. }
  8307. copy( source ) {
  8308. super.copy( source, false );
  8309. const levels = source.levels;
  8310. for ( let i = 0, l = levels.length; i < l; i ++ ) {
  8311. const level = levels[ i ];
  8312. this.addLevel( level.object.clone(), level.distance, level.hysteresis );
  8313. }
  8314. this.autoUpdate = source.autoUpdate;
  8315. return this;
  8316. }
  8317. addLevel( object, distance = 0, hysteresis = 0 ) {
  8318. distance = Math.abs( distance );
  8319. const levels = this.levels;
  8320. let l;
  8321. for ( l = 0; l < levels.length; l ++ ) {
  8322. if ( distance < levels[ l ].distance ) {
  8323. break;
  8324. }
  8325. }
  8326. levels.splice( l, 0, { distance: distance, hysteresis: hysteresis, object: object } );
  8327. this.add( object );
  8328. return this;
  8329. }
  8330. removeLevel( distance ) {
  8331. const levels = this.levels;
  8332. for ( let i = 0; i < levels.length; i ++ ) {
  8333. if ( levels[ i ].distance === distance ) {
  8334. const removedElements = levels.splice( i, 1 );
  8335. this.remove( removedElements[ 0 ].object );
  8336. return true;
  8337. }
  8338. }
  8339. return false;
  8340. }
  8341. getCurrentLevel() {
  8342. return this._currentLevel;
  8343. }
  8344. getObjectForDistance( distance ) {
  8345. const levels = this.levels;
  8346. if ( levels.length > 0 ) {
  8347. let i, l;
  8348. for ( i = 1, l = levels.length; i < l; i ++ ) {
  8349. let levelDistance = levels[ i ].distance;
  8350. if ( levels[ i ].object.visible ) {
  8351. levelDistance -= levelDistance * levels[ i ].hysteresis;
  8352. }
  8353. if ( distance < levelDistance ) {
  8354. break;
  8355. }
  8356. }
  8357. return levels[ i - 1 ].object;
  8358. }
  8359. return null;
  8360. }
  8361. raycast( raycaster, intersects ) {
  8362. const levels = this.levels;
  8363. if ( levels.length > 0 ) {
  8364. _v1$2.setFromMatrixPosition( this.matrixWorld );
  8365. const distance = raycaster.ray.origin.distanceTo( _v1$2 );
  8366. this.getObjectForDistance( distance ).raycast( raycaster, intersects );
  8367. }
  8368. }
  8369. update( camera ) {
  8370. const levels = this.levels;
  8371. if ( levels.length > 1 ) {
  8372. _v1$2.setFromMatrixPosition( camera.matrixWorld );
  8373. _v2$1.setFromMatrixPosition( this.matrixWorld );
  8374. const distance = _v1$2.distanceTo( _v2$1 ) / camera.zoom;
  8375. levels[ 0 ].object.visible = true;
  8376. let i, l;
  8377. for ( i = 1, l = levels.length; i < l; i ++ ) {
  8378. let levelDistance = levels[ i ].distance;
  8379. if ( levels[ i ].object.visible ) {
  8380. levelDistance -= levelDistance * levels[ i ].hysteresis;
  8381. }
  8382. if ( distance >= levelDistance ) {
  8383. levels[ i - 1 ].object.visible = false;
  8384. levels[ i ].object.visible = true;
  8385. } else {
  8386. break;
  8387. }
  8388. }
  8389. this._currentLevel = i - 1;
  8390. for ( ; i < l; i ++ ) {
  8391. levels[ i ].object.visible = false;
  8392. }
  8393. }
  8394. }
  8395. toJSON( meta ) {
  8396. const data = super.toJSON( meta );
  8397. if ( this.autoUpdate === false ) data.object.autoUpdate = false;
  8398. data.object.levels = [];
  8399. const levels = this.levels;
  8400. for ( let i = 0, l = levels.length; i < l; i ++ ) {
  8401. const level = levels[ i ];
  8402. data.object.levels.push( {
  8403. object: level.object.uuid,
  8404. distance: level.distance,
  8405. hysteresis: level.hysteresis
  8406. } );
  8407. }
  8408. return data;
  8409. }
  8410. }
  8411. const _basePosition = /*@__PURE__*/ new Vector3();
  8412. const _skinIndex = /*@__PURE__*/ new Vector4();
  8413. const _skinWeight = /*@__PURE__*/ new Vector4();
  8414. const _vector3 = /*@__PURE__*/ new Vector3();
  8415. const _matrix4 = /*@__PURE__*/ new Matrix4();
  8416. const _vertex = /*@__PURE__*/ new Vector3();
  8417. const _sphere$5 = /*@__PURE__*/ new Sphere();
  8418. const _inverseMatrix$2 = /*@__PURE__*/ new Matrix4();
  8419. const _ray$2 = /*@__PURE__*/ new Ray();
  8420. class SkinnedMesh extends Mesh {
  8421. constructor( geometry, material ) {
  8422. super( geometry, material );
  8423. this.isSkinnedMesh = true;
  8424. this.type = 'SkinnedMesh';
  8425. this.bindMode = AttachedBindMode;
  8426. this.bindMatrix = new Matrix4();
  8427. this.bindMatrixInverse = new Matrix4();
  8428. this.boundingBox = null;
  8429. this.boundingSphere = null;
  8430. }
  8431. computeBoundingBox() {
  8432. const geometry = this.geometry;
  8433. if ( this.boundingBox === null ) {
  8434. this.boundingBox = new Box3();
  8435. }
  8436. this.boundingBox.makeEmpty();
  8437. const positionAttribute = geometry.getAttribute( 'position' );
  8438. for ( let i = 0; i < positionAttribute.count; i ++ ) {
  8439. this.getVertexPosition( i, _vertex );
  8440. this.boundingBox.expandByPoint( _vertex );
  8441. }
  8442. }
  8443. computeBoundingSphere() {
  8444. const geometry = this.geometry;
  8445. if ( this.boundingSphere === null ) {
  8446. this.boundingSphere = new Sphere();
  8447. }
  8448. this.boundingSphere.makeEmpty();
  8449. const positionAttribute = geometry.getAttribute( 'position' );
  8450. for ( let i = 0; i < positionAttribute.count; i ++ ) {
  8451. this.getVertexPosition( i, _vertex );
  8452. this.boundingSphere.expandByPoint( _vertex );
  8453. }
  8454. }
  8455. copy( source, recursive ) {
  8456. super.copy( source, recursive );
  8457. this.bindMode = source.bindMode;
  8458. this.bindMatrix.copy( source.bindMatrix );
  8459. this.bindMatrixInverse.copy( source.bindMatrixInverse );
  8460. this.skeleton = source.skeleton;
  8461. if ( source.boundingBox !== null ) this.boundingBox = source.boundingBox.clone();
  8462. if ( source.boundingSphere !== null ) this.boundingSphere = source.boundingSphere.clone();
  8463. return this;
  8464. }
  8465. raycast( raycaster, intersects ) {
  8466. const material = this.material;
  8467. const matrixWorld = this.matrixWorld;
  8468. if ( material === undefined ) return;
  8469. // test with bounding sphere in world space
  8470. if ( this.boundingSphere === null ) this.computeBoundingSphere();
  8471. _sphere$5.copy( this.boundingSphere );
  8472. _sphere$5.applyMatrix4( matrixWorld );
  8473. if ( raycaster.ray.intersectsSphere( _sphere$5 ) === false ) return;
  8474. // convert ray to local space of skinned mesh
  8475. _inverseMatrix$2.copy( matrixWorld ).invert();
  8476. _ray$2.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$2 );
  8477. // test with bounding box in local space
  8478. if ( this.boundingBox !== null ) {
  8479. if ( _ray$2.intersectsBox( this.boundingBox ) === false ) return;
  8480. }
  8481. // test for intersections with geometry
  8482. this._computeIntersections( raycaster, intersects, _ray$2 );
  8483. }
  8484. getVertexPosition( index, target ) {
  8485. super.getVertexPosition( index, target );
  8486. this.applyBoneTransform( index, target );
  8487. return target;
  8488. }
  8489. bind( skeleton, bindMatrix ) {
  8490. this.skeleton = skeleton;
  8491. if ( bindMatrix === undefined ) {
  8492. this.updateMatrixWorld( true );
  8493. this.skeleton.calculateInverses();
  8494. bindMatrix = this.matrixWorld;
  8495. }
  8496. this.bindMatrix.copy( bindMatrix );
  8497. this.bindMatrixInverse.copy( bindMatrix ).invert();
  8498. }
  8499. pose() {
  8500. this.skeleton.pose();
  8501. }
  8502. normalizeSkinWeights() {
  8503. const vector = new Vector4();
  8504. const skinWeight = this.geometry.attributes.skinWeight;
  8505. for ( let i = 0, l = skinWeight.count; i < l; i ++ ) {
  8506. vector.fromBufferAttribute( skinWeight, i );
  8507. const scale = 1.0 / vector.manhattanLength();
  8508. if ( scale !== Infinity ) {
  8509. vector.multiplyScalar( scale );
  8510. } else {
  8511. vector.set( 1, 0, 0, 0 ); // do something reasonable
  8512. }
  8513. skinWeight.setXYZW( i, vector.x, vector.y, vector.z, vector.w );
  8514. }
  8515. }
  8516. updateMatrixWorld( force ) {
  8517. super.updateMatrixWorld( force );
  8518. if ( this.bindMode === AttachedBindMode ) {
  8519. this.bindMatrixInverse.copy( this.matrixWorld ).invert();
  8520. } else if ( this.bindMode === DetachedBindMode ) {
  8521. this.bindMatrixInverse.copy( this.bindMatrix ).invert();
  8522. } else {
  8523. console.warn( 'THREE.SkinnedMesh: Unrecognized bindMode: ' + this.bindMode );
  8524. }
  8525. }
  8526. applyBoneTransform( index, vector ) {
  8527. const skeleton = this.skeleton;
  8528. const geometry = this.geometry;
  8529. _skinIndex.fromBufferAttribute( geometry.attributes.skinIndex, index );
  8530. _skinWeight.fromBufferAttribute( geometry.attributes.skinWeight, index );
  8531. _basePosition.copy( vector ).applyMatrix4( this.bindMatrix );
  8532. vector.set( 0, 0, 0 );
  8533. for ( let i = 0; i < 4; i ++ ) {
  8534. const weight = _skinWeight.getComponent( i );
  8535. if ( weight !== 0 ) {
  8536. const boneIndex = _skinIndex.getComponent( i );
  8537. _matrix4.multiplyMatrices( skeleton.bones[ boneIndex ].matrixWorld, skeleton.boneInverses[ boneIndex ] );
  8538. vector.addScaledVector( _vector3.copy( _basePosition ).applyMatrix4( _matrix4 ), weight );
  8539. }
  8540. }
  8541. return vector.applyMatrix4( this.bindMatrixInverse );
  8542. }
  8543. }
  8544. class Bone extends Object3D {
  8545. constructor() {
  8546. super();
  8547. this.isBone = true;
  8548. this.type = 'Bone';
  8549. }
  8550. }
  8551. class DataTexture extends Texture {
  8552. constructor( data = null, width = 1, height = 1, format, type, mapping, wrapS, wrapT, magFilter = NearestFilter, minFilter = NearestFilter, anisotropy, colorSpace ) {
  8553. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace );
  8554. this.isDataTexture = true;
  8555. this.image = { data: data, width: width, height: height };
  8556. this.generateMipmaps = false;
  8557. this.flipY = false;
  8558. this.unpackAlignment = 1;
  8559. }
  8560. }
  8561. const _offsetMatrix = /*@__PURE__*/ new Matrix4();
  8562. const _identityMatrix$1 = /*@__PURE__*/ new Matrix4();
  8563. class Skeleton {
  8564. constructor( bones = [], boneInverses = [] ) {
  8565. this.uuid = generateUUID();
  8566. this.bones = bones.slice( 0 );
  8567. this.boneInverses = boneInverses;
  8568. this.boneMatrices = null;
  8569. this.boneTexture = null;
  8570. this.init();
  8571. }
  8572. init() {
  8573. const bones = this.bones;
  8574. const boneInverses = this.boneInverses;
  8575. this.boneMatrices = new Float32Array( bones.length * 16 );
  8576. // calculate inverse bone matrices if necessary
  8577. if ( boneInverses.length === 0 ) {
  8578. this.calculateInverses();
  8579. } else {
  8580. // handle special case
  8581. if ( bones.length !== boneInverses.length ) {
  8582. console.warn( 'THREE.Skeleton: Number of inverse bone matrices does not match amount of bones.' );
  8583. this.boneInverses = [];
  8584. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  8585. this.boneInverses.push( new Matrix4() );
  8586. }
  8587. }
  8588. }
  8589. }
  8590. calculateInverses() {
  8591. this.boneInverses.length = 0;
  8592. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  8593. const inverse = new Matrix4();
  8594. if ( this.bones[ i ] ) {
  8595. inverse.copy( this.bones[ i ].matrixWorld ).invert();
  8596. }
  8597. this.boneInverses.push( inverse );
  8598. }
  8599. }
  8600. pose() {
  8601. // recover the bind-time world matrices
  8602. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  8603. const bone = this.bones[ i ];
  8604. if ( bone ) {
  8605. bone.matrixWorld.copy( this.boneInverses[ i ] ).invert();
  8606. }
  8607. }
  8608. // compute the local matrices, positions, rotations and scales
  8609. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  8610. const bone = this.bones[ i ];
  8611. if ( bone ) {
  8612. if ( bone.parent && bone.parent.isBone ) {
  8613. bone.matrix.copy( bone.parent.matrixWorld ).invert();
  8614. bone.matrix.multiply( bone.matrixWorld );
  8615. } else {
  8616. bone.matrix.copy( bone.matrixWorld );
  8617. }
  8618. bone.matrix.decompose( bone.position, bone.quaternion, bone.scale );
  8619. }
  8620. }
  8621. }
  8622. update() {
  8623. const bones = this.bones;
  8624. const boneInverses = this.boneInverses;
  8625. const boneMatrices = this.boneMatrices;
  8626. const boneTexture = this.boneTexture;
  8627. // flatten bone matrices to array
  8628. for ( let i = 0, il = bones.length; i < il; i ++ ) {
  8629. // compute the offset between the current and the original transform
  8630. const matrix = bones[ i ] ? bones[ i ].matrixWorld : _identityMatrix$1;
  8631. _offsetMatrix.multiplyMatrices( matrix, boneInverses[ i ] );
  8632. _offsetMatrix.toArray( boneMatrices, i * 16 );
  8633. }
  8634. if ( boneTexture !== null ) {
  8635. boneTexture.needsUpdate = true;
  8636. }
  8637. }
  8638. clone() {
  8639. return new Skeleton( this.bones, this.boneInverses );
  8640. }
  8641. computeBoneTexture() {
  8642. // layout (1 matrix = 4 pixels)
  8643. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  8644. // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8)
  8645. // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16)
  8646. // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32)
  8647. // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64)
  8648. let size = Math.sqrt( this.bones.length * 4 ); // 4 pixels needed for 1 matrix
  8649. size = Math.ceil( size / 4 ) * 4;
  8650. size = Math.max( size, 4 );
  8651. const boneMatrices = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel
  8652. boneMatrices.set( this.boneMatrices ); // copy current values
  8653. const boneTexture = new DataTexture( boneMatrices, size, size, RGBAFormat, FloatType );
  8654. boneTexture.needsUpdate = true;
  8655. this.boneMatrices = boneMatrices;
  8656. this.boneTexture = boneTexture;
  8657. return this;
  8658. }
  8659. getBoneByName( name ) {
  8660. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  8661. const bone = this.bones[ i ];
  8662. if ( bone.name === name ) {
  8663. return bone;
  8664. }
  8665. }
  8666. return undefined;
  8667. }
  8668. dispose( ) {
  8669. if ( this.boneTexture !== null ) {
  8670. this.boneTexture.dispose();
  8671. this.boneTexture = null;
  8672. }
  8673. }
  8674. fromJSON( json, bones ) {
  8675. this.uuid = json.uuid;
  8676. for ( let i = 0, l = json.bones.length; i < l; i ++ ) {
  8677. const uuid = json.bones[ i ];
  8678. let bone = bones[ uuid ];
  8679. if ( bone === undefined ) {
  8680. console.warn( 'THREE.Skeleton: No bone found with UUID:', uuid );
  8681. bone = new Bone();
  8682. }
  8683. this.bones.push( bone );
  8684. this.boneInverses.push( new Matrix4().fromArray( json.boneInverses[ i ] ) );
  8685. }
  8686. this.init();
  8687. return this;
  8688. }
  8689. toJSON() {
  8690. const data = {
  8691. metadata: {
  8692. version: 4.6,
  8693. type: 'Skeleton',
  8694. generator: 'Skeleton.toJSON'
  8695. },
  8696. bones: [],
  8697. boneInverses: []
  8698. };
  8699. data.uuid = this.uuid;
  8700. const bones = this.bones;
  8701. const boneInverses = this.boneInverses;
  8702. for ( let i = 0, l = bones.length; i < l; i ++ ) {
  8703. const bone = bones[ i ];
  8704. data.bones.push( bone.uuid );
  8705. const boneInverse = boneInverses[ i ];
  8706. data.boneInverses.push( boneInverse.toArray() );
  8707. }
  8708. return data;
  8709. }
  8710. }
  8711. class InstancedBufferAttribute extends BufferAttribute {
  8712. constructor( array, itemSize, normalized, meshPerAttribute = 1 ) {
  8713. super( array, itemSize, normalized );
  8714. this.isInstancedBufferAttribute = true;
  8715. this.meshPerAttribute = meshPerAttribute;
  8716. }
  8717. copy( source ) {
  8718. super.copy( source );
  8719. this.meshPerAttribute = source.meshPerAttribute;
  8720. return this;
  8721. }
  8722. toJSON() {
  8723. const data = super.toJSON();
  8724. data.meshPerAttribute = this.meshPerAttribute;
  8725. data.isInstancedBufferAttribute = true;
  8726. return data;
  8727. }
  8728. }
  8729. const _instanceLocalMatrix = /*@__PURE__*/ new Matrix4();
  8730. const _instanceWorldMatrix = /*@__PURE__*/ new Matrix4();
  8731. const _instanceIntersects = [];
  8732. const _box3 = /*@__PURE__*/ new Box3();
  8733. const _identity = /*@__PURE__*/ new Matrix4();
  8734. const _mesh$1 = /*@__PURE__*/ new Mesh();
  8735. const _sphere$4 = /*@__PURE__*/ new Sphere();
  8736. class InstancedMesh extends Mesh {
  8737. constructor( geometry, material, count ) {
  8738. super( geometry, material );
  8739. this.isInstancedMesh = true;
  8740. this.instanceMatrix = new InstancedBufferAttribute( new Float32Array( count * 16 ), 16 );
  8741. this.instanceColor = null;
  8742. this.morphTexture = null;
  8743. this.count = count;
  8744. this.boundingBox = null;
  8745. this.boundingSphere = null;
  8746. for ( let i = 0; i < count; i ++ ) {
  8747. this.setMatrixAt( i, _identity );
  8748. }
  8749. }
  8750. computeBoundingBox() {
  8751. const geometry = this.geometry;
  8752. const count = this.count;
  8753. if ( this.boundingBox === null ) {
  8754. this.boundingBox = new Box3();
  8755. }
  8756. if ( geometry.boundingBox === null ) {
  8757. geometry.computeBoundingBox();
  8758. }
  8759. this.boundingBox.makeEmpty();
  8760. for ( let i = 0; i < count; i ++ ) {
  8761. this.getMatrixAt( i, _instanceLocalMatrix );
  8762. _box3.copy( geometry.boundingBox ).applyMatrix4( _instanceLocalMatrix );
  8763. this.boundingBox.union( _box3 );
  8764. }
  8765. }
  8766. computeBoundingSphere() {
  8767. const geometry = this.geometry;
  8768. const count = this.count;
  8769. if ( this.boundingSphere === null ) {
  8770. this.boundingSphere = new Sphere();
  8771. }
  8772. if ( geometry.boundingSphere === null ) {
  8773. geometry.computeBoundingSphere();
  8774. }
  8775. this.boundingSphere.makeEmpty();
  8776. for ( let i = 0; i < count; i ++ ) {
  8777. this.getMatrixAt( i, _instanceLocalMatrix );
  8778. _sphere$4.copy( geometry.boundingSphere ).applyMatrix4( _instanceLocalMatrix );
  8779. this.boundingSphere.union( _sphere$4 );
  8780. }
  8781. }
  8782. copy( source, recursive ) {
  8783. super.copy( source, recursive );
  8784. this.instanceMatrix.copy( source.instanceMatrix );
  8785. if ( source.morphTexture !== null ) this.morphTexture = source.morphTexture.clone();
  8786. if ( source.instanceColor !== null ) this.instanceColor = source.instanceColor.clone();
  8787. this.count = source.count;
  8788. if ( source.boundingBox !== null ) this.boundingBox = source.boundingBox.clone();
  8789. if ( source.boundingSphere !== null ) this.boundingSphere = source.boundingSphere.clone();
  8790. return this;
  8791. }
  8792. getColorAt( index, color ) {
  8793. color.fromArray( this.instanceColor.array, index * 3 );
  8794. }
  8795. getMatrixAt( index, matrix ) {
  8796. matrix.fromArray( this.instanceMatrix.array, index * 16 );
  8797. }
  8798. getMorphAt( index, object ) {
  8799. const objectInfluences = object.morphTargetInfluences;
  8800. const array = this.morphTexture.source.data.data;
  8801. const len = objectInfluences.length + 1; // All influences + the baseInfluenceSum
  8802. const dataIndex = index * len + 1; // Skip the baseInfluenceSum at the beginning
  8803. for ( let i = 0; i < objectInfluences.length; i ++ ) {
  8804. objectInfluences[ i ] = array[ dataIndex + i ];
  8805. }
  8806. }
  8807. raycast( raycaster, intersects ) {
  8808. const matrixWorld = this.matrixWorld;
  8809. const raycastTimes = this.count;
  8810. _mesh$1.geometry = this.geometry;
  8811. _mesh$1.material = this.material;
  8812. if ( _mesh$1.material === undefined ) return;
  8813. // test with bounding sphere first
  8814. if ( this.boundingSphere === null ) this.computeBoundingSphere();
  8815. _sphere$4.copy( this.boundingSphere );
  8816. _sphere$4.applyMatrix4( matrixWorld );
  8817. if ( raycaster.ray.intersectsSphere( _sphere$4 ) === false ) return;
  8818. // now test each instance
  8819. for ( let instanceId = 0; instanceId < raycastTimes; instanceId ++ ) {
  8820. // calculate the world matrix for each instance
  8821. this.getMatrixAt( instanceId, _instanceLocalMatrix );
  8822. _instanceWorldMatrix.multiplyMatrices( matrixWorld, _instanceLocalMatrix );
  8823. // the mesh represents this single instance
  8824. _mesh$1.matrixWorld = _instanceWorldMatrix;
  8825. _mesh$1.raycast( raycaster, _instanceIntersects );
  8826. // process the result of raycast
  8827. for ( let i = 0, l = _instanceIntersects.length; i < l; i ++ ) {
  8828. const intersect = _instanceIntersects[ i ];
  8829. intersect.instanceId = instanceId;
  8830. intersect.object = this;
  8831. intersects.push( intersect );
  8832. }
  8833. _instanceIntersects.length = 0;
  8834. }
  8835. }
  8836. setColorAt( index, color ) {
  8837. if ( this.instanceColor === null ) {
  8838. this.instanceColor = new InstancedBufferAttribute( new Float32Array( this.instanceMatrix.count * 3 ).fill( 1 ), 3 );
  8839. }
  8840. color.toArray( this.instanceColor.array, index * 3 );
  8841. }
  8842. setMatrixAt( index, matrix ) {
  8843. matrix.toArray( this.instanceMatrix.array, index * 16 );
  8844. }
  8845. setMorphAt( index, object ) {
  8846. const objectInfluences = object.morphTargetInfluences;
  8847. const len = objectInfluences.length + 1; // morphBaseInfluence + all influences
  8848. if ( this.morphTexture === null ) {
  8849. this.morphTexture = new DataTexture( new Float32Array( len * this.count ), len, this.count, RedFormat, FloatType );
  8850. }
  8851. const array = this.morphTexture.source.data.data;
  8852. let morphInfluencesSum = 0;
  8853. for ( let i = 0; i < objectInfluences.length; i ++ ) {
  8854. morphInfluencesSum += objectInfluences[ i ];
  8855. }
  8856. const morphBaseInfluence = this.geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
  8857. const dataIndex = len * index;
  8858. array[ dataIndex ] = morphBaseInfluence;
  8859. array.set( objectInfluences, dataIndex + 1 );
  8860. }
  8861. updateMorphTargets() {
  8862. }
  8863. dispose() {
  8864. this.dispatchEvent( { type: 'dispose' } );
  8865. if ( this.morphTexture !== null ) {
  8866. this.morphTexture.dispose();
  8867. this.morphTexture = null;
  8868. }
  8869. return this;
  8870. }
  8871. }
  8872. const _vector1 = /*@__PURE__*/ new Vector3();
  8873. const _vector2 = /*@__PURE__*/ new Vector3();
  8874. const _normalMatrix = /*@__PURE__*/ new Matrix3();
  8875. class Plane {
  8876. constructor( normal = new Vector3( 1, 0, 0 ), constant = 0 ) {
  8877. this.isPlane = true;
  8878. // normal is assumed to be normalized
  8879. this.normal = normal;
  8880. this.constant = constant;
  8881. }
  8882. set( normal, constant ) {
  8883. this.normal.copy( normal );
  8884. this.constant = constant;
  8885. return this;
  8886. }
  8887. setComponents( x, y, z, w ) {
  8888. this.normal.set( x, y, z );
  8889. this.constant = w;
  8890. return this;
  8891. }
  8892. setFromNormalAndCoplanarPoint( normal, point ) {
  8893. this.normal.copy( normal );
  8894. this.constant = - point.dot( this.normal );
  8895. return this;
  8896. }
  8897. setFromCoplanarPoints( a, b, c ) {
  8898. const normal = _vector1.subVectors( c, b ).cross( _vector2.subVectors( a, b ) ).normalize();
  8899. // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  8900. this.setFromNormalAndCoplanarPoint( normal, a );
  8901. return this;
  8902. }
  8903. copy( plane ) {
  8904. this.normal.copy( plane.normal );
  8905. this.constant = plane.constant;
  8906. return this;
  8907. }
  8908. normalize() {
  8909. // Note: will lead to a divide by zero if the plane is invalid.
  8910. const inverseNormalLength = 1.0 / this.normal.length();
  8911. this.normal.multiplyScalar( inverseNormalLength );
  8912. this.constant *= inverseNormalLength;
  8913. return this;
  8914. }
  8915. negate() {
  8916. this.constant *= - 1;
  8917. this.normal.negate();
  8918. return this;
  8919. }
  8920. distanceToPoint( point ) {
  8921. return this.normal.dot( point ) + this.constant;
  8922. }
  8923. distanceToSphere( sphere ) {
  8924. return this.distanceToPoint( sphere.center ) - sphere.radius;
  8925. }
  8926. projectPoint( point, target ) {
  8927. return target.copy( point ).addScaledVector( this.normal, - this.distanceToPoint( point ) );
  8928. }
  8929. intersectLine( line, target ) {
  8930. const direction = line.delta( _vector1 );
  8931. const denominator = this.normal.dot( direction );
  8932. if ( denominator === 0 ) {
  8933. // line is coplanar, return origin
  8934. if ( this.distanceToPoint( line.start ) === 0 ) {
  8935. return target.copy( line.start );
  8936. }
  8937. // Unsure if this is the correct method to handle this case.
  8938. return null;
  8939. }
  8940. const t = - ( line.start.dot( this.normal ) + this.constant ) / denominator;
  8941. if ( t < 0 || t > 1 ) {
  8942. return null;
  8943. }
  8944. return target.copy( line.start ).addScaledVector( direction, t );
  8945. }
  8946. intersectsLine( line ) {
  8947. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  8948. const startSign = this.distanceToPoint( line.start );
  8949. const endSign = this.distanceToPoint( line.end );
  8950. return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 );
  8951. }
  8952. intersectsBox( box ) {
  8953. return box.intersectsPlane( this );
  8954. }
  8955. intersectsSphere( sphere ) {
  8956. return sphere.intersectsPlane( this );
  8957. }
  8958. coplanarPoint( target ) {
  8959. return target.copy( this.normal ).multiplyScalar( - this.constant );
  8960. }
  8961. applyMatrix4( matrix, optionalNormalMatrix ) {
  8962. const normalMatrix = optionalNormalMatrix || _normalMatrix.getNormalMatrix( matrix );
  8963. const referencePoint = this.coplanarPoint( _vector1 ).applyMatrix4( matrix );
  8964. const normal = this.normal.applyMatrix3( normalMatrix ).normalize();
  8965. this.constant = - referencePoint.dot( normal );
  8966. return this;
  8967. }
  8968. translate( offset ) {
  8969. this.constant -= offset.dot( this.normal );
  8970. return this;
  8971. }
  8972. equals( plane ) {
  8973. return plane.normal.equals( this.normal ) && ( plane.constant === this.constant );
  8974. }
  8975. clone() {
  8976. return new this.constructor().copy( this );
  8977. }
  8978. }
  8979. const _sphere$3 = /*@__PURE__*/ new Sphere();
  8980. const _vector$6 = /*@__PURE__*/ new Vector3();
  8981. class Frustum {
  8982. constructor( p0 = new Plane(), p1 = new Plane(), p2 = new Plane(), p3 = new Plane(), p4 = new Plane(), p5 = new Plane() ) {
  8983. this.planes = [ p0, p1, p2, p3, p4, p5 ];
  8984. }
  8985. set( p0, p1, p2, p3, p4, p5 ) {
  8986. const planes = this.planes;
  8987. planes[ 0 ].copy( p0 );
  8988. planes[ 1 ].copy( p1 );
  8989. planes[ 2 ].copy( p2 );
  8990. planes[ 3 ].copy( p3 );
  8991. planes[ 4 ].copy( p4 );
  8992. planes[ 5 ].copy( p5 );
  8993. return this;
  8994. }
  8995. copy( frustum ) {
  8996. const planes = this.planes;
  8997. for ( let i = 0; i < 6; i ++ ) {
  8998. planes[ i ].copy( frustum.planes[ i ] );
  8999. }
  9000. return this;
  9001. }
  9002. setFromProjectionMatrix( m, coordinateSystem = WebGLCoordinateSystem ) {
  9003. const planes = this.planes;
  9004. const me = m.elements;
  9005. const me0 = me[ 0 ], me1 = me[ 1 ], me2 = me[ 2 ], me3 = me[ 3 ];
  9006. const me4 = me[ 4 ], me5 = me[ 5 ], me6 = me[ 6 ], me7 = me[ 7 ];
  9007. const me8 = me[ 8 ], me9 = me[ 9 ], me10 = me[ 10 ], me11 = me[ 11 ];
  9008. const me12 = me[ 12 ], me13 = me[ 13 ], me14 = me[ 14 ], me15 = me[ 15 ];
  9009. planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize();
  9010. planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize();
  9011. planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize();
  9012. planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize();
  9013. planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize();
  9014. if ( coordinateSystem === WebGLCoordinateSystem ) {
  9015. planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize();
  9016. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  9017. planes[ 5 ].setComponents( me2, me6, me10, me14 ).normalize();
  9018. } else {
  9019. throw new Error( 'THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: ' + coordinateSystem );
  9020. }
  9021. return this;
  9022. }
  9023. intersectsObject( object ) {
  9024. if ( object.boundingSphere !== undefined ) {
  9025. if ( object.boundingSphere === null ) object.computeBoundingSphere();
  9026. _sphere$3.copy( object.boundingSphere ).applyMatrix4( object.matrixWorld );
  9027. } else {
  9028. const geometry = object.geometry;
  9029. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  9030. _sphere$3.copy( geometry.boundingSphere ).applyMatrix4( object.matrixWorld );
  9031. }
  9032. return this.intersectsSphere( _sphere$3 );
  9033. }
  9034. intersectsSprite( sprite ) {
  9035. _sphere$3.center.set( 0, 0, 0 );
  9036. _sphere$3.radius = 0.7071067811865476;
  9037. _sphere$3.applyMatrix4( sprite.matrixWorld );
  9038. return this.intersectsSphere( _sphere$3 );
  9039. }
  9040. intersectsSphere( sphere ) {
  9041. const planes = this.planes;
  9042. const center = sphere.center;
  9043. const negRadius = - sphere.radius;
  9044. for ( let i = 0; i < 6; i ++ ) {
  9045. const distance = planes[ i ].distanceToPoint( center );
  9046. if ( distance < negRadius ) {
  9047. return false;
  9048. }
  9049. }
  9050. return true;
  9051. }
  9052. intersectsBox( box ) {
  9053. const planes = this.planes;
  9054. for ( let i = 0; i < 6; i ++ ) {
  9055. const plane = planes[ i ];
  9056. // corner at max distance
  9057. _vector$6.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  9058. _vector$6.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  9059. _vector$6.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  9060. if ( plane.distanceToPoint( _vector$6 ) < 0 ) {
  9061. return false;
  9062. }
  9063. }
  9064. return true;
  9065. }
  9066. containsPoint( point ) {
  9067. const planes = this.planes;
  9068. for ( let i = 0; i < 6; i ++ ) {
  9069. if ( planes[ i ].distanceToPoint( point ) < 0 ) {
  9070. return false;
  9071. }
  9072. }
  9073. return true;
  9074. }
  9075. clone() {
  9076. return new this.constructor().copy( this );
  9077. }
  9078. }
  9079. function ascIdSort( a, b ) {
  9080. return a - b;
  9081. }
  9082. function sortOpaque( a, b ) {
  9083. return a.z - b.z;
  9084. }
  9085. function sortTransparent( a, b ) {
  9086. return b.z - a.z;
  9087. }
  9088. class MultiDrawRenderList {
  9089. constructor() {
  9090. this.index = 0;
  9091. this.pool = [];
  9092. this.list = [];
  9093. }
  9094. push( drawRange, z, index ) {
  9095. const pool = this.pool;
  9096. const list = this.list;
  9097. if ( this.index >= pool.length ) {
  9098. pool.push( {
  9099. start: - 1,
  9100. count: - 1,
  9101. z: - 1,
  9102. index: - 1,
  9103. } );
  9104. }
  9105. const item = pool[ this.index ];
  9106. list.push( item );
  9107. this.index ++;
  9108. item.start = drawRange.start;
  9109. item.count = drawRange.count;
  9110. item.z = z;
  9111. item.index = index;
  9112. }
  9113. reset() {
  9114. this.list.length = 0;
  9115. this.index = 0;
  9116. }
  9117. }
  9118. const _matrix$1 = /*@__PURE__*/ new Matrix4();
  9119. const _invMatrixWorld = /*@__PURE__*/ new Matrix4();
  9120. const _identityMatrix = /*@__PURE__*/ new Matrix4();
  9121. const _whiteColor = /*@__PURE__*/ new Color( 1, 1, 1 );
  9122. const _projScreenMatrix$3 = /*@__PURE__*/ new Matrix4();
  9123. const _frustum$1 = /*@__PURE__*/ new Frustum();
  9124. const _box$1 = /*@__PURE__*/ new Box3();
  9125. const _sphere$2 = /*@__PURE__*/ new Sphere();
  9126. const _vector$5 = /*@__PURE__*/ new Vector3();
  9127. const _forward = /*@__PURE__*/ new Vector3();
  9128. const _temp = /*@__PURE__*/ new Vector3();
  9129. const _renderList = /*@__PURE__*/ new MultiDrawRenderList();
  9130. const _mesh = /*@__PURE__*/ new Mesh();
  9131. const _batchIntersects = [];
  9132. // @TODO: SkinnedMesh support?
  9133. // @TODO: geometry.groups support?
  9134. // @TODO: geometry.drawRange support?
  9135. // @TODO: geometry.morphAttributes support?
  9136. // @TODO: Support uniform parameter per geometry
  9137. // @TODO: Add an "optimize" function to pack geometry and remove data gaps
  9138. // copies data from attribute "src" into "target" starting at "targetOffset"
  9139. function copyAttributeData( src, target, targetOffset = 0 ) {
  9140. const itemSize = target.itemSize;
  9141. if ( src.isInterleavedBufferAttribute || src.array.constructor !== target.array.constructor ) {
  9142. // use the component getters and setters if the array data cannot
  9143. // be copied directly
  9144. const vertexCount = src.count;
  9145. for ( let i = 0; i < vertexCount; i ++ ) {
  9146. for ( let c = 0; c < itemSize; c ++ ) {
  9147. target.setComponent( i + targetOffset, c, src.getComponent( i, c ) );
  9148. }
  9149. }
  9150. } else {
  9151. // faster copy approach using typed array set function
  9152. target.array.set( src.array, targetOffset * itemSize );
  9153. }
  9154. target.needsUpdate = true;
  9155. }
  9156. // safely copies array contents to a potentially smaller array
  9157. function copyArrayContents( src, target ) {
  9158. const len = Math.min( src.length, target.length );
  9159. target.set( new src.constructor( src.buffer, 0, len ) );
  9160. }
  9161. class BatchedMesh extends Mesh {
  9162. get maxInstanceCount() {
  9163. return this._maxInstanceCount;
  9164. }
  9165. constructor( maxInstanceCount, maxVertexCount, maxIndexCount = maxVertexCount * 2, material ) {
  9166. super( new BufferGeometry(), material );
  9167. this.isBatchedMesh = true;
  9168. this.perObjectFrustumCulled = true;
  9169. this.sortObjects = true;
  9170. this.boundingBox = null;
  9171. this.boundingSphere = null;
  9172. this.customSort = null;
  9173. // stores visible, active, and geometry id per object
  9174. this._drawInfo = [];
  9175. // instance, geometry ids that have been set as inactive, and are available to be overwritten
  9176. this._availableInstanceIds = [];
  9177. this._availableGeometryIds = [];
  9178. // geometry information
  9179. this._drawRanges = [];
  9180. this._reservedRanges = [];
  9181. this._bounds = [];
  9182. this._maxInstanceCount = maxInstanceCount;
  9183. this._maxVertexCount = maxVertexCount;
  9184. this._maxIndexCount = maxIndexCount;
  9185. this._geometryInitialized = false;
  9186. this._geometryCount = 0;
  9187. this._multiDrawCounts = new Int32Array( maxInstanceCount );
  9188. this._multiDrawStarts = new Int32Array( maxInstanceCount );
  9189. this._multiDrawCount = 0;
  9190. this._multiDrawInstances = null;
  9191. this._visibilityChanged = true;
  9192. // Local matrix per geometry by using data texture
  9193. this._matricesTexture = null;
  9194. this._indirectTexture = null;
  9195. this._colorsTexture = null;
  9196. this._initMatricesTexture();
  9197. this._initIndirectTexture();
  9198. }
  9199. _initMatricesTexture() {
  9200. // layout (1 matrix = 4 pixels)
  9201. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  9202. // with 8x8 pixel texture max 16 matrices * 4 pixels = (8 * 8)
  9203. // 16x16 pixel texture max 64 matrices * 4 pixels = (16 * 16)
  9204. // 32x32 pixel texture max 256 matrices * 4 pixels = (32 * 32)
  9205. // 64x64 pixel texture max 1024 matrices * 4 pixels = (64 * 64)
  9206. let size = Math.sqrt( this._maxInstanceCount * 4 ); // 4 pixels needed for 1 matrix
  9207. size = Math.ceil( size / 4 ) * 4;
  9208. size = Math.max( size, 4 );
  9209. const matricesArray = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel
  9210. const matricesTexture = new DataTexture( matricesArray, size, size, RGBAFormat, FloatType );
  9211. this._matricesTexture = matricesTexture;
  9212. }
  9213. _initIndirectTexture() {
  9214. let size = Math.sqrt( this._maxInstanceCount );
  9215. size = Math.ceil( size );
  9216. const indirectArray = new Uint32Array( size * size );
  9217. const indirectTexture = new DataTexture( indirectArray, size, size, RedIntegerFormat, UnsignedIntType );
  9218. this._indirectTexture = indirectTexture;
  9219. }
  9220. _initColorsTexture() {
  9221. let size = Math.sqrt( this._maxInstanceCount );
  9222. size = Math.ceil( size );
  9223. // 4 floats per RGBA pixel initialized to white
  9224. const colorsArray = new Float32Array( size * size * 4 ).fill( 1 );
  9225. const colorsTexture = new DataTexture( colorsArray, size, size, RGBAFormat, FloatType );
  9226. colorsTexture.colorSpace = ColorManagement.workingColorSpace;
  9227. this._colorsTexture = colorsTexture;
  9228. }
  9229. _initializeGeometry( reference ) {
  9230. const geometry = this.geometry;
  9231. const maxVertexCount = this._maxVertexCount;
  9232. const maxIndexCount = this._maxIndexCount;
  9233. if ( this._geometryInitialized === false ) {
  9234. for ( const attributeName in reference.attributes ) {
  9235. const srcAttribute = reference.getAttribute( attributeName );
  9236. const { array, itemSize, normalized } = srcAttribute;
  9237. const dstArray = new array.constructor( maxVertexCount * itemSize );
  9238. const dstAttribute = new BufferAttribute( dstArray, itemSize, normalized );
  9239. geometry.setAttribute( attributeName, dstAttribute );
  9240. }
  9241. if ( reference.getIndex() !== null ) {
  9242. // Reserve last u16 index for primitive restart.
  9243. const indexArray = maxVertexCount > 65535
  9244. ? new Uint32Array( maxIndexCount )
  9245. : new Uint16Array( maxIndexCount );
  9246. geometry.setIndex( new BufferAttribute( indexArray, 1 ) );
  9247. }
  9248. this._geometryInitialized = true;
  9249. }
  9250. }
  9251. // Make sure the geometry is compatible with the existing combined geometry attributes
  9252. _validateGeometry( geometry ) {
  9253. // check to ensure the geometries are using consistent attributes and indices
  9254. const batchGeometry = this.geometry;
  9255. if ( Boolean( geometry.getIndex() ) !== Boolean( batchGeometry.getIndex() ) ) {
  9256. throw new Error( 'BatchedMesh: All geometries must consistently have "index".' );
  9257. }
  9258. for ( const attributeName in batchGeometry.attributes ) {
  9259. if ( ! geometry.hasAttribute( attributeName ) ) {
  9260. throw new Error( `BatchedMesh: Added geometry missing "${ attributeName }". All geometries must have consistent attributes.` );
  9261. }
  9262. const srcAttribute = geometry.getAttribute( attributeName );
  9263. const dstAttribute = batchGeometry.getAttribute( attributeName );
  9264. if ( srcAttribute.itemSize !== dstAttribute.itemSize || srcAttribute.normalized !== dstAttribute.normalized ) {
  9265. throw new Error( 'BatchedMesh: All attributes must have a consistent itemSize and normalized value.' );
  9266. }
  9267. }
  9268. }
  9269. setCustomSort( func ) {
  9270. this.customSort = func;
  9271. return this;
  9272. }
  9273. computeBoundingBox() {
  9274. if ( this.boundingBox === null ) {
  9275. this.boundingBox = new Box3();
  9276. }
  9277. const boundingBox = this.boundingBox;
  9278. const drawInfo = this._drawInfo;
  9279. boundingBox.makeEmpty();
  9280. for ( let i = 0, l = drawInfo.length; i < l; i ++ ) {
  9281. if ( drawInfo[ i ].active === false ) continue;
  9282. const geometryId = drawInfo[ i ].geometryIndex;
  9283. this.getMatrixAt( i, _matrix$1 );
  9284. this.getBoundingBoxAt( geometryId, _box$1 ).applyMatrix4( _matrix$1 );
  9285. boundingBox.union( _box$1 );
  9286. }
  9287. }
  9288. computeBoundingSphere() {
  9289. if ( this.boundingSphere === null ) {
  9290. this.boundingSphere = new Sphere();
  9291. }
  9292. const boundingSphere = this.boundingSphere;
  9293. const drawInfo = this._drawInfo;
  9294. boundingSphere.makeEmpty();
  9295. for ( let i = 0, l = drawInfo.length; i < l; i ++ ) {
  9296. if ( drawInfo[ i ].active === false ) continue;
  9297. const geometryId = drawInfo[ i ].geometryIndex;
  9298. this.getMatrixAt( i, _matrix$1 );
  9299. this.getBoundingSphereAt( geometryId, _sphere$2 ).applyMatrix4( _matrix$1 );
  9300. boundingSphere.union( _sphere$2 );
  9301. }
  9302. }
  9303. addInstance( geometryId ) {
  9304. const atCapacity = this._drawInfo.length >= this.maxInstanceCount;
  9305. // ensure we're not over geometry
  9306. if ( atCapacity && this._availableInstanceIds.length === 0 ) {
  9307. throw new Error( 'BatchedMesh: Maximum item count reached.' );
  9308. }
  9309. const instanceDrawInfo = {
  9310. visible: true,
  9311. active: true,
  9312. geometryIndex: geometryId,
  9313. };
  9314. let drawId = null;
  9315. // Prioritize using previously freed instance ids
  9316. if ( this._availableInstanceIds.length > 0 ) {
  9317. this._availableInstanceIds.sort( ascIdSort );
  9318. drawId = this._availableInstanceIds.shift();
  9319. this._drawInfo[ drawId ] = instanceDrawInfo;
  9320. } else {
  9321. drawId = this._drawInfo.length;
  9322. this._drawInfo.push( instanceDrawInfo );
  9323. }
  9324. const matricesTexture = this._matricesTexture;
  9325. const matricesArray = matricesTexture.image.data;
  9326. _identityMatrix.toArray( matricesArray, drawId * 16 );
  9327. matricesTexture.needsUpdate = true;
  9328. const colorsTexture = this._colorsTexture;
  9329. if ( colorsTexture ) {
  9330. _whiteColor.toArray( colorsTexture.image.data, drawId * 4 );
  9331. colorsTexture.needsUpdate = true;
  9332. }
  9333. return drawId;
  9334. }
  9335. addGeometry( geometry, vertexCount = - 1, indexCount = - 1 ) {
  9336. this._initializeGeometry( geometry );
  9337. this._validateGeometry( geometry );
  9338. // get the necessary range fo the geometry
  9339. const reservedRange = {
  9340. vertexStart: - 1,
  9341. vertexCount: - 1,
  9342. indexStart: - 1,
  9343. indexCount: - 1,
  9344. };
  9345. let lastRange = null;
  9346. const reservedRanges = this._reservedRanges;
  9347. const drawRanges = this._drawRanges;
  9348. const bounds = this._bounds;
  9349. if ( this._geometryCount !== 0 ) {
  9350. lastRange = reservedRanges[ reservedRanges.length - 1 ];
  9351. }
  9352. if ( vertexCount === - 1 ) {
  9353. reservedRange.vertexCount = geometry.getAttribute( 'position' ).count;
  9354. } else {
  9355. reservedRange.vertexCount = vertexCount;
  9356. }
  9357. if ( lastRange === null ) {
  9358. reservedRange.vertexStart = 0;
  9359. } else {
  9360. reservedRange.vertexStart = lastRange.vertexStart + lastRange.vertexCount;
  9361. }
  9362. const index = geometry.getIndex();
  9363. const hasIndex = index !== null;
  9364. if ( hasIndex ) {
  9365. if ( indexCount === - 1 ) {
  9366. reservedRange.indexCount = index.count;
  9367. } else {
  9368. reservedRange.indexCount = indexCount;
  9369. }
  9370. if ( lastRange === null ) {
  9371. reservedRange.indexStart = 0;
  9372. } else {
  9373. reservedRange.indexStart = lastRange.indexStart + lastRange.indexCount;
  9374. }
  9375. }
  9376. if (
  9377. reservedRange.indexStart !== - 1 &&
  9378. reservedRange.indexStart + reservedRange.indexCount > this._maxIndexCount ||
  9379. reservedRange.vertexStart + reservedRange.vertexCount > this._maxVertexCount
  9380. ) {
  9381. throw new Error( 'BatchedMesh: Reserved space request exceeds the maximum buffer size.' );
  9382. }
  9383. // add the reserved range and draw range objects
  9384. const drawRange = {
  9385. start: hasIndex ? reservedRange.indexStart : reservedRange.vertexStart,
  9386. count: - 1,
  9387. active: true,
  9388. };
  9389. const boundsInfo = {
  9390. boxInitialized: false,
  9391. box: new Box3(),
  9392. sphereInitialized: false,
  9393. sphere: new Sphere()
  9394. };
  9395. // update id
  9396. let geometryId;
  9397. if ( this._availableGeometryIds.length > 0 ) {
  9398. this._availableGeometryIds.sort( ascIdSort );
  9399. geometryId = this._availableGeometryIds.shift();
  9400. reservedRanges[ geometryId ] = reservedRange;
  9401. drawRanges[ geometryId ] = drawRange;
  9402. bounds[ geometryId ] = boundsInfo;
  9403. } else {
  9404. geometryId = this._geometryCount;
  9405. this._geometryCount ++;
  9406. reservedRanges.push( reservedRange );
  9407. drawRanges.push( drawRange );
  9408. bounds.push( boundsInfo );
  9409. }
  9410. // update the geometry
  9411. this.setGeometryAt( geometryId, geometry );
  9412. return geometryId;
  9413. }
  9414. setGeometryAt( geometryId, geometry ) {
  9415. if ( geometryId >= this._geometryCount ) {
  9416. throw new Error( 'BatchedMesh: Maximum geometry count reached.' );
  9417. }
  9418. this._validateGeometry( geometry );
  9419. const batchGeometry = this.geometry;
  9420. const hasIndex = batchGeometry.getIndex() !== null;
  9421. const dstIndex = batchGeometry.getIndex();
  9422. const srcIndex = geometry.getIndex();
  9423. const reservedRange = this._reservedRanges[ geometryId ];
  9424. if (
  9425. hasIndex &&
  9426. srcIndex.count > reservedRange.indexCount ||
  9427. geometry.attributes.position.count > reservedRange.vertexCount
  9428. ) {
  9429. throw new Error( 'BatchedMesh: Reserved space not large enough for provided geometry.' );
  9430. }
  9431. // copy geometry over
  9432. const vertexStart = reservedRange.vertexStart;
  9433. const vertexCount = reservedRange.vertexCount;
  9434. for ( const attributeName in batchGeometry.attributes ) {
  9435. // copy attribute data
  9436. const srcAttribute = geometry.getAttribute( attributeName );
  9437. const dstAttribute = batchGeometry.getAttribute( attributeName );
  9438. copyAttributeData( srcAttribute, dstAttribute, vertexStart );
  9439. // fill the rest in with zeroes
  9440. const itemSize = srcAttribute.itemSize;
  9441. for ( let i = srcAttribute.count, l = vertexCount; i < l; i ++ ) {
  9442. const index = vertexStart + i;
  9443. for ( let c = 0; c < itemSize; c ++ ) {
  9444. dstAttribute.setComponent( index, c, 0 );
  9445. }
  9446. }
  9447. dstAttribute.needsUpdate = true;
  9448. dstAttribute.addUpdateRange( vertexStart * itemSize, vertexCount * itemSize );
  9449. }
  9450. // copy index
  9451. if ( hasIndex ) {
  9452. const indexStart = reservedRange.indexStart;
  9453. // copy index data over
  9454. for ( let i = 0; i < srcIndex.count; i ++ ) {
  9455. dstIndex.setX( indexStart + i, vertexStart + srcIndex.getX( i ) );
  9456. }
  9457. // fill the rest in with zeroes
  9458. for ( let i = srcIndex.count, l = reservedRange.indexCount; i < l; i ++ ) {
  9459. dstIndex.setX( indexStart + i, vertexStart );
  9460. }
  9461. dstIndex.needsUpdate = true;
  9462. dstIndex.addUpdateRange( indexStart, reservedRange.indexCount );
  9463. }
  9464. // store the bounding boxes
  9465. const bound = this._bounds[ geometryId ];
  9466. if ( geometry.boundingBox !== null ) {
  9467. bound.box.copy( geometry.boundingBox );
  9468. bound.boxInitialized = true;
  9469. } else {
  9470. bound.boxInitialized = false;
  9471. }
  9472. if ( geometry.boundingSphere !== null ) {
  9473. bound.sphere.copy( geometry.boundingSphere );
  9474. bound.sphereInitialized = true;
  9475. } else {
  9476. bound.sphereInitialized = false;
  9477. }
  9478. // set drawRange count
  9479. const drawRange = this._drawRanges[ geometryId ];
  9480. const posAttr = geometry.getAttribute( 'position' );
  9481. drawRange.count = hasIndex ? srcIndex.count : posAttr.count;
  9482. this._visibilityChanged = true;
  9483. return geometryId;
  9484. }
  9485. deleteGeometry( geometryId ) {
  9486. const drawRanges = this._drawRanges;
  9487. if ( geometryId >= drawRanges.length || drawRanges[ geometryId ].active === false ) {
  9488. return this;
  9489. }
  9490. // delete any instances associated with this geometry
  9491. const drawInfo = this._drawInfo;
  9492. for ( let i = 0, l = drawInfo.length; i < l; i ++ ) {
  9493. if ( drawInfo[ i ].geometryIndex === geometryId ) {
  9494. this.deleteInstance( i );
  9495. }
  9496. }
  9497. drawRanges[ geometryId ].active = false;
  9498. this._availableGeometryIds.push( geometryId );
  9499. this._visibilityChanged = true;
  9500. return this;
  9501. }
  9502. deleteInstance( instanceId ) {
  9503. const drawInfo = this._drawInfo;
  9504. if ( instanceId >= drawInfo.length || drawInfo[ instanceId ].active === false ) {
  9505. return this;
  9506. }
  9507. drawInfo[ instanceId ].active = false;
  9508. this._availableInstanceIds.push( instanceId );
  9509. this._visibilityChanged = true;
  9510. return this;
  9511. }
  9512. optimize() {
  9513. // track the next indices to copy data to
  9514. let nextVertexStart = 0;
  9515. let nextIndexStart = 0;
  9516. // iterate over all geometry ranges
  9517. const drawRanges = this._drawRanges;
  9518. const reservedRanges = this._reservedRanges;
  9519. const geometry = this.geometry;
  9520. for ( let i = 0, l = drawRanges.length; i < l; i ++ ) {
  9521. // if a geometry range is inactive then don't copy anything
  9522. const drawRange = drawRanges[ i ];
  9523. const reservedRange = reservedRanges[ i ];
  9524. if ( drawRange.active === false ) {
  9525. continue;
  9526. }
  9527. // if a geometry contains an index buffer then shift it, as well
  9528. if ( geometry.index !== null && reservedRange.indexStart !== nextIndexStart ) {
  9529. const { indexStart, indexCount } = reservedRange;
  9530. const index = geometry.index;
  9531. const array = index.array;
  9532. // shift the index pointers based on how the vertex data will shift
  9533. // adjusting the index must happen first so the original vertex start value is available
  9534. const elementDelta = nextVertexStart - reservedRange.vertexStart;
  9535. for ( let j = indexStart; j < indexStart + indexCount; j ++ ) {
  9536. array[ j ] = array[ j ] + elementDelta;
  9537. }
  9538. index.array.copyWithin( nextIndexStart, indexStart, indexStart + indexCount );
  9539. index.addUpdateRange( nextIndexStart, indexCount );
  9540. reservedRange.indexStart = nextIndexStart;
  9541. nextIndexStart += reservedRange.indexCount;
  9542. }
  9543. // if a geometry needs to be moved then copy attribute data to overwrite unused space
  9544. if ( reservedRange.vertexStart !== nextVertexStart ) {
  9545. const { vertexStart, vertexCount } = reservedRange;
  9546. const attributes = geometry.attributes;
  9547. for ( const key in attributes ) {
  9548. const attribute = attributes[ key ];
  9549. const { array, itemSize } = attribute;
  9550. array.copyWithin( nextVertexStart * itemSize, vertexStart * itemSize, ( vertexStart + vertexCount ) * itemSize );
  9551. attribute.addUpdateRange( nextVertexStart * itemSize, vertexCount * itemSize );
  9552. }
  9553. reservedRange.vertexStart = nextVertexStart;
  9554. nextVertexStart += reservedRange.vertexCount;
  9555. }
  9556. drawRange.start = geometry.index ? reservedRange.indexStart : reservedRange.vertexStart;
  9557. }
  9558. return this;
  9559. }
  9560. // get bounding box and compute it if it doesn't exist
  9561. getBoundingBoxAt( geometryId, target ) {
  9562. if ( geometryId >= this._geometryCount ) {
  9563. return null;
  9564. }
  9565. // compute bounding box
  9566. const bound = this._bounds[ geometryId ];
  9567. const box = bound.box;
  9568. const geometry = this.geometry;
  9569. if ( bound.boxInitialized === false ) {
  9570. box.makeEmpty();
  9571. const index = geometry.index;
  9572. const position = geometry.attributes.position;
  9573. const drawRange = this._drawRanges[ geometryId ];
  9574. for ( let i = drawRange.start, l = drawRange.start + drawRange.count; i < l; i ++ ) {
  9575. let iv = i;
  9576. if ( index ) {
  9577. iv = index.getX( iv );
  9578. }
  9579. box.expandByPoint( _vector$5.fromBufferAttribute( position, iv ) );
  9580. }
  9581. bound.boxInitialized = true;
  9582. }
  9583. target.copy( box );
  9584. return target;
  9585. }
  9586. // get bounding sphere and compute it if it doesn't exist
  9587. getBoundingSphereAt( geometryId, target ) {
  9588. if ( geometryId >= this._geometryCount ) {
  9589. return null;
  9590. }
  9591. // compute bounding sphere
  9592. const bound = this._bounds[ geometryId ];
  9593. const sphere = bound.sphere;
  9594. const geometry = this.geometry;
  9595. if ( bound.sphereInitialized === false ) {
  9596. sphere.makeEmpty();
  9597. this.getBoundingBoxAt( geometryId, _box$1 );
  9598. _box$1.getCenter( sphere.center );
  9599. const index = geometry.index;
  9600. const position = geometry.attributes.position;
  9601. const drawRange = this._drawRanges[ geometryId ];
  9602. let maxRadiusSq = 0;
  9603. for ( let i = drawRange.start, l = drawRange.start + drawRange.count; i < l; i ++ ) {
  9604. let iv = i;
  9605. if ( index ) {
  9606. iv = index.getX( iv );
  9607. }
  9608. _vector$5.fromBufferAttribute( position, iv );
  9609. maxRadiusSq = Math.max( maxRadiusSq, sphere.center.distanceToSquared( _vector$5 ) );
  9610. }
  9611. sphere.radius = Math.sqrt( maxRadiusSq );
  9612. bound.sphereInitialized = true;
  9613. }
  9614. target.copy( sphere );
  9615. return target;
  9616. }
  9617. setMatrixAt( instanceId, matrix ) {
  9618. // @TODO: Map geometryId to index of the arrays because
  9619. // optimize() can make geometryId mismatch the index
  9620. const drawInfo = this._drawInfo;
  9621. const matricesTexture = this._matricesTexture;
  9622. const matricesArray = this._matricesTexture.image.data;
  9623. if ( instanceId >= drawInfo.length || drawInfo[ instanceId ].active === false ) {
  9624. return this;
  9625. }
  9626. matrix.toArray( matricesArray, instanceId * 16 );
  9627. matricesTexture.needsUpdate = true;
  9628. return this;
  9629. }
  9630. getMatrixAt( instanceId, matrix ) {
  9631. const drawInfo = this._drawInfo;
  9632. const matricesArray = this._matricesTexture.image.data;
  9633. if ( instanceId >= drawInfo.length || drawInfo[ instanceId ].active === false ) {
  9634. return null;
  9635. }
  9636. return matrix.fromArray( matricesArray, instanceId * 16 );
  9637. }
  9638. setColorAt( instanceId, color ) {
  9639. if ( this._colorsTexture === null ) {
  9640. this._initColorsTexture();
  9641. }
  9642. // @TODO: Map id to index of the arrays because
  9643. // optimize() can make id mismatch the index
  9644. const colorsTexture = this._colorsTexture;
  9645. const colorsArray = this._colorsTexture.image.data;
  9646. const drawInfo = this._drawInfo;
  9647. if ( instanceId >= drawInfo.length || drawInfo[ instanceId ].active === false ) {
  9648. return this;
  9649. }
  9650. color.toArray( colorsArray, instanceId * 4 );
  9651. colorsTexture.needsUpdate = true;
  9652. return this;
  9653. }
  9654. getColorAt( instanceId, color ) {
  9655. const colorsArray = this._colorsTexture.image.data;
  9656. const drawInfo = this._drawInfo;
  9657. if ( instanceId >= drawInfo.length || drawInfo[ instanceId ].active === false ) {
  9658. return null;
  9659. }
  9660. return color.fromArray( colorsArray, instanceId * 4 );
  9661. }
  9662. setVisibleAt( instanceId, value ) {
  9663. // if the geometry is out of range, not active, or visibility state
  9664. // does not change then return early
  9665. const drawInfo = this._drawInfo;
  9666. if (
  9667. instanceId >= drawInfo.length ||
  9668. drawInfo[ instanceId ].active === false ||
  9669. drawInfo[ instanceId ].visible === value
  9670. ) {
  9671. return this;
  9672. }
  9673. drawInfo[ instanceId ].visible = value;
  9674. this._visibilityChanged = true;
  9675. return this;
  9676. }
  9677. getVisibleAt( instanceId ) {
  9678. // return early if the geometry is out of range or not active
  9679. const drawInfo = this._drawInfo;
  9680. if ( instanceId >= drawInfo.length || drawInfo[ instanceId ].active === false ) {
  9681. return false;
  9682. }
  9683. return drawInfo[ instanceId ].visible;
  9684. }
  9685. setGeometryIdAt( instanceId, geometryId ) {
  9686. // return early if the geometry is out of range or not active
  9687. const drawInfo = this._drawInfo;
  9688. if ( instanceId >= drawInfo.length || drawInfo[ instanceId ].active === false ) {
  9689. return null;
  9690. }
  9691. // check if the provided geometryId is within the valid range
  9692. if ( geometryId < 0 || geometryId >= this._geometryCount ) {
  9693. return null;
  9694. }
  9695. drawInfo[ instanceId ].geometryIndex = geometryId;
  9696. return this;
  9697. }
  9698. getGeometryIdAt( instanceId ) {
  9699. const drawInfo = this._drawInfo;
  9700. if ( instanceId >= drawInfo.length || drawInfo[ instanceId ].active === false ) {
  9701. return - 1;
  9702. }
  9703. return drawInfo[ instanceId ].geometryIndex;
  9704. }
  9705. getGeometryRangeAt( geometryId, target = {} ) {
  9706. if ( geometryId < 0 || geometryId >= this._geometryCount ) {
  9707. return null;
  9708. }
  9709. const drawRange = this._drawRanges[ geometryId ];
  9710. target.start = drawRange.start;
  9711. target.count = drawRange.count;
  9712. return target;
  9713. }
  9714. setInstanceCount( maxInstanceCount ) {
  9715. // shrink the available instances as much as possible
  9716. const availableInstanceIds = this._availableInstanceIds;
  9717. const drawInfo = this._drawInfo;
  9718. availableInstanceIds.sort( ascIdSort );
  9719. while ( availableInstanceIds[ availableInstanceIds.length - 1 ] === drawInfo.length ) {
  9720. drawInfo.pop();
  9721. availableInstanceIds.pop();
  9722. }
  9723. // throw an error if it can't be shrunk to the desired size
  9724. if ( maxInstanceCount < drawInfo.length ) {
  9725. throw new Error( `BatchedMesh: Instance ids outside the range ${ maxInstanceCount } are being used. Cannot shrink instance count.` );
  9726. }
  9727. // copy the multi draw counts
  9728. const multiDrawCounts = new Int32Array( maxInstanceCount );
  9729. const multiDrawStarts = new Int32Array( maxInstanceCount );
  9730. copyArrayContents( this._multiDrawCounts, multiDrawCounts );
  9731. copyArrayContents( this._multiDrawStarts, multiDrawStarts );
  9732. this._multiDrawCounts = multiDrawCounts;
  9733. this._multiDrawStarts = multiDrawStarts;
  9734. this._maxInstanceCount = maxInstanceCount;
  9735. // update texture data for instance sampling
  9736. const indirectTexture = this._indirectTexture;
  9737. const matricesTexture = this._matricesTexture;
  9738. const colorsTexture = this._colorsTexture;
  9739. this._initIndirectTexture();
  9740. copyArrayContents( indirectTexture.image.data, this._indirectTexture.image.data );
  9741. this._initMatricesTexture();
  9742. copyArrayContents( matricesTexture.image.data, this._matricesTexture.image.data );
  9743. if ( colorsTexture ) {
  9744. this._initColorsTexture();
  9745. copyArrayContents( colorsTexture.image.data, this._colorsTexture.image.data );
  9746. }
  9747. }
  9748. setGeometrySize( maxVertexCount, maxIndexCount ) {
  9749. // Check if we can shrink to the requested vertex attribute size
  9750. const validRanges = [ ...this._reservedRanges ].filter( ( range, i ) => this._drawRanges[ i ].active );
  9751. const requiredVertexLength = Math.max( ...validRanges.map( range => range.vertexStart + range.vertexCount ) );
  9752. if ( requiredVertexLength > maxVertexCount ) {
  9753. throw new Error( `BatchedMesh: Geometry vertex values are being used outside the range ${ maxIndexCount }. Cannot shrink further.` );
  9754. }
  9755. // Check if we can shrink to the requested index attribute size
  9756. if ( this.geometry.index ) {
  9757. const requiredIndexLength = Math.max( ...validRanges.map( range => range.indexStart + range.indexCount ) );
  9758. if ( requiredIndexLength > maxIndexCount ) {
  9759. throw new Error( `BatchedMesh: Geometry index values are being used outside the range ${ maxIndexCount }. Cannot shrink further.` );
  9760. }
  9761. }
  9762. //
  9763. // dispose of the previous geometry
  9764. const oldGeometry = this.geometry;
  9765. oldGeometry.dispose();
  9766. // recreate the geometry needed based on the previous variant
  9767. this._maxVertexCount = maxVertexCount;
  9768. this._maxIndexCount = maxIndexCount;
  9769. this._geometryInitialized = false;
  9770. this.geometry = new BufferGeometry();
  9771. this._initializeGeometry( oldGeometry );
  9772. // copy data from the previous geometry
  9773. const geometry = this.geometry;
  9774. if ( oldGeometry.index ) {
  9775. copyArrayContents( oldGeometry.index.array, geometry.index.array );
  9776. }
  9777. for ( const key in oldGeometry.attributes ) {
  9778. copyArrayContents( oldGeometry.attributes[ key ].array, geometry.attributes[ key ].array );
  9779. }
  9780. }
  9781. raycast( raycaster, intersects ) {
  9782. const drawInfo = this._drawInfo;
  9783. const drawRanges = this._drawRanges;
  9784. const matrixWorld = this.matrixWorld;
  9785. const batchGeometry = this.geometry;
  9786. // iterate over each geometry
  9787. _mesh.material = this.material;
  9788. _mesh.geometry.index = batchGeometry.index;
  9789. _mesh.geometry.attributes = batchGeometry.attributes;
  9790. if ( _mesh.geometry.boundingBox === null ) {
  9791. _mesh.geometry.boundingBox = new Box3();
  9792. }
  9793. if ( _mesh.geometry.boundingSphere === null ) {
  9794. _mesh.geometry.boundingSphere = new Sphere();
  9795. }
  9796. for ( let i = 0, l = drawInfo.length; i < l; i ++ ) {
  9797. if ( ! drawInfo[ i ].visible || ! drawInfo[ i ].active ) {
  9798. continue;
  9799. }
  9800. const geometryId = drawInfo[ i ].geometryIndex;
  9801. const drawRange = drawRanges[ geometryId ];
  9802. _mesh.geometry.setDrawRange( drawRange.start, drawRange.count );
  9803. // ge the intersects
  9804. this.getMatrixAt( i, _mesh.matrixWorld ).premultiply( matrixWorld );
  9805. this.getBoundingBoxAt( geometryId, _mesh.geometry.boundingBox );
  9806. this.getBoundingSphereAt( geometryId, _mesh.geometry.boundingSphere );
  9807. _mesh.raycast( raycaster, _batchIntersects );
  9808. // add batch id to the intersects
  9809. for ( let j = 0, l = _batchIntersects.length; j < l; j ++ ) {
  9810. const intersect = _batchIntersects[ j ];
  9811. intersect.object = this;
  9812. intersect.batchId = i;
  9813. intersects.push( intersect );
  9814. }
  9815. _batchIntersects.length = 0;
  9816. }
  9817. _mesh.material = null;
  9818. _mesh.geometry.index = null;
  9819. _mesh.geometry.attributes = {};
  9820. _mesh.geometry.setDrawRange( 0, Infinity );
  9821. }
  9822. copy( source ) {
  9823. super.copy( source );
  9824. this.geometry = source.geometry.clone();
  9825. this.perObjectFrustumCulled = source.perObjectFrustumCulled;
  9826. this.sortObjects = source.sortObjects;
  9827. this.boundingBox = source.boundingBox !== null ? source.boundingBox.clone() : null;
  9828. this.boundingSphere = source.boundingSphere !== null ? source.boundingSphere.clone() : null;
  9829. this._drawRanges = source._drawRanges.map( range => ( { ...range } ) );
  9830. this._reservedRanges = source._reservedRanges.map( range => ( { ...range } ) );
  9831. this._drawInfo = source._drawInfo.map( inf => ( { ...inf } ) );
  9832. this._bounds = source._bounds.map( bound => ( {
  9833. boxInitialized: bound.boxInitialized,
  9834. box: bound.box.clone(),
  9835. sphereInitialized: bound.sphereInitialized,
  9836. sphere: bound.sphere.clone()
  9837. } ) );
  9838. this._maxInstanceCount = source._maxInstanceCount;
  9839. this._maxVertexCount = source._maxVertexCount;
  9840. this._maxIndexCount = source._maxIndexCount;
  9841. this._geometryInitialized = source._geometryInitialized;
  9842. this._geometryCount = source._geometryCount;
  9843. this._multiDrawCounts = source._multiDrawCounts.slice();
  9844. this._multiDrawStarts = source._multiDrawStarts.slice();
  9845. this._matricesTexture = source._matricesTexture.clone();
  9846. this._matricesTexture.image.data = this._matricesTexture.image.data.slice();
  9847. if ( this._colorsTexture !== null ) {
  9848. this._colorsTexture = source._colorsTexture.clone();
  9849. this._colorsTexture.image.data = this._colorsTexture.image.data.slice();
  9850. }
  9851. return this;
  9852. }
  9853. dispose() {
  9854. // Assuming the geometry is not shared with other meshes
  9855. this.geometry.dispose();
  9856. this._matricesTexture.dispose();
  9857. this._matricesTexture = null;
  9858. this._indirectTexture.dispose();
  9859. this._indirectTexture = null;
  9860. if ( this._colorsTexture !== null ) {
  9861. this._colorsTexture.dispose();
  9862. this._colorsTexture = null;
  9863. }
  9864. return this;
  9865. }
  9866. onBeforeRender( renderer, scene, camera, geometry, material/*, _group*/ ) {
  9867. // if visibility has not changed and frustum culling and object sorting is not required
  9868. // then skip iterating over all items
  9869. if ( ! this._visibilityChanged && ! this.perObjectFrustumCulled && ! this.sortObjects ) {
  9870. return;
  9871. }
  9872. // the indexed version of the multi draw function requires specifying the start
  9873. // offset in bytes.
  9874. const index = geometry.getIndex();
  9875. const bytesPerElement = index === null ? 1 : index.array.BYTES_PER_ELEMENT;
  9876. const drawInfo = this._drawInfo;
  9877. const multiDrawStarts = this._multiDrawStarts;
  9878. const multiDrawCounts = this._multiDrawCounts;
  9879. const drawRanges = this._drawRanges;
  9880. const perObjectFrustumCulled = this.perObjectFrustumCulled;
  9881. const indirectTexture = this._indirectTexture;
  9882. const indirectArray = indirectTexture.image.data;
  9883. // prepare the frustum in the local frame
  9884. if ( perObjectFrustumCulled ) {
  9885. _projScreenMatrix$3
  9886. .multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse )
  9887. .multiply( this.matrixWorld );
  9888. _frustum$1.setFromProjectionMatrix(
  9889. _projScreenMatrix$3,
  9890. renderer.coordinateSystem
  9891. );
  9892. }
  9893. let count = 0;
  9894. if ( this.sortObjects ) {
  9895. // get the camera position in the local frame
  9896. _invMatrixWorld.copy( this.matrixWorld ).invert();
  9897. _vector$5.setFromMatrixPosition( camera.matrixWorld ).applyMatrix4( _invMatrixWorld );
  9898. _forward.set( 0, 0, - 1 ).transformDirection( camera.matrixWorld ).transformDirection( _invMatrixWorld );
  9899. for ( let i = 0, l = drawInfo.length; i < l; i ++ ) {
  9900. if ( drawInfo[ i ].visible && drawInfo[ i ].active ) {
  9901. const geometryId = drawInfo[ i ].geometryIndex;
  9902. // get the bounds in world space
  9903. this.getMatrixAt( i, _matrix$1 );
  9904. this.getBoundingSphereAt( geometryId, _sphere$2 ).applyMatrix4( _matrix$1 );
  9905. // determine whether the batched geometry is within the frustum
  9906. let culled = false;
  9907. if ( perObjectFrustumCulled ) {
  9908. culled = ! _frustum$1.intersectsSphere( _sphere$2 );
  9909. }
  9910. if ( ! culled ) {
  9911. // get the distance from camera used for sorting
  9912. const z = _temp.subVectors( _sphere$2.center, _vector$5 ).dot( _forward );
  9913. _renderList.push( drawRanges[ geometryId ], z, i );
  9914. }
  9915. }
  9916. }
  9917. // Sort the draw ranges and prep for rendering
  9918. const list = _renderList.list;
  9919. const customSort = this.customSort;
  9920. if ( customSort === null ) {
  9921. list.sort( material.transparent ? sortTransparent : sortOpaque );
  9922. } else {
  9923. customSort.call( this, list, camera );
  9924. }
  9925. for ( let i = 0, l = list.length; i < l; i ++ ) {
  9926. const item = list[ i ];
  9927. multiDrawStarts[ count ] = item.start * bytesPerElement;
  9928. multiDrawCounts[ count ] = item.count;
  9929. indirectArray[ count ] = item.index;
  9930. count ++;
  9931. }
  9932. _renderList.reset();
  9933. } else {
  9934. for ( let i = 0, l = drawInfo.length; i < l; i ++ ) {
  9935. if ( drawInfo[ i ].visible && drawInfo[ i ].active ) {
  9936. const geometryId = drawInfo[ i ].geometryIndex;
  9937. // determine whether the batched geometry is within the frustum
  9938. let culled = false;
  9939. if ( perObjectFrustumCulled ) {
  9940. // get the bounds in world space
  9941. this.getMatrixAt( i, _matrix$1 );
  9942. this.getBoundingSphereAt( geometryId, _sphere$2 ).applyMatrix4( _matrix$1 );
  9943. culled = ! _frustum$1.intersectsSphere( _sphere$2 );
  9944. }
  9945. if ( ! culled ) {
  9946. const range = drawRanges[ geometryId ];
  9947. multiDrawStarts[ count ] = range.start * bytesPerElement;
  9948. multiDrawCounts[ count ] = range.count;
  9949. indirectArray[ count ] = i;
  9950. count ++;
  9951. }
  9952. }
  9953. }
  9954. }
  9955. indirectTexture.needsUpdate = true;
  9956. this._multiDrawCount = count;
  9957. this._visibilityChanged = false;
  9958. }
  9959. onBeforeShadow( renderer, object, camera, shadowCamera, geometry, depthMaterial/* , group */ ) {
  9960. this.onBeforeRender( renderer, null, shadowCamera, geometry, depthMaterial );
  9961. }
  9962. }
  9963. class LineBasicMaterial extends Material {
  9964. static get type() {
  9965. return 'LineBasicMaterial';
  9966. }
  9967. constructor( parameters ) {
  9968. super();
  9969. this.isLineBasicMaterial = true;
  9970. this.color = new Color( 0xffffff );
  9971. this.map = null;
  9972. this.linewidth = 1;
  9973. this.linecap = 'round';
  9974. this.linejoin = 'round';
  9975. this.fog = true;
  9976. this.setValues( parameters );
  9977. }
  9978. copy( source ) {
  9979. super.copy( source );
  9980. this.color.copy( source.color );
  9981. this.map = source.map;
  9982. this.linewidth = source.linewidth;
  9983. this.linecap = source.linecap;
  9984. this.linejoin = source.linejoin;
  9985. this.fog = source.fog;
  9986. return this;
  9987. }
  9988. }
  9989. const _vStart = /*@__PURE__*/ new Vector3();
  9990. const _vEnd = /*@__PURE__*/ new Vector3();
  9991. const _inverseMatrix$1 = /*@__PURE__*/ new Matrix4();
  9992. const _ray$1 = /*@__PURE__*/ new Ray();
  9993. const _sphere$1 = /*@__PURE__*/ new Sphere();
  9994. const _intersectPointOnRay = /*@__PURE__*/ new Vector3();
  9995. const _intersectPointOnSegment = /*@__PURE__*/ new Vector3();
  9996. class Line extends Object3D {
  9997. constructor( geometry = new BufferGeometry(), material = new LineBasicMaterial() ) {
  9998. super();
  9999. this.isLine = true;
  10000. this.type = 'Line';
  10001. this.geometry = geometry;
  10002. this.material = material;
  10003. this.updateMorphTargets();
  10004. }
  10005. copy( source, recursive ) {
  10006. super.copy( source, recursive );
  10007. this.material = Array.isArray( source.material ) ? source.material.slice() : source.material;
  10008. this.geometry = source.geometry;
  10009. return this;
  10010. }
  10011. computeLineDistances() {
  10012. const geometry = this.geometry;
  10013. // we assume non-indexed geometry
  10014. if ( geometry.index === null ) {
  10015. const positionAttribute = geometry.attributes.position;
  10016. const lineDistances = [ 0 ];
  10017. for ( let i = 1, l = positionAttribute.count; i < l; i ++ ) {
  10018. _vStart.fromBufferAttribute( positionAttribute, i - 1 );
  10019. _vEnd.fromBufferAttribute( positionAttribute, i );
  10020. lineDistances[ i ] = lineDistances[ i - 1 ];
  10021. lineDistances[ i ] += _vStart.distanceTo( _vEnd );
  10022. }
  10023. geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  10024. } else {
  10025. console.warn( 'THREE.Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  10026. }
  10027. return this;
  10028. }
  10029. raycast( raycaster, intersects ) {
  10030. const geometry = this.geometry;
  10031. const matrixWorld = this.matrixWorld;
  10032. const threshold = raycaster.params.Line.threshold;
  10033. const drawRange = geometry.drawRange;
  10034. // Checking boundingSphere distance to ray
  10035. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  10036. _sphere$1.copy( geometry.boundingSphere );
  10037. _sphere$1.applyMatrix4( matrixWorld );
  10038. _sphere$1.radius += threshold;
  10039. if ( raycaster.ray.intersectsSphere( _sphere$1 ) === false ) return;
  10040. //
  10041. _inverseMatrix$1.copy( matrixWorld ).invert();
  10042. _ray$1.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$1 );
  10043. const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  10044. const localThresholdSq = localThreshold * localThreshold;
  10045. const step = this.isLineSegments ? 2 : 1;
  10046. const index = geometry.index;
  10047. const attributes = geometry.attributes;
  10048. const positionAttribute = attributes.position;
  10049. if ( index !== null ) {
  10050. const start = Math.max( 0, drawRange.start );
  10051. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  10052. for ( let i = start, l = end - 1; i < l; i += step ) {
  10053. const a = index.getX( i );
  10054. const b = index.getX( i + 1 );
  10055. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, a, b );
  10056. if ( intersect ) {
  10057. intersects.push( intersect );
  10058. }
  10059. }
  10060. if ( this.isLineLoop ) {
  10061. const a = index.getX( end - 1 );
  10062. const b = index.getX( start );
  10063. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, a, b );
  10064. if ( intersect ) {
  10065. intersects.push( intersect );
  10066. }
  10067. }
  10068. } else {
  10069. const start = Math.max( 0, drawRange.start );
  10070. const end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) );
  10071. for ( let i = start, l = end - 1; i < l; i += step ) {
  10072. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, i, i + 1 );
  10073. if ( intersect ) {
  10074. intersects.push( intersect );
  10075. }
  10076. }
  10077. if ( this.isLineLoop ) {
  10078. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, end - 1, start );
  10079. if ( intersect ) {
  10080. intersects.push( intersect );
  10081. }
  10082. }
  10083. }
  10084. }
  10085. updateMorphTargets() {
  10086. const geometry = this.geometry;
  10087. const morphAttributes = geometry.morphAttributes;
  10088. const keys = Object.keys( morphAttributes );
  10089. if ( keys.length > 0 ) {
  10090. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  10091. if ( morphAttribute !== undefined ) {
  10092. this.morphTargetInfluences = [];
  10093. this.morphTargetDictionary = {};
  10094. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  10095. const name = morphAttribute[ m ].name || String( m );
  10096. this.morphTargetInfluences.push( 0 );
  10097. this.morphTargetDictionary[ name ] = m;
  10098. }
  10099. }
  10100. }
  10101. }
  10102. }
  10103. function checkIntersection( object, raycaster, ray, thresholdSq, a, b ) {
  10104. const positionAttribute = object.geometry.attributes.position;
  10105. _vStart.fromBufferAttribute( positionAttribute, a );
  10106. _vEnd.fromBufferAttribute( positionAttribute, b );
  10107. const distSq = ray.distanceSqToSegment( _vStart, _vEnd, _intersectPointOnRay, _intersectPointOnSegment );
  10108. if ( distSq > thresholdSq ) return;
  10109. _intersectPointOnRay.applyMatrix4( object.matrixWorld ); // Move back to world space for distance calculation
  10110. const distance = raycaster.ray.origin.distanceTo( _intersectPointOnRay );
  10111. if ( distance < raycaster.near || distance > raycaster.far ) return;
  10112. return {
  10113. distance: distance,
  10114. // What do we want? intersection point on the ray or on the segment??
  10115. // point: raycaster.ray.at( distance ),
  10116. point: _intersectPointOnSegment.clone().applyMatrix4( object.matrixWorld ),
  10117. index: a,
  10118. face: null,
  10119. faceIndex: null,
  10120. barycoord: null,
  10121. object: object
  10122. };
  10123. }
  10124. const _start = /*@__PURE__*/ new Vector3();
  10125. const _end = /*@__PURE__*/ new Vector3();
  10126. class LineSegments extends Line {
  10127. constructor( geometry, material ) {
  10128. super( geometry, material );
  10129. this.isLineSegments = true;
  10130. this.type = 'LineSegments';
  10131. }
  10132. computeLineDistances() {
  10133. const geometry = this.geometry;
  10134. // we assume non-indexed geometry
  10135. if ( geometry.index === null ) {
  10136. const positionAttribute = geometry.attributes.position;
  10137. const lineDistances = [];
  10138. for ( let i = 0, l = positionAttribute.count; i < l; i += 2 ) {
  10139. _start.fromBufferAttribute( positionAttribute, i );
  10140. _end.fromBufferAttribute( positionAttribute, i + 1 );
  10141. lineDistances[ i ] = ( i === 0 ) ? 0 : lineDistances[ i - 1 ];
  10142. lineDistances[ i + 1 ] = lineDistances[ i ] + _start.distanceTo( _end );
  10143. }
  10144. geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  10145. } else {
  10146. console.warn( 'THREE.LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  10147. }
  10148. return this;
  10149. }
  10150. }
  10151. class LineLoop extends Line {
  10152. constructor( geometry, material ) {
  10153. super( geometry, material );
  10154. this.isLineLoop = true;
  10155. this.type = 'LineLoop';
  10156. }
  10157. }
  10158. class PointsMaterial extends Material {
  10159. static get type() {
  10160. return 'PointsMaterial';
  10161. }
  10162. constructor( parameters ) {
  10163. super();
  10164. this.isPointsMaterial = true;
  10165. this.color = new Color( 0xffffff );
  10166. this.map = null;
  10167. this.alphaMap = null;
  10168. this.size = 1;
  10169. this.sizeAttenuation = true;
  10170. this.fog = true;
  10171. this.setValues( parameters );
  10172. }
  10173. copy( source ) {
  10174. super.copy( source );
  10175. this.color.copy( source.color );
  10176. this.map = source.map;
  10177. this.alphaMap = source.alphaMap;
  10178. this.size = source.size;
  10179. this.sizeAttenuation = source.sizeAttenuation;
  10180. this.fog = source.fog;
  10181. return this;
  10182. }
  10183. }
  10184. const _inverseMatrix = /*@__PURE__*/ new Matrix4();
  10185. const _ray = /*@__PURE__*/ new Ray();
  10186. const _sphere = /*@__PURE__*/ new Sphere();
  10187. const _position$2 = /*@__PURE__*/ new Vector3();
  10188. class Points extends Object3D {
  10189. constructor( geometry = new BufferGeometry(), material = new PointsMaterial() ) {
  10190. super();
  10191. this.isPoints = true;
  10192. this.type = 'Points';
  10193. this.geometry = geometry;
  10194. this.material = material;
  10195. this.updateMorphTargets();
  10196. }
  10197. copy( source, recursive ) {
  10198. super.copy( source, recursive );
  10199. this.material = Array.isArray( source.material ) ? source.material.slice() : source.material;
  10200. this.geometry = source.geometry;
  10201. return this;
  10202. }
  10203. raycast( raycaster, intersects ) {
  10204. const geometry = this.geometry;
  10205. const matrixWorld = this.matrixWorld;
  10206. const threshold = raycaster.params.Points.threshold;
  10207. const drawRange = geometry.drawRange;
  10208. // Checking boundingSphere distance to ray
  10209. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  10210. _sphere.copy( geometry.boundingSphere );
  10211. _sphere.applyMatrix4( matrixWorld );
  10212. _sphere.radius += threshold;
  10213. if ( raycaster.ray.intersectsSphere( _sphere ) === false ) return;
  10214. //
  10215. _inverseMatrix.copy( matrixWorld ).invert();
  10216. _ray.copy( raycaster.ray ).applyMatrix4( _inverseMatrix );
  10217. const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  10218. const localThresholdSq = localThreshold * localThreshold;
  10219. const index = geometry.index;
  10220. const attributes = geometry.attributes;
  10221. const positionAttribute = attributes.position;
  10222. if ( index !== null ) {
  10223. const start = Math.max( 0, drawRange.start );
  10224. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  10225. for ( let i = start, il = end; i < il; i ++ ) {
  10226. const a = index.getX( i );
  10227. _position$2.fromBufferAttribute( positionAttribute, a );
  10228. testPoint( _position$2, a, localThresholdSq, matrixWorld, raycaster, intersects, this );
  10229. }
  10230. } else {
  10231. const start = Math.max( 0, drawRange.start );
  10232. const end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) );
  10233. for ( let i = start, l = end; i < l; i ++ ) {
  10234. _position$2.fromBufferAttribute( positionAttribute, i );
  10235. testPoint( _position$2, i, localThresholdSq, matrixWorld, raycaster, intersects, this );
  10236. }
  10237. }
  10238. }
  10239. updateMorphTargets() {
  10240. const geometry = this.geometry;
  10241. const morphAttributes = geometry.morphAttributes;
  10242. const keys = Object.keys( morphAttributes );
  10243. if ( keys.length > 0 ) {
  10244. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  10245. if ( morphAttribute !== undefined ) {
  10246. this.morphTargetInfluences = [];
  10247. this.morphTargetDictionary = {};
  10248. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  10249. const name = morphAttribute[ m ].name || String( m );
  10250. this.morphTargetInfluences.push( 0 );
  10251. this.morphTargetDictionary[ name ] = m;
  10252. }
  10253. }
  10254. }
  10255. }
  10256. }
  10257. function testPoint( point, index, localThresholdSq, matrixWorld, raycaster, intersects, object ) {
  10258. const rayPointDistanceSq = _ray.distanceSqToPoint( point );
  10259. if ( rayPointDistanceSq < localThresholdSq ) {
  10260. const intersectPoint = new Vector3();
  10261. _ray.closestPointToPoint( point, intersectPoint );
  10262. intersectPoint.applyMatrix4( matrixWorld );
  10263. const distance = raycaster.ray.origin.distanceTo( intersectPoint );
  10264. if ( distance < raycaster.near || distance > raycaster.far ) return;
  10265. intersects.push( {
  10266. distance: distance,
  10267. distanceToRay: Math.sqrt( rayPointDistanceSq ),
  10268. point: intersectPoint,
  10269. index: index,
  10270. face: null,
  10271. faceIndex: null,
  10272. barycoord: null,
  10273. object: object
  10274. } );
  10275. }
  10276. }
  10277. class Group extends Object3D {
  10278. constructor() {
  10279. super();
  10280. this.isGroup = true;
  10281. this.type = 'Group';
  10282. }
  10283. }
  10284. class VideoTexture extends Texture {
  10285. constructor( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  10286. super( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  10287. this.isVideoTexture = true;
  10288. this.minFilter = minFilter !== undefined ? minFilter : LinearFilter;
  10289. this.magFilter = magFilter !== undefined ? magFilter : LinearFilter;
  10290. this.generateMipmaps = false;
  10291. const scope = this;
  10292. function updateVideo() {
  10293. scope.needsUpdate = true;
  10294. video.requestVideoFrameCallback( updateVideo );
  10295. }
  10296. if ( 'requestVideoFrameCallback' in video ) {
  10297. video.requestVideoFrameCallback( updateVideo );
  10298. }
  10299. }
  10300. clone() {
  10301. return new this.constructor( this.image ).copy( this );
  10302. }
  10303. update() {
  10304. const video = this.image;
  10305. const hasVideoFrameCallback = 'requestVideoFrameCallback' in video;
  10306. if ( hasVideoFrameCallback === false && video.readyState >= video.HAVE_CURRENT_DATA ) {
  10307. this.needsUpdate = true;
  10308. }
  10309. }
  10310. }
  10311. class FramebufferTexture extends Texture {
  10312. constructor( width, height ) {
  10313. super( { width, height } );
  10314. this.isFramebufferTexture = true;
  10315. this.magFilter = NearestFilter;
  10316. this.minFilter = NearestFilter;
  10317. this.generateMipmaps = false;
  10318. this.needsUpdate = true;
  10319. }
  10320. }
  10321. class CompressedTexture extends Texture {
  10322. constructor( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, colorSpace ) {
  10323. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace );
  10324. this.isCompressedTexture = true;
  10325. this.image = { width: width, height: height };
  10326. this.mipmaps = mipmaps;
  10327. // no flipping for cube textures
  10328. // (also flipping doesn't work for compressed textures )
  10329. this.flipY = false;
  10330. // can't generate mipmaps for compressed textures
  10331. // mips must be embedded in DDS files
  10332. this.generateMipmaps = false;
  10333. }
  10334. }
  10335. class CompressedArrayTexture extends CompressedTexture {
  10336. constructor( mipmaps, width, height, depth, format, type ) {
  10337. super( mipmaps, width, height, format, type );
  10338. this.isCompressedArrayTexture = true;
  10339. this.image.depth = depth;
  10340. this.wrapR = ClampToEdgeWrapping;
  10341. this.layerUpdates = new Set();
  10342. }
  10343. addLayerUpdate( layerIndex ) {
  10344. this.layerUpdates.add( layerIndex );
  10345. }
  10346. clearLayerUpdates() {
  10347. this.layerUpdates.clear();
  10348. }
  10349. }
  10350. class CompressedCubeTexture extends CompressedTexture {
  10351. constructor( images, format, type ) {
  10352. super( undefined, images[ 0 ].width, images[ 0 ].height, format, type, CubeReflectionMapping );
  10353. this.isCompressedCubeTexture = true;
  10354. this.isCubeTexture = true;
  10355. this.image = images;
  10356. }
  10357. }
  10358. class CanvasTexture extends Texture {
  10359. constructor( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  10360. super( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  10361. this.isCanvasTexture = true;
  10362. this.needsUpdate = true;
  10363. }
  10364. }
  10365. class DepthTexture extends Texture {
  10366. constructor( width, height, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, format = DepthFormat ) {
  10367. if ( format !== DepthFormat && format !== DepthStencilFormat ) {
  10368. throw new Error( 'DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat' );
  10369. }
  10370. if ( type === undefined && format === DepthFormat ) type = UnsignedIntType;
  10371. if ( type === undefined && format === DepthStencilFormat ) type = UnsignedInt248Type;
  10372. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  10373. this.isDepthTexture = true;
  10374. this.image = { width: width, height: height };
  10375. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  10376. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  10377. this.flipY = false;
  10378. this.generateMipmaps = false;
  10379. this.compareFunction = null;
  10380. }
  10381. copy( source ) {
  10382. super.copy( source );
  10383. this.compareFunction = source.compareFunction;
  10384. return this;
  10385. }
  10386. toJSON( meta ) {
  10387. const data = super.toJSON( meta );
  10388. if ( this.compareFunction !== null ) data.compareFunction = this.compareFunction;
  10389. return data;
  10390. }
  10391. }
  10392. /**
  10393. * Extensible curve object.
  10394. *
  10395. * Some common of curve methods:
  10396. * .getPoint( t, optionalTarget ), .getTangent( t, optionalTarget )
  10397. * .getPointAt( u, optionalTarget ), .getTangentAt( u, optionalTarget )
  10398. * .getPoints(), .getSpacedPoints()
  10399. * .getLength()
  10400. * .updateArcLengths()
  10401. *
  10402. * This following curves inherit from THREE.Curve:
  10403. *
  10404. * -- 2D curves --
  10405. * THREE.ArcCurve
  10406. * THREE.CubicBezierCurve
  10407. * THREE.EllipseCurve
  10408. * THREE.LineCurve
  10409. * THREE.QuadraticBezierCurve
  10410. * THREE.SplineCurve
  10411. *
  10412. * -- 3D curves --
  10413. * THREE.CatmullRomCurve3
  10414. * THREE.CubicBezierCurve3
  10415. * THREE.LineCurve3
  10416. * THREE.QuadraticBezierCurve3
  10417. *
  10418. * A series of curves can be represented as a THREE.CurvePath.
  10419. *
  10420. **/
  10421. class Curve {
  10422. constructor() {
  10423. this.type = 'Curve';
  10424. this.arcLengthDivisions = 200;
  10425. }
  10426. // Virtual base class method to overwrite and implement in subclasses
  10427. // - t [0 .. 1]
  10428. getPoint( /* t, optionalTarget */ ) {
  10429. console.warn( 'THREE.Curve: .getPoint() not implemented.' );
  10430. return null;
  10431. }
  10432. // Get point at relative position in curve according to arc length
  10433. // - u [0 .. 1]
  10434. getPointAt( u, optionalTarget ) {
  10435. const t = this.getUtoTmapping( u );
  10436. return this.getPoint( t, optionalTarget );
  10437. }
  10438. // Get sequence of points using getPoint( t )
  10439. getPoints( divisions = 5 ) {
  10440. const points = [];
  10441. for ( let d = 0; d <= divisions; d ++ ) {
  10442. points.push( this.getPoint( d / divisions ) );
  10443. }
  10444. return points;
  10445. }
  10446. // Get sequence of points using getPointAt( u )
  10447. getSpacedPoints( divisions = 5 ) {
  10448. const points = [];
  10449. for ( let d = 0; d <= divisions; d ++ ) {
  10450. points.push( this.getPointAt( d / divisions ) );
  10451. }
  10452. return points;
  10453. }
  10454. // Get total curve arc length
  10455. getLength() {
  10456. const lengths = this.getLengths();
  10457. return lengths[ lengths.length - 1 ];
  10458. }
  10459. // Get list of cumulative segment lengths
  10460. getLengths( divisions = this.arcLengthDivisions ) {
  10461. if ( this.cacheArcLengths &&
  10462. ( this.cacheArcLengths.length === divisions + 1 ) &&
  10463. ! this.needsUpdate ) {
  10464. return this.cacheArcLengths;
  10465. }
  10466. this.needsUpdate = false;
  10467. const cache = [];
  10468. let current, last = this.getPoint( 0 );
  10469. let sum = 0;
  10470. cache.push( 0 );
  10471. for ( let p = 1; p <= divisions; p ++ ) {
  10472. current = this.getPoint( p / divisions );
  10473. sum += current.distanceTo( last );
  10474. cache.push( sum );
  10475. last = current;
  10476. }
  10477. this.cacheArcLengths = cache;
  10478. return cache; // { sums: cache, sum: sum }; Sum is in the last element.
  10479. }
  10480. updateArcLengths() {
  10481. this.needsUpdate = true;
  10482. this.getLengths();
  10483. }
  10484. // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equidistant
  10485. getUtoTmapping( u, distance ) {
  10486. const arcLengths = this.getLengths();
  10487. let i = 0;
  10488. const il = arcLengths.length;
  10489. let targetArcLength; // The targeted u distance value to get
  10490. if ( distance ) {
  10491. targetArcLength = distance;
  10492. } else {
  10493. targetArcLength = u * arcLengths[ il - 1 ];
  10494. }
  10495. // binary search for the index with largest value smaller than target u distance
  10496. let low = 0, high = il - 1, comparison;
  10497. while ( low <= high ) {
  10498. 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
  10499. comparison = arcLengths[ i ] - targetArcLength;
  10500. if ( comparison < 0 ) {
  10501. low = i + 1;
  10502. } else if ( comparison > 0 ) {
  10503. high = i - 1;
  10504. } else {
  10505. high = i;
  10506. break;
  10507. // DONE
  10508. }
  10509. }
  10510. i = high;
  10511. if ( arcLengths[ i ] === targetArcLength ) {
  10512. return i / ( il - 1 );
  10513. }
  10514. // we could get finer grain at lengths, or use simple interpolation between two points
  10515. const lengthBefore = arcLengths[ i ];
  10516. const lengthAfter = arcLengths[ i + 1 ];
  10517. const segmentLength = lengthAfter - lengthBefore;
  10518. // determine where we are between the 'before' and 'after' points
  10519. const segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  10520. // add that fractional amount to t
  10521. const t = ( i + segmentFraction ) / ( il - 1 );
  10522. return t;
  10523. }
  10524. // Returns a unit vector tangent at t
  10525. // In case any sub curve does not implement its tangent derivation,
  10526. // 2 points a small delta apart will be used to find its gradient
  10527. // which seems to give a reasonable approximation
  10528. getTangent( t, optionalTarget ) {
  10529. const delta = 0.0001;
  10530. let t1 = t - delta;
  10531. let t2 = t + delta;
  10532. // Capping in case of danger
  10533. if ( t1 < 0 ) t1 = 0;
  10534. if ( t2 > 1 ) t2 = 1;
  10535. const pt1 = this.getPoint( t1 );
  10536. const pt2 = this.getPoint( t2 );
  10537. const tangent = optionalTarget || ( ( pt1.isVector2 ) ? new Vector2() : new Vector3() );
  10538. tangent.copy( pt2 ).sub( pt1 ).normalize();
  10539. return tangent;
  10540. }
  10541. getTangentAt( u, optionalTarget ) {
  10542. const t = this.getUtoTmapping( u );
  10543. return this.getTangent( t, optionalTarget );
  10544. }
  10545. computeFrenetFrames( segments, closed ) {
  10546. // see http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  10547. const normal = new Vector3();
  10548. const tangents = [];
  10549. const normals = [];
  10550. const binormals = [];
  10551. const vec = new Vector3();
  10552. const mat = new Matrix4();
  10553. // compute the tangent vectors for each segment on the curve
  10554. for ( let i = 0; i <= segments; i ++ ) {
  10555. const u = i / segments;
  10556. tangents[ i ] = this.getTangentAt( u, new Vector3() );
  10557. }
  10558. // select an initial normal vector perpendicular to the first tangent vector,
  10559. // and in the direction of the minimum tangent xyz component
  10560. normals[ 0 ] = new Vector3();
  10561. binormals[ 0 ] = new Vector3();
  10562. let min = Number.MAX_VALUE;
  10563. const tx = Math.abs( tangents[ 0 ].x );
  10564. const ty = Math.abs( tangents[ 0 ].y );
  10565. const tz = Math.abs( tangents[ 0 ].z );
  10566. if ( tx <= min ) {
  10567. min = tx;
  10568. normal.set( 1, 0, 0 );
  10569. }
  10570. if ( ty <= min ) {
  10571. min = ty;
  10572. normal.set( 0, 1, 0 );
  10573. }
  10574. if ( tz <= min ) {
  10575. normal.set( 0, 0, 1 );
  10576. }
  10577. vec.crossVectors( tangents[ 0 ], normal ).normalize();
  10578. normals[ 0 ].crossVectors( tangents[ 0 ], vec );
  10579. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] );
  10580. // compute the slowly-varying normal and binormal vectors for each segment on the curve
  10581. for ( let i = 1; i <= segments; i ++ ) {
  10582. normals[ i ] = normals[ i - 1 ].clone();
  10583. binormals[ i ] = binormals[ i - 1 ].clone();
  10584. vec.crossVectors( tangents[ i - 1 ], tangents[ i ] );
  10585. if ( vec.length() > Number.EPSILON ) {
  10586. vec.normalize();
  10587. const theta = Math.acos( clamp$1( tangents[ i - 1 ].dot( tangents[ i ] ), - 1, 1 ) ); // clamp for floating pt errors
  10588. normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) );
  10589. }
  10590. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  10591. }
  10592. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  10593. if ( closed === true ) {
  10594. let theta = Math.acos( clamp$1( normals[ 0 ].dot( normals[ segments ] ), - 1, 1 ) );
  10595. theta /= segments;
  10596. if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ segments ] ) ) > 0 ) {
  10597. theta = - theta;
  10598. }
  10599. for ( let i = 1; i <= segments; i ++ ) {
  10600. // twist a little...
  10601. normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) );
  10602. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  10603. }
  10604. }
  10605. return {
  10606. tangents: tangents,
  10607. normals: normals,
  10608. binormals: binormals
  10609. };
  10610. }
  10611. clone() {
  10612. return new this.constructor().copy( this );
  10613. }
  10614. copy( source ) {
  10615. this.arcLengthDivisions = source.arcLengthDivisions;
  10616. return this;
  10617. }
  10618. toJSON() {
  10619. const data = {
  10620. metadata: {
  10621. version: 4.6,
  10622. type: 'Curve',
  10623. generator: 'Curve.toJSON'
  10624. }
  10625. };
  10626. data.arcLengthDivisions = this.arcLengthDivisions;
  10627. data.type = this.type;
  10628. return data;
  10629. }
  10630. fromJSON( json ) {
  10631. this.arcLengthDivisions = json.arcLengthDivisions;
  10632. return this;
  10633. }
  10634. }
  10635. class EllipseCurve extends Curve {
  10636. constructor( aX = 0, aY = 0, xRadius = 1, yRadius = 1, aStartAngle = 0, aEndAngle = Math.PI * 2, aClockwise = false, aRotation = 0 ) {
  10637. super();
  10638. this.isEllipseCurve = true;
  10639. this.type = 'EllipseCurve';
  10640. this.aX = aX;
  10641. this.aY = aY;
  10642. this.xRadius = xRadius;
  10643. this.yRadius = yRadius;
  10644. this.aStartAngle = aStartAngle;
  10645. this.aEndAngle = aEndAngle;
  10646. this.aClockwise = aClockwise;
  10647. this.aRotation = aRotation;
  10648. }
  10649. getPoint( t, optionalTarget = new Vector2() ) {
  10650. const point = optionalTarget;
  10651. const twoPi = Math.PI * 2;
  10652. let deltaAngle = this.aEndAngle - this.aStartAngle;
  10653. const samePoints = Math.abs( deltaAngle ) < Number.EPSILON;
  10654. // ensures that deltaAngle is 0 .. 2 PI
  10655. while ( deltaAngle < 0 ) deltaAngle += twoPi;
  10656. while ( deltaAngle > twoPi ) deltaAngle -= twoPi;
  10657. if ( deltaAngle < Number.EPSILON ) {
  10658. if ( samePoints ) {
  10659. deltaAngle = 0;
  10660. } else {
  10661. deltaAngle = twoPi;
  10662. }
  10663. }
  10664. if ( this.aClockwise === true && ! samePoints ) {
  10665. if ( deltaAngle === twoPi ) {
  10666. deltaAngle = - twoPi;
  10667. } else {
  10668. deltaAngle = deltaAngle - twoPi;
  10669. }
  10670. }
  10671. const angle = this.aStartAngle + t * deltaAngle;
  10672. let x = this.aX + this.xRadius * Math.cos( angle );
  10673. let y = this.aY + this.yRadius * Math.sin( angle );
  10674. if ( this.aRotation !== 0 ) {
  10675. const cos = Math.cos( this.aRotation );
  10676. const sin = Math.sin( this.aRotation );
  10677. const tx = x - this.aX;
  10678. const ty = y - this.aY;
  10679. // Rotate the point about the center of the ellipse.
  10680. x = tx * cos - ty * sin + this.aX;
  10681. y = tx * sin + ty * cos + this.aY;
  10682. }
  10683. return point.set( x, y );
  10684. }
  10685. copy( source ) {
  10686. super.copy( source );
  10687. this.aX = source.aX;
  10688. this.aY = source.aY;
  10689. this.xRadius = source.xRadius;
  10690. this.yRadius = source.yRadius;
  10691. this.aStartAngle = source.aStartAngle;
  10692. this.aEndAngle = source.aEndAngle;
  10693. this.aClockwise = source.aClockwise;
  10694. this.aRotation = source.aRotation;
  10695. return this;
  10696. }
  10697. toJSON() {
  10698. const data = super.toJSON();
  10699. data.aX = this.aX;
  10700. data.aY = this.aY;
  10701. data.xRadius = this.xRadius;
  10702. data.yRadius = this.yRadius;
  10703. data.aStartAngle = this.aStartAngle;
  10704. data.aEndAngle = this.aEndAngle;
  10705. data.aClockwise = this.aClockwise;
  10706. data.aRotation = this.aRotation;
  10707. return data;
  10708. }
  10709. fromJSON( json ) {
  10710. super.fromJSON( json );
  10711. this.aX = json.aX;
  10712. this.aY = json.aY;
  10713. this.xRadius = json.xRadius;
  10714. this.yRadius = json.yRadius;
  10715. this.aStartAngle = json.aStartAngle;
  10716. this.aEndAngle = json.aEndAngle;
  10717. this.aClockwise = json.aClockwise;
  10718. this.aRotation = json.aRotation;
  10719. return this;
  10720. }
  10721. }
  10722. class ArcCurve extends EllipseCurve {
  10723. constructor( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  10724. super( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  10725. this.isArcCurve = true;
  10726. this.type = 'ArcCurve';
  10727. }
  10728. }
  10729. /**
  10730. * Centripetal CatmullRom Curve - which is useful for avoiding
  10731. * cusps and self-intersections in non-uniform catmull rom curves.
  10732. * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf
  10733. *
  10734. * curve.type accepts centripetal(default), chordal and catmullrom
  10735. * curve.tension is used for catmullrom which defaults to 0.5
  10736. */
  10737. /*
  10738. Based on an optimized c++ solution in
  10739. - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/
  10740. - http://ideone.com/NoEbVM
  10741. This CubicPoly class could be used for reusing some variables and calculations,
  10742. but for three.js curve use, it could be possible inlined and flatten into a single function call
  10743. which can be placed in CurveUtils.
  10744. */
  10745. function CubicPoly() {
  10746. let c0 = 0, c1 = 0, c2 = 0, c3 = 0;
  10747. /*
  10748. * Compute coefficients for a cubic polynomial
  10749. * p(s) = c0 + c1*s + c2*s^2 + c3*s^3
  10750. * such that
  10751. * p(0) = x0, p(1) = x1
  10752. * and
  10753. * p'(0) = t0, p'(1) = t1.
  10754. */
  10755. function init( x0, x1, t0, t1 ) {
  10756. c0 = x0;
  10757. c1 = t0;
  10758. c2 = - 3 * x0 + 3 * x1 - 2 * t0 - t1;
  10759. c3 = 2 * x0 - 2 * x1 + t0 + t1;
  10760. }
  10761. return {
  10762. initCatmullRom: function ( x0, x1, x2, x3, tension ) {
  10763. init( x1, x2, tension * ( x2 - x0 ), tension * ( x3 - x1 ) );
  10764. },
  10765. initNonuniformCatmullRom: function ( x0, x1, x2, x3, dt0, dt1, dt2 ) {
  10766. // compute tangents when parameterized in [t1,t2]
  10767. let t1 = ( x1 - x0 ) / dt0 - ( x2 - x0 ) / ( dt0 + dt1 ) + ( x2 - x1 ) / dt1;
  10768. let t2 = ( x2 - x1 ) / dt1 - ( x3 - x1 ) / ( dt1 + dt2 ) + ( x3 - x2 ) / dt2;
  10769. // rescale tangents for parametrization in [0,1]
  10770. t1 *= dt1;
  10771. t2 *= dt1;
  10772. init( x1, x2, t1, t2 );
  10773. },
  10774. calc: function ( t ) {
  10775. const t2 = t * t;
  10776. const t3 = t2 * t;
  10777. return c0 + c1 * t + c2 * t2 + c3 * t3;
  10778. }
  10779. };
  10780. }
  10781. //
  10782. const tmp = /*@__PURE__*/ new Vector3();
  10783. const px = /*@__PURE__*/ new CubicPoly();
  10784. const py = /*@__PURE__*/ new CubicPoly();
  10785. const pz = /*@__PURE__*/ new CubicPoly();
  10786. class CatmullRomCurve3 extends Curve {
  10787. constructor( points = [], closed = false, curveType = 'centripetal', tension = 0.5 ) {
  10788. super();
  10789. this.isCatmullRomCurve3 = true;
  10790. this.type = 'CatmullRomCurve3';
  10791. this.points = points;
  10792. this.closed = closed;
  10793. this.curveType = curveType;
  10794. this.tension = tension;
  10795. }
  10796. getPoint( t, optionalTarget = new Vector3() ) {
  10797. const point = optionalTarget;
  10798. const points = this.points;
  10799. const l = points.length;
  10800. const p = ( l - ( this.closed ? 0 : 1 ) ) * t;
  10801. let intPoint = Math.floor( p );
  10802. let weight = p - intPoint;
  10803. if ( this.closed ) {
  10804. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / l ) + 1 ) * l;
  10805. } else if ( weight === 0 && intPoint === l - 1 ) {
  10806. intPoint = l - 2;
  10807. weight = 1;
  10808. }
  10809. let p0, p3; // 4 points (p1 & p2 defined below)
  10810. if ( this.closed || intPoint > 0 ) {
  10811. p0 = points[ ( intPoint - 1 ) % l ];
  10812. } else {
  10813. // extrapolate first point
  10814. tmp.subVectors( points[ 0 ], points[ 1 ] ).add( points[ 0 ] );
  10815. p0 = tmp;
  10816. }
  10817. const p1 = points[ intPoint % l ];
  10818. const p2 = points[ ( intPoint + 1 ) % l ];
  10819. if ( this.closed || intPoint + 2 < l ) {
  10820. p3 = points[ ( intPoint + 2 ) % l ];
  10821. } else {
  10822. // extrapolate last point
  10823. tmp.subVectors( points[ l - 1 ], points[ l - 2 ] ).add( points[ l - 1 ] );
  10824. p3 = tmp;
  10825. }
  10826. if ( this.curveType === 'centripetal' || this.curveType === 'chordal' ) {
  10827. // init Centripetal / Chordal Catmull-Rom
  10828. const pow = this.curveType === 'chordal' ? 0.5 : 0.25;
  10829. let dt0 = Math.pow( p0.distanceToSquared( p1 ), pow );
  10830. let dt1 = Math.pow( p1.distanceToSquared( p2 ), pow );
  10831. let dt2 = Math.pow( p2.distanceToSquared( p3 ), pow );
  10832. // safety check for repeated points
  10833. if ( dt1 < 1e-4 ) dt1 = 1.0;
  10834. if ( dt0 < 1e-4 ) dt0 = dt1;
  10835. if ( dt2 < 1e-4 ) dt2 = dt1;
  10836. px.initNonuniformCatmullRom( p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2 );
  10837. py.initNonuniformCatmullRom( p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2 );
  10838. pz.initNonuniformCatmullRom( p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2 );
  10839. } else if ( this.curveType === 'catmullrom' ) {
  10840. px.initCatmullRom( p0.x, p1.x, p2.x, p3.x, this.tension );
  10841. py.initCatmullRom( p0.y, p1.y, p2.y, p3.y, this.tension );
  10842. pz.initCatmullRom( p0.z, p1.z, p2.z, p3.z, this.tension );
  10843. }
  10844. point.set(
  10845. px.calc( weight ),
  10846. py.calc( weight ),
  10847. pz.calc( weight )
  10848. );
  10849. return point;
  10850. }
  10851. copy( source ) {
  10852. super.copy( source );
  10853. this.points = [];
  10854. for ( let i = 0, l = source.points.length; i < l; i ++ ) {
  10855. const point = source.points[ i ];
  10856. this.points.push( point.clone() );
  10857. }
  10858. this.closed = source.closed;
  10859. this.curveType = source.curveType;
  10860. this.tension = source.tension;
  10861. return this;
  10862. }
  10863. toJSON() {
  10864. const data = super.toJSON();
  10865. data.points = [];
  10866. for ( let i = 0, l = this.points.length; i < l; i ++ ) {
  10867. const point = this.points[ i ];
  10868. data.points.push( point.toArray() );
  10869. }
  10870. data.closed = this.closed;
  10871. data.curveType = this.curveType;
  10872. data.tension = this.tension;
  10873. return data;
  10874. }
  10875. fromJSON( json ) {
  10876. super.fromJSON( json );
  10877. this.points = [];
  10878. for ( let i = 0, l = json.points.length; i < l; i ++ ) {
  10879. const point = json.points[ i ];
  10880. this.points.push( new Vector3().fromArray( point ) );
  10881. }
  10882. this.closed = json.closed;
  10883. this.curveType = json.curveType;
  10884. this.tension = json.tension;
  10885. return this;
  10886. }
  10887. }
  10888. /**
  10889. * Bezier Curves formulas obtained from
  10890. * https://en.wikipedia.org/wiki/B%C3%A9zier_curve
  10891. */
  10892. function CatmullRom( t, p0, p1, p2, p3 ) {
  10893. const v0 = ( p2 - p0 ) * 0.5;
  10894. const v1 = ( p3 - p1 ) * 0.5;
  10895. const t2 = t * t;
  10896. const t3 = t * t2;
  10897. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  10898. }
  10899. //
  10900. function QuadraticBezierP0( t, p ) {
  10901. const k = 1 - t;
  10902. return k * k * p;
  10903. }
  10904. function QuadraticBezierP1( t, p ) {
  10905. return 2 * ( 1 - t ) * t * p;
  10906. }
  10907. function QuadraticBezierP2( t, p ) {
  10908. return t * t * p;
  10909. }
  10910. function QuadraticBezier( t, p0, p1, p2 ) {
  10911. return QuadraticBezierP0( t, p0 ) + QuadraticBezierP1( t, p1 ) +
  10912. QuadraticBezierP2( t, p2 );
  10913. }
  10914. //
  10915. function CubicBezierP0( t, p ) {
  10916. const k = 1 - t;
  10917. return k * k * k * p;
  10918. }
  10919. function CubicBezierP1( t, p ) {
  10920. const k = 1 - t;
  10921. return 3 * k * k * t * p;
  10922. }
  10923. function CubicBezierP2( t, p ) {
  10924. return 3 * ( 1 - t ) * t * t * p;
  10925. }
  10926. function CubicBezierP3( t, p ) {
  10927. return t * t * t * p;
  10928. }
  10929. function CubicBezier( t, p0, p1, p2, p3 ) {
  10930. return CubicBezierP0( t, p0 ) + CubicBezierP1( t, p1 ) + CubicBezierP2( t, p2 ) +
  10931. CubicBezierP3( t, p3 );
  10932. }
  10933. class CubicBezierCurve extends Curve {
  10934. constructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2(), v3 = new Vector2() ) {
  10935. super();
  10936. this.isCubicBezierCurve = true;
  10937. this.type = 'CubicBezierCurve';
  10938. this.v0 = v0;
  10939. this.v1 = v1;
  10940. this.v2 = v2;
  10941. this.v3 = v3;
  10942. }
  10943. getPoint( t, optionalTarget = new Vector2() ) {
  10944. const point = optionalTarget;
  10945. const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  10946. point.set(
  10947. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  10948. CubicBezier( t, v0.y, v1.y, v2.y, v3.y )
  10949. );
  10950. return point;
  10951. }
  10952. copy( source ) {
  10953. super.copy( source );
  10954. this.v0.copy( source.v0 );
  10955. this.v1.copy( source.v1 );
  10956. this.v2.copy( source.v2 );
  10957. this.v3.copy( source.v3 );
  10958. return this;
  10959. }
  10960. toJSON() {
  10961. const data = super.toJSON();
  10962. data.v0 = this.v0.toArray();
  10963. data.v1 = this.v1.toArray();
  10964. data.v2 = this.v2.toArray();
  10965. data.v3 = this.v3.toArray();
  10966. return data;
  10967. }
  10968. fromJSON( json ) {
  10969. super.fromJSON( json );
  10970. this.v0.fromArray( json.v0 );
  10971. this.v1.fromArray( json.v1 );
  10972. this.v2.fromArray( json.v2 );
  10973. this.v3.fromArray( json.v3 );
  10974. return this;
  10975. }
  10976. }
  10977. class CubicBezierCurve3 extends Curve {
  10978. constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3(), v3 = new Vector3() ) {
  10979. super();
  10980. this.isCubicBezierCurve3 = true;
  10981. this.type = 'CubicBezierCurve3';
  10982. this.v0 = v0;
  10983. this.v1 = v1;
  10984. this.v2 = v2;
  10985. this.v3 = v3;
  10986. }
  10987. getPoint( t, optionalTarget = new Vector3() ) {
  10988. const point = optionalTarget;
  10989. const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  10990. point.set(
  10991. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  10992. CubicBezier( t, v0.y, v1.y, v2.y, v3.y ),
  10993. CubicBezier( t, v0.z, v1.z, v2.z, v3.z )
  10994. );
  10995. return point;
  10996. }
  10997. copy( source ) {
  10998. super.copy( source );
  10999. this.v0.copy( source.v0 );
  11000. this.v1.copy( source.v1 );
  11001. this.v2.copy( source.v2 );
  11002. this.v3.copy( source.v3 );
  11003. return this;
  11004. }
  11005. toJSON() {
  11006. const data = super.toJSON();
  11007. data.v0 = this.v0.toArray();
  11008. data.v1 = this.v1.toArray();
  11009. data.v2 = this.v2.toArray();
  11010. data.v3 = this.v3.toArray();
  11011. return data;
  11012. }
  11013. fromJSON( json ) {
  11014. super.fromJSON( json );
  11015. this.v0.fromArray( json.v0 );
  11016. this.v1.fromArray( json.v1 );
  11017. this.v2.fromArray( json.v2 );
  11018. this.v3.fromArray( json.v3 );
  11019. return this;
  11020. }
  11021. }
  11022. class LineCurve extends Curve {
  11023. constructor( v1 = new Vector2(), v2 = new Vector2() ) {
  11024. super();
  11025. this.isLineCurve = true;
  11026. this.type = 'LineCurve';
  11027. this.v1 = v1;
  11028. this.v2 = v2;
  11029. }
  11030. getPoint( t, optionalTarget = new Vector2() ) {
  11031. const point = optionalTarget;
  11032. if ( t === 1 ) {
  11033. point.copy( this.v2 );
  11034. } else {
  11035. point.copy( this.v2 ).sub( this.v1 );
  11036. point.multiplyScalar( t ).add( this.v1 );
  11037. }
  11038. return point;
  11039. }
  11040. // Line curve is linear, so we can overwrite default getPointAt
  11041. getPointAt( u, optionalTarget ) {
  11042. return this.getPoint( u, optionalTarget );
  11043. }
  11044. getTangent( t, optionalTarget = new Vector2() ) {
  11045. return optionalTarget.subVectors( this.v2, this.v1 ).normalize();
  11046. }
  11047. getTangentAt( u, optionalTarget ) {
  11048. return this.getTangent( u, optionalTarget );
  11049. }
  11050. copy( source ) {
  11051. super.copy( source );
  11052. this.v1.copy( source.v1 );
  11053. this.v2.copy( source.v2 );
  11054. return this;
  11055. }
  11056. toJSON() {
  11057. const data = super.toJSON();
  11058. data.v1 = this.v1.toArray();
  11059. data.v2 = this.v2.toArray();
  11060. return data;
  11061. }
  11062. fromJSON( json ) {
  11063. super.fromJSON( json );
  11064. this.v1.fromArray( json.v1 );
  11065. this.v2.fromArray( json.v2 );
  11066. return this;
  11067. }
  11068. }
  11069. class LineCurve3 extends Curve {
  11070. constructor( v1 = new Vector3(), v2 = new Vector3() ) {
  11071. super();
  11072. this.isLineCurve3 = true;
  11073. this.type = 'LineCurve3';
  11074. this.v1 = v1;
  11075. this.v2 = v2;
  11076. }
  11077. getPoint( t, optionalTarget = new Vector3() ) {
  11078. const point = optionalTarget;
  11079. if ( t === 1 ) {
  11080. point.copy( this.v2 );
  11081. } else {
  11082. point.copy( this.v2 ).sub( this.v1 );
  11083. point.multiplyScalar( t ).add( this.v1 );
  11084. }
  11085. return point;
  11086. }
  11087. // Line curve is linear, so we can overwrite default getPointAt
  11088. getPointAt( u, optionalTarget ) {
  11089. return this.getPoint( u, optionalTarget );
  11090. }
  11091. getTangent( t, optionalTarget = new Vector3() ) {
  11092. return optionalTarget.subVectors( this.v2, this.v1 ).normalize();
  11093. }
  11094. getTangentAt( u, optionalTarget ) {
  11095. return this.getTangent( u, optionalTarget );
  11096. }
  11097. copy( source ) {
  11098. super.copy( source );
  11099. this.v1.copy( source.v1 );
  11100. this.v2.copy( source.v2 );
  11101. return this;
  11102. }
  11103. toJSON() {
  11104. const data = super.toJSON();
  11105. data.v1 = this.v1.toArray();
  11106. data.v2 = this.v2.toArray();
  11107. return data;
  11108. }
  11109. fromJSON( json ) {
  11110. super.fromJSON( json );
  11111. this.v1.fromArray( json.v1 );
  11112. this.v2.fromArray( json.v2 );
  11113. return this;
  11114. }
  11115. }
  11116. class QuadraticBezierCurve extends Curve {
  11117. constructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2() ) {
  11118. super();
  11119. this.isQuadraticBezierCurve = true;
  11120. this.type = 'QuadraticBezierCurve';
  11121. this.v0 = v0;
  11122. this.v1 = v1;
  11123. this.v2 = v2;
  11124. }
  11125. getPoint( t, optionalTarget = new Vector2() ) {
  11126. const point = optionalTarget;
  11127. const v0 = this.v0, v1 = this.v1, v2 = this.v2;
  11128. point.set(
  11129. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  11130. QuadraticBezier( t, v0.y, v1.y, v2.y )
  11131. );
  11132. return point;
  11133. }
  11134. copy( source ) {
  11135. super.copy( source );
  11136. this.v0.copy( source.v0 );
  11137. this.v1.copy( source.v1 );
  11138. this.v2.copy( source.v2 );
  11139. return this;
  11140. }
  11141. toJSON() {
  11142. const data = super.toJSON();
  11143. data.v0 = this.v0.toArray();
  11144. data.v1 = this.v1.toArray();
  11145. data.v2 = this.v2.toArray();
  11146. return data;
  11147. }
  11148. fromJSON( json ) {
  11149. super.fromJSON( json );
  11150. this.v0.fromArray( json.v0 );
  11151. this.v1.fromArray( json.v1 );
  11152. this.v2.fromArray( json.v2 );
  11153. return this;
  11154. }
  11155. }
  11156. class QuadraticBezierCurve3 extends Curve {
  11157. constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3() ) {
  11158. super();
  11159. this.isQuadraticBezierCurve3 = true;
  11160. this.type = 'QuadraticBezierCurve3';
  11161. this.v0 = v0;
  11162. this.v1 = v1;
  11163. this.v2 = v2;
  11164. }
  11165. getPoint( t, optionalTarget = new Vector3() ) {
  11166. const point = optionalTarget;
  11167. const v0 = this.v0, v1 = this.v1, v2 = this.v2;
  11168. point.set(
  11169. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  11170. QuadraticBezier( t, v0.y, v1.y, v2.y ),
  11171. QuadraticBezier( t, v0.z, v1.z, v2.z )
  11172. );
  11173. return point;
  11174. }
  11175. copy( source ) {
  11176. super.copy( source );
  11177. this.v0.copy( source.v0 );
  11178. this.v1.copy( source.v1 );
  11179. this.v2.copy( source.v2 );
  11180. return this;
  11181. }
  11182. toJSON() {
  11183. const data = super.toJSON();
  11184. data.v0 = this.v0.toArray();
  11185. data.v1 = this.v1.toArray();
  11186. data.v2 = this.v2.toArray();
  11187. return data;
  11188. }
  11189. fromJSON( json ) {
  11190. super.fromJSON( json );
  11191. this.v0.fromArray( json.v0 );
  11192. this.v1.fromArray( json.v1 );
  11193. this.v2.fromArray( json.v2 );
  11194. return this;
  11195. }
  11196. }
  11197. class SplineCurve extends Curve {
  11198. constructor( points = [] ) {
  11199. super();
  11200. this.isSplineCurve = true;
  11201. this.type = 'SplineCurve';
  11202. this.points = points;
  11203. }
  11204. getPoint( t, optionalTarget = new Vector2() ) {
  11205. const point = optionalTarget;
  11206. const points = this.points;
  11207. const p = ( points.length - 1 ) * t;
  11208. const intPoint = Math.floor( p );
  11209. const weight = p - intPoint;
  11210. const p0 = points[ intPoint === 0 ? intPoint : intPoint - 1 ];
  11211. const p1 = points[ intPoint ];
  11212. const p2 = points[ intPoint > points.length - 2 ? points.length - 1 : intPoint + 1 ];
  11213. const p3 = points[ intPoint > points.length - 3 ? points.length - 1 : intPoint + 2 ];
  11214. point.set(
  11215. CatmullRom( weight, p0.x, p1.x, p2.x, p3.x ),
  11216. CatmullRom( weight, p0.y, p1.y, p2.y, p3.y )
  11217. );
  11218. return point;
  11219. }
  11220. copy( source ) {
  11221. super.copy( source );
  11222. this.points = [];
  11223. for ( let i = 0, l = source.points.length; i < l; i ++ ) {
  11224. const point = source.points[ i ];
  11225. this.points.push( point.clone() );
  11226. }
  11227. return this;
  11228. }
  11229. toJSON() {
  11230. const data = super.toJSON();
  11231. data.points = [];
  11232. for ( let i = 0, l = this.points.length; i < l; i ++ ) {
  11233. const point = this.points[ i ];
  11234. data.points.push( point.toArray() );
  11235. }
  11236. return data;
  11237. }
  11238. fromJSON( json ) {
  11239. super.fromJSON( json );
  11240. this.points = [];
  11241. for ( let i = 0, l = json.points.length; i < l; i ++ ) {
  11242. const point = json.points[ i ];
  11243. this.points.push( new Vector2().fromArray( point ) );
  11244. }
  11245. return this;
  11246. }
  11247. }
  11248. var Curves = /*#__PURE__*/Object.freeze({
  11249. __proto__: null,
  11250. ArcCurve: ArcCurve,
  11251. CatmullRomCurve3: CatmullRomCurve3,
  11252. CubicBezierCurve: CubicBezierCurve,
  11253. CubicBezierCurve3: CubicBezierCurve3,
  11254. EllipseCurve: EllipseCurve,
  11255. LineCurve: LineCurve,
  11256. LineCurve3: LineCurve3,
  11257. QuadraticBezierCurve: QuadraticBezierCurve,
  11258. QuadraticBezierCurve3: QuadraticBezierCurve3,
  11259. SplineCurve: SplineCurve
  11260. });
  11261. /**************************************************************
  11262. * Curved Path - a curve path is simply a array of connected
  11263. * curves, but retains the api of a curve
  11264. **************************************************************/
  11265. class CurvePath extends Curve {
  11266. constructor() {
  11267. super();
  11268. this.type = 'CurvePath';
  11269. this.curves = [];
  11270. this.autoClose = false; // Automatically closes the path
  11271. }
  11272. add( curve ) {
  11273. this.curves.push( curve );
  11274. }
  11275. closePath() {
  11276. // Add a line curve if start and end of lines are not connected
  11277. const startPoint = this.curves[ 0 ].getPoint( 0 );
  11278. const endPoint = this.curves[ this.curves.length - 1 ].getPoint( 1 );
  11279. if ( ! startPoint.equals( endPoint ) ) {
  11280. const lineType = ( startPoint.isVector2 === true ) ? 'LineCurve' : 'LineCurve3';
  11281. this.curves.push( new Curves[ lineType ]( endPoint, startPoint ) );
  11282. }
  11283. return this;
  11284. }
  11285. // To get accurate point with reference to
  11286. // entire path distance at time t,
  11287. // following has to be done:
  11288. // 1. Length of each sub path have to be known
  11289. // 2. Locate and identify type of curve
  11290. // 3. Get t for the curve
  11291. // 4. Return curve.getPointAt(t')
  11292. getPoint( t, optionalTarget ) {
  11293. const d = t * this.getLength();
  11294. const curveLengths = this.getCurveLengths();
  11295. let i = 0;
  11296. // To think about boundaries points.
  11297. while ( i < curveLengths.length ) {
  11298. if ( curveLengths[ i ] >= d ) {
  11299. const diff = curveLengths[ i ] - d;
  11300. const curve = this.curves[ i ];
  11301. const segmentLength = curve.getLength();
  11302. const u = segmentLength === 0 ? 0 : 1 - diff / segmentLength;
  11303. return curve.getPointAt( u, optionalTarget );
  11304. }
  11305. i ++;
  11306. }
  11307. return null;
  11308. // loop where sum != 0, sum > d , sum+1 <d
  11309. }
  11310. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  11311. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  11312. // getPoint() depends on getLength
  11313. getLength() {
  11314. const lens = this.getCurveLengths();
  11315. return lens[ lens.length - 1 ];
  11316. }
  11317. // cacheLengths must be recalculated.
  11318. updateArcLengths() {
  11319. this.needsUpdate = true;
  11320. this.cacheLengths = null;
  11321. this.getCurveLengths();
  11322. }
  11323. // Compute lengths and cache them
  11324. // We cannot overwrite getLengths() because UtoT mapping uses it.
  11325. getCurveLengths() {
  11326. // We use cache values if curves and cache array are same length
  11327. if ( this.cacheLengths && this.cacheLengths.length === this.curves.length ) {
  11328. return this.cacheLengths;
  11329. }
  11330. // Get length of sub-curve
  11331. // Push sums into cached array
  11332. const lengths = [];
  11333. let sums = 0;
  11334. for ( let i = 0, l = this.curves.length; i < l; i ++ ) {
  11335. sums += this.curves[ i ].getLength();
  11336. lengths.push( sums );
  11337. }
  11338. this.cacheLengths = lengths;
  11339. return lengths;
  11340. }
  11341. getSpacedPoints( divisions = 40 ) {
  11342. const points = [];
  11343. for ( let i = 0; i <= divisions; i ++ ) {
  11344. points.push( this.getPoint( i / divisions ) );
  11345. }
  11346. if ( this.autoClose ) {
  11347. points.push( points[ 0 ] );
  11348. }
  11349. return points;
  11350. }
  11351. getPoints( divisions = 12 ) {
  11352. const points = [];
  11353. let last;
  11354. for ( let i = 0, curves = this.curves; i < curves.length; i ++ ) {
  11355. const curve = curves[ i ];
  11356. const resolution = curve.isEllipseCurve ? divisions * 2
  11357. : ( curve.isLineCurve || curve.isLineCurve3 ) ? 1
  11358. : curve.isSplineCurve ? divisions * curve.points.length
  11359. : divisions;
  11360. const pts = curve.getPoints( resolution );
  11361. for ( let j = 0; j < pts.length; j ++ ) {
  11362. const point = pts[ j ];
  11363. if ( last && last.equals( point ) ) continue; // ensures no consecutive points are duplicates
  11364. points.push( point );
  11365. last = point;
  11366. }
  11367. }
  11368. if ( this.autoClose && points.length > 1 && ! points[ points.length - 1 ].equals( points[ 0 ] ) ) {
  11369. points.push( points[ 0 ] );
  11370. }
  11371. return points;
  11372. }
  11373. copy( source ) {
  11374. super.copy( source );
  11375. this.curves = [];
  11376. for ( let i = 0, l = source.curves.length; i < l; i ++ ) {
  11377. const curve = source.curves[ i ];
  11378. this.curves.push( curve.clone() );
  11379. }
  11380. this.autoClose = source.autoClose;
  11381. return this;
  11382. }
  11383. toJSON() {
  11384. const data = super.toJSON();
  11385. data.autoClose = this.autoClose;
  11386. data.curves = [];
  11387. for ( let i = 0, l = this.curves.length; i < l; i ++ ) {
  11388. const curve = this.curves[ i ];
  11389. data.curves.push( curve.toJSON() );
  11390. }
  11391. return data;
  11392. }
  11393. fromJSON( json ) {
  11394. super.fromJSON( json );
  11395. this.autoClose = json.autoClose;
  11396. this.curves = [];
  11397. for ( let i = 0, l = json.curves.length; i < l; i ++ ) {
  11398. const curve = json.curves[ i ];
  11399. this.curves.push( new Curves[ curve.type ]().fromJSON( curve ) );
  11400. }
  11401. return this;
  11402. }
  11403. }
  11404. class Path extends CurvePath {
  11405. constructor( points ) {
  11406. super();
  11407. this.type = 'Path';
  11408. this.currentPoint = new Vector2();
  11409. if ( points ) {
  11410. this.setFromPoints( points );
  11411. }
  11412. }
  11413. setFromPoints( points ) {
  11414. this.moveTo( points[ 0 ].x, points[ 0 ].y );
  11415. for ( let i = 1, l = points.length; i < l; i ++ ) {
  11416. this.lineTo( points[ i ].x, points[ i ].y );
  11417. }
  11418. return this;
  11419. }
  11420. moveTo( x, y ) {
  11421. this.currentPoint.set( x, y ); // TODO consider referencing vectors instead of copying?
  11422. return this;
  11423. }
  11424. lineTo( x, y ) {
  11425. const curve = new LineCurve( this.currentPoint.clone(), new Vector2( x, y ) );
  11426. this.curves.push( curve );
  11427. this.currentPoint.set( x, y );
  11428. return this;
  11429. }
  11430. quadraticCurveTo( aCPx, aCPy, aX, aY ) {
  11431. const curve = new QuadraticBezierCurve(
  11432. this.currentPoint.clone(),
  11433. new Vector2( aCPx, aCPy ),
  11434. new Vector2( aX, aY )
  11435. );
  11436. this.curves.push( curve );
  11437. this.currentPoint.set( aX, aY );
  11438. return this;
  11439. }
  11440. bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  11441. const curve = new CubicBezierCurve(
  11442. this.currentPoint.clone(),
  11443. new Vector2( aCP1x, aCP1y ),
  11444. new Vector2( aCP2x, aCP2y ),
  11445. new Vector2( aX, aY )
  11446. );
  11447. this.curves.push( curve );
  11448. this.currentPoint.set( aX, aY );
  11449. return this;
  11450. }
  11451. splineThru( pts /*Array of Vector*/ ) {
  11452. const npts = [ this.currentPoint.clone() ].concat( pts );
  11453. const curve = new SplineCurve( npts );
  11454. this.curves.push( curve );
  11455. this.currentPoint.copy( pts[ pts.length - 1 ] );
  11456. return this;
  11457. }
  11458. arc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  11459. const x0 = this.currentPoint.x;
  11460. const y0 = this.currentPoint.y;
  11461. this.absarc( aX + x0, aY + y0, aRadius,
  11462. aStartAngle, aEndAngle, aClockwise );
  11463. return this;
  11464. }
  11465. absarc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  11466. this.absellipse( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  11467. return this;
  11468. }
  11469. ellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  11470. const x0 = this.currentPoint.x;
  11471. const y0 = this.currentPoint.y;
  11472. this.absellipse( aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  11473. return this;
  11474. }
  11475. absellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  11476. const curve = new EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  11477. if ( this.curves.length > 0 ) {
  11478. // if a previous curve is present, attempt to join
  11479. const firstPoint = curve.getPoint( 0 );
  11480. if ( ! firstPoint.equals( this.currentPoint ) ) {
  11481. this.lineTo( firstPoint.x, firstPoint.y );
  11482. }
  11483. }
  11484. this.curves.push( curve );
  11485. const lastPoint = curve.getPoint( 1 );
  11486. this.currentPoint.copy( lastPoint );
  11487. return this;
  11488. }
  11489. copy( source ) {
  11490. super.copy( source );
  11491. this.currentPoint.copy( source.currentPoint );
  11492. return this;
  11493. }
  11494. toJSON() {
  11495. const data = super.toJSON();
  11496. data.currentPoint = this.currentPoint.toArray();
  11497. return data;
  11498. }
  11499. fromJSON( json ) {
  11500. super.fromJSON( json );
  11501. this.currentPoint.fromArray( json.currentPoint );
  11502. return this;
  11503. }
  11504. }
  11505. class LatheGeometry extends BufferGeometry {
  11506. 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 ) {
  11507. super();
  11508. this.type = 'LatheGeometry';
  11509. this.parameters = {
  11510. points: points,
  11511. segments: segments,
  11512. phiStart: phiStart,
  11513. phiLength: phiLength
  11514. };
  11515. segments = Math.floor( segments );
  11516. // clamp phiLength so it's in range of [ 0, 2PI ]
  11517. phiLength = clamp$1( phiLength, 0, Math.PI * 2 );
  11518. // buffers
  11519. const indices = [];
  11520. const vertices = [];
  11521. const uvs = [];
  11522. const initNormals = [];
  11523. const normals = [];
  11524. // helper variables
  11525. const inverseSegments = 1.0 / segments;
  11526. const vertex = new Vector3();
  11527. const uv = new Vector2();
  11528. const normal = new Vector3();
  11529. const curNormal = new Vector3();
  11530. const prevNormal = new Vector3();
  11531. let dx = 0;
  11532. let dy = 0;
  11533. // pre-compute normals for initial "meridian"
  11534. for ( let j = 0; j <= ( points.length - 1 ); j ++ ) {
  11535. switch ( j ) {
  11536. case 0: // special handling for 1st vertex on path
  11537. dx = points[ j + 1 ].x - points[ j ].x;
  11538. dy = points[ j + 1 ].y - points[ j ].y;
  11539. normal.x = dy * 1.0;
  11540. normal.y = - dx;
  11541. normal.z = dy * 0.0;
  11542. prevNormal.copy( normal );
  11543. normal.normalize();
  11544. initNormals.push( normal.x, normal.y, normal.z );
  11545. break;
  11546. case ( points.length - 1 ): // special handling for last Vertex on path
  11547. initNormals.push( prevNormal.x, prevNormal.y, prevNormal.z );
  11548. break;
  11549. default: // default handling for all vertices in between
  11550. dx = points[ j + 1 ].x - points[ j ].x;
  11551. dy = points[ j + 1 ].y - points[ j ].y;
  11552. normal.x = dy * 1.0;
  11553. normal.y = - dx;
  11554. normal.z = dy * 0.0;
  11555. curNormal.copy( normal );
  11556. normal.x += prevNormal.x;
  11557. normal.y += prevNormal.y;
  11558. normal.z += prevNormal.z;
  11559. normal.normalize();
  11560. initNormals.push( normal.x, normal.y, normal.z );
  11561. prevNormal.copy( curNormal );
  11562. }
  11563. }
  11564. // generate vertices, uvs and normals
  11565. for ( let i = 0; i <= segments; i ++ ) {
  11566. const phi = phiStart + i * inverseSegments * phiLength;
  11567. const sin = Math.sin( phi );
  11568. const cos = Math.cos( phi );
  11569. for ( let j = 0; j <= ( points.length - 1 ); j ++ ) {
  11570. // vertex
  11571. vertex.x = points[ j ].x * sin;
  11572. vertex.y = points[ j ].y;
  11573. vertex.z = points[ j ].x * cos;
  11574. vertices.push( vertex.x, vertex.y, vertex.z );
  11575. // uv
  11576. uv.x = i / segments;
  11577. uv.y = j / ( points.length - 1 );
  11578. uvs.push( uv.x, uv.y );
  11579. // normal
  11580. const x = initNormals[ 3 * j + 0 ] * sin;
  11581. const y = initNormals[ 3 * j + 1 ];
  11582. const z = initNormals[ 3 * j + 0 ] * cos;
  11583. normals.push( x, y, z );
  11584. }
  11585. }
  11586. // indices
  11587. for ( let i = 0; i < segments; i ++ ) {
  11588. for ( let j = 0; j < ( points.length - 1 ); j ++ ) {
  11589. const base = j + i * points.length;
  11590. const a = base;
  11591. const b = base + points.length;
  11592. const c = base + points.length + 1;
  11593. const d = base + 1;
  11594. // faces
  11595. indices.push( a, b, d );
  11596. indices.push( c, d, b );
  11597. }
  11598. }
  11599. // build geometry
  11600. this.setIndex( indices );
  11601. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  11602. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  11603. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  11604. }
  11605. copy( source ) {
  11606. super.copy( source );
  11607. this.parameters = Object.assign( {}, source.parameters );
  11608. return this;
  11609. }
  11610. static fromJSON( data ) {
  11611. return new LatheGeometry( data.points, data.segments, data.phiStart, data.phiLength );
  11612. }
  11613. }
  11614. class CapsuleGeometry extends LatheGeometry {
  11615. constructor( radius = 1, length = 1, capSegments = 4, radialSegments = 8 ) {
  11616. const path = new Path();
  11617. path.absarc( 0, - length / 2, radius, Math.PI * 1.5, 0 );
  11618. path.absarc( 0, length / 2, radius, 0, Math.PI * 0.5 );
  11619. super( path.getPoints( capSegments ), radialSegments );
  11620. this.type = 'CapsuleGeometry';
  11621. this.parameters = {
  11622. radius: radius,
  11623. length: length,
  11624. capSegments: capSegments,
  11625. radialSegments: radialSegments,
  11626. };
  11627. }
  11628. static fromJSON( data ) {
  11629. return new CapsuleGeometry( data.radius, data.length, data.capSegments, data.radialSegments );
  11630. }
  11631. }
  11632. class CircleGeometry extends BufferGeometry {
  11633. constructor( radius = 1, segments = 32, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  11634. super();
  11635. this.type = 'CircleGeometry';
  11636. this.parameters = {
  11637. radius: radius,
  11638. segments: segments,
  11639. thetaStart: thetaStart,
  11640. thetaLength: thetaLength
  11641. };
  11642. segments = Math.max( 3, segments );
  11643. // buffers
  11644. const indices = [];
  11645. const vertices = [];
  11646. const normals = [];
  11647. const uvs = [];
  11648. // helper variables
  11649. const vertex = new Vector3();
  11650. const uv = new Vector2();
  11651. // center point
  11652. vertices.push( 0, 0, 0 );
  11653. normals.push( 0, 0, 1 );
  11654. uvs.push( 0.5, 0.5 );
  11655. for ( let s = 0, i = 3; s <= segments; s ++, i += 3 ) {
  11656. const segment = thetaStart + s / segments * thetaLength;
  11657. // vertex
  11658. vertex.x = radius * Math.cos( segment );
  11659. vertex.y = radius * Math.sin( segment );
  11660. vertices.push( vertex.x, vertex.y, vertex.z );
  11661. // normal
  11662. normals.push( 0, 0, 1 );
  11663. // uvs
  11664. uv.x = ( vertices[ i ] / radius + 1 ) / 2;
  11665. uv.y = ( vertices[ i + 1 ] / radius + 1 ) / 2;
  11666. uvs.push( uv.x, uv.y );
  11667. }
  11668. // indices
  11669. for ( let i = 1; i <= segments; i ++ ) {
  11670. indices.push( i, i + 1, 0 );
  11671. }
  11672. // build geometry
  11673. this.setIndex( indices );
  11674. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  11675. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  11676. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  11677. }
  11678. copy( source ) {
  11679. super.copy( source );
  11680. this.parameters = Object.assign( {}, source.parameters );
  11681. return this;
  11682. }
  11683. static fromJSON( data ) {
  11684. return new CircleGeometry( data.radius, data.segments, data.thetaStart, data.thetaLength );
  11685. }
  11686. }
  11687. class CylinderGeometry extends BufferGeometry {
  11688. constructor( radiusTop = 1, radiusBottom = 1, height = 1, radialSegments = 32, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  11689. super();
  11690. this.type = 'CylinderGeometry';
  11691. this.parameters = {
  11692. radiusTop: radiusTop,
  11693. radiusBottom: radiusBottom,
  11694. height: height,
  11695. radialSegments: radialSegments,
  11696. heightSegments: heightSegments,
  11697. openEnded: openEnded,
  11698. thetaStart: thetaStart,
  11699. thetaLength: thetaLength
  11700. };
  11701. const scope = this;
  11702. radialSegments = Math.floor( radialSegments );
  11703. heightSegments = Math.floor( heightSegments );
  11704. // buffers
  11705. const indices = [];
  11706. const vertices = [];
  11707. const normals = [];
  11708. const uvs = [];
  11709. // helper variables
  11710. let index = 0;
  11711. const indexArray = [];
  11712. const halfHeight = height / 2;
  11713. let groupStart = 0;
  11714. // generate geometry
  11715. generateTorso();
  11716. if ( openEnded === false ) {
  11717. if ( radiusTop > 0 ) generateCap( true );
  11718. if ( radiusBottom > 0 ) generateCap( false );
  11719. }
  11720. // build geometry
  11721. this.setIndex( indices );
  11722. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  11723. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  11724. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  11725. function generateTorso() {
  11726. const normal = new Vector3();
  11727. const vertex = new Vector3();
  11728. let groupCount = 0;
  11729. // this will be used to calculate the normal
  11730. const slope = ( radiusBottom - radiusTop ) / height;
  11731. // generate vertices, normals and uvs
  11732. for ( let y = 0; y <= heightSegments; y ++ ) {
  11733. const indexRow = [];
  11734. const v = y / heightSegments;
  11735. // calculate the radius of the current row
  11736. const radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  11737. for ( let x = 0; x <= radialSegments; x ++ ) {
  11738. const u = x / radialSegments;
  11739. const theta = u * thetaLength + thetaStart;
  11740. const sinTheta = Math.sin( theta );
  11741. const cosTheta = Math.cos( theta );
  11742. // vertex
  11743. vertex.x = radius * sinTheta;
  11744. vertex.y = - v * height + halfHeight;
  11745. vertex.z = radius * cosTheta;
  11746. vertices.push( vertex.x, vertex.y, vertex.z );
  11747. // normal
  11748. normal.set( sinTheta, slope, cosTheta ).normalize();
  11749. normals.push( normal.x, normal.y, normal.z );
  11750. // uv
  11751. uvs.push( u, 1 - v );
  11752. // save index of vertex in respective row
  11753. indexRow.push( index ++ );
  11754. }
  11755. // now save vertices of the row in our index array
  11756. indexArray.push( indexRow );
  11757. }
  11758. // generate indices
  11759. for ( let x = 0; x < radialSegments; x ++ ) {
  11760. for ( let y = 0; y < heightSegments; y ++ ) {
  11761. // we use the index array to access the correct indices
  11762. const a = indexArray[ y ][ x ];
  11763. const b = indexArray[ y + 1 ][ x ];
  11764. const c = indexArray[ y + 1 ][ x + 1 ];
  11765. const d = indexArray[ y ][ x + 1 ];
  11766. // faces
  11767. if ( radiusTop > 0 ) {
  11768. indices.push( a, b, d );
  11769. groupCount += 3;
  11770. }
  11771. if ( radiusBottom > 0 ) {
  11772. indices.push( b, c, d );
  11773. groupCount += 3;
  11774. }
  11775. }
  11776. }
  11777. // add a group to the geometry. this will ensure multi material support
  11778. scope.addGroup( groupStart, groupCount, 0 );
  11779. // calculate new start value for groups
  11780. groupStart += groupCount;
  11781. }
  11782. function generateCap( top ) {
  11783. // save the index of the first center vertex
  11784. const centerIndexStart = index;
  11785. const uv = new Vector2();
  11786. const vertex = new Vector3();
  11787. let groupCount = 0;
  11788. const radius = ( top === true ) ? radiusTop : radiusBottom;
  11789. const sign = ( top === true ) ? 1 : - 1;
  11790. // first we generate the center vertex data of the cap.
  11791. // because the geometry needs one set of uvs per face,
  11792. // we must generate a center vertex per face/segment
  11793. for ( let x = 1; x <= radialSegments; x ++ ) {
  11794. // vertex
  11795. vertices.push( 0, halfHeight * sign, 0 );
  11796. // normal
  11797. normals.push( 0, sign, 0 );
  11798. // uv
  11799. uvs.push( 0.5, 0.5 );
  11800. // increase index
  11801. index ++;
  11802. }
  11803. // save the index of the last center vertex
  11804. const centerIndexEnd = index;
  11805. // now we generate the surrounding vertices, normals and uvs
  11806. for ( let x = 0; x <= radialSegments; x ++ ) {
  11807. const u = x / radialSegments;
  11808. const theta = u * thetaLength + thetaStart;
  11809. const cosTheta = Math.cos( theta );
  11810. const sinTheta = Math.sin( theta );
  11811. // vertex
  11812. vertex.x = radius * sinTheta;
  11813. vertex.y = halfHeight * sign;
  11814. vertex.z = radius * cosTheta;
  11815. vertices.push( vertex.x, vertex.y, vertex.z );
  11816. // normal
  11817. normals.push( 0, sign, 0 );
  11818. // uv
  11819. uv.x = ( cosTheta * 0.5 ) + 0.5;
  11820. uv.y = ( sinTheta * 0.5 * sign ) + 0.5;
  11821. uvs.push( uv.x, uv.y );
  11822. // increase index
  11823. index ++;
  11824. }
  11825. // generate indices
  11826. for ( let x = 0; x < radialSegments; x ++ ) {
  11827. const c = centerIndexStart + x;
  11828. const i = centerIndexEnd + x;
  11829. if ( top === true ) {
  11830. // face top
  11831. indices.push( i, i + 1, c );
  11832. } else {
  11833. // face bottom
  11834. indices.push( i + 1, i, c );
  11835. }
  11836. groupCount += 3;
  11837. }
  11838. // add a group to the geometry. this will ensure multi material support
  11839. scope.addGroup( groupStart, groupCount, top === true ? 1 : 2 );
  11840. // calculate new start value for groups
  11841. groupStart += groupCount;
  11842. }
  11843. }
  11844. copy( source ) {
  11845. super.copy( source );
  11846. this.parameters = Object.assign( {}, source.parameters );
  11847. return this;
  11848. }
  11849. static fromJSON( data ) {
  11850. return new CylinderGeometry( data.radiusTop, data.radiusBottom, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength );
  11851. }
  11852. }
  11853. class ConeGeometry extends CylinderGeometry {
  11854. constructor( radius = 1, height = 1, radialSegments = 32, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  11855. super( 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength );
  11856. this.type = 'ConeGeometry';
  11857. this.parameters = {
  11858. radius: radius,
  11859. height: height,
  11860. radialSegments: radialSegments,
  11861. heightSegments: heightSegments,
  11862. openEnded: openEnded,
  11863. thetaStart: thetaStart,
  11864. thetaLength: thetaLength
  11865. };
  11866. }
  11867. static fromJSON( data ) {
  11868. return new ConeGeometry( data.radius, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength );
  11869. }
  11870. }
  11871. class PolyhedronGeometry extends BufferGeometry {
  11872. constructor( vertices = [], indices = [], radius = 1, detail = 0 ) {
  11873. super();
  11874. this.type = 'PolyhedronGeometry';
  11875. this.parameters = {
  11876. vertices: vertices,
  11877. indices: indices,
  11878. radius: radius,
  11879. detail: detail
  11880. };
  11881. // default buffer data
  11882. const vertexBuffer = [];
  11883. const uvBuffer = [];
  11884. // the subdivision creates the vertex buffer data
  11885. subdivide( detail );
  11886. // all vertices should lie on a conceptual sphere with a given radius
  11887. applyRadius( radius );
  11888. // finally, create the uv data
  11889. generateUVs();
  11890. // build non-indexed geometry
  11891. this.setAttribute( 'position', new Float32BufferAttribute( vertexBuffer, 3 ) );
  11892. this.setAttribute( 'normal', new Float32BufferAttribute( vertexBuffer.slice(), 3 ) );
  11893. this.setAttribute( 'uv', new Float32BufferAttribute( uvBuffer, 2 ) );
  11894. if ( detail === 0 ) {
  11895. this.computeVertexNormals(); // flat normals
  11896. } else {
  11897. this.normalizeNormals(); // smooth normals
  11898. }
  11899. // helper functions
  11900. function subdivide( detail ) {
  11901. const a = new Vector3();
  11902. const b = new Vector3();
  11903. const c = new Vector3();
  11904. // iterate over all faces and apply a subdivision with the given detail value
  11905. for ( let i = 0; i < indices.length; i += 3 ) {
  11906. // get the vertices of the face
  11907. getVertexByIndex( indices[ i + 0 ], a );
  11908. getVertexByIndex( indices[ i + 1 ], b );
  11909. getVertexByIndex( indices[ i + 2 ], c );
  11910. // perform subdivision
  11911. subdivideFace( a, b, c, detail );
  11912. }
  11913. }
  11914. function subdivideFace( a, b, c, detail ) {
  11915. const cols = detail + 1;
  11916. // we use this multidimensional array as a data structure for creating the subdivision
  11917. const v = [];
  11918. // construct all of the vertices for this subdivision
  11919. for ( let i = 0; i <= cols; i ++ ) {
  11920. v[ i ] = [];
  11921. const aj = a.clone().lerp( c, i / cols );
  11922. const bj = b.clone().lerp( c, i / cols );
  11923. const rows = cols - i;
  11924. for ( let j = 0; j <= rows; j ++ ) {
  11925. if ( j === 0 && i === cols ) {
  11926. v[ i ][ j ] = aj;
  11927. } else {
  11928. v[ i ][ j ] = aj.clone().lerp( bj, j / rows );
  11929. }
  11930. }
  11931. }
  11932. // construct all of the faces
  11933. for ( let i = 0; i < cols; i ++ ) {
  11934. for ( let j = 0; j < 2 * ( cols - i ) - 1; j ++ ) {
  11935. const k = Math.floor( j / 2 );
  11936. if ( j % 2 === 0 ) {
  11937. pushVertex( v[ i ][ k + 1 ] );
  11938. pushVertex( v[ i + 1 ][ k ] );
  11939. pushVertex( v[ i ][ k ] );
  11940. } else {
  11941. pushVertex( v[ i ][ k + 1 ] );
  11942. pushVertex( v[ i + 1 ][ k + 1 ] );
  11943. pushVertex( v[ i + 1 ][ k ] );
  11944. }
  11945. }
  11946. }
  11947. }
  11948. function applyRadius( radius ) {
  11949. const vertex = new Vector3();
  11950. // iterate over the entire buffer and apply the radius to each vertex
  11951. for ( let i = 0; i < vertexBuffer.length; i += 3 ) {
  11952. vertex.x = vertexBuffer[ i + 0 ];
  11953. vertex.y = vertexBuffer[ i + 1 ];
  11954. vertex.z = vertexBuffer[ i + 2 ];
  11955. vertex.normalize().multiplyScalar( radius );
  11956. vertexBuffer[ i + 0 ] = vertex.x;
  11957. vertexBuffer[ i + 1 ] = vertex.y;
  11958. vertexBuffer[ i + 2 ] = vertex.z;
  11959. }
  11960. }
  11961. function generateUVs() {
  11962. const vertex = new Vector3();
  11963. for ( let i = 0; i < vertexBuffer.length; i += 3 ) {
  11964. vertex.x = vertexBuffer[ i + 0 ];
  11965. vertex.y = vertexBuffer[ i + 1 ];
  11966. vertex.z = vertexBuffer[ i + 2 ];
  11967. const u = azimuth( vertex ) / 2 / Math.PI + 0.5;
  11968. const v = inclination( vertex ) / Math.PI + 0.5;
  11969. uvBuffer.push( u, 1 - v );
  11970. }
  11971. correctUVs();
  11972. correctSeam();
  11973. }
  11974. function correctSeam() {
  11975. // handle case when face straddles the seam, see #3269
  11976. for ( let i = 0; i < uvBuffer.length; i += 6 ) {
  11977. // uv data of a single face
  11978. const x0 = uvBuffer[ i + 0 ];
  11979. const x1 = uvBuffer[ i + 2 ];
  11980. const x2 = uvBuffer[ i + 4 ];
  11981. const max = Math.max( x0, x1, x2 );
  11982. const min = Math.min( x0, x1, x2 );
  11983. // 0.9 is somewhat arbitrary
  11984. if ( max > 0.9 && min < 0.1 ) {
  11985. if ( x0 < 0.2 ) uvBuffer[ i + 0 ] += 1;
  11986. if ( x1 < 0.2 ) uvBuffer[ i + 2 ] += 1;
  11987. if ( x2 < 0.2 ) uvBuffer[ i + 4 ] += 1;
  11988. }
  11989. }
  11990. }
  11991. function pushVertex( vertex ) {
  11992. vertexBuffer.push( vertex.x, vertex.y, vertex.z );
  11993. }
  11994. function getVertexByIndex( index, vertex ) {
  11995. const stride = index * 3;
  11996. vertex.x = vertices[ stride + 0 ];
  11997. vertex.y = vertices[ stride + 1 ];
  11998. vertex.z = vertices[ stride + 2 ];
  11999. }
  12000. function correctUVs() {
  12001. const a = new Vector3();
  12002. const b = new Vector3();
  12003. const c = new Vector3();
  12004. const centroid = new Vector3();
  12005. const uvA = new Vector2();
  12006. const uvB = new Vector2();
  12007. const uvC = new Vector2();
  12008. for ( let i = 0, j = 0; i < vertexBuffer.length; i += 9, j += 6 ) {
  12009. a.set( vertexBuffer[ i + 0 ], vertexBuffer[ i + 1 ], vertexBuffer[ i + 2 ] );
  12010. b.set( vertexBuffer[ i + 3 ], vertexBuffer[ i + 4 ], vertexBuffer[ i + 5 ] );
  12011. c.set( vertexBuffer[ i + 6 ], vertexBuffer[ i + 7 ], vertexBuffer[ i + 8 ] );
  12012. uvA.set( uvBuffer[ j + 0 ], uvBuffer[ j + 1 ] );
  12013. uvB.set( uvBuffer[ j + 2 ], uvBuffer[ j + 3 ] );
  12014. uvC.set( uvBuffer[ j + 4 ], uvBuffer[ j + 5 ] );
  12015. centroid.copy( a ).add( b ).add( c ).divideScalar( 3 );
  12016. const azi = azimuth( centroid );
  12017. correctUV( uvA, j + 0, a, azi );
  12018. correctUV( uvB, j + 2, b, azi );
  12019. correctUV( uvC, j + 4, c, azi );
  12020. }
  12021. }
  12022. function correctUV( uv, stride, vector, azimuth ) {
  12023. if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) {
  12024. uvBuffer[ stride ] = uv.x - 1;
  12025. }
  12026. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) {
  12027. uvBuffer[ stride ] = azimuth / 2 / Math.PI + 0.5;
  12028. }
  12029. }
  12030. // Angle around the Y axis, counter-clockwise when looking from above.
  12031. function azimuth( vector ) {
  12032. return Math.atan2( vector.z, - vector.x );
  12033. }
  12034. // Angle above the XZ plane.
  12035. function inclination( vector ) {
  12036. return Math.atan2( - vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  12037. }
  12038. }
  12039. copy( source ) {
  12040. super.copy( source );
  12041. this.parameters = Object.assign( {}, source.parameters );
  12042. return this;
  12043. }
  12044. static fromJSON( data ) {
  12045. return new PolyhedronGeometry( data.vertices, data.indices, data.radius, data.details );
  12046. }
  12047. }
  12048. class DodecahedronGeometry extends PolyhedronGeometry {
  12049. constructor( radius = 1, detail = 0 ) {
  12050. const t = ( 1 + Math.sqrt( 5 ) ) / 2;
  12051. const r = 1 / t;
  12052. const vertices = [
  12053. // (±1, ±1, ±1)
  12054. - 1, - 1, - 1, - 1, - 1, 1,
  12055. - 1, 1, - 1, - 1, 1, 1,
  12056. 1, - 1, - 1, 1, - 1, 1,
  12057. 1, 1, - 1, 1, 1, 1,
  12058. // (0, ±1/φ, ±φ)
  12059. 0, - r, - t, 0, - r, t,
  12060. 0, r, - t, 0, r, t,
  12061. // (±1/φ, ±φ, 0)
  12062. - r, - t, 0, - r, t, 0,
  12063. r, - t, 0, r, t, 0,
  12064. // (±φ, 0, ±1/φ)
  12065. - t, 0, - r, t, 0, - r,
  12066. - t, 0, r, t, 0, r
  12067. ];
  12068. const indices = [
  12069. 3, 11, 7, 3, 7, 15, 3, 15, 13,
  12070. 7, 19, 17, 7, 17, 6, 7, 6, 15,
  12071. 17, 4, 8, 17, 8, 10, 17, 10, 6,
  12072. 8, 0, 16, 8, 16, 2, 8, 2, 10,
  12073. 0, 12, 1, 0, 1, 18, 0, 18, 16,
  12074. 6, 10, 2, 6, 2, 13, 6, 13, 15,
  12075. 2, 16, 18, 2, 18, 3, 2, 3, 13,
  12076. 18, 1, 9, 18, 9, 11, 18, 11, 3,
  12077. 4, 14, 12, 4, 12, 0, 4, 0, 8,
  12078. 11, 9, 5, 11, 5, 19, 11, 19, 7,
  12079. 19, 5, 14, 19, 14, 4, 19, 4, 17,
  12080. 1, 12, 14, 1, 14, 5, 1, 5, 9
  12081. ];
  12082. super( vertices, indices, radius, detail );
  12083. this.type = 'DodecahedronGeometry';
  12084. this.parameters = {
  12085. radius: radius,
  12086. detail: detail
  12087. };
  12088. }
  12089. static fromJSON( data ) {
  12090. return new DodecahedronGeometry( data.radius, data.detail );
  12091. }
  12092. }
  12093. const _v0 = /*@__PURE__*/ new Vector3();
  12094. const _v1$1 = /*@__PURE__*/ new Vector3();
  12095. const _normal$1 = /*@__PURE__*/ new Vector3();
  12096. const _triangle = /*@__PURE__*/ new Triangle();
  12097. class EdgesGeometry extends BufferGeometry {
  12098. constructor( geometry = null, thresholdAngle = 1 ) {
  12099. super();
  12100. this.type = 'EdgesGeometry';
  12101. this.parameters = {
  12102. geometry: geometry,
  12103. thresholdAngle: thresholdAngle
  12104. };
  12105. if ( geometry !== null ) {
  12106. const precisionPoints = 4;
  12107. const precision = Math.pow( 10, precisionPoints );
  12108. const thresholdDot = Math.cos( DEG2RAD * thresholdAngle );
  12109. const indexAttr = geometry.getIndex();
  12110. const positionAttr = geometry.getAttribute( 'position' );
  12111. const indexCount = indexAttr ? indexAttr.count : positionAttr.count;
  12112. const indexArr = [ 0, 0, 0 ];
  12113. const vertKeys = [ 'a', 'b', 'c' ];
  12114. const hashes = new Array( 3 );
  12115. const edgeData = {};
  12116. const vertices = [];
  12117. for ( let i = 0; i < indexCount; i += 3 ) {
  12118. if ( indexAttr ) {
  12119. indexArr[ 0 ] = indexAttr.getX( i );
  12120. indexArr[ 1 ] = indexAttr.getX( i + 1 );
  12121. indexArr[ 2 ] = indexAttr.getX( i + 2 );
  12122. } else {
  12123. indexArr[ 0 ] = i;
  12124. indexArr[ 1 ] = i + 1;
  12125. indexArr[ 2 ] = i + 2;
  12126. }
  12127. const { a, b, c } = _triangle;
  12128. a.fromBufferAttribute( positionAttr, indexArr[ 0 ] );
  12129. b.fromBufferAttribute( positionAttr, indexArr[ 1 ] );
  12130. c.fromBufferAttribute( positionAttr, indexArr[ 2 ] );
  12131. _triangle.getNormal( _normal$1 );
  12132. // create hashes for the edge from the vertices
  12133. hashes[ 0 ] = `${ Math.round( a.x * precision ) },${ Math.round( a.y * precision ) },${ Math.round( a.z * precision ) }`;
  12134. hashes[ 1 ] = `${ Math.round( b.x * precision ) },${ Math.round( b.y * precision ) },${ Math.round( b.z * precision ) }`;
  12135. hashes[ 2 ] = `${ Math.round( c.x * precision ) },${ Math.round( c.y * precision ) },${ Math.round( c.z * precision ) }`;
  12136. // skip degenerate triangles
  12137. if ( hashes[ 0 ] === hashes[ 1 ] || hashes[ 1 ] === hashes[ 2 ] || hashes[ 2 ] === hashes[ 0 ] ) {
  12138. continue;
  12139. }
  12140. // iterate over every edge
  12141. for ( let j = 0; j < 3; j ++ ) {
  12142. // get the first and next vertex making up the edge
  12143. const jNext = ( j + 1 ) % 3;
  12144. const vecHash0 = hashes[ j ];
  12145. const vecHash1 = hashes[ jNext ];
  12146. const v0 = _triangle[ vertKeys[ j ] ];
  12147. const v1 = _triangle[ vertKeys[ jNext ] ];
  12148. const hash = `${ vecHash0 }_${ vecHash1 }`;
  12149. const reverseHash = `${ vecHash1 }_${ vecHash0 }`;
  12150. if ( reverseHash in edgeData && edgeData[ reverseHash ] ) {
  12151. // if we found a sibling edge add it into the vertex array if
  12152. // it meets the angle threshold and delete the edge from the map.
  12153. if ( _normal$1.dot( edgeData[ reverseHash ].normal ) <= thresholdDot ) {
  12154. vertices.push( v0.x, v0.y, v0.z );
  12155. vertices.push( v1.x, v1.y, v1.z );
  12156. }
  12157. edgeData[ reverseHash ] = null;
  12158. } else if ( ! ( hash in edgeData ) ) {
  12159. // if we've already got an edge here then skip adding a new one
  12160. edgeData[ hash ] = {
  12161. index0: indexArr[ j ],
  12162. index1: indexArr[ jNext ],
  12163. normal: _normal$1.clone(),
  12164. };
  12165. }
  12166. }
  12167. }
  12168. // iterate over all remaining, unmatched edges and add them to the vertex array
  12169. for ( const key in edgeData ) {
  12170. if ( edgeData[ key ] ) {
  12171. const { index0, index1 } = edgeData[ key ];
  12172. _v0.fromBufferAttribute( positionAttr, index0 );
  12173. _v1$1.fromBufferAttribute( positionAttr, index1 );
  12174. vertices.push( _v0.x, _v0.y, _v0.z );
  12175. vertices.push( _v1$1.x, _v1$1.y, _v1$1.z );
  12176. }
  12177. }
  12178. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  12179. }
  12180. }
  12181. copy( source ) {
  12182. super.copy( source );
  12183. this.parameters = Object.assign( {}, source.parameters );
  12184. return this;
  12185. }
  12186. }
  12187. class Shape extends Path {
  12188. constructor( points ) {
  12189. super( points );
  12190. this.uuid = generateUUID();
  12191. this.type = 'Shape';
  12192. this.holes = [];
  12193. }
  12194. getPointsHoles( divisions ) {
  12195. const holesPts = [];
  12196. for ( let i = 0, l = this.holes.length; i < l; i ++ ) {
  12197. holesPts[ i ] = this.holes[ i ].getPoints( divisions );
  12198. }
  12199. return holesPts;
  12200. }
  12201. // get points of shape and holes (keypoints based on segments parameter)
  12202. extractPoints( divisions ) {
  12203. return {
  12204. shape: this.getPoints( divisions ),
  12205. holes: this.getPointsHoles( divisions )
  12206. };
  12207. }
  12208. copy( source ) {
  12209. super.copy( source );
  12210. this.holes = [];
  12211. for ( let i = 0, l = source.holes.length; i < l; i ++ ) {
  12212. const hole = source.holes[ i ];
  12213. this.holes.push( hole.clone() );
  12214. }
  12215. return this;
  12216. }
  12217. toJSON() {
  12218. const data = super.toJSON();
  12219. data.uuid = this.uuid;
  12220. data.holes = [];
  12221. for ( let i = 0, l = this.holes.length; i < l; i ++ ) {
  12222. const hole = this.holes[ i ];
  12223. data.holes.push( hole.toJSON() );
  12224. }
  12225. return data;
  12226. }
  12227. fromJSON( json ) {
  12228. super.fromJSON( json );
  12229. this.uuid = json.uuid;
  12230. this.holes = [];
  12231. for ( let i = 0, l = json.holes.length; i < l; i ++ ) {
  12232. const hole = json.holes[ i ];
  12233. this.holes.push( new Path().fromJSON( hole ) );
  12234. }
  12235. return this;
  12236. }
  12237. }
  12238. /**
  12239. * Port from https://github.com/mapbox/earcut (v2.2.4)
  12240. */
  12241. const Earcut = {
  12242. triangulate: function ( data, holeIndices, dim = 2 ) {
  12243. const hasHoles = holeIndices && holeIndices.length;
  12244. const outerLen = hasHoles ? holeIndices[ 0 ] * dim : data.length;
  12245. let outerNode = linkedList( data, 0, outerLen, dim, true );
  12246. const triangles = [];
  12247. if ( ! outerNode || outerNode.next === outerNode.prev ) return triangles;
  12248. let minX, minY, maxX, maxY, x, y, invSize;
  12249. if ( hasHoles ) outerNode = eliminateHoles( data, holeIndices, outerNode, dim );
  12250. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  12251. if ( data.length > 80 * dim ) {
  12252. minX = maxX = data[ 0 ];
  12253. minY = maxY = data[ 1 ];
  12254. for ( let i = dim; i < outerLen; i += dim ) {
  12255. x = data[ i ];
  12256. y = data[ i + 1 ];
  12257. if ( x < minX ) minX = x;
  12258. if ( y < minY ) minY = y;
  12259. if ( x > maxX ) maxX = x;
  12260. if ( y > maxY ) maxY = y;
  12261. }
  12262. // minX, minY and invSize are later used to transform coords into integers for z-order calculation
  12263. invSize = Math.max( maxX - minX, maxY - minY );
  12264. invSize = invSize !== 0 ? 32767 / invSize : 0;
  12265. }
  12266. earcutLinked( outerNode, triangles, dim, minX, minY, invSize, 0 );
  12267. return triangles;
  12268. }
  12269. };
  12270. // create a circular doubly linked list from polygon points in the specified winding order
  12271. function linkedList( data, start, end, dim, clockwise ) {
  12272. let i, last;
  12273. if ( clockwise === ( signedArea( data, start, end, dim ) > 0 ) ) {
  12274. for ( i = start; i < end; i += dim ) last = insertNode( i, data[ i ], data[ i + 1 ], last );
  12275. } else {
  12276. for ( i = end - dim; i >= start; i -= dim ) last = insertNode( i, data[ i ], data[ i + 1 ], last );
  12277. }
  12278. if ( last && equals$1( last, last.next ) ) {
  12279. removeNode( last );
  12280. last = last.next;
  12281. }
  12282. return last;
  12283. }
  12284. // eliminate colinear or duplicate points
  12285. function filterPoints( start, end ) {
  12286. if ( ! start ) return start;
  12287. if ( ! end ) end = start;
  12288. let p = start,
  12289. again;
  12290. do {
  12291. again = false;
  12292. if ( ! p.steiner && ( equals$1( p, p.next ) || area( p.prev, p, p.next ) === 0 ) ) {
  12293. removeNode( p );
  12294. p = end = p.prev;
  12295. if ( p === p.next ) break;
  12296. again = true;
  12297. } else {
  12298. p = p.next;
  12299. }
  12300. } while ( again || p !== end );
  12301. return end;
  12302. }
  12303. // main ear slicing loop which triangulates a polygon (given as a linked list)
  12304. function earcutLinked( ear, triangles, dim, minX, minY, invSize, pass ) {
  12305. if ( ! ear ) return;
  12306. // interlink polygon nodes in z-order
  12307. if ( ! pass && invSize ) indexCurve( ear, minX, minY, invSize );
  12308. let stop = ear,
  12309. prev, next;
  12310. // iterate through ears, slicing them one by one
  12311. while ( ear.prev !== ear.next ) {
  12312. prev = ear.prev;
  12313. next = ear.next;
  12314. if ( invSize ? isEarHashed( ear, minX, minY, invSize ) : isEar( ear ) ) {
  12315. // cut off the triangle
  12316. triangles.push( prev.i / dim | 0 );
  12317. triangles.push( ear.i / dim | 0 );
  12318. triangles.push( next.i / dim | 0 );
  12319. removeNode( ear );
  12320. // skipping the next vertex leads to less sliver triangles
  12321. ear = next.next;
  12322. stop = next.next;
  12323. continue;
  12324. }
  12325. ear = next;
  12326. // if we looped through the whole remaining polygon and can't find any more ears
  12327. if ( ear === stop ) {
  12328. // try filtering points and slicing again
  12329. if ( ! pass ) {
  12330. earcutLinked( filterPoints( ear ), triangles, dim, minX, minY, invSize, 1 );
  12331. // if this didn't work, try curing all small self-intersections locally
  12332. } else if ( pass === 1 ) {
  12333. ear = cureLocalIntersections( filterPoints( ear ), triangles, dim );
  12334. earcutLinked( ear, triangles, dim, minX, minY, invSize, 2 );
  12335. // as a last resort, try splitting the remaining polygon into two
  12336. } else if ( pass === 2 ) {
  12337. splitEarcut( ear, triangles, dim, minX, minY, invSize );
  12338. }
  12339. break;
  12340. }
  12341. }
  12342. }
  12343. // check whether a polygon node forms a valid ear with adjacent nodes
  12344. function isEar( ear ) {
  12345. const a = ear.prev,
  12346. b = ear,
  12347. c = ear.next;
  12348. if ( area( a, b, c ) >= 0 ) return false; // reflex, can't be an ear
  12349. // now make sure we don't have other points inside the potential ear
  12350. const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y;
  12351. // triangle bbox; min & max are calculated like this for speed
  12352. const x0 = ax < bx ? ( ax < cx ? ax : cx ) : ( bx < cx ? bx : cx ),
  12353. y0 = ay < by ? ( ay < cy ? ay : cy ) : ( by < cy ? by : cy ),
  12354. x1 = ax > bx ? ( ax > cx ? ax : cx ) : ( bx > cx ? bx : cx ),
  12355. y1 = ay > by ? ( ay > cy ? ay : cy ) : ( by > cy ? by : cy );
  12356. let p = c.next;
  12357. while ( p !== a ) {
  12358. if ( p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 &&
  12359. pointInTriangle( ax, ay, bx, by, cx, cy, p.x, p.y ) &&
  12360. area( p.prev, p, p.next ) >= 0 ) return false;
  12361. p = p.next;
  12362. }
  12363. return true;
  12364. }
  12365. function isEarHashed( ear, minX, minY, invSize ) {
  12366. const a = ear.prev,
  12367. b = ear,
  12368. c = ear.next;
  12369. if ( area( a, b, c ) >= 0 ) return false; // reflex, can't be an ear
  12370. const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y;
  12371. // triangle bbox; min & max are calculated like this for speed
  12372. const x0 = ax < bx ? ( ax < cx ? ax : cx ) : ( bx < cx ? bx : cx ),
  12373. y0 = ay < by ? ( ay < cy ? ay : cy ) : ( by < cy ? by : cy ),
  12374. x1 = ax > bx ? ( ax > cx ? ax : cx ) : ( bx > cx ? bx : cx ),
  12375. y1 = ay > by ? ( ay > cy ? ay : cy ) : ( by > cy ? by : cy );
  12376. // z-order range for the current triangle bbox;
  12377. const minZ = zOrder( x0, y0, minX, minY, invSize ),
  12378. maxZ = zOrder( x1, y1, minX, minY, invSize );
  12379. let p = ear.prevZ,
  12380. n = ear.nextZ;
  12381. // look for points inside the triangle in both directions
  12382. while ( p && p.z >= minZ && n && n.z <= maxZ ) {
  12383. if ( p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c &&
  12384. pointInTriangle( ax, ay, bx, by, cx, cy, p.x, p.y ) && area( p.prev, p, p.next ) >= 0 ) return false;
  12385. p = p.prevZ;
  12386. if ( n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c &&
  12387. pointInTriangle( ax, ay, bx, by, cx, cy, n.x, n.y ) && area( n.prev, n, n.next ) >= 0 ) return false;
  12388. n = n.nextZ;
  12389. }
  12390. // look for remaining points in decreasing z-order
  12391. while ( p && p.z >= minZ ) {
  12392. if ( p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c &&
  12393. pointInTriangle( ax, ay, bx, by, cx, cy, p.x, p.y ) && area( p.prev, p, p.next ) >= 0 ) return false;
  12394. p = p.prevZ;
  12395. }
  12396. // look for remaining points in increasing z-order
  12397. while ( n && n.z <= maxZ ) {
  12398. if ( n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c &&
  12399. pointInTriangle( ax, ay, bx, by, cx, cy, n.x, n.y ) && area( n.prev, n, n.next ) >= 0 ) return false;
  12400. n = n.nextZ;
  12401. }
  12402. return true;
  12403. }
  12404. // go through all polygon nodes and cure small local self-intersections
  12405. function cureLocalIntersections( start, triangles, dim ) {
  12406. let p = start;
  12407. do {
  12408. const a = p.prev,
  12409. b = p.next.next;
  12410. if ( ! equals$1( a, b ) && intersects( a, p, p.next, b ) && locallyInside( a, b ) && locallyInside( b, a ) ) {
  12411. triangles.push( a.i / dim | 0 );
  12412. triangles.push( p.i / dim | 0 );
  12413. triangles.push( b.i / dim | 0 );
  12414. // remove two nodes involved
  12415. removeNode( p );
  12416. removeNode( p.next );
  12417. p = start = b;
  12418. }
  12419. p = p.next;
  12420. } while ( p !== start );
  12421. return filterPoints( p );
  12422. }
  12423. // try splitting polygon into two and triangulate them independently
  12424. function splitEarcut( start, triangles, dim, minX, minY, invSize ) {
  12425. // look for a valid diagonal that divides the polygon into two
  12426. let a = start;
  12427. do {
  12428. let b = a.next.next;
  12429. while ( b !== a.prev ) {
  12430. if ( a.i !== b.i && isValidDiagonal( a, b ) ) {
  12431. // split the polygon in two by the diagonal
  12432. let c = splitPolygon( a, b );
  12433. // filter colinear points around the cuts
  12434. a = filterPoints( a, a.next );
  12435. c = filterPoints( c, c.next );
  12436. // run earcut on each half
  12437. earcutLinked( a, triangles, dim, minX, minY, invSize, 0 );
  12438. earcutLinked( c, triangles, dim, minX, minY, invSize, 0 );
  12439. return;
  12440. }
  12441. b = b.next;
  12442. }
  12443. a = a.next;
  12444. } while ( a !== start );
  12445. }
  12446. // link every hole into the outer loop, producing a single-ring polygon without holes
  12447. function eliminateHoles( data, holeIndices, outerNode, dim ) {
  12448. const queue = [];
  12449. let i, len, start, end, list;
  12450. for ( i = 0, len = holeIndices.length; i < len; i ++ ) {
  12451. start = holeIndices[ i ] * dim;
  12452. end = i < len - 1 ? holeIndices[ i + 1 ] * dim : data.length;
  12453. list = linkedList( data, start, end, dim, false );
  12454. if ( list === list.next ) list.steiner = true;
  12455. queue.push( getLeftmost( list ) );
  12456. }
  12457. queue.sort( compareX );
  12458. // process holes from left to right
  12459. for ( i = 0; i < queue.length; i ++ ) {
  12460. outerNode = eliminateHole( queue[ i ], outerNode );
  12461. }
  12462. return outerNode;
  12463. }
  12464. function compareX( a, b ) {
  12465. return a.x - b.x;
  12466. }
  12467. // find a bridge between vertices that connects hole with an outer ring and link it
  12468. function eliminateHole( hole, outerNode ) {
  12469. const bridge = findHoleBridge( hole, outerNode );
  12470. if ( ! bridge ) {
  12471. return outerNode;
  12472. }
  12473. const bridgeReverse = splitPolygon( bridge, hole );
  12474. // filter collinear points around the cuts
  12475. filterPoints( bridgeReverse, bridgeReverse.next );
  12476. return filterPoints( bridge, bridge.next );
  12477. }
  12478. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  12479. function findHoleBridge( hole, outerNode ) {
  12480. let p = outerNode,
  12481. qx = - Infinity,
  12482. m;
  12483. const hx = hole.x, hy = hole.y;
  12484. // find a segment intersected by a ray from the hole's leftmost point to the left;
  12485. // segment's endpoint with lesser x will be potential connection point
  12486. do {
  12487. if ( hy <= p.y && hy >= p.next.y && p.next.y !== p.y ) {
  12488. const x = p.x + ( hy - p.y ) * ( p.next.x - p.x ) / ( p.next.y - p.y );
  12489. if ( x <= hx && x > qx ) {
  12490. qx = x;
  12491. m = p.x < p.next.x ? p : p.next;
  12492. if ( x === hx ) return m; // hole touches outer segment; pick leftmost endpoint
  12493. }
  12494. }
  12495. p = p.next;
  12496. } while ( p !== outerNode );
  12497. if ( ! m ) return null;
  12498. // look for points inside the triangle of hole point, segment intersection and endpoint;
  12499. // if there are no points found, we have a valid connection;
  12500. // otherwise choose the point of the minimum angle with the ray as connection point
  12501. const stop = m,
  12502. mx = m.x,
  12503. my = m.y;
  12504. let tanMin = Infinity, tan;
  12505. p = m;
  12506. do {
  12507. if ( hx >= p.x && p.x >= mx && hx !== p.x &&
  12508. pointInTriangle( hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y ) ) {
  12509. tan = Math.abs( hy - p.y ) / ( hx - p.x ); // tangential
  12510. if ( locallyInside( p, hole ) && ( tan < tanMin || ( tan === tanMin && ( p.x > m.x || ( p.x === m.x && sectorContainsSector( m, p ) ) ) ) ) ) {
  12511. m = p;
  12512. tanMin = tan;
  12513. }
  12514. }
  12515. p = p.next;
  12516. } while ( p !== stop );
  12517. return m;
  12518. }
  12519. // whether sector in vertex m contains sector in vertex p in the same coordinates
  12520. function sectorContainsSector( m, p ) {
  12521. return area( m.prev, m, p.prev ) < 0 && area( p.next, m, m.next ) < 0;
  12522. }
  12523. // interlink polygon nodes in z-order
  12524. function indexCurve( start, minX, minY, invSize ) {
  12525. let p = start;
  12526. do {
  12527. if ( p.z === 0 ) p.z = zOrder( p.x, p.y, minX, minY, invSize );
  12528. p.prevZ = p.prev;
  12529. p.nextZ = p.next;
  12530. p = p.next;
  12531. } while ( p !== start );
  12532. p.prevZ.nextZ = null;
  12533. p.prevZ = null;
  12534. sortLinked( p );
  12535. }
  12536. // Simon Tatham's linked list merge sort algorithm
  12537. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  12538. function sortLinked( list ) {
  12539. let i, p, q, e, tail, numMerges, pSize, qSize,
  12540. inSize = 1;
  12541. do {
  12542. p = list;
  12543. list = null;
  12544. tail = null;
  12545. numMerges = 0;
  12546. while ( p ) {
  12547. numMerges ++;
  12548. q = p;
  12549. pSize = 0;
  12550. for ( i = 0; i < inSize; i ++ ) {
  12551. pSize ++;
  12552. q = q.nextZ;
  12553. if ( ! q ) break;
  12554. }
  12555. qSize = inSize;
  12556. while ( pSize > 0 || ( qSize > 0 && q ) ) {
  12557. if ( pSize !== 0 && ( qSize === 0 || ! q || p.z <= q.z ) ) {
  12558. e = p;
  12559. p = p.nextZ;
  12560. pSize --;
  12561. } else {
  12562. e = q;
  12563. q = q.nextZ;
  12564. qSize --;
  12565. }
  12566. if ( tail ) tail.nextZ = e;
  12567. else list = e;
  12568. e.prevZ = tail;
  12569. tail = e;
  12570. }
  12571. p = q;
  12572. }
  12573. tail.nextZ = null;
  12574. inSize *= 2;
  12575. } while ( numMerges > 1 );
  12576. return list;
  12577. }
  12578. // z-order of a point given coords and inverse of the longer side of data bbox
  12579. function zOrder( x, y, minX, minY, invSize ) {
  12580. // coords are transformed into non-negative 15-bit integer range
  12581. x = ( x - minX ) * invSize | 0;
  12582. y = ( y - minY ) * invSize | 0;
  12583. x = ( x | ( x << 8 ) ) & 0x00FF00FF;
  12584. x = ( x | ( x << 4 ) ) & 0x0F0F0F0F;
  12585. x = ( x | ( x << 2 ) ) & 0x33333333;
  12586. x = ( x | ( x << 1 ) ) & 0x55555555;
  12587. y = ( y | ( y << 8 ) ) & 0x00FF00FF;
  12588. y = ( y | ( y << 4 ) ) & 0x0F0F0F0F;
  12589. y = ( y | ( y << 2 ) ) & 0x33333333;
  12590. y = ( y | ( y << 1 ) ) & 0x55555555;
  12591. return x | ( y << 1 );
  12592. }
  12593. // find the leftmost node of a polygon ring
  12594. function getLeftmost( start ) {
  12595. let p = start,
  12596. leftmost = start;
  12597. do {
  12598. if ( p.x < leftmost.x || ( p.x === leftmost.x && p.y < leftmost.y ) ) leftmost = p;
  12599. p = p.next;
  12600. } while ( p !== start );
  12601. return leftmost;
  12602. }
  12603. // check if a point lies within a convex triangle
  12604. function pointInTriangle( ax, ay, bx, by, cx, cy, px, py ) {
  12605. return ( cx - px ) * ( ay - py ) >= ( ax - px ) * ( cy - py ) &&
  12606. ( ax - px ) * ( by - py ) >= ( bx - px ) * ( ay - py ) &&
  12607. ( bx - px ) * ( cy - py ) >= ( cx - px ) * ( by - py );
  12608. }
  12609. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  12610. function isValidDiagonal( a, b ) {
  12611. return a.next.i !== b.i && a.prev.i !== b.i && ! intersectsPolygon( a, b ) && // dones't intersect other edges
  12612. ( locallyInside( a, b ) && locallyInside( b, a ) && middleInside( a, b ) && // locally visible
  12613. ( area( a.prev, a, b.prev ) || area( a, b.prev, b ) ) || // does not create opposite-facing sectors
  12614. equals$1( a, b ) && area( a.prev, a, a.next ) > 0 && area( b.prev, b, b.next ) > 0 ); // special zero-length case
  12615. }
  12616. // signed area of a triangle
  12617. function area( p, q, r ) {
  12618. return ( q.y - p.y ) * ( r.x - q.x ) - ( q.x - p.x ) * ( r.y - q.y );
  12619. }
  12620. // check if two points are equal
  12621. function equals$1( p1, p2 ) {
  12622. return p1.x === p2.x && p1.y === p2.y;
  12623. }
  12624. // check if two segments intersect
  12625. function intersects( p1, q1, p2, q2 ) {
  12626. const o1 = sign$1( area( p1, q1, p2 ) );
  12627. const o2 = sign$1( area( p1, q1, q2 ) );
  12628. const o3 = sign$1( area( p2, q2, p1 ) );
  12629. const o4 = sign$1( area( p2, q2, q1 ) );
  12630. if ( o1 !== o2 && o3 !== o4 ) return true; // general case
  12631. if ( o1 === 0 && onSegment( p1, p2, q1 ) ) return true; // p1, q1 and p2 are collinear and p2 lies on p1q1
  12632. if ( o2 === 0 && onSegment( p1, q2, q1 ) ) return true; // p1, q1 and q2 are collinear and q2 lies on p1q1
  12633. if ( o3 === 0 && onSegment( p2, p1, q2 ) ) return true; // p2, q2 and p1 are collinear and p1 lies on p2q2
  12634. if ( o4 === 0 && onSegment( p2, q1, q2 ) ) return true; // p2, q2 and q1 are collinear and q1 lies on p2q2
  12635. return false;
  12636. }
  12637. // for collinear points p, q, r, check if point q lies on segment pr
  12638. function onSegment( p, q, r ) {
  12639. 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 );
  12640. }
  12641. function sign$1( num ) {
  12642. return num > 0 ? 1 : num < 0 ? - 1 : 0;
  12643. }
  12644. // check if a polygon diagonal intersects any polygon segments
  12645. function intersectsPolygon( a, b ) {
  12646. let p = a;
  12647. do {
  12648. if ( p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i &&
  12649. intersects( p, p.next, a, b ) ) return true;
  12650. p = p.next;
  12651. } while ( p !== a );
  12652. return false;
  12653. }
  12654. // check if a polygon diagonal is locally inside the polygon
  12655. function locallyInside( a, b ) {
  12656. return area( a.prev, a, a.next ) < 0 ?
  12657. area( a, b, a.next ) >= 0 && area( a, a.prev, b ) >= 0 :
  12658. area( a, b, a.prev ) < 0 || area( a, a.next, b ) < 0;
  12659. }
  12660. // check if the middle point of a polygon diagonal is inside the polygon
  12661. function middleInside( a, b ) {
  12662. let p = a,
  12663. inside = false;
  12664. const px = ( a.x + b.x ) / 2,
  12665. py = ( a.y + b.y ) / 2;
  12666. do {
  12667. if ( ( ( p.y > py ) !== ( p.next.y > py ) ) && p.next.y !== p.y &&
  12668. ( px < ( p.next.x - p.x ) * ( py - p.y ) / ( p.next.y - p.y ) + p.x ) )
  12669. inside = ! inside;
  12670. p = p.next;
  12671. } while ( p !== a );
  12672. return inside;
  12673. }
  12674. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  12675. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  12676. function splitPolygon( a, b ) {
  12677. const a2 = new Node$1( a.i, a.x, a.y ),
  12678. b2 = new Node$1( b.i, b.x, b.y ),
  12679. an = a.next,
  12680. bp = b.prev;
  12681. a.next = b;
  12682. b.prev = a;
  12683. a2.next = an;
  12684. an.prev = a2;
  12685. b2.next = a2;
  12686. a2.prev = b2;
  12687. bp.next = b2;
  12688. b2.prev = bp;
  12689. return b2;
  12690. }
  12691. // create a node and optionally link it with previous one (in a circular doubly linked list)
  12692. function insertNode( i, x, y, last ) {
  12693. const p = new Node$1( i, x, y );
  12694. if ( ! last ) {
  12695. p.prev = p;
  12696. p.next = p;
  12697. } else {
  12698. p.next = last.next;
  12699. p.prev = last;
  12700. last.next.prev = p;
  12701. last.next = p;
  12702. }
  12703. return p;
  12704. }
  12705. function removeNode( p ) {
  12706. p.next.prev = p.prev;
  12707. p.prev.next = p.next;
  12708. if ( p.prevZ ) p.prevZ.nextZ = p.nextZ;
  12709. if ( p.nextZ ) p.nextZ.prevZ = p.prevZ;
  12710. }
  12711. function Node$1( i, x, y ) {
  12712. // vertex index in coordinates array
  12713. this.i = i;
  12714. // vertex coordinates
  12715. this.x = x;
  12716. this.y = y;
  12717. // previous and next vertex nodes in a polygon ring
  12718. this.prev = null;
  12719. this.next = null;
  12720. // z-order curve value
  12721. this.z = 0;
  12722. // previous and next nodes in z-order
  12723. this.prevZ = null;
  12724. this.nextZ = null;
  12725. // indicates whether this is a steiner point
  12726. this.steiner = false;
  12727. }
  12728. function signedArea( data, start, end, dim ) {
  12729. let sum = 0;
  12730. for ( let i = start, j = end - dim; i < end; i += dim ) {
  12731. sum += ( data[ j ] - data[ i ] ) * ( data[ i + 1 ] + data[ j + 1 ] );
  12732. j = i;
  12733. }
  12734. return sum;
  12735. }
  12736. class ShapeUtils {
  12737. // calculate area of the contour polygon
  12738. static area( contour ) {
  12739. const n = contour.length;
  12740. let a = 0.0;
  12741. for ( let p = n - 1, q = 0; q < n; p = q ++ ) {
  12742. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  12743. }
  12744. return a * 0.5;
  12745. }
  12746. static isClockWise( pts ) {
  12747. return ShapeUtils.area( pts ) < 0;
  12748. }
  12749. static triangulateShape( contour, holes ) {
  12750. const vertices = []; // flat array of vertices like [ x0,y0, x1,y1, x2,y2, ... ]
  12751. const holeIndices = []; // array of hole indices
  12752. const faces = []; // final array of vertex indices like [ [ a,b,d ], [ b,c,d ] ]
  12753. removeDupEndPts( contour );
  12754. addContour( vertices, contour );
  12755. //
  12756. let holeIndex = contour.length;
  12757. holes.forEach( removeDupEndPts );
  12758. for ( let i = 0; i < holes.length; i ++ ) {
  12759. holeIndices.push( holeIndex );
  12760. holeIndex += holes[ i ].length;
  12761. addContour( vertices, holes[ i ] );
  12762. }
  12763. //
  12764. const triangles = Earcut.triangulate( vertices, holeIndices );
  12765. //
  12766. for ( let i = 0; i < triangles.length; i += 3 ) {
  12767. faces.push( triangles.slice( i, i + 3 ) );
  12768. }
  12769. return faces;
  12770. }
  12771. }
  12772. function removeDupEndPts( points ) {
  12773. const l = points.length;
  12774. if ( l > 2 && points[ l - 1 ].equals( points[ 0 ] ) ) {
  12775. points.pop();
  12776. }
  12777. }
  12778. function addContour( vertices, contour ) {
  12779. for ( let i = 0; i < contour.length; i ++ ) {
  12780. vertices.push( contour[ i ].x );
  12781. vertices.push( contour[ i ].y );
  12782. }
  12783. }
  12784. /**
  12785. * Creates extruded geometry from a path shape.
  12786. *
  12787. * parameters = {
  12788. *
  12789. * curveSegments: <int>, // number of points on the curves
  12790. * steps: <int>, // number of points for z-side extrusions / used for subdividing segments of extrude spline too
  12791. * depth: <float>, // Depth to extrude the shape
  12792. *
  12793. * bevelEnabled: <bool>, // turn on bevel
  12794. * bevelThickness: <float>, // how deep into the original shape bevel goes
  12795. * bevelSize: <float>, // how far from shape outline (including bevelOffset) is bevel
  12796. * bevelOffset: <float>, // how far from shape outline does bevel start
  12797. * bevelSegments: <int>, // number of bevel layers
  12798. *
  12799. * extrudePath: <THREE.Curve> // curve to extrude shape along
  12800. *
  12801. * UVGenerator: <Object> // object that provides UV generator functions
  12802. *
  12803. * }
  12804. */
  12805. class ExtrudeGeometry extends BufferGeometry {
  12806. 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 = {} ) {
  12807. super();
  12808. this.type = 'ExtrudeGeometry';
  12809. this.parameters = {
  12810. shapes: shapes,
  12811. options: options
  12812. };
  12813. shapes = Array.isArray( shapes ) ? shapes : [ shapes ];
  12814. const scope = this;
  12815. const verticesArray = [];
  12816. const uvArray = [];
  12817. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  12818. const shape = shapes[ i ];
  12819. addShape( shape );
  12820. }
  12821. // build geometry
  12822. this.setAttribute( 'position', new Float32BufferAttribute( verticesArray, 3 ) );
  12823. this.setAttribute( 'uv', new Float32BufferAttribute( uvArray, 2 ) );
  12824. this.computeVertexNormals();
  12825. // functions
  12826. function addShape( shape ) {
  12827. const placeholder = [];
  12828. // options
  12829. const curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  12830. const steps = options.steps !== undefined ? options.steps : 1;
  12831. const depth = options.depth !== undefined ? options.depth : 1;
  12832. let bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true;
  12833. let bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 0.2;
  12834. let bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 0.1;
  12835. let bevelOffset = options.bevelOffset !== undefined ? options.bevelOffset : 0;
  12836. let bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  12837. const extrudePath = options.extrudePath;
  12838. const uvgen = options.UVGenerator !== undefined ? options.UVGenerator : WorldUVGenerator;
  12839. //
  12840. let extrudePts, extrudeByPath = false;
  12841. let splineTube, binormal, normal, position2;
  12842. if ( extrudePath ) {
  12843. extrudePts = extrudePath.getSpacedPoints( steps );
  12844. extrudeByPath = true;
  12845. bevelEnabled = false; // bevels not supported for path extrusion
  12846. // SETUP TNB variables
  12847. // TODO1 - have a .isClosed in spline?
  12848. splineTube = extrudePath.computeFrenetFrames( steps, false );
  12849. // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  12850. binormal = new Vector3();
  12851. normal = new Vector3();
  12852. position2 = new Vector3();
  12853. }
  12854. // Safeguards if bevels are not enabled
  12855. if ( ! bevelEnabled ) {
  12856. bevelSegments = 0;
  12857. bevelThickness = 0;
  12858. bevelSize = 0;
  12859. bevelOffset = 0;
  12860. }
  12861. // Variables initialization
  12862. const shapePoints = shape.extractPoints( curveSegments );
  12863. let vertices = shapePoints.shape;
  12864. const holes = shapePoints.holes;
  12865. const reverse = ! ShapeUtils.isClockWise( vertices );
  12866. if ( reverse ) {
  12867. vertices = vertices.reverse();
  12868. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  12869. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  12870. const ahole = holes[ h ];
  12871. if ( ShapeUtils.isClockWise( ahole ) ) {
  12872. holes[ h ] = ahole.reverse();
  12873. }
  12874. }
  12875. }
  12876. const faces = ShapeUtils.triangulateShape( vertices, holes );
  12877. /* Vertices */
  12878. const contour = vertices; // vertices has all points but contour has only points of circumference
  12879. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  12880. const ahole = holes[ h ];
  12881. vertices = vertices.concat( ahole );
  12882. }
  12883. function scalePt2( pt, vec, size ) {
  12884. if ( ! vec ) console.error( 'THREE.ExtrudeGeometry: vec does not exist' );
  12885. return pt.clone().addScaledVector( vec, size );
  12886. }
  12887. const vlen = vertices.length, flen = faces.length;
  12888. // Find directions for point movement
  12889. function getBevelVec( inPt, inPrev, inNext ) {
  12890. // computes for inPt the corresponding point inPt' on a new contour
  12891. // shifted by 1 unit (length of normalized vector) to the left
  12892. // if we walk along contour clockwise, this new contour is outside the old one
  12893. //
  12894. // inPt' is the intersection of the two lines parallel to the two
  12895. // adjacent edges of inPt at a distance of 1 unit on the left side.
  12896. let v_trans_x, v_trans_y, shrink_by; // resulting translation vector for inPt
  12897. // good reading for geometry algorithms (here: line-line intersection)
  12898. // http://geomalgorithms.com/a05-_intersect-1.html
  12899. const v_prev_x = inPt.x - inPrev.x,
  12900. v_prev_y = inPt.y - inPrev.y;
  12901. const v_next_x = inNext.x - inPt.x,
  12902. v_next_y = inNext.y - inPt.y;
  12903. const v_prev_lensq = ( v_prev_x * v_prev_x + v_prev_y * v_prev_y );
  12904. // check for collinear edges
  12905. const collinear0 = ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  12906. if ( Math.abs( collinear0 ) > Number.EPSILON ) {
  12907. // not collinear
  12908. // length of vectors for normalizing
  12909. const v_prev_len = Math.sqrt( v_prev_lensq );
  12910. const v_next_len = Math.sqrt( v_next_x * v_next_x + v_next_y * v_next_y );
  12911. // shift adjacent points by unit vectors to the left
  12912. const ptPrevShift_x = ( inPrev.x - v_prev_y / v_prev_len );
  12913. const ptPrevShift_y = ( inPrev.y + v_prev_x / v_prev_len );
  12914. const ptNextShift_x = ( inNext.x - v_next_y / v_next_len );
  12915. const ptNextShift_y = ( inNext.y + v_next_x / v_next_len );
  12916. // scaling factor for v_prev to intersection point
  12917. const sf = ( ( ptNextShift_x - ptPrevShift_x ) * v_next_y -
  12918. ( ptNextShift_y - ptPrevShift_y ) * v_next_x ) /
  12919. ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  12920. // vector from inPt to intersection point
  12921. v_trans_x = ( ptPrevShift_x + v_prev_x * sf - inPt.x );
  12922. v_trans_y = ( ptPrevShift_y + v_prev_y * sf - inPt.y );
  12923. // Don't normalize!, otherwise sharp corners become ugly
  12924. // but prevent crazy spikes
  12925. const v_trans_lensq = ( v_trans_x * v_trans_x + v_trans_y * v_trans_y );
  12926. if ( v_trans_lensq <= 2 ) {
  12927. return new Vector2( v_trans_x, v_trans_y );
  12928. } else {
  12929. shrink_by = Math.sqrt( v_trans_lensq / 2 );
  12930. }
  12931. } else {
  12932. // handle special case of collinear edges
  12933. let direction_eq = false; // assumes: opposite
  12934. if ( v_prev_x > Number.EPSILON ) {
  12935. if ( v_next_x > Number.EPSILON ) {
  12936. direction_eq = true;
  12937. }
  12938. } else {
  12939. if ( v_prev_x < - Number.EPSILON ) {
  12940. if ( v_next_x < - Number.EPSILON ) {
  12941. direction_eq = true;
  12942. }
  12943. } else {
  12944. if ( Math.sign( v_prev_y ) === Math.sign( v_next_y ) ) {
  12945. direction_eq = true;
  12946. }
  12947. }
  12948. }
  12949. if ( direction_eq ) {
  12950. // console.log("Warning: lines are a straight sequence");
  12951. v_trans_x = - v_prev_y;
  12952. v_trans_y = v_prev_x;
  12953. shrink_by = Math.sqrt( v_prev_lensq );
  12954. } else {
  12955. // console.log("Warning: lines are a straight spike");
  12956. v_trans_x = v_prev_x;
  12957. v_trans_y = v_prev_y;
  12958. shrink_by = Math.sqrt( v_prev_lensq / 2 );
  12959. }
  12960. }
  12961. return new Vector2( v_trans_x / shrink_by, v_trans_y / shrink_by );
  12962. }
  12963. const contourMovements = [];
  12964. for ( let i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  12965. if ( j === il ) j = 0;
  12966. if ( k === il ) k = 0;
  12967. // (j)---(i)---(k)
  12968. // console.log('i,j,k', i, j , k)
  12969. contourMovements[ i ] = getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  12970. }
  12971. const holesMovements = [];
  12972. let oneHoleMovements, verticesMovements = contourMovements.concat();
  12973. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  12974. const ahole = holes[ h ];
  12975. oneHoleMovements = [];
  12976. for ( let i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  12977. if ( j === il ) j = 0;
  12978. if ( k === il ) k = 0;
  12979. // (j)---(i)---(k)
  12980. oneHoleMovements[ i ] = getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  12981. }
  12982. holesMovements.push( oneHoleMovements );
  12983. verticesMovements = verticesMovements.concat( oneHoleMovements );
  12984. }
  12985. // Loop bevelSegments, 1 for the front, 1 for the back
  12986. for ( let b = 0; b < bevelSegments; b ++ ) {
  12987. //for ( b = bevelSegments; b > 0; b -- ) {
  12988. const t = b / bevelSegments;
  12989. const z = bevelThickness * Math.cos( t * Math.PI / 2 );
  12990. const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;
  12991. // contract shape
  12992. for ( let i = 0, il = contour.length; i < il; i ++ ) {
  12993. const vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  12994. v( vert.x, vert.y, - z );
  12995. }
  12996. // expand holes
  12997. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  12998. const ahole = holes[ h ];
  12999. oneHoleMovements = holesMovements[ h ];
  13000. for ( let i = 0, il = ahole.length; i < il; i ++ ) {
  13001. const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  13002. v( vert.x, vert.y, - z );
  13003. }
  13004. }
  13005. }
  13006. const bs = bevelSize + bevelOffset;
  13007. // Back facing vertices
  13008. for ( let i = 0; i < vlen; i ++ ) {
  13009. const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  13010. if ( ! extrudeByPath ) {
  13011. v( vert.x, vert.y, 0 );
  13012. } else {
  13013. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  13014. normal.copy( splineTube.normals[ 0 ] ).multiplyScalar( vert.x );
  13015. binormal.copy( splineTube.binormals[ 0 ] ).multiplyScalar( vert.y );
  13016. position2.copy( extrudePts[ 0 ] ).add( normal ).add( binormal );
  13017. v( position2.x, position2.y, position2.z );
  13018. }
  13019. }
  13020. // Add stepped vertices...
  13021. // Including front facing vertices
  13022. for ( let s = 1; s <= steps; s ++ ) {
  13023. for ( let i = 0; i < vlen; i ++ ) {
  13024. const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  13025. if ( ! extrudeByPath ) {
  13026. v( vert.x, vert.y, depth / steps * s );
  13027. } else {
  13028. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  13029. normal.copy( splineTube.normals[ s ] ).multiplyScalar( vert.x );
  13030. binormal.copy( splineTube.binormals[ s ] ).multiplyScalar( vert.y );
  13031. position2.copy( extrudePts[ s ] ).add( normal ).add( binormal );
  13032. v( position2.x, position2.y, position2.z );
  13033. }
  13034. }
  13035. }
  13036. // Add bevel segments planes
  13037. //for ( b = 1; b <= bevelSegments; b ++ ) {
  13038. for ( let b = bevelSegments - 1; b >= 0; b -- ) {
  13039. const t = b / bevelSegments;
  13040. const z = bevelThickness * Math.cos( t * Math.PI / 2 );
  13041. const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;
  13042. // contract shape
  13043. for ( let i = 0, il = contour.length; i < il; i ++ ) {
  13044. const vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  13045. v( vert.x, vert.y, depth + z );
  13046. }
  13047. // expand holes
  13048. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  13049. const ahole = holes[ h ];
  13050. oneHoleMovements = holesMovements[ h ];
  13051. for ( let i = 0, il = ahole.length; i < il; i ++ ) {
  13052. const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  13053. if ( ! extrudeByPath ) {
  13054. v( vert.x, vert.y, depth + z );
  13055. } else {
  13056. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  13057. }
  13058. }
  13059. }
  13060. }
  13061. /* Faces */
  13062. // Top and bottom faces
  13063. buildLidFaces();
  13064. // Sides faces
  13065. buildSideFaces();
  13066. ///// Internal functions
  13067. function buildLidFaces() {
  13068. const start = verticesArray.length / 3;
  13069. if ( bevelEnabled ) {
  13070. let layer = 0; // steps + 1
  13071. let offset = vlen * layer;
  13072. // Bottom faces
  13073. for ( let i = 0; i < flen; i ++ ) {
  13074. const face = faces[ i ];
  13075. f3( face[ 2 ] + offset, face[ 1 ] + offset, face[ 0 ] + offset );
  13076. }
  13077. layer = steps + bevelSegments * 2;
  13078. offset = vlen * layer;
  13079. // Top faces
  13080. for ( let i = 0; i < flen; i ++ ) {
  13081. const face = faces[ i ];
  13082. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset );
  13083. }
  13084. } else {
  13085. // Bottom faces
  13086. for ( let i = 0; i < flen; i ++ ) {
  13087. const face = faces[ i ];
  13088. f3( face[ 2 ], face[ 1 ], face[ 0 ] );
  13089. }
  13090. // Top faces
  13091. for ( let i = 0; i < flen; i ++ ) {
  13092. const face = faces[ i ];
  13093. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps );
  13094. }
  13095. }
  13096. scope.addGroup( start, verticesArray.length / 3 - start, 0 );
  13097. }
  13098. // Create faces for the z-sides of the shape
  13099. function buildSideFaces() {
  13100. const start = verticesArray.length / 3;
  13101. let layeroffset = 0;
  13102. sidewalls( contour, layeroffset );
  13103. layeroffset += contour.length;
  13104. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  13105. const ahole = holes[ h ];
  13106. sidewalls( ahole, layeroffset );
  13107. //, true
  13108. layeroffset += ahole.length;
  13109. }
  13110. scope.addGroup( start, verticesArray.length / 3 - start, 1 );
  13111. }
  13112. function sidewalls( contour, layeroffset ) {
  13113. let i = contour.length;
  13114. while ( -- i >= 0 ) {
  13115. const j = i;
  13116. let k = i - 1;
  13117. if ( k < 0 ) k = contour.length - 1;
  13118. //console.log('b', i,j, i-1, k,vertices.length);
  13119. for ( let s = 0, sl = ( steps + bevelSegments * 2 ); s < sl; s ++ ) {
  13120. const slen1 = vlen * s;
  13121. const slen2 = vlen * ( s + 1 );
  13122. const a = layeroffset + j + slen1,
  13123. b = layeroffset + k + slen1,
  13124. c = layeroffset + k + slen2,
  13125. d = layeroffset + j + slen2;
  13126. f4( a, b, c, d );
  13127. }
  13128. }
  13129. }
  13130. function v( x, y, z ) {
  13131. placeholder.push( x );
  13132. placeholder.push( y );
  13133. placeholder.push( z );
  13134. }
  13135. function f3( a, b, c ) {
  13136. addVertex( a );
  13137. addVertex( b );
  13138. addVertex( c );
  13139. const nextIndex = verticesArray.length / 3;
  13140. const uvs = uvgen.generateTopUV( scope, verticesArray, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  13141. addUV( uvs[ 0 ] );
  13142. addUV( uvs[ 1 ] );
  13143. addUV( uvs[ 2 ] );
  13144. }
  13145. function f4( a, b, c, d ) {
  13146. addVertex( a );
  13147. addVertex( b );
  13148. addVertex( d );
  13149. addVertex( b );
  13150. addVertex( c );
  13151. addVertex( d );
  13152. const nextIndex = verticesArray.length / 3;
  13153. const uvs = uvgen.generateSideWallUV( scope, verticesArray, nextIndex - 6, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  13154. addUV( uvs[ 0 ] );
  13155. addUV( uvs[ 1 ] );
  13156. addUV( uvs[ 3 ] );
  13157. addUV( uvs[ 1 ] );
  13158. addUV( uvs[ 2 ] );
  13159. addUV( uvs[ 3 ] );
  13160. }
  13161. function addVertex( index ) {
  13162. verticesArray.push( placeholder[ index * 3 + 0 ] );
  13163. verticesArray.push( placeholder[ index * 3 + 1 ] );
  13164. verticesArray.push( placeholder[ index * 3 + 2 ] );
  13165. }
  13166. function addUV( vector2 ) {
  13167. uvArray.push( vector2.x );
  13168. uvArray.push( vector2.y );
  13169. }
  13170. }
  13171. }
  13172. copy( source ) {
  13173. super.copy( source );
  13174. this.parameters = Object.assign( {}, source.parameters );
  13175. return this;
  13176. }
  13177. toJSON() {
  13178. const data = super.toJSON();
  13179. const shapes = this.parameters.shapes;
  13180. const options = this.parameters.options;
  13181. return toJSON$1( shapes, options, data );
  13182. }
  13183. static fromJSON( data, shapes ) {
  13184. const geometryShapes = [];
  13185. for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  13186. const shape = shapes[ data.shapes[ j ] ];
  13187. geometryShapes.push( shape );
  13188. }
  13189. const extrudePath = data.options.extrudePath;
  13190. if ( extrudePath !== undefined ) {
  13191. data.options.extrudePath = new Curves[ extrudePath.type ]().fromJSON( extrudePath );
  13192. }
  13193. return new ExtrudeGeometry( geometryShapes, data.options );
  13194. }
  13195. }
  13196. const WorldUVGenerator = {
  13197. generateTopUV: function ( geometry, vertices, indexA, indexB, indexC ) {
  13198. const a_x = vertices[ indexA * 3 ];
  13199. const a_y = vertices[ indexA * 3 + 1 ];
  13200. const b_x = vertices[ indexB * 3 ];
  13201. const b_y = vertices[ indexB * 3 + 1 ];
  13202. const c_x = vertices[ indexC * 3 ];
  13203. const c_y = vertices[ indexC * 3 + 1 ];
  13204. return [
  13205. new Vector2( a_x, a_y ),
  13206. new Vector2( b_x, b_y ),
  13207. new Vector2( c_x, c_y )
  13208. ];
  13209. },
  13210. generateSideWallUV: function ( geometry, vertices, indexA, indexB, indexC, indexD ) {
  13211. const a_x = vertices[ indexA * 3 ];
  13212. const a_y = vertices[ indexA * 3 + 1 ];
  13213. const a_z = vertices[ indexA * 3 + 2 ];
  13214. const b_x = vertices[ indexB * 3 ];
  13215. const b_y = vertices[ indexB * 3 + 1 ];
  13216. const b_z = vertices[ indexB * 3 + 2 ];
  13217. const c_x = vertices[ indexC * 3 ];
  13218. const c_y = vertices[ indexC * 3 + 1 ];
  13219. const c_z = vertices[ indexC * 3 + 2 ];
  13220. const d_x = vertices[ indexD * 3 ];
  13221. const d_y = vertices[ indexD * 3 + 1 ];
  13222. const d_z = vertices[ indexD * 3 + 2 ];
  13223. if ( Math.abs( a_y - b_y ) < Math.abs( a_x - b_x ) ) {
  13224. return [
  13225. new Vector2( a_x, 1 - a_z ),
  13226. new Vector2( b_x, 1 - b_z ),
  13227. new Vector2( c_x, 1 - c_z ),
  13228. new Vector2( d_x, 1 - d_z )
  13229. ];
  13230. } else {
  13231. return [
  13232. new Vector2( a_y, 1 - a_z ),
  13233. new Vector2( b_y, 1 - b_z ),
  13234. new Vector2( c_y, 1 - c_z ),
  13235. new Vector2( d_y, 1 - d_z )
  13236. ];
  13237. }
  13238. }
  13239. };
  13240. function toJSON$1( shapes, options, data ) {
  13241. data.shapes = [];
  13242. if ( Array.isArray( shapes ) ) {
  13243. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  13244. const shape = shapes[ i ];
  13245. data.shapes.push( shape.uuid );
  13246. }
  13247. } else {
  13248. data.shapes.push( shapes.uuid );
  13249. }
  13250. data.options = Object.assign( {}, options );
  13251. if ( options.extrudePath !== undefined ) data.options.extrudePath = options.extrudePath.toJSON();
  13252. return data;
  13253. }
  13254. class IcosahedronGeometry extends PolyhedronGeometry {
  13255. constructor( radius = 1, detail = 0 ) {
  13256. const t = ( 1 + Math.sqrt( 5 ) ) / 2;
  13257. const vertices = [
  13258. - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t, 0,
  13259. 0, - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t,
  13260. t, 0, - 1, t, 0, 1, - t, 0, - 1, - t, 0, 1
  13261. ];
  13262. const indices = [
  13263. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 0, 10, 11,
  13264. 1, 5, 9, 5, 11, 4, 11, 10, 2, 10, 7, 6, 7, 1, 8,
  13265. 3, 9, 4, 3, 4, 2, 3, 2, 6, 3, 6, 8, 3, 8, 9,
  13266. 4, 9, 5, 2, 4, 11, 6, 2, 10, 8, 6, 7, 9, 8, 1
  13267. ];
  13268. super( vertices, indices, radius, detail );
  13269. this.type = 'IcosahedronGeometry';
  13270. this.parameters = {
  13271. radius: radius,
  13272. detail: detail
  13273. };
  13274. }
  13275. static fromJSON( data ) {
  13276. return new IcosahedronGeometry( data.radius, data.detail );
  13277. }
  13278. }
  13279. class OctahedronGeometry extends PolyhedronGeometry {
  13280. constructor( radius = 1, detail = 0 ) {
  13281. const vertices = [
  13282. 1, 0, 0, - 1, 0, 0, 0, 1, 0,
  13283. 0, - 1, 0, 0, 0, 1, 0, 0, - 1
  13284. ];
  13285. const indices = [
  13286. 0, 2, 4, 0, 4, 3, 0, 3, 5,
  13287. 0, 5, 2, 1, 2, 5, 1, 5, 3,
  13288. 1, 3, 4, 1, 4, 2
  13289. ];
  13290. super( vertices, indices, radius, detail );
  13291. this.type = 'OctahedronGeometry';
  13292. this.parameters = {
  13293. radius: radius,
  13294. detail: detail
  13295. };
  13296. }
  13297. static fromJSON( data ) {
  13298. return new OctahedronGeometry( data.radius, data.detail );
  13299. }
  13300. }
  13301. class PlaneGeometry extends BufferGeometry {
  13302. constructor( width = 1, height = 1, widthSegments = 1, heightSegments = 1 ) {
  13303. super();
  13304. this.type = 'PlaneGeometry';
  13305. this.parameters = {
  13306. width: width,
  13307. height: height,
  13308. widthSegments: widthSegments,
  13309. heightSegments: heightSegments
  13310. };
  13311. const width_half = width / 2;
  13312. const height_half = height / 2;
  13313. const gridX = Math.floor( widthSegments );
  13314. const gridY = Math.floor( heightSegments );
  13315. const gridX1 = gridX + 1;
  13316. const gridY1 = gridY + 1;
  13317. const segment_width = width / gridX;
  13318. const segment_height = height / gridY;
  13319. //
  13320. const indices = [];
  13321. const vertices = [];
  13322. const normals = [];
  13323. const uvs = [];
  13324. for ( let iy = 0; iy < gridY1; iy ++ ) {
  13325. const y = iy * segment_height - height_half;
  13326. for ( let ix = 0; ix < gridX1; ix ++ ) {
  13327. const x = ix * segment_width - width_half;
  13328. vertices.push( x, - y, 0 );
  13329. normals.push( 0, 0, 1 );
  13330. uvs.push( ix / gridX );
  13331. uvs.push( 1 - ( iy / gridY ) );
  13332. }
  13333. }
  13334. for ( let iy = 0; iy < gridY; iy ++ ) {
  13335. for ( let ix = 0; ix < gridX; ix ++ ) {
  13336. const a = ix + gridX1 * iy;
  13337. const b = ix + gridX1 * ( iy + 1 );
  13338. const c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  13339. const d = ( ix + 1 ) + gridX1 * iy;
  13340. indices.push( a, b, d );
  13341. indices.push( b, c, d );
  13342. }
  13343. }
  13344. this.setIndex( indices );
  13345. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  13346. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  13347. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  13348. }
  13349. copy( source ) {
  13350. super.copy( source );
  13351. this.parameters = Object.assign( {}, source.parameters );
  13352. return this;
  13353. }
  13354. static fromJSON( data ) {
  13355. return new PlaneGeometry( data.width, data.height, data.widthSegments, data.heightSegments );
  13356. }
  13357. }
  13358. class RingGeometry extends BufferGeometry {
  13359. constructor( innerRadius = 0.5, outerRadius = 1, thetaSegments = 32, phiSegments = 1, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  13360. super();
  13361. this.type = 'RingGeometry';
  13362. this.parameters = {
  13363. innerRadius: innerRadius,
  13364. outerRadius: outerRadius,
  13365. thetaSegments: thetaSegments,
  13366. phiSegments: phiSegments,
  13367. thetaStart: thetaStart,
  13368. thetaLength: thetaLength
  13369. };
  13370. thetaSegments = Math.max( 3, thetaSegments );
  13371. phiSegments = Math.max( 1, phiSegments );
  13372. // buffers
  13373. const indices = [];
  13374. const vertices = [];
  13375. const normals = [];
  13376. const uvs = [];
  13377. // some helper variables
  13378. let radius = innerRadius;
  13379. const radiusStep = ( ( outerRadius - innerRadius ) / phiSegments );
  13380. const vertex = new Vector3();
  13381. const uv = new Vector2();
  13382. // generate vertices, normals and uvs
  13383. for ( let j = 0; j <= phiSegments; j ++ ) {
  13384. for ( let i = 0; i <= thetaSegments; i ++ ) {
  13385. // values are generate from the inside of the ring to the outside
  13386. const segment = thetaStart + i / thetaSegments * thetaLength;
  13387. // vertex
  13388. vertex.x = radius * Math.cos( segment );
  13389. vertex.y = radius * Math.sin( segment );
  13390. vertices.push( vertex.x, vertex.y, vertex.z );
  13391. // normal
  13392. normals.push( 0, 0, 1 );
  13393. // uv
  13394. uv.x = ( vertex.x / outerRadius + 1 ) / 2;
  13395. uv.y = ( vertex.y / outerRadius + 1 ) / 2;
  13396. uvs.push( uv.x, uv.y );
  13397. }
  13398. // increase the radius for next row of vertices
  13399. radius += radiusStep;
  13400. }
  13401. // indices
  13402. for ( let j = 0; j < phiSegments; j ++ ) {
  13403. const thetaSegmentLevel = j * ( thetaSegments + 1 );
  13404. for ( let i = 0; i < thetaSegments; i ++ ) {
  13405. const segment = i + thetaSegmentLevel;
  13406. const a = segment;
  13407. const b = segment + thetaSegments + 1;
  13408. const c = segment + thetaSegments + 2;
  13409. const d = segment + 1;
  13410. // faces
  13411. indices.push( a, b, d );
  13412. indices.push( b, c, d );
  13413. }
  13414. }
  13415. // build geometry
  13416. this.setIndex( indices );
  13417. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  13418. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  13419. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  13420. }
  13421. copy( source ) {
  13422. super.copy( source );
  13423. this.parameters = Object.assign( {}, source.parameters );
  13424. return this;
  13425. }
  13426. static fromJSON( data ) {
  13427. return new RingGeometry( data.innerRadius, data.outerRadius, data.thetaSegments, data.phiSegments, data.thetaStart, data.thetaLength );
  13428. }
  13429. }
  13430. class ShapeGeometry extends BufferGeometry {
  13431. constructor( shapes = new Shape( [ new Vector2( 0, 0.5 ), new Vector2( - 0.5, - 0.5 ), new Vector2( 0.5, - 0.5 ) ] ), curveSegments = 12 ) {
  13432. super();
  13433. this.type = 'ShapeGeometry';
  13434. this.parameters = {
  13435. shapes: shapes,
  13436. curveSegments: curveSegments
  13437. };
  13438. // buffers
  13439. const indices = [];
  13440. const vertices = [];
  13441. const normals = [];
  13442. const uvs = [];
  13443. // helper variables
  13444. let groupStart = 0;
  13445. let groupCount = 0;
  13446. // allow single and array values for "shapes" parameter
  13447. if ( Array.isArray( shapes ) === false ) {
  13448. addShape( shapes );
  13449. } else {
  13450. for ( let i = 0; i < shapes.length; i ++ ) {
  13451. addShape( shapes[ i ] );
  13452. this.addGroup( groupStart, groupCount, i ); // enables MultiMaterial support
  13453. groupStart += groupCount;
  13454. groupCount = 0;
  13455. }
  13456. }
  13457. // build geometry
  13458. this.setIndex( indices );
  13459. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  13460. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  13461. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  13462. // helper functions
  13463. function addShape( shape ) {
  13464. const indexOffset = vertices.length / 3;
  13465. const points = shape.extractPoints( curveSegments );
  13466. let shapeVertices = points.shape;
  13467. const shapeHoles = points.holes;
  13468. // check direction of vertices
  13469. if ( ShapeUtils.isClockWise( shapeVertices ) === false ) {
  13470. shapeVertices = shapeVertices.reverse();
  13471. }
  13472. for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) {
  13473. const shapeHole = shapeHoles[ i ];
  13474. if ( ShapeUtils.isClockWise( shapeHole ) === true ) {
  13475. shapeHoles[ i ] = shapeHole.reverse();
  13476. }
  13477. }
  13478. const faces = ShapeUtils.triangulateShape( shapeVertices, shapeHoles );
  13479. // join vertices of inner and outer paths to a single array
  13480. for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) {
  13481. const shapeHole = shapeHoles[ i ];
  13482. shapeVertices = shapeVertices.concat( shapeHole );
  13483. }
  13484. // vertices, normals, uvs
  13485. for ( let i = 0, l = shapeVertices.length; i < l; i ++ ) {
  13486. const vertex = shapeVertices[ i ];
  13487. vertices.push( vertex.x, vertex.y, 0 );
  13488. normals.push( 0, 0, 1 );
  13489. uvs.push( vertex.x, vertex.y ); // world uvs
  13490. }
  13491. // indices
  13492. for ( let i = 0, l = faces.length; i < l; i ++ ) {
  13493. const face = faces[ i ];
  13494. const a = face[ 0 ] + indexOffset;
  13495. const b = face[ 1 ] + indexOffset;
  13496. const c = face[ 2 ] + indexOffset;
  13497. indices.push( a, b, c );
  13498. groupCount += 3;
  13499. }
  13500. }
  13501. }
  13502. copy( source ) {
  13503. super.copy( source );
  13504. this.parameters = Object.assign( {}, source.parameters );
  13505. return this;
  13506. }
  13507. toJSON() {
  13508. const data = super.toJSON();
  13509. const shapes = this.parameters.shapes;
  13510. return toJSON( shapes, data );
  13511. }
  13512. static fromJSON( data, shapes ) {
  13513. const geometryShapes = [];
  13514. for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  13515. const shape = shapes[ data.shapes[ j ] ];
  13516. geometryShapes.push( shape );
  13517. }
  13518. return new ShapeGeometry( geometryShapes, data.curveSegments );
  13519. }
  13520. }
  13521. function toJSON( shapes, data ) {
  13522. data.shapes = [];
  13523. if ( Array.isArray( shapes ) ) {
  13524. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  13525. const shape = shapes[ i ];
  13526. data.shapes.push( shape.uuid );
  13527. }
  13528. } else {
  13529. data.shapes.push( shapes.uuid );
  13530. }
  13531. return data;
  13532. }
  13533. class SphereGeometry extends BufferGeometry {
  13534. constructor( radius = 1, widthSegments = 32, heightSegments = 16, phiStart = 0, phiLength = Math.PI * 2, thetaStart = 0, thetaLength = Math.PI ) {
  13535. super();
  13536. this.type = 'SphereGeometry';
  13537. this.parameters = {
  13538. radius: radius,
  13539. widthSegments: widthSegments,
  13540. heightSegments: heightSegments,
  13541. phiStart: phiStart,
  13542. phiLength: phiLength,
  13543. thetaStart: thetaStart,
  13544. thetaLength: thetaLength
  13545. };
  13546. widthSegments = Math.max( 3, Math.floor( widthSegments ) );
  13547. heightSegments = Math.max( 2, Math.floor( heightSegments ) );
  13548. const thetaEnd = Math.min( thetaStart + thetaLength, Math.PI );
  13549. let index = 0;
  13550. const grid = [];
  13551. const vertex = new Vector3();
  13552. const normal = new Vector3();
  13553. // buffers
  13554. const indices = [];
  13555. const vertices = [];
  13556. const normals = [];
  13557. const uvs = [];
  13558. // generate vertices, normals and uvs
  13559. for ( let iy = 0; iy <= heightSegments; iy ++ ) {
  13560. const verticesRow = [];
  13561. const v = iy / heightSegments;
  13562. // special case for the poles
  13563. let uOffset = 0;
  13564. if ( iy === 0 && thetaStart === 0 ) {
  13565. uOffset = 0.5 / widthSegments;
  13566. } else if ( iy === heightSegments && thetaEnd === Math.PI ) {
  13567. uOffset = - 0.5 / widthSegments;
  13568. }
  13569. for ( let ix = 0; ix <= widthSegments; ix ++ ) {
  13570. const u = ix / widthSegments;
  13571. // vertex
  13572. vertex.x = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  13573. vertex.y = radius * Math.cos( thetaStart + v * thetaLength );
  13574. vertex.z = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  13575. vertices.push( vertex.x, vertex.y, vertex.z );
  13576. // normal
  13577. normal.copy( vertex ).normalize();
  13578. normals.push( normal.x, normal.y, normal.z );
  13579. // uv
  13580. uvs.push( u + uOffset, 1 - v );
  13581. verticesRow.push( index ++ );
  13582. }
  13583. grid.push( verticesRow );
  13584. }
  13585. // indices
  13586. for ( let iy = 0; iy < heightSegments; iy ++ ) {
  13587. for ( let ix = 0; ix < widthSegments; ix ++ ) {
  13588. const a = grid[ iy ][ ix + 1 ];
  13589. const b = grid[ iy ][ ix ];
  13590. const c = grid[ iy + 1 ][ ix ];
  13591. const d = grid[ iy + 1 ][ ix + 1 ];
  13592. if ( iy !== 0 || thetaStart > 0 ) indices.push( a, b, d );
  13593. if ( iy !== heightSegments - 1 || thetaEnd < Math.PI ) indices.push( b, c, d );
  13594. }
  13595. }
  13596. // build geometry
  13597. this.setIndex( indices );
  13598. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  13599. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  13600. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  13601. }
  13602. copy( source ) {
  13603. super.copy( source );
  13604. this.parameters = Object.assign( {}, source.parameters );
  13605. return this;
  13606. }
  13607. static fromJSON( data ) {
  13608. return new SphereGeometry( data.radius, data.widthSegments, data.heightSegments, data.phiStart, data.phiLength, data.thetaStart, data.thetaLength );
  13609. }
  13610. }
  13611. class TetrahedronGeometry extends PolyhedronGeometry {
  13612. constructor( radius = 1, detail = 0 ) {
  13613. const vertices = [
  13614. 1, 1, 1, - 1, - 1, 1, - 1, 1, - 1, 1, - 1, - 1
  13615. ];
  13616. const indices = [
  13617. 2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1
  13618. ];
  13619. super( vertices, indices, radius, detail );
  13620. this.type = 'TetrahedronGeometry';
  13621. this.parameters = {
  13622. radius: radius,
  13623. detail: detail
  13624. };
  13625. }
  13626. static fromJSON( data ) {
  13627. return new TetrahedronGeometry( data.radius, data.detail );
  13628. }
  13629. }
  13630. class TorusGeometry extends BufferGeometry {
  13631. constructor( radius = 1, tube = 0.4, radialSegments = 12, tubularSegments = 48, arc = Math.PI * 2 ) {
  13632. super();
  13633. this.type = 'TorusGeometry';
  13634. this.parameters = {
  13635. radius: radius,
  13636. tube: tube,
  13637. radialSegments: radialSegments,
  13638. tubularSegments: tubularSegments,
  13639. arc: arc
  13640. };
  13641. radialSegments = Math.floor( radialSegments );
  13642. tubularSegments = Math.floor( tubularSegments );
  13643. // buffers
  13644. const indices = [];
  13645. const vertices = [];
  13646. const normals = [];
  13647. const uvs = [];
  13648. // helper variables
  13649. const center = new Vector3();
  13650. const vertex = new Vector3();
  13651. const normal = new Vector3();
  13652. // generate vertices, normals and uvs
  13653. for ( let j = 0; j <= radialSegments; j ++ ) {
  13654. for ( let i = 0; i <= tubularSegments; i ++ ) {
  13655. const u = i / tubularSegments * arc;
  13656. const v = j / radialSegments * Math.PI * 2;
  13657. // vertex
  13658. vertex.x = ( radius + tube * Math.cos( v ) ) * Math.cos( u );
  13659. vertex.y = ( radius + tube * Math.cos( v ) ) * Math.sin( u );
  13660. vertex.z = tube * Math.sin( v );
  13661. vertices.push( vertex.x, vertex.y, vertex.z );
  13662. // normal
  13663. center.x = radius * Math.cos( u );
  13664. center.y = radius * Math.sin( u );
  13665. normal.subVectors( vertex, center ).normalize();
  13666. normals.push( normal.x, normal.y, normal.z );
  13667. // uv
  13668. uvs.push( i / tubularSegments );
  13669. uvs.push( j / radialSegments );
  13670. }
  13671. }
  13672. // generate indices
  13673. for ( let j = 1; j <= radialSegments; j ++ ) {
  13674. for ( let i = 1; i <= tubularSegments; i ++ ) {
  13675. // indices
  13676. const a = ( tubularSegments + 1 ) * j + i - 1;
  13677. const b = ( tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  13678. const c = ( tubularSegments + 1 ) * ( j - 1 ) + i;
  13679. const d = ( tubularSegments + 1 ) * j + i;
  13680. // faces
  13681. indices.push( a, b, d );
  13682. indices.push( b, c, d );
  13683. }
  13684. }
  13685. // build geometry
  13686. this.setIndex( indices );
  13687. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  13688. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  13689. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  13690. }
  13691. copy( source ) {
  13692. super.copy( source );
  13693. this.parameters = Object.assign( {}, source.parameters );
  13694. return this;
  13695. }
  13696. static fromJSON( data ) {
  13697. return new TorusGeometry( data.radius, data.tube, data.radialSegments, data.tubularSegments, data.arc );
  13698. }
  13699. }
  13700. class TorusKnotGeometry extends BufferGeometry {
  13701. constructor( radius = 1, tube = 0.4, tubularSegments = 64, radialSegments = 8, p = 2, q = 3 ) {
  13702. super();
  13703. this.type = 'TorusKnotGeometry';
  13704. this.parameters = {
  13705. radius: radius,
  13706. tube: tube,
  13707. tubularSegments: tubularSegments,
  13708. radialSegments: radialSegments,
  13709. p: p,
  13710. q: q
  13711. };
  13712. tubularSegments = Math.floor( tubularSegments );
  13713. radialSegments = Math.floor( radialSegments );
  13714. // buffers
  13715. const indices = [];
  13716. const vertices = [];
  13717. const normals = [];
  13718. const uvs = [];
  13719. // helper variables
  13720. const vertex = new Vector3();
  13721. const normal = new Vector3();
  13722. const P1 = new Vector3();
  13723. const P2 = new Vector3();
  13724. const B = new Vector3();
  13725. const T = new Vector3();
  13726. const N = new Vector3();
  13727. // generate vertices, normals and uvs
  13728. for ( let i = 0; i <= tubularSegments; ++ i ) {
  13729. // the radian "u" is used to calculate the position on the torus curve of the current tubular segment
  13730. const u = i / tubularSegments * p * Math.PI * 2;
  13731. // now we calculate two points. P1 is our current position on the curve, P2 is a little farther ahead.
  13732. // these points are used to create a special "coordinate space", which is necessary to calculate the correct vertex positions
  13733. calculatePositionOnCurve( u, p, q, radius, P1 );
  13734. calculatePositionOnCurve( u + 0.01, p, q, radius, P2 );
  13735. // calculate orthonormal basis
  13736. T.subVectors( P2, P1 );
  13737. N.addVectors( P2, P1 );
  13738. B.crossVectors( T, N );
  13739. N.crossVectors( B, T );
  13740. // normalize B, N. T can be ignored, we don't use it
  13741. B.normalize();
  13742. N.normalize();
  13743. for ( let j = 0; j <= radialSegments; ++ j ) {
  13744. // now calculate the vertices. they are nothing more than an extrusion of the torus curve.
  13745. // because we extrude a shape in the xy-plane, there is no need to calculate a z-value.
  13746. const v = j / radialSegments * Math.PI * 2;
  13747. const cx = - tube * Math.cos( v );
  13748. const cy = tube * Math.sin( v );
  13749. // now calculate the final vertex position.
  13750. // first we orient the extrusion with our basis vectors, then we add it to the current position on the curve
  13751. vertex.x = P1.x + ( cx * N.x + cy * B.x );
  13752. vertex.y = P1.y + ( cx * N.y + cy * B.y );
  13753. vertex.z = P1.z + ( cx * N.z + cy * B.z );
  13754. vertices.push( vertex.x, vertex.y, vertex.z );
  13755. // normal (P1 is always the center/origin of the extrusion, thus we can use it to calculate the normal)
  13756. normal.subVectors( vertex, P1 ).normalize();
  13757. normals.push( normal.x, normal.y, normal.z );
  13758. // uv
  13759. uvs.push( i / tubularSegments );
  13760. uvs.push( j / radialSegments );
  13761. }
  13762. }
  13763. // generate indices
  13764. for ( let j = 1; j <= tubularSegments; j ++ ) {
  13765. for ( let i = 1; i <= radialSegments; i ++ ) {
  13766. // indices
  13767. const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  13768. const b = ( radialSegments + 1 ) * j + ( i - 1 );
  13769. const c = ( radialSegments + 1 ) * j + i;
  13770. const d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  13771. // faces
  13772. indices.push( a, b, d );
  13773. indices.push( b, c, d );
  13774. }
  13775. }
  13776. // build geometry
  13777. this.setIndex( indices );
  13778. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  13779. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  13780. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  13781. // this function calculates the current position on the torus curve
  13782. function calculatePositionOnCurve( u, p, q, radius, position ) {
  13783. const cu = Math.cos( u );
  13784. const su = Math.sin( u );
  13785. const quOverP = q / p * u;
  13786. const cs = Math.cos( quOverP );
  13787. position.x = radius * ( 2 + cs ) * 0.5 * cu;
  13788. position.y = radius * ( 2 + cs ) * su * 0.5;
  13789. position.z = radius * Math.sin( quOverP ) * 0.5;
  13790. }
  13791. }
  13792. copy( source ) {
  13793. super.copy( source );
  13794. this.parameters = Object.assign( {}, source.parameters );
  13795. return this;
  13796. }
  13797. static fromJSON( data ) {
  13798. return new TorusKnotGeometry( data.radius, data.tube, data.tubularSegments, data.radialSegments, data.p, data.q );
  13799. }
  13800. }
  13801. class TubeGeometry extends BufferGeometry {
  13802. 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 ) {
  13803. super();
  13804. this.type = 'TubeGeometry';
  13805. this.parameters = {
  13806. path: path,
  13807. tubularSegments: tubularSegments,
  13808. radius: radius,
  13809. radialSegments: radialSegments,
  13810. closed: closed
  13811. };
  13812. const frames = path.computeFrenetFrames( tubularSegments, closed );
  13813. // expose internals
  13814. this.tangents = frames.tangents;
  13815. this.normals = frames.normals;
  13816. this.binormals = frames.binormals;
  13817. // helper variables
  13818. const vertex = new Vector3();
  13819. const normal = new Vector3();
  13820. const uv = new Vector2();
  13821. let P = new Vector3();
  13822. // buffer
  13823. const vertices = [];
  13824. const normals = [];
  13825. const uvs = [];
  13826. const indices = [];
  13827. // create buffer data
  13828. generateBufferData();
  13829. // build geometry
  13830. this.setIndex( indices );
  13831. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  13832. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  13833. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  13834. // functions
  13835. function generateBufferData() {
  13836. for ( let i = 0; i < tubularSegments; i ++ ) {
  13837. generateSegment( i );
  13838. }
  13839. // if the geometry is not closed, generate the last row of vertices and normals
  13840. // at the regular position on the given path
  13841. //
  13842. // if the geometry is closed, duplicate the first row of vertices and normals (uvs will differ)
  13843. generateSegment( ( closed === false ) ? tubularSegments : 0 );
  13844. // uvs are generated in a separate function.
  13845. // this makes it easy compute correct values for closed geometries
  13846. generateUVs();
  13847. // finally create faces
  13848. generateIndices();
  13849. }
  13850. function generateSegment( i ) {
  13851. // we use getPointAt to sample evenly distributed points from the given path
  13852. P = path.getPointAt( i / tubularSegments, P );
  13853. // retrieve corresponding normal and binormal
  13854. const N = frames.normals[ i ];
  13855. const B = frames.binormals[ i ];
  13856. // generate normals and vertices for the current segment
  13857. for ( let j = 0; j <= radialSegments; j ++ ) {
  13858. const v = j / radialSegments * Math.PI * 2;
  13859. const sin = Math.sin( v );
  13860. const cos = - Math.cos( v );
  13861. // normal
  13862. normal.x = ( cos * N.x + sin * B.x );
  13863. normal.y = ( cos * N.y + sin * B.y );
  13864. normal.z = ( cos * N.z + sin * B.z );
  13865. normal.normalize();
  13866. normals.push( normal.x, normal.y, normal.z );
  13867. // vertex
  13868. vertex.x = P.x + radius * normal.x;
  13869. vertex.y = P.y + radius * normal.y;
  13870. vertex.z = P.z + radius * normal.z;
  13871. vertices.push( vertex.x, vertex.y, vertex.z );
  13872. }
  13873. }
  13874. function generateIndices() {
  13875. for ( let j = 1; j <= tubularSegments; j ++ ) {
  13876. for ( let i = 1; i <= radialSegments; i ++ ) {
  13877. const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  13878. const b = ( radialSegments + 1 ) * j + ( i - 1 );
  13879. const c = ( radialSegments + 1 ) * j + i;
  13880. const d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  13881. // faces
  13882. indices.push( a, b, d );
  13883. indices.push( b, c, d );
  13884. }
  13885. }
  13886. }
  13887. function generateUVs() {
  13888. for ( let i = 0; i <= tubularSegments; i ++ ) {
  13889. for ( let j = 0; j <= radialSegments; j ++ ) {
  13890. uv.x = i / tubularSegments;
  13891. uv.y = j / radialSegments;
  13892. uvs.push( uv.x, uv.y );
  13893. }
  13894. }
  13895. }
  13896. }
  13897. copy( source ) {
  13898. super.copy( source );
  13899. this.parameters = Object.assign( {}, source.parameters );
  13900. return this;
  13901. }
  13902. toJSON() {
  13903. const data = super.toJSON();
  13904. data.path = this.parameters.path.toJSON();
  13905. return data;
  13906. }
  13907. static fromJSON( data ) {
  13908. // This only works for built-in curves (e.g. CatmullRomCurve3).
  13909. // User defined curves or instances of CurvePath will not be deserialized.
  13910. return new TubeGeometry(
  13911. new Curves[ data.path.type ]().fromJSON( data.path ),
  13912. data.tubularSegments,
  13913. data.radius,
  13914. data.radialSegments,
  13915. data.closed
  13916. );
  13917. }
  13918. }
  13919. class WireframeGeometry extends BufferGeometry {
  13920. constructor( geometry = null ) {
  13921. super();
  13922. this.type = 'WireframeGeometry';
  13923. this.parameters = {
  13924. geometry: geometry
  13925. };
  13926. if ( geometry !== null ) {
  13927. // buffer
  13928. const vertices = [];
  13929. const edges = new Set();
  13930. // helper variables
  13931. const start = new Vector3();
  13932. const end = new Vector3();
  13933. if ( geometry.index !== null ) {
  13934. // indexed BufferGeometry
  13935. const position = geometry.attributes.position;
  13936. const indices = geometry.index;
  13937. let groups = geometry.groups;
  13938. if ( groups.length === 0 ) {
  13939. groups = [ { start: 0, count: indices.count, materialIndex: 0 } ];
  13940. }
  13941. // create a data structure that contains all edges without duplicates
  13942. for ( let o = 0, ol = groups.length; o < ol; ++ o ) {
  13943. const group = groups[ o ];
  13944. const groupStart = group.start;
  13945. const groupCount = group.count;
  13946. for ( let i = groupStart, l = ( groupStart + groupCount ); i < l; i += 3 ) {
  13947. for ( let j = 0; j < 3; j ++ ) {
  13948. const index1 = indices.getX( i + j );
  13949. const index2 = indices.getX( i + ( j + 1 ) % 3 );
  13950. start.fromBufferAttribute( position, index1 );
  13951. end.fromBufferAttribute( position, index2 );
  13952. if ( isUniqueEdge( start, end, edges ) === true ) {
  13953. vertices.push( start.x, start.y, start.z );
  13954. vertices.push( end.x, end.y, end.z );
  13955. }
  13956. }
  13957. }
  13958. }
  13959. } else {
  13960. // non-indexed BufferGeometry
  13961. const position = geometry.attributes.position;
  13962. for ( let i = 0, l = ( position.count / 3 ); i < l; i ++ ) {
  13963. for ( let j = 0; j < 3; j ++ ) {
  13964. // three edges per triangle, an edge is represented as (index1, index2)
  13965. // e.g. the first triangle has the following edges: (0,1),(1,2),(2,0)
  13966. const index1 = 3 * i + j;
  13967. const index2 = 3 * i + ( ( j + 1 ) % 3 );
  13968. start.fromBufferAttribute( position, index1 );
  13969. end.fromBufferAttribute( position, index2 );
  13970. if ( isUniqueEdge( start, end, edges ) === true ) {
  13971. vertices.push( start.x, start.y, start.z );
  13972. vertices.push( end.x, end.y, end.z );
  13973. }
  13974. }
  13975. }
  13976. }
  13977. // build geometry
  13978. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  13979. }
  13980. }
  13981. copy( source ) {
  13982. super.copy( source );
  13983. this.parameters = Object.assign( {}, source.parameters );
  13984. return this;
  13985. }
  13986. }
  13987. function isUniqueEdge( start, end, edges ) {
  13988. const hash1 = `${start.x},${start.y},${start.z}-${end.x},${end.y},${end.z}`;
  13989. const hash2 = `${end.x},${end.y},${end.z}-${start.x},${start.y},${start.z}`; // coincident edge
  13990. if ( edges.has( hash1 ) === true || edges.has( hash2 ) === true ) {
  13991. return false;
  13992. } else {
  13993. edges.add( hash1 );
  13994. edges.add( hash2 );
  13995. return true;
  13996. }
  13997. }
  13998. var Geometries$1 = /*#__PURE__*/Object.freeze({
  13999. __proto__: null,
  14000. BoxGeometry: BoxGeometry,
  14001. CapsuleGeometry: CapsuleGeometry,
  14002. CircleGeometry: CircleGeometry,
  14003. ConeGeometry: ConeGeometry,
  14004. CylinderGeometry: CylinderGeometry,
  14005. DodecahedronGeometry: DodecahedronGeometry,
  14006. EdgesGeometry: EdgesGeometry,
  14007. ExtrudeGeometry: ExtrudeGeometry,
  14008. IcosahedronGeometry: IcosahedronGeometry,
  14009. LatheGeometry: LatheGeometry,
  14010. OctahedronGeometry: OctahedronGeometry,
  14011. PlaneGeometry: PlaneGeometry,
  14012. PolyhedronGeometry: PolyhedronGeometry,
  14013. RingGeometry: RingGeometry,
  14014. ShapeGeometry: ShapeGeometry,
  14015. SphereGeometry: SphereGeometry,
  14016. TetrahedronGeometry: TetrahedronGeometry,
  14017. TorusGeometry: TorusGeometry,
  14018. TorusKnotGeometry: TorusKnotGeometry,
  14019. TubeGeometry: TubeGeometry,
  14020. WireframeGeometry: WireframeGeometry
  14021. });
  14022. class ShadowMaterial extends Material {
  14023. static get type() {
  14024. return 'ShadowMaterial';
  14025. }
  14026. constructor( parameters ) {
  14027. super();
  14028. this.isShadowMaterial = true;
  14029. this.color = new Color( 0x000000 );
  14030. this.transparent = true;
  14031. this.fog = true;
  14032. this.setValues( parameters );
  14033. }
  14034. copy( source ) {
  14035. super.copy( source );
  14036. this.color.copy( source.color );
  14037. this.fog = source.fog;
  14038. return this;
  14039. }
  14040. }
  14041. class RawShaderMaterial extends ShaderMaterial {
  14042. static get type() {
  14043. return 'RawShaderMaterial';
  14044. }
  14045. constructor( parameters ) {
  14046. super( parameters );
  14047. this.isRawShaderMaterial = true;
  14048. }
  14049. }
  14050. class MeshStandardMaterial extends Material {
  14051. static get type() {
  14052. return 'MeshStandardMaterial';
  14053. }
  14054. constructor( parameters ) {
  14055. super();
  14056. this.isMeshStandardMaterial = true;
  14057. this.defines = { 'STANDARD': '' };
  14058. this.color = new Color( 0xffffff ); // diffuse
  14059. this.roughness = 1.0;
  14060. this.metalness = 0.0;
  14061. this.map = null;
  14062. this.lightMap = null;
  14063. this.lightMapIntensity = 1.0;
  14064. this.aoMap = null;
  14065. this.aoMapIntensity = 1.0;
  14066. this.emissive = new Color( 0x000000 );
  14067. this.emissiveIntensity = 1.0;
  14068. this.emissiveMap = null;
  14069. this.bumpMap = null;
  14070. this.bumpScale = 1;
  14071. this.normalMap = null;
  14072. this.normalMapType = TangentSpaceNormalMap;
  14073. this.normalScale = new Vector2( 1, 1 );
  14074. this.displacementMap = null;
  14075. this.displacementScale = 1;
  14076. this.displacementBias = 0;
  14077. this.roughnessMap = null;
  14078. this.metalnessMap = null;
  14079. this.alphaMap = null;
  14080. this.envMap = null;
  14081. this.envMapRotation = new Euler();
  14082. this.envMapIntensity = 1.0;
  14083. this.wireframe = false;
  14084. this.wireframeLinewidth = 1;
  14085. this.wireframeLinecap = 'round';
  14086. this.wireframeLinejoin = 'round';
  14087. this.flatShading = false;
  14088. this.fog = true;
  14089. this.setValues( parameters );
  14090. }
  14091. copy( source ) {
  14092. super.copy( source );
  14093. this.defines = { 'STANDARD': '' };
  14094. this.color.copy( source.color );
  14095. this.roughness = source.roughness;
  14096. this.metalness = source.metalness;
  14097. this.map = source.map;
  14098. this.lightMap = source.lightMap;
  14099. this.lightMapIntensity = source.lightMapIntensity;
  14100. this.aoMap = source.aoMap;
  14101. this.aoMapIntensity = source.aoMapIntensity;
  14102. this.emissive.copy( source.emissive );
  14103. this.emissiveMap = source.emissiveMap;
  14104. this.emissiveIntensity = source.emissiveIntensity;
  14105. this.bumpMap = source.bumpMap;
  14106. this.bumpScale = source.bumpScale;
  14107. this.normalMap = source.normalMap;
  14108. this.normalMapType = source.normalMapType;
  14109. this.normalScale.copy( source.normalScale );
  14110. this.displacementMap = source.displacementMap;
  14111. this.displacementScale = source.displacementScale;
  14112. this.displacementBias = source.displacementBias;
  14113. this.roughnessMap = source.roughnessMap;
  14114. this.metalnessMap = source.metalnessMap;
  14115. this.alphaMap = source.alphaMap;
  14116. this.envMap = source.envMap;
  14117. this.envMapRotation.copy( source.envMapRotation );
  14118. this.envMapIntensity = source.envMapIntensity;
  14119. this.wireframe = source.wireframe;
  14120. this.wireframeLinewidth = source.wireframeLinewidth;
  14121. this.wireframeLinecap = source.wireframeLinecap;
  14122. this.wireframeLinejoin = source.wireframeLinejoin;
  14123. this.flatShading = source.flatShading;
  14124. this.fog = source.fog;
  14125. return this;
  14126. }
  14127. }
  14128. class MeshPhysicalMaterial extends MeshStandardMaterial {
  14129. static get type() {
  14130. return 'MeshPhysicalMaterial';
  14131. }
  14132. constructor( parameters ) {
  14133. super();
  14134. this.isMeshPhysicalMaterial = true;
  14135. this.defines = {
  14136. 'STANDARD': '',
  14137. 'PHYSICAL': ''
  14138. };
  14139. this.anisotropyRotation = 0;
  14140. this.anisotropyMap = null;
  14141. this.clearcoatMap = null;
  14142. this.clearcoatRoughness = 0.0;
  14143. this.clearcoatRoughnessMap = null;
  14144. this.clearcoatNormalScale = new Vector2( 1, 1 );
  14145. this.clearcoatNormalMap = null;
  14146. this.ior = 1.5;
  14147. Object.defineProperty( this, 'reflectivity', {
  14148. get: function () {
  14149. return ( clamp$1( 2.5 * ( this.ior - 1 ) / ( this.ior + 1 ), 0, 1 ) );
  14150. },
  14151. set: function ( reflectivity ) {
  14152. this.ior = ( 1 + 0.4 * reflectivity ) / ( 1 - 0.4 * reflectivity );
  14153. }
  14154. } );
  14155. this.iridescenceMap = null;
  14156. this.iridescenceIOR = 1.3;
  14157. this.iridescenceThicknessRange = [ 100, 400 ];
  14158. this.iridescenceThicknessMap = null;
  14159. this.sheenColor = new Color( 0x000000 );
  14160. this.sheenColorMap = null;
  14161. this.sheenRoughness = 1.0;
  14162. this.sheenRoughnessMap = null;
  14163. this.transmissionMap = null;
  14164. this.thickness = 0;
  14165. this.thicknessMap = null;
  14166. this.attenuationDistance = Infinity;
  14167. this.attenuationColor = new Color( 1, 1, 1 );
  14168. this.specularIntensity = 1.0;
  14169. this.specularIntensityMap = null;
  14170. this.specularColor = new Color( 1, 1, 1 );
  14171. this.specularColorMap = null;
  14172. this._anisotropy = 0;
  14173. this._clearcoat = 0;
  14174. this._dispersion = 0;
  14175. this._iridescence = 0;
  14176. this._sheen = 0.0;
  14177. this._transmission = 0;
  14178. this.setValues( parameters );
  14179. }
  14180. get anisotropy() {
  14181. return this._anisotropy;
  14182. }
  14183. set anisotropy( value ) {
  14184. if ( this._anisotropy > 0 !== value > 0 ) {
  14185. this.version ++;
  14186. }
  14187. this._anisotropy = value;
  14188. }
  14189. get clearcoat() {
  14190. return this._clearcoat;
  14191. }
  14192. set clearcoat( value ) {
  14193. if ( this._clearcoat > 0 !== value > 0 ) {
  14194. this.version ++;
  14195. }
  14196. this._clearcoat = value;
  14197. }
  14198. get iridescence() {
  14199. return this._iridescence;
  14200. }
  14201. set iridescence( value ) {
  14202. if ( this._iridescence > 0 !== value > 0 ) {
  14203. this.version ++;
  14204. }
  14205. this._iridescence = value;
  14206. }
  14207. get dispersion() {
  14208. return this._dispersion;
  14209. }
  14210. set dispersion( value ) {
  14211. if ( this._dispersion > 0 !== value > 0 ) {
  14212. this.version ++;
  14213. }
  14214. this._dispersion = value;
  14215. }
  14216. get sheen() {
  14217. return this._sheen;
  14218. }
  14219. set sheen( value ) {
  14220. if ( this._sheen > 0 !== value > 0 ) {
  14221. this.version ++;
  14222. }
  14223. this._sheen = value;
  14224. }
  14225. get transmission() {
  14226. return this._transmission;
  14227. }
  14228. set transmission( value ) {
  14229. if ( this._transmission > 0 !== value > 0 ) {
  14230. this.version ++;
  14231. }
  14232. this._transmission = value;
  14233. }
  14234. copy( source ) {
  14235. super.copy( source );
  14236. this.defines = {
  14237. 'STANDARD': '',
  14238. 'PHYSICAL': ''
  14239. };
  14240. this.anisotropy = source.anisotropy;
  14241. this.anisotropyRotation = source.anisotropyRotation;
  14242. this.anisotropyMap = source.anisotropyMap;
  14243. this.clearcoat = source.clearcoat;
  14244. this.clearcoatMap = source.clearcoatMap;
  14245. this.clearcoatRoughness = source.clearcoatRoughness;
  14246. this.clearcoatRoughnessMap = source.clearcoatRoughnessMap;
  14247. this.clearcoatNormalMap = source.clearcoatNormalMap;
  14248. this.clearcoatNormalScale.copy( source.clearcoatNormalScale );
  14249. this.dispersion = source.dispersion;
  14250. this.ior = source.ior;
  14251. this.iridescence = source.iridescence;
  14252. this.iridescenceMap = source.iridescenceMap;
  14253. this.iridescenceIOR = source.iridescenceIOR;
  14254. this.iridescenceThicknessRange = [ ...source.iridescenceThicknessRange ];
  14255. this.iridescenceThicknessMap = source.iridescenceThicknessMap;
  14256. this.sheen = source.sheen;
  14257. this.sheenColor.copy( source.sheenColor );
  14258. this.sheenColorMap = source.sheenColorMap;
  14259. this.sheenRoughness = source.sheenRoughness;
  14260. this.sheenRoughnessMap = source.sheenRoughnessMap;
  14261. this.transmission = source.transmission;
  14262. this.transmissionMap = source.transmissionMap;
  14263. this.thickness = source.thickness;
  14264. this.thicknessMap = source.thicknessMap;
  14265. this.attenuationDistance = source.attenuationDistance;
  14266. this.attenuationColor.copy( source.attenuationColor );
  14267. this.specularIntensity = source.specularIntensity;
  14268. this.specularIntensityMap = source.specularIntensityMap;
  14269. this.specularColor.copy( source.specularColor );
  14270. this.specularColorMap = source.specularColorMap;
  14271. return this;
  14272. }
  14273. }
  14274. class MeshPhongMaterial extends Material {
  14275. static get type() {
  14276. return 'MeshPhongMaterial';
  14277. }
  14278. constructor( parameters ) {
  14279. super();
  14280. this.isMeshPhongMaterial = true;
  14281. this.color = new Color( 0xffffff ); // diffuse
  14282. this.specular = new Color( 0x111111 );
  14283. this.shininess = 30;
  14284. this.map = null;
  14285. this.lightMap = null;
  14286. this.lightMapIntensity = 1.0;
  14287. this.aoMap = null;
  14288. this.aoMapIntensity = 1.0;
  14289. this.emissive = new Color( 0x000000 );
  14290. this.emissiveIntensity = 1.0;
  14291. this.emissiveMap = null;
  14292. this.bumpMap = null;
  14293. this.bumpScale = 1;
  14294. this.normalMap = null;
  14295. this.normalMapType = TangentSpaceNormalMap;
  14296. this.normalScale = new Vector2( 1, 1 );
  14297. this.displacementMap = null;
  14298. this.displacementScale = 1;
  14299. this.displacementBias = 0;
  14300. this.specularMap = null;
  14301. this.alphaMap = null;
  14302. this.envMap = null;
  14303. this.envMapRotation = new Euler();
  14304. this.combine = MultiplyOperation;
  14305. this.reflectivity = 1;
  14306. this.refractionRatio = 0.98;
  14307. this.wireframe = false;
  14308. this.wireframeLinewidth = 1;
  14309. this.wireframeLinecap = 'round';
  14310. this.wireframeLinejoin = 'round';
  14311. this.flatShading = false;
  14312. this.fog = true;
  14313. this.setValues( parameters );
  14314. }
  14315. copy( source ) {
  14316. super.copy( source );
  14317. this.color.copy( source.color );
  14318. this.specular.copy( source.specular );
  14319. this.shininess = source.shininess;
  14320. this.map = source.map;
  14321. this.lightMap = source.lightMap;
  14322. this.lightMapIntensity = source.lightMapIntensity;
  14323. this.aoMap = source.aoMap;
  14324. this.aoMapIntensity = source.aoMapIntensity;
  14325. this.emissive.copy( source.emissive );
  14326. this.emissiveMap = source.emissiveMap;
  14327. this.emissiveIntensity = source.emissiveIntensity;
  14328. this.bumpMap = source.bumpMap;
  14329. this.bumpScale = source.bumpScale;
  14330. this.normalMap = source.normalMap;
  14331. this.normalMapType = source.normalMapType;
  14332. this.normalScale.copy( source.normalScale );
  14333. this.displacementMap = source.displacementMap;
  14334. this.displacementScale = source.displacementScale;
  14335. this.displacementBias = source.displacementBias;
  14336. this.specularMap = source.specularMap;
  14337. this.alphaMap = source.alphaMap;
  14338. this.envMap = source.envMap;
  14339. this.envMapRotation.copy( source.envMapRotation );
  14340. this.combine = source.combine;
  14341. this.reflectivity = source.reflectivity;
  14342. this.refractionRatio = source.refractionRatio;
  14343. this.wireframe = source.wireframe;
  14344. this.wireframeLinewidth = source.wireframeLinewidth;
  14345. this.wireframeLinecap = source.wireframeLinecap;
  14346. this.wireframeLinejoin = source.wireframeLinejoin;
  14347. this.flatShading = source.flatShading;
  14348. this.fog = source.fog;
  14349. return this;
  14350. }
  14351. }
  14352. class MeshToonMaterial extends Material {
  14353. static get type() {
  14354. return 'MeshToonMaterial';
  14355. }
  14356. constructor( parameters ) {
  14357. super();
  14358. this.isMeshToonMaterial = true;
  14359. this.defines = { 'TOON': '' };
  14360. this.color = new Color( 0xffffff );
  14361. this.map = null;
  14362. this.gradientMap = null;
  14363. this.lightMap = null;
  14364. this.lightMapIntensity = 1.0;
  14365. this.aoMap = null;
  14366. this.aoMapIntensity = 1.0;
  14367. this.emissive = new Color( 0x000000 );
  14368. this.emissiveIntensity = 1.0;
  14369. this.emissiveMap = null;
  14370. this.bumpMap = null;
  14371. this.bumpScale = 1;
  14372. this.normalMap = null;
  14373. this.normalMapType = TangentSpaceNormalMap;
  14374. this.normalScale = new Vector2( 1, 1 );
  14375. this.displacementMap = null;
  14376. this.displacementScale = 1;
  14377. this.displacementBias = 0;
  14378. this.alphaMap = null;
  14379. this.wireframe = false;
  14380. this.wireframeLinewidth = 1;
  14381. this.wireframeLinecap = 'round';
  14382. this.wireframeLinejoin = 'round';
  14383. this.fog = true;
  14384. this.setValues( parameters );
  14385. }
  14386. copy( source ) {
  14387. super.copy( source );
  14388. this.color.copy( source.color );
  14389. this.map = source.map;
  14390. this.gradientMap = source.gradientMap;
  14391. this.lightMap = source.lightMap;
  14392. this.lightMapIntensity = source.lightMapIntensity;
  14393. this.aoMap = source.aoMap;
  14394. this.aoMapIntensity = source.aoMapIntensity;
  14395. this.emissive.copy( source.emissive );
  14396. this.emissiveMap = source.emissiveMap;
  14397. this.emissiveIntensity = source.emissiveIntensity;
  14398. this.bumpMap = source.bumpMap;
  14399. this.bumpScale = source.bumpScale;
  14400. this.normalMap = source.normalMap;
  14401. this.normalMapType = source.normalMapType;
  14402. this.normalScale.copy( source.normalScale );
  14403. this.displacementMap = source.displacementMap;
  14404. this.displacementScale = source.displacementScale;
  14405. this.displacementBias = source.displacementBias;
  14406. this.alphaMap = source.alphaMap;
  14407. this.wireframe = source.wireframe;
  14408. this.wireframeLinewidth = source.wireframeLinewidth;
  14409. this.wireframeLinecap = source.wireframeLinecap;
  14410. this.wireframeLinejoin = source.wireframeLinejoin;
  14411. this.fog = source.fog;
  14412. return this;
  14413. }
  14414. }
  14415. class MeshNormalMaterial extends Material {
  14416. static get type() {
  14417. return 'MeshNormalMaterial';
  14418. }
  14419. constructor( parameters ) {
  14420. super();
  14421. this.isMeshNormalMaterial = true;
  14422. this.bumpMap = null;
  14423. this.bumpScale = 1;
  14424. this.normalMap = null;
  14425. this.normalMapType = TangentSpaceNormalMap;
  14426. this.normalScale = new Vector2( 1, 1 );
  14427. this.displacementMap = null;
  14428. this.displacementScale = 1;
  14429. this.displacementBias = 0;
  14430. this.wireframe = false;
  14431. this.wireframeLinewidth = 1;
  14432. this.flatShading = false;
  14433. this.setValues( parameters );
  14434. }
  14435. copy( source ) {
  14436. super.copy( source );
  14437. this.bumpMap = source.bumpMap;
  14438. this.bumpScale = source.bumpScale;
  14439. this.normalMap = source.normalMap;
  14440. this.normalMapType = source.normalMapType;
  14441. this.normalScale.copy( source.normalScale );
  14442. this.displacementMap = source.displacementMap;
  14443. this.displacementScale = source.displacementScale;
  14444. this.displacementBias = source.displacementBias;
  14445. this.wireframe = source.wireframe;
  14446. this.wireframeLinewidth = source.wireframeLinewidth;
  14447. this.flatShading = source.flatShading;
  14448. return this;
  14449. }
  14450. }
  14451. class MeshLambertMaterial extends Material {
  14452. static get type() {
  14453. return 'MeshLambertMaterial';
  14454. }
  14455. constructor( parameters ) {
  14456. super();
  14457. this.isMeshLambertMaterial = true;
  14458. this.color = new Color( 0xffffff ); // diffuse
  14459. this.map = null;
  14460. this.lightMap = null;
  14461. this.lightMapIntensity = 1.0;
  14462. this.aoMap = null;
  14463. this.aoMapIntensity = 1.0;
  14464. this.emissive = new Color( 0x000000 );
  14465. this.emissiveIntensity = 1.0;
  14466. this.emissiveMap = null;
  14467. this.bumpMap = null;
  14468. this.bumpScale = 1;
  14469. this.normalMap = null;
  14470. this.normalMapType = TangentSpaceNormalMap;
  14471. this.normalScale = new Vector2( 1, 1 );
  14472. this.displacementMap = null;
  14473. this.displacementScale = 1;
  14474. this.displacementBias = 0;
  14475. this.specularMap = null;
  14476. this.alphaMap = null;
  14477. this.envMap = null;
  14478. this.envMapRotation = new Euler();
  14479. this.combine = MultiplyOperation;
  14480. this.reflectivity = 1;
  14481. this.refractionRatio = 0.98;
  14482. this.wireframe = false;
  14483. this.wireframeLinewidth = 1;
  14484. this.wireframeLinecap = 'round';
  14485. this.wireframeLinejoin = 'round';
  14486. this.flatShading = false;
  14487. this.fog = true;
  14488. this.setValues( parameters );
  14489. }
  14490. copy( source ) {
  14491. super.copy( source );
  14492. this.color.copy( source.color );
  14493. this.map = source.map;
  14494. this.lightMap = source.lightMap;
  14495. this.lightMapIntensity = source.lightMapIntensity;
  14496. this.aoMap = source.aoMap;
  14497. this.aoMapIntensity = source.aoMapIntensity;
  14498. this.emissive.copy( source.emissive );
  14499. this.emissiveMap = source.emissiveMap;
  14500. this.emissiveIntensity = source.emissiveIntensity;
  14501. this.bumpMap = source.bumpMap;
  14502. this.bumpScale = source.bumpScale;
  14503. this.normalMap = source.normalMap;
  14504. this.normalMapType = source.normalMapType;
  14505. this.normalScale.copy( source.normalScale );
  14506. this.displacementMap = source.displacementMap;
  14507. this.displacementScale = source.displacementScale;
  14508. this.displacementBias = source.displacementBias;
  14509. this.specularMap = source.specularMap;
  14510. this.alphaMap = source.alphaMap;
  14511. this.envMap = source.envMap;
  14512. this.envMapRotation.copy( source.envMapRotation );
  14513. this.combine = source.combine;
  14514. this.reflectivity = source.reflectivity;
  14515. this.refractionRatio = source.refractionRatio;
  14516. this.wireframe = source.wireframe;
  14517. this.wireframeLinewidth = source.wireframeLinewidth;
  14518. this.wireframeLinecap = source.wireframeLinecap;
  14519. this.wireframeLinejoin = source.wireframeLinejoin;
  14520. this.flatShading = source.flatShading;
  14521. this.fog = source.fog;
  14522. return this;
  14523. }
  14524. }
  14525. class MeshDepthMaterial extends Material {
  14526. static get type() {
  14527. return 'MeshDepthMaterial';
  14528. }
  14529. constructor( parameters ) {
  14530. super();
  14531. this.isMeshDepthMaterial = true;
  14532. this.depthPacking = BasicDepthPacking;
  14533. this.map = null;
  14534. this.alphaMap = null;
  14535. this.displacementMap = null;
  14536. this.displacementScale = 1;
  14537. this.displacementBias = 0;
  14538. this.wireframe = false;
  14539. this.wireframeLinewidth = 1;
  14540. this.setValues( parameters );
  14541. }
  14542. copy( source ) {
  14543. super.copy( source );
  14544. this.depthPacking = source.depthPacking;
  14545. this.map = source.map;
  14546. this.alphaMap = source.alphaMap;
  14547. this.displacementMap = source.displacementMap;
  14548. this.displacementScale = source.displacementScale;
  14549. this.displacementBias = source.displacementBias;
  14550. this.wireframe = source.wireframe;
  14551. this.wireframeLinewidth = source.wireframeLinewidth;
  14552. return this;
  14553. }
  14554. }
  14555. class MeshDistanceMaterial extends Material {
  14556. static get type() {
  14557. return 'MeshDistanceMaterial';
  14558. }
  14559. constructor( parameters ) {
  14560. super();
  14561. this.isMeshDistanceMaterial = true;
  14562. this.map = null;
  14563. this.alphaMap = null;
  14564. this.displacementMap = null;
  14565. this.displacementScale = 1;
  14566. this.displacementBias = 0;
  14567. this.setValues( parameters );
  14568. }
  14569. copy( source ) {
  14570. super.copy( source );
  14571. this.map = source.map;
  14572. this.alphaMap = source.alphaMap;
  14573. this.displacementMap = source.displacementMap;
  14574. this.displacementScale = source.displacementScale;
  14575. this.displacementBias = source.displacementBias;
  14576. return this;
  14577. }
  14578. }
  14579. class MeshMatcapMaterial extends Material {
  14580. static get type() {
  14581. return 'MeshMatcapMaterial';
  14582. }
  14583. constructor( parameters ) {
  14584. super();
  14585. this.isMeshMatcapMaterial = true;
  14586. this.defines = { 'MATCAP': '' };
  14587. this.color = new Color( 0xffffff ); // diffuse
  14588. this.matcap = null;
  14589. this.map = null;
  14590. this.bumpMap = null;
  14591. this.bumpScale = 1;
  14592. this.normalMap = null;
  14593. this.normalMapType = TangentSpaceNormalMap;
  14594. this.normalScale = new Vector2( 1, 1 );
  14595. this.displacementMap = null;
  14596. this.displacementScale = 1;
  14597. this.displacementBias = 0;
  14598. this.alphaMap = null;
  14599. this.flatShading = false;
  14600. this.fog = true;
  14601. this.setValues( parameters );
  14602. }
  14603. copy( source ) {
  14604. super.copy( source );
  14605. this.defines = { 'MATCAP': '' };
  14606. this.color.copy( source.color );
  14607. this.matcap = source.matcap;
  14608. this.map = source.map;
  14609. this.bumpMap = source.bumpMap;
  14610. this.bumpScale = source.bumpScale;
  14611. this.normalMap = source.normalMap;
  14612. this.normalMapType = source.normalMapType;
  14613. this.normalScale.copy( source.normalScale );
  14614. this.displacementMap = source.displacementMap;
  14615. this.displacementScale = source.displacementScale;
  14616. this.displacementBias = source.displacementBias;
  14617. this.alphaMap = source.alphaMap;
  14618. this.flatShading = source.flatShading;
  14619. this.fog = source.fog;
  14620. return this;
  14621. }
  14622. }
  14623. class LineDashedMaterial extends LineBasicMaterial {
  14624. static get type() {
  14625. return 'LineDashedMaterial';
  14626. }
  14627. constructor( parameters ) {
  14628. super();
  14629. this.isLineDashedMaterial = true;
  14630. this.scale = 1;
  14631. this.dashSize = 3;
  14632. this.gapSize = 1;
  14633. this.setValues( parameters );
  14634. }
  14635. copy( source ) {
  14636. super.copy( source );
  14637. this.scale = source.scale;
  14638. this.dashSize = source.dashSize;
  14639. this.gapSize = source.gapSize;
  14640. return this;
  14641. }
  14642. }
  14643. // converts an array to a specific type
  14644. function convertArray( array, type, forceClone ) {
  14645. if ( ! array || // let 'undefined' and 'null' pass
  14646. ! forceClone && array.constructor === type ) return array;
  14647. if ( typeof type.BYTES_PER_ELEMENT === 'number' ) {
  14648. return new type( array ); // create typed array
  14649. }
  14650. return Array.prototype.slice.call( array ); // create Array
  14651. }
  14652. function isTypedArray( object ) {
  14653. return ArrayBuffer.isView( object ) &&
  14654. ! ( object instanceof DataView );
  14655. }
  14656. // returns an array by which times and values can be sorted
  14657. function getKeyframeOrder( times ) {
  14658. function compareTime( i, j ) {
  14659. return times[ i ] - times[ j ];
  14660. }
  14661. const n = times.length;
  14662. const result = new Array( n );
  14663. for ( let i = 0; i !== n; ++ i ) result[ i ] = i;
  14664. result.sort( compareTime );
  14665. return result;
  14666. }
  14667. // uses the array previously returned by 'getKeyframeOrder' to sort data
  14668. function sortedArray( values, stride, order ) {
  14669. const nValues = values.length;
  14670. const result = new values.constructor( nValues );
  14671. for ( let i = 0, dstOffset = 0; dstOffset !== nValues; ++ i ) {
  14672. const srcOffset = order[ i ] * stride;
  14673. for ( let j = 0; j !== stride; ++ j ) {
  14674. result[ dstOffset ++ ] = values[ srcOffset + j ];
  14675. }
  14676. }
  14677. return result;
  14678. }
  14679. // function for parsing AOS keyframe formats
  14680. function flattenJSON( jsonKeys, times, values, valuePropertyName ) {
  14681. let i = 1, key = jsonKeys[ 0 ];
  14682. while ( key !== undefined && key[ valuePropertyName ] === undefined ) {
  14683. key = jsonKeys[ i ++ ];
  14684. }
  14685. if ( key === undefined ) return; // no data
  14686. let value = key[ valuePropertyName ];
  14687. if ( value === undefined ) return; // no data
  14688. if ( Array.isArray( value ) ) {
  14689. do {
  14690. value = key[ valuePropertyName ];
  14691. if ( value !== undefined ) {
  14692. times.push( key.time );
  14693. values.push.apply( values, value ); // push all elements
  14694. }
  14695. key = jsonKeys[ i ++ ];
  14696. } while ( key !== undefined );
  14697. } else if ( value.toArray !== undefined ) {
  14698. // ...assume THREE.Math-ish
  14699. do {
  14700. value = key[ valuePropertyName ];
  14701. if ( value !== undefined ) {
  14702. times.push( key.time );
  14703. value.toArray( values, values.length );
  14704. }
  14705. key = jsonKeys[ i ++ ];
  14706. } while ( key !== undefined );
  14707. } else {
  14708. // otherwise push as-is
  14709. do {
  14710. value = key[ valuePropertyName ];
  14711. if ( value !== undefined ) {
  14712. times.push( key.time );
  14713. values.push( value );
  14714. }
  14715. key = jsonKeys[ i ++ ];
  14716. } while ( key !== undefined );
  14717. }
  14718. }
  14719. function subclip( sourceClip, name, startFrame, endFrame, fps = 30 ) {
  14720. const clip = sourceClip.clone();
  14721. clip.name = name;
  14722. const tracks = [];
  14723. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  14724. const track = clip.tracks[ i ];
  14725. const valueSize = track.getValueSize();
  14726. const times = [];
  14727. const values = [];
  14728. for ( let j = 0; j < track.times.length; ++ j ) {
  14729. const frame = track.times[ j ] * fps;
  14730. if ( frame < startFrame || frame >= endFrame ) continue;
  14731. times.push( track.times[ j ] );
  14732. for ( let k = 0; k < valueSize; ++ k ) {
  14733. values.push( track.values[ j * valueSize + k ] );
  14734. }
  14735. }
  14736. if ( times.length === 0 ) continue;
  14737. track.times = convertArray( times, track.times.constructor );
  14738. track.values = convertArray( values, track.values.constructor );
  14739. tracks.push( track );
  14740. }
  14741. clip.tracks = tracks;
  14742. // find minimum .times value across all tracks in the trimmed clip
  14743. let minStartTime = Infinity;
  14744. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  14745. if ( minStartTime > clip.tracks[ i ].times[ 0 ] ) {
  14746. minStartTime = clip.tracks[ i ].times[ 0 ];
  14747. }
  14748. }
  14749. // shift all tracks such that clip begins at t=0
  14750. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  14751. clip.tracks[ i ].shift( - 1 * minStartTime );
  14752. }
  14753. clip.resetDuration();
  14754. return clip;
  14755. }
  14756. function makeClipAdditive( targetClip, referenceFrame = 0, referenceClip = targetClip, fps = 30 ) {
  14757. if ( fps <= 0 ) fps = 30;
  14758. const numTracks = referenceClip.tracks.length;
  14759. const referenceTime = referenceFrame / fps;
  14760. // Make each track's values relative to the values at the reference frame
  14761. for ( let i = 0; i < numTracks; ++ i ) {
  14762. const referenceTrack = referenceClip.tracks[ i ];
  14763. const referenceTrackType = referenceTrack.ValueTypeName;
  14764. // Skip this track if it's non-numeric
  14765. if ( referenceTrackType === 'bool' || referenceTrackType === 'string' ) continue;
  14766. // Find the track in the target clip whose name and type matches the reference track
  14767. const targetTrack = targetClip.tracks.find( function ( track ) {
  14768. return track.name === referenceTrack.name
  14769. && track.ValueTypeName === referenceTrackType;
  14770. } );
  14771. if ( targetTrack === undefined ) continue;
  14772. let referenceOffset = 0;
  14773. const referenceValueSize = referenceTrack.getValueSize();
  14774. if ( referenceTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  14775. referenceOffset = referenceValueSize / 3;
  14776. }
  14777. let targetOffset = 0;
  14778. const targetValueSize = targetTrack.getValueSize();
  14779. if ( targetTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  14780. targetOffset = targetValueSize / 3;
  14781. }
  14782. const lastIndex = referenceTrack.times.length - 1;
  14783. let referenceValue;
  14784. // Find the value to subtract out of the track
  14785. if ( referenceTime <= referenceTrack.times[ 0 ] ) {
  14786. // Reference frame is earlier than the first keyframe, so just use the first keyframe
  14787. const startIndex = referenceOffset;
  14788. const endIndex = referenceValueSize - referenceOffset;
  14789. referenceValue = referenceTrack.values.slice( startIndex, endIndex );
  14790. } else if ( referenceTime >= referenceTrack.times[ lastIndex ] ) {
  14791. // Reference frame is after the last keyframe, so just use the last keyframe
  14792. const startIndex = lastIndex * referenceValueSize + referenceOffset;
  14793. const endIndex = startIndex + referenceValueSize - referenceOffset;
  14794. referenceValue = referenceTrack.values.slice( startIndex, endIndex );
  14795. } else {
  14796. // Interpolate to the reference value
  14797. const interpolant = referenceTrack.createInterpolant();
  14798. const startIndex = referenceOffset;
  14799. const endIndex = referenceValueSize - referenceOffset;
  14800. interpolant.evaluate( referenceTime );
  14801. referenceValue = interpolant.resultBuffer.slice( startIndex, endIndex );
  14802. }
  14803. // Conjugate the quaternion
  14804. if ( referenceTrackType === 'quaternion' ) {
  14805. const referenceQuat = new Quaternion().fromArray( referenceValue ).normalize().conjugate();
  14806. referenceQuat.toArray( referenceValue );
  14807. }
  14808. // Subtract the reference value from all of the track values
  14809. const numTimes = targetTrack.times.length;
  14810. for ( let j = 0; j < numTimes; ++ j ) {
  14811. const valueStart = j * targetValueSize + targetOffset;
  14812. if ( referenceTrackType === 'quaternion' ) {
  14813. // Multiply the conjugate for quaternion track types
  14814. Quaternion.multiplyQuaternionsFlat(
  14815. targetTrack.values,
  14816. valueStart,
  14817. referenceValue,
  14818. 0,
  14819. targetTrack.values,
  14820. valueStart
  14821. );
  14822. } else {
  14823. const valueEnd = targetValueSize - targetOffset * 2;
  14824. // Subtract each value for all other numeric track types
  14825. for ( let k = 0; k < valueEnd; ++ k ) {
  14826. targetTrack.values[ valueStart + k ] -= referenceValue[ k ];
  14827. }
  14828. }
  14829. }
  14830. }
  14831. targetClip.blendMode = AdditiveAnimationBlendMode;
  14832. return targetClip;
  14833. }
  14834. const AnimationUtils = {
  14835. convertArray: convertArray,
  14836. isTypedArray: isTypedArray,
  14837. getKeyframeOrder: getKeyframeOrder,
  14838. sortedArray: sortedArray,
  14839. flattenJSON: flattenJSON,
  14840. subclip: subclip,
  14841. makeClipAdditive: makeClipAdditive
  14842. };
  14843. /**
  14844. * Abstract base class of interpolants over parametric samples.
  14845. *
  14846. * The parameter domain is one dimensional, typically the time or a path
  14847. * along a curve defined by the data.
  14848. *
  14849. * The sample values can have any dimensionality and derived classes may
  14850. * apply special interpretations to the data.
  14851. *
  14852. * This class provides the interval seek in a Template Method, deferring
  14853. * the actual interpolation to derived classes.
  14854. *
  14855. * Time complexity is O(1) for linear access crossing at most two points
  14856. * and O(log N) for random access, where N is the number of positions.
  14857. *
  14858. * References:
  14859. *
  14860. * http://www.oodesign.com/template-method-pattern.html
  14861. *
  14862. */
  14863. class Interpolant {
  14864. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  14865. this.parameterPositions = parameterPositions;
  14866. this._cachedIndex = 0;
  14867. this.resultBuffer = resultBuffer !== undefined ?
  14868. resultBuffer : new sampleValues.constructor( sampleSize );
  14869. this.sampleValues = sampleValues;
  14870. this.valueSize = sampleSize;
  14871. this.settings = null;
  14872. this.DefaultSettings_ = {};
  14873. }
  14874. evaluate( t ) {
  14875. const pp = this.parameterPositions;
  14876. let i1 = this._cachedIndex,
  14877. t1 = pp[ i1 ],
  14878. t0 = pp[ i1 - 1 ];
  14879. validate_interval: {
  14880. seek: {
  14881. let right;
  14882. linear_scan: {
  14883. //- See http://jsperf.com/comparison-to-undefined/3
  14884. //- slower code:
  14885. //-
  14886. //- if ( t >= t1 || t1 === undefined ) {
  14887. forward_scan: if ( ! ( t < t1 ) ) {
  14888. for ( let giveUpAt = i1 + 2; ; ) {
  14889. if ( t1 === undefined ) {
  14890. if ( t < t0 ) break forward_scan;
  14891. // after end
  14892. i1 = pp.length;
  14893. this._cachedIndex = i1;
  14894. return this.copySampleValue_( i1 - 1 );
  14895. }
  14896. if ( i1 === giveUpAt ) break; // this loop
  14897. t0 = t1;
  14898. t1 = pp[ ++ i1 ];
  14899. if ( t < t1 ) {
  14900. // we have arrived at the sought interval
  14901. break seek;
  14902. }
  14903. }
  14904. // prepare binary search on the right side of the index
  14905. right = pp.length;
  14906. break linear_scan;
  14907. }
  14908. //- slower code:
  14909. //- if ( t < t0 || t0 === undefined ) {
  14910. if ( ! ( t >= t0 ) ) {
  14911. // looping?
  14912. const t1global = pp[ 1 ];
  14913. if ( t < t1global ) {
  14914. i1 = 2; // + 1, using the scan for the details
  14915. t0 = t1global;
  14916. }
  14917. // linear reverse scan
  14918. for ( let giveUpAt = i1 - 2; ; ) {
  14919. if ( t0 === undefined ) {
  14920. // before start
  14921. this._cachedIndex = 0;
  14922. return this.copySampleValue_( 0 );
  14923. }
  14924. if ( i1 === giveUpAt ) break; // this loop
  14925. t1 = t0;
  14926. t0 = pp[ -- i1 - 1 ];
  14927. if ( t >= t0 ) {
  14928. // we have arrived at the sought interval
  14929. break seek;
  14930. }
  14931. }
  14932. // prepare binary search on the left side of the index
  14933. right = i1;
  14934. i1 = 0;
  14935. break linear_scan;
  14936. }
  14937. // the interval is valid
  14938. break validate_interval;
  14939. } // linear scan
  14940. // binary search
  14941. while ( i1 < right ) {
  14942. const mid = ( i1 + right ) >>> 1;
  14943. if ( t < pp[ mid ] ) {
  14944. right = mid;
  14945. } else {
  14946. i1 = mid + 1;
  14947. }
  14948. }
  14949. t1 = pp[ i1 ];
  14950. t0 = pp[ i1 - 1 ];
  14951. // check boundary cases, again
  14952. if ( t0 === undefined ) {
  14953. this._cachedIndex = 0;
  14954. return this.copySampleValue_( 0 );
  14955. }
  14956. if ( t1 === undefined ) {
  14957. i1 = pp.length;
  14958. this._cachedIndex = i1;
  14959. return this.copySampleValue_( i1 - 1 );
  14960. }
  14961. } // seek
  14962. this._cachedIndex = i1;
  14963. this.intervalChanged_( i1, t0, t1 );
  14964. } // validate_interval
  14965. return this.interpolate_( i1, t0, t, t1 );
  14966. }
  14967. getSettings_() {
  14968. return this.settings || this.DefaultSettings_;
  14969. }
  14970. copySampleValue_( index ) {
  14971. // copies a sample value to the result buffer
  14972. const result = this.resultBuffer,
  14973. values = this.sampleValues,
  14974. stride = this.valueSize,
  14975. offset = index * stride;
  14976. for ( let i = 0; i !== stride; ++ i ) {
  14977. result[ i ] = values[ offset + i ];
  14978. }
  14979. return result;
  14980. }
  14981. // Template methods for derived classes:
  14982. interpolate_( /* i1, t0, t, t1 */ ) {
  14983. throw new Error( 'call to abstract method' );
  14984. // implementations shall return this.resultBuffer
  14985. }
  14986. intervalChanged_( /* i1, t0, t1 */ ) {
  14987. // empty
  14988. }
  14989. }
  14990. /**
  14991. * Fast and simple cubic spline interpolant.
  14992. *
  14993. * It was derived from a Hermitian construction setting the first derivative
  14994. * at each sample position to the linear slope between neighboring positions
  14995. * over their parameter interval.
  14996. */
  14997. class CubicInterpolant extends Interpolant {
  14998. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  14999. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  15000. this._weightPrev = - 0;
  15001. this._offsetPrev = - 0;
  15002. this._weightNext = - 0;
  15003. this._offsetNext = - 0;
  15004. this.DefaultSettings_ = {
  15005. endingStart: ZeroCurvatureEnding,
  15006. endingEnd: ZeroCurvatureEnding
  15007. };
  15008. }
  15009. intervalChanged_( i1, t0, t1 ) {
  15010. const pp = this.parameterPositions;
  15011. let iPrev = i1 - 2,
  15012. iNext = i1 + 1,
  15013. tPrev = pp[ iPrev ],
  15014. tNext = pp[ iNext ];
  15015. if ( tPrev === undefined ) {
  15016. switch ( this.getSettings_().endingStart ) {
  15017. case ZeroSlopeEnding:
  15018. // f'(t0) = 0
  15019. iPrev = i1;
  15020. tPrev = 2 * t0 - t1;
  15021. break;
  15022. case WrapAroundEnding:
  15023. // use the other end of the curve
  15024. iPrev = pp.length - 2;
  15025. tPrev = t0 + pp[ iPrev ] - pp[ iPrev + 1 ];
  15026. break;
  15027. default: // ZeroCurvatureEnding
  15028. // f''(t0) = 0 a.k.a. Natural Spline
  15029. iPrev = i1;
  15030. tPrev = t1;
  15031. }
  15032. }
  15033. if ( tNext === undefined ) {
  15034. switch ( this.getSettings_().endingEnd ) {
  15035. case ZeroSlopeEnding:
  15036. // f'(tN) = 0
  15037. iNext = i1;
  15038. tNext = 2 * t1 - t0;
  15039. break;
  15040. case WrapAroundEnding:
  15041. // use the other end of the curve
  15042. iNext = 1;
  15043. tNext = t1 + pp[ 1 ] - pp[ 0 ];
  15044. break;
  15045. default: // ZeroCurvatureEnding
  15046. // f''(tN) = 0, a.k.a. Natural Spline
  15047. iNext = i1 - 1;
  15048. tNext = t0;
  15049. }
  15050. }
  15051. const halfDt = ( t1 - t0 ) * 0.5,
  15052. stride = this.valueSize;
  15053. this._weightPrev = halfDt / ( t0 - tPrev );
  15054. this._weightNext = halfDt / ( tNext - t1 );
  15055. this._offsetPrev = iPrev * stride;
  15056. this._offsetNext = iNext * stride;
  15057. }
  15058. interpolate_( i1, t0, t, t1 ) {
  15059. const result = this.resultBuffer,
  15060. values = this.sampleValues,
  15061. stride = this.valueSize,
  15062. o1 = i1 * stride, o0 = o1 - stride,
  15063. oP = this._offsetPrev, oN = this._offsetNext,
  15064. wP = this._weightPrev, wN = this._weightNext,
  15065. p = ( t - t0 ) / ( t1 - t0 ),
  15066. pp = p * p,
  15067. ppp = pp * p;
  15068. // evaluate polynomials
  15069. const sP = - wP * ppp + 2 * wP * pp - wP * p;
  15070. const s0 = ( 1 + wP ) * ppp + ( - 1.5 - 2 * wP ) * pp + ( - 0.5 + wP ) * p + 1;
  15071. const s1 = ( - 1 - wN ) * ppp + ( 1.5 + wN ) * pp + 0.5 * p;
  15072. const sN = wN * ppp - wN * pp;
  15073. // combine data linearly
  15074. for ( let i = 0; i !== stride; ++ i ) {
  15075. result[ i ] =
  15076. sP * values[ oP + i ] +
  15077. s0 * values[ o0 + i ] +
  15078. s1 * values[ o1 + i ] +
  15079. sN * values[ oN + i ];
  15080. }
  15081. return result;
  15082. }
  15083. }
  15084. class LinearInterpolant extends Interpolant {
  15085. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  15086. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  15087. }
  15088. interpolate_( i1, t0, t, t1 ) {
  15089. const result = this.resultBuffer,
  15090. values = this.sampleValues,
  15091. stride = this.valueSize,
  15092. offset1 = i1 * stride,
  15093. offset0 = offset1 - stride,
  15094. weight1 = ( t - t0 ) / ( t1 - t0 ),
  15095. weight0 = 1 - weight1;
  15096. for ( let i = 0; i !== stride; ++ i ) {
  15097. result[ i ] =
  15098. values[ offset0 + i ] * weight0 +
  15099. values[ offset1 + i ] * weight1;
  15100. }
  15101. return result;
  15102. }
  15103. }
  15104. /**
  15105. *
  15106. * Interpolant that evaluates to the sample value at the position preceding
  15107. * the parameter.
  15108. */
  15109. class DiscreteInterpolant extends Interpolant {
  15110. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  15111. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  15112. }
  15113. interpolate_( i1 /*, t0, t, t1 */ ) {
  15114. return this.copySampleValue_( i1 - 1 );
  15115. }
  15116. }
  15117. class KeyframeTrack {
  15118. constructor( name, times, values, interpolation ) {
  15119. if ( name === undefined ) throw new Error( 'THREE.KeyframeTrack: track name is undefined' );
  15120. if ( times === undefined || times.length === 0 ) throw new Error( 'THREE.KeyframeTrack: no keyframes in track named ' + name );
  15121. this.name = name;
  15122. this.times = convertArray( times, this.TimeBufferType );
  15123. this.values = convertArray( values, this.ValueBufferType );
  15124. this.setInterpolation( interpolation || this.DefaultInterpolation );
  15125. }
  15126. // Serialization (in static context, because of constructor invocation
  15127. // and automatic invocation of .toJSON):
  15128. static toJSON( track ) {
  15129. const trackType = track.constructor;
  15130. let json;
  15131. // derived classes can define a static toJSON method
  15132. if ( trackType.toJSON !== this.toJSON ) {
  15133. json = trackType.toJSON( track );
  15134. } else {
  15135. // by default, we assume the data can be serialized as-is
  15136. json = {
  15137. 'name': track.name,
  15138. 'times': convertArray( track.times, Array ),
  15139. 'values': convertArray( track.values, Array )
  15140. };
  15141. const interpolation = track.getInterpolation();
  15142. if ( interpolation !== track.DefaultInterpolation ) {
  15143. json.interpolation = interpolation;
  15144. }
  15145. }
  15146. json.type = track.ValueTypeName; // mandatory
  15147. return json;
  15148. }
  15149. InterpolantFactoryMethodDiscrete( result ) {
  15150. return new DiscreteInterpolant( this.times, this.values, this.getValueSize(), result );
  15151. }
  15152. InterpolantFactoryMethodLinear( result ) {
  15153. return new LinearInterpolant( this.times, this.values, this.getValueSize(), result );
  15154. }
  15155. InterpolantFactoryMethodSmooth( result ) {
  15156. return new CubicInterpolant( this.times, this.values, this.getValueSize(), result );
  15157. }
  15158. setInterpolation( interpolation ) {
  15159. let factoryMethod;
  15160. switch ( interpolation ) {
  15161. case InterpolateDiscrete:
  15162. factoryMethod = this.InterpolantFactoryMethodDiscrete;
  15163. break;
  15164. case InterpolateLinear:
  15165. factoryMethod = this.InterpolantFactoryMethodLinear;
  15166. break;
  15167. case InterpolateSmooth:
  15168. factoryMethod = this.InterpolantFactoryMethodSmooth;
  15169. break;
  15170. }
  15171. if ( factoryMethod === undefined ) {
  15172. const message = 'unsupported interpolation for ' +
  15173. this.ValueTypeName + ' keyframe track named ' + this.name;
  15174. if ( this.createInterpolant === undefined ) {
  15175. // fall back to default, unless the default itself is messed up
  15176. if ( interpolation !== this.DefaultInterpolation ) {
  15177. this.setInterpolation( this.DefaultInterpolation );
  15178. } else {
  15179. throw new Error( message ); // fatal, in this case
  15180. }
  15181. }
  15182. console.warn( 'THREE.KeyframeTrack:', message );
  15183. return this;
  15184. }
  15185. this.createInterpolant = factoryMethod;
  15186. return this;
  15187. }
  15188. getInterpolation() {
  15189. switch ( this.createInterpolant ) {
  15190. case this.InterpolantFactoryMethodDiscrete:
  15191. return InterpolateDiscrete;
  15192. case this.InterpolantFactoryMethodLinear:
  15193. return InterpolateLinear;
  15194. case this.InterpolantFactoryMethodSmooth:
  15195. return InterpolateSmooth;
  15196. }
  15197. }
  15198. getValueSize() {
  15199. return this.values.length / this.times.length;
  15200. }
  15201. // move all keyframes either forwards or backwards in time
  15202. shift( timeOffset ) {
  15203. if ( timeOffset !== 0.0 ) {
  15204. const times = this.times;
  15205. for ( let i = 0, n = times.length; i !== n; ++ i ) {
  15206. times[ i ] += timeOffset;
  15207. }
  15208. }
  15209. return this;
  15210. }
  15211. // scale all keyframe times by a factor (useful for frame <-> seconds conversions)
  15212. scale( timeScale ) {
  15213. if ( timeScale !== 1.0 ) {
  15214. const times = this.times;
  15215. for ( let i = 0, n = times.length; i !== n; ++ i ) {
  15216. times[ i ] *= timeScale;
  15217. }
  15218. }
  15219. return this;
  15220. }
  15221. // removes keyframes before and after animation without changing any values within the range [startTime, endTime].
  15222. // IMPORTANT: We do not shift around keys to the start of the track time, because for interpolated keys this will change their values
  15223. trim( startTime, endTime ) {
  15224. const times = this.times,
  15225. nKeys = times.length;
  15226. let from = 0,
  15227. to = nKeys - 1;
  15228. while ( from !== nKeys && times[ from ] < startTime ) {
  15229. ++ from;
  15230. }
  15231. while ( to !== - 1 && times[ to ] > endTime ) {
  15232. -- to;
  15233. }
  15234. ++ to; // inclusive -> exclusive bound
  15235. if ( from !== 0 || to !== nKeys ) {
  15236. // empty tracks are forbidden, so keep at least one keyframe
  15237. if ( from >= to ) {
  15238. to = Math.max( to, 1 );
  15239. from = to - 1;
  15240. }
  15241. const stride = this.getValueSize();
  15242. this.times = times.slice( from, to );
  15243. this.values = this.values.slice( from * stride, to * stride );
  15244. }
  15245. return this;
  15246. }
  15247. // ensure we do not get a GarbageInGarbageOut situation, make sure tracks are at least minimally viable
  15248. validate() {
  15249. let valid = true;
  15250. const valueSize = this.getValueSize();
  15251. if ( valueSize - Math.floor( valueSize ) !== 0 ) {
  15252. console.error( 'THREE.KeyframeTrack: Invalid value size in track.', this );
  15253. valid = false;
  15254. }
  15255. const times = this.times,
  15256. values = this.values,
  15257. nKeys = times.length;
  15258. if ( nKeys === 0 ) {
  15259. console.error( 'THREE.KeyframeTrack: Track is empty.', this );
  15260. valid = false;
  15261. }
  15262. let prevTime = null;
  15263. for ( let i = 0; i !== nKeys; i ++ ) {
  15264. const currTime = times[ i ];
  15265. if ( typeof currTime === 'number' && isNaN( currTime ) ) {
  15266. console.error( 'THREE.KeyframeTrack: Time is not a valid number.', this, i, currTime );
  15267. valid = false;
  15268. break;
  15269. }
  15270. if ( prevTime !== null && prevTime > currTime ) {
  15271. console.error( 'THREE.KeyframeTrack: Out of order keys.', this, i, currTime, prevTime );
  15272. valid = false;
  15273. break;
  15274. }
  15275. prevTime = currTime;
  15276. }
  15277. if ( values !== undefined ) {
  15278. if ( isTypedArray( values ) ) {
  15279. for ( let i = 0, n = values.length; i !== n; ++ i ) {
  15280. const value = values[ i ];
  15281. if ( isNaN( value ) ) {
  15282. console.error( 'THREE.KeyframeTrack: Value is not a valid number.', this, i, value );
  15283. valid = false;
  15284. break;
  15285. }
  15286. }
  15287. }
  15288. }
  15289. return valid;
  15290. }
  15291. // removes equivalent sequential keys as common in morph target sequences
  15292. // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0)
  15293. optimize() {
  15294. // times or values may be shared with other tracks, so overwriting is unsafe
  15295. const times = this.times.slice(),
  15296. values = this.values.slice(),
  15297. stride = this.getValueSize(),
  15298. smoothInterpolation = this.getInterpolation() === InterpolateSmooth,
  15299. lastIndex = times.length - 1;
  15300. let writeIndex = 1;
  15301. for ( let i = 1; i < lastIndex; ++ i ) {
  15302. let keep = false;
  15303. const time = times[ i ];
  15304. const timeNext = times[ i + 1 ];
  15305. // remove adjacent keyframes scheduled at the same time
  15306. if ( time !== timeNext && ( i !== 1 || time !== times[ 0 ] ) ) {
  15307. if ( ! smoothInterpolation ) {
  15308. // remove unnecessary keyframes same as their neighbors
  15309. const offset = i * stride,
  15310. offsetP = offset - stride,
  15311. offsetN = offset + stride;
  15312. for ( let j = 0; j !== stride; ++ j ) {
  15313. const value = values[ offset + j ];
  15314. if ( value !== values[ offsetP + j ] ||
  15315. value !== values[ offsetN + j ] ) {
  15316. keep = true;
  15317. break;
  15318. }
  15319. }
  15320. } else {
  15321. keep = true;
  15322. }
  15323. }
  15324. // in-place compaction
  15325. if ( keep ) {
  15326. if ( i !== writeIndex ) {
  15327. times[ writeIndex ] = times[ i ];
  15328. const readOffset = i * stride,
  15329. writeOffset = writeIndex * stride;
  15330. for ( let j = 0; j !== stride; ++ j ) {
  15331. values[ writeOffset + j ] = values[ readOffset + j ];
  15332. }
  15333. }
  15334. ++ writeIndex;
  15335. }
  15336. }
  15337. // flush last keyframe (compaction looks ahead)
  15338. if ( lastIndex > 0 ) {
  15339. times[ writeIndex ] = times[ lastIndex ];
  15340. for ( let readOffset = lastIndex * stride, writeOffset = writeIndex * stride, j = 0; j !== stride; ++ j ) {
  15341. values[ writeOffset + j ] = values[ readOffset + j ];
  15342. }
  15343. ++ writeIndex;
  15344. }
  15345. if ( writeIndex !== times.length ) {
  15346. this.times = times.slice( 0, writeIndex );
  15347. this.values = values.slice( 0, writeIndex * stride );
  15348. } else {
  15349. this.times = times;
  15350. this.values = values;
  15351. }
  15352. return this;
  15353. }
  15354. clone() {
  15355. const times = this.times.slice();
  15356. const values = this.values.slice();
  15357. const TypedKeyframeTrack = this.constructor;
  15358. const track = new TypedKeyframeTrack( this.name, times, values );
  15359. // Interpolant argument to constructor is not saved, so copy the factory method directly.
  15360. track.createInterpolant = this.createInterpolant;
  15361. return track;
  15362. }
  15363. }
  15364. KeyframeTrack.prototype.TimeBufferType = Float32Array;
  15365. KeyframeTrack.prototype.ValueBufferType = Float32Array;
  15366. KeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear;
  15367. /**
  15368. * A Track of Boolean keyframe values.
  15369. */
  15370. class BooleanKeyframeTrack extends KeyframeTrack {
  15371. // No interpolation parameter because only InterpolateDiscrete is valid.
  15372. constructor( name, times, values ) {
  15373. super( name, times, values );
  15374. }
  15375. }
  15376. BooleanKeyframeTrack.prototype.ValueTypeName = 'bool';
  15377. BooleanKeyframeTrack.prototype.ValueBufferType = Array;
  15378. BooleanKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  15379. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  15380. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  15381. /**
  15382. * A Track of keyframe values that represent color.
  15383. */
  15384. class ColorKeyframeTrack extends KeyframeTrack {}
  15385. ColorKeyframeTrack.prototype.ValueTypeName = 'color';
  15386. /**
  15387. * A Track of numeric keyframe values.
  15388. */
  15389. class NumberKeyframeTrack extends KeyframeTrack {}
  15390. NumberKeyframeTrack.prototype.ValueTypeName = 'number';
  15391. /**
  15392. * Spherical linear unit quaternion interpolant.
  15393. */
  15394. class QuaternionLinearInterpolant extends Interpolant {
  15395. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  15396. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  15397. }
  15398. interpolate_( i1, t0, t, t1 ) {
  15399. const result = this.resultBuffer,
  15400. values = this.sampleValues,
  15401. stride = this.valueSize,
  15402. alpha = ( t - t0 ) / ( t1 - t0 );
  15403. let offset = i1 * stride;
  15404. for ( let end = offset + stride; offset !== end; offset += 4 ) {
  15405. Quaternion.slerpFlat( result, 0, values, offset - stride, values, offset, alpha );
  15406. }
  15407. return result;
  15408. }
  15409. }
  15410. /**
  15411. * A Track of quaternion keyframe values.
  15412. */
  15413. class QuaternionKeyframeTrack extends KeyframeTrack {
  15414. InterpolantFactoryMethodLinear( result ) {
  15415. return new QuaternionLinearInterpolant( this.times, this.values, this.getValueSize(), result );
  15416. }
  15417. }
  15418. QuaternionKeyframeTrack.prototype.ValueTypeName = 'quaternion';
  15419. // ValueBufferType is inherited
  15420. // DefaultInterpolation is inherited;
  15421. QuaternionKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  15422. /**
  15423. * A Track that interpolates Strings
  15424. */
  15425. class StringKeyframeTrack extends KeyframeTrack {
  15426. // No interpolation parameter because only InterpolateDiscrete is valid.
  15427. constructor( name, times, values ) {
  15428. super( name, times, values );
  15429. }
  15430. }
  15431. StringKeyframeTrack.prototype.ValueTypeName = 'string';
  15432. StringKeyframeTrack.prototype.ValueBufferType = Array;
  15433. StringKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  15434. StringKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  15435. StringKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  15436. /**
  15437. * A Track of vectored keyframe values.
  15438. */
  15439. class VectorKeyframeTrack extends KeyframeTrack {}
  15440. VectorKeyframeTrack.prototype.ValueTypeName = 'vector';
  15441. class AnimationClip {
  15442. constructor( name = '', duration = - 1, tracks = [], blendMode = NormalAnimationBlendMode ) {
  15443. this.name = name;
  15444. this.tracks = tracks;
  15445. this.duration = duration;
  15446. this.blendMode = blendMode;
  15447. this.uuid = generateUUID();
  15448. // this means it should figure out its duration by scanning the tracks
  15449. if ( this.duration < 0 ) {
  15450. this.resetDuration();
  15451. }
  15452. }
  15453. static parse( json ) {
  15454. const tracks = [],
  15455. jsonTracks = json.tracks,
  15456. frameTime = 1.0 / ( json.fps || 1.0 );
  15457. for ( let i = 0, n = jsonTracks.length; i !== n; ++ i ) {
  15458. tracks.push( parseKeyframeTrack( jsonTracks[ i ] ).scale( frameTime ) );
  15459. }
  15460. const clip = new this( json.name, json.duration, tracks, json.blendMode );
  15461. clip.uuid = json.uuid;
  15462. return clip;
  15463. }
  15464. static toJSON( clip ) {
  15465. const tracks = [],
  15466. clipTracks = clip.tracks;
  15467. const json = {
  15468. 'name': clip.name,
  15469. 'duration': clip.duration,
  15470. 'tracks': tracks,
  15471. 'uuid': clip.uuid,
  15472. 'blendMode': clip.blendMode
  15473. };
  15474. for ( let i = 0, n = clipTracks.length; i !== n; ++ i ) {
  15475. tracks.push( KeyframeTrack.toJSON( clipTracks[ i ] ) );
  15476. }
  15477. return json;
  15478. }
  15479. static CreateFromMorphTargetSequence( name, morphTargetSequence, fps, noLoop ) {
  15480. const numMorphTargets = morphTargetSequence.length;
  15481. const tracks = [];
  15482. for ( let i = 0; i < numMorphTargets; i ++ ) {
  15483. let times = [];
  15484. let values = [];
  15485. times.push(
  15486. ( i + numMorphTargets - 1 ) % numMorphTargets,
  15487. i,
  15488. ( i + 1 ) % numMorphTargets );
  15489. values.push( 0, 1, 0 );
  15490. const order = getKeyframeOrder( times );
  15491. times = sortedArray( times, 1, order );
  15492. values = sortedArray( values, 1, order );
  15493. // if there is a key at the first frame, duplicate it as the
  15494. // last frame as well for perfect loop.
  15495. if ( ! noLoop && times[ 0 ] === 0 ) {
  15496. times.push( numMorphTargets );
  15497. values.push( values[ 0 ] );
  15498. }
  15499. tracks.push(
  15500. new NumberKeyframeTrack(
  15501. '.morphTargetInfluences[' + morphTargetSequence[ i ].name + ']',
  15502. times, values
  15503. ).scale( 1.0 / fps ) );
  15504. }
  15505. return new this( name, - 1, tracks );
  15506. }
  15507. static findByName( objectOrClipArray, name ) {
  15508. let clipArray = objectOrClipArray;
  15509. if ( ! Array.isArray( objectOrClipArray ) ) {
  15510. const o = objectOrClipArray;
  15511. clipArray = o.geometry && o.geometry.animations || o.animations;
  15512. }
  15513. for ( let i = 0; i < clipArray.length; i ++ ) {
  15514. if ( clipArray[ i ].name === name ) {
  15515. return clipArray[ i ];
  15516. }
  15517. }
  15518. return null;
  15519. }
  15520. static CreateClipsFromMorphTargetSequences( morphTargets, fps, noLoop ) {
  15521. const animationToMorphTargets = {};
  15522. // tested with https://regex101.com/ on trick sequences
  15523. // such flamingo_flyA_003, flamingo_run1_003, crdeath0059
  15524. const pattern = /^([\w-]*?)([\d]+)$/;
  15525. // sort morph target names into animation groups based
  15526. // patterns like Walk_001, Walk_002, Run_001, Run_002
  15527. for ( let i = 0, il = morphTargets.length; i < il; i ++ ) {
  15528. const morphTarget = morphTargets[ i ];
  15529. const parts = morphTarget.name.match( pattern );
  15530. if ( parts && parts.length > 1 ) {
  15531. const name = parts[ 1 ];
  15532. let animationMorphTargets = animationToMorphTargets[ name ];
  15533. if ( ! animationMorphTargets ) {
  15534. animationToMorphTargets[ name ] = animationMorphTargets = [];
  15535. }
  15536. animationMorphTargets.push( morphTarget );
  15537. }
  15538. }
  15539. const clips = [];
  15540. for ( const name in animationToMorphTargets ) {
  15541. clips.push( this.CreateFromMorphTargetSequence( name, animationToMorphTargets[ name ], fps, noLoop ) );
  15542. }
  15543. return clips;
  15544. }
  15545. // parse the animation.hierarchy format
  15546. static parseAnimation( animation, bones ) {
  15547. if ( ! animation ) {
  15548. console.error( 'THREE.AnimationClip: No animation in JSONLoader data.' );
  15549. return null;
  15550. }
  15551. const addNonemptyTrack = function ( trackType, trackName, animationKeys, propertyName, destTracks ) {
  15552. // only return track if there are actually keys.
  15553. if ( animationKeys.length !== 0 ) {
  15554. const times = [];
  15555. const values = [];
  15556. flattenJSON( animationKeys, times, values, propertyName );
  15557. // empty keys are filtered out, so check again
  15558. if ( times.length !== 0 ) {
  15559. destTracks.push( new trackType( trackName, times, values ) );
  15560. }
  15561. }
  15562. };
  15563. const tracks = [];
  15564. const clipName = animation.name || 'default';
  15565. const fps = animation.fps || 30;
  15566. const blendMode = animation.blendMode;
  15567. // automatic length determination in AnimationClip.
  15568. let duration = animation.length || - 1;
  15569. const hierarchyTracks = animation.hierarchy || [];
  15570. for ( let h = 0; h < hierarchyTracks.length; h ++ ) {
  15571. const animationKeys = hierarchyTracks[ h ].keys;
  15572. // skip empty tracks
  15573. if ( ! animationKeys || animationKeys.length === 0 ) continue;
  15574. // process morph targets
  15575. if ( animationKeys[ 0 ].morphTargets ) {
  15576. // figure out all morph targets used in this track
  15577. const morphTargetNames = {};
  15578. let k;
  15579. for ( k = 0; k < animationKeys.length; k ++ ) {
  15580. if ( animationKeys[ k ].morphTargets ) {
  15581. for ( let m = 0; m < animationKeys[ k ].morphTargets.length; m ++ ) {
  15582. morphTargetNames[ animationKeys[ k ].morphTargets[ m ] ] = - 1;
  15583. }
  15584. }
  15585. }
  15586. // create a track for each morph target with all zero
  15587. // morphTargetInfluences except for the keys in which
  15588. // the morphTarget is named.
  15589. for ( const morphTargetName in morphTargetNames ) {
  15590. const times = [];
  15591. const values = [];
  15592. for ( let m = 0; m !== animationKeys[ k ].morphTargets.length; ++ m ) {
  15593. const animationKey = animationKeys[ k ];
  15594. times.push( animationKey.time );
  15595. values.push( ( animationKey.morphTarget === morphTargetName ) ? 1 : 0 );
  15596. }
  15597. tracks.push( new NumberKeyframeTrack( '.morphTargetInfluence[' + morphTargetName + ']', times, values ) );
  15598. }
  15599. duration = morphTargetNames.length * fps;
  15600. } else {
  15601. // ...assume skeletal animation
  15602. const boneName = '.bones[' + bones[ h ].name + ']';
  15603. addNonemptyTrack(
  15604. VectorKeyframeTrack, boneName + '.position',
  15605. animationKeys, 'pos', tracks );
  15606. addNonemptyTrack(
  15607. QuaternionKeyframeTrack, boneName + '.quaternion',
  15608. animationKeys, 'rot', tracks );
  15609. addNonemptyTrack(
  15610. VectorKeyframeTrack, boneName + '.scale',
  15611. animationKeys, 'scl', tracks );
  15612. }
  15613. }
  15614. if ( tracks.length === 0 ) {
  15615. return null;
  15616. }
  15617. const clip = new this( clipName, duration, tracks, blendMode );
  15618. return clip;
  15619. }
  15620. resetDuration() {
  15621. const tracks = this.tracks;
  15622. let duration = 0;
  15623. for ( let i = 0, n = tracks.length; i !== n; ++ i ) {
  15624. const track = this.tracks[ i ];
  15625. duration = Math.max( duration, track.times[ track.times.length - 1 ] );
  15626. }
  15627. this.duration = duration;
  15628. return this;
  15629. }
  15630. trim() {
  15631. for ( let i = 0; i < this.tracks.length; i ++ ) {
  15632. this.tracks[ i ].trim( 0, this.duration );
  15633. }
  15634. return this;
  15635. }
  15636. validate() {
  15637. let valid = true;
  15638. for ( let i = 0; i < this.tracks.length; i ++ ) {
  15639. valid = valid && this.tracks[ i ].validate();
  15640. }
  15641. return valid;
  15642. }
  15643. optimize() {
  15644. for ( let i = 0; i < this.tracks.length; i ++ ) {
  15645. this.tracks[ i ].optimize();
  15646. }
  15647. return this;
  15648. }
  15649. clone() {
  15650. const tracks = [];
  15651. for ( let i = 0; i < this.tracks.length; i ++ ) {
  15652. tracks.push( this.tracks[ i ].clone() );
  15653. }
  15654. return new this.constructor( this.name, this.duration, tracks, this.blendMode );
  15655. }
  15656. toJSON() {
  15657. return this.constructor.toJSON( this );
  15658. }
  15659. }
  15660. function getTrackTypeForValueTypeName( typeName ) {
  15661. switch ( typeName.toLowerCase() ) {
  15662. case 'scalar':
  15663. case 'double':
  15664. case 'float':
  15665. case 'number':
  15666. case 'integer':
  15667. return NumberKeyframeTrack;
  15668. case 'vector':
  15669. case 'vector2':
  15670. case 'vector3':
  15671. case 'vector4':
  15672. return VectorKeyframeTrack;
  15673. case 'color':
  15674. return ColorKeyframeTrack;
  15675. case 'quaternion':
  15676. return QuaternionKeyframeTrack;
  15677. case 'bool':
  15678. case 'boolean':
  15679. return BooleanKeyframeTrack;
  15680. case 'string':
  15681. return StringKeyframeTrack;
  15682. }
  15683. throw new Error( 'THREE.KeyframeTrack: Unsupported typeName: ' + typeName );
  15684. }
  15685. function parseKeyframeTrack( json ) {
  15686. if ( json.type === undefined ) {
  15687. throw new Error( 'THREE.KeyframeTrack: track type undefined, can not parse' );
  15688. }
  15689. const trackType = getTrackTypeForValueTypeName( json.type );
  15690. if ( json.times === undefined ) {
  15691. const times = [], values = [];
  15692. flattenJSON( json.keys, times, values, 'value' );
  15693. json.times = times;
  15694. json.values = values;
  15695. }
  15696. // derived classes can define a static parse method
  15697. if ( trackType.parse !== undefined ) {
  15698. return trackType.parse( json );
  15699. } else {
  15700. // by default, we assume a constructor compatible with the base
  15701. return new trackType( json.name, json.times, json.values, json.interpolation );
  15702. }
  15703. }
  15704. const Cache = {
  15705. enabled: false,
  15706. files: {},
  15707. add: function ( key, file ) {
  15708. if ( this.enabled === false ) return;
  15709. // console.log( 'THREE.Cache', 'Adding key:', key );
  15710. this.files[ key ] = file;
  15711. },
  15712. get: function ( key ) {
  15713. if ( this.enabled === false ) return;
  15714. // console.log( 'THREE.Cache', 'Checking key:', key );
  15715. return this.files[ key ];
  15716. },
  15717. remove: function ( key ) {
  15718. delete this.files[ key ];
  15719. },
  15720. clear: function () {
  15721. this.files = {};
  15722. }
  15723. };
  15724. class LoadingManager {
  15725. constructor( onLoad, onProgress, onError ) {
  15726. const scope = this;
  15727. let isLoading = false;
  15728. let itemsLoaded = 0;
  15729. let itemsTotal = 0;
  15730. let urlModifier = undefined;
  15731. const handlers = [];
  15732. // Refer to #5689 for the reason why we don't set .onStart
  15733. // in the constructor
  15734. this.onStart = undefined;
  15735. this.onLoad = onLoad;
  15736. this.onProgress = onProgress;
  15737. this.onError = onError;
  15738. this.itemStart = function ( url ) {
  15739. itemsTotal ++;
  15740. if ( isLoading === false ) {
  15741. if ( scope.onStart !== undefined ) {
  15742. scope.onStart( url, itemsLoaded, itemsTotal );
  15743. }
  15744. }
  15745. isLoading = true;
  15746. };
  15747. this.itemEnd = function ( url ) {
  15748. itemsLoaded ++;
  15749. if ( scope.onProgress !== undefined ) {
  15750. scope.onProgress( url, itemsLoaded, itemsTotal );
  15751. }
  15752. if ( itemsLoaded === itemsTotal ) {
  15753. isLoading = false;
  15754. if ( scope.onLoad !== undefined ) {
  15755. scope.onLoad();
  15756. }
  15757. }
  15758. };
  15759. this.itemError = function ( url ) {
  15760. if ( scope.onError !== undefined ) {
  15761. scope.onError( url );
  15762. }
  15763. };
  15764. this.resolveURL = function ( url ) {
  15765. if ( urlModifier ) {
  15766. return urlModifier( url );
  15767. }
  15768. return url;
  15769. };
  15770. this.setURLModifier = function ( transform ) {
  15771. urlModifier = transform;
  15772. return this;
  15773. };
  15774. this.addHandler = function ( regex, loader ) {
  15775. handlers.push( regex, loader );
  15776. return this;
  15777. };
  15778. this.removeHandler = function ( regex ) {
  15779. const index = handlers.indexOf( regex );
  15780. if ( index !== - 1 ) {
  15781. handlers.splice( index, 2 );
  15782. }
  15783. return this;
  15784. };
  15785. this.getHandler = function ( file ) {
  15786. for ( let i = 0, l = handlers.length; i < l; i += 2 ) {
  15787. const regex = handlers[ i ];
  15788. const loader = handlers[ i + 1 ];
  15789. if ( regex.global ) regex.lastIndex = 0; // see #17920
  15790. if ( regex.test( file ) ) {
  15791. return loader;
  15792. }
  15793. }
  15794. return null;
  15795. };
  15796. }
  15797. }
  15798. const DefaultLoadingManager = /*@__PURE__*/ new LoadingManager();
  15799. class Loader {
  15800. constructor( manager ) {
  15801. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  15802. this.crossOrigin = 'anonymous';
  15803. this.withCredentials = false;
  15804. this.path = '';
  15805. this.resourcePath = '';
  15806. this.requestHeader = {};
  15807. }
  15808. load( /* url, onLoad, onProgress, onError */ ) {}
  15809. loadAsync( url, onProgress ) {
  15810. const scope = this;
  15811. return new Promise( function ( resolve, reject ) {
  15812. scope.load( url, resolve, onProgress, reject );
  15813. } );
  15814. }
  15815. parse( /* data */ ) {}
  15816. setCrossOrigin( crossOrigin ) {
  15817. this.crossOrigin = crossOrigin;
  15818. return this;
  15819. }
  15820. setWithCredentials( value ) {
  15821. this.withCredentials = value;
  15822. return this;
  15823. }
  15824. setPath( path ) {
  15825. this.path = path;
  15826. return this;
  15827. }
  15828. setResourcePath( resourcePath ) {
  15829. this.resourcePath = resourcePath;
  15830. return this;
  15831. }
  15832. setRequestHeader( requestHeader ) {
  15833. this.requestHeader = requestHeader;
  15834. return this;
  15835. }
  15836. }
  15837. Loader.DEFAULT_MATERIAL_NAME = '__DEFAULT';
  15838. const loading = {};
  15839. class HttpError extends Error {
  15840. constructor( message, response ) {
  15841. super( message );
  15842. this.response = response;
  15843. }
  15844. }
  15845. class FileLoader extends Loader {
  15846. constructor( manager ) {
  15847. super( manager );
  15848. }
  15849. load( url, onLoad, onProgress, onError ) {
  15850. if ( url === undefined ) url = '';
  15851. if ( this.path !== undefined ) url = this.path + url;
  15852. url = this.manager.resolveURL( url );
  15853. const cached = Cache.get( url );
  15854. if ( cached !== undefined ) {
  15855. this.manager.itemStart( url );
  15856. setTimeout( () => {
  15857. if ( onLoad ) onLoad( cached );
  15858. this.manager.itemEnd( url );
  15859. }, 0 );
  15860. return cached;
  15861. }
  15862. // Check if request is duplicate
  15863. if ( loading[ url ] !== undefined ) {
  15864. loading[ url ].push( {
  15865. onLoad: onLoad,
  15866. onProgress: onProgress,
  15867. onError: onError
  15868. } );
  15869. return;
  15870. }
  15871. // Initialise array for duplicate requests
  15872. loading[ url ] = [];
  15873. loading[ url ].push( {
  15874. onLoad: onLoad,
  15875. onProgress: onProgress,
  15876. onError: onError,
  15877. } );
  15878. // create request
  15879. const req = new Request( url, {
  15880. headers: new Headers( this.requestHeader ),
  15881. credentials: this.withCredentials ? 'include' : 'same-origin',
  15882. // An abort controller could be added within a future PR
  15883. } );
  15884. // record states ( avoid data race )
  15885. const mimeType = this.mimeType;
  15886. const responseType = this.responseType;
  15887. // start the fetch
  15888. fetch( req )
  15889. .then( response => {
  15890. if ( response.status === 200 || response.status === 0 ) {
  15891. // Some browsers return HTTP Status 0 when using non-http protocol
  15892. // e.g. 'file://' or 'data://'. Handle as success.
  15893. if ( response.status === 0 ) {
  15894. console.warn( 'THREE.FileLoader: HTTP Status 0 received.' );
  15895. }
  15896. // Workaround: Checking if response.body === undefined for Alipay browser #23548
  15897. if ( typeof ReadableStream === 'undefined' || response.body === undefined || response.body.getReader === undefined ) {
  15898. return response;
  15899. }
  15900. const callbacks = loading[ url ];
  15901. const reader = response.body.getReader();
  15902. // Nginx needs X-File-Size check
  15903. // https://serverfault.com/questions/482875/why-does-nginx-remove-content-length-header-for-chunked-content
  15904. const contentLength = response.headers.get( 'X-File-Size' ) || response.headers.get( 'Content-Length' );
  15905. const total = contentLength ? parseInt( contentLength ) : 0;
  15906. const lengthComputable = total !== 0;
  15907. let loaded = 0;
  15908. // periodically read data into the new stream tracking while download progress
  15909. const stream = new ReadableStream( {
  15910. start( controller ) {
  15911. readData();
  15912. function readData() {
  15913. reader.read().then( ( { done, value } ) => {
  15914. if ( done ) {
  15915. controller.close();
  15916. } else {
  15917. loaded += value.byteLength;
  15918. const event = new ProgressEvent( 'progress', { lengthComputable, loaded, total } );
  15919. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  15920. const callback = callbacks[ i ];
  15921. if ( callback.onProgress ) callback.onProgress( event );
  15922. }
  15923. controller.enqueue( value );
  15924. readData();
  15925. }
  15926. }, ( e ) => {
  15927. controller.error( e );
  15928. } );
  15929. }
  15930. }
  15931. } );
  15932. return new Response( stream );
  15933. } else {
  15934. throw new HttpError( `fetch for "${response.url}" responded with ${response.status}: ${response.statusText}`, response );
  15935. }
  15936. } )
  15937. .then( response => {
  15938. switch ( responseType ) {
  15939. case 'arraybuffer':
  15940. return response.arrayBuffer();
  15941. case 'blob':
  15942. return response.blob();
  15943. case 'document':
  15944. return response.text()
  15945. .then( text => {
  15946. const parser = new DOMParser();
  15947. return parser.parseFromString( text, mimeType );
  15948. } );
  15949. case 'json':
  15950. return response.json();
  15951. default:
  15952. if ( mimeType === undefined ) {
  15953. return response.text();
  15954. } else {
  15955. // sniff encoding
  15956. const re = /charset="?([^;"\s]*)"?/i;
  15957. const exec = re.exec( mimeType );
  15958. const label = exec && exec[ 1 ] ? exec[ 1 ].toLowerCase() : undefined;
  15959. const decoder = new TextDecoder( label );
  15960. return response.arrayBuffer().then( ab => decoder.decode( ab ) );
  15961. }
  15962. }
  15963. } )
  15964. .then( data => {
  15965. // Add to cache only on HTTP success, so that we do not cache
  15966. // error response bodies as proper responses to requests.
  15967. Cache.add( url, data );
  15968. const callbacks = loading[ url ];
  15969. delete loading[ url ];
  15970. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  15971. const callback = callbacks[ i ];
  15972. if ( callback.onLoad ) callback.onLoad( data );
  15973. }
  15974. } )
  15975. .catch( err => {
  15976. // Abort errors and other errors are handled the same
  15977. const callbacks = loading[ url ];
  15978. if ( callbacks === undefined ) {
  15979. // When onLoad was called and url was deleted in `loading`
  15980. this.manager.itemError( url );
  15981. throw err;
  15982. }
  15983. delete loading[ url ];
  15984. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  15985. const callback = callbacks[ i ];
  15986. if ( callback.onError ) callback.onError( err );
  15987. }
  15988. this.manager.itemError( url );
  15989. } )
  15990. .finally( () => {
  15991. this.manager.itemEnd( url );
  15992. } );
  15993. this.manager.itemStart( url );
  15994. }
  15995. setResponseType( value ) {
  15996. this.responseType = value;
  15997. return this;
  15998. }
  15999. setMimeType( value ) {
  16000. this.mimeType = value;
  16001. return this;
  16002. }
  16003. }
  16004. class AnimationLoader extends Loader {
  16005. constructor( manager ) {
  16006. super( manager );
  16007. }
  16008. load( url, onLoad, onProgress, onError ) {
  16009. const scope = this;
  16010. const loader = new FileLoader( this.manager );
  16011. loader.setPath( this.path );
  16012. loader.setRequestHeader( this.requestHeader );
  16013. loader.setWithCredentials( this.withCredentials );
  16014. loader.load( url, function ( text ) {
  16015. try {
  16016. onLoad( scope.parse( JSON.parse( text ) ) );
  16017. } catch ( e ) {
  16018. if ( onError ) {
  16019. onError( e );
  16020. } else {
  16021. console.error( e );
  16022. }
  16023. scope.manager.itemError( url );
  16024. }
  16025. }, onProgress, onError );
  16026. }
  16027. parse( json ) {
  16028. const animations = [];
  16029. for ( let i = 0; i < json.length; i ++ ) {
  16030. const clip = AnimationClip.parse( json[ i ] );
  16031. animations.push( clip );
  16032. }
  16033. return animations;
  16034. }
  16035. }
  16036. /**
  16037. * Abstract Base class to block based textures loader (dds, pvr, ...)
  16038. *
  16039. * Sub classes have to implement the parse() method which will be used in load().
  16040. */
  16041. class CompressedTextureLoader extends Loader {
  16042. constructor( manager ) {
  16043. super( manager );
  16044. }
  16045. load( url, onLoad, onProgress, onError ) {
  16046. const scope = this;
  16047. const images = [];
  16048. const texture = new CompressedTexture();
  16049. const loader = new FileLoader( this.manager );
  16050. loader.setPath( this.path );
  16051. loader.setResponseType( 'arraybuffer' );
  16052. loader.setRequestHeader( this.requestHeader );
  16053. loader.setWithCredentials( scope.withCredentials );
  16054. let loaded = 0;
  16055. function loadTexture( i ) {
  16056. loader.load( url[ i ], function ( buffer ) {
  16057. const texDatas = scope.parse( buffer, true );
  16058. images[ i ] = {
  16059. width: texDatas.width,
  16060. height: texDatas.height,
  16061. format: texDatas.format,
  16062. mipmaps: texDatas.mipmaps
  16063. };
  16064. loaded += 1;
  16065. if ( loaded === 6 ) {
  16066. if ( texDatas.mipmapCount === 1 ) texture.minFilter = LinearFilter;
  16067. texture.image = images;
  16068. texture.format = texDatas.format;
  16069. texture.needsUpdate = true;
  16070. if ( onLoad ) onLoad( texture );
  16071. }
  16072. }, onProgress, onError );
  16073. }
  16074. if ( Array.isArray( url ) ) {
  16075. for ( let i = 0, il = url.length; i < il; ++ i ) {
  16076. loadTexture( i );
  16077. }
  16078. } else {
  16079. // compressed cubemap texture stored in a single DDS file
  16080. loader.load( url, function ( buffer ) {
  16081. const texDatas = scope.parse( buffer, true );
  16082. if ( texDatas.isCubemap ) {
  16083. const faces = texDatas.mipmaps.length / texDatas.mipmapCount;
  16084. for ( let f = 0; f < faces; f ++ ) {
  16085. images[ f ] = { mipmaps: [] };
  16086. for ( let i = 0; i < texDatas.mipmapCount; i ++ ) {
  16087. images[ f ].mipmaps.push( texDatas.mipmaps[ f * texDatas.mipmapCount + i ] );
  16088. images[ f ].format = texDatas.format;
  16089. images[ f ].width = texDatas.width;
  16090. images[ f ].height = texDatas.height;
  16091. }
  16092. }
  16093. texture.image = images;
  16094. } else {
  16095. texture.image.width = texDatas.width;
  16096. texture.image.height = texDatas.height;
  16097. texture.mipmaps = texDatas.mipmaps;
  16098. }
  16099. if ( texDatas.mipmapCount === 1 ) {
  16100. texture.minFilter = LinearFilter;
  16101. }
  16102. texture.format = texDatas.format;
  16103. texture.needsUpdate = true;
  16104. if ( onLoad ) onLoad( texture );
  16105. }, onProgress, onError );
  16106. }
  16107. return texture;
  16108. }
  16109. }
  16110. class ImageLoader extends Loader {
  16111. constructor( manager ) {
  16112. super( manager );
  16113. }
  16114. load( url, onLoad, onProgress, onError ) {
  16115. if ( this.path !== undefined ) url = this.path + url;
  16116. url = this.manager.resolveURL( url );
  16117. const scope = this;
  16118. const cached = Cache.get( url );
  16119. if ( cached !== undefined ) {
  16120. scope.manager.itemStart( url );
  16121. setTimeout( function () {
  16122. if ( onLoad ) onLoad( cached );
  16123. scope.manager.itemEnd( url );
  16124. }, 0 );
  16125. return cached;
  16126. }
  16127. const image = createElementNS( 'img' );
  16128. function onImageLoad() {
  16129. removeEventListeners();
  16130. Cache.add( url, this );
  16131. if ( onLoad ) onLoad( this );
  16132. scope.manager.itemEnd( url );
  16133. }
  16134. function onImageError( event ) {
  16135. removeEventListeners();
  16136. if ( onError ) onError( event );
  16137. scope.manager.itemError( url );
  16138. scope.manager.itemEnd( url );
  16139. }
  16140. function removeEventListeners() {
  16141. image.removeEventListener( 'load', onImageLoad, false );
  16142. image.removeEventListener( 'error', onImageError, false );
  16143. }
  16144. image.addEventListener( 'load', onImageLoad, false );
  16145. image.addEventListener( 'error', onImageError, false );
  16146. if ( url.slice( 0, 5 ) !== 'data:' ) {
  16147. if ( this.crossOrigin !== undefined ) image.crossOrigin = this.crossOrigin;
  16148. }
  16149. scope.manager.itemStart( url );
  16150. image.src = url;
  16151. return image;
  16152. }
  16153. }
  16154. class CubeTextureLoader extends Loader {
  16155. constructor( manager ) {
  16156. super( manager );
  16157. }
  16158. load( urls, onLoad, onProgress, onError ) {
  16159. const texture = new CubeTexture();
  16160. texture.colorSpace = SRGBColorSpace;
  16161. const loader = new ImageLoader( this.manager );
  16162. loader.setCrossOrigin( this.crossOrigin );
  16163. loader.setPath( this.path );
  16164. let loaded = 0;
  16165. function loadTexture( i ) {
  16166. loader.load( urls[ i ], function ( image ) {
  16167. texture.images[ i ] = image;
  16168. loaded ++;
  16169. if ( loaded === 6 ) {
  16170. texture.needsUpdate = true;
  16171. if ( onLoad ) onLoad( texture );
  16172. }
  16173. }, undefined, onError );
  16174. }
  16175. for ( let i = 0; i < urls.length; ++ i ) {
  16176. loadTexture( i );
  16177. }
  16178. return texture;
  16179. }
  16180. }
  16181. /**
  16182. * Abstract Base class to load generic binary textures formats (rgbe, hdr, ...)
  16183. *
  16184. * Sub classes have to implement the parse() method which will be used in load().
  16185. */
  16186. class DataTextureLoader extends Loader {
  16187. constructor( manager ) {
  16188. super( manager );
  16189. }
  16190. load( url, onLoad, onProgress, onError ) {
  16191. const scope = this;
  16192. const texture = new DataTexture();
  16193. const loader = new FileLoader( this.manager );
  16194. loader.setResponseType( 'arraybuffer' );
  16195. loader.setRequestHeader( this.requestHeader );
  16196. loader.setPath( this.path );
  16197. loader.setWithCredentials( scope.withCredentials );
  16198. loader.load( url, function ( buffer ) {
  16199. let texData;
  16200. try {
  16201. texData = scope.parse( buffer );
  16202. } catch ( error ) {
  16203. if ( onError !== undefined ) {
  16204. onError( error );
  16205. } else {
  16206. console.error( error );
  16207. return;
  16208. }
  16209. }
  16210. if ( texData.image !== undefined ) {
  16211. texture.image = texData.image;
  16212. } else if ( texData.data !== undefined ) {
  16213. texture.image.width = texData.width;
  16214. texture.image.height = texData.height;
  16215. texture.image.data = texData.data;
  16216. }
  16217. texture.wrapS = texData.wrapS !== undefined ? texData.wrapS : ClampToEdgeWrapping;
  16218. texture.wrapT = texData.wrapT !== undefined ? texData.wrapT : ClampToEdgeWrapping;
  16219. texture.magFilter = texData.magFilter !== undefined ? texData.magFilter : LinearFilter;
  16220. texture.minFilter = texData.minFilter !== undefined ? texData.minFilter : LinearFilter;
  16221. texture.anisotropy = texData.anisotropy !== undefined ? texData.anisotropy : 1;
  16222. if ( texData.colorSpace !== undefined ) {
  16223. texture.colorSpace = texData.colorSpace;
  16224. }
  16225. if ( texData.flipY !== undefined ) {
  16226. texture.flipY = texData.flipY;
  16227. }
  16228. if ( texData.format !== undefined ) {
  16229. texture.format = texData.format;
  16230. }
  16231. if ( texData.type !== undefined ) {
  16232. texture.type = texData.type;
  16233. }
  16234. if ( texData.mipmaps !== undefined ) {
  16235. texture.mipmaps = texData.mipmaps;
  16236. texture.minFilter = LinearMipmapLinearFilter; // presumably...
  16237. }
  16238. if ( texData.mipmapCount === 1 ) {
  16239. texture.minFilter = LinearFilter;
  16240. }
  16241. if ( texData.generateMipmaps !== undefined ) {
  16242. texture.generateMipmaps = texData.generateMipmaps;
  16243. }
  16244. texture.needsUpdate = true;
  16245. if ( onLoad ) onLoad( texture, texData );
  16246. }, onProgress, onError );
  16247. return texture;
  16248. }
  16249. }
  16250. class TextureLoader extends Loader {
  16251. constructor( manager ) {
  16252. super( manager );
  16253. }
  16254. load( url, onLoad, onProgress, onError ) {
  16255. const texture = new Texture();
  16256. const loader = new ImageLoader( this.manager );
  16257. loader.setCrossOrigin( this.crossOrigin );
  16258. loader.setPath( this.path );
  16259. loader.load( url, function ( image ) {
  16260. texture.image = image;
  16261. texture.needsUpdate = true;
  16262. if ( onLoad !== undefined ) {
  16263. onLoad( texture );
  16264. }
  16265. }, onProgress, onError );
  16266. return texture;
  16267. }
  16268. }
  16269. class Light extends Object3D {
  16270. constructor( color, intensity = 1 ) {
  16271. super();
  16272. this.isLight = true;
  16273. this.type = 'Light';
  16274. this.color = new Color( color );
  16275. this.intensity = intensity;
  16276. }
  16277. dispose() {
  16278. // Empty here in base class; some subclasses override.
  16279. }
  16280. copy( source, recursive ) {
  16281. super.copy( source, recursive );
  16282. this.color.copy( source.color );
  16283. this.intensity = source.intensity;
  16284. return this;
  16285. }
  16286. toJSON( meta ) {
  16287. const data = super.toJSON( meta );
  16288. data.object.color = this.color.getHex();
  16289. data.object.intensity = this.intensity;
  16290. if ( this.groundColor !== undefined ) data.object.groundColor = this.groundColor.getHex();
  16291. if ( this.distance !== undefined ) data.object.distance = this.distance;
  16292. if ( this.angle !== undefined ) data.object.angle = this.angle;
  16293. if ( this.decay !== undefined ) data.object.decay = this.decay;
  16294. if ( this.penumbra !== undefined ) data.object.penumbra = this.penumbra;
  16295. if ( this.shadow !== undefined ) data.object.shadow = this.shadow.toJSON();
  16296. if ( this.target !== undefined ) data.object.target = this.target.uuid;
  16297. return data;
  16298. }
  16299. }
  16300. class HemisphereLight extends Light {
  16301. constructor( skyColor, groundColor, intensity ) {
  16302. super( skyColor, intensity );
  16303. this.isHemisphereLight = true;
  16304. this.type = 'HemisphereLight';
  16305. this.position.copy( Object3D.DEFAULT_UP );
  16306. this.updateMatrix();
  16307. this.groundColor = new Color( groundColor );
  16308. }
  16309. copy( source, recursive ) {
  16310. super.copy( source, recursive );
  16311. this.groundColor.copy( source.groundColor );
  16312. return this;
  16313. }
  16314. }
  16315. const _projScreenMatrix$2 = /*@__PURE__*/ new Matrix4();
  16316. const _lightPositionWorld$1 = /*@__PURE__*/ new Vector3();
  16317. const _lookTarget$1 = /*@__PURE__*/ new Vector3();
  16318. class LightShadow {
  16319. constructor( camera ) {
  16320. this.camera = camera;
  16321. this.intensity = 1;
  16322. this.bias = 0;
  16323. this.normalBias = 0;
  16324. this.radius = 1;
  16325. this.blurSamples = 8;
  16326. this.mapSize = new Vector2( 512, 512 );
  16327. this.map = null;
  16328. this.mapPass = null;
  16329. this.matrix = new Matrix4();
  16330. this.autoUpdate = true;
  16331. this.needsUpdate = false;
  16332. this._frustum = new Frustum();
  16333. this._frameExtents = new Vector2( 1, 1 );
  16334. this._viewportCount = 1;
  16335. this._viewports = [
  16336. new Vector4( 0, 0, 1, 1 )
  16337. ];
  16338. }
  16339. getViewportCount() {
  16340. return this._viewportCount;
  16341. }
  16342. getFrustum() {
  16343. return this._frustum;
  16344. }
  16345. updateMatrices( light ) {
  16346. const shadowCamera = this.camera;
  16347. const shadowMatrix = this.matrix;
  16348. _lightPositionWorld$1.setFromMatrixPosition( light.matrixWorld );
  16349. shadowCamera.position.copy( _lightPositionWorld$1 );
  16350. _lookTarget$1.setFromMatrixPosition( light.target.matrixWorld );
  16351. shadowCamera.lookAt( _lookTarget$1 );
  16352. shadowCamera.updateMatrixWorld();
  16353. _projScreenMatrix$2.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  16354. this._frustum.setFromProjectionMatrix( _projScreenMatrix$2 );
  16355. shadowMatrix.set(
  16356. 0.5, 0.0, 0.0, 0.5,
  16357. 0.0, 0.5, 0.0, 0.5,
  16358. 0.0, 0.0, 0.5, 0.5,
  16359. 0.0, 0.0, 0.0, 1.0
  16360. );
  16361. shadowMatrix.multiply( _projScreenMatrix$2 );
  16362. }
  16363. getViewport( viewportIndex ) {
  16364. return this._viewports[ viewportIndex ];
  16365. }
  16366. getFrameExtents() {
  16367. return this._frameExtents;
  16368. }
  16369. dispose() {
  16370. if ( this.map ) {
  16371. this.map.dispose();
  16372. }
  16373. if ( this.mapPass ) {
  16374. this.mapPass.dispose();
  16375. }
  16376. }
  16377. copy( source ) {
  16378. this.camera = source.camera.clone();
  16379. this.intensity = source.intensity;
  16380. this.bias = source.bias;
  16381. this.radius = source.radius;
  16382. this.mapSize.copy( source.mapSize );
  16383. return this;
  16384. }
  16385. clone() {
  16386. return new this.constructor().copy( this );
  16387. }
  16388. toJSON() {
  16389. const object = {};
  16390. if ( this.intensity !== 1 ) object.intensity = this.intensity;
  16391. if ( this.bias !== 0 ) object.bias = this.bias;
  16392. if ( this.normalBias !== 0 ) object.normalBias = this.normalBias;
  16393. if ( this.radius !== 1 ) object.radius = this.radius;
  16394. if ( this.mapSize.x !== 512 || this.mapSize.y !== 512 ) object.mapSize = this.mapSize.toArray();
  16395. object.camera = this.camera.toJSON( false ).object;
  16396. delete object.camera.matrix;
  16397. return object;
  16398. }
  16399. }
  16400. class SpotLightShadow extends LightShadow {
  16401. constructor() {
  16402. super( new PerspectiveCamera( 50, 1, 0.5, 500 ) );
  16403. this.isSpotLightShadow = true;
  16404. this.focus = 1;
  16405. }
  16406. updateMatrices( light ) {
  16407. const camera = this.camera;
  16408. const fov = RAD2DEG * 2 * light.angle * this.focus;
  16409. const aspect = this.mapSize.width / this.mapSize.height;
  16410. const far = light.distance || camera.far;
  16411. if ( fov !== camera.fov || aspect !== camera.aspect || far !== camera.far ) {
  16412. camera.fov = fov;
  16413. camera.aspect = aspect;
  16414. camera.far = far;
  16415. camera.updateProjectionMatrix();
  16416. }
  16417. super.updateMatrices( light );
  16418. }
  16419. copy( source ) {
  16420. super.copy( source );
  16421. this.focus = source.focus;
  16422. return this;
  16423. }
  16424. }
  16425. class SpotLight extends Light {
  16426. constructor( color, intensity, distance = 0, angle = Math.PI / 3, penumbra = 0, decay = 2 ) {
  16427. super( color, intensity );
  16428. this.isSpotLight = true;
  16429. this.type = 'SpotLight';
  16430. this.position.copy( Object3D.DEFAULT_UP );
  16431. this.updateMatrix();
  16432. this.target = new Object3D();
  16433. this.distance = distance;
  16434. this.angle = angle;
  16435. this.penumbra = penumbra;
  16436. this.decay = decay;
  16437. this.map = null;
  16438. this.shadow = new SpotLightShadow();
  16439. }
  16440. get power() {
  16441. // compute the light's luminous power (in lumens) from its intensity (in candela)
  16442. // by convention for a spotlight, luminous power (lm) = π * luminous intensity (cd)
  16443. return this.intensity * Math.PI;
  16444. }
  16445. set power( power ) {
  16446. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  16447. this.intensity = power / Math.PI;
  16448. }
  16449. dispose() {
  16450. this.shadow.dispose();
  16451. }
  16452. copy( source, recursive ) {
  16453. super.copy( source, recursive );
  16454. this.distance = source.distance;
  16455. this.angle = source.angle;
  16456. this.penumbra = source.penumbra;
  16457. this.decay = source.decay;
  16458. this.target = source.target.clone();
  16459. this.shadow = source.shadow.clone();
  16460. return this;
  16461. }
  16462. }
  16463. const _projScreenMatrix$1 = /*@__PURE__*/ new Matrix4();
  16464. const _lightPositionWorld = /*@__PURE__*/ new Vector3();
  16465. const _lookTarget = /*@__PURE__*/ new Vector3();
  16466. class PointLightShadow extends LightShadow {
  16467. constructor() {
  16468. super( new PerspectiveCamera( 90, 1, 0.5, 500 ) );
  16469. this.isPointLightShadow = true;
  16470. this._frameExtents = new Vector2( 4, 2 );
  16471. this._viewportCount = 6;
  16472. this._viewports = [
  16473. // These viewports map a cube-map onto a 2D texture with the
  16474. // following orientation:
  16475. //
  16476. // xzXZ
  16477. // y Y
  16478. //
  16479. // X - Positive x direction
  16480. // x - Negative x direction
  16481. // Y - Positive y direction
  16482. // y - Negative y direction
  16483. // Z - Positive z direction
  16484. // z - Negative z direction
  16485. // positive X
  16486. new Vector4( 2, 1, 1, 1 ),
  16487. // negative X
  16488. new Vector4( 0, 1, 1, 1 ),
  16489. // positive Z
  16490. new Vector4( 3, 1, 1, 1 ),
  16491. // negative Z
  16492. new Vector4( 1, 1, 1, 1 ),
  16493. // positive Y
  16494. new Vector4( 3, 0, 1, 1 ),
  16495. // negative Y
  16496. new Vector4( 1, 0, 1, 1 )
  16497. ];
  16498. this._cubeDirections = [
  16499. new Vector3( 1, 0, 0 ), new Vector3( - 1, 0, 0 ), new Vector3( 0, 0, 1 ),
  16500. new Vector3( 0, 0, - 1 ), new Vector3( 0, 1, 0 ), new Vector3( 0, - 1, 0 )
  16501. ];
  16502. this._cubeUps = [
  16503. new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ),
  16504. new Vector3( 0, 1, 0 ), new Vector3( 0, 0, 1 ), new Vector3( 0, 0, - 1 )
  16505. ];
  16506. }
  16507. updateMatrices( light, viewportIndex = 0 ) {
  16508. const camera = this.camera;
  16509. const shadowMatrix = this.matrix;
  16510. const far = light.distance || camera.far;
  16511. if ( far !== camera.far ) {
  16512. camera.far = far;
  16513. camera.updateProjectionMatrix();
  16514. }
  16515. _lightPositionWorld.setFromMatrixPosition( light.matrixWorld );
  16516. camera.position.copy( _lightPositionWorld );
  16517. _lookTarget.copy( camera.position );
  16518. _lookTarget.add( this._cubeDirections[ viewportIndex ] );
  16519. camera.up.copy( this._cubeUps[ viewportIndex ] );
  16520. camera.lookAt( _lookTarget );
  16521. camera.updateMatrixWorld();
  16522. shadowMatrix.makeTranslation( - _lightPositionWorld.x, - _lightPositionWorld.y, - _lightPositionWorld.z );
  16523. _projScreenMatrix$1.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  16524. this._frustum.setFromProjectionMatrix( _projScreenMatrix$1 );
  16525. }
  16526. }
  16527. class PointLight extends Light {
  16528. constructor( color, intensity, distance = 0, decay = 2 ) {
  16529. super( color, intensity );
  16530. this.isPointLight = true;
  16531. this.type = 'PointLight';
  16532. this.distance = distance;
  16533. this.decay = decay;
  16534. this.shadow = new PointLightShadow();
  16535. }
  16536. get power() {
  16537. // compute the light's luminous power (in lumens) from its intensity (in candela)
  16538. // for an isotropic light source, luminous power (lm) = 4 π luminous intensity (cd)
  16539. return this.intensity * 4 * Math.PI;
  16540. }
  16541. set power( power ) {
  16542. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  16543. this.intensity = power / ( 4 * Math.PI );
  16544. }
  16545. dispose() {
  16546. this.shadow.dispose();
  16547. }
  16548. copy( source, recursive ) {
  16549. super.copy( source, recursive );
  16550. this.distance = source.distance;
  16551. this.decay = source.decay;
  16552. this.shadow = source.shadow.clone();
  16553. return this;
  16554. }
  16555. }
  16556. class OrthographicCamera extends Camera {
  16557. constructor( left = - 1, right = 1, top = 1, bottom = - 1, near = 0.1, far = 2000 ) {
  16558. super();
  16559. this.isOrthographicCamera = true;
  16560. this.type = 'OrthographicCamera';
  16561. this.zoom = 1;
  16562. this.view = null;
  16563. this.left = left;
  16564. this.right = right;
  16565. this.top = top;
  16566. this.bottom = bottom;
  16567. this.near = near;
  16568. this.far = far;
  16569. this.updateProjectionMatrix();
  16570. }
  16571. copy( source, recursive ) {
  16572. super.copy( source, recursive );
  16573. this.left = source.left;
  16574. this.right = source.right;
  16575. this.top = source.top;
  16576. this.bottom = source.bottom;
  16577. this.near = source.near;
  16578. this.far = source.far;
  16579. this.zoom = source.zoom;
  16580. this.view = source.view === null ? null : Object.assign( {}, source.view );
  16581. return this;
  16582. }
  16583. setViewOffset( fullWidth, fullHeight, x, y, width, height ) {
  16584. if ( this.view === null ) {
  16585. this.view = {
  16586. enabled: true,
  16587. fullWidth: 1,
  16588. fullHeight: 1,
  16589. offsetX: 0,
  16590. offsetY: 0,
  16591. width: 1,
  16592. height: 1
  16593. };
  16594. }
  16595. this.view.enabled = true;
  16596. this.view.fullWidth = fullWidth;
  16597. this.view.fullHeight = fullHeight;
  16598. this.view.offsetX = x;
  16599. this.view.offsetY = y;
  16600. this.view.width = width;
  16601. this.view.height = height;
  16602. this.updateProjectionMatrix();
  16603. }
  16604. clearViewOffset() {
  16605. if ( this.view !== null ) {
  16606. this.view.enabled = false;
  16607. }
  16608. this.updateProjectionMatrix();
  16609. }
  16610. updateProjectionMatrix() {
  16611. const dx = ( this.right - this.left ) / ( 2 * this.zoom );
  16612. const dy = ( this.top - this.bottom ) / ( 2 * this.zoom );
  16613. const cx = ( this.right + this.left ) / 2;
  16614. const cy = ( this.top + this.bottom ) / 2;
  16615. let left = cx - dx;
  16616. let right = cx + dx;
  16617. let top = cy + dy;
  16618. let bottom = cy - dy;
  16619. if ( this.view !== null && this.view.enabled ) {
  16620. const scaleW = ( this.right - this.left ) / this.view.fullWidth / this.zoom;
  16621. const scaleH = ( this.top - this.bottom ) / this.view.fullHeight / this.zoom;
  16622. left += scaleW * this.view.offsetX;
  16623. right = left + scaleW * this.view.width;
  16624. top -= scaleH * this.view.offsetY;
  16625. bottom = top - scaleH * this.view.height;
  16626. }
  16627. this.projectionMatrix.makeOrthographic( left, right, top, bottom, this.near, this.far, this.coordinateSystem );
  16628. this.projectionMatrixInverse.copy( this.projectionMatrix ).invert();
  16629. }
  16630. toJSON( meta ) {
  16631. const data = super.toJSON( meta );
  16632. data.object.zoom = this.zoom;
  16633. data.object.left = this.left;
  16634. data.object.right = this.right;
  16635. data.object.top = this.top;
  16636. data.object.bottom = this.bottom;
  16637. data.object.near = this.near;
  16638. data.object.far = this.far;
  16639. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  16640. return data;
  16641. }
  16642. }
  16643. class DirectionalLightShadow extends LightShadow {
  16644. constructor() {
  16645. super( new OrthographicCamera( - 5, 5, 5, - 5, 0.5, 500 ) );
  16646. this.isDirectionalLightShadow = true;
  16647. }
  16648. }
  16649. class DirectionalLight extends Light {
  16650. constructor( color, intensity ) {
  16651. super( color, intensity );
  16652. this.isDirectionalLight = true;
  16653. this.type = 'DirectionalLight';
  16654. this.position.copy( Object3D.DEFAULT_UP );
  16655. this.updateMatrix();
  16656. this.target = new Object3D();
  16657. this.shadow = new DirectionalLightShadow();
  16658. }
  16659. dispose() {
  16660. this.shadow.dispose();
  16661. }
  16662. copy( source ) {
  16663. super.copy( source );
  16664. this.target = source.target.clone();
  16665. this.shadow = source.shadow.clone();
  16666. return this;
  16667. }
  16668. }
  16669. class AmbientLight extends Light {
  16670. constructor( color, intensity ) {
  16671. super( color, intensity );
  16672. this.isAmbientLight = true;
  16673. this.type = 'AmbientLight';
  16674. }
  16675. }
  16676. class RectAreaLight extends Light {
  16677. constructor( color, intensity, width = 10, height = 10 ) {
  16678. super( color, intensity );
  16679. this.isRectAreaLight = true;
  16680. this.type = 'RectAreaLight';
  16681. this.width = width;
  16682. this.height = height;
  16683. }
  16684. get power() {
  16685. // compute the light's luminous power (in lumens) from its intensity (in nits)
  16686. return this.intensity * this.width * this.height * Math.PI;
  16687. }
  16688. set power( power ) {
  16689. // set the light's intensity (in nits) from the desired luminous power (in lumens)
  16690. this.intensity = power / ( this.width * this.height * Math.PI );
  16691. }
  16692. copy( source ) {
  16693. super.copy( source );
  16694. this.width = source.width;
  16695. this.height = source.height;
  16696. return this;
  16697. }
  16698. toJSON( meta ) {
  16699. const data = super.toJSON( meta );
  16700. data.object.width = this.width;
  16701. data.object.height = this.height;
  16702. return data;
  16703. }
  16704. }
  16705. /**
  16706. * Primary reference:
  16707. * https://graphics.stanford.edu/papers/envmap/envmap.pdf
  16708. *
  16709. * Secondary reference:
  16710. * https://www.ppsloan.org/publications/StupidSH36.pdf
  16711. */
  16712. // 3-band SH defined by 9 coefficients
  16713. class SphericalHarmonics3 {
  16714. constructor() {
  16715. this.isSphericalHarmonics3 = true;
  16716. this.coefficients = [];
  16717. for ( let i = 0; i < 9; i ++ ) {
  16718. this.coefficients.push( new Vector3() );
  16719. }
  16720. }
  16721. set( coefficients ) {
  16722. for ( let i = 0; i < 9; i ++ ) {
  16723. this.coefficients[ i ].copy( coefficients[ i ] );
  16724. }
  16725. return this;
  16726. }
  16727. zero() {
  16728. for ( let i = 0; i < 9; i ++ ) {
  16729. this.coefficients[ i ].set( 0, 0, 0 );
  16730. }
  16731. return this;
  16732. }
  16733. // get the radiance in the direction of the normal
  16734. // target is a Vector3
  16735. getAt( normal, target ) {
  16736. // normal is assumed to be unit length
  16737. const x = normal.x, y = normal.y, z = normal.z;
  16738. const coeff = this.coefficients;
  16739. // band 0
  16740. target.copy( coeff[ 0 ] ).multiplyScalar( 0.282095 );
  16741. // band 1
  16742. target.addScaledVector( coeff[ 1 ], 0.488603 * y );
  16743. target.addScaledVector( coeff[ 2 ], 0.488603 * z );
  16744. target.addScaledVector( coeff[ 3 ], 0.488603 * x );
  16745. // band 2
  16746. target.addScaledVector( coeff[ 4 ], 1.092548 * ( x * y ) );
  16747. target.addScaledVector( coeff[ 5 ], 1.092548 * ( y * z ) );
  16748. target.addScaledVector( coeff[ 6 ], 0.315392 * ( 3.0 * z * z - 1.0 ) );
  16749. target.addScaledVector( coeff[ 7 ], 1.092548 * ( x * z ) );
  16750. target.addScaledVector( coeff[ 8 ], 0.546274 * ( x * x - y * y ) );
  16751. return target;
  16752. }
  16753. // get the irradiance (radiance convolved with cosine lobe) in the direction of the normal
  16754. // target is a Vector3
  16755. // https://graphics.stanford.edu/papers/envmap/envmap.pdf
  16756. getIrradianceAt( normal, target ) {
  16757. // normal is assumed to be unit length
  16758. const x = normal.x, y = normal.y, z = normal.z;
  16759. const coeff = this.coefficients;
  16760. // band 0
  16761. target.copy( coeff[ 0 ] ).multiplyScalar( 0.886227 ); // π * 0.282095
  16762. // band 1
  16763. target.addScaledVector( coeff[ 1 ], 2.0 * 0.511664 * y ); // ( 2 * π / 3 ) * 0.488603
  16764. target.addScaledVector( coeff[ 2 ], 2.0 * 0.511664 * z );
  16765. target.addScaledVector( coeff[ 3 ], 2.0 * 0.511664 * x );
  16766. // band 2
  16767. target.addScaledVector( coeff[ 4 ], 2.0 * 0.429043 * x * y ); // ( π / 4 ) * 1.092548
  16768. target.addScaledVector( coeff[ 5 ], 2.0 * 0.429043 * y * z );
  16769. target.addScaledVector( coeff[ 6 ], 0.743125 * z * z - 0.247708 ); // ( π / 4 ) * 0.315392 * 3
  16770. target.addScaledVector( coeff[ 7 ], 2.0 * 0.429043 * x * z );
  16771. target.addScaledVector( coeff[ 8 ], 0.429043 * ( x * x - y * y ) ); // ( π / 4 ) * 0.546274
  16772. return target;
  16773. }
  16774. add( sh ) {
  16775. for ( let i = 0; i < 9; i ++ ) {
  16776. this.coefficients[ i ].add( sh.coefficients[ i ] );
  16777. }
  16778. return this;
  16779. }
  16780. addScaledSH( sh, s ) {
  16781. for ( let i = 0; i < 9; i ++ ) {
  16782. this.coefficients[ i ].addScaledVector( sh.coefficients[ i ], s );
  16783. }
  16784. return this;
  16785. }
  16786. scale( s ) {
  16787. for ( let i = 0; i < 9; i ++ ) {
  16788. this.coefficients[ i ].multiplyScalar( s );
  16789. }
  16790. return this;
  16791. }
  16792. lerp( sh, alpha ) {
  16793. for ( let i = 0; i < 9; i ++ ) {
  16794. this.coefficients[ i ].lerp( sh.coefficients[ i ], alpha );
  16795. }
  16796. return this;
  16797. }
  16798. equals( sh ) {
  16799. for ( let i = 0; i < 9; i ++ ) {
  16800. if ( ! this.coefficients[ i ].equals( sh.coefficients[ i ] ) ) {
  16801. return false;
  16802. }
  16803. }
  16804. return true;
  16805. }
  16806. copy( sh ) {
  16807. return this.set( sh.coefficients );
  16808. }
  16809. clone() {
  16810. return new this.constructor().copy( this );
  16811. }
  16812. fromArray( array, offset = 0 ) {
  16813. const coefficients = this.coefficients;
  16814. for ( let i = 0; i < 9; i ++ ) {
  16815. coefficients[ i ].fromArray( array, offset + ( i * 3 ) );
  16816. }
  16817. return this;
  16818. }
  16819. toArray( array = [], offset = 0 ) {
  16820. const coefficients = this.coefficients;
  16821. for ( let i = 0; i < 9; i ++ ) {
  16822. coefficients[ i ].toArray( array, offset + ( i * 3 ) );
  16823. }
  16824. return array;
  16825. }
  16826. // evaluate the basis functions
  16827. // shBasis is an Array[ 9 ]
  16828. static getBasisAt( normal, shBasis ) {
  16829. // normal is assumed to be unit length
  16830. const x = normal.x, y = normal.y, z = normal.z;
  16831. // band 0
  16832. shBasis[ 0 ] = 0.282095;
  16833. // band 1
  16834. shBasis[ 1 ] = 0.488603 * y;
  16835. shBasis[ 2 ] = 0.488603 * z;
  16836. shBasis[ 3 ] = 0.488603 * x;
  16837. // band 2
  16838. shBasis[ 4 ] = 1.092548 * x * y;
  16839. shBasis[ 5 ] = 1.092548 * y * z;
  16840. shBasis[ 6 ] = 0.315392 * ( 3 * z * z - 1 );
  16841. shBasis[ 7 ] = 1.092548 * x * z;
  16842. shBasis[ 8 ] = 0.546274 * ( x * x - y * y );
  16843. }
  16844. }
  16845. class LightProbe extends Light {
  16846. constructor( sh = new SphericalHarmonics3(), intensity = 1 ) {
  16847. super( undefined, intensity );
  16848. this.isLightProbe = true;
  16849. this.sh = sh;
  16850. }
  16851. copy( source ) {
  16852. super.copy( source );
  16853. this.sh.copy( source.sh );
  16854. return this;
  16855. }
  16856. fromJSON( json ) {
  16857. this.intensity = json.intensity; // TODO: Move this bit to Light.fromJSON();
  16858. this.sh.fromArray( json.sh );
  16859. return this;
  16860. }
  16861. toJSON( meta ) {
  16862. const data = super.toJSON( meta );
  16863. data.object.sh = this.sh.toArray();
  16864. return data;
  16865. }
  16866. }
  16867. class MaterialLoader extends Loader {
  16868. constructor( manager ) {
  16869. super( manager );
  16870. this.textures = {};
  16871. }
  16872. load( url, onLoad, onProgress, onError ) {
  16873. const scope = this;
  16874. const loader = new FileLoader( scope.manager );
  16875. loader.setPath( scope.path );
  16876. loader.setRequestHeader( scope.requestHeader );
  16877. loader.setWithCredentials( scope.withCredentials );
  16878. loader.load( url, function ( text ) {
  16879. try {
  16880. onLoad( scope.parse( JSON.parse( text ) ) );
  16881. } catch ( e ) {
  16882. if ( onError ) {
  16883. onError( e );
  16884. } else {
  16885. console.error( e );
  16886. }
  16887. scope.manager.itemError( url );
  16888. }
  16889. }, onProgress, onError );
  16890. }
  16891. parse( json ) {
  16892. const textures = this.textures;
  16893. function getTexture( name ) {
  16894. if ( textures[ name ] === undefined ) {
  16895. console.warn( 'THREE.MaterialLoader: Undefined texture', name );
  16896. }
  16897. return textures[ name ];
  16898. }
  16899. const material = this.createMaterialFromType( json.type );
  16900. if ( json.uuid !== undefined ) material.uuid = json.uuid;
  16901. if ( json.name !== undefined ) material.name = json.name;
  16902. if ( json.color !== undefined && material.color !== undefined ) material.color.setHex( json.color );
  16903. if ( json.roughness !== undefined ) material.roughness = json.roughness;
  16904. if ( json.metalness !== undefined ) material.metalness = json.metalness;
  16905. if ( json.sheen !== undefined ) material.sheen = json.sheen;
  16906. if ( json.sheenColor !== undefined ) material.sheenColor = new Color().setHex( json.sheenColor );
  16907. if ( json.sheenRoughness !== undefined ) material.sheenRoughness = json.sheenRoughness;
  16908. if ( json.emissive !== undefined && material.emissive !== undefined ) material.emissive.setHex( json.emissive );
  16909. if ( json.specular !== undefined && material.specular !== undefined ) material.specular.setHex( json.specular );
  16910. if ( json.specularIntensity !== undefined ) material.specularIntensity = json.specularIntensity;
  16911. if ( json.specularColor !== undefined && material.specularColor !== undefined ) material.specularColor.setHex( json.specularColor );
  16912. if ( json.shininess !== undefined ) material.shininess = json.shininess;
  16913. if ( json.clearcoat !== undefined ) material.clearcoat = json.clearcoat;
  16914. if ( json.clearcoatRoughness !== undefined ) material.clearcoatRoughness = json.clearcoatRoughness;
  16915. if ( json.dispersion !== undefined ) material.dispersion = json.dispersion;
  16916. if ( json.iridescence !== undefined ) material.iridescence = json.iridescence;
  16917. if ( json.iridescenceIOR !== undefined ) material.iridescenceIOR = json.iridescenceIOR;
  16918. if ( json.iridescenceThicknessRange !== undefined ) material.iridescenceThicknessRange = json.iridescenceThicknessRange;
  16919. if ( json.transmission !== undefined ) material.transmission = json.transmission;
  16920. if ( json.thickness !== undefined ) material.thickness = json.thickness;
  16921. if ( json.attenuationDistance !== undefined ) material.attenuationDistance = json.attenuationDistance;
  16922. if ( json.attenuationColor !== undefined && material.attenuationColor !== undefined ) material.attenuationColor.setHex( json.attenuationColor );
  16923. if ( json.anisotropy !== undefined ) material.anisotropy = json.anisotropy;
  16924. if ( json.anisotropyRotation !== undefined ) material.anisotropyRotation = json.anisotropyRotation;
  16925. if ( json.fog !== undefined ) material.fog = json.fog;
  16926. if ( json.flatShading !== undefined ) material.flatShading = json.flatShading;
  16927. if ( json.blending !== undefined ) material.blending = json.blending;
  16928. if ( json.combine !== undefined ) material.combine = json.combine;
  16929. if ( json.side !== undefined ) material.side = json.side;
  16930. if ( json.shadowSide !== undefined ) material.shadowSide = json.shadowSide;
  16931. if ( json.opacity !== undefined ) material.opacity = json.opacity;
  16932. if ( json.transparent !== undefined ) material.transparent = json.transparent;
  16933. if ( json.alphaTest !== undefined ) material.alphaTest = json.alphaTest;
  16934. if ( json.alphaHash !== undefined ) material.alphaHash = json.alphaHash;
  16935. if ( json.depthFunc !== undefined ) material.depthFunc = json.depthFunc;
  16936. if ( json.depthTest !== undefined ) material.depthTest = json.depthTest;
  16937. if ( json.depthWrite !== undefined ) material.depthWrite = json.depthWrite;
  16938. if ( json.colorWrite !== undefined ) material.colorWrite = json.colorWrite;
  16939. if ( json.blendSrc !== undefined ) material.blendSrc = json.blendSrc;
  16940. if ( json.blendDst !== undefined ) material.blendDst = json.blendDst;
  16941. if ( json.blendEquation !== undefined ) material.blendEquation = json.blendEquation;
  16942. if ( json.blendSrcAlpha !== undefined ) material.blendSrcAlpha = json.blendSrcAlpha;
  16943. if ( json.blendDstAlpha !== undefined ) material.blendDstAlpha = json.blendDstAlpha;
  16944. if ( json.blendEquationAlpha !== undefined ) material.blendEquationAlpha = json.blendEquationAlpha;
  16945. if ( json.blendColor !== undefined && material.blendColor !== undefined ) material.blendColor.setHex( json.blendColor );
  16946. if ( json.blendAlpha !== undefined ) material.blendAlpha = json.blendAlpha;
  16947. if ( json.stencilWriteMask !== undefined ) material.stencilWriteMask = json.stencilWriteMask;
  16948. if ( json.stencilFunc !== undefined ) material.stencilFunc = json.stencilFunc;
  16949. if ( json.stencilRef !== undefined ) material.stencilRef = json.stencilRef;
  16950. if ( json.stencilFuncMask !== undefined ) material.stencilFuncMask = json.stencilFuncMask;
  16951. if ( json.stencilFail !== undefined ) material.stencilFail = json.stencilFail;
  16952. if ( json.stencilZFail !== undefined ) material.stencilZFail = json.stencilZFail;
  16953. if ( json.stencilZPass !== undefined ) material.stencilZPass = json.stencilZPass;
  16954. if ( json.stencilWrite !== undefined ) material.stencilWrite = json.stencilWrite;
  16955. if ( json.wireframe !== undefined ) material.wireframe = json.wireframe;
  16956. if ( json.wireframeLinewidth !== undefined ) material.wireframeLinewidth = json.wireframeLinewidth;
  16957. if ( json.wireframeLinecap !== undefined ) material.wireframeLinecap = json.wireframeLinecap;
  16958. if ( json.wireframeLinejoin !== undefined ) material.wireframeLinejoin = json.wireframeLinejoin;
  16959. if ( json.rotation !== undefined ) material.rotation = json.rotation;
  16960. if ( json.linewidth !== undefined ) material.linewidth = json.linewidth;
  16961. if ( json.dashSize !== undefined ) material.dashSize = json.dashSize;
  16962. if ( json.gapSize !== undefined ) material.gapSize = json.gapSize;
  16963. if ( json.scale !== undefined ) material.scale = json.scale;
  16964. if ( json.polygonOffset !== undefined ) material.polygonOffset = json.polygonOffset;
  16965. if ( json.polygonOffsetFactor !== undefined ) material.polygonOffsetFactor = json.polygonOffsetFactor;
  16966. if ( json.polygonOffsetUnits !== undefined ) material.polygonOffsetUnits = json.polygonOffsetUnits;
  16967. if ( json.dithering !== undefined ) material.dithering = json.dithering;
  16968. if ( json.alphaToCoverage !== undefined ) material.alphaToCoverage = json.alphaToCoverage;
  16969. if ( json.premultipliedAlpha !== undefined ) material.premultipliedAlpha = json.premultipliedAlpha;
  16970. if ( json.forceSinglePass !== undefined ) material.forceSinglePass = json.forceSinglePass;
  16971. if ( json.visible !== undefined ) material.visible = json.visible;
  16972. if ( json.toneMapped !== undefined ) material.toneMapped = json.toneMapped;
  16973. if ( json.userData !== undefined ) material.userData = json.userData;
  16974. if ( json.vertexColors !== undefined ) {
  16975. if ( typeof json.vertexColors === 'number' ) {
  16976. material.vertexColors = ( json.vertexColors > 0 ) ? true : false;
  16977. } else {
  16978. material.vertexColors = json.vertexColors;
  16979. }
  16980. }
  16981. // Shader Material
  16982. if ( json.uniforms !== undefined ) {
  16983. for ( const name in json.uniforms ) {
  16984. const uniform = json.uniforms[ name ];
  16985. material.uniforms[ name ] = {};
  16986. switch ( uniform.type ) {
  16987. case 't':
  16988. material.uniforms[ name ].value = getTexture( uniform.value );
  16989. break;
  16990. case 'c':
  16991. material.uniforms[ name ].value = new Color().setHex( uniform.value );
  16992. break;
  16993. case 'v2':
  16994. material.uniforms[ name ].value = new Vector2().fromArray( uniform.value );
  16995. break;
  16996. case 'v3':
  16997. material.uniforms[ name ].value = new Vector3().fromArray( uniform.value );
  16998. break;
  16999. case 'v4':
  17000. material.uniforms[ name ].value = new Vector4().fromArray( uniform.value );
  17001. break;
  17002. case 'm3':
  17003. material.uniforms[ name ].value = new Matrix3().fromArray( uniform.value );
  17004. break;
  17005. case 'm4':
  17006. material.uniforms[ name ].value = new Matrix4().fromArray( uniform.value );
  17007. break;
  17008. default:
  17009. material.uniforms[ name ].value = uniform.value;
  17010. }
  17011. }
  17012. }
  17013. if ( json.defines !== undefined ) material.defines = json.defines;
  17014. if ( json.vertexShader !== undefined ) material.vertexShader = json.vertexShader;
  17015. if ( json.fragmentShader !== undefined ) material.fragmentShader = json.fragmentShader;
  17016. if ( json.glslVersion !== undefined ) material.glslVersion = json.glslVersion;
  17017. if ( json.extensions !== undefined ) {
  17018. for ( const key in json.extensions ) {
  17019. material.extensions[ key ] = json.extensions[ key ];
  17020. }
  17021. }
  17022. if ( json.lights !== undefined ) material.lights = json.lights;
  17023. if ( json.clipping !== undefined ) material.clipping = json.clipping;
  17024. // for PointsMaterial
  17025. if ( json.size !== undefined ) material.size = json.size;
  17026. if ( json.sizeAttenuation !== undefined ) material.sizeAttenuation = json.sizeAttenuation;
  17027. // maps
  17028. if ( json.map !== undefined ) material.map = getTexture( json.map );
  17029. if ( json.matcap !== undefined ) material.matcap = getTexture( json.matcap );
  17030. if ( json.alphaMap !== undefined ) material.alphaMap = getTexture( json.alphaMap );
  17031. if ( json.bumpMap !== undefined ) material.bumpMap = getTexture( json.bumpMap );
  17032. if ( json.bumpScale !== undefined ) material.bumpScale = json.bumpScale;
  17033. if ( json.normalMap !== undefined ) material.normalMap = getTexture( json.normalMap );
  17034. if ( json.normalMapType !== undefined ) material.normalMapType = json.normalMapType;
  17035. if ( json.normalScale !== undefined ) {
  17036. let normalScale = json.normalScale;
  17037. if ( Array.isArray( normalScale ) === false ) {
  17038. // Blender exporter used to export a scalar. See #7459
  17039. normalScale = [ normalScale, normalScale ];
  17040. }
  17041. material.normalScale = new Vector2().fromArray( normalScale );
  17042. }
  17043. if ( json.displacementMap !== undefined ) material.displacementMap = getTexture( json.displacementMap );
  17044. if ( json.displacementScale !== undefined ) material.displacementScale = json.displacementScale;
  17045. if ( json.displacementBias !== undefined ) material.displacementBias = json.displacementBias;
  17046. if ( json.roughnessMap !== undefined ) material.roughnessMap = getTexture( json.roughnessMap );
  17047. if ( json.metalnessMap !== undefined ) material.metalnessMap = getTexture( json.metalnessMap );
  17048. if ( json.emissiveMap !== undefined ) material.emissiveMap = getTexture( json.emissiveMap );
  17049. if ( json.emissiveIntensity !== undefined ) material.emissiveIntensity = json.emissiveIntensity;
  17050. if ( json.specularMap !== undefined ) material.specularMap = getTexture( json.specularMap );
  17051. if ( json.specularIntensityMap !== undefined ) material.specularIntensityMap = getTexture( json.specularIntensityMap );
  17052. if ( json.specularColorMap !== undefined ) material.specularColorMap = getTexture( json.specularColorMap );
  17053. if ( json.envMap !== undefined ) material.envMap = getTexture( json.envMap );
  17054. if ( json.envMapRotation !== undefined ) material.envMapRotation.fromArray( json.envMapRotation );
  17055. if ( json.envMapIntensity !== undefined ) material.envMapIntensity = json.envMapIntensity;
  17056. if ( json.reflectivity !== undefined ) material.reflectivity = json.reflectivity;
  17057. if ( json.refractionRatio !== undefined ) material.refractionRatio = json.refractionRatio;
  17058. if ( json.lightMap !== undefined ) material.lightMap = getTexture( json.lightMap );
  17059. if ( json.lightMapIntensity !== undefined ) material.lightMapIntensity = json.lightMapIntensity;
  17060. if ( json.aoMap !== undefined ) material.aoMap = getTexture( json.aoMap );
  17061. if ( json.aoMapIntensity !== undefined ) material.aoMapIntensity = json.aoMapIntensity;
  17062. if ( json.gradientMap !== undefined ) material.gradientMap = getTexture( json.gradientMap );
  17063. if ( json.clearcoatMap !== undefined ) material.clearcoatMap = getTexture( json.clearcoatMap );
  17064. if ( json.clearcoatRoughnessMap !== undefined ) material.clearcoatRoughnessMap = getTexture( json.clearcoatRoughnessMap );
  17065. if ( json.clearcoatNormalMap !== undefined ) material.clearcoatNormalMap = getTexture( json.clearcoatNormalMap );
  17066. if ( json.clearcoatNormalScale !== undefined ) material.clearcoatNormalScale = new Vector2().fromArray( json.clearcoatNormalScale );
  17067. if ( json.iridescenceMap !== undefined ) material.iridescenceMap = getTexture( json.iridescenceMap );
  17068. if ( json.iridescenceThicknessMap !== undefined ) material.iridescenceThicknessMap = getTexture( json.iridescenceThicknessMap );
  17069. if ( json.transmissionMap !== undefined ) material.transmissionMap = getTexture( json.transmissionMap );
  17070. if ( json.thicknessMap !== undefined ) material.thicknessMap = getTexture( json.thicknessMap );
  17071. if ( json.anisotropyMap !== undefined ) material.anisotropyMap = getTexture( json.anisotropyMap );
  17072. if ( json.sheenColorMap !== undefined ) material.sheenColorMap = getTexture( json.sheenColorMap );
  17073. if ( json.sheenRoughnessMap !== undefined ) material.sheenRoughnessMap = getTexture( json.sheenRoughnessMap );
  17074. return material;
  17075. }
  17076. setTextures( value ) {
  17077. this.textures = value;
  17078. return this;
  17079. }
  17080. createMaterialFromType( type ) {
  17081. return MaterialLoader.createMaterialFromType( type );
  17082. }
  17083. static createMaterialFromType( type ) {
  17084. const materialLib = {
  17085. ShadowMaterial,
  17086. SpriteMaterial,
  17087. RawShaderMaterial,
  17088. ShaderMaterial,
  17089. PointsMaterial,
  17090. MeshPhysicalMaterial,
  17091. MeshStandardMaterial,
  17092. MeshPhongMaterial,
  17093. MeshToonMaterial,
  17094. MeshNormalMaterial,
  17095. MeshLambertMaterial,
  17096. MeshDepthMaterial,
  17097. MeshDistanceMaterial,
  17098. MeshBasicMaterial,
  17099. MeshMatcapMaterial,
  17100. LineDashedMaterial,
  17101. LineBasicMaterial,
  17102. Material
  17103. };
  17104. return new materialLib[ type ]();
  17105. }
  17106. }
  17107. class LoaderUtils {
  17108. static decodeText( array ) { // @deprecated, r165
  17109. console.warn( 'THREE.LoaderUtils: decodeText() has been deprecated with r165 and will be removed with r175. Use TextDecoder instead.' );
  17110. if ( typeof TextDecoder !== 'undefined' ) {
  17111. return new TextDecoder().decode( array );
  17112. }
  17113. // Avoid the String.fromCharCode.apply(null, array) shortcut, which
  17114. // throws a "maximum call stack size exceeded" error for large arrays.
  17115. let s = '';
  17116. for ( let i = 0, il = array.length; i < il; i ++ ) {
  17117. // Implicitly assumes little-endian.
  17118. s += String.fromCharCode( array[ i ] );
  17119. }
  17120. try {
  17121. // merges multi-byte utf-8 characters.
  17122. return decodeURIComponent( escape( s ) );
  17123. } catch ( e ) { // see #16358
  17124. return s;
  17125. }
  17126. }
  17127. static extractUrlBase( url ) {
  17128. const index = url.lastIndexOf( '/' );
  17129. if ( index === - 1 ) return './';
  17130. return url.slice( 0, index + 1 );
  17131. }
  17132. static resolveURL( url, path ) {
  17133. // Invalid URL
  17134. if ( typeof url !== 'string' || url === '' ) return '';
  17135. // Host Relative URL
  17136. if ( /^https?:\/\//i.test( path ) && /^\//.test( url ) ) {
  17137. path = path.replace( /(^https?:\/\/[^\/]+).*/i, '$1' );
  17138. }
  17139. // Absolute URL http://,https://,//
  17140. if ( /^(https?:)?\/\//i.test( url ) ) return url;
  17141. // Data URI
  17142. if ( /^data:.*,.*$/i.test( url ) ) return url;
  17143. // Blob URL
  17144. if ( /^blob:.*$/i.test( url ) ) return url;
  17145. // Relative URL
  17146. return path + url;
  17147. }
  17148. }
  17149. class InstancedBufferGeometry extends BufferGeometry {
  17150. constructor() {
  17151. super();
  17152. this.isInstancedBufferGeometry = true;
  17153. this.type = 'InstancedBufferGeometry';
  17154. this.instanceCount = Infinity;
  17155. }
  17156. copy( source ) {
  17157. super.copy( source );
  17158. this.instanceCount = source.instanceCount;
  17159. return this;
  17160. }
  17161. toJSON() {
  17162. const data = super.toJSON();
  17163. data.instanceCount = this.instanceCount;
  17164. data.isInstancedBufferGeometry = true;
  17165. return data;
  17166. }
  17167. }
  17168. class BufferGeometryLoader extends Loader {
  17169. constructor( manager ) {
  17170. super( manager );
  17171. }
  17172. load( url, onLoad, onProgress, onError ) {
  17173. const scope = this;
  17174. const loader = new FileLoader( scope.manager );
  17175. loader.setPath( scope.path );
  17176. loader.setRequestHeader( scope.requestHeader );
  17177. loader.setWithCredentials( scope.withCredentials );
  17178. loader.load( url, function ( text ) {
  17179. try {
  17180. onLoad( scope.parse( JSON.parse( text ) ) );
  17181. } catch ( e ) {
  17182. if ( onError ) {
  17183. onError( e );
  17184. } else {
  17185. console.error( e );
  17186. }
  17187. scope.manager.itemError( url );
  17188. }
  17189. }, onProgress, onError );
  17190. }
  17191. parse( json ) {
  17192. const interleavedBufferMap = {};
  17193. const arrayBufferMap = {};
  17194. function getInterleavedBuffer( json, uuid ) {
  17195. if ( interleavedBufferMap[ uuid ] !== undefined ) return interleavedBufferMap[ uuid ];
  17196. const interleavedBuffers = json.interleavedBuffers;
  17197. const interleavedBuffer = interleavedBuffers[ uuid ];
  17198. const buffer = getArrayBuffer( json, interleavedBuffer.buffer );
  17199. const array = getTypedArray( interleavedBuffer.type, buffer );
  17200. const ib = new InterleavedBuffer( array, interleavedBuffer.stride );
  17201. ib.uuid = interleavedBuffer.uuid;
  17202. interleavedBufferMap[ uuid ] = ib;
  17203. return ib;
  17204. }
  17205. function getArrayBuffer( json, uuid ) {
  17206. if ( arrayBufferMap[ uuid ] !== undefined ) return arrayBufferMap[ uuid ];
  17207. const arrayBuffers = json.arrayBuffers;
  17208. const arrayBuffer = arrayBuffers[ uuid ];
  17209. const ab = new Uint32Array( arrayBuffer ).buffer;
  17210. arrayBufferMap[ uuid ] = ab;
  17211. return ab;
  17212. }
  17213. const geometry = json.isInstancedBufferGeometry ? new InstancedBufferGeometry() : new BufferGeometry();
  17214. const index = json.data.index;
  17215. if ( index !== undefined ) {
  17216. const typedArray = getTypedArray( index.type, index.array );
  17217. geometry.setIndex( new BufferAttribute( typedArray, 1 ) );
  17218. }
  17219. const attributes = json.data.attributes;
  17220. for ( const key in attributes ) {
  17221. const attribute = attributes[ key ];
  17222. let bufferAttribute;
  17223. if ( attribute.isInterleavedBufferAttribute ) {
  17224. const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data );
  17225. bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized );
  17226. } else {
  17227. const typedArray = getTypedArray( attribute.type, attribute.array );
  17228. const bufferAttributeConstr = attribute.isInstancedBufferAttribute ? InstancedBufferAttribute : BufferAttribute;
  17229. bufferAttribute = new bufferAttributeConstr( typedArray, attribute.itemSize, attribute.normalized );
  17230. }
  17231. if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name;
  17232. if ( attribute.usage !== undefined ) bufferAttribute.setUsage( attribute.usage );
  17233. geometry.setAttribute( key, bufferAttribute );
  17234. }
  17235. const morphAttributes = json.data.morphAttributes;
  17236. if ( morphAttributes ) {
  17237. for ( const key in morphAttributes ) {
  17238. const attributeArray = morphAttributes[ key ];
  17239. const array = [];
  17240. for ( let i = 0, il = attributeArray.length; i < il; i ++ ) {
  17241. const attribute = attributeArray[ i ];
  17242. let bufferAttribute;
  17243. if ( attribute.isInterleavedBufferAttribute ) {
  17244. const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data );
  17245. bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized );
  17246. } else {
  17247. const typedArray = getTypedArray( attribute.type, attribute.array );
  17248. bufferAttribute = new BufferAttribute( typedArray, attribute.itemSize, attribute.normalized );
  17249. }
  17250. if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name;
  17251. array.push( bufferAttribute );
  17252. }
  17253. geometry.morphAttributes[ key ] = array;
  17254. }
  17255. }
  17256. const morphTargetsRelative = json.data.morphTargetsRelative;
  17257. if ( morphTargetsRelative ) {
  17258. geometry.morphTargetsRelative = true;
  17259. }
  17260. const groups = json.data.groups || json.data.drawcalls || json.data.offsets;
  17261. if ( groups !== undefined ) {
  17262. for ( let i = 0, n = groups.length; i !== n; ++ i ) {
  17263. const group = groups[ i ];
  17264. geometry.addGroup( group.start, group.count, group.materialIndex );
  17265. }
  17266. }
  17267. const boundingSphere = json.data.boundingSphere;
  17268. if ( boundingSphere !== undefined ) {
  17269. const center = new Vector3();
  17270. if ( boundingSphere.center !== undefined ) {
  17271. center.fromArray( boundingSphere.center );
  17272. }
  17273. geometry.boundingSphere = new Sphere( center, boundingSphere.radius );
  17274. }
  17275. if ( json.name ) geometry.name = json.name;
  17276. if ( json.userData ) geometry.userData = json.userData;
  17277. return geometry;
  17278. }
  17279. }
  17280. class ObjectLoader extends Loader {
  17281. constructor( manager ) {
  17282. super( manager );
  17283. }
  17284. load( url, onLoad, onProgress, onError ) {
  17285. const scope = this;
  17286. const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  17287. this.resourcePath = this.resourcePath || path;
  17288. const loader = new FileLoader( this.manager );
  17289. loader.setPath( this.path );
  17290. loader.setRequestHeader( this.requestHeader );
  17291. loader.setWithCredentials( this.withCredentials );
  17292. loader.load( url, function ( text ) {
  17293. let json = null;
  17294. try {
  17295. json = JSON.parse( text );
  17296. } catch ( error ) {
  17297. if ( onError !== undefined ) onError( error );
  17298. console.error( 'THREE:ObjectLoader: Can\'t parse ' + url + '.', error.message );
  17299. return;
  17300. }
  17301. const metadata = json.metadata;
  17302. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  17303. if ( onError !== undefined ) onError( new Error( 'THREE.ObjectLoader: Can\'t load ' + url ) );
  17304. console.error( 'THREE.ObjectLoader: Can\'t load ' + url );
  17305. return;
  17306. }
  17307. scope.parse( json, onLoad );
  17308. }, onProgress, onError );
  17309. }
  17310. async loadAsync( url, onProgress ) {
  17311. const scope = this;
  17312. const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  17313. this.resourcePath = this.resourcePath || path;
  17314. const loader = new FileLoader( this.manager );
  17315. loader.setPath( this.path );
  17316. loader.setRequestHeader( this.requestHeader );
  17317. loader.setWithCredentials( this.withCredentials );
  17318. const text = await loader.loadAsync( url, onProgress );
  17319. const json = JSON.parse( text );
  17320. const metadata = json.metadata;
  17321. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  17322. throw new Error( 'THREE.ObjectLoader: Can\'t load ' + url );
  17323. }
  17324. return await scope.parseAsync( json );
  17325. }
  17326. parse( json, onLoad ) {
  17327. const animations = this.parseAnimations( json.animations );
  17328. const shapes = this.parseShapes( json.shapes );
  17329. const geometries = this.parseGeometries( json.geometries, shapes );
  17330. const images = this.parseImages( json.images, function () {
  17331. if ( onLoad !== undefined ) onLoad( object );
  17332. } );
  17333. const textures = this.parseTextures( json.textures, images );
  17334. const materials = this.parseMaterials( json.materials, textures );
  17335. const object = this.parseObject( json.object, geometries, materials, textures, animations );
  17336. const skeletons = this.parseSkeletons( json.skeletons, object );
  17337. this.bindSkeletons( object, skeletons );
  17338. this.bindLightTargets( object );
  17339. //
  17340. if ( onLoad !== undefined ) {
  17341. let hasImages = false;
  17342. for ( const uuid in images ) {
  17343. if ( images[ uuid ].data instanceof HTMLImageElement ) {
  17344. hasImages = true;
  17345. break;
  17346. }
  17347. }
  17348. if ( hasImages === false ) onLoad( object );
  17349. }
  17350. return object;
  17351. }
  17352. async parseAsync( json ) {
  17353. const animations = this.parseAnimations( json.animations );
  17354. const shapes = this.parseShapes( json.shapes );
  17355. const geometries = this.parseGeometries( json.geometries, shapes );
  17356. const images = await this.parseImagesAsync( json.images );
  17357. const textures = this.parseTextures( json.textures, images );
  17358. const materials = this.parseMaterials( json.materials, textures );
  17359. const object = this.parseObject( json.object, geometries, materials, textures, animations );
  17360. const skeletons = this.parseSkeletons( json.skeletons, object );
  17361. this.bindSkeletons( object, skeletons );
  17362. this.bindLightTargets( object );
  17363. return object;
  17364. }
  17365. parseShapes( json ) {
  17366. const shapes = {};
  17367. if ( json !== undefined ) {
  17368. for ( let i = 0, l = json.length; i < l; i ++ ) {
  17369. const shape = new Shape().fromJSON( json[ i ] );
  17370. shapes[ shape.uuid ] = shape;
  17371. }
  17372. }
  17373. return shapes;
  17374. }
  17375. parseSkeletons( json, object ) {
  17376. const skeletons = {};
  17377. const bones = {};
  17378. // generate bone lookup table
  17379. object.traverse( function ( child ) {
  17380. if ( child.isBone ) bones[ child.uuid ] = child;
  17381. } );
  17382. // create skeletons
  17383. if ( json !== undefined ) {
  17384. for ( let i = 0, l = json.length; i < l; i ++ ) {
  17385. const skeleton = new Skeleton().fromJSON( json[ i ], bones );
  17386. skeletons[ skeleton.uuid ] = skeleton;
  17387. }
  17388. }
  17389. return skeletons;
  17390. }
  17391. parseGeometries( json, shapes ) {
  17392. const geometries = {};
  17393. if ( json !== undefined ) {
  17394. const bufferGeometryLoader = new BufferGeometryLoader();
  17395. for ( let i = 0, l = json.length; i < l; i ++ ) {
  17396. let geometry;
  17397. const data = json[ i ];
  17398. switch ( data.type ) {
  17399. case 'BufferGeometry':
  17400. case 'InstancedBufferGeometry':
  17401. geometry = bufferGeometryLoader.parse( data );
  17402. break;
  17403. default:
  17404. if ( data.type in Geometries$1 ) {
  17405. geometry = Geometries$1[ data.type ].fromJSON( data, shapes );
  17406. } else {
  17407. console.warn( `THREE.ObjectLoader: Unsupported geometry type "${ data.type }"` );
  17408. }
  17409. }
  17410. geometry.uuid = data.uuid;
  17411. if ( data.name !== undefined ) geometry.name = data.name;
  17412. if ( data.userData !== undefined ) geometry.userData = data.userData;
  17413. geometries[ data.uuid ] = geometry;
  17414. }
  17415. }
  17416. return geometries;
  17417. }
  17418. parseMaterials( json, textures ) {
  17419. const cache = {}; // MultiMaterial
  17420. const materials = {};
  17421. if ( json !== undefined ) {
  17422. const loader = new MaterialLoader();
  17423. loader.setTextures( textures );
  17424. for ( let i = 0, l = json.length; i < l; i ++ ) {
  17425. const data = json[ i ];
  17426. if ( cache[ data.uuid ] === undefined ) {
  17427. cache[ data.uuid ] = loader.parse( data );
  17428. }
  17429. materials[ data.uuid ] = cache[ data.uuid ];
  17430. }
  17431. }
  17432. return materials;
  17433. }
  17434. parseAnimations( json ) {
  17435. const animations = {};
  17436. if ( json !== undefined ) {
  17437. for ( let i = 0; i < json.length; i ++ ) {
  17438. const data = json[ i ];
  17439. const clip = AnimationClip.parse( data );
  17440. animations[ clip.uuid ] = clip;
  17441. }
  17442. }
  17443. return animations;
  17444. }
  17445. parseImages( json, onLoad ) {
  17446. const scope = this;
  17447. const images = {};
  17448. let loader;
  17449. function loadImage( url ) {
  17450. scope.manager.itemStart( url );
  17451. return loader.load( url, function () {
  17452. scope.manager.itemEnd( url );
  17453. }, undefined, function () {
  17454. scope.manager.itemError( url );
  17455. scope.manager.itemEnd( url );
  17456. } );
  17457. }
  17458. function deserializeImage( image ) {
  17459. if ( typeof image === 'string' ) {
  17460. const url = image;
  17461. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url;
  17462. return loadImage( path );
  17463. } else {
  17464. if ( image.data ) {
  17465. return {
  17466. data: getTypedArray( image.type, image.data ),
  17467. width: image.width,
  17468. height: image.height
  17469. };
  17470. } else {
  17471. return null;
  17472. }
  17473. }
  17474. }
  17475. if ( json !== undefined && json.length > 0 ) {
  17476. const manager = new LoadingManager( onLoad );
  17477. loader = new ImageLoader( manager );
  17478. loader.setCrossOrigin( this.crossOrigin );
  17479. for ( let i = 0, il = json.length; i < il; i ++ ) {
  17480. const image = json[ i ];
  17481. const url = image.url;
  17482. if ( Array.isArray( url ) ) {
  17483. // load array of images e.g CubeTexture
  17484. const imageArray = [];
  17485. for ( let j = 0, jl = url.length; j < jl; j ++ ) {
  17486. const currentUrl = url[ j ];
  17487. const deserializedImage = deserializeImage( currentUrl );
  17488. if ( deserializedImage !== null ) {
  17489. if ( deserializedImage instanceof HTMLImageElement ) {
  17490. imageArray.push( deserializedImage );
  17491. } else {
  17492. // special case: handle array of data textures for cube textures
  17493. imageArray.push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) );
  17494. }
  17495. }
  17496. }
  17497. images[ image.uuid ] = new Source( imageArray );
  17498. } else {
  17499. // load single image
  17500. const deserializedImage = deserializeImage( image.url );
  17501. images[ image.uuid ] = new Source( deserializedImage );
  17502. }
  17503. }
  17504. }
  17505. return images;
  17506. }
  17507. async parseImagesAsync( json ) {
  17508. const scope = this;
  17509. const images = {};
  17510. let loader;
  17511. async function deserializeImage( image ) {
  17512. if ( typeof image === 'string' ) {
  17513. const url = image;
  17514. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url;
  17515. return await loader.loadAsync( path );
  17516. } else {
  17517. if ( image.data ) {
  17518. return {
  17519. data: getTypedArray( image.type, image.data ),
  17520. width: image.width,
  17521. height: image.height
  17522. };
  17523. } else {
  17524. return null;
  17525. }
  17526. }
  17527. }
  17528. if ( json !== undefined && json.length > 0 ) {
  17529. loader = new ImageLoader( this.manager );
  17530. loader.setCrossOrigin( this.crossOrigin );
  17531. for ( let i = 0, il = json.length; i < il; i ++ ) {
  17532. const image = json[ i ];
  17533. const url = image.url;
  17534. if ( Array.isArray( url ) ) {
  17535. // load array of images e.g CubeTexture
  17536. const imageArray = [];
  17537. for ( let j = 0, jl = url.length; j < jl; j ++ ) {
  17538. const currentUrl = url[ j ];
  17539. const deserializedImage = await deserializeImage( currentUrl );
  17540. if ( deserializedImage !== null ) {
  17541. if ( deserializedImage instanceof HTMLImageElement ) {
  17542. imageArray.push( deserializedImage );
  17543. } else {
  17544. // special case: handle array of data textures for cube textures
  17545. imageArray.push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) );
  17546. }
  17547. }
  17548. }
  17549. images[ image.uuid ] = new Source( imageArray );
  17550. } else {
  17551. // load single image
  17552. const deserializedImage = await deserializeImage( image.url );
  17553. images[ image.uuid ] = new Source( deserializedImage );
  17554. }
  17555. }
  17556. }
  17557. return images;
  17558. }
  17559. parseTextures( json, images ) {
  17560. function parseConstant( value, type ) {
  17561. if ( typeof value === 'number' ) return value;
  17562. console.warn( 'THREE.ObjectLoader.parseTexture: Constant should be in numeric form.', value );
  17563. return type[ value ];
  17564. }
  17565. const textures = {};
  17566. if ( json !== undefined ) {
  17567. for ( let i = 0, l = json.length; i < l; i ++ ) {
  17568. const data = json[ i ];
  17569. if ( data.image === undefined ) {
  17570. console.warn( 'THREE.ObjectLoader: No "image" specified for', data.uuid );
  17571. }
  17572. if ( images[ data.image ] === undefined ) {
  17573. console.warn( 'THREE.ObjectLoader: Undefined image', data.image );
  17574. }
  17575. const source = images[ data.image ];
  17576. const image = source.data;
  17577. let texture;
  17578. if ( Array.isArray( image ) ) {
  17579. texture = new CubeTexture();
  17580. if ( image.length === 6 ) texture.needsUpdate = true;
  17581. } else {
  17582. if ( image && image.data ) {
  17583. texture = new DataTexture();
  17584. } else {
  17585. texture = new Texture();
  17586. }
  17587. if ( image ) texture.needsUpdate = true; // textures can have undefined image data
  17588. }
  17589. texture.source = source;
  17590. texture.uuid = data.uuid;
  17591. if ( data.name !== undefined ) texture.name = data.name;
  17592. if ( data.mapping !== undefined ) texture.mapping = parseConstant( data.mapping, TEXTURE_MAPPING );
  17593. if ( data.channel !== undefined ) texture.channel = data.channel;
  17594. if ( data.offset !== undefined ) texture.offset.fromArray( data.offset );
  17595. if ( data.repeat !== undefined ) texture.repeat.fromArray( data.repeat );
  17596. if ( data.center !== undefined ) texture.center.fromArray( data.center );
  17597. if ( data.rotation !== undefined ) texture.rotation = data.rotation;
  17598. if ( data.wrap !== undefined ) {
  17599. texture.wrapS = parseConstant( data.wrap[ 0 ], TEXTURE_WRAPPING );
  17600. texture.wrapT = parseConstant( data.wrap[ 1 ], TEXTURE_WRAPPING );
  17601. }
  17602. if ( data.format !== undefined ) texture.format = data.format;
  17603. if ( data.internalFormat !== undefined ) texture.internalFormat = data.internalFormat;
  17604. if ( data.type !== undefined ) texture.type = data.type;
  17605. if ( data.colorSpace !== undefined ) texture.colorSpace = data.colorSpace;
  17606. if ( data.minFilter !== undefined ) texture.minFilter = parseConstant( data.minFilter, TEXTURE_FILTER );
  17607. if ( data.magFilter !== undefined ) texture.magFilter = parseConstant( data.magFilter, TEXTURE_FILTER );
  17608. if ( data.anisotropy !== undefined ) texture.anisotropy = data.anisotropy;
  17609. if ( data.flipY !== undefined ) texture.flipY = data.flipY;
  17610. if ( data.generateMipmaps !== undefined ) texture.generateMipmaps = data.generateMipmaps;
  17611. if ( data.premultiplyAlpha !== undefined ) texture.premultiplyAlpha = data.premultiplyAlpha;
  17612. if ( data.unpackAlignment !== undefined ) texture.unpackAlignment = data.unpackAlignment;
  17613. if ( data.compareFunction !== undefined ) texture.compareFunction = data.compareFunction;
  17614. if ( data.userData !== undefined ) texture.userData = data.userData;
  17615. textures[ data.uuid ] = texture;
  17616. }
  17617. }
  17618. return textures;
  17619. }
  17620. parseObject( data, geometries, materials, textures, animations ) {
  17621. let object;
  17622. function getGeometry( name ) {
  17623. if ( geometries[ name ] === undefined ) {
  17624. console.warn( 'THREE.ObjectLoader: Undefined geometry', name );
  17625. }
  17626. return geometries[ name ];
  17627. }
  17628. function getMaterial( name ) {
  17629. if ( name === undefined ) return undefined;
  17630. if ( Array.isArray( name ) ) {
  17631. const array = [];
  17632. for ( let i = 0, l = name.length; i < l; i ++ ) {
  17633. const uuid = name[ i ];
  17634. if ( materials[ uuid ] === undefined ) {
  17635. console.warn( 'THREE.ObjectLoader: Undefined material', uuid );
  17636. }
  17637. array.push( materials[ uuid ] );
  17638. }
  17639. return array;
  17640. }
  17641. if ( materials[ name ] === undefined ) {
  17642. console.warn( 'THREE.ObjectLoader: Undefined material', name );
  17643. }
  17644. return materials[ name ];
  17645. }
  17646. function getTexture( uuid ) {
  17647. if ( textures[ uuid ] === undefined ) {
  17648. console.warn( 'THREE.ObjectLoader: Undefined texture', uuid );
  17649. }
  17650. return textures[ uuid ];
  17651. }
  17652. let geometry, material;
  17653. switch ( data.type ) {
  17654. case 'Scene':
  17655. object = new Scene();
  17656. if ( data.background !== undefined ) {
  17657. if ( Number.isInteger( data.background ) ) {
  17658. object.background = new Color( data.background );
  17659. } else {
  17660. object.background = getTexture( data.background );
  17661. }
  17662. }
  17663. if ( data.environment !== undefined ) {
  17664. object.environment = getTexture( data.environment );
  17665. }
  17666. if ( data.fog !== undefined ) {
  17667. if ( data.fog.type === 'Fog' ) {
  17668. object.fog = new Fog( data.fog.color, data.fog.near, data.fog.far );
  17669. } else if ( data.fog.type === 'FogExp2' ) {
  17670. object.fog = new FogExp2( data.fog.color, data.fog.density );
  17671. }
  17672. if ( data.fog.name !== '' ) {
  17673. object.fog.name = data.fog.name;
  17674. }
  17675. }
  17676. if ( data.backgroundBlurriness !== undefined ) object.backgroundBlurriness = data.backgroundBlurriness;
  17677. if ( data.backgroundIntensity !== undefined ) object.backgroundIntensity = data.backgroundIntensity;
  17678. if ( data.backgroundRotation !== undefined ) object.backgroundRotation.fromArray( data.backgroundRotation );
  17679. if ( data.environmentIntensity !== undefined ) object.environmentIntensity = data.environmentIntensity;
  17680. if ( data.environmentRotation !== undefined ) object.environmentRotation.fromArray( data.environmentRotation );
  17681. break;
  17682. case 'PerspectiveCamera':
  17683. object = new PerspectiveCamera( data.fov, data.aspect, data.near, data.far );
  17684. if ( data.focus !== undefined ) object.focus = data.focus;
  17685. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  17686. if ( data.filmGauge !== undefined ) object.filmGauge = data.filmGauge;
  17687. if ( data.filmOffset !== undefined ) object.filmOffset = data.filmOffset;
  17688. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  17689. break;
  17690. case 'OrthographicCamera':
  17691. object = new OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far );
  17692. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  17693. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  17694. break;
  17695. case 'AmbientLight':
  17696. object = new AmbientLight( data.color, data.intensity );
  17697. break;
  17698. case 'DirectionalLight':
  17699. object = new DirectionalLight( data.color, data.intensity );
  17700. object.target = data.target || '';
  17701. break;
  17702. case 'PointLight':
  17703. object = new PointLight( data.color, data.intensity, data.distance, data.decay );
  17704. break;
  17705. case 'RectAreaLight':
  17706. object = new RectAreaLight( data.color, data.intensity, data.width, data.height );
  17707. break;
  17708. case 'SpotLight':
  17709. object = new SpotLight( data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay );
  17710. object.target = data.target || '';
  17711. break;
  17712. case 'HemisphereLight':
  17713. object = new HemisphereLight( data.color, data.groundColor, data.intensity );
  17714. break;
  17715. case 'LightProbe':
  17716. object = new LightProbe().fromJSON( data );
  17717. break;
  17718. case 'SkinnedMesh':
  17719. geometry = getGeometry( data.geometry );
  17720. material = getMaterial( data.material );
  17721. object = new SkinnedMesh( geometry, material );
  17722. if ( data.bindMode !== undefined ) object.bindMode = data.bindMode;
  17723. if ( data.bindMatrix !== undefined ) object.bindMatrix.fromArray( data.bindMatrix );
  17724. if ( data.skeleton !== undefined ) object.skeleton = data.skeleton;
  17725. break;
  17726. case 'Mesh':
  17727. geometry = getGeometry( data.geometry );
  17728. material = getMaterial( data.material );
  17729. object = new Mesh( geometry, material );
  17730. break;
  17731. case 'InstancedMesh':
  17732. geometry = getGeometry( data.geometry );
  17733. material = getMaterial( data.material );
  17734. const count = data.count;
  17735. const instanceMatrix = data.instanceMatrix;
  17736. const instanceColor = data.instanceColor;
  17737. object = new InstancedMesh( geometry, material, count );
  17738. object.instanceMatrix = new InstancedBufferAttribute( new Float32Array( instanceMatrix.array ), 16 );
  17739. if ( instanceColor !== undefined ) object.instanceColor = new InstancedBufferAttribute( new Float32Array( instanceColor.array ), instanceColor.itemSize );
  17740. break;
  17741. case 'BatchedMesh':
  17742. geometry = getGeometry( data.geometry );
  17743. material = getMaterial( data.material );
  17744. object = new BatchedMesh( data.maxInstanceCount, data.maxVertexCount, data.maxIndexCount, material );
  17745. object.geometry = geometry;
  17746. object.perObjectFrustumCulled = data.perObjectFrustumCulled;
  17747. object.sortObjects = data.sortObjects;
  17748. object._drawRanges = data.drawRanges;
  17749. object._reservedRanges = data.reservedRanges;
  17750. object._visibility = data.visibility;
  17751. object._active = data.active;
  17752. object._bounds = data.bounds.map( bound => {
  17753. const box = new Box3();
  17754. box.min.fromArray( bound.boxMin );
  17755. box.max.fromArray( bound.boxMax );
  17756. const sphere = new Sphere();
  17757. sphere.radius = bound.sphereRadius;
  17758. sphere.center.fromArray( bound.sphereCenter );
  17759. return {
  17760. boxInitialized: bound.boxInitialized,
  17761. box: box,
  17762. sphereInitialized: bound.sphereInitialized,
  17763. sphere: sphere
  17764. };
  17765. } );
  17766. object._maxInstanceCount = data.maxInstanceCount;
  17767. object._maxVertexCount = data.maxVertexCount;
  17768. object._maxIndexCount = data.maxIndexCount;
  17769. object._geometryInitialized = data.geometryInitialized;
  17770. object._geometryCount = data.geometryCount;
  17771. object._matricesTexture = getTexture( data.matricesTexture.uuid );
  17772. if ( data.colorsTexture !== undefined ) object._colorsTexture = getTexture( data.colorsTexture.uuid );
  17773. break;
  17774. case 'LOD':
  17775. object = new LOD();
  17776. break;
  17777. case 'Line':
  17778. object = new Line( getGeometry( data.geometry ), getMaterial( data.material ) );
  17779. break;
  17780. case 'LineLoop':
  17781. object = new LineLoop( getGeometry( data.geometry ), getMaterial( data.material ) );
  17782. break;
  17783. case 'LineSegments':
  17784. object = new LineSegments( getGeometry( data.geometry ), getMaterial( data.material ) );
  17785. break;
  17786. case 'PointCloud':
  17787. case 'Points':
  17788. object = new Points( getGeometry( data.geometry ), getMaterial( data.material ) );
  17789. break;
  17790. case 'Sprite':
  17791. object = new Sprite( getMaterial( data.material ) );
  17792. break;
  17793. case 'Group':
  17794. object = new Group();
  17795. break;
  17796. case 'Bone':
  17797. object = new Bone();
  17798. break;
  17799. default:
  17800. object = new Object3D();
  17801. }
  17802. object.uuid = data.uuid;
  17803. if ( data.name !== undefined ) object.name = data.name;
  17804. if ( data.matrix !== undefined ) {
  17805. object.matrix.fromArray( data.matrix );
  17806. if ( data.matrixAutoUpdate !== undefined ) object.matrixAutoUpdate = data.matrixAutoUpdate;
  17807. if ( object.matrixAutoUpdate ) object.matrix.decompose( object.position, object.quaternion, object.scale );
  17808. } else {
  17809. if ( data.position !== undefined ) object.position.fromArray( data.position );
  17810. if ( data.rotation !== undefined ) object.rotation.fromArray( data.rotation );
  17811. if ( data.quaternion !== undefined ) object.quaternion.fromArray( data.quaternion );
  17812. if ( data.scale !== undefined ) object.scale.fromArray( data.scale );
  17813. }
  17814. if ( data.up !== undefined ) object.up.fromArray( data.up );
  17815. if ( data.castShadow !== undefined ) object.castShadow = data.castShadow;
  17816. if ( data.receiveShadow !== undefined ) object.receiveShadow = data.receiveShadow;
  17817. if ( data.shadow ) {
  17818. if ( data.shadow.intensity !== undefined ) object.shadow.intensity = data.shadow.intensity;
  17819. if ( data.shadow.bias !== undefined ) object.shadow.bias = data.shadow.bias;
  17820. if ( data.shadow.normalBias !== undefined ) object.shadow.normalBias = data.shadow.normalBias;
  17821. if ( data.shadow.radius !== undefined ) object.shadow.radius = data.shadow.radius;
  17822. if ( data.shadow.mapSize !== undefined ) object.shadow.mapSize.fromArray( data.shadow.mapSize );
  17823. if ( data.shadow.camera !== undefined ) object.shadow.camera = this.parseObject( data.shadow.camera );
  17824. }
  17825. if ( data.visible !== undefined ) object.visible = data.visible;
  17826. if ( data.frustumCulled !== undefined ) object.frustumCulled = data.frustumCulled;
  17827. if ( data.renderOrder !== undefined ) object.renderOrder = data.renderOrder;
  17828. if ( data.userData !== undefined ) object.userData = data.userData;
  17829. if ( data.layers !== undefined ) object.layers.mask = data.layers;
  17830. if ( data.children !== undefined ) {
  17831. const children = data.children;
  17832. for ( let i = 0; i < children.length; i ++ ) {
  17833. object.add( this.parseObject( children[ i ], geometries, materials, textures, animations ) );
  17834. }
  17835. }
  17836. if ( data.animations !== undefined ) {
  17837. const objectAnimations = data.animations;
  17838. for ( let i = 0; i < objectAnimations.length; i ++ ) {
  17839. const uuid = objectAnimations[ i ];
  17840. object.animations.push( animations[ uuid ] );
  17841. }
  17842. }
  17843. if ( data.type === 'LOD' ) {
  17844. if ( data.autoUpdate !== undefined ) object.autoUpdate = data.autoUpdate;
  17845. const levels = data.levels;
  17846. for ( let l = 0; l < levels.length; l ++ ) {
  17847. const level = levels[ l ];
  17848. const child = object.getObjectByProperty( 'uuid', level.object );
  17849. if ( child !== undefined ) {
  17850. object.addLevel( child, level.distance, level.hysteresis );
  17851. }
  17852. }
  17853. }
  17854. return object;
  17855. }
  17856. bindSkeletons( object, skeletons ) {
  17857. if ( Object.keys( skeletons ).length === 0 ) return;
  17858. object.traverse( function ( child ) {
  17859. if ( child.isSkinnedMesh === true && child.skeleton !== undefined ) {
  17860. const skeleton = skeletons[ child.skeleton ];
  17861. if ( skeleton === undefined ) {
  17862. console.warn( 'THREE.ObjectLoader: No skeleton found with UUID:', child.skeleton );
  17863. } else {
  17864. child.bind( skeleton, child.bindMatrix );
  17865. }
  17866. }
  17867. } );
  17868. }
  17869. bindLightTargets( object ) {
  17870. object.traverse( function ( child ) {
  17871. if ( child.isDirectionalLight || child.isSpotLight ) {
  17872. const uuid = child.target;
  17873. const target = object.getObjectByProperty( 'uuid', uuid );
  17874. if ( target !== undefined ) {
  17875. child.target = target;
  17876. } else {
  17877. child.target = new Object3D();
  17878. }
  17879. }
  17880. } );
  17881. }
  17882. }
  17883. const TEXTURE_MAPPING = {
  17884. UVMapping: UVMapping,
  17885. CubeReflectionMapping: CubeReflectionMapping,
  17886. CubeRefractionMapping: CubeRefractionMapping,
  17887. EquirectangularReflectionMapping: EquirectangularReflectionMapping,
  17888. EquirectangularRefractionMapping: EquirectangularRefractionMapping,
  17889. CubeUVReflectionMapping: CubeUVReflectionMapping
  17890. };
  17891. const TEXTURE_WRAPPING = {
  17892. RepeatWrapping: RepeatWrapping,
  17893. ClampToEdgeWrapping: ClampToEdgeWrapping,
  17894. MirroredRepeatWrapping: MirroredRepeatWrapping
  17895. };
  17896. const TEXTURE_FILTER = {
  17897. NearestFilter: NearestFilter,
  17898. NearestMipmapNearestFilter: NearestMipmapNearestFilter,
  17899. NearestMipmapLinearFilter: NearestMipmapLinearFilter,
  17900. LinearFilter: LinearFilter,
  17901. LinearMipmapNearestFilter: LinearMipmapNearestFilter,
  17902. LinearMipmapLinearFilter: LinearMipmapLinearFilter
  17903. };
  17904. class ImageBitmapLoader extends Loader {
  17905. constructor( manager ) {
  17906. super( manager );
  17907. this.isImageBitmapLoader = true;
  17908. if ( typeof createImageBitmap === 'undefined' ) {
  17909. console.warn( 'THREE.ImageBitmapLoader: createImageBitmap() not supported.' );
  17910. }
  17911. if ( typeof fetch === 'undefined' ) {
  17912. console.warn( 'THREE.ImageBitmapLoader: fetch() not supported.' );
  17913. }
  17914. this.options = { premultiplyAlpha: 'none' };
  17915. }
  17916. setOptions( options ) {
  17917. this.options = options;
  17918. return this;
  17919. }
  17920. load( url, onLoad, onProgress, onError ) {
  17921. if ( url === undefined ) url = '';
  17922. if ( this.path !== undefined ) url = this.path + url;
  17923. url = this.manager.resolveURL( url );
  17924. const scope = this;
  17925. const cached = Cache.get( url );
  17926. if ( cached !== undefined ) {
  17927. scope.manager.itemStart( url );
  17928. // If cached is a promise, wait for it to resolve
  17929. if ( cached.then ) {
  17930. cached.then( imageBitmap => {
  17931. if ( onLoad ) onLoad( imageBitmap );
  17932. scope.manager.itemEnd( url );
  17933. } ).catch( e => {
  17934. if ( onError ) onError( e );
  17935. } );
  17936. return;
  17937. }
  17938. // If cached is not a promise (i.e., it's already an imageBitmap)
  17939. setTimeout( function () {
  17940. if ( onLoad ) onLoad( cached );
  17941. scope.manager.itemEnd( url );
  17942. }, 0 );
  17943. return cached;
  17944. }
  17945. const fetchOptions = {};
  17946. fetchOptions.credentials = ( this.crossOrigin === 'anonymous' ) ? 'same-origin' : 'include';
  17947. fetchOptions.headers = this.requestHeader;
  17948. const promise = fetch( url, fetchOptions ).then( function ( res ) {
  17949. return res.blob();
  17950. } ).then( function ( blob ) {
  17951. return createImageBitmap( blob, Object.assign( scope.options, { colorSpaceConversion: 'none' } ) );
  17952. } ).then( function ( imageBitmap ) {
  17953. Cache.add( url, imageBitmap );
  17954. if ( onLoad ) onLoad( imageBitmap );
  17955. scope.manager.itemEnd( url );
  17956. return imageBitmap;
  17957. } ).catch( function ( e ) {
  17958. if ( onError ) onError( e );
  17959. Cache.remove( url );
  17960. scope.manager.itemError( url );
  17961. scope.manager.itemEnd( url );
  17962. } );
  17963. Cache.add( url, promise );
  17964. scope.manager.itemStart( url );
  17965. }
  17966. }
  17967. let _context;
  17968. class AudioContext {
  17969. static getContext() {
  17970. if ( _context === undefined ) {
  17971. _context = new ( window.AudioContext || window.webkitAudioContext )();
  17972. }
  17973. return _context;
  17974. }
  17975. static setContext( value ) {
  17976. _context = value;
  17977. }
  17978. }
  17979. class AudioLoader extends Loader {
  17980. constructor( manager ) {
  17981. super( manager );
  17982. }
  17983. load( url, onLoad, onProgress, onError ) {
  17984. const scope = this;
  17985. const loader = new FileLoader( this.manager );
  17986. loader.setResponseType( 'arraybuffer' );
  17987. loader.setPath( this.path );
  17988. loader.setRequestHeader( this.requestHeader );
  17989. loader.setWithCredentials( this.withCredentials );
  17990. loader.load( url, function ( buffer ) {
  17991. try {
  17992. // Create a copy of the buffer. The `decodeAudioData` method
  17993. // detaches the buffer when complete, preventing reuse.
  17994. const bufferCopy = buffer.slice( 0 );
  17995. const context = AudioContext.getContext();
  17996. context.decodeAudioData( bufferCopy, function ( audioBuffer ) {
  17997. onLoad( audioBuffer );
  17998. } ).catch( handleError );
  17999. } catch ( e ) {
  18000. handleError( e );
  18001. }
  18002. }, onProgress, onError );
  18003. function handleError( e ) {
  18004. if ( onError ) {
  18005. onError( e );
  18006. } else {
  18007. console.error( e );
  18008. }
  18009. scope.manager.itemError( url );
  18010. }
  18011. }
  18012. }
  18013. const _eyeRight = /*@__PURE__*/ new Matrix4();
  18014. const _eyeLeft = /*@__PURE__*/ new Matrix4();
  18015. const _projectionMatrix = /*@__PURE__*/ new Matrix4();
  18016. class StereoCamera {
  18017. constructor() {
  18018. this.type = 'StereoCamera';
  18019. this.aspect = 1;
  18020. this.eyeSep = 0.064;
  18021. this.cameraL = new PerspectiveCamera();
  18022. this.cameraL.layers.enable( 1 );
  18023. this.cameraL.matrixAutoUpdate = false;
  18024. this.cameraR = new PerspectiveCamera();
  18025. this.cameraR.layers.enable( 2 );
  18026. this.cameraR.matrixAutoUpdate = false;
  18027. this._cache = {
  18028. focus: null,
  18029. fov: null,
  18030. aspect: null,
  18031. near: null,
  18032. far: null,
  18033. zoom: null,
  18034. eyeSep: null
  18035. };
  18036. }
  18037. update( camera ) {
  18038. const cache = this._cache;
  18039. const needsUpdate = cache.focus !== camera.focus || cache.fov !== camera.fov ||
  18040. cache.aspect !== camera.aspect * this.aspect || cache.near !== camera.near ||
  18041. cache.far !== camera.far || cache.zoom !== camera.zoom || cache.eyeSep !== this.eyeSep;
  18042. if ( needsUpdate ) {
  18043. cache.focus = camera.focus;
  18044. cache.fov = camera.fov;
  18045. cache.aspect = camera.aspect * this.aspect;
  18046. cache.near = camera.near;
  18047. cache.far = camera.far;
  18048. cache.zoom = camera.zoom;
  18049. cache.eyeSep = this.eyeSep;
  18050. // Off-axis stereoscopic effect based on
  18051. // http://paulbourke.net/stereographics/stereorender/
  18052. _projectionMatrix.copy( camera.projectionMatrix );
  18053. const eyeSepHalf = cache.eyeSep / 2;
  18054. const eyeSepOnProjection = eyeSepHalf * cache.near / cache.focus;
  18055. const ymax = ( cache.near * Math.tan( DEG2RAD * cache.fov * 0.5 ) ) / cache.zoom;
  18056. let xmin, xmax;
  18057. // translate xOffset
  18058. _eyeLeft.elements[ 12 ] = - eyeSepHalf;
  18059. _eyeRight.elements[ 12 ] = eyeSepHalf;
  18060. // for left eye
  18061. xmin = - ymax * cache.aspect + eyeSepOnProjection;
  18062. xmax = ymax * cache.aspect + eyeSepOnProjection;
  18063. _projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
  18064. _projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  18065. this.cameraL.projectionMatrix.copy( _projectionMatrix );
  18066. // for right eye
  18067. xmin = - ymax * cache.aspect - eyeSepOnProjection;
  18068. xmax = ymax * cache.aspect - eyeSepOnProjection;
  18069. _projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
  18070. _projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  18071. this.cameraR.projectionMatrix.copy( _projectionMatrix );
  18072. }
  18073. this.cameraL.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeLeft );
  18074. this.cameraR.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeRight );
  18075. }
  18076. }
  18077. class ArrayCamera extends PerspectiveCamera {
  18078. constructor( array = [] ) {
  18079. super();
  18080. this.isArrayCamera = true;
  18081. this.cameras = array;
  18082. }
  18083. }
  18084. class Clock {
  18085. constructor( autoStart = true ) {
  18086. this.autoStart = autoStart;
  18087. this.startTime = 0;
  18088. this.oldTime = 0;
  18089. this.elapsedTime = 0;
  18090. this.running = false;
  18091. }
  18092. start() {
  18093. this.startTime = now();
  18094. this.oldTime = this.startTime;
  18095. this.elapsedTime = 0;
  18096. this.running = true;
  18097. }
  18098. stop() {
  18099. this.getElapsedTime();
  18100. this.running = false;
  18101. this.autoStart = false;
  18102. }
  18103. getElapsedTime() {
  18104. this.getDelta();
  18105. return this.elapsedTime;
  18106. }
  18107. getDelta() {
  18108. let diff = 0;
  18109. if ( this.autoStart && ! this.running ) {
  18110. this.start();
  18111. return 0;
  18112. }
  18113. if ( this.running ) {
  18114. const newTime = now();
  18115. diff = ( newTime - this.oldTime ) / 1000;
  18116. this.oldTime = newTime;
  18117. this.elapsedTime += diff;
  18118. }
  18119. return diff;
  18120. }
  18121. }
  18122. function now() {
  18123. return performance.now();
  18124. }
  18125. const _position$1 = /*@__PURE__*/ new Vector3();
  18126. const _quaternion$1 = /*@__PURE__*/ new Quaternion();
  18127. const _scale$1 = /*@__PURE__*/ new Vector3();
  18128. const _orientation$1 = /*@__PURE__*/ new Vector3();
  18129. class AudioListener extends Object3D {
  18130. constructor() {
  18131. super();
  18132. this.type = 'AudioListener';
  18133. this.context = AudioContext.getContext();
  18134. this.gain = this.context.createGain();
  18135. this.gain.connect( this.context.destination );
  18136. this.filter = null;
  18137. this.timeDelta = 0;
  18138. // private
  18139. this._clock = new Clock();
  18140. }
  18141. getInput() {
  18142. return this.gain;
  18143. }
  18144. removeFilter() {
  18145. if ( this.filter !== null ) {
  18146. this.gain.disconnect( this.filter );
  18147. this.filter.disconnect( this.context.destination );
  18148. this.gain.connect( this.context.destination );
  18149. this.filter = null;
  18150. }
  18151. return this;
  18152. }
  18153. getFilter() {
  18154. return this.filter;
  18155. }
  18156. setFilter( value ) {
  18157. if ( this.filter !== null ) {
  18158. this.gain.disconnect( this.filter );
  18159. this.filter.disconnect( this.context.destination );
  18160. } else {
  18161. this.gain.disconnect( this.context.destination );
  18162. }
  18163. this.filter = value;
  18164. this.gain.connect( this.filter );
  18165. this.filter.connect( this.context.destination );
  18166. return this;
  18167. }
  18168. getMasterVolume() {
  18169. return this.gain.gain.value;
  18170. }
  18171. setMasterVolume( value ) {
  18172. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  18173. return this;
  18174. }
  18175. updateMatrixWorld( force ) {
  18176. super.updateMatrixWorld( force );
  18177. const listener = this.context.listener;
  18178. const up = this.up;
  18179. this.timeDelta = this._clock.getDelta();
  18180. this.matrixWorld.decompose( _position$1, _quaternion$1, _scale$1 );
  18181. _orientation$1.set( 0, 0, - 1 ).applyQuaternion( _quaternion$1 );
  18182. if ( listener.positionX ) {
  18183. // code path for Chrome (see #14393)
  18184. const endTime = this.context.currentTime + this.timeDelta;
  18185. listener.positionX.linearRampToValueAtTime( _position$1.x, endTime );
  18186. listener.positionY.linearRampToValueAtTime( _position$1.y, endTime );
  18187. listener.positionZ.linearRampToValueAtTime( _position$1.z, endTime );
  18188. listener.forwardX.linearRampToValueAtTime( _orientation$1.x, endTime );
  18189. listener.forwardY.linearRampToValueAtTime( _orientation$1.y, endTime );
  18190. listener.forwardZ.linearRampToValueAtTime( _orientation$1.z, endTime );
  18191. listener.upX.linearRampToValueAtTime( up.x, endTime );
  18192. listener.upY.linearRampToValueAtTime( up.y, endTime );
  18193. listener.upZ.linearRampToValueAtTime( up.z, endTime );
  18194. } else {
  18195. listener.setPosition( _position$1.x, _position$1.y, _position$1.z );
  18196. listener.setOrientation( _orientation$1.x, _orientation$1.y, _orientation$1.z, up.x, up.y, up.z );
  18197. }
  18198. }
  18199. }
  18200. class Audio extends Object3D {
  18201. constructor( listener ) {
  18202. super();
  18203. this.type = 'Audio';
  18204. this.listener = listener;
  18205. this.context = listener.context;
  18206. this.gain = this.context.createGain();
  18207. this.gain.connect( listener.getInput() );
  18208. this.autoplay = false;
  18209. this.buffer = null;
  18210. this.detune = 0;
  18211. this.loop = false;
  18212. this.loopStart = 0;
  18213. this.loopEnd = 0;
  18214. this.offset = 0;
  18215. this.duration = undefined;
  18216. this.playbackRate = 1;
  18217. this.isPlaying = false;
  18218. this.hasPlaybackControl = true;
  18219. this.source = null;
  18220. this.sourceType = 'empty';
  18221. this._startedAt = 0;
  18222. this._progress = 0;
  18223. this._connected = false;
  18224. this.filters = [];
  18225. }
  18226. getOutput() {
  18227. return this.gain;
  18228. }
  18229. setNodeSource( audioNode ) {
  18230. this.hasPlaybackControl = false;
  18231. this.sourceType = 'audioNode';
  18232. this.source = audioNode;
  18233. this.connect();
  18234. return this;
  18235. }
  18236. setMediaElementSource( mediaElement ) {
  18237. this.hasPlaybackControl = false;
  18238. this.sourceType = 'mediaNode';
  18239. this.source = this.context.createMediaElementSource( mediaElement );
  18240. this.connect();
  18241. return this;
  18242. }
  18243. setMediaStreamSource( mediaStream ) {
  18244. this.hasPlaybackControl = false;
  18245. this.sourceType = 'mediaStreamNode';
  18246. this.source = this.context.createMediaStreamSource( mediaStream );
  18247. this.connect();
  18248. return this;
  18249. }
  18250. setBuffer( audioBuffer ) {
  18251. this.buffer = audioBuffer;
  18252. this.sourceType = 'buffer';
  18253. if ( this.autoplay ) this.play();
  18254. return this;
  18255. }
  18256. play( delay = 0 ) {
  18257. if ( this.isPlaying === true ) {
  18258. console.warn( 'THREE.Audio: Audio is already playing.' );
  18259. return;
  18260. }
  18261. if ( this.hasPlaybackControl === false ) {
  18262. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  18263. return;
  18264. }
  18265. this._startedAt = this.context.currentTime + delay;
  18266. const source = this.context.createBufferSource();
  18267. source.buffer = this.buffer;
  18268. source.loop = this.loop;
  18269. source.loopStart = this.loopStart;
  18270. source.loopEnd = this.loopEnd;
  18271. source.onended = this.onEnded.bind( this );
  18272. source.start( this._startedAt, this._progress + this.offset, this.duration );
  18273. this.isPlaying = true;
  18274. this.source = source;
  18275. this.setDetune( this.detune );
  18276. this.setPlaybackRate( this.playbackRate );
  18277. return this.connect();
  18278. }
  18279. pause() {
  18280. if ( this.hasPlaybackControl === false ) {
  18281. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  18282. return;
  18283. }
  18284. if ( this.isPlaying === true ) {
  18285. // update current progress
  18286. this._progress += Math.max( this.context.currentTime - this._startedAt, 0 ) * this.playbackRate;
  18287. if ( this.loop === true ) {
  18288. // ensure _progress does not exceed duration with looped audios
  18289. this._progress = this._progress % ( this.duration || this.buffer.duration );
  18290. }
  18291. this.source.stop();
  18292. this.source.onended = null;
  18293. this.isPlaying = false;
  18294. }
  18295. return this;
  18296. }
  18297. stop( delay = 0 ) {
  18298. if ( this.hasPlaybackControl === false ) {
  18299. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  18300. return;
  18301. }
  18302. this._progress = 0;
  18303. if ( this.source !== null ) {
  18304. this.source.stop( this.context.currentTime + delay );
  18305. this.source.onended = null;
  18306. }
  18307. this.isPlaying = false;
  18308. return this;
  18309. }
  18310. connect() {
  18311. if ( this.filters.length > 0 ) {
  18312. this.source.connect( this.filters[ 0 ] );
  18313. for ( let i = 1, l = this.filters.length; i < l; i ++ ) {
  18314. this.filters[ i - 1 ].connect( this.filters[ i ] );
  18315. }
  18316. this.filters[ this.filters.length - 1 ].connect( this.getOutput() );
  18317. } else {
  18318. this.source.connect( this.getOutput() );
  18319. }
  18320. this._connected = true;
  18321. return this;
  18322. }
  18323. disconnect() {
  18324. if ( this._connected === false ) {
  18325. return;
  18326. }
  18327. if ( this.filters.length > 0 ) {
  18328. this.source.disconnect( this.filters[ 0 ] );
  18329. for ( let i = 1, l = this.filters.length; i < l; i ++ ) {
  18330. this.filters[ i - 1 ].disconnect( this.filters[ i ] );
  18331. }
  18332. this.filters[ this.filters.length - 1 ].disconnect( this.getOutput() );
  18333. } else {
  18334. this.source.disconnect( this.getOutput() );
  18335. }
  18336. this._connected = false;
  18337. return this;
  18338. }
  18339. getFilters() {
  18340. return this.filters;
  18341. }
  18342. setFilters( value ) {
  18343. if ( ! value ) value = [];
  18344. if ( this._connected === true ) {
  18345. this.disconnect();
  18346. this.filters = value.slice();
  18347. this.connect();
  18348. } else {
  18349. this.filters = value.slice();
  18350. }
  18351. return this;
  18352. }
  18353. setDetune( value ) {
  18354. this.detune = value;
  18355. if ( this.isPlaying === true && this.source.detune !== undefined ) {
  18356. this.source.detune.setTargetAtTime( this.detune, this.context.currentTime, 0.01 );
  18357. }
  18358. return this;
  18359. }
  18360. getDetune() {
  18361. return this.detune;
  18362. }
  18363. getFilter() {
  18364. return this.getFilters()[ 0 ];
  18365. }
  18366. setFilter( filter ) {
  18367. return this.setFilters( filter ? [ filter ] : [] );
  18368. }
  18369. setPlaybackRate( value ) {
  18370. if ( this.hasPlaybackControl === false ) {
  18371. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  18372. return;
  18373. }
  18374. this.playbackRate = value;
  18375. if ( this.isPlaying === true ) {
  18376. this.source.playbackRate.setTargetAtTime( this.playbackRate, this.context.currentTime, 0.01 );
  18377. }
  18378. return this;
  18379. }
  18380. getPlaybackRate() {
  18381. return this.playbackRate;
  18382. }
  18383. onEnded() {
  18384. this.isPlaying = false;
  18385. }
  18386. getLoop() {
  18387. if ( this.hasPlaybackControl === false ) {
  18388. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  18389. return false;
  18390. }
  18391. return this.loop;
  18392. }
  18393. setLoop( value ) {
  18394. if ( this.hasPlaybackControl === false ) {
  18395. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  18396. return;
  18397. }
  18398. this.loop = value;
  18399. if ( this.isPlaying === true ) {
  18400. this.source.loop = this.loop;
  18401. }
  18402. return this;
  18403. }
  18404. setLoopStart( value ) {
  18405. this.loopStart = value;
  18406. return this;
  18407. }
  18408. setLoopEnd( value ) {
  18409. this.loopEnd = value;
  18410. return this;
  18411. }
  18412. getVolume() {
  18413. return this.gain.gain.value;
  18414. }
  18415. setVolume( value ) {
  18416. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  18417. return this;
  18418. }
  18419. }
  18420. const _position = /*@__PURE__*/ new Vector3();
  18421. const _quaternion = /*@__PURE__*/ new Quaternion();
  18422. const _scale = /*@__PURE__*/ new Vector3();
  18423. const _orientation = /*@__PURE__*/ new Vector3();
  18424. class PositionalAudio extends Audio {
  18425. constructor( listener ) {
  18426. super( listener );
  18427. this.panner = this.context.createPanner();
  18428. this.panner.panningModel = 'HRTF';
  18429. this.panner.connect( this.gain );
  18430. }
  18431. connect() {
  18432. super.connect();
  18433. this.panner.connect( this.gain );
  18434. }
  18435. disconnect() {
  18436. super.disconnect();
  18437. this.panner.disconnect( this.gain );
  18438. }
  18439. getOutput() {
  18440. return this.panner;
  18441. }
  18442. getRefDistance() {
  18443. return this.panner.refDistance;
  18444. }
  18445. setRefDistance( value ) {
  18446. this.panner.refDistance = value;
  18447. return this;
  18448. }
  18449. getRolloffFactor() {
  18450. return this.panner.rolloffFactor;
  18451. }
  18452. setRolloffFactor( value ) {
  18453. this.panner.rolloffFactor = value;
  18454. return this;
  18455. }
  18456. getDistanceModel() {
  18457. return this.panner.distanceModel;
  18458. }
  18459. setDistanceModel( value ) {
  18460. this.panner.distanceModel = value;
  18461. return this;
  18462. }
  18463. getMaxDistance() {
  18464. return this.panner.maxDistance;
  18465. }
  18466. setMaxDistance( value ) {
  18467. this.panner.maxDistance = value;
  18468. return this;
  18469. }
  18470. setDirectionalCone( coneInnerAngle, coneOuterAngle, coneOuterGain ) {
  18471. this.panner.coneInnerAngle = coneInnerAngle;
  18472. this.panner.coneOuterAngle = coneOuterAngle;
  18473. this.panner.coneOuterGain = coneOuterGain;
  18474. return this;
  18475. }
  18476. updateMatrixWorld( force ) {
  18477. super.updateMatrixWorld( force );
  18478. if ( this.hasPlaybackControl === true && this.isPlaying === false ) return;
  18479. this.matrixWorld.decompose( _position, _quaternion, _scale );
  18480. _orientation.set( 0, 0, 1 ).applyQuaternion( _quaternion );
  18481. const panner = this.panner;
  18482. if ( panner.positionX ) {
  18483. // code path for Chrome and Firefox (see #14393)
  18484. const endTime = this.context.currentTime + this.listener.timeDelta;
  18485. panner.positionX.linearRampToValueAtTime( _position.x, endTime );
  18486. panner.positionY.linearRampToValueAtTime( _position.y, endTime );
  18487. panner.positionZ.linearRampToValueAtTime( _position.z, endTime );
  18488. panner.orientationX.linearRampToValueAtTime( _orientation.x, endTime );
  18489. panner.orientationY.linearRampToValueAtTime( _orientation.y, endTime );
  18490. panner.orientationZ.linearRampToValueAtTime( _orientation.z, endTime );
  18491. } else {
  18492. panner.setPosition( _position.x, _position.y, _position.z );
  18493. panner.setOrientation( _orientation.x, _orientation.y, _orientation.z );
  18494. }
  18495. }
  18496. }
  18497. class AudioAnalyser {
  18498. constructor( audio, fftSize = 2048 ) {
  18499. this.analyser = audio.context.createAnalyser();
  18500. this.analyser.fftSize = fftSize;
  18501. this.data = new Uint8Array( this.analyser.frequencyBinCount );
  18502. audio.getOutput().connect( this.analyser );
  18503. }
  18504. getFrequencyData() {
  18505. this.analyser.getByteFrequencyData( this.data );
  18506. return this.data;
  18507. }
  18508. getAverageFrequency() {
  18509. let value = 0;
  18510. const data = this.getFrequencyData();
  18511. for ( let i = 0; i < data.length; i ++ ) {
  18512. value += data[ i ];
  18513. }
  18514. return value / data.length;
  18515. }
  18516. }
  18517. class PropertyMixer {
  18518. constructor( binding, typeName, valueSize ) {
  18519. this.binding = binding;
  18520. this.valueSize = valueSize;
  18521. let mixFunction,
  18522. mixFunctionAdditive,
  18523. setIdentity;
  18524. // buffer layout: [ incoming | accu0 | accu1 | orig | addAccu | (optional work) ]
  18525. //
  18526. // interpolators can use .buffer as their .result
  18527. // the data then goes to 'incoming'
  18528. //
  18529. // 'accu0' and 'accu1' are used frame-interleaved for
  18530. // the cumulative result and are compared to detect
  18531. // changes
  18532. //
  18533. // 'orig' stores the original state of the property
  18534. //
  18535. // 'add' is used for additive cumulative results
  18536. //
  18537. // 'work' is optional and is only present for quaternion types. It is used
  18538. // to store intermediate quaternion multiplication results
  18539. switch ( typeName ) {
  18540. case 'quaternion':
  18541. mixFunction = this._slerp;
  18542. mixFunctionAdditive = this._slerpAdditive;
  18543. setIdentity = this._setAdditiveIdentityQuaternion;
  18544. this.buffer = new Float64Array( valueSize * 6 );
  18545. this._workIndex = 5;
  18546. break;
  18547. case 'string':
  18548. case 'bool':
  18549. mixFunction = this._select;
  18550. // Use the regular mix function and for additive on these types,
  18551. // additive is not relevant for non-numeric types
  18552. mixFunctionAdditive = this._select;
  18553. setIdentity = this._setAdditiveIdentityOther;
  18554. this.buffer = new Array( valueSize * 5 );
  18555. break;
  18556. default:
  18557. mixFunction = this._lerp;
  18558. mixFunctionAdditive = this._lerpAdditive;
  18559. setIdentity = this._setAdditiveIdentityNumeric;
  18560. this.buffer = new Float64Array( valueSize * 5 );
  18561. }
  18562. this._mixBufferRegion = mixFunction;
  18563. this._mixBufferRegionAdditive = mixFunctionAdditive;
  18564. this._setIdentity = setIdentity;
  18565. this._origIndex = 3;
  18566. this._addIndex = 4;
  18567. this.cumulativeWeight = 0;
  18568. this.cumulativeWeightAdditive = 0;
  18569. this.useCount = 0;
  18570. this.referenceCount = 0;
  18571. }
  18572. // accumulate data in the 'incoming' region into 'accu<i>'
  18573. accumulate( accuIndex, weight ) {
  18574. // note: happily accumulating nothing when weight = 0, the caller knows
  18575. // the weight and shouldn't have made the call in the first place
  18576. const buffer = this.buffer,
  18577. stride = this.valueSize,
  18578. offset = accuIndex * stride + stride;
  18579. let currentWeight = this.cumulativeWeight;
  18580. if ( currentWeight === 0 ) {
  18581. // accuN := incoming * weight
  18582. for ( let i = 0; i !== stride; ++ i ) {
  18583. buffer[ offset + i ] = buffer[ i ];
  18584. }
  18585. currentWeight = weight;
  18586. } else {
  18587. // accuN := accuN + incoming * weight
  18588. currentWeight += weight;
  18589. const mix = weight / currentWeight;
  18590. this._mixBufferRegion( buffer, offset, 0, mix, stride );
  18591. }
  18592. this.cumulativeWeight = currentWeight;
  18593. }
  18594. // accumulate data in the 'incoming' region into 'add'
  18595. accumulateAdditive( weight ) {
  18596. const buffer = this.buffer,
  18597. stride = this.valueSize,
  18598. offset = stride * this._addIndex;
  18599. if ( this.cumulativeWeightAdditive === 0 ) {
  18600. // add = identity
  18601. this._setIdentity();
  18602. }
  18603. // add := add + incoming * weight
  18604. this._mixBufferRegionAdditive( buffer, offset, 0, weight, stride );
  18605. this.cumulativeWeightAdditive += weight;
  18606. }
  18607. // apply the state of 'accu<i>' to the binding when accus differ
  18608. apply( accuIndex ) {
  18609. const stride = this.valueSize,
  18610. buffer = this.buffer,
  18611. offset = accuIndex * stride + stride,
  18612. weight = this.cumulativeWeight,
  18613. weightAdditive = this.cumulativeWeightAdditive,
  18614. binding = this.binding;
  18615. this.cumulativeWeight = 0;
  18616. this.cumulativeWeightAdditive = 0;
  18617. if ( weight < 1 ) {
  18618. // accuN := accuN + original * ( 1 - cumulativeWeight )
  18619. const originalValueOffset = stride * this._origIndex;
  18620. this._mixBufferRegion(
  18621. buffer, offset, originalValueOffset, 1 - weight, stride );
  18622. }
  18623. if ( weightAdditive > 0 ) {
  18624. // accuN := accuN + additive accuN
  18625. this._mixBufferRegionAdditive( buffer, offset, this._addIndex * stride, 1, stride );
  18626. }
  18627. for ( let i = stride, e = stride + stride; i !== e; ++ i ) {
  18628. if ( buffer[ i ] !== buffer[ i + stride ] ) {
  18629. // value has changed -> update scene graph
  18630. binding.setValue( buffer, offset );
  18631. break;
  18632. }
  18633. }
  18634. }
  18635. // remember the state of the bound property and copy it to both accus
  18636. saveOriginalState() {
  18637. const binding = this.binding;
  18638. const buffer = this.buffer,
  18639. stride = this.valueSize,
  18640. originalValueOffset = stride * this._origIndex;
  18641. binding.getValue( buffer, originalValueOffset );
  18642. // accu[0..1] := orig -- initially detect changes against the original
  18643. for ( let i = stride, e = originalValueOffset; i !== e; ++ i ) {
  18644. buffer[ i ] = buffer[ originalValueOffset + ( i % stride ) ];
  18645. }
  18646. // Add to identity for additive
  18647. this._setIdentity();
  18648. this.cumulativeWeight = 0;
  18649. this.cumulativeWeightAdditive = 0;
  18650. }
  18651. // apply the state previously taken via 'saveOriginalState' to the binding
  18652. restoreOriginalState() {
  18653. const originalValueOffset = this.valueSize * 3;
  18654. this.binding.setValue( this.buffer, originalValueOffset );
  18655. }
  18656. _setAdditiveIdentityNumeric() {
  18657. const startIndex = this._addIndex * this.valueSize;
  18658. const endIndex = startIndex + this.valueSize;
  18659. for ( let i = startIndex; i < endIndex; i ++ ) {
  18660. this.buffer[ i ] = 0;
  18661. }
  18662. }
  18663. _setAdditiveIdentityQuaternion() {
  18664. this._setAdditiveIdentityNumeric();
  18665. this.buffer[ this._addIndex * this.valueSize + 3 ] = 1;
  18666. }
  18667. _setAdditiveIdentityOther() {
  18668. const startIndex = this._origIndex * this.valueSize;
  18669. const targetIndex = this._addIndex * this.valueSize;
  18670. for ( let i = 0; i < this.valueSize; i ++ ) {
  18671. this.buffer[ targetIndex + i ] = this.buffer[ startIndex + i ];
  18672. }
  18673. }
  18674. // mix functions
  18675. _select( buffer, dstOffset, srcOffset, t, stride ) {
  18676. if ( t >= 0.5 ) {
  18677. for ( let i = 0; i !== stride; ++ i ) {
  18678. buffer[ dstOffset + i ] = buffer[ srcOffset + i ];
  18679. }
  18680. }
  18681. }
  18682. _slerp( buffer, dstOffset, srcOffset, t ) {
  18683. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, srcOffset, t );
  18684. }
  18685. _slerpAdditive( buffer, dstOffset, srcOffset, t, stride ) {
  18686. const workOffset = this._workIndex * stride;
  18687. // Store result in intermediate buffer offset
  18688. Quaternion.multiplyQuaternionsFlat( buffer, workOffset, buffer, dstOffset, buffer, srcOffset );
  18689. // Slerp to the intermediate result
  18690. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, workOffset, t );
  18691. }
  18692. _lerp( buffer, dstOffset, srcOffset, t, stride ) {
  18693. const s = 1 - t;
  18694. for ( let i = 0; i !== stride; ++ i ) {
  18695. const j = dstOffset + i;
  18696. buffer[ j ] = buffer[ j ] * s + buffer[ srcOffset + i ] * t;
  18697. }
  18698. }
  18699. _lerpAdditive( buffer, dstOffset, srcOffset, t, stride ) {
  18700. for ( let i = 0; i !== stride; ++ i ) {
  18701. const j = dstOffset + i;
  18702. buffer[ j ] = buffer[ j ] + buffer[ srcOffset + i ] * t;
  18703. }
  18704. }
  18705. }
  18706. // Characters [].:/ are reserved for track binding syntax.
  18707. const _RESERVED_CHARS_RE = '\\[\\]\\.:\\/';
  18708. const _reservedRe = new RegExp( '[' + _RESERVED_CHARS_RE + ']', 'g' );
  18709. // Attempts to allow node names from any language. ES5's `\w` regexp matches
  18710. // only latin characters, and the unicode \p{L} is not yet supported. So
  18711. // instead, we exclude reserved characters and match everything else.
  18712. const _wordChar = '[^' + _RESERVED_CHARS_RE + ']';
  18713. const _wordCharOrDot = '[^' + _RESERVED_CHARS_RE.replace( '\\.', '' ) + ']';
  18714. // Parent directories, delimited by '/' or ':'. Currently unused, but must
  18715. // be matched to parse the rest of the track name.
  18716. const _directoryRe = /*@__PURE__*/ /((?:WC+[\/:])*)/.source.replace( 'WC', _wordChar );
  18717. // Target node. May contain word characters (a-zA-Z0-9_) and '.' or '-'.
  18718. const _nodeRe = /*@__PURE__*/ /(WCOD+)?/.source.replace( 'WCOD', _wordCharOrDot );
  18719. // Object on target node, and accessor. May not contain reserved
  18720. // characters. Accessor may contain any character except closing bracket.
  18721. const _objectRe = /*@__PURE__*/ /(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace( 'WC', _wordChar );
  18722. // Property and accessor. May not contain reserved characters. Accessor may
  18723. // contain any non-bracket characters.
  18724. const _propertyRe = /*@__PURE__*/ /\.(WC+)(?:\[(.+)\])?/.source.replace( 'WC', _wordChar );
  18725. const _trackRe = new RegExp( ''
  18726. + '^'
  18727. + _directoryRe
  18728. + _nodeRe
  18729. + _objectRe
  18730. + _propertyRe
  18731. + '$'
  18732. );
  18733. const _supportedObjectNames = [ 'material', 'materials', 'bones', 'map' ];
  18734. class Composite {
  18735. constructor( targetGroup, path, optionalParsedPath ) {
  18736. const parsedPath = optionalParsedPath || PropertyBinding.parseTrackName( path );
  18737. this._targetGroup = targetGroup;
  18738. this._bindings = targetGroup.subscribe_( path, parsedPath );
  18739. }
  18740. getValue( array, offset ) {
  18741. this.bind(); // bind all binding
  18742. const firstValidIndex = this._targetGroup.nCachedObjects_,
  18743. binding = this._bindings[ firstValidIndex ];
  18744. // and only call .getValue on the first
  18745. if ( binding !== undefined ) binding.getValue( array, offset );
  18746. }
  18747. setValue( array, offset ) {
  18748. const bindings = this._bindings;
  18749. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  18750. bindings[ i ].setValue( array, offset );
  18751. }
  18752. }
  18753. bind() {
  18754. const bindings = this._bindings;
  18755. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  18756. bindings[ i ].bind();
  18757. }
  18758. }
  18759. unbind() {
  18760. const bindings = this._bindings;
  18761. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  18762. bindings[ i ].unbind();
  18763. }
  18764. }
  18765. }
  18766. // Note: This class uses a State pattern on a per-method basis:
  18767. // 'bind' sets 'this.getValue' / 'setValue' and shadows the
  18768. // prototype version of these methods with one that represents
  18769. // the bound state. When the property is not found, the methods
  18770. // become no-ops.
  18771. class PropertyBinding {
  18772. constructor( rootNode, path, parsedPath ) {
  18773. this.path = path;
  18774. this.parsedPath = parsedPath || PropertyBinding.parseTrackName( path );
  18775. this.node = PropertyBinding.findNode( rootNode, this.parsedPath.nodeName );
  18776. this.rootNode = rootNode;
  18777. // initial state of these methods that calls 'bind'
  18778. this.getValue = this._getValue_unbound;
  18779. this.setValue = this._setValue_unbound;
  18780. }
  18781. static create( root, path, parsedPath ) {
  18782. if ( ! ( root && root.isAnimationObjectGroup ) ) {
  18783. return new PropertyBinding( root, path, parsedPath );
  18784. } else {
  18785. return new PropertyBinding.Composite( root, path, parsedPath );
  18786. }
  18787. }
  18788. /**
  18789. * Replaces spaces with underscores and removes unsupported characters from
  18790. * node names, to ensure compatibility with parseTrackName().
  18791. *
  18792. * @param {string} name Node name to be sanitized.
  18793. * @return {string}
  18794. */
  18795. static sanitizeNodeName( name ) {
  18796. return name.replace( /\s/g, '_' ).replace( _reservedRe, '' );
  18797. }
  18798. static parseTrackName( trackName ) {
  18799. const matches = _trackRe.exec( trackName );
  18800. if ( matches === null ) {
  18801. throw new Error( 'PropertyBinding: Cannot parse trackName: ' + trackName );
  18802. }
  18803. const results = {
  18804. // directoryName: matches[ 1 ], // (tschw) currently unused
  18805. nodeName: matches[ 2 ],
  18806. objectName: matches[ 3 ],
  18807. objectIndex: matches[ 4 ],
  18808. propertyName: matches[ 5 ], // required
  18809. propertyIndex: matches[ 6 ]
  18810. };
  18811. const lastDot = results.nodeName && results.nodeName.lastIndexOf( '.' );
  18812. if ( lastDot !== undefined && lastDot !== - 1 ) {
  18813. const objectName = results.nodeName.substring( lastDot + 1 );
  18814. // Object names must be checked against an allowlist. Otherwise, there
  18815. // is no way to parse 'foo.bar.baz': 'baz' must be a property, but
  18816. // 'bar' could be the objectName, or part of a nodeName (which can
  18817. // include '.' characters).
  18818. if ( _supportedObjectNames.indexOf( objectName ) !== - 1 ) {
  18819. results.nodeName = results.nodeName.substring( 0, lastDot );
  18820. results.objectName = objectName;
  18821. }
  18822. }
  18823. if ( results.propertyName === null || results.propertyName.length === 0 ) {
  18824. throw new Error( 'PropertyBinding: can not parse propertyName from trackName: ' + trackName );
  18825. }
  18826. return results;
  18827. }
  18828. static findNode( root, nodeName ) {
  18829. if ( nodeName === undefined || nodeName === '' || nodeName === '.' || nodeName === - 1 || nodeName === root.name || nodeName === root.uuid ) {
  18830. return root;
  18831. }
  18832. // search into skeleton bones.
  18833. if ( root.skeleton ) {
  18834. const bone = root.skeleton.getBoneByName( nodeName );
  18835. if ( bone !== undefined ) {
  18836. return bone;
  18837. }
  18838. }
  18839. // search into node subtree.
  18840. if ( root.children ) {
  18841. const searchNodeSubtree = function ( children ) {
  18842. for ( let i = 0; i < children.length; i ++ ) {
  18843. const childNode = children[ i ];
  18844. if ( childNode.name === nodeName || childNode.uuid === nodeName ) {
  18845. return childNode;
  18846. }
  18847. const result = searchNodeSubtree( childNode.children );
  18848. if ( result ) return result;
  18849. }
  18850. return null;
  18851. };
  18852. const subTreeNode = searchNodeSubtree( root.children );
  18853. if ( subTreeNode ) {
  18854. return subTreeNode;
  18855. }
  18856. }
  18857. return null;
  18858. }
  18859. // these are used to "bind" a nonexistent property
  18860. _getValue_unavailable() {}
  18861. _setValue_unavailable() {}
  18862. // Getters
  18863. _getValue_direct( buffer, offset ) {
  18864. buffer[ offset ] = this.targetObject[ this.propertyName ];
  18865. }
  18866. _getValue_array( buffer, offset ) {
  18867. const source = this.resolvedProperty;
  18868. for ( let i = 0, n = source.length; i !== n; ++ i ) {
  18869. buffer[ offset ++ ] = source[ i ];
  18870. }
  18871. }
  18872. _getValue_arrayElement( buffer, offset ) {
  18873. buffer[ offset ] = this.resolvedProperty[ this.propertyIndex ];
  18874. }
  18875. _getValue_toArray( buffer, offset ) {
  18876. this.resolvedProperty.toArray( buffer, offset );
  18877. }
  18878. // Direct
  18879. _setValue_direct( buffer, offset ) {
  18880. this.targetObject[ this.propertyName ] = buffer[ offset ];
  18881. }
  18882. _setValue_direct_setNeedsUpdate( buffer, offset ) {
  18883. this.targetObject[ this.propertyName ] = buffer[ offset ];
  18884. this.targetObject.needsUpdate = true;
  18885. }
  18886. _setValue_direct_setMatrixWorldNeedsUpdate( buffer, offset ) {
  18887. this.targetObject[ this.propertyName ] = buffer[ offset ];
  18888. this.targetObject.matrixWorldNeedsUpdate = true;
  18889. }
  18890. // EntireArray
  18891. _setValue_array( buffer, offset ) {
  18892. const dest = this.resolvedProperty;
  18893. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  18894. dest[ i ] = buffer[ offset ++ ];
  18895. }
  18896. }
  18897. _setValue_array_setNeedsUpdate( buffer, offset ) {
  18898. const dest = this.resolvedProperty;
  18899. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  18900. dest[ i ] = buffer[ offset ++ ];
  18901. }
  18902. this.targetObject.needsUpdate = true;
  18903. }
  18904. _setValue_array_setMatrixWorldNeedsUpdate( buffer, offset ) {
  18905. const dest = this.resolvedProperty;
  18906. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  18907. dest[ i ] = buffer[ offset ++ ];
  18908. }
  18909. this.targetObject.matrixWorldNeedsUpdate = true;
  18910. }
  18911. // ArrayElement
  18912. _setValue_arrayElement( buffer, offset ) {
  18913. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  18914. }
  18915. _setValue_arrayElement_setNeedsUpdate( buffer, offset ) {
  18916. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  18917. this.targetObject.needsUpdate = true;
  18918. }
  18919. _setValue_arrayElement_setMatrixWorldNeedsUpdate( buffer, offset ) {
  18920. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  18921. this.targetObject.matrixWorldNeedsUpdate = true;
  18922. }
  18923. // HasToFromArray
  18924. _setValue_fromArray( buffer, offset ) {
  18925. this.resolvedProperty.fromArray( buffer, offset );
  18926. }
  18927. _setValue_fromArray_setNeedsUpdate( buffer, offset ) {
  18928. this.resolvedProperty.fromArray( buffer, offset );
  18929. this.targetObject.needsUpdate = true;
  18930. }
  18931. _setValue_fromArray_setMatrixWorldNeedsUpdate( buffer, offset ) {
  18932. this.resolvedProperty.fromArray( buffer, offset );
  18933. this.targetObject.matrixWorldNeedsUpdate = true;
  18934. }
  18935. _getValue_unbound( targetArray, offset ) {
  18936. this.bind();
  18937. this.getValue( targetArray, offset );
  18938. }
  18939. _setValue_unbound( sourceArray, offset ) {
  18940. this.bind();
  18941. this.setValue( sourceArray, offset );
  18942. }
  18943. // create getter / setter pair for a property in the scene graph
  18944. bind() {
  18945. let targetObject = this.node;
  18946. const parsedPath = this.parsedPath;
  18947. const objectName = parsedPath.objectName;
  18948. const propertyName = parsedPath.propertyName;
  18949. let propertyIndex = parsedPath.propertyIndex;
  18950. if ( ! targetObject ) {
  18951. targetObject = PropertyBinding.findNode( this.rootNode, parsedPath.nodeName );
  18952. this.node = targetObject;
  18953. }
  18954. // set fail state so we can just 'return' on error
  18955. this.getValue = this._getValue_unavailable;
  18956. this.setValue = this._setValue_unavailable;
  18957. // ensure there is a value node
  18958. if ( ! targetObject ) {
  18959. console.warn( 'THREE.PropertyBinding: No target node found for track: ' + this.path + '.' );
  18960. return;
  18961. }
  18962. if ( objectName ) {
  18963. let objectIndex = parsedPath.objectIndex;
  18964. // special cases were we need to reach deeper into the hierarchy to get the face materials....
  18965. switch ( objectName ) {
  18966. case 'materials':
  18967. if ( ! targetObject.material ) {
  18968. console.error( 'THREE.PropertyBinding: Can not bind to material as node does not have a material.', this );
  18969. return;
  18970. }
  18971. if ( ! targetObject.material.materials ) {
  18972. console.error( 'THREE.PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.', this );
  18973. return;
  18974. }
  18975. targetObject = targetObject.material.materials;
  18976. break;
  18977. case 'bones':
  18978. if ( ! targetObject.skeleton ) {
  18979. console.error( 'THREE.PropertyBinding: Can not bind to bones as node does not have a skeleton.', this );
  18980. return;
  18981. }
  18982. // potential future optimization: skip this if propertyIndex is already an integer
  18983. // and convert the integer string to a true integer.
  18984. targetObject = targetObject.skeleton.bones;
  18985. // support resolving morphTarget names into indices.
  18986. for ( let i = 0; i < targetObject.length; i ++ ) {
  18987. if ( targetObject[ i ].name === objectIndex ) {
  18988. objectIndex = i;
  18989. break;
  18990. }
  18991. }
  18992. break;
  18993. case 'map':
  18994. if ( 'map' in targetObject ) {
  18995. targetObject = targetObject.map;
  18996. break;
  18997. }
  18998. if ( ! targetObject.material ) {
  18999. console.error( 'THREE.PropertyBinding: Can not bind to material as node does not have a material.', this );
  19000. return;
  19001. }
  19002. if ( ! targetObject.material.map ) {
  19003. console.error( 'THREE.PropertyBinding: Can not bind to material.map as node.material does not have a map.', this );
  19004. return;
  19005. }
  19006. targetObject = targetObject.material.map;
  19007. break;
  19008. default:
  19009. if ( targetObject[ objectName ] === undefined ) {
  19010. console.error( 'THREE.PropertyBinding: Can not bind to objectName of node undefined.', this );
  19011. return;
  19012. }
  19013. targetObject = targetObject[ objectName ];
  19014. }
  19015. if ( objectIndex !== undefined ) {
  19016. if ( targetObject[ objectIndex ] === undefined ) {
  19017. console.error( 'THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.', this, targetObject );
  19018. return;
  19019. }
  19020. targetObject = targetObject[ objectIndex ];
  19021. }
  19022. }
  19023. // resolve property
  19024. const nodeProperty = targetObject[ propertyName ];
  19025. if ( nodeProperty === undefined ) {
  19026. const nodeName = parsedPath.nodeName;
  19027. console.error( 'THREE.PropertyBinding: Trying to update property for track: ' + nodeName +
  19028. '.' + propertyName + ' but it wasn\'t found.', targetObject );
  19029. return;
  19030. }
  19031. // determine versioning scheme
  19032. let versioning = this.Versioning.None;
  19033. this.targetObject = targetObject;
  19034. if ( targetObject.needsUpdate !== undefined ) { // material
  19035. versioning = this.Versioning.NeedsUpdate;
  19036. } else if ( targetObject.matrixWorldNeedsUpdate !== undefined ) { // node transform
  19037. versioning = this.Versioning.MatrixWorldNeedsUpdate;
  19038. }
  19039. // determine how the property gets bound
  19040. let bindingType = this.BindingType.Direct;
  19041. if ( propertyIndex !== undefined ) {
  19042. // access a sub element of the property array (only primitives are supported right now)
  19043. if ( propertyName === 'morphTargetInfluences' ) {
  19044. // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer.
  19045. // support resolving morphTarget names into indices.
  19046. if ( ! targetObject.geometry ) {
  19047. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.', this );
  19048. return;
  19049. }
  19050. if ( ! targetObject.geometry.morphAttributes ) {
  19051. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.', this );
  19052. return;
  19053. }
  19054. if ( targetObject.morphTargetDictionary[ propertyIndex ] !== undefined ) {
  19055. propertyIndex = targetObject.morphTargetDictionary[ propertyIndex ];
  19056. }
  19057. }
  19058. bindingType = this.BindingType.ArrayElement;
  19059. this.resolvedProperty = nodeProperty;
  19060. this.propertyIndex = propertyIndex;
  19061. } else if ( nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined ) {
  19062. // must use copy for Object3D.Euler/Quaternion
  19063. bindingType = this.BindingType.HasFromToArray;
  19064. this.resolvedProperty = nodeProperty;
  19065. } else if ( Array.isArray( nodeProperty ) ) {
  19066. bindingType = this.BindingType.EntireArray;
  19067. this.resolvedProperty = nodeProperty;
  19068. } else {
  19069. this.propertyName = propertyName;
  19070. }
  19071. // select getter / setter
  19072. this.getValue = this.GetterByBindingType[ bindingType ];
  19073. this.setValue = this.SetterByBindingTypeAndVersioning[ bindingType ][ versioning ];
  19074. }
  19075. unbind() {
  19076. this.node = null;
  19077. // back to the prototype version of getValue / setValue
  19078. // note: avoiding to mutate the shape of 'this' via 'delete'
  19079. this.getValue = this._getValue_unbound;
  19080. this.setValue = this._setValue_unbound;
  19081. }
  19082. }
  19083. PropertyBinding.Composite = Composite;
  19084. PropertyBinding.prototype.BindingType = {
  19085. Direct: 0,
  19086. EntireArray: 1,
  19087. ArrayElement: 2,
  19088. HasFromToArray: 3
  19089. };
  19090. PropertyBinding.prototype.Versioning = {
  19091. None: 0,
  19092. NeedsUpdate: 1,
  19093. MatrixWorldNeedsUpdate: 2
  19094. };
  19095. PropertyBinding.prototype.GetterByBindingType = [
  19096. PropertyBinding.prototype._getValue_direct,
  19097. PropertyBinding.prototype._getValue_array,
  19098. PropertyBinding.prototype._getValue_arrayElement,
  19099. PropertyBinding.prototype._getValue_toArray,
  19100. ];
  19101. PropertyBinding.prototype.SetterByBindingTypeAndVersioning = [
  19102. [
  19103. // Direct
  19104. PropertyBinding.prototype._setValue_direct,
  19105. PropertyBinding.prototype._setValue_direct_setNeedsUpdate,
  19106. PropertyBinding.prototype._setValue_direct_setMatrixWorldNeedsUpdate,
  19107. ], [
  19108. // EntireArray
  19109. PropertyBinding.prototype._setValue_array,
  19110. PropertyBinding.prototype._setValue_array_setNeedsUpdate,
  19111. PropertyBinding.prototype._setValue_array_setMatrixWorldNeedsUpdate,
  19112. ], [
  19113. // ArrayElement
  19114. PropertyBinding.prototype._setValue_arrayElement,
  19115. PropertyBinding.prototype._setValue_arrayElement_setNeedsUpdate,
  19116. PropertyBinding.prototype._setValue_arrayElement_setMatrixWorldNeedsUpdate,
  19117. ], [
  19118. // HasToFromArray
  19119. PropertyBinding.prototype._setValue_fromArray,
  19120. PropertyBinding.prototype._setValue_fromArray_setNeedsUpdate,
  19121. PropertyBinding.prototype._setValue_fromArray_setMatrixWorldNeedsUpdate,
  19122. ]
  19123. ];
  19124. /**
  19125. *
  19126. * A group of objects that receives a shared animation state.
  19127. *
  19128. * Usage:
  19129. *
  19130. * - Add objects you would otherwise pass as 'root' to the
  19131. * constructor or the .clipAction method of AnimationMixer.
  19132. *
  19133. * - Instead pass this object as 'root'.
  19134. *
  19135. * - You can also add and remove objects later when the mixer
  19136. * is running.
  19137. *
  19138. * Note:
  19139. *
  19140. * Objects of this class appear as one object to the mixer,
  19141. * so cache control of the individual objects must be done
  19142. * on the group.
  19143. *
  19144. * Limitation:
  19145. *
  19146. * - The animated properties must be compatible among the
  19147. * all objects in the group.
  19148. *
  19149. * - A single property can either be controlled through a
  19150. * target group or directly, but not both.
  19151. */
  19152. class AnimationObjectGroup {
  19153. constructor() {
  19154. this.isAnimationObjectGroup = true;
  19155. this.uuid = generateUUID();
  19156. // cached objects followed by the active ones
  19157. this._objects = Array.prototype.slice.call( arguments );
  19158. this.nCachedObjects_ = 0; // threshold
  19159. // note: read by PropertyBinding.Composite
  19160. const indices = {};
  19161. this._indicesByUUID = indices; // for bookkeeping
  19162. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  19163. indices[ arguments[ i ].uuid ] = i;
  19164. }
  19165. this._paths = []; // inside: string
  19166. this._parsedPaths = []; // inside: { we don't care, here }
  19167. this._bindings = []; // inside: Array< PropertyBinding >
  19168. this._bindingsIndicesByPath = {}; // inside: indices in these arrays
  19169. const scope = this;
  19170. this.stats = {
  19171. objects: {
  19172. get total() {
  19173. return scope._objects.length;
  19174. },
  19175. get inUse() {
  19176. return this.total - scope.nCachedObjects_;
  19177. }
  19178. },
  19179. get bindingsPerObject() {
  19180. return scope._bindings.length;
  19181. }
  19182. };
  19183. }
  19184. add() {
  19185. const objects = this._objects,
  19186. indicesByUUID = this._indicesByUUID,
  19187. paths = this._paths,
  19188. parsedPaths = this._parsedPaths,
  19189. bindings = this._bindings,
  19190. nBindings = bindings.length;
  19191. let knownObject = undefined,
  19192. nObjects = objects.length,
  19193. nCachedObjects = this.nCachedObjects_;
  19194. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  19195. const object = arguments[ i ],
  19196. uuid = object.uuid;
  19197. let index = indicesByUUID[ uuid ];
  19198. if ( index === undefined ) {
  19199. // unknown object -> add it to the ACTIVE region
  19200. index = nObjects ++;
  19201. indicesByUUID[ uuid ] = index;
  19202. objects.push( object );
  19203. // accounting is done, now do the same for all bindings
  19204. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  19205. bindings[ j ].push( new PropertyBinding( object, paths[ j ], parsedPaths[ j ] ) );
  19206. }
  19207. } else if ( index < nCachedObjects ) {
  19208. knownObject = objects[ index ];
  19209. // move existing object to the ACTIVE region
  19210. const firstActiveIndex = -- nCachedObjects,
  19211. lastCachedObject = objects[ firstActiveIndex ];
  19212. indicesByUUID[ lastCachedObject.uuid ] = index;
  19213. objects[ index ] = lastCachedObject;
  19214. indicesByUUID[ uuid ] = firstActiveIndex;
  19215. objects[ firstActiveIndex ] = object;
  19216. // accounting is done, now do the same for all bindings
  19217. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  19218. const bindingsForPath = bindings[ j ],
  19219. lastCached = bindingsForPath[ firstActiveIndex ];
  19220. let binding = bindingsForPath[ index ];
  19221. bindingsForPath[ index ] = lastCached;
  19222. if ( binding === undefined ) {
  19223. // since we do not bother to create new bindings
  19224. // for objects that are cached, the binding may
  19225. // or may not exist
  19226. binding = new PropertyBinding( object, paths[ j ], parsedPaths[ j ] );
  19227. }
  19228. bindingsForPath[ firstActiveIndex ] = binding;
  19229. }
  19230. } else if ( objects[ index ] !== knownObject ) {
  19231. console.error( 'THREE.AnimationObjectGroup: Different objects with the same UUID ' +
  19232. 'detected. Clean the caches or recreate your infrastructure when reloading scenes.' );
  19233. } // else the object is already where we want it to be
  19234. } // for arguments
  19235. this.nCachedObjects_ = nCachedObjects;
  19236. }
  19237. remove() {
  19238. const objects = this._objects,
  19239. indicesByUUID = this._indicesByUUID,
  19240. bindings = this._bindings,
  19241. nBindings = bindings.length;
  19242. let nCachedObjects = this.nCachedObjects_;
  19243. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  19244. const object = arguments[ i ],
  19245. uuid = object.uuid,
  19246. index = indicesByUUID[ uuid ];
  19247. if ( index !== undefined && index >= nCachedObjects ) {
  19248. // move existing object into the CACHED region
  19249. const lastCachedIndex = nCachedObjects ++,
  19250. firstActiveObject = objects[ lastCachedIndex ];
  19251. indicesByUUID[ firstActiveObject.uuid ] = index;
  19252. objects[ index ] = firstActiveObject;
  19253. indicesByUUID[ uuid ] = lastCachedIndex;
  19254. objects[ lastCachedIndex ] = object;
  19255. // accounting is done, now do the same for all bindings
  19256. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  19257. const bindingsForPath = bindings[ j ],
  19258. firstActive = bindingsForPath[ lastCachedIndex ],
  19259. binding = bindingsForPath[ index ];
  19260. bindingsForPath[ index ] = firstActive;
  19261. bindingsForPath[ lastCachedIndex ] = binding;
  19262. }
  19263. }
  19264. } // for arguments
  19265. this.nCachedObjects_ = nCachedObjects;
  19266. }
  19267. // remove & forget
  19268. uncache() {
  19269. const objects = this._objects,
  19270. indicesByUUID = this._indicesByUUID,
  19271. bindings = this._bindings,
  19272. nBindings = bindings.length;
  19273. let nCachedObjects = this.nCachedObjects_,
  19274. nObjects = objects.length;
  19275. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  19276. const object = arguments[ i ],
  19277. uuid = object.uuid,
  19278. index = indicesByUUID[ uuid ];
  19279. if ( index !== undefined ) {
  19280. delete indicesByUUID[ uuid ];
  19281. if ( index < nCachedObjects ) {
  19282. // object is cached, shrink the CACHED region
  19283. const firstActiveIndex = -- nCachedObjects,
  19284. lastCachedObject = objects[ firstActiveIndex ],
  19285. lastIndex = -- nObjects,
  19286. lastObject = objects[ lastIndex ];
  19287. // last cached object takes this object's place
  19288. indicesByUUID[ lastCachedObject.uuid ] = index;
  19289. objects[ index ] = lastCachedObject;
  19290. // last object goes to the activated slot and pop
  19291. indicesByUUID[ lastObject.uuid ] = firstActiveIndex;
  19292. objects[ firstActiveIndex ] = lastObject;
  19293. objects.pop();
  19294. // accounting is done, now do the same for all bindings
  19295. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  19296. const bindingsForPath = bindings[ j ],
  19297. lastCached = bindingsForPath[ firstActiveIndex ],
  19298. last = bindingsForPath[ lastIndex ];
  19299. bindingsForPath[ index ] = lastCached;
  19300. bindingsForPath[ firstActiveIndex ] = last;
  19301. bindingsForPath.pop();
  19302. }
  19303. } else {
  19304. // object is active, just swap with the last and pop
  19305. const lastIndex = -- nObjects,
  19306. lastObject = objects[ lastIndex ];
  19307. if ( lastIndex > 0 ) {
  19308. indicesByUUID[ lastObject.uuid ] = index;
  19309. }
  19310. objects[ index ] = lastObject;
  19311. objects.pop();
  19312. // accounting is done, now do the same for all bindings
  19313. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  19314. const bindingsForPath = bindings[ j ];
  19315. bindingsForPath[ index ] = bindingsForPath[ lastIndex ];
  19316. bindingsForPath.pop();
  19317. }
  19318. } // cached or active
  19319. } // if object is known
  19320. } // for arguments
  19321. this.nCachedObjects_ = nCachedObjects;
  19322. }
  19323. // Internal interface used by befriended PropertyBinding.Composite:
  19324. subscribe_( path, parsedPath ) {
  19325. // returns an array of bindings for the given path that is changed
  19326. // according to the contained objects in the group
  19327. const indicesByPath = this._bindingsIndicesByPath;
  19328. let index = indicesByPath[ path ];
  19329. const bindings = this._bindings;
  19330. if ( index !== undefined ) return bindings[ index ];
  19331. const paths = this._paths,
  19332. parsedPaths = this._parsedPaths,
  19333. objects = this._objects,
  19334. nObjects = objects.length,
  19335. nCachedObjects = this.nCachedObjects_,
  19336. bindingsForPath = new Array( nObjects );
  19337. index = bindings.length;
  19338. indicesByPath[ path ] = index;
  19339. paths.push( path );
  19340. parsedPaths.push( parsedPath );
  19341. bindings.push( bindingsForPath );
  19342. for ( let i = nCachedObjects, n = objects.length; i !== n; ++ i ) {
  19343. const object = objects[ i ];
  19344. bindingsForPath[ i ] = new PropertyBinding( object, path, parsedPath );
  19345. }
  19346. return bindingsForPath;
  19347. }
  19348. unsubscribe_( path ) {
  19349. // tells the group to forget about a property path and no longer
  19350. // update the array previously obtained with 'subscribe_'
  19351. const indicesByPath = this._bindingsIndicesByPath,
  19352. index = indicesByPath[ path ];
  19353. if ( index !== undefined ) {
  19354. const paths = this._paths,
  19355. parsedPaths = this._parsedPaths,
  19356. bindings = this._bindings,
  19357. lastBindingsIndex = bindings.length - 1,
  19358. lastBindings = bindings[ lastBindingsIndex ],
  19359. lastBindingsPath = path[ lastBindingsIndex ];
  19360. indicesByPath[ lastBindingsPath ] = index;
  19361. bindings[ index ] = lastBindings;
  19362. bindings.pop();
  19363. parsedPaths[ index ] = parsedPaths[ lastBindingsIndex ];
  19364. parsedPaths.pop();
  19365. paths[ index ] = paths[ lastBindingsIndex ];
  19366. paths.pop();
  19367. }
  19368. }
  19369. }
  19370. class AnimationAction {
  19371. constructor( mixer, clip, localRoot = null, blendMode = clip.blendMode ) {
  19372. this._mixer = mixer;
  19373. this._clip = clip;
  19374. this._localRoot = localRoot;
  19375. this.blendMode = blendMode;
  19376. const tracks = clip.tracks,
  19377. nTracks = tracks.length,
  19378. interpolants = new Array( nTracks );
  19379. const interpolantSettings = {
  19380. endingStart: ZeroCurvatureEnding,
  19381. endingEnd: ZeroCurvatureEnding
  19382. };
  19383. for ( let i = 0; i !== nTracks; ++ i ) {
  19384. const interpolant = tracks[ i ].createInterpolant( null );
  19385. interpolants[ i ] = interpolant;
  19386. interpolant.settings = interpolantSettings;
  19387. }
  19388. this._interpolantSettings = interpolantSettings;
  19389. this._interpolants = interpolants; // bound by the mixer
  19390. // inside: PropertyMixer (managed by the mixer)
  19391. this._propertyBindings = new Array( nTracks );
  19392. this._cacheIndex = null; // for the memory manager
  19393. this._byClipCacheIndex = null; // for the memory manager
  19394. this._timeScaleInterpolant = null;
  19395. this._weightInterpolant = null;
  19396. this.loop = LoopRepeat;
  19397. this._loopCount = - 1;
  19398. // global mixer time when the action is to be started
  19399. // it's set back to 'null' upon start of the action
  19400. this._startTime = null;
  19401. // scaled local time of the action
  19402. // gets clamped or wrapped to 0..clip.duration according to loop
  19403. this.time = 0;
  19404. this.timeScale = 1;
  19405. this._effectiveTimeScale = 1;
  19406. this.weight = 1;
  19407. this._effectiveWeight = 1;
  19408. this.repetitions = Infinity; // no. of repetitions when looping
  19409. this.paused = false; // true -> zero effective time scale
  19410. this.enabled = true; // false -> zero effective weight
  19411. this.clampWhenFinished = false;// keep feeding the last frame?
  19412. this.zeroSlopeAtStart = true;// for smooth interpolation w/o separate
  19413. this.zeroSlopeAtEnd = true;// clips for start, loop and end
  19414. }
  19415. // State & Scheduling
  19416. play() {
  19417. this._mixer._activateAction( this );
  19418. return this;
  19419. }
  19420. stop() {
  19421. this._mixer._deactivateAction( this );
  19422. return this.reset();
  19423. }
  19424. reset() {
  19425. this.paused = false;
  19426. this.enabled = true;
  19427. this.time = 0; // restart clip
  19428. this._loopCount = - 1;// forget previous loops
  19429. this._startTime = null;// forget scheduling
  19430. return this.stopFading().stopWarping();
  19431. }
  19432. isRunning() {
  19433. return this.enabled && ! this.paused && this.timeScale !== 0 &&
  19434. this._startTime === null && this._mixer._isActiveAction( this );
  19435. }
  19436. // return true when play has been called
  19437. isScheduled() {
  19438. return this._mixer._isActiveAction( this );
  19439. }
  19440. startAt( time ) {
  19441. this._startTime = time;
  19442. return this;
  19443. }
  19444. setLoop( mode, repetitions ) {
  19445. this.loop = mode;
  19446. this.repetitions = repetitions;
  19447. return this;
  19448. }
  19449. // Weight
  19450. // set the weight stopping any scheduled fading
  19451. // although .enabled = false yields an effective weight of zero, this
  19452. // method does *not* change .enabled, because it would be confusing
  19453. setEffectiveWeight( weight ) {
  19454. this.weight = weight;
  19455. // note: same logic as when updated at runtime
  19456. this._effectiveWeight = this.enabled ? weight : 0;
  19457. return this.stopFading();
  19458. }
  19459. // return the weight considering fading and .enabled
  19460. getEffectiveWeight() {
  19461. return this._effectiveWeight;
  19462. }
  19463. fadeIn( duration ) {
  19464. return this._scheduleFading( duration, 0, 1 );
  19465. }
  19466. fadeOut( duration ) {
  19467. return this._scheduleFading( duration, 1, 0 );
  19468. }
  19469. crossFadeFrom( fadeOutAction, duration, warp ) {
  19470. fadeOutAction.fadeOut( duration );
  19471. this.fadeIn( duration );
  19472. if ( warp ) {
  19473. const fadeInDuration = this._clip.duration,
  19474. fadeOutDuration = fadeOutAction._clip.duration,
  19475. startEndRatio = fadeOutDuration / fadeInDuration,
  19476. endStartRatio = fadeInDuration / fadeOutDuration;
  19477. fadeOutAction.warp( 1.0, startEndRatio, duration );
  19478. this.warp( endStartRatio, 1.0, duration );
  19479. }
  19480. return this;
  19481. }
  19482. crossFadeTo( fadeInAction, duration, warp ) {
  19483. return fadeInAction.crossFadeFrom( this, duration, warp );
  19484. }
  19485. stopFading() {
  19486. const weightInterpolant = this._weightInterpolant;
  19487. if ( weightInterpolant !== null ) {
  19488. this._weightInterpolant = null;
  19489. this._mixer._takeBackControlInterpolant( weightInterpolant );
  19490. }
  19491. return this;
  19492. }
  19493. // Time Scale Control
  19494. // set the time scale stopping any scheduled warping
  19495. // although .paused = true yields an effective time scale of zero, this
  19496. // method does *not* change .paused, because it would be confusing
  19497. setEffectiveTimeScale( timeScale ) {
  19498. this.timeScale = timeScale;
  19499. this._effectiveTimeScale = this.paused ? 0 : timeScale;
  19500. return this.stopWarping();
  19501. }
  19502. // return the time scale considering warping and .paused
  19503. getEffectiveTimeScale() {
  19504. return this._effectiveTimeScale;
  19505. }
  19506. setDuration( duration ) {
  19507. this.timeScale = this._clip.duration / duration;
  19508. return this.stopWarping();
  19509. }
  19510. syncWith( action ) {
  19511. this.time = action.time;
  19512. this.timeScale = action.timeScale;
  19513. return this.stopWarping();
  19514. }
  19515. halt( duration ) {
  19516. return this.warp( this._effectiveTimeScale, 0, duration );
  19517. }
  19518. warp( startTimeScale, endTimeScale, duration ) {
  19519. const mixer = this._mixer,
  19520. now = mixer.time,
  19521. timeScale = this.timeScale;
  19522. let interpolant = this._timeScaleInterpolant;
  19523. if ( interpolant === null ) {
  19524. interpolant = mixer._lendControlInterpolant();
  19525. this._timeScaleInterpolant = interpolant;
  19526. }
  19527. const times = interpolant.parameterPositions,
  19528. values = interpolant.sampleValues;
  19529. times[ 0 ] = now;
  19530. times[ 1 ] = now + duration;
  19531. values[ 0 ] = startTimeScale / timeScale;
  19532. values[ 1 ] = endTimeScale / timeScale;
  19533. return this;
  19534. }
  19535. stopWarping() {
  19536. const timeScaleInterpolant = this._timeScaleInterpolant;
  19537. if ( timeScaleInterpolant !== null ) {
  19538. this._timeScaleInterpolant = null;
  19539. this._mixer._takeBackControlInterpolant( timeScaleInterpolant );
  19540. }
  19541. return this;
  19542. }
  19543. // Object Accessors
  19544. getMixer() {
  19545. return this._mixer;
  19546. }
  19547. getClip() {
  19548. return this._clip;
  19549. }
  19550. getRoot() {
  19551. return this._localRoot || this._mixer._root;
  19552. }
  19553. // Interna
  19554. _update( time, deltaTime, timeDirection, accuIndex ) {
  19555. // called by the mixer
  19556. if ( ! this.enabled ) {
  19557. // call ._updateWeight() to update ._effectiveWeight
  19558. this._updateWeight( time );
  19559. return;
  19560. }
  19561. const startTime = this._startTime;
  19562. if ( startTime !== null ) {
  19563. // check for scheduled start of action
  19564. const timeRunning = ( time - startTime ) * timeDirection;
  19565. if ( timeRunning < 0 || timeDirection === 0 ) {
  19566. deltaTime = 0;
  19567. } else {
  19568. this._startTime = null; // unschedule
  19569. deltaTime = timeDirection * timeRunning;
  19570. }
  19571. }
  19572. // apply time scale and advance time
  19573. deltaTime *= this._updateTimeScale( time );
  19574. const clipTime = this._updateTime( deltaTime );
  19575. // note: _updateTime may disable the action resulting in
  19576. // an effective weight of 0
  19577. const weight = this._updateWeight( time );
  19578. if ( weight > 0 ) {
  19579. const interpolants = this._interpolants;
  19580. const propertyMixers = this._propertyBindings;
  19581. switch ( this.blendMode ) {
  19582. case AdditiveAnimationBlendMode:
  19583. for ( let j = 0, m = interpolants.length; j !== m; ++ j ) {
  19584. interpolants[ j ].evaluate( clipTime );
  19585. propertyMixers[ j ].accumulateAdditive( weight );
  19586. }
  19587. break;
  19588. case NormalAnimationBlendMode:
  19589. default:
  19590. for ( let j = 0, m = interpolants.length; j !== m; ++ j ) {
  19591. interpolants[ j ].evaluate( clipTime );
  19592. propertyMixers[ j ].accumulate( accuIndex, weight );
  19593. }
  19594. }
  19595. }
  19596. }
  19597. _updateWeight( time ) {
  19598. let weight = 0;
  19599. if ( this.enabled ) {
  19600. weight = this.weight;
  19601. const interpolant = this._weightInterpolant;
  19602. if ( interpolant !== null ) {
  19603. const interpolantValue = interpolant.evaluate( time )[ 0 ];
  19604. weight *= interpolantValue;
  19605. if ( time > interpolant.parameterPositions[ 1 ] ) {
  19606. this.stopFading();
  19607. if ( interpolantValue === 0 ) {
  19608. // faded out, disable
  19609. this.enabled = false;
  19610. }
  19611. }
  19612. }
  19613. }
  19614. this._effectiveWeight = weight;
  19615. return weight;
  19616. }
  19617. _updateTimeScale( time ) {
  19618. let timeScale = 0;
  19619. if ( ! this.paused ) {
  19620. timeScale = this.timeScale;
  19621. const interpolant = this._timeScaleInterpolant;
  19622. if ( interpolant !== null ) {
  19623. const interpolantValue = interpolant.evaluate( time )[ 0 ];
  19624. timeScale *= interpolantValue;
  19625. if ( time > interpolant.parameterPositions[ 1 ] ) {
  19626. this.stopWarping();
  19627. if ( timeScale === 0 ) {
  19628. // motion has halted, pause
  19629. this.paused = true;
  19630. } else {
  19631. // warp done - apply final time scale
  19632. this.timeScale = timeScale;
  19633. }
  19634. }
  19635. }
  19636. }
  19637. this._effectiveTimeScale = timeScale;
  19638. return timeScale;
  19639. }
  19640. _updateTime( deltaTime ) {
  19641. const duration = this._clip.duration;
  19642. const loop = this.loop;
  19643. let time = this.time + deltaTime;
  19644. let loopCount = this._loopCount;
  19645. const pingPong = ( loop === LoopPingPong );
  19646. if ( deltaTime === 0 ) {
  19647. if ( loopCount === - 1 ) return time;
  19648. return ( pingPong && ( loopCount & 1 ) === 1 ) ? duration - time : time;
  19649. }
  19650. if ( loop === LoopOnce ) {
  19651. if ( loopCount === - 1 ) {
  19652. // just started
  19653. this._loopCount = 0;
  19654. this._setEndings( true, true, false );
  19655. }
  19656. handle_stop: {
  19657. if ( time >= duration ) {
  19658. time = duration;
  19659. } else if ( time < 0 ) {
  19660. time = 0;
  19661. } else {
  19662. this.time = time;
  19663. break handle_stop;
  19664. }
  19665. if ( this.clampWhenFinished ) this.paused = true;
  19666. else this.enabled = false;
  19667. this.time = time;
  19668. this._mixer.dispatchEvent( {
  19669. type: 'finished', action: this,
  19670. direction: deltaTime < 0 ? - 1 : 1
  19671. } );
  19672. }
  19673. } else { // repetitive Repeat or PingPong
  19674. if ( loopCount === - 1 ) {
  19675. // just started
  19676. if ( deltaTime >= 0 ) {
  19677. loopCount = 0;
  19678. this._setEndings( true, this.repetitions === 0, pingPong );
  19679. } else {
  19680. // when looping in reverse direction, the initial
  19681. // transition through zero counts as a repetition,
  19682. // so leave loopCount at -1
  19683. this._setEndings( this.repetitions === 0, true, pingPong );
  19684. }
  19685. }
  19686. if ( time >= duration || time < 0 ) {
  19687. // wrap around
  19688. const loopDelta = Math.floor( time / duration ); // signed
  19689. time -= duration * loopDelta;
  19690. loopCount += Math.abs( loopDelta );
  19691. const pending = this.repetitions - loopCount;
  19692. if ( pending <= 0 ) {
  19693. // have to stop (switch state, clamp time, fire event)
  19694. if ( this.clampWhenFinished ) this.paused = true;
  19695. else this.enabled = false;
  19696. time = deltaTime > 0 ? duration : 0;
  19697. this.time = time;
  19698. this._mixer.dispatchEvent( {
  19699. type: 'finished', action: this,
  19700. direction: deltaTime > 0 ? 1 : - 1
  19701. } );
  19702. } else {
  19703. // keep running
  19704. if ( pending === 1 ) {
  19705. // entering the last round
  19706. const atStart = deltaTime < 0;
  19707. this._setEndings( atStart, ! atStart, pingPong );
  19708. } else {
  19709. this._setEndings( false, false, pingPong );
  19710. }
  19711. this._loopCount = loopCount;
  19712. this.time = time;
  19713. this._mixer.dispatchEvent( {
  19714. type: 'loop', action: this, loopDelta: loopDelta
  19715. } );
  19716. }
  19717. } else {
  19718. this.time = time;
  19719. }
  19720. if ( pingPong && ( loopCount & 1 ) === 1 ) {
  19721. // invert time for the "pong round"
  19722. return duration - time;
  19723. }
  19724. }
  19725. return time;
  19726. }
  19727. _setEndings( atStart, atEnd, pingPong ) {
  19728. const settings = this._interpolantSettings;
  19729. if ( pingPong ) {
  19730. settings.endingStart = ZeroSlopeEnding;
  19731. settings.endingEnd = ZeroSlopeEnding;
  19732. } else {
  19733. // assuming for LoopOnce atStart == atEnd == true
  19734. if ( atStart ) {
  19735. settings.endingStart = this.zeroSlopeAtStart ? ZeroSlopeEnding : ZeroCurvatureEnding;
  19736. } else {
  19737. settings.endingStart = WrapAroundEnding;
  19738. }
  19739. if ( atEnd ) {
  19740. settings.endingEnd = this.zeroSlopeAtEnd ? ZeroSlopeEnding : ZeroCurvatureEnding;
  19741. } else {
  19742. settings.endingEnd = WrapAroundEnding;
  19743. }
  19744. }
  19745. }
  19746. _scheduleFading( duration, weightNow, weightThen ) {
  19747. const mixer = this._mixer, now = mixer.time;
  19748. let interpolant = this._weightInterpolant;
  19749. if ( interpolant === null ) {
  19750. interpolant = mixer._lendControlInterpolant();
  19751. this._weightInterpolant = interpolant;
  19752. }
  19753. const times = interpolant.parameterPositions,
  19754. values = interpolant.sampleValues;
  19755. times[ 0 ] = now;
  19756. values[ 0 ] = weightNow;
  19757. times[ 1 ] = now + duration;
  19758. values[ 1 ] = weightThen;
  19759. return this;
  19760. }
  19761. }
  19762. const _controlInterpolantsResultBuffer = new Float32Array( 1 );
  19763. class AnimationMixer extends EventDispatcher {
  19764. constructor( root ) {
  19765. super();
  19766. this._root = root;
  19767. this._initMemoryManager();
  19768. this._accuIndex = 0;
  19769. this.time = 0;
  19770. this.timeScale = 1.0;
  19771. }
  19772. _bindAction( action, prototypeAction ) {
  19773. const root = action._localRoot || this._root,
  19774. tracks = action._clip.tracks,
  19775. nTracks = tracks.length,
  19776. bindings = action._propertyBindings,
  19777. interpolants = action._interpolants,
  19778. rootUuid = root.uuid,
  19779. bindingsByRoot = this._bindingsByRootAndName;
  19780. let bindingsByName = bindingsByRoot[ rootUuid ];
  19781. if ( bindingsByName === undefined ) {
  19782. bindingsByName = {};
  19783. bindingsByRoot[ rootUuid ] = bindingsByName;
  19784. }
  19785. for ( let i = 0; i !== nTracks; ++ i ) {
  19786. const track = tracks[ i ],
  19787. trackName = track.name;
  19788. let binding = bindingsByName[ trackName ];
  19789. if ( binding !== undefined ) {
  19790. ++ binding.referenceCount;
  19791. bindings[ i ] = binding;
  19792. } else {
  19793. binding = bindings[ i ];
  19794. if ( binding !== undefined ) {
  19795. // existing binding, make sure the cache knows
  19796. if ( binding._cacheIndex === null ) {
  19797. ++ binding.referenceCount;
  19798. this._addInactiveBinding( binding, rootUuid, trackName );
  19799. }
  19800. continue;
  19801. }
  19802. const path = prototypeAction && prototypeAction.
  19803. _propertyBindings[ i ].binding.parsedPath;
  19804. binding = new PropertyMixer(
  19805. PropertyBinding.create( root, trackName, path ),
  19806. track.ValueTypeName, track.getValueSize() );
  19807. ++ binding.referenceCount;
  19808. this._addInactiveBinding( binding, rootUuid, trackName );
  19809. bindings[ i ] = binding;
  19810. }
  19811. interpolants[ i ].resultBuffer = binding.buffer;
  19812. }
  19813. }
  19814. _activateAction( action ) {
  19815. if ( ! this._isActiveAction( action ) ) {
  19816. if ( action._cacheIndex === null ) {
  19817. // this action has been forgotten by the cache, but the user
  19818. // appears to be still using it -> rebind
  19819. const rootUuid = ( action._localRoot || this._root ).uuid,
  19820. clipUuid = action._clip.uuid,
  19821. actionsForClip = this._actionsByClip[ clipUuid ];
  19822. this._bindAction( action,
  19823. actionsForClip && actionsForClip.knownActions[ 0 ] );
  19824. this._addInactiveAction( action, clipUuid, rootUuid );
  19825. }
  19826. const bindings = action._propertyBindings;
  19827. // increment reference counts / sort out state
  19828. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  19829. const binding = bindings[ i ];
  19830. if ( binding.useCount ++ === 0 ) {
  19831. this._lendBinding( binding );
  19832. binding.saveOriginalState();
  19833. }
  19834. }
  19835. this._lendAction( action );
  19836. }
  19837. }
  19838. _deactivateAction( action ) {
  19839. if ( this._isActiveAction( action ) ) {
  19840. const bindings = action._propertyBindings;
  19841. // decrement reference counts / sort out state
  19842. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  19843. const binding = bindings[ i ];
  19844. if ( -- binding.useCount === 0 ) {
  19845. binding.restoreOriginalState();
  19846. this._takeBackBinding( binding );
  19847. }
  19848. }
  19849. this._takeBackAction( action );
  19850. }
  19851. }
  19852. // Memory manager
  19853. _initMemoryManager() {
  19854. this._actions = []; // 'nActiveActions' followed by inactive ones
  19855. this._nActiveActions = 0;
  19856. this._actionsByClip = {};
  19857. // inside:
  19858. // {
  19859. // knownActions: Array< AnimationAction > - used as prototypes
  19860. // actionByRoot: AnimationAction - lookup
  19861. // }
  19862. this._bindings = []; // 'nActiveBindings' followed by inactive ones
  19863. this._nActiveBindings = 0;
  19864. this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer >
  19865. this._controlInterpolants = []; // same game as above
  19866. this._nActiveControlInterpolants = 0;
  19867. const scope = this;
  19868. this.stats = {
  19869. actions: {
  19870. get total() {
  19871. return scope._actions.length;
  19872. },
  19873. get inUse() {
  19874. return scope._nActiveActions;
  19875. }
  19876. },
  19877. bindings: {
  19878. get total() {
  19879. return scope._bindings.length;
  19880. },
  19881. get inUse() {
  19882. return scope._nActiveBindings;
  19883. }
  19884. },
  19885. controlInterpolants: {
  19886. get total() {
  19887. return scope._controlInterpolants.length;
  19888. },
  19889. get inUse() {
  19890. return scope._nActiveControlInterpolants;
  19891. }
  19892. }
  19893. };
  19894. }
  19895. // Memory management for AnimationAction objects
  19896. _isActiveAction( action ) {
  19897. const index = action._cacheIndex;
  19898. return index !== null && index < this._nActiveActions;
  19899. }
  19900. _addInactiveAction( action, clipUuid, rootUuid ) {
  19901. const actions = this._actions,
  19902. actionsByClip = this._actionsByClip;
  19903. let actionsForClip = actionsByClip[ clipUuid ];
  19904. if ( actionsForClip === undefined ) {
  19905. actionsForClip = {
  19906. knownActions: [ action ],
  19907. actionByRoot: {}
  19908. };
  19909. action._byClipCacheIndex = 0;
  19910. actionsByClip[ clipUuid ] = actionsForClip;
  19911. } else {
  19912. const knownActions = actionsForClip.knownActions;
  19913. action._byClipCacheIndex = knownActions.length;
  19914. knownActions.push( action );
  19915. }
  19916. action._cacheIndex = actions.length;
  19917. actions.push( action );
  19918. actionsForClip.actionByRoot[ rootUuid ] = action;
  19919. }
  19920. _removeInactiveAction( action ) {
  19921. const actions = this._actions,
  19922. lastInactiveAction = actions[ actions.length - 1 ],
  19923. cacheIndex = action._cacheIndex;
  19924. lastInactiveAction._cacheIndex = cacheIndex;
  19925. actions[ cacheIndex ] = lastInactiveAction;
  19926. actions.pop();
  19927. action._cacheIndex = null;
  19928. const clipUuid = action._clip.uuid,
  19929. actionsByClip = this._actionsByClip,
  19930. actionsForClip = actionsByClip[ clipUuid ],
  19931. knownActionsForClip = actionsForClip.knownActions,
  19932. lastKnownAction =
  19933. knownActionsForClip[ knownActionsForClip.length - 1 ],
  19934. byClipCacheIndex = action._byClipCacheIndex;
  19935. lastKnownAction._byClipCacheIndex = byClipCacheIndex;
  19936. knownActionsForClip[ byClipCacheIndex ] = lastKnownAction;
  19937. knownActionsForClip.pop();
  19938. action._byClipCacheIndex = null;
  19939. const actionByRoot = actionsForClip.actionByRoot,
  19940. rootUuid = ( action._localRoot || this._root ).uuid;
  19941. delete actionByRoot[ rootUuid ];
  19942. if ( knownActionsForClip.length === 0 ) {
  19943. delete actionsByClip[ clipUuid ];
  19944. }
  19945. this._removeInactiveBindingsForAction( action );
  19946. }
  19947. _removeInactiveBindingsForAction( action ) {
  19948. const bindings = action._propertyBindings;
  19949. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  19950. const binding = bindings[ i ];
  19951. if ( -- binding.referenceCount === 0 ) {
  19952. this._removeInactiveBinding( binding );
  19953. }
  19954. }
  19955. }
  19956. _lendAction( action ) {
  19957. // [ active actions | inactive actions ]
  19958. // [ active actions >| inactive actions ]
  19959. // s a
  19960. // <-swap->
  19961. // a s
  19962. const actions = this._actions,
  19963. prevIndex = action._cacheIndex,
  19964. lastActiveIndex = this._nActiveActions ++,
  19965. firstInactiveAction = actions[ lastActiveIndex ];
  19966. action._cacheIndex = lastActiveIndex;
  19967. actions[ lastActiveIndex ] = action;
  19968. firstInactiveAction._cacheIndex = prevIndex;
  19969. actions[ prevIndex ] = firstInactiveAction;
  19970. }
  19971. _takeBackAction( action ) {
  19972. // [ active actions | inactive actions ]
  19973. // [ active actions |< inactive actions ]
  19974. // a s
  19975. // <-swap->
  19976. // s a
  19977. const actions = this._actions,
  19978. prevIndex = action._cacheIndex,
  19979. firstInactiveIndex = -- this._nActiveActions,
  19980. lastActiveAction = actions[ firstInactiveIndex ];
  19981. action._cacheIndex = firstInactiveIndex;
  19982. actions[ firstInactiveIndex ] = action;
  19983. lastActiveAction._cacheIndex = prevIndex;
  19984. actions[ prevIndex ] = lastActiveAction;
  19985. }
  19986. // Memory management for PropertyMixer objects
  19987. _addInactiveBinding( binding, rootUuid, trackName ) {
  19988. const bindingsByRoot = this._bindingsByRootAndName,
  19989. bindings = this._bindings;
  19990. let bindingByName = bindingsByRoot[ rootUuid ];
  19991. if ( bindingByName === undefined ) {
  19992. bindingByName = {};
  19993. bindingsByRoot[ rootUuid ] = bindingByName;
  19994. }
  19995. bindingByName[ trackName ] = binding;
  19996. binding._cacheIndex = bindings.length;
  19997. bindings.push( binding );
  19998. }
  19999. _removeInactiveBinding( binding ) {
  20000. const bindings = this._bindings,
  20001. propBinding = binding.binding,
  20002. rootUuid = propBinding.rootNode.uuid,
  20003. trackName = propBinding.path,
  20004. bindingsByRoot = this._bindingsByRootAndName,
  20005. bindingByName = bindingsByRoot[ rootUuid ],
  20006. lastInactiveBinding = bindings[ bindings.length - 1 ],
  20007. cacheIndex = binding._cacheIndex;
  20008. lastInactiveBinding._cacheIndex = cacheIndex;
  20009. bindings[ cacheIndex ] = lastInactiveBinding;
  20010. bindings.pop();
  20011. delete bindingByName[ trackName ];
  20012. if ( Object.keys( bindingByName ).length === 0 ) {
  20013. delete bindingsByRoot[ rootUuid ];
  20014. }
  20015. }
  20016. _lendBinding( binding ) {
  20017. const bindings = this._bindings,
  20018. prevIndex = binding._cacheIndex,
  20019. lastActiveIndex = this._nActiveBindings ++,
  20020. firstInactiveBinding = bindings[ lastActiveIndex ];
  20021. binding._cacheIndex = lastActiveIndex;
  20022. bindings[ lastActiveIndex ] = binding;
  20023. firstInactiveBinding._cacheIndex = prevIndex;
  20024. bindings[ prevIndex ] = firstInactiveBinding;
  20025. }
  20026. _takeBackBinding( binding ) {
  20027. const bindings = this._bindings,
  20028. prevIndex = binding._cacheIndex,
  20029. firstInactiveIndex = -- this._nActiveBindings,
  20030. lastActiveBinding = bindings[ firstInactiveIndex ];
  20031. binding._cacheIndex = firstInactiveIndex;
  20032. bindings[ firstInactiveIndex ] = binding;
  20033. lastActiveBinding._cacheIndex = prevIndex;
  20034. bindings[ prevIndex ] = lastActiveBinding;
  20035. }
  20036. // Memory management of Interpolants for weight and time scale
  20037. _lendControlInterpolant() {
  20038. const interpolants = this._controlInterpolants,
  20039. lastActiveIndex = this._nActiveControlInterpolants ++;
  20040. let interpolant = interpolants[ lastActiveIndex ];
  20041. if ( interpolant === undefined ) {
  20042. interpolant = new LinearInterpolant(
  20043. new Float32Array( 2 ), new Float32Array( 2 ),
  20044. 1, _controlInterpolantsResultBuffer );
  20045. interpolant.__cacheIndex = lastActiveIndex;
  20046. interpolants[ lastActiveIndex ] = interpolant;
  20047. }
  20048. return interpolant;
  20049. }
  20050. _takeBackControlInterpolant( interpolant ) {
  20051. const interpolants = this._controlInterpolants,
  20052. prevIndex = interpolant.__cacheIndex,
  20053. firstInactiveIndex = -- this._nActiveControlInterpolants,
  20054. lastActiveInterpolant = interpolants[ firstInactiveIndex ];
  20055. interpolant.__cacheIndex = firstInactiveIndex;
  20056. interpolants[ firstInactiveIndex ] = interpolant;
  20057. lastActiveInterpolant.__cacheIndex = prevIndex;
  20058. interpolants[ prevIndex ] = lastActiveInterpolant;
  20059. }
  20060. // return an action for a clip optionally using a custom root target
  20061. // object (this method allocates a lot of dynamic memory in case a
  20062. // previously unknown clip/root combination is specified)
  20063. clipAction( clip, optionalRoot, blendMode ) {
  20064. const root = optionalRoot || this._root,
  20065. rootUuid = root.uuid;
  20066. let clipObject = typeof clip === 'string' ? AnimationClip.findByName( root, clip ) : clip;
  20067. const clipUuid = clipObject !== null ? clipObject.uuid : clip;
  20068. const actionsForClip = this._actionsByClip[ clipUuid ];
  20069. let prototypeAction = null;
  20070. if ( blendMode === undefined ) {
  20071. if ( clipObject !== null ) {
  20072. blendMode = clipObject.blendMode;
  20073. } else {
  20074. blendMode = NormalAnimationBlendMode;
  20075. }
  20076. }
  20077. if ( actionsForClip !== undefined ) {
  20078. const existingAction = actionsForClip.actionByRoot[ rootUuid ];
  20079. if ( existingAction !== undefined && existingAction.blendMode === blendMode ) {
  20080. return existingAction;
  20081. }
  20082. // we know the clip, so we don't have to parse all
  20083. // the bindings again but can just copy
  20084. prototypeAction = actionsForClip.knownActions[ 0 ];
  20085. // also, take the clip from the prototype action
  20086. if ( clipObject === null )
  20087. clipObject = prototypeAction._clip;
  20088. }
  20089. // clip must be known when specified via string
  20090. if ( clipObject === null ) return null;
  20091. // allocate all resources required to run it
  20092. const newAction = new AnimationAction( this, clipObject, optionalRoot, blendMode );
  20093. this._bindAction( newAction, prototypeAction );
  20094. // and make the action known to the memory manager
  20095. this._addInactiveAction( newAction, clipUuid, rootUuid );
  20096. return newAction;
  20097. }
  20098. // get an existing action
  20099. existingAction( clip, optionalRoot ) {
  20100. const root = optionalRoot || this._root,
  20101. rootUuid = root.uuid,
  20102. clipObject = typeof clip === 'string' ?
  20103. AnimationClip.findByName( root, clip ) : clip,
  20104. clipUuid = clipObject ? clipObject.uuid : clip,
  20105. actionsForClip = this._actionsByClip[ clipUuid ];
  20106. if ( actionsForClip !== undefined ) {
  20107. return actionsForClip.actionByRoot[ rootUuid ] || null;
  20108. }
  20109. return null;
  20110. }
  20111. // deactivates all previously scheduled actions
  20112. stopAllAction() {
  20113. const actions = this._actions,
  20114. nActions = this._nActiveActions;
  20115. for ( let i = nActions - 1; i >= 0; -- i ) {
  20116. actions[ i ].stop();
  20117. }
  20118. return this;
  20119. }
  20120. // advance the time and update apply the animation
  20121. update( deltaTime ) {
  20122. deltaTime *= this.timeScale;
  20123. const actions = this._actions,
  20124. nActions = this._nActiveActions,
  20125. time = this.time += deltaTime,
  20126. timeDirection = Math.sign( deltaTime ),
  20127. accuIndex = this._accuIndex ^= 1;
  20128. // run active actions
  20129. for ( let i = 0; i !== nActions; ++ i ) {
  20130. const action = actions[ i ];
  20131. action._update( time, deltaTime, timeDirection, accuIndex );
  20132. }
  20133. // update scene graph
  20134. const bindings = this._bindings,
  20135. nBindings = this._nActiveBindings;
  20136. for ( let i = 0; i !== nBindings; ++ i ) {
  20137. bindings[ i ].apply( accuIndex );
  20138. }
  20139. return this;
  20140. }
  20141. // Allows you to seek to a specific time in an animation.
  20142. setTime( timeInSeconds ) {
  20143. this.time = 0; // Zero out time attribute for AnimationMixer object;
  20144. for ( let i = 0; i < this._actions.length; i ++ ) {
  20145. this._actions[ i ].time = 0; // Zero out time attribute for all associated AnimationAction objects.
  20146. }
  20147. return this.update( timeInSeconds ); // Update used to set exact time. Returns "this" AnimationMixer object.
  20148. }
  20149. // return this mixer's root target object
  20150. getRoot() {
  20151. return this._root;
  20152. }
  20153. // free all resources specific to a particular clip
  20154. uncacheClip( clip ) {
  20155. const actions = this._actions,
  20156. clipUuid = clip.uuid,
  20157. actionsByClip = this._actionsByClip,
  20158. actionsForClip = actionsByClip[ clipUuid ];
  20159. if ( actionsForClip !== undefined ) {
  20160. // note: just calling _removeInactiveAction would mess up the
  20161. // iteration state and also require updating the state we can
  20162. // just throw away
  20163. const actionsToRemove = actionsForClip.knownActions;
  20164. for ( let i = 0, n = actionsToRemove.length; i !== n; ++ i ) {
  20165. const action = actionsToRemove[ i ];
  20166. this._deactivateAction( action );
  20167. const cacheIndex = action._cacheIndex,
  20168. lastInactiveAction = actions[ actions.length - 1 ];
  20169. action._cacheIndex = null;
  20170. action._byClipCacheIndex = null;
  20171. lastInactiveAction._cacheIndex = cacheIndex;
  20172. actions[ cacheIndex ] = lastInactiveAction;
  20173. actions.pop();
  20174. this._removeInactiveBindingsForAction( action );
  20175. }
  20176. delete actionsByClip[ clipUuid ];
  20177. }
  20178. }
  20179. // free all resources specific to a particular root target object
  20180. uncacheRoot( root ) {
  20181. const rootUuid = root.uuid,
  20182. actionsByClip = this._actionsByClip;
  20183. for ( const clipUuid in actionsByClip ) {
  20184. const actionByRoot = actionsByClip[ clipUuid ].actionByRoot,
  20185. action = actionByRoot[ rootUuid ];
  20186. if ( action !== undefined ) {
  20187. this._deactivateAction( action );
  20188. this._removeInactiveAction( action );
  20189. }
  20190. }
  20191. const bindingsByRoot = this._bindingsByRootAndName,
  20192. bindingByName = bindingsByRoot[ rootUuid ];
  20193. if ( bindingByName !== undefined ) {
  20194. for ( const trackName in bindingByName ) {
  20195. const binding = bindingByName[ trackName ];
  20196. binding.restoreOriginalState();
  20197. this._removeInactiveBinding( binding );
  20198. }
  20199. }
  20200. }
  20201. // remove a targeted clip from the cache
  20202. uncacheAction( clip, optionalRoot ) {
  20203. const action = this.existingAction( clip, optionalRoot );
  20204. if ( action !== null ) {
  20205. this._deactivateAction( action );
  20206. this._removeInactiveAction( action );
  20207. }
  20208. }
  20209. }
  20210. let Uniform$1 = class Uniform {
  20211. constructor( value ) {
  20212. this.value = value;
  20213. }
  20214. clone() {
  20215. return new Uniform( this.value.clone === undefined ? this.value : this.value.clone() );
  20216. }
  20217. };
  20218. let _id$8 = 0;
  20219. let UniformsGroup$1 = class UniformsGroup extends EventDispatcher {
  20220. constructor() {
  20221. super();
  20222. this.isUniformsGroup = true;
  20223. Object.defineProperty( this, 'id', { value: _id$8 ++ } );
  20224. this.name = '';
  20225. this.usage = StaticDrawUsage;
  20226. this.uniforms = [];
  20227. }
  20228. add( uniform ) {
  20229. this.uniforms.push( uniform );
  20230. return this;
  20231. }
  20232. remove( uniform ) {
  20233. const index = this.uniforms.indexOf( uniform );
  20234. if ( index !== - 1 ) this.uniforms.splice( index, 1 );
  20235. return this;
  20236. }
  20237. setName( name ) {
  20238. this.name = name;
  20239. return this;
  20240. }
  20241. setUsage( value ) {
  20242. this.usage = value;
  20243. return this;
  20244. }
  20245. dispose() {
  20246. this.dispatchEvent( { type: 'dispose' } );
  20247. return this;
  20248. }
  20249. copy( source ) {
  20250. this.name = source.name;
  20251. this.usage = source.usage;
  20252. const uniformsSource = source.uniforms;
  20253. this.uniforms.length = 0;
  20254. for ( let i = 0, l = uniformsSource.length; i < l; i ++ ) {
  20255. const uniforms = Array.isArray( uniformsSource[ i ] ) ? uniformsSource[ i ] : [ uniformsSource[ i ] ];
  20256. for ( let j = 0; j < uniforms.length; j ++ ) {
  20257. this.uniforms.push( uniforms[ j ].clone() );
  20258. }
  20259. }
  20260. return this;
  20261. }
  20262. clone() {
  20263. return new this.constructor().copy( this );
  20264. }
  20265. };
  20266. class InstancedInterleavedBuffer extends InterleavedBuffer {
  20267. constructor( array, stride, meshPerAttribute = 1 ) {
  20268. super( array, stride );
  20269. this.isInstancedInterleavedBuffer = true;
  20270. this.meshPerAttribute = meshPerAttribute;
  20271. }
  20272. copy( source ) {
  20273. super.copy( source );
  20274. this.meshPerAttribute = source.meshPerAttribute;
  20275. return this;
  20276. }
  20277. clone( data ) {
  20278. const ib = super.clone( data );
  20279. ib.meshPerAttribute = this.meshPerAttribute;
  20280. return ib;
  20281. }
  20282. toJSON( data ) {
  20283. const json = super.toJSON( data );
  20284. json.isInstancedInterleavedBuffer = true;
  20285. json.meshPerAttribute = this.meshPerAttribute;
  20286. return json;
  20287. }
  20288. }
  20289. class GLBufferAttribute {
  20290. constructor( buffer, type, itemSize, elementSize, count ) {
  20291. this.isGLBufferAttribute = true;
  20292. this.name = '';
  20293. this.buffer = buffer;
  20294. this.type = type;
  20295. this.itemSize = itemSize;
  20296. this.elementSize = elementSize;
  20297. this.count = count;
  20298. this.version = 0;
  20299. }
  20300. set needsUpdate( value ) {
  20301. if ( value === true ) this.version ++;
  20302. }
  20303. setBuffer( buffer ) {
  20304. this.buffer = buffer;
  20305. return this;
  20306. }
  20307. setType( type, elementSize ) {
  20308. this.type = type;
  20309. this.elementSize = elementSize;
  20310. return this;
  20311. }
  20312. setItemSize( itemSize ) {
  20313. this.itemSize = itemSize;
  20314. return this;
  20315. }
  20316. setCount( count ) {
  20317. this.count = count;
  20318. return this;
  20319. }
  20320. }
  20321. const _matrix = /*@__PURE__*/ new Matrix4();
  20322. class Raycaster {
  20323. constructor( origin, direction, near = 0, far = Infinity ) {
  20324. this.ray = new Ray( origin, direction );
  20325. // direction is assumed to be normalized (for accurate distance calculations)
  20326. this.near = near;
  20327. this.far = far;
  20328. this.camera = null;
  20329. this.layers = new Layers();
  20330. this.params = {
  20331. Mesh: {},
  20332. Line: { threshold: 1 },
  20333. LOD: {},
  20334. Points: { threshold: 1 },
  20335. Sprite: {}
  20336. };
  20337. }
  20338. set( origin, direction ) {
  20339. // direction is assumed to be normalized (for accurate distance calculations)
  20340. this.ray.set( origin, direction );
  20341. }
  20342. setFromCamera( coords, camera ) {
  20343. if ( camera.isPerspectiveCamera ) {
  20344. this.ray.origin.setFromMatrixPosition( camera.matrixWorld );
  20345. this.ray.direction.set( coords.x, coords.y, 0.5 ).unproject( camera ).sub( this.ray.origin ).normalize();
  20346. this.camera = camera;
  20347. } else if ( camera.isOrthographicCamera ) {
  20348. this.ray.origin.set( coords.x, coords.y, ( camera.near + camera.far ) / ( camera.near - camera.far ) ).unproject( camera ); // set origin in plane of camera
  20349. this.ray.direction.set( 0, 0, - 1 ).transformDirection( camera.matrixWorld );
  20350. this.camera = camera;
  20351. } else {
  20352. console.error( 'THREE.Raycaster: Unsupported camera type: ' + camera.type );
  20353. }
  20354. }
  20355. setFromXRController( controller ) {
  20356. _matrix.identity().extractRotation( controller.matrixWorld );
  20357. this.ray.origin.setFromMatrixPosition( controller.matrixWorld );
  20358. this.ray.direction.set( 0, 0, - 1 ).applyMatrix4( _matrix );
  20359. return this;
  20360. }
  20361. intersectObject( object, recursive = true, intersects = [] ) {
  20362. intersect( object, this, intersects, recursive );
  20363. intersects.sort( ascSort );
  20364. return intersects;
  20365. }
  20366. intersectObjects( objects, recursive = true, intersects = [] ) {
  20367. for ( let i = 0, l = objects.length; i < l; i ++ ) {
  20368. intersect( objects[ i ], this, intersects, recursive );
  20369. }
  20370. intersects.sort( ascSort );
  20371. return intersects;
  20372. }
  20373. }
  20374. function ascSort( a, b ) {
  20375. return a.distance - b.distance;
  20376. }
  20377. function intersect( object, raycaster, intersects, recursive ) {
  20378. let propagate = true;
  20379. if ( object.layers.test( raycaster.layers ) ) {
  20380. const result = object.raycast( raycaster, intersects );
  20381. if ( result === false ) propagate = false;
  20382. }
  20383. if ( propagate === true && recursive === true ) {
  20384. const children = object.children;
  20385. for ( let i = 0, l = children.length; i < l; i ++ ) {
  20386. intersect( children[ i ], raycaster, intersects, true );
  20387. }
  20388. }
  20389. }
  20390. /**
  20391. * Ref: https://en.wikipedia.org/wiki/Spherical_coordinate_system
  20392. *
  20393. * phi (the polar angle) is measured from the positive y-axis. The positive y-axis is up.
  20394. * theta (the azimuthal angle) is measured from the positive z-axis.
  20395. */
  20396. class Spherical {
  20397. constructor( radius = 1, phi = 0, theta = 0 ) {
  20398. this.radius = radius;
  20399. this.phi = phi; // polar angle
  20400. this.theta = theta; // azimuthal angle
  20401. return this;
  20402. }
  20403. set( radius, phi, theta ) {
  20404. this.radius = radius;
  20405. this.phi = phi;
  20406. this.theta = theta;
  20407. return this;
  20408. }
  20409. copy( other ) {
  20410. this.radius = other.radius;
  20411. this.phi = other.phi;
  20412. this.theta = other.theta;
  20413. return this;
  20414. }
  20415. // restrict phi to be between EPS and PI-EPS
  20416. makeSafe() {
  20417. const EPS = 0.000001;
  20418. this.phi = Math.max( EPS, Math.min( Math.PI - EPS, this.phi ) );
  20419. return this;
  20420. }
  20421. setFromVector3( v ) {
  20422. return this.setFromCartesianCoords( v.x, v.y, v.z );
  20423. }
  20424. setFromCartesianCoords( x, y, z ) {
  20425. this.radius = Math.sqrt( x * x + y * y + z * z );
  20426. if ( this.radius === 0 ) {
  20427. this.theta = 0;
  20428. this.phi = 0;
  20429. } else {
  20430. this.theta = Math.atan2( x, z );
  20431. this.phi = Math.acos( clamp$1( y / this.radius, - 1, 1 ) );
  20432. }
  20433. return this;
  20434. }
  20435. clone() {
  20436. return new this.constructor().copy( this );
  20437. }
  20438. }
  20439. /**
  20440. * Ref: https://en.wikipedia.org/wiki/Cylindrical_coordinate_system
  20441. */
  20442. class Cylindrical {
  20443. constructor( radius = 1, theta = 0, y = 0 ) {
  20444. this.radius = radius; // distance from the origin to a point in the x-z plane
  20445. this.theta = theta; // counterclockwise angle in the x-z plane measured in radians from the positive z-axis
  20446. this.y = y; // height above the x-z plane
  20447. return this;
  20448. }
  20449. set( radius, theta, y ) {
  20450. this.radius = radius;
  20451. this.theta = theta;
  20452. this.y = y;
  20453. return this;
  20454. }
  20455. copy( other ) {
  20456. this.radius = other.radius;
  20457. this.theta = other.theta;
  20458. this.y = other.y;
  20459. return this;
  20460. }
  20461. setFromVector3( v ) {
  20462. return this.setFromCartesianCoords( v.x, v.y, v.z );
  20463. }
  20464. setFromCartesianCoords( x, y, z ) {
  20465. this.radius = Math.sqrt( x * x + z * z );
  20466. this.theta = Math.atan2( x, z );
  20467. this.y = y;
  20468. return this;
  20469. }
  20470. clone() {
  20471. return new this.constructor().copy( this );
  20472. }
  20473. }
  20474. class Matrix2 {
  20475. constructor( n11, n12, n21, n22 ) {
  20476. Matrix2.prototype.isMatrix2 = true;
  20477. this.elements = [
  20478. 1, 0,
  20479. 0, 1,
  20480. ];
  20481. if ( n11 !== undefined ) {
  20482. this.set( n11, n12, n21, n22 );
  20483. }
  20484. }
  20485. identity() {
  20486. this.set(
  20487. 1, 0,
  20488. 0, 1,
  20489. );
  20490. return this;
  20491. }
  20492. fromArray( array, offset = 0 ) {
  20493. for ( let i = 0; i < 4; i ++ ) {
  20494. this.elements[ i ] = array[ i + offset ];
  20495. }
  20496. return this;
  20497. }
  20498. set( n11, n12, n21, n22 ) {
  20499. const te = this.elements;
  20500. te[ 0 ] = n11; te[ 2 ] = n12;
  20501. te[ 1 ] = n21; te[ 3 ] = n22;
  20502. return this;
  20503. }
  20504. }
  20505. const _vector$4 = /*@__PURE__*/ new Vector2();
  20506. class Box2 {
  20507. constructor( min = new Vector2( + Infinity, + Infinity ), max = new Vector2( - Infinity, - Infinity ) ) {
  20508. this.isBox2 = true;
  20509. this.min = min;
  20510. this.max = max;
  20511. }
  20512. set( min, max ) {
  20513. this.min.copy( min );
  20514. this.max.copy( max );
  20515. return this;
  20516. }
  20517. setFromPoints( points ) {
  20518. this.makeEmpty();
  20519. for ( let i = 0, il = points.length; i < il; i ++ ) {
  20520. this.expandByPoint( points[ i ] );
  20521. }
  20522. return this;
  20523. }
  20524. setFromCenterAndSize( center, size ) {
  20525. const halfSize = _vector$4.copy( size ).multiplyScalar( 0.5 );
  20526. this.min.copy( center ).sub( halfSize );
  20527. this.max.copy( center ).add( halfSize );
  20528. return this;
  20529. }
  20530. clone() {
  20531. return new this.constructor().copy( this );
  20532. }
  20533. copy( box ) {
  20534. this.min.copy( box.min );
  20535. this.max.copy( box.max );
  20536. return this;
  20537. }
  20538. makeEmpty() {
  20539. this.min.x = this.min.y = + Infinity;
  20540. this.max.x = this.max.y = - Infinity;
  20541. return this;
  20542. }
  20543. isEmpty() {
  20544. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  20545. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y );
  20546. }
  20547. getCenter( target ) {
  20548. return this.isEmpty() ? target.set( 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  20549. }
  20550. getSize( target ) {
  20551. return this.isEmpty() ? target.set( 0, 0 ) : target.subVectors( this.max, this.min );
  20552. }
  20553. expandByPoint( point ) {
  20554. this.min.min( point );
  20555. this.max.max( point );
  20556. return this;
  20557. }
  20558. expandByVector( vector ) {
  20559. this.min.sub( vector );
  20560. this.max.add( vector );
  20561. return this;
  20562. }
  20563. expandByScalar( scalar ) {
  20564. this.min.addScalar( - scalar );
  20565. this.max.addScalar( scalar );
  20566. return this;
  20567. }
  20568. containsPoint( point ) {
  20569. return point.x >= this.min.x && point.x <= this.max.x &&
  20570. point.y >= this.min.y && point.y <= this.max.y;
  20571. }
  20572. containsBox( box ) {
  20573. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  20574. this.min.y <= box.min.y && box.max.y <= this.max.y;
  20575. }
  20576. getParameter( point, target ) {
  20577. // This can potentially have a divide by zero if the box
  20578. // has a size dimension of 0.
  20579. return target.set(
  20580. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  20581. ( point.y - this.min.y ) / ( this.max.y - this.min.y )
  20582. );
  20583. }
  20584. intersectsBox( box ) {
  20585. // using 4 splitting planes to rule out intersections
  20586. return box.max.x >= this.min.x && box.min.x <= this.max.x &&
  20587. box.max.y >= this.min.y && box.min.y <= this.max.y;
  20588. }
  20589. clampPoint( point, target ) {
  20590. return target.copy( point ).clamp( this.min, this.max );
  20591. }
  20592. distanceToPoint( point ) {
  20593. return this.clampPoint( point, _vector$4 ).distanceTo( point );
  20594. }
  20595. intersect( box ) {
  20596. this.min.max( box.min );
  20597. this.max.min( box.max );
  20598. if ( this.isEmpty() ) this.makeEmpty();
  20599. return this;
  20600. }
  20601. union( box ) {
  20602. this.min.min( box.min );
  20603. this.max.max( box.max );
  20604. return this;
  20605. }
  20606. translate( offset ) {
  20607. this.min.add( offset );
  20608. this.max.add( offset );
  20609. return this;
  20610. }
  20611. equals( box ) {
  20612. return box.min.equals( this.min ) && box.max.equals( this.max );
  20613. }
  20614. }
  20615. const _startP = /*@__PURE__*/ new Vector3();
  20616. const _startEnd = /*@__PURE__*/ new Vector3();
  20617. class Line3 {
  20618. constructor( start = new Vector3(), end = new Vector3() ) {
  20619. this.start = start;
  20620. this.end = end;
  20621. }
  20622. set( start, end ) {
  20623. this.start.copy( start );
  20624. this.end.copy( end );
  20625. return this;
  20626. }
  20627. copy( line ) {
  20628. this.start.copy( line.start );
  20629. this.end.copy( line.end );
  20630. return this;
  20631. }
  20632. getCenter( target ) {
  20633. return target.addVectors( this.start, this.end ).multiplyScalar( 0.5 );
  20634. }
  20635. delta( target ) {
  20636. return target.subVectors( this.end, this.start );
  20637. }
  20638. distanceSq() {
  20639. return this.start.distanceToSquared( this.end );
  20640. }
  20641. distance() {
  20642. return this.start.distanceTo( this.end );
  20643. }
  20644. at( t, target ) {
  20645. return this.delta( target ).multiplyScalar( t ).add( this.start );
  20646. }
  20647. closestPointToPointParameter( point, clampToLine ) {
  20648. _startP.subVectors( point, this.start );
  20649. _startEnd.subVectors( this.end, this.start );
  20650. const startEnd2 = _startEnd.dot( _startEnd );
  20651. const startEnd_startP = _startEnd.dot( _startP );
  20652. let t = startEnd_startP / startEnd2;
  20653. if ( clampToLine ) {
  20654. t = clamp$1( t, 0, 1 );
  20655. }
  20656. return t;
  20657. }
  20658. closestPointToPoint( point, clampToLine, target ) {
  20659. const t = this.closestPointToPointParameter( point, clampToLine );
  20660. return this.delta( target ).multiplyScalar( t ).add( this.start );
  20661. }
  20662. applyMatrix4( matrix ) {
  20663. this.start.applyMatrix4( matrix );
  20664. this.end.applyMatrix4( matrix );
  20665. return this;
  20666. }
  20667. equals( line ) {
  20668. return line.start.equals( this.start ) && line.end.equals( this.end );
  20669. }
  20670. clone() {
  20671. return new this.constructor().copy( this );
  20672. }
  20673. }
  20674. const _vector$3 = /*@__PURE__*/ new Vector3();
  20675. class SpotLightHelper extends Object3D {
  20676. constructor( light, color ) {
  20677. super();
  20678. this.light = light;
  20679. this.matrixAutoUpdate = false;
  20680. this.color = color;
  20681. this.type = 'SpotLightHelper';
  20682. const geometry = new BufferGeometry();
  20683. const positions = [
  20684. 0, 0, 0, 0, 0, 1,
  20685. 0, 0, 0, 1, 0, 1,
  20686. 0, 0, 0, - 1, 0, 1,
  20687. 0, 0, 0, 0, 1, 1,
  20688. 0, 0, 0, 0, - 1, 1
  20689. ];
  20690. for ( let i = 0, j = 1, l = 32; i < l; i ++, j ++ ) {
  20691. const p1 = ( i / l ) * Math.PI * 2;
  20692. const p2 = ( j / l ) * Math.PI * 2;
  20693. positions.push(
  20694. Math.cos( p1 ), Math.sin( p1 ), 1,
  20695. Math.cos( p2 ), Math.sin( p2 ), 1
  20696. );
  20697. }
  20698. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  20699. const material = new LineBasicMaterial( { fog: false, toneMapped: false } );
  20700. this.cone = new LineSegments( geometry, material );
  20701. this.add( this.cone );
  20702. this.update();
  20703. }
  20704. dispose() {
  20705. this.cone.geometry.dispose();
  20706. this.cone.material.dispose();
  20707. }
  20708. update() {
  20709. this.light.updateWorldMatrix( true, false );
  20710. this.light.target.updateWorldMatrix( true, false );
  20711. // update the local matrix based on the parent and light target transforms
  20712. if ( this.parent ) {
  20713. this.parent.updateWorldMatrix( true );
  20714. this.matrix
  20715. .copy( this.parent.matrixWorld )
  20716. .invert()
  20717. .multiply( this.light.matrixWorld );
  20718. } else {
  20719. this.matrix.copy( this.light.matrixWorld );
  20720. }
  20721. this.matrixWorld.copy( this.light.matrixWorld );
  20722. const coneLength = this.light.distance ? this.light.distance : 1000;
  20723. const coneWidth = coneLength * Math.tan( this.light.angle );
  20724. this.cone.scale.set( coneWidth, coneWidth, coneLength );
  20725. _vector$3.setFromMatrixPosition( this.light.target.matrixWorld );
  20726. this.cone.lookAt( _vector$3 );
  20727. if ( this.color !== undefined ) {
  20728. this.cone.material.color.set( this.color );
  20729. } else {
  20730. this.cone.material.color.copy( this.light.color );
  20731. }
  20732. }
  20733. }
  20734. const _vector$2 = /*@__PURE__*/ new Vector3();
  20735. const _boneMatrix = /*@__PURE__*/ new Matrix4();
  20736. const _matrixWorldInv = /*@__PURE__*/ new Matrix4();
  20737. class SkeletonHelper extends LineSegments {
  20738. constructor( object ) {
  20739. const bones = getBoneList( object );
  20740. const geometry = new BufferGeometry();
  20741. const vertices = [];
  20742. const colors = [];
  20743. const color1 = new Color( 0, 0, 1 );
  20744. const color2 = new Color( 0, 1, 0 );
  20745. for ( let i = 0; i < bones.length; i ++ ) {
  20746. const bone = bones[ i ];
  20747. if ( bone.parent && bone.parent.isBone ) {
  20748. vertices.push( 0, 0, 0 );
  20749. vertices.push( 0, 0, 0 );
  20750. colors.push( color1.r, color1.g, color1.b );
  20751. colors.push( color2.r, color2.g, color2.b );
  20752. }
  20753. }
  20754. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  20755. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  20756. const material = new LineBasicMaterial( { vertexColors: true, depthTest: false, depthWrite: false, toneMapped: false, transparent: true } );
  20757. super( geometry, material );
  20758. this.isSkeletonHelper = true;
  20759. this.type = 'SkeletonHelper';
  20760. this.root = object;
  20761. this.bones = bones;
  20762. this.matrix = object.matrixWorld;
  20763. this.matrixAutoUpdate = false;
  20764. }
  20765. updateMatrixWorld( force ) {
  20766. const bones = this.bones;
  20767. const geometry = this.geometry;
  20768. const position = geometry.getAttribute( 'position' );
  20769. _matrixWorldInv.copy( this.root.matrixWorld ).invert();
  20770. for ( let i = 0, j = 0; i < bones.length; i ++ ) {
  20771. const bone = bones[ i ];
  20772. if ( bone.parent && bone.parent.isBone ) {
  20773. _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.matrixWorld );
  20774. _vector$2.setFromMatrixPosition( _boneMatrix );
  20775. position.setXYZ( j, _vector$2.x, _vector$2.y, _vector$2.z );
  20776. _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.parent.matrixWorld );
  20777. _vector$2.setFromMatrixPosition( _boneMatrix );
  20778. position.setXYZ( j + 1, _vector$2.x, _vector$2.y, _vector$2.z );
  20779. j += 2;
  20780. }
  20781. }
  20782. geometry.getAttribute( 'position' ).needsUpdate = true;
  20783. super.updateMatrixWorld( force );
  20784. }
  20785. dispose() {
  20786. this.geometry.dispose();
  20787. this.material.dispose();
  20788. }
  20789. }
  20790. function getBoneList( object ) {
  20791. const boneList = [];
  20792. if ( object.isBone === true ) {
  20793. boneList.push( object );
  20794. }
  20795. for ( let i = 0; i < object.children.length; i ++ ) {
  20796. boneList.push.apply( boneList, getBoneList( object.children[ i ] ) );
  20797. }
  20798. return boneList;
  20799. }
  20800. class PointLightHelper extends Mesh {
  20801. constructor( light, sphereSize, color ) {
  20802. const geometry = new SphereGeometry( sphereSize, 4, 2 );
  20803. const material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );
  20804. super( geometry, material );
  20805. this.light = light;
  20806. this.color = color;
  20807. this.type = 'PointLightHelper';
  20808. this.matrix = this.light.matrixWorld;
  20809. this.matrixAutoUpdate = false;
  20810. this.update();
  20811. /*
  20812. // TODO: delete this comment?
  20813. const distanceGeometry = new THREE.IcosahedronGeometry( 1, 2 );
  20814. const distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  20815. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  20816. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  20817. const d = light.distance;
  20818. if ( d === 0.0 ) {
  20819. this.lightDistance.visible = false;
  20820. } else {
  20821. this.lightDistance.scale.set( d, d, d );
  20822. }
  20823. this.add( this.lightDistance );
  20824. */
  20825. }
  20826. dispose() {
  20827. this.geometry.dispose();
  20828. this.material.dispose();
  20829. }
  20830. update() {
  20831. this.light.updateWorldMatrix( true, false );
  20832. if ( this.color !== undefined ) {
  20833. this.material.color.set( this.color );
  20834. } else {
  20835. this.material.color.copy( this.light.color );
  20836. }
  20837. /*
  20838. const d = this.light.distance;
  20839. if ( d === 0.0 ) {
  20840. this.lightDistance.visible = false;
  20841. } else {
  20842. this.lightDistance.visible = true;
  20843. this.lightDistance.scale.set( d, d, d );
  20844. }
  20845. */
  20846. }
  20847. }
  20848. const _vector$1 = /*@__PURE__*/ new Vector3();
  20849. const _color1 = /*@__PURE__*/ new Color();
  20850. const _color2 = /*@__PURE__*/ new Color();
  20851. class HemisphereLightHelper extends Object3D {
  20852. constructor( light, size, color ) {
  20853. super();
  20854. this.light = light;
  20855. this.matrix = light.matrixWorld;
  20856. this.matrixAutoUpdate = false;
  20857. this.color = color;
  20858. this.type = 'HemisphereLightHelper';
  20859. const geometry = new OctahedronGeometry( size );
  20860. geometry.rotateY( Math.PI * 0.5 );
  20861. this.material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );
  20862. if ( this.color === undefined ) this.material.vertexColors = true;
  20863. const position = geometry.getAttribute( 'position' );
  20864. const colors = new Float32Array( position.count * 3 );
  20865. geometry.setAttribute( 'color', new BufferAttribute( colors, 3 ) );
  20866. this.add( new Mesh( geometry, this.material ) );
  20867. this.update();
  20868. }
  20869. dispose() {
  20870. this.children[ 0 ].geometry.dispose();
  20871. this.children[ 0 ].material.dispose();
  20872. }
  20873. update() {
  20874. const mesh = this.children[ 0 ];
  20875. if ( this.color !== undefined ) {
  20876. this.material.color.set( this.color );
  20877. } else {
  20878. const colors = mesh.geometry.getAttribute( 'color' );
  20879. _color1.copy( this.light.color );
  20880. _color2.copy( this.light.groundColor );
  20881. for ( let i = 0, l = colors.count; i < l; i ++ ) {
  20882. const color = ( i < ( l / 2 ) ) ? _color1 : _color2;
  20883. colors.setXYZ( i, color.r, color.g, color.b );
  20884. }
  20885. colors.needsUpdate = true;
  20886. }
  20887. this.light.updateWorldMatrix( true, false );
  20888. mesh.lookAt( _vector$1.setFromMatrixPosition( this.light.matrixWorld ).negate() );
  20889. }
  20890. }
  20891. class GridHelper extends LineSegments {
  20892. constructor( size = 10, divisions = 10, color1 = 0x444444, color2 = 0x888888 ) {
  20893. color1 = new Color( color1 );
  20894. color2 = new Color( color2 );
  20895. const center = divisions / 2;
  20896. const step = size / divisions;
  20897. const halfSize = size / 2;
  20898. const vertices = [], colors = [];
  20899. for ( let i = 0, j = 0, k = - halfSize; i <= divisions; i ++, k += step ) {
  20900. vertices.push( - halfSize, 0, k, halfSize, 0, k );
  20901. vertices.push( k, 0, - halfSize, k, 0, halfSize );
  20902. const color = i === center ? color1 : color2;
  20903. color.toArray( colors, j ); j += 3;
  20904. color.toArray( colors, j ); j += 3;
  20905. color.toArray( colors, j ); j += 3;
  20906. color.toArray( colors, j ); j += 3;
  20907. }
  20908. const geometry = new BufferGeometry();
  20909. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  20910. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  20911. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  20912. super( geometry, material );
  20913. this.type = 'GridHelper';
  20914. }
  20915. dispose() {
  20916. this.geometry.dispose();
  20917. this.material.dispose();
  20918. }
  20919. }
  20920. class PolarGridHelper extends LineSegments {
  20921. constructor( radius = 10, sectors = 16, rings = 8, divisions = 64, color1 = 0x444444, color2 = 0x888888 ) {
  20922. color1 = new Color( color1 );
  20923. color2 = new Color( color2 );
  20924. const vertices = [];
  20925. const colors = [];
  20926. // create the sectors
  20927. if ( sectors > 1 ) {
  20928. for ( let i = 0; i < sectors; i ++ ) {
  20929. const v = ( i / sectors ) * ( Math.PI * 2 );
  20930. const x = Math.sin( v ) * radius;
  20931. const z = Math.cos( v ) * radius;
  20932. vertices.push( 0, 0, 0 );
  20933. vertices.push( x, 0, z );
  20934. const color = ( i & 1 ) ? color1 : color2;
  20935. colors.push( color.r, color.g, color.b );
  20936. colors.push( color.r, color.g, color.b );
  20937. }
  20938. }
  20939. // create the rings
  20940. for ( let i = 0; i < rings; i ++ ) {
  20941. const color = ( i & 1 ) ? color1 : color2;
  20942. const r = radius - ( radius / rings * i );
  20943. for ( let j = 0; j < divisions; j ++ ) {
  20944. // first vertex
  20945. let v = ( j / divisions ) * ( Math.PI * 2 );
  20946. let x = Math.sin( v ) * r;
  20947. let z = Math.cos( v ) * r;
  20948. vertices.push( x, 0, z );
  20949. colors.push( color.r, color.g, color.b );
  20950. // second vertex
  20951. v = ( ( j + 1 ) / divisions ) * ( Math.PI * 2 );
  20952. x = Math.sin( v ) * r;
  20953. z = Math.cos( v ) * r;
  20954. vertices.push( x, 0, z );
  20955. colors.push( color.r, color.g, color.b );
  20956. }
  20957. }
  20958. const geometry = new BufferGeometry();
  20959. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  20960. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  20961. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  20962. super( geometry, material );
  20963. this.type = 'PolarGridHelper';
  20964. }
  20965. dispose() {
  20966. this.geometry.dispose();
  20967. this.material.dispose();
  20968. }
  20969. }
  20970. const _v1 = /*@__PURE__*/ new Vector3();
  20971. const _v2 = /*@__PURE__*/ new Vector3();
  20972. const _v3 = /*@__PURE__*/ new Vector3();
  20973. class DirectionalLightHelper extends Object3D {
  20974. constructor( light, size, color ) {
  20975. super();
  20976. this.light = light;
  20977. this.matrix = light.matrixWorld;
  20978. this.matrixAutoUpdate = false;
  20979. this.color = color;
  20980. this.type = 'DirectionalLightHelper';
  20981. if ( size === undefined ) size = 1;
  20982. let geometry = new BufferGeometry();
  20983. geometry.setAttribute( 'position', new Float32BufferAttribute( [
  20984. - size, size, 0,
  20985. size, size, 0,
  20986. size, - size, 0,
  20987. - size, - size, 0,
  20988. - size, size, 0
  20989. ], 3 ) );
  20990. const material = new LineBasicMaterial( { fog: false, toneMapped: false } );
  20991. this.lightPlane = new Line( geometry, material );
  20992. this.add( this.lightPlane );
  20993. geometry = new BufferGeometry();
  20994. geometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 0, 1 ], 3 ) );
  20995. this.targetLine = new Line( geometry, material );
  20996. this.add( this.targetLine );
  20997. this.update();
  20998. }
  20999. dispose() {
  21000. this.lightPlane.geometry.dispose();
  21001. this.lightPlane.material.dispose();
  21002. this.targetLine.geometry.dispose();
  21003. this.targetLine.material.dispose();
  21004. }
  21005. update() {
  21006. this.light.updateWorldMatrix( true, false );
  21007. this.light.target.updateWorldMatrix( true, false );
  21008. _v1.setFromMatrixPosition( this.light.matrixWorld );
  21009. _v2.setFromMatrixPosition( this.light.target.matrixWorld );
  21010. _v3.subVectors( _v2, _v1 );
  21011. this.lightPlane.lookAt( _v2 );
  21012. if ( this.color !== undefined ) {
  21013. this.lightPlane.material.color.set( this.color );
  21014. this.targetLine.material.color.set( this.color );
  21015. } else {
  21016. this.lightPlane.material.color.copy( this.light.color );
  21017. this.targetLine.material.color.copy( this.light.color );
  21018. }
  21019. this.targetLine.lookAt( _v2 );
  21020. this.targetLine.scale.z = _v3.length();
  21021. }
  21022. }
  21023. const _vector = /*@__PURE__*/ new Vector3();
  21024. const _camera$1 = /*@__PURE__*/ new Camera();
  21025. /**
  21026. * - shows frustum, line of sight and up of the camera
  21027. * - suitable for fast updates
  21028. * - based on frustum visualization in lightgl.js shadowmap example
  21029. * https://github.com/evanw/lightgl.js/blob/master/tests/shadowmap.html
  21030. */
  21031. class CameraHelper extends LineSegments {
  21032. constructor( camera ) {
  21033. const geometry = new BufferGeometry();
  21034. const material = new LineBasicMaterial( { color: 0xffffff, vertexColors: true, toneMapped: false } );
  21035. const vertices = [];
  21036. const colors = [];
  21037. const pointMap = {};
  21038. // near
  21039. addLine( 'n1', 'n2' );
  21040. addLine( 'n2', 'n4' );
  21041. addLine( 'n4', 'n3' );
  21042. addLine( 'n3', 'n1' );
  21043. // far
  21044. addLine( 'f1', 'f2' );
  21045. addLine( 'f2', 'f4' );
  21046. addLine( 'f4', 'f3' );
  21047. addLine( 'f3', 'f1' );
  21048. // sides
  21049. addLine( 'n1', 'f1' );
  21050. addLine( 'n2', 'f2' );
  21051. addLine( 'n3', 'f3' );
  21052. addLine( 'n4', 'f4' );
  21053. // cone
  21054. addLine( 'p', 'n1' );
  21055. addLine( 'p', 'n2' );
  21056. addLine( 'p', 'n3' );
  21057. addLine( 'p', 'n4' );
  21058. // up
  21059. addLine( 'u1', 'u2' );
  21060. addLine( 'u2', 'u3' );
  21061. addLine( 'u3', 'u1' );
  21062. // target
  21063. addLine( 'c', 't' );
  21064. addLine( 'p', 'c' );
  21065. // cross
  21066. addLine( 'cn1', 'cn2' );
  21067. addLine( 'cn3', 'cn4' );
  21068. addLine( 'cf1', 'cf2' );
  21069. addLine( 'cf3', 'cf4' );
  21070. function addLine( a, b ) {
  21071. addPoint( a );
  21072. addPoint( b );
  21073. }
  21074. function addPoint( id ) {
  21075. vertices.push( 0, 0, 0 );
  21076. colors.push( 0, 0, 0 );
  21077. if ( pointMap[ id ] === undefined ) {
  21078. pointMap[ id ] = [];
  21079. }
  21080. pointMap[ id ].push( ( vertices.length / 3 ) - 1 );
  21081. }
  21082. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21083. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  21084. super( geometry, material );
  21085. this.type = 'CameraHelper';
  21086. this.camera = camera;
  21087. if ( this.camera.updateProjectionMatrix ) this.camera.updateProjectionMatrix();
  21088. this.matrix = camera.matrixWorld;
  21089. this.matrixAutoUpdate = false;
  21090. this.pointMap = pointMap;
  21091. this.update();
  21092. // colors
  21093. const colorFrustum = new Color( 0xffaa00 );
  21094. const colorCone = new Color( 0xff0000 );
  21095. const colorUp = new Color( 0x00aaff );
  21096. const colorTarget = new Color( 0xffffff );
  21097. const colorCross = new Color( 0x333333 );
  21098. this.setColors( colorFrustum, colorCone, colorUp, colorTarget, colorCross );
  21099. }
  21100. setColors( frustum, cone, up, target, cross ) {
  21101. const geometry = this.geometry;
  21102. const colorAttribute = geometry.getAttribute( 'color' );
  21103. // near
  21104. colorAttribute.setXYZ( 0, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 1, frustum.r, frustum.g, frustum.b ); // n1, n2
  21105. colorAttribute.setXYZ( 2, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 3, frustum.r, frustum.g, frustum.b ); // n2, n4
  21106. colorAttribute.setXYZ( 4, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 5, frustum.r, frustum.g, frustum.b ); // n4, n3
  21107. colorAttribute.setXYZ( 6, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 7, frustum.r, frustum.g, frustum.b ); // n3, n1
  21108. // far
  21109. colorAttribute.setXYZ( 8, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 9, frustum.r, frustum.g, frustum.b ); // f1, f2
  21110. colorAttribute.setXYZ( 10, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 11, frustum.r, frustum.g, frustum.b ); // f2, f4
  21111. colorAttribute.setXYZ( 12, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 13, frustum.r, frustum.g, frustum.b ); // f4, f3
  21112. colorAttribute.setXYZ( 14, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 15, frustum.r, frustum.g, frustum.b ); // f3, f1
  21113. // sides
  21114. colorAttribute.setXYZ( 16, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 17, frustum.r, frustum.g, frustum.b ); // n1, f1
  21115. colorAttribute.setXYZ( 18, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 19, frustum.r, frustum.g, frustum.b ); // n2, f2
  21116. colorAttribute.setXYZ( 20, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 21, frustum.r, frustum.g, frustum.b ); // n3, f3
  21117. colorAttribute.setXYZ( 22, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 23, frustum.r, frustum.g, frustum.b ); // n4, f4
  21118. // cone
  21119. colorAttribute.setXYZ( 24, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 25, cone.r, cone.g, cone.b ); // p, n1
  21120. colorAttribute.setXYZ( 26, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 27, cone.r, cone.g, cone.b ); // p, n2
  21121. colorAttribute.setXYZ( 28, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 29, cone.r, cone.g, cone.b ); // p, n3
  21122. colorAttribute.setXYZ( 30, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 31, cone.r, cone.g, cone.b ); // p, n4
  21123. // up
  21124. colorAttribute.setXYZ( 32, up.r, up.g, up.b ); colorAttribute.setXYZ( 33, up.r, up.g, up.b ); // u1, u2
  21125. colorAttribute.setXYZ( 34, up.r, up.g, up.b ); colorAttribute.setXYZ( 35, up.r, up.g, up.b ); // u2, u3
  21126. colorAttribute.setXYZ( 36, up.r, up.g, up.b ); colorAttribute.setXYZ( 37, up.r, up.g, up.b ); // u3, u1
  21127. // target
  21128. colorAttribute.setXYZ( 38, target.r, target.g, target.b ); colorAttribute.setXYZ( 39, target.r, target.g, target.b ); // c, t
  21129. colorAttribute.setXYZ( 40, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 41, cross.r, cross.g, cross.b ); // p, c
  21130. // cross
  21131. colorAttribute.setXYZ( 42, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 43, cross.r, cross.g, cross.b ); // cn1, cn2
  21132. colorAttribute.setXYZ( 44, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 45, cross.r, cross.g, cross.b ); // cn3, cn4
  21133. colorAttribute.setXYZ( 46, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 47, cross.r, cross.g, cross.b ); // cf1, cf2
  21134. colorAttribute.setXYZ( 48, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 49, cross.r, cross.g, cross.b ); // cf3, cf4
  21135. colorAttribute.needsUpdate = true;
  21136. }
  21137. update() {
  21138. const geometry = this.geometry;
  21139. const pointMap = this.pointMap;
  21140. const w = 1, h = 1;
  21141. // we need just camera projection matrix inverse
  21142. // world matrix must be identity
  21143. _camera$1.projectionMatrixInverse.copy( this.camera.projectionMatrixInverse );
  21144. // center / target
  21145. setPoint( 'c', pointMap, geometry, _camera$1, 0, 0, - 1 );
  21146. setPoint( 't', pointMap, geometry, _camera$1, 0, 0, 1 );
  21147. // near
  21148. setPoint( 'n1', pointMap, geometry, _camera$1, - w, - h, - 1 );
  21149. setPoint( 'n2', pointMap, geometry, _camera$1, w, - h, - 1 );
  21150. setPoint( 'n3', pointMap, geometry, _camera$1, - w, h, - 1 );
  21151. setPoint( 'n4', pointMap, geometry, _camera$1, w, h, - 1 );
  21152. // far
  21153. setPoint( 'f1', pointMap, geometry, _camera$1, - w, - h, 1 );
  21154. setPoint( 'f2', pointMap, geometry, _camera$1, w, - h, 1 );
  21155. setPoint( 'f3', pointMap, geometry, _camera$1, - w, h, 1 );
  21156. setPoint( 'f4', pointMap, geometry, _camera$1, w, h, 1 );
  21157. // up
  21158. setPoint( 'u1', pointMap, geometry, _camera$1, w * 0.7, h * 1.1, - 1 );
  21159. setPoint( 'u2', pointMap, geometry, _camera$1, - w * 0.7, h * 1.1, - 1 );
  21160. setPoint( 'u3', pointMap, geometry, _camera$1, 0, h * 2, - 1 );
  21161. // cross
  21162. setPoint( 'cf1', pointMap, geometry, _camera$1, - w, 0, 1 );
  21163. setPoint( 'cf2', pointMap, geometry, _camera$1, w, 0, 1 );
  21164. setPoint( 'cf3', pointMap, geometry, _camera$1, 0, - h, 1 );
  21165. setPoint( 'cf4', pointMap, geometry, _camera$1, 0, h, 1 );
  21166. setPoint( 'cn1', pointMap, geometry, _camera$1, - w, 0, - 1 );
  21167. setPoint( 'cn2', pointMap, geometry, _camera$1, w, 0, - 1 );
  21168. setPoint( 'cn3', pointMap, geometry, _camera$1, 0, - h, - 1 );
  21169. setPoint( 'cn4', pointMap, geometry, _camera$1, 0, h, - 1 );
  21170. geometry.getAttribute( 'position' ).needsUpdate = true;
  21171. }
  21172. dispose() {
  21173. this.geometry.dispose();
  21174. this.material.dispose();
  21175. }
  21176. }
  21177. function setPoint( point, pointMap, geometry, camera, x, y, z ) {
  21178. _vector.set( x, y, z ).unproject( camera );
  21179. const points = pointMap[ point ];
  21180. if ( points !== undefined ) {
  21181. const position = geometry.getAttribute( 'position' );
  21182. for ( let i = 0, l = points.length; i < l; i ++ ) {
  21183. position.setXYZ( points[ i ], _vector.x, _vector.y, _vector.z );
  21184. }
  21185. }
  21186. }
  21187. const _box = /*@__PURE__*/ new Box3();
  21188. class BoxHelper extends LineSegments {
  21189. constructor( object, color = 0xffff00 ) {
  21190. 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 ] );
  21191. const positions = new Float32Array( 8 * 3 );
  21192. const geometry = new BufferGeometry();
  21193. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  21194. geometry.setAttribute( 'position', new BufferAttribute( positions, 3 ) );
  21195. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  21196. this.object = object;
  21197. this.type = 'BoxHelper';
  21198. this.matrixAutoUpdate = false;
  21199. this.update();
  21200. }
  21201. update( object ) {
  21202. if ( object !== undefined ) {
  21203. console.warn( 'THREE.BoxHelper: .update() has no longer arguments.' );
  21204. }
  21205. if ( this.object !== undefined ) {
  21206. _box.setFromObject( this.object );
  21207. }
  21208. if ( _box.isEmpty() ) return;
  21209. const min = _box.min;
  21210. const max = _box.max;
  21211. /*
  21212. 5____4
  21213. 1/___0/|
  21214. | 6__|_7
  21215. 2/___3/
  21216. 0: max.x, max.y, max.z
  21217. 1: min.x, max.y, max.z
  21218. 2: min.x, min.y, max.z
  21219. 3: max.x, min.y, max.z
  21220. 4: max.x, max.y, min.z
  21221. 5: min.x, max.y, min.z
  21222. 6: min.x, min.y, min.z
  21223. 7: max.x, min.y, min.z
  21224. */
  21225. const position = this.geometry.attributes.position;
  21226. const array = position.array;
  21227. array[ 0 ] = max.x; array[ 1 ] = max.y; array[ 2 ] = max.z;
  21228. array[ 3 ] = min.x; array[ 4 ] = max.y; array[ 5 ] = max.z;
  21229. array[ 6 ] = min.x; array[ 7 ] = min.y; array[ 8 ] = max.z;
  21230. array[ 9 ] = max.x; array[ 10 ] = min.y; array[ 11 ] = max.z;
  21231. array[ 12 ] = max.x; array[ 13 ] = max.y; array[ 14 ] = min.z;
  21232. array[ 15 ] = min.x; array[ 16 ] = max.y; array[ 17 ] = min.z;
  21233. array[ 18 ] = min.x; array[ 19 ] = min.y; array[ 20 ] = min.z;
  21234. array[ 21 ] = max.x; array[ 22 ] = min.y; array[ 23 ] = min.z;
  21235. position.needsUpdate = true;
  21236. this.geometry.computeBoundingSphere();
  21237. }
  21238. setFromObject( object ) {
  21239. this.object = object;
  21240. this.update();
  21241. return this;
  21242. }
  21243. copy( source, recursive ) {
  21244. super.copy( source, recursive );
  21245. this.object = source.object;
  21246. return this;
  21247. }
  21248. dispose() {
  21249. this.geometry.dispose();
  21250. this.material.dispose();
  21251. }
  21252. }
  21253. class Box3Helper extends LineSegments {
  21254. constructor( box, color = 0xffff00 ) {
  21255. 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 ] );
  21256. 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 ];
  21257. const geometry = new BufferGeometry();
  21258. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  21259. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  21260. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  21261. this.box = box;
  21262. this.type = 'Box3Helper';
  21263. this.geometry.computeBoundingSphere();
  21264. }
  21265. updateMatrixWorld( force ) {
  21266. const box = this.box;
  21267. if ( box.isEmpty() ) return;
  21268. box.getCenter( this.position );
  21269. box.getSize( this.scale );
  21270. this.scale.multiplyScalar( 0.5 );
  21271. super.updateMatrixWorld( force );
  21272. }
  21273. dispose() {
  21274. this.geometry.dispose();
  21275. this.material.dispose();
  21276. }
  21277. }
  21278. class PlaneHelper extends Line {
  21279. constructor( plane, size = 1, hex = 0xffff00 ) {
  21280. const color = hex;
  21281. 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 ];
  21282. const geometry = new BufferGeometry();
  21283. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  21284. geometry.computeBoundingSphere();
  21285. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  21286. this.type = 'PlaneHelper';
  21287. this.plane = plane;
  21288. this.size = size;
  21289. const positions2 = [ 1, 1, 0, - 1, 1, 0, - 1, - 1, 0, 1, 1, 0, - 1, - 1, 0, 1, - 1, 0 ];
  21290. const geometry2 = new BufferGeometry();
  21291. geometry2.setAttribute( 'position', new Float32BufferAttribute( positions2, 3 ) );
  21292. geometry2.computeBoundingSphere();
  21293. this.add( new Mesh( geometry2, new MeshBasicMaterial( { color: color, opacity: 0.2, transparent: true, depthWrite: false, toneMapped: false } ) ) );
  21294. }
  21295. updateMatrixWorld( force ) {
  21296. this.position.set( 0, 0, 0 );
  21297. this.scale.set( 0.5 * this.size, 0.5 * this.size, 1 );
  21298. this.lookAt( this.plane.normal );
  21299. this.translateZ( - this.plane.constant );
  21300. super.updateMatrixWorld( force );
  21301. }
  21302. dispose() {
  21303. this.geometry.dispose();
  21304. this.material.dispose();
  21305. this.children[ 0 ].geometry.dispose();
  21306. this.children[ 0 ].material.dispose();
  21307. }
  21308. }
  21309. const _axis = /*@__PURE__*/ new Vector3();
  21310. let _lineGeometry, _coneGeometry;
  21311. class ArrowHelper extends Object3D {
  21312. // dir is assumed to be normalized
  21313. 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 ) {
  21314. super();
  21315. this.type = 'ArrowHelper';
  21316. if ( _lineGeometry === undefined ) {
  21317. _lineGeometry = new BufferGeometry();
  21318. _lineGeometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 1, 0 ], 3 ) );
  21319. _coneGeometry = new CylinderGeometry( 0, 0.5, 1, 5, 1 );
  21320. _coneGeometry.translate( 0, - 0.5, 0 );
  21321. }
  21322. this.position.copy( origin );
  21323. this.line = new Line( _lineGeometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  21324. this.line.matrixAutoUpdate = false;
  21325. this.add( this.line );
  21326. this.cone = new Mesh( _coneGeometry, new MeshBasicMaterial( { color: color, toneMapped: false } ) );
  21327. this.cone.matrixAutoUpdate = false;
  21328. this.add( this.cone );
  21329. this.setDirection( dir );
  21330. this.setLength( length, headLength, headWidth );
  21331. }
  21332. setDirection( dir ) {
  21333. // dir is assumed to be normalized
  21334. if ( dir.y > 0.99999 ) {
  21335. this.quaternion.set( 0, 0, 0, 1 );
  21336. } else if ( dir.y < - 0.99999 ) {
  21337. this.quaternion.set( 1, 0, 0, 0 );
  21338. } else {
  21339. _axis.set( dir.z, 0, - dir.x ).normalize();
  21340. const radians = Math.acos( dir.y );
  21341. this.quaternion.setFromAxisAngle( _axis, radians );
  21342. }
  21343. }
  21344. setLength( length, headLength = length * 0.2, headWidth = headLength * 0.2 ) {
  21345. this.line.scale.set( 1, Math.max( 0.0001, length - headLength ), 1 ); // see #17458
  21346. this.line.updateMatrix();
  21347. this.cone.scale.set( headWidth, headLength, headWidth );
  21348. this.cone.position.y = length;
  21349. this.cone.updateMatrix();
  21350. }
  21351. setColor( color ) {
  21352. this.line.material.color.set( color );
  21353. this.cone.material.color.set( color );
  21354. }
  21355. copy( source ) {
  21356. super.copy( source, false );
  21357. this.line.copy( source.line );
  21358. this.cone.copy( source.cone );
  21359. return this;
  21360. }
  21361. dispose() {
  21362. this.line.geometry.dispose();
  21363. this.line.material.dispose();
  21364. this.cone.geometry.dispose();
  21365. this.cone.material.dispose();
  21366. }
  21367. }
  21368. class AxesHelper extends LineSegments {
  21369. constructor( size = 1 ) {
  21370. const vertices = [
  21371. 0, 0, 0, size, 0, 0,
  21372. 0, 0, 0, 0, size, 0,
  21373. 0, 0, 0, 0, 0, size
  21374. ];
  21375. const colors = [
  21376. 1, 0, 0, 1, 0.6, 0,
  21377. 0, 1, 0, 0.6, 1, 0,
  21378. 0, 0, 1, 0, 0.6, 1
  21379. ];
  21380. const geometry = new BufferGeometry();
  21381. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21382. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  21383. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  21384. super( geometry, material );
  21385. this.type = 'AxesHelper';
  21386. }
  21387. setColors( xAxisColor, yAxisColor, zAxisColor ) {
  21388. const color = new Color();
  21389. const array = this.geometry.attributes.color.array;
  21390. color.set( xAxisColor );
  21391. color.toArray( array, 0 );
  21392. color.toArray( array, 3 );
  21393. color.set( yAxisColor );
  21394. color.toArray( array, 6 );
  21395. color.toArray( array, 9 );
  21396. color.set( zAxisColor );
  21397. color.toArray( array, 12 );
  21398. color.toArray( array, 15 );
  21399. this.geometry.attributes.color.needsUpdate = true;
  21400. return this;
  21401. }
  21402. dispose() {
  21403. this.geometry.dispose();
  21404. this.material.dispose();
  21405. }
  21406. }
  21407. class ShapePath {
  21408. constructor() {
  21409. this.type = 'ShapePath';
  21410. this.color = new Color();
  21411. this.subPaths = [];
  21412. this.currentPath = null;
  21413. }
  21414. moveTo( x, y ) {
  21415. this.currentPath = new Path();
  21416. this.subPaths.push( this.currentPath );
  21417. this.currentPath.moveTo( x, y );
  21418. return this;
  21419. }
  21420. lineTo( x, y ) {
  21421. this.currentPath.lineTo( x, y );
  21422. return this;
  21423. }
  21424. quadraticCurveTo( aCPx, aCPy, aX, aY ) {
  21425. this.currentPath.quadraticCurveTo( aCPx, aCPy, aX, aY );
  21426. return this;
  21427. }
  21428. bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  21429. this.currentPath.bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY );
  21430. return this;
  21431. }
  21432. splineThru( pts ) {
  21433. this.currentPath.splineThru( pts );
  21434. return this;
  21435. }
  21436. toShapes( isCCW ) {
  21437. function toShapesNoHoles( inSubpaths ) {
  21438. const shapes = [];
  21439. for ( let i = 0, l = inSubpaths.length; i < l; i ++ ) {
  21440. const tmpPath = inSubpaths[ i ];
  21441. const tmpShape = new Shape();
  21442. tmpShape.curves = tmpPath.curves;
  21443. shapes.push( tmpShape );
  21444. }
  21445. return shapes;
  21446. }
  21447. function isPointInsidePolygon( inPt, inPolygon ) {
  21448. const polyLen = inPolygon.length;
  21449. // inPt on polygon contour => immediate success or
  21450. // toggling of inside/outside at every single! intersection point of an edge
  21451. // with the horizontal line through inPt, left of inPt
  21452. // not counting lowerY endpoints of edges and whole edges on that line
  21453. let inside = false;
  21454. for ( let p = polyLen - 1, q = 0; q < polyLen; p = q ++ ) {
  21455. let edgeLowPt = inPolygon[ p ];
  21456. let edgeHighPt = inPolygon[ q ];
  21457. let edgeDx = edgeHighPt.x - edgeLowPt.x;
  21458. let edgeDy = edgeHighPt.y - edgeLowPt.y;
  21459. if ( Math.abs( edgeDy ) > Number.EPSILON ) {
  21460. // not parallel
  21461. if ( edgeDy < 0 ) {
  21462. edgeLowPt = inPolygon[ q ]; edgeDx = - edgeDx;
  21463. edgeHighPt = inPolygon[ p ]; edgeDy = - edgeDy;
  21464. }
  21465. if ( ( inPt.y < edgeLowPt.y ) || ( inPt.y > edgeHighPt.y ) ) continue;
  21466. if ( inPt.y === edgeLowPt.y ) {
  21467. if ( inPt.x === edgeLowPt.x ) return true; // inPt is on contour ?
  21468. // continue; // no intersection or edgeLowPt => doesn't count !!!
  21469. } else {
  21470. const perpEdge = edgeDy * ( inPt.x - edgeLowPt.x ) - edgeDx * ( inPt.y - edgeLowPt.y );
  21471. if ( perpEdge === 0 ) return true; // inPt is on contour ?
  21472. if ( perpEdge < 0 ) continue;
  21473. inside = ! inside; // true intersection left of inPt
  21474. }
  21475. } else {
  21476. // parallel or collinear
  21477. if ( inPt.y !== edgeLowPt.y ) continue; // parallel
  21478. // edge lies on the same horizontal line as inPt
  21479. if ( ( ( edgeHighPt.x <= inPt.x ) && ( inPt.x <= edgeLowPt.x ) ) ||
  21480. ( ( edgeLowPt.x <= inPt.x ) && ( inPt.x <= edgeHighPt.x ) ) ) return true; // inPt: Point on contour !
  21481. // continue;
  21482. }
  21483. }
  21484. return inside;
  21485. }
  21486. const isClockWise = ShapeUtils.isClockWise;
  21487. const subPaths = this.subPaths;
  21488. if ( subPaths.length === 0 ) return [];
  21489. let solid, tmpPath, tmpShape;
  21490. const shapes = [];
  21491. if ( subPaths.length === 1 ) {
  21492. tmpPath = subPaths[ 0 ];
  21493. tmpShape = new Shape();
  21494. tmpShape.curves = tmpPath.curves;
  21495. shapes.push( tmpShape );
  21496. return shapes;
  21497. }
  21498. let holesFirst = ! isClockWise( subPaths[ 0 ].getPoints() );
  21499. holesFirst = isCCW ? ! holesFirst : holesFirst;
  21500. // console.log("Holes first", holesFirst);
  21501. const betterShapeHoles = [];
  21502. const newShapes = [];
  21503. let newShapeHoles = [];
  21504. let mainIdx = 0;
  21505. let tmpPoints;
  21506. newShapes[ mainIdx ] = undefined;
  21507. newShapeHoles[ mainIdx ] = [];
  21508. for ( let i = 0, l = subPaths.length; i < l; i ++ ) {
  21509. tmpPath = subPaths[ i ];
  21510. tmpPoints = tmpPath.getPoints();
  21511. solid = isClockWise( tmpPoints );
  21512. solid = isCCW ? ! solid : solid;
  21513. if ( solid ) {
  21514. if ( ( ! holesFirst ) && ( newShapes[ mainIdx ] ) ) mainIdx ++;
  21515. newShapes[ mainIdx ] = { s: new Shape(), p: tmpPoints };
  21516. newShapes[ mainIdx ].s.curves = tmpPath.curves;
  21517. if ( holesFirst ) mainIdx ++;
  21518. newShapeHoles[ mainIdx ] = [];
  21519. //console.log('cw', i);
  21520. } else {
  21521. newShapeHoles[ mainIdx ].push( { h: tmpPath, p: tmpPoints[ 0 ] } );
  21522. //console.log('ccw', i);
  21523. }
  21524. }
  21525. // only Holes? -> probably all Shapes with wrong orientation
  21526. if ( ! newShapes[ 0 ] ) return toShapesNoHoles( subPaths );
  21527. if ( newShapes.length > 1 ) {
  21528. let ambiguous = false;
  21529. let toChange = 0;
  21530. for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  21531. betterShapeHoles[ sIdx ] = [];
  21532. }
  21533. for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  21534. const sho = newShapeHoles[ sIdx ];
  21535. for ( let hIdx = 0; hIdx < sho.length; hIdx ++ ) {
  21536. const ho = sho[ hIdx ];
  21537. let hole_unassigned = true;
  21538. for ( let s2Idx = 0; s2Idx < newShapes.length; s2Idx ++ ) {
  21539. if ( isPointInsidePolygon( ho.p, newShapes[ s2Idx ].p ) ) {
  21540. if ( sIdx !== s2Idx ) toChange ++;
  21541. if ( hole_unassigned ) {
  21542. hole_unassigned = false;
  21543. betterShapeHoles[ s2Idx ].push( ho );
  21544. } else {
  21545. ambiguous = true;
  21546. }
  21547. }
  21548. }
  21549. if ( hole_unassigned ) {
  21550. betterShapeHoles[ sIdx ].push( ho );
  21551. }
  21552. }
  21553. }
  21554. if ( toChange > 0 && ambiguous === false ) {
  21555. newShapeHoles = betterShapeHoles;
  21556. }
  21557. }
  21558. let tmpHoles;
  21559. for ( let i = 0, il = newShapes.length; i < il; i ++ ) {
  21560. tmpShape = newShapes[ i ].s;
  21561. shapes.push( tmpShape );
  21562. tmpHoles = newShapeHoles[ i ];
  21563. for ( let j = 0, jl = tmpHoles.length; j < jl; j ++ ) {
  21564. tmpShape.holes.push( tmpHoles[ j ].h );
  21565. }
  21566. }
  21567. //console.log("shape", shapes);
  21568. return shapes;
  21569. }
  21570. }
  21571. class Controls extends EventDispatcher {
  21572. constructor( object, domElement = null ) {
  21573. super();
  21574. this.object = object;
  21575. this.domElement = domElement;
  21576. this.enabled = true;
  21577. this.state = - 1;
  21578. this.keys = {};
  21579. this.mouseButtons = { LEFT: null, MIDDLE: null, RIGHT: null };
  21580. this.touches = { ONE: null, TWO: null };
  21581. }
  21582. connect() {}
  21583. disconnect() {}
  21584. dispose() {}
  21585. update( /* delta */ ) {}
  21586. }
  21587. class WebGLMultipleRenderTargets extends WebGLRenderTarget { // @deprecated, r162
  21588. constructor( width = 1, height = 1, count = 1, options = {} ) {
  21589. console.warn( 'THREE.WebGLMultipleRenderTargets has been deprecated and will be removed in r172. Use THREE.WebGLRenderTarget and set the "count" parameter to enable MRT.' );
  21590. super( width, height, { ...options, count } );
  21591. this.isWebGLMultipleRenderTargets = true;
  21592. }
  21593. get texture() {
  21594. return this.textures;
  21595. }
  21596. }
  21597. const refreshUniforms = [
  21598. 'alphaMap',
  21599. 'alphaTest',
  21600. 'anisotropy',
  21601. 'anisotropyMap',
  21602. 'anisotropyRotation',
  21603. 'aoMap',
  21604. 'attenuationColor',
  21605. 'attenuationDistance',
  21606. 'bumpMap',
  21607. 'clearcoat',
  21608. 'clearcoatMap',
  21609. 'clearcoatNormalMap',
  21610. 'clearcoatNormalScale',
  21611. 'clearcoatRoughness',
  21612. 'color',
  21613. 'dispersion',
  21614. 'displacementMap',
  21615. 'emissive',
  21616. 'emissiveMap',
  21617. 'envMap',
  21618. 'gradientMap',
  21619. 'ior',
  21620. 'iridescence',
  21621. 'iridescenceIOR',
  21622. 'iridescenceMap',
  21623. 'iridescenceThicknessMap',
  21624. 'lightMap',
  21625. 'map',
  21626. 'matcap',
  21627. 'metalness',
  21628. 'metalnessMap',
  21629. 'normalMap',
  21630. 'normalScale',
  21631. 'opacity',
  21632. 'roughness',
  21633. 'roughnessMap',
  21634. 'sheen',
  21635. 'sheenColor',
  21636. 'sheenColorMap',
  21637. 'sheenRoughnessMap',
  21638. 'shininess',
  21639. 'specular',
  21640. 'specularColor',
  21641. 'specularColorMap',
  21642. 'specularIntensity',
  21643. 'specularIntensityMap',
  21644. 'specularMap',
  21645. 'thickness',
  21646. 'transmission',
  21647. 'transmissionMap'
  21648. ];
  21649. class NodeMaterialObserver {
  21650. constructor( builder ) {
  21651. this.renderObjects = new WeakMap();
  21652. this.hasNode = this.containsNode( builder );
  21653. this.hasAnimation = builder.object.isSkinnedMesh === true;
  21654. this.refreshUniforms = refreshUniforms;
  21655. this.renderId = 0;
  21656. }
  21657. firstInitialization( renderObject ) {
  21658. const hasInitialized = this.renderObjects.has( renderObject );
  21659. if ( hasInitialized === false ) {
  21660. this.getRenderObjectData( renderObject );
  21661. return true;
  21662. }
  21663. return false;
  21664. }
  21665. getRenderObjectData( renderObject ) {
  21666. let data = this.renderObjects.get( renderObject );
  21667. if ( data === undefined ) {
  21668. const { geometry, material } = renderObject;
  21669. data = {
  21670. material: this.getMaterialData( material ),
  21671. geometry: {
  21672. attributes: this.getAttributesData( geometry.attributes ),
  21673. indexVersion: geometry.index ? geometry.index.version : null,
  21674. drawRange: { start: geometry.drawRange.start, count: geometry.drawRange.count }
  21675. },
  21676. worldMatrix: renderObject.object.matrixWorld.clone()
  21677. };
  21678. if ( renderObject.object.center ) {
  21679. data.center = renderObject.object.center.clone();
  21680. }
  21681. if ( renderObject.object.morphTargetInfluences ) {
  21682. data.morphTargetInfluences = renderObject.object.morphTargetInfluences.slice();
  21683. }
  21684. if ( renderObject.bundle !== null ) {
  21685. data.version = renderObject.bundle.version;
  21686. }
  21687. this.renderObjects.set( renderObject, data );
  21688. }
  21689. return data;
  21690. }
  21691. getAttributesData( attributes ) {
  21692. const attributesData = {};
  21693. for ( const name in attributes ) {
  21694. const attribute = attributes[ name ];
  21695. attributesData[ name ] = {
  21696. version: attribute.version
  21697. };
  21698. }
  21699. return attributesData;
  21700. }
  21701. containsNode( builder ) {
  21702. const material = builder.material;
  21703. for ( const property in material ) {
  21704. if ( material[ property ] && material[ property ].isNode )
  21705. return true;
  21706. }
  21707. if ( builder.renderer.nodes.modelViewMatrix !== null || builder.renderer.nodes.modelNormalViewMatrix !== null )
  21708. return true;
  21709. return false;
  21710. }
  21711. getMaterialData( material ) {
  21712. const data = {};
  21713. for ( const property of this.refreshUniforms ) {
  21714. const value = material[ property ];
  21715. if ( value === null || value === undefined ) continue;
  21716. if ( typeof value === 'object' && value.clone !== undefined ) {
  21717. if ( value.isTexture === true ) {
  21718. data[ property ] = { id: value.id, version: value.version };
  21719. } else {
  21720. data[ property ] = value.clone();
  21721. }
  21722. } else {
  21723. data[ property ] = value;
  21724. }
  21725. }
  21726. return data;
  21727. }
  21728. equals( renderObject ) {
  21729. const { object, material, geometry } = renderObject;
  21730. const renderObjectData = this.getRenderObjectData( renderObject );
  21731. // world matrix
  21732. if ( renderObjectData.worldMatrix.equals( object.matrixWorld ) !== true ) {
  21733. renderObjectData.worldMatrix.copy( object.matrixWorld );
  21734. return false;
  21735. }
  21736. // material
  21737. const materialData = renderObjectData.material;
  21738. for ( const property in materialData ) {
  21739. const value = materialData[ property ];
  21740. const mtlValue = material[ property ];
  21741. if ( value.equals !== undefined ) {
  21742. if ( value.equals( mtlValue ) === false ) {
  21743. value.copy( mtlValue );
  21744. return false;
  21745. }
  21746. } else if ( mtlValue.isTexture === true ) {
  21747. if ( value.id !== mtlValue.id || value.version !== mtlValue.version ) {
  21748. value.id = mtlValue.id;
  21749. value.version = mtlValue.version;
  21750. return false;
  21751. }
  21752. } else if ( value !== mtlValue ) {
  21753. materialData[ property ] = mtlValue;
  21754. return false;
  21755. }
  21756. }
  21757. // geometry
  21758. const storedGeometryData = renderObjectData.geometry;
  21759. const attributes = geometry.attributes;
  21760. const storedAttributes = storedGeometryData.attributes;
  21761. const storedAttributeNames = Object.keys( storedAttributes );
  21762. const currentAttributeNames = Object.keys( attributes );
  21763. if ( storedAttributeNames.length !== currentAttributeNames.length ) {
  21764. renderObjectData.geometry.attributes = this.getAttributesData( attributes );
  21765. return false;
  21766. }
  21767. // Compare each attribute
  21768. for ( const name of storedAttributeNames ) {
  21769. const storedAttributeData = storedAttributes[ name ];
  21770. const attribute = attributes[ name ];
  21771. if ( attribute === undefined ) {
  21772. // Attribute was removed
  21773. delete storedAttributes[ name ];
  21774. return false;
  21775. }
  21776. if ( storedAttributeData.version !== attribute.version ) {
  21777. storedAttributeData.version = attribute.version;
  21778. return false;
  21779. }
  21780. }
  21781. // Check index
  21782. const index = geometry.index;
  21783. const storedIndexVersion = storedGeometryData.indexVersion;
  21784. const currentIndexVersion = index ? index.version : null;
  21785. if ( storedIndexVersion !== currentIndexVersion ) {
  21786. storedGeometryData.indexVersion = currentIndexVersion;
  21787. return false;
  21788. }
  21789. // Check drawRange
  21790. if ( storedGeometryData.drawRange.start !== geometry.drawRange.start || storedGeometryData.drawRange.count !== geometry.drawRange.count ) {
  21791. storedGeometryData.drawRange.start = geometry.drawRange.start;
  21792. storedGeometryData.drawRange.count = geometry.drawRange.count;
  21793. return false;
  21794. }
  21795. // morph targets
  21796. if ( renderObjectData.morphTargetInfluences ) {
  21797. let morphChanged = false;
  21798. for ( let i = 0; i < renderObjectData.morphTargetInfluences.length; i ++ ) {
  21799. if ( renderObjectData.morphTargetInfluences[ i ] !== object.morphTargetInfluences[ i ] ) {
  21800. morphChanged = true;
  21801. }
  21802. }
  21803. if ( morphChanged ) return true;
  21804. }
  21805. // center
  21806. if ( renderObjectData.center ) {
  21807. if ( renderObjectData.center.equals( object.center ) === false ) {
  21808. renderObjectData.center.copy( object.center );
  21809. return true;
  21810. }
  21811. }
  21812. // bundle
  21813. if ( renderObject.bundle !== null ) {
  21814. renderObjectData.version = renderObject.bundle.version;
  21815. }
  21816. return true;
  21817. }
  21818. needsRefresh( renderObject, nodeFrame ) {
  21819. if ( this.hasNode || this.hasAnimation || this.firstInitialization( renderObject ) )
  21820. return true;
  21821. const { renderId } = nodeFrame;
  21822. if ( this.renderId !== renderId ) {
  21823. this.renderId = renderId;
  21824. return true;
  21825. }
  21826. const isStatic = renderObject.object.static === true;
  21827. const isBundle = renderObject.bundle !== null && renderObject.bundle.static === true && this.getRenderObjectData( renderObject ).version === renderObject.bundle.version;
  21828. if ( isStatic || isBundle )
  21829. return false;
  21830. const notEqual = this.equals( renderObject ) !== true;
  21831. return notEqual;
  21832. }
  21833. }
  21834. // cyrb53 (c) 2018 bryc (github.com/bryc). License: Public domain. Attribution appreciated.
  21835. // A fast and simple 64-bit (or 53-bit) string hash function with decent collision resistance.
  21836. // Largely inspired by MurmurHash2/3, but with a focus on speed/simplicity.
  21837. // See https://stackoverflow.com/questions/7616461/generate-a-hash-from-string-in-javascript/52171480#52171480
  21838. // https://github.com/bryc/code/blob/master/jshash/experimental/cyrb53.js
  21839. function cyrb53( value, seed = 0 ) {
  21840. let h1 = 0xdeadbeef ^ seed, h2 = 0x41c6ce57 ^ seed;
  21841. if ( value instanceof Array ) {
  21842. for ( let i = 0, val; i < value.length; i ++ ) {
  21843. val = value[ i ];
  21844. h1 = Math.imul( h1 ^ val, 2654435761 );
  21845. h2 = Math.imul( h2 ^ val, 1597334677 );
  21846. }
  21847. } else {
  21848. for ( let i = 0, ch; i < value.length; i ++ ) {
  21849. ch = value.charCodeAt( i );
  21850. h1 = Math.imul( h1 ^ ch, 2654435761 );
  21851. h2 = Math.imul( h2 ^ ch, 1597334677 );
  21852. }
  21853. }
  21854. h1 = Math.imul( h1 ^ ( h1 >>> 16 ), 2246822507 );
  21855. h1 ^= Math.imul( h2 ^ ( h2 >>> 13 ), 3266489909 );
  21856. h2 = Math.imul( h2 ^ ( h2 >>> 16 ), 2246822507 );
  21857. h2 ^= Math.imul( h1 ^ ( h1 >>> 13 ), 3266489909 );
  21858. return 4294967296 * ( 2097151 & h2 ) + ( h1 >>> 0 );
  21859. }
  21860. const hashString = ( str ) => cyrb53( str );
  21861. const hashArray = ( array ) => cyrb53( array );
  21862. const hash$1 = ( ...params ) => cyrb53( params );
  21863. function getCacheKey$1( object, force = false ) {
  21864. const values = [];
  21865. if ( object.isNode === true ) {
  21866. values.push( object.id );
  21867. object = object.getSelf();
  21868. }
  21869. for ( const { property, childNode } of getNodeChildren( object ) ) {
  21870. values.push( values, cyrb53( property.slice( 0, - 4 ) ), childNode.getCacheKey( force ) );
  21871. }
  21872. return cyrb53( values );
  21873. }
  21874. function* getNodeChildren( node, toJSON = false ) {
  21875. for ( const property in node ) {
  21876. // Ignore private properties.
  21877. if ( property.startsWith( '_' ) === true ) continue;
  21878. const object = node[ property ];
  21879. if ( Array.isArray( object ) === true ) {
  21880. for ( let i = 0; i < object.length; i ++ ) {
  21881. const child = object[ i ];
  21882. if ( child && ( child.isNode === true || toJSON && typeof child.toJSON === 'function' ) ) {
  21883. yield { property, index: i, childNode: child };
  21884. }
  21885. }
  21886. } else if ( object && object.isNode === true ) {
  21887. yield { property, childNode: object };
  21888. } else if ( typeof object === 'object' ) {
  21889. for ( const subProperty in object ) {
  21890. const child = object[ subProperty ];
  21891. if ( child && ( child.isNode === true || toJSON && typeof child.toJSON === 'function' ) ) {
  21892. yield { property, index: subProperty, childNode: child };
  21893. }
  21894. }
  21895. }
  21896. }
  21897. }
  21898. function getValueType( value ) {
  21899. if ( value === undefined || value === null ) return null;
  21900. const typeOf = typeof value;
  21901. if ( value.isNode === true ) {
  21902. return 'node';
  21903. } else if ( typeOf === 'number' ) {
  21904. return 'float';
  21905. } else if ( typeOf === 'boolean' ) {
  21906. return 'bool';
  21907. } else if ( typeOf === 'string' ) {
  21908. return 'string';
  21909. } else if ( typeOf === 'function' ) {
  21910. return 'shader';
  21911. } else if ( value.isVector2 === true ) {
  21912. return 'vec2';
  21913. } else if ( value.isVector3 === true ) {
  21914. return 'vec3';
  21915. } else if ( value.isVector4 === true ) {
  21916. return 'vec4';
  21917. } else if ( value.isMatrix3 === true ) {
  21918. return 'mat3';
  21919. } else if ( value.isMatrix4 === true ) {
  21920. return 'mat4';
  21921. } else if ( value.isColor === true ) {
  21922. return 'color';
  21923. } else if ( value instanceof ArrayBuffer ) {
  21924. return 'ArrayBuffer';
  21925. }
  21926. return null;
  21927. }
  21928. function getValueFromType( type, ...params ) {
  21929. const last4 = type ? type.slice( - 4 ) : undefined;
  21930. if ( params.length === 1 ) { // ensure same behaviour as in NodeBuilder.format()
  21931. if ( last4 === 'vec2' ) params = [ params[ 0 ], params[ 0 ] ];
  21932. else if ( last4 === 'vec3' ) params = [ params[ 0 ], params[ 0 ], params[ 0 ] ];
  21933. else if ( last4 === 'vec4' ) params = [ params[ 0 ], params[ 0 ], params[ 0 ], params[ 0 ] ];
  21934. }
  21935. if ( type === 'color' ) {
  21936. return new Color( ...params );
  21937. } else if ( last4 === 'vec2' ) {
  21938. return new Vector2( ...params );
  21939. } else if ( last4 === 'vec3' ) {
  21940. return new Vector3( ...params );
  21941. } else if ( last4 === 'vec4' ) {
  21942. return new Vector4( ...params );
  21943. } else if ( last4 === 'mat3' ) {
  21944. return new Matrix3( ...params );
  21945. } else if ( last4 === 'mat4' ) {
  21946. return new Matrix4( ...params );
  21947. } else if ( type === 'bool' ) {
  21948. return params[ 0 ] || false;
  21949. } else if ( ( type === 'float' ) || ( type === 'int' ) || ( type === 'uint' ) ) {
  21950. return params[ 0 ] || 0;
  21951. } else if ( type === 'string' ) {
  21952. return params[ 0 ] || '';
  21953. } else if ( type === 'ArrayBuffer' ) {
  21954. return base64ToArrayBuffer( params[ 0 ] );
  21955. }
  21956. return null;
  21957. }
  21958. function arrayBufferToBase64( arrayBuffer ) {
  21959. let chars = '';
  21960. const array = new Uint8Array( arrayBuffer );
  21961. for ( let i = 0; i < array.length; i ++ ) {
  21962. chars += String.fromCharCode( array[ i ] );
  21963. }
  21964. return btoa( chars );
  21965. }
  21966. function base64ToArrayBuffer( base64 ) {
  21967. return Uint8Array.from( atob( base64 ), c => c.charCodeAt( 0 ) ).buffer;
  21968. }
  21969. var NodeUtils = /*#__PURE__*/Object.freeze({
  21970. __proto__: null,
  21971. arrayBufferToBase64: arrayBufferToBase64,
  21972. base64ToArrayBuffer: base64ToArrayBuffer,
  21973. getCacheKey: getCacheKey$1,
  21974. getNodeChildren: getNodeChildren,
  21975. getValueFromType: getValueFromType,
  21976. getValueType: getValueType,
  21977. hash: hash$1,
  21978. hashArray: hashArray,
  21979. hashString: hashString
  21980. });
  21981. const NodeShaderStage = {
  21982. VERTEX: 'vertex',
  21983. FRAGMENT: 'fragment'
  21984. };
  21985. const NodeUpdateType = {
  21986. NONE: 'none',
  21987. FRAME: 'frame',
  21988. RENDER: 'render',
  21989. OBJECT: 'object'
  21990. };
  21991. const NodeType = {
  21992. BOOLEAN: 'bool',
  21993. INTEGER: 'int',
  21994. FLOAT: 'float',
  21995. VECTOR2: 'vec2',
  21996. VECTOR3: 'vec3',
  21997. VECTOR4: 'vec4',
  21998. MATRIX2: 'mat2',
  21999. MATRIX3: 'mat3',
  22000. MATRIX4: 'mat4'
  22001. };
  22002. const defaultShaderStages = [ 'fragment', 'vertex' ];
  22003. const defaultBuildStages = [ 'setup', 'analyze', 'generate' ];
  22004. const shaderStages = [ ...defaultShaderStages, 'compute' ];
  22005. const vectorComponents = [ 'x', 'y', 'z', 'w' ];
  22006. let _nodeId = 0;
  22007. class Node extends EventDispatcher {
  22008. static get type() {
  22009. return 'Node';
  22010. }
  22011. constructor( nodeType = null ) {
  22012. super();
  22013. this.nodeType = nodeType;
  22014. this.updateType = NodeUpdateType.NONE;
  22015. this.updateBeforeType = NodeUpdateType.NONE;
  22016. this.updateAfterType = NodeUpdateType.NONE;
  22017. this.uuid = MathUtils.generateUUID();
  22018. this.version = 0;
  22019. this._cacheKey = null;
  22020. this._cacheKeyVersion = 0;
  22021. this.global = false;
  22022. this.isNode = true;
  22023. Object.defineProperty( this, 'id', { value: _nodeId ++ } );
  22024. }
  22025. set needsUpdate( value ) {
  22026. if ( value === true ) {
  22027. this.version ++;
  22028. }
  22029. }
  22030. get type() {
  22031. return this.constructor.type;
  22032. }
  22033. onUpdate( callback, updateType ) {
  22034. this.updateType = updateType;
  22035. this.update = callback.bind( this.getSelf() );
  22036. return this;
  22037. }
  22038. onFrameUpdate( callback ) {
  22039. return this.onUpdate( callback, NodeUpdateType.FRAME );
  22040. }
  22041. onRenderUpdate( callback ) {
  22042. return this.onUpdate( callback, NodeUpdateType.RENDER );
  22043. }
  22044. onObjectUpdate( callback ) {
  22045. return this.onUpdate( callback, NodeUpdateType.OBJECT );
  22046. }
  22047. onReference( callback ) {
  22048. this.updateReference = callback.bind( this.getSelf() );
  22049. return this;
  22050. }
  22051. getSelf() {
  22052. // Returns non-node object.
  22053. return this.self || this;
  22054. }
  22055. updateReference( /*state*/ ) {
  22056. return this;
  22057. }
  22058. isGlobal( /*builder*/ ) {
  22059. return this.global;
  22060. }
  22061. * getChildren() {
  22062. for ( const { childNode } of getNodeChildren( this ) ) {
  22063. yield childNode;
  22064. }
  22065. }
  22066. dispose() {
  22067. this.dispatchEvent( { type: 'dispose' } );
  22068. }
  22069. traverse( callback ) {
  22070. callback( this );
  22071. for ( const childNode of this.getChildren() ) {
  22072. childNode.traverse( callback );
  22073. }
  22074. }
  22075. getCacheKey( force = false ) {
  22076. force = force || this.version !== this._cacheKeyVersion;
  22077. if ( force === true || this._cacheKey === null ) {
  22078. this._cacheKey = getCacheKey$1( this, force );
  22079. this._cacheKeyVersion = this.version;
  22080. }
  22081. return this._cacheKey;
  22082. }
  22083. getScope() {
  22084. return this;
  22085. }
  22086. getHash( /*builder*/ ) {
  22087. return this.uuid;
  22088. }
  22089. getUpdateType() {
  22090. return this.updateType;
  22091. }
  22092. getUpdateBeforeType() {
  22093. return this.updateBeforeType;
  22094. }
  22095. getUpdateAfterType() {
  22096. return this.updateAfterType;
  22097. }
  22098. getElementType( builder ) {
  22099. const type = this.getNodeType( builder );
  22100. const elementType = builder.getElementType( type );
  22101. return elementType;
  22102. }
  22103. getNodeType( builder ) {
  22104. const nodeProperties = builder.getNodeProperties( this );
  22105. if ( nodeProperties.outputNode ) {
  22106. return nodeProperties.outputNode.getNodeType( builder );
  22107. }
  22108. return this.nodeType;
  22109. }
  22110. getShared( builder ) {
  22111. const hash = this.getHash( builder );
  22112. const nodeFromHash = builder.getNodeFromHash( hash );
  22113. return nodeFromHash || this;
  22114. }
  22115. setup( builder ) {
  22116. const nodeProperties = builder.getNodeProperties( this );
  22117. let index = 0;
  22118. for ( const childNode of this.getChildren() ) {
  22119. nodeProperties[ 'node' + index ++ ] = childNode;
  22120. }
  22121. // return a outputNode if exists
  22122. return null;
  22123. }
  22124. analyze( builder ) {
  22125. const usageCount = builder.increaseUsage( this );
  22126. if ( usageCount === 1 ) {
  22127. // node flow children
  22128. const nodeProperties = builder.getNodeProperties( this );
  22129. for ( const childNode of Object.values( nodeProperties ) ) {
  22130. if ( childNode && childNode.isNode === true ) {
  22131. childNode.build( builder );
  22132. }
  22133. }
  22134. }
  22135. }
  22136. generate( builder, output ) {
  22137. const { outputNode } = builder.getNodeProperties( this );
  22138. if ( outputNode && outputNode.isNode === true ) {
  22139. return outputNode.build( builder, output );
  22140. }
  22141. }
  22142. updateBefore( /*frame*/ ) {
  22143. console.warn( 'Abstract function.' );
  22144. }
  22145. updateAfter( /*frame*/ ) {
  22146. console.warn( 'Abstract function.' );
  22147. }
  22148. update( /*frame*/ ) {
  22149. console.warn( 'Abstract function.' );
  22150. }
  22151. build( builder, output = null ) {
  22152. const refNode = this.getShared( builder );
  22153. if ( this !== refNode ) {
  22154. return refNode.build( builder, output );
  22155. }
  22156. builder.addNode( this );
  22157. builder.addChain( this );
  22158. /* Build stages expected results:
  22159. - "setup" -> Node
  22160. - "analyze" -> null
  22161. - "generate" -> String
  22162. */
  22163. let result = null;
  22164. const buildStage = builder.getBuildStage();
  22165. if ( buildStage === 'setup' ) {
  22166. this.updateReference( builder );
  22167. const properties = builder.getNodeProperties( this );
  22168. if ( properties.initialized !== true ) {
  22169. const stackNodesBeforeSetup = builder.stack.nodes.length;
  22170. properties.initialized = true;
  22171. properties.outputNode = this.setup( builder );
  22172. if ( properties.outputNode !== null && builder.stack.nodes.length !== stackNodesBeforeSetup ) ;
  22173. for ( const childNode of Object.values( properties ) ) {
  22174. if ( childNode && childNode.isNode === true ) {
  22175. childNode.build( builder );
  22176. }
  22177. }
  22178. }
  22179. } else if ( buildStage === 'analyze' ) {
  22180. this.analyze( builder );
  22181. } else if ( buildStage === 'generate' ) {
  22182. const isGenerateOnce = this.generate.length === 1;
  22183. if ( isGenerateOnce ) {
  22184. const type = this.getNodeType( builder );
  22185. const nodeData = builder.getDataFromNode( this );
  22186. result = nodeData.snippet;
  22187. if ( result === undefined ) {
  22188. result = this.generate( builder ) || '';
  22189. nodeData.snippet = result;
  22190. } else if ( nodeData.flowCodes !== undefined && builder.context.nodeBlock !== undefined ) {
  22191. builder.addFlowCodeHierarchy( this, builder.context.nodeBlock );
  22192. }
  22193. result = builder.format( result, type, output );
  22194. } else {
  22195. result = this.generate( builder, output ) || '';
  22196. }
  22197. }
  22198. builder.removeChain( this );
  22199. return result;
  22200. }
  22201. getSerializeChildren() {
  22202. return getNodeChildren( this );
  22203. }
  22204. serialize( json ) {
  22205. const nodeChildren = this.getSerializeChildren();
  22206. const inputNodes = {};
  22207. for ( const { property, index, childNode } of nodeChildren ) {
  22208. if ( index !== undefined ) {
  22209. if ( inputNodes[ property ] === undefined ) {
  22210. inputNodes[ property ] = Number.isInteger( index ) ? [] : {};
  22211. }
  22212. inputNodes[ property ][ index ] = childNode.toJSON( json.meta ).uuid;
  22213. } else {
  22214. inputNodes[ property ] = childNode.toJSON( json.meta ).uuid;
  22215. }
  22216. }
  22217. if ( Object.keys( inputNodes ).length > 0 ) {
  22218. json.inputNodes = inputNodes;
  22219. }
  22220. }
  22221. deserialize( json ) {
  22222. if ( json.inputNodes !== undefined ) {
  22223. const nodes = json.meta.nodes;
  22224. for ( const property in json.inputNodes ) {
  22225. if ( Array.isArray( json.inputNodes[ property ] ) ) {
  22226. const inputArray = [];
  22227. for ( const uuid of json.inputNodes[ property ] ) {
  22228. inputArray.push( nodes[ uuid ] );
  22229. }
  22230. this[ property ] = inputArray;
  22231. } else if ( typeof json.inputNodes[ property ] === 'object' ) {
  22232. const inputObject = {};
  22233. for ( const subProperty in json.inputNodes[ property ] ) {
  22234. const uuid = json.inputNodes[ property ][ subProperty ];
  22235. inputObject[ subProperty ] = nodes[ uuid ];
  22236. }
  22237. this[ property ] = inputObject;
  22238. } else {
  22239. const uuid = json.inputNodes[ property ];
  22240. this[ property ] = nodes[ uuid ];
  22241. }
  22242. }
  22243. }
  22244. }
  22245. toJSON( meta ) {
  22246. const { uuid, type } = this;
  22247. const isRoot = ( meta === undefined || typeof meta === 'string' );
  22248. if ( isRoot ) {
  22249. meta = {
  22250. textures: {},
  22251. images: {},
  22252. nodes: {}
  22253. };
  22254. }
  22255. // serialize
  22256. let data = meta.nodes[ uuid ];
  22257. if ( data === undefined ) {
  22258. data = {
  22259. uuid,
  22260. type,
  22261. meta,
  22262. metadata: {
  22263. version: 4.6,
  22264. type: 'Node',
  22265. generator: 'Node.toJSON'
  22266. }
  22267. };
  22268. if ( isRoot !== true ) meta.nodes[ data.uuid ] = data;
  22269. this.serialize( data );
  22270. delete data.meta;
  22271. }
  22272. // TODO: Copied from Object3D.toJSON
  22273. function extractFromCache( cache ) {
  22274. const values = [];
  22275. for ( const key in cache ) {
  22276. const data = cache[ key ];
  22277. delete data.metadata;
  22278. values.push( data );
  22279. }
  22280. return values;
  22281. }
  22282. if ( isRoot ) {
  22283. const textures = extractFromCache( meta.textures );
  22284. const images = extractFromCache( meta.images );
  22285. const nodes = extractFromCache( meta.nodes );
  22286. if ( textures.length > 0 ) data.textures = textures;
  22287. if ( images.length > 0 ) data.images = images;
  22288. if ( nodes.length > 0 ) data.nodes = nodes;
  22289. }
  22290. return data;
  22291. }
  22292. }
  22293. class ArrayElementNode extends Node {
  22294. static get type() {
  22295. return 'ArrayElementNode';
  22296. } // @TODO: If extending from TempNode it breaks webgpu_compute
  22297. constructor( node, indexNode ) {
  22298. super();
  22299. this.node = node;
  22300. this.indexNode = indexNode;
  22301. this.isArrayElementNode = true;
  22302. }
  22303. getNodeType( builder ) {
  22304. return this.node.getElementType( builder );
  22305. }
  22306. generate( builder ) {
  22307. const nodeSnippet = this.node.build( builder );
  22308. const indexSnippet = this.indexNode.build( builder, 'uint' );
  22309. return `${nodeSnippet}[ ${indexSnippet} ]`;
  22310. }
  22311. }
  22312. class ConvertNode extends Node {
  22313. static get type() {
  22314. return 'ConvertNode';
  22315. }
  22316. constructor( node, convertTo ) {
  22317. super();
  22318. this.node = node;
  22319. this.convertTo = convertTo;
  22320. }
  22321. getNodeType( builder ) {
  22322. const requestType = this.node.getNodeType( builder );
  22323. let convertTo = null;
  22324. for ( const overloadingType of this.convertTo.split( '|' ) ) {
  22325. if ( convertTo === null || builder.getTypeLength( requestType ) === builder.getTypeLength( overloadingType ) ) {
  22326. convertTo = overloadingType;
  22327. }
  22328. }
  22329. return convertTo;
  22330. }
  22331. serialize( data ) {
  22332. super.serialize( data );
  22333. data.convertTo = this.convertTo;
  22334. }
  22335. deserialize( data ) {
  22336. super.deserialize( data );
  22337. this.convertTo = data.convertTo;
  22338. }
  22339. generate( builder, output ) {
  22340. const node = this.node;
  22341. const type = this.getNodeType( builder );
  22342. const snippet = node.build( builder, type );
  22343. return builder.format( snippet, type, output );
  22344. }
  22345. }
  22346. class TempNode extends Node {
  22347. static get type() {
  22348. return 'TempNode';
  22349. }
  22350. constructor( type ) {
  22351. super( type );
  22352. this.isTempNode = true;
  22353. }
  22354. hasDependencies( builder ) {
  22355. return builder.getDataFromNode( this ).usageCount > 1;
  22356. }
  22357. build( builder, output ) {
  22358. const buildStage = builder.getBuildStage();
  22359. if ( buildStage === 'generate' ) {
  22360. const type = builder.getVectorType( this.getNodeType( builder, output ) );
  22361. const nodeData = builder.getDataFromNode( this );
  22362. if ( nodeData.propertyName !== undefined ) {
  22363. return builder.format( nodeData.propertyName, type, output );
  22364. } else if ( type !== 'void' && output !== 'void' && this.hasDependencies( builder ) ) {
  22365. const snippet = super.build( builder, type );
  22366. const nodeVar = builder.getVarFromNode( this, null, type );
  22367. const propertyName = builder.getPropertyName( nodeVar );
  22368. builder.addLineFlowCode( `${propertyName} = ${snippet}`, this );
  22369. nodeData.snippet = snippet;
  22370. nodeData.propertyName = propertyName;
  22371. return builder.format( nodeData.propertyName, type, output );
  22372. }
  22373. }
  22374. return super.build( builder, output );
  22375. }
  22376. }
  22377. class JoinNode extends TempNode {
  22378. static get type() {
  22379. return 'JoinNode';
  22380. }
  22381. constructor( nodes = [], nodeType = null ) {
  22382. super( nodeType );
  22383. this.nodes = nodes;
  22384. }
  22385. getNodeType( builder ) {
  22386. if ( this.nodeType !== null ) {
  22387. return builder.getVectorType( this.nodeType );
  22388. }
  22389. return builder.getTypeFromLength( this.nodes.reduce( ( count, cur ) => count + builder.getTypeLength( cur.getNodeType( builder ) ), 0 ) );
  22390. }
  22391. generate( builder, output ) {
  22392. const type = this.getNodeType( builder );
  22393. const nodes = this.nodes;
  22394. const primitiveType = builder.getComponentType( type );
  22395. const snippetValues = [];
  22396. for ( const input of nodes ) {
  22397. let inputSnippet = input.build( builder );
  22398. const inputPrimitiveType = builder.getComponentType( input.getNodeType( builder ) );
  22399. if ( inputPrimitiveType !== primitiveType ) {
  22400. inputSnippet = builder.format( inputSnippet, inputPrimitiveType, primitiveType );
  22401. }
  22402. snippetValues.push( inputSnippet );
  22403. }
  22404. const snippet = `${ builder.getType( type ) }( ${ snippetValues.join( ', ' ) } )`;
  22405. return builder.format( snippet, type, output );
  22406. }
  22407. }
  22408. const stringVectorComponents = vectorComponents.join( '' );
  22409. class SplitNode extends Node {
  22410. static get type() {
  22411. return 'SplitNode';
  22412. }
  22413. constructor( node, components = 'x' ) {
  22414. super();
  22415. this.node = node;
  22416. this.components = components;
  22417. this.isSplitNode = true;
  22418. }
  22419. getVectorLength() {
  22420. let vectorLength = this.components.length;
  22421. for ( const c of this.components ) {
  22422. vectorLength = Math.max( vectorComponents.indexOf( c ) + 1, vectorLength );
  22423. }
  22424. return vectorLength;
  22425. }
  22426. getComponentType( builder ) {
  22427. return builder.getComponentType( this.node.getNodeType( builder ) );
  22428. }
  22429. getNodeType( builder ) {
  22430. return builder.getTypeFromLength( this.components.length, this.getComponentType( builder ) );
  22431. }
  22432. generate( builder, output ) {
  22433. const node = this.node;
  22434. const nodeTypeLength = builder.getTypeLength( node.getNodeType( builder ) );
  22435. let snippet = null;
  22436. if ( nodeTypeLength > 1 ) {
  22437. let type = null;
  22438. const componentsLength = this.getVectorLength();
  22439. if ( componentsLength >= nodeTypeLength ) {
  22440. // needed expand the input node
  22441. type = builder.getTypeFromLength( this.getVectorLength(), this.getComponentType( builder ) );
  22442. }
  22443. const nodeSnippet = node.build( builder, type );
  22444. if ( this.components.length === nodeTypeLength && this.components === stringVectorComponents.slice( 0, this.components.length ) ) {
  22445. // unnecessary swizzle
  22446. snippet = builder.format( nodeSnippet, type, output );
  22447. } else {
  22448. snippet = builder.format( `${nodeSnippet}.${this.components}`, this.getNodeType( builder ), output );
  22449. }
  22450. } else {
  22451. // ignore .components if .node returns float/integer
  22452. snippet = node.build( builder, output );
  22453. }
  22454. return snippet;
  22455. }
  22456. serialize( data ) {
  22457. super.serialize( data );
  22458. data.components = this.components;
  22459. }
  22460. deserialize( data ) {
  22461. super.deserialize( data );
  22462. this.components = data.components;
  22463. }
  22464. }
  22465. class SetNode extends TempNode {
  22466. static get type() {
  22467. return 'SetNode';
  22468. }
  22469. constructor( sourceNode, components, targetNode ) {
  22470. super();
  22471. this.sourceNode = sourceNode;
  22472. this.components = components;
  22473. this.targetNode = targetNode;
  22474. }
  22475. getNodeType( builder ) {
  22476. return this.sourceNode.getNodeType( builder );
  22477. }
  22478. generate( builder ) {
  22479. const { sourceNode, components, targetNode } = this;
  22480. const sourceType = this.getNodeType( builder );
  22481. const targetType = builder.getTypeFromLength( components.length, targetNode.getNodeType( builder ) );
  22482. const targetSnippet = targetNode.build( builder, targetType );
  22483. const sourceSnippet = sourceNode.build( builder, sourceType );
  22484. const length = builder.getTypeLength( sourceType );
  22485. const snippetValues = [];
  22486. for ( let i = 0; i < length; i ++ ) {
  22487. const component = vectorComponents[ i ];
  22488. if ( component === components[ 0 ] ) {
  22489. snippetValues.push( targetSnippet );
  22490. i += components.length - 1;
  22491. } else {
  22492. snippetValues.push( sourceSnippet + '.' + component );
  22493. }
  22494. }
  22495. return `${ builder.getType( sourceType ) }( ${ snippetValues.join( ', ' ) } )`;
  22496. }
  22497. }
  22498. class FlipNode extends TempNode {
  22499. static get type() {
  22500. return 'FlipNode';
  22501. }
  22502. constructor( sourceNode, components ) {
  22503. super();
  22504. this.sourceNode = sourceNode;
  22505. this.components = components;
  22506. }
  22507. getNodeType( builder ) {
  22508. return this.sourceNode.getNodeType( builder );
  22509. }
  22510. generate( builder ) {
  22511. const { components, sourceNode } = this;
  22512. const sourceType = this.getNodeType( builder );
  22513. const sourceSnippet = sourceNode.build( builder );
  22514. const sourceCache = builder.getVarFromNode( this );
  22515. const sourceProperty = builder.getPropertyName( sourceCache );
  22516. builder.addLineFlowCode( sourceProperty + ' = ' + sourceSnippet, this );
  22517. const length = builder.getTypeLength( sourceType );
  22518. const snippetValues = [];
  22519. let componentIndex = 0;
  22520. for ( let i = 0; i < length; i ++ ) {
  22521. const component = vectorComponents[ i ];
  22522. if ( component === components[ componentIndex ] ) {
  22523. snippetValues.push( '1.0 - ' + ( sourceProperty + '.' + component ) );
  22524. componentIndex ++;
  22525. } else {
  22526. snippetValues.push( sourceProperty + '.' + component );
  22527. }
  22528. }
  22529. return `${ builder.getType( sourceType ) }( ${ snippetValues.join( ', ' ) } )`;
  22530. }
  22531. }
  22532. class InputNode extends Node {
  22533. static get type() {
  22534. return 'InputNode';
  22535. }
  22536. constructor( value, nodeType = null ) {
  22537. super( nodeType );
  22538. this.isInputNode = true;
  22539. this.value = value;
  22540. this.precision = null;
  22541. }
  22542. getNodeType( /*builder*/ ) {
  22543. if ( this.nodeType === null ) {
  22544. return getValueType( this.value );
  22545. }
  22546. return this.nodeType;
  22547. }
  22548. getInputType( builder ) {
  22549. return this.getNodeType( builder );
  22550. }
  22551. setPrecision( precision ) {
  22552. this.precision = precision;
  22553. return this;
  22554. }
  22555. serialize( data ) {
  22556. super.serialize( data );
  22557. data.value = this.value;
  22558. if ( this.value && this.value.toArray ) data.value = this.value.toArray();
  22559. data.valueType = getValueType( this.value );
  22560. data.nodeType = this.nodeType;
  22561. if ( data.valueType === 'ArrayBuffer' ) data.value = arrayBufferToBase64( data.value );
  22562. data.precision = this.precision;
  22563. }
  22564. deserialize( data ) {
  22565. super.deserialize( data );
  22566. this.nodeType = data.nodeType;
  22567. this.value = Array.isArray( data.value ) ? getValueFromType( data.valueType, ...data.value ) : data.value;
  22568. this.precision = data.precision || null;
  22569. if ( this.value && this.value.fromArray ) this.value = this.value.fromArray( data.value );
  22570. }
  22571. generate( /*builder, output*/ ) {
  22572. console.warn( 'Abstract function.' );
  22573. }
  22574. }
  22575. class ConstNode extends InputNode {
  22576. static get type() {
  22577. return 'ConstNode';
  22578. }
  22579. constructor( value, nodeType = null ) {
  22580. super( value, nodeType );
  22581. this.isConstNode = true;
  22582. }
  22583. generateConst( builder ) {
  22584. return builder.generateConst( this.getNodeType( builder ), this.value );
  22585. }
  22586. generate( builder, output ) {
  22587. const type = this.getNodeType( builder );
  22588. return builder.format( this.generateConst( builder ), type, output );
  22589. }
  22590. }
  22591. //
  22592. let currentStack = null;
  22593. const NodeElements = new Map();
  22594. function addMethodChaining( name, nodeElement ) {
  22595. if ( NodeElements.has( name ) ) {
  22596. console.warn( `Redefinition of method chaining ${ name }` );
  22597. return;
  22598. }
  22599. if ( typeof nodeElement !== 'function' ) throw new Error( `Node element ${ name } is not a function` );
  22600. NodeElements.set( name, nodeElement );
  22601. }
  22602. const parseSwizzle = ( props ) => props.replace( /r|s/g, 'x' ).replace( /g|t/g, 'y' ).replace( /b|p/g, 'z' ).replace( /a|q/g, 'w' );
  22603. const parseSwizzleAndSort = ( props ) => parseSwizzle( props ).split( '' ).sort().join( '' );
  22604. const shaderNodeHandler = {
  22605. setup( NodeClosure, params ) {
  22606. const inputs = params.shift();
  22607. return NodeClosure( nodeObjects( inputs ), ...params );
  22608. },
  22609. get( node, prop, nodeObj ) {
  22610. if ( typeof prop === 'string' && node[ prop ] === undefined ) {
  22611. if ( node.isStackNode !== true && prop === 'assign' ) {
  22612. return ( ...params ) => {
  22613. currentStack.assign( nodeObj, ...params );
  22614. return nodeObj;
  22615. };
  22616. } else if ( NodeElements.has( prop ) ) {
  22617. const nodeElement = NodeElements.get( prop );
  22618. return node.isStackNode ? ( ...params ) => nodeObj.add( nodeElement( ...params ) ) : ( ...params ) => nodeElement( nodeObj, ...params );
  22619. } else if ( prop === 'self' ) {
  22620. return node;
  22621. } else if ( prop.endsWith( 'Assign' ) && NodeElements.has( prop.slice( 0, prop.length - 'Assign'.length ) ) ) {
  22622. const nodeElement = NodeElements.get( prop.slice( 0, prop.length - 'Assign'.length ) );
  22623. return node.isStackNode ? ( ...params ) => nodeObj.assign( params[ 0 ], nodeElement( ...params ) ) : ( ...params ) => nodeObj.assign( nodeElement( nodeObj, ...params ) );
  22624. } else if ( /^[xyzwrgbastpq]{1,4}$/.test( prop ) === true ) {
  22625. // accessing properties ( swizzle )
  22626. prop = parseSwizzle( prop );
  22627. return nodeObject( new SplitNode( nodeObj, prop ) );
  22628. } else if ( /^set[XYZWRGBASTPQ]{1,4}$/.test( prop ) === true ) {
  22629. // set properties ( swizzle ) and sort to xyzw sequence
  22630. prop = parseSwizzleAndSort( prop.slice( 3 ).toLowerCase() );
  22631. return ( value ) => nodeObject( new SetNode( node, prop, value ) );
  22632. } else if ( /^flip[XYZWRGBASTPQ]{1,4}$/.test( prop ) === true ) {
  22633. // set properties ( swizzle ) and sort to xyzw sequence
  22634. prop = parseSwizzleAndSort( prop.slice( 4 ).toLowerCase() );
  22635. return () => nodeObject( new FlipNode( nodeObject( node ), prop ) );
  22636. } else if ( prop === 'width' || prop === 'height' || prop === 'depth' ) {
  22637. // accessing property
  22638. if ( prop === 'width' ) prop = 'x';
  22639. else if ( prop === 'height' ) prop = 'y';
  22640. else if ( prop === 'depth' ) prop = 'z';
  22641. return nodeObject( new SplitNode( node, prop ) );
  22642. } else if ( /^\d+$/.test( prop ) === true ) {
  22643. // accessing array
  22644. return nodeObject( new ArrayElementNode( nodeObj, new ConstNode( Number( prop ), 'uint' ) ) );
  22645. }
  22646. }
  22647. return Reflect.get( node, prop, nodeObj );
  22648. },
  22649. set( node, prop, value, nodeObj ) {
  22650. if ( typeof prop === 'string' && node[ prop ] === undefined ) {
  22651. // setting properties
  22652. if ( /^[xyzwrgbastpq]{1,4}$/.test( prop ) === true || prop === 'width' || prop === 'height' || prop === 'depth' || /^\d+$/.test( prop ) === true ) {
  22653. nodeObj[ prop ].assign( value );
  22654. return true;
  22655. }
  22656. }
  22657. return Reflect.set( node, prop, value, nodeObj );
  22658. }
  22659. };
  22660. const nodeObjectsCacheMap = new WeakMap();
  22661. const nodeBuilderFunctionsCacheMap = new WeakMap();
  22662. const ShaderNodeObject = function ( obj, altType = null ) {
  22663. const type = getValueType( obj );
  22664. if ( type === 'node' ) {
  22665. let nodeObject = nodeObjectsCacheMap.get( obj );
  22666. if ( nodeObject === undefined ) {
  22667. nodeObject = new Proxy( obj, shaderNodeHandler );
  22668. nodeObjectsCacheMap.set( obj, nodeObject );
  22669. nodeObjectsCacheMap.set( nodeObject, nodeObject );
  22670. }
  22671. return nodeObject;
  22672. } else if ( ( altType === null && ( type === 'float' || type === 'boolean' ) ) || ( type && type !== 'shader' && type !== 'string' ) ) {
  22673. return nodeObject( getConstNode( obj, altType ) );
  22674. } else if ( type === 'shader' ) {
  22675. return Fn( obj );
  22676. }
  22677. return obj;
  22678. };
  22679. const ShaderNodeObjects = function ( objects, altType = null ) {
  22680. for ( const name in objects ) {
  22681. objects[ name ] = nodeObject( objects[ name ], altType );
  22682. }
  22683. return objects;
  22684. };
  22685. const ShaderNodeArray = function ( array, altType = null ) {
  22686. const len = array.length;
  22687. for ( let i = 0; i < len; i ++ ) {
  22688. array[ i ] = nodeObject( array[ i ], altType );
  22689. }
  22690. return array;
  22691. };
  22692. const ShaderNodeProxy = function ( NodeClass, scope = null, factor = null, settings = null ) {
  22693. const assignNode = ( node ) => nodeObject( settings !== null ? Object.assign( node, settings ) : node );
  22694. if ( scope === null ) {
  22695. return ( ...params ) => {
  22696. return assignNode( new NodeClass( ...nodeArray( params ) ) );
  22697. };
  22698. } else if ( factor !== null ) {
  22699. factor = nodeObject( factor );
  22700. return ( ...params ) => {
  22701. return assignNode( new NodeClass( scope, ...nodeArray( params ), factor ) );
  22702. };
  22703. } else {
  22704. return ( ...params ) => {
  22705. return assignNode( new NodeClass( scope, ...nodeArray( params ) ) );
  22706. };
  22707. }
  22708. };
  22709. const ShaderNodeImmutable = function ( NodeClass, ...params ) {
  22710. return nodeObject( new NodeClass( ...nodeArray( params ) ) );
  22711. };
  22712. class ShaderCallNodeInternal extends Node {
  22713. constructor( shaderNode, inputNodes ) {
  22714. super();
  22715. this.shaderNode = shaderNode;
  22716. this.inputNodes = inputNodes;
  22717. }
  22718. getNodeType( builder ) {
  22719. return this.shaderNode.nodeType || this.getOutputNode( builder ).getNodeType( builder );
  22720. }
  22721. call( builder ) {
  22722. const { shaderNode, inputNodes } = this;
  22723. const properties = builder.getNodeProperties( shaderNode );
  22724. if ( properties.onceOutput ) return properties.onceOutput;
  22725. //
  22726. let result = null;
  22727. if ( shaderNode.layout ) {
  22728. let functionNodesCacheMap = nodeBuilderFunctionsCacheMap.get( builder.constructor );
  22729. if ( functionNodesCacheMap === undefined ) {
  22730. functionNodesCacheMap = new WeakMap();
  22731. nodeBuilderFunctionsCacheMap.set( builder.constructor, functionNodesCacheMap );
  22732. }
  22733. let functionNode = functionNodesCacheMap.get( shaderNode );
  22734. if ( functionNode === undefined ) {
  22735. functionNode = nodeObject( builder.buildFunctionNode( shaderNode ) );
  22736. functionNodesCacheMap.set( shaderNode, functionNode );
  22737. }
  22738. if ( builder.currentFunctionNode !== null ) {
  22739. builder.currentFunctionNode.includes.push( functionNode );
  22740. }
  22741. result = nodeObject( functionNode.call( inputNodes ) );
  22742. } else {
  22743. const jsFunc = shaderNode.jsFunc;
  22744. const outputNode = inputNodes !== null ? jsFunc( inputNodes, builder ) : jsFunc( builder );
  22745. result = nodeObject( outputNode );
  22746. }
  22747. if ( shaderNode.once ) {
  22748. properties.onceOutput = result;
  22749. }
  22750. return result;
  22751. }
  22752. getOutputNode( builder ) {
  22753. const properties = builder.getNodeProperties( this );
  22754. if ( properties.outputNode === null ) {
  22755. properties.outputNode = this.setupOutput( builder );
  22756. }
  22757. return properties.outputNode;
  22758. }
  22759. setup( builder ) {
  22760. return this.getOutputNode( builder );
  22761. }
  22762. setupOutput( builder ) {
  22763. builder.addStack();
  22764. builder.stack.outputNode = this.call( builder );
  22765. return builder.removeStack();
  22766. }
  22767. generate( builder, output ) {
  22768. const outputNode = this.getOutputNode( builder );
  22769. return outputNode.build( builder, output );
  22770. }
  22771. }
  22772. class ShaderNodeInternal extends Node {
  22773. constructor( jsFunc, nodeType ) {
  22774. super( nodeType );
  22775. this.jsFunc = jsFunc;
  22776. this.layout = null;
  22777. this.global = true;
  22778. this.once = false;
  22779. }
  22780. setLayout( layout ) {
  22781. this.layout = layout;
  22782. return this;
  22783. }
  22784. call( inputs = null ) {
  22785. nodeObjects( inputs );
  22786. return nodeObject( new ShaderCallNodeInternal( this, inputs ) );
  22787. }
  22788. setup() {
  22789. return this.call();
  22790. }
  22791. }
  22792. const bools = [ false, true ];
  22793. const uints = [ 0, 1, 2, 3 ];
  22794. const ints = [ - 1, - 2 ];
  22795. const floats = [ 0.5, 1.5, 1 / 3, 1e-6, 1e6, Math.PI, Math.PI * 2, 1 / Math.PI, 2 / Math.PI, 1 / ( Math.PI * 2 ), Math.PI / 2 ];
  22796. const boolsCacheMap = new Map();
  22797. for ( const bool of bools ) boolsCacheMap.set( bool, new ConstNode( bool ) );
  22798. const uintsCacheMap = new Map();
  22799. for ( const uint of uints ) uintsCacheMap.set( uint, new ConstNode( uint, 'uint' ) );
  22800. const intsCacheMap = new Map( [ ...uintsCacheMap ].map( el => new ConstNode( el.value, 'int' ) ) );
  22801. for ( const int of ints ) intsCacheMap.set( int, new ConstNode( int, 'int' ) );
  22802. const floatsCacheMap = new Map( [ ...intsCacheMap ].map( el => new ConstNode( el.value ) ) );
  22803. for ( const float of floats ) floatsCacheMap.set( float, new ConstNode( float ) );
  22804. for ( const float of floats ) floatsCacheMap.set( - float, new ConstNode( - float ) );
  22805. const cacheMaps = { bool: boolsCacheMap, uint: uintsCacheMap, ints: intsCacheMap, float: floatsCacheMap };
  22806. const constNodesCacheMap = new Map( [ ...boolsCacheMap, ...floatsCacheMap ] );
  22807. const getConstNode = ( value, type ) => {
  22808. if ( constNodesCacheMap.has( value ) ) {
  22809. return constNodesCacheMap.get( value );
  22810. } else if ( value.isNode === true ) {
  22811. return value;
  22812. } else {
  22813. return new ConstNode( value, type );
  22814. }
  22815. };
  22816. const safeGetNodeType = ( node ) => {
  22817. try {
  22818. return node.getNodeType();
  22819. } catch ( _ ) {
  22820. return undefined;
  22821. }
  22822. };
  22823. const ConvertType = function ( type, cacheMap = null ) {
  22824. return ( ...params ) => {
  22825. if ( params.length === 0 || ( ! [ 'bool', 'float', 'int', 'uint' ].includes( type ) && params.every( param => typeof param !== 'object' ) ) ) {
  22826. params = [ getValueFromType( type, ...params ) ];
  22827. }
  22828. if ( params.length === 1 && cacheMap !== null && cacheMap.has( params[ 0 ] ) ) {
  22829. return nodeObject( cacheMap.get( params[ 0 ] ) );
  22830. }
  22831. if ( params.length === 1 ) {
  22832. const node = getConstNode( params[ 0 ], type );
  22833. if ( safeGetNodeType( node ) === type ) return nodeObject( node );
  22834. return nodeObject( new ConvertNode( node, type ) );
  22835. }
  22836. const nodes = params.map( param => getConstNode( param ) );
  22837. return nodeObject( new JoinNode( nodes, type ) );
  22838. };
  22839. };
  22840. // exports
  22841. const defined = ( v ) => typeof v === 'object' && v !== null ? v.value : v; // TODO: remove boolean conversion and defined function
  22842. // utils
  22843. const getConstNodeType = ( value ) => ( value !== undefined && value !== null ) ? ( value.nodeType || value.convertTo || ( typeof value === 'string' ? value : null ) ) : null;
  22844. // shader node base
  22845. function ShaderNode( jsFunc, nodeType ) {
  22846. return new Proxy( new ShaderNodeInternal( jsFunc, nodeType ), shaderNodeHandler );
  22847. }
  22848. const nodeObject = ( val, altType = null ) => /* new */ ShaderNodeObject( val, altType );
  22849. const nodeObjects = ( val, altType = null ) => new ShaderNodeObjects( val, altType );
  22850. const nodeArray = ( val, altType = null ) => new ShaderNodeArray( val, altType );
  22851. const nodeProxy = ( ...params ) => new ShaderNodeProxy( ...params );
  22852. const nodeImmutable = ( ...params ) => new ShaderNodeImmutable( ...params );
  22853. const Fn = ( jsFunc, nodeType ) => {
  22854. const shaderNode = new ShaderNode( jsFunc, nodeType );
  22855. const fn = ( ...params ) => {
  22856. let inputs;
  22857. nodeObjects( params );
  22858. if ( params[ 0 ] && params[ 0 ].isNode ) {
  22859. inputs = [ ...params ];
  22860. } else {
  22861. inputs = params[ 0 ];
  22862. }
  22863. return shaderNode.call( inputs );
  22864. };
  22865. fn.shaderNode = shaderNode;
  22866. fn.setLayout = ( layout ) => {
  22867. shaderNode.setLayout( layout );
  22868. return fn;
  22869. };
  22870. fn.once = () => {
  22871. shaderNode.once = true;
  22872. return fn;
  22873. };
  22874. return fn;
  22875. };
  22876. const tslFn = ( ...params ) => { // @deprecated, r168
  22877. console.warn( 'TSL.ShaderNode: tslFn() has been renamed to Fn().' );
  22878. return Fn( ...params );
  22879. };
  22880. //
  22881. addMethodChaining( 'toGlobal', ( node ) => {
  22882. node.global = true;
  22883. return node;
  22884. } );
  22885. //
  22886. const setCurrentStack = ( stack ) => {
  22887. currentStack = stack;
  22888. };
  22889. const getCurrentStack = () => currentStack;
  22890. const If = ( ...params ) => currentStack.If( ...params );
  22891. function append( node ) {
  22892. if ( currentStack ) currentStack.add( node );
  22893. return node;
  22894. }
  22895. addMethodChaining( 'append', append );
  22896. // types
  22897. const color = new ConvertType( 'color' );
  22898. const float = new ConvertType( 'float', cacheMaps.float );
  22899. const int = new ConvertType( 'int', cacheMaps.ints );
  22900. const uint = new ConvertType( 'uint', cacheMaps.uint );
  22901. const bool = new ConvertType( 'bool', cacheMaps.bool );
  22902. const vec2 = new ConvertType( 'vec2' );
  22903. const ivec2 = new ConvertType( 'ivec2' );
  22904. const uvec2 = new ConvertType( 'uvec2' );
  22905. const bvec2 = new ConvertType( 'bvec2' );
  22906. const vec3 = new ConvertType( 'vec3' );
  22907. const ivec3 = new ConvertType( 'ivec3' );
  22908. const uvec3 = new ConvertType( 'uvec3' );
  22909. const bvec3 = new ConvertType( 'bvec3' );
  22910. const vec4 = new ConvertType( 'vec4' );
  22911. const ivec4 = new ConvertType( 'ivec4' );
  22912. const uvec4 = new ConvertType( 'uvec4' );
  22913. const bvec4 = new ConvertType( 'bvec4' );
  22914. const mat2 = new ConvertType( 'mat2' );
  22915. const mat3 = new ConvertType( 'mat3' );
  22916. const mat4 = new ConvertType( 'mat4' );
  22917. const string = ( value = '' ) => nodeObject( new ConstNode( value, 'string' ) );
  22918. const arrayBuffer = ( value ) => nodeObject( new ConstNode( value, 'ArrayBuffer' ) );
  22919. addMethodChaining( 'toColor', color );
  22920. addMethodChaining( 'toFloat', float );
  22921. addMethodChaining( 'toInt', int );
  22922. addMethodChaining( 'toUint', uint );
  22923. addMethodChaining( 'toBool', bool );
  22924. addMethodChaining( 'toVec2', vec2 );
  22925. addMethodChaining( 'toIVec2', ivec2 );
  22926. addMethodChaining( 'toUVec2', uvec2 );
  22927. addMethodChaining( 'toBVec2', bvec2 );
  22928. addMethodChaining( 'toVec3', vec3 );
  22929. addMethodChaining( 'toIVec3', ivec3 );
  22930. addMethodChaining( 'toUVec3', uvec3 );
  22931. addMethodChaining( 'toBVec3', bvec3 );
  22932. addMethodChaining( 'toVec4', vec4 );
  22933. addMethodChaining( 'toIVec4', ivec4 );
  22934. addMethodChaining( 'toUVec4', uvec4 );
  22935. addMethodChaining( 'toBVec4', bvec4 );
  22936. addMethodChaining( 'toMat2', mat2 );
  22937. addMethodChaining( 'toMat3', mat3 );
  22938. addMethodChaining( 'toMat4', mat4 );
  22939. // basic nodes
  22940. const element = /*@__PURE__*/ nodeProxy( ArrayElementNode );
  22941. const convert = ( node, types ) => nodeObject( new ConvertNode( nodeObject( node ), types ) );
  22942. const split = ( node, channels ) => nodeObject( new SplitNode( nodeObject( node ), channels ) );
  22943. addMethodChaining( 'element', element );
  22944. addMethodChaining( 'convert', convert );
  22945. class UniformGroupNode extends Node {
  22946. static get type() {
  22947. return 'UniformGroupNode';
  22948. }
  22949. constructor( name, shared = false, order = 1 ) {
  22950. super( 'string' );
  22951. this.name = name;
  22952. this.version = 0;
  22953. this.shared = shared;
  22954. this.order = order;
  22955. this.isUniformGroup = true;
  22956. }
  22957. set needsUpdate( value ) {
  22958. if ( value === true ) this.version ++;
  22959. }
  22960. serialize( data ) {
  22961. super.serialize( data );
  22962. data.name = this.name;
  22963. data.version = this.version;
  22964. data.shared = this.shared;
  22965. }
  22966. deserialize( data ) {
  22967. super.deserialize( data );
  22968. this.name = data.name;
  22969. this.version = data.version;
  22970. this.shared = data.shared;
  22971. }
  22972. }
  22973. const uniformGroup = ( name ) => new UniformGroupNode( name );
  22974. const sharedUniformGroup = ( name, order = 0 ) => new UniformGroupNode( name, true, order );
  22975. const frameGroup = /*@__PURE__*/ sharedUniformGroup( 'frame' );
  22976. const renderGroup = /*@__PURE__*/ sharedUniformGroup( 'render' );
  22977. const objectGroup = /*@__PURE__*/ uniformGroup( 'object' );
  22978. class UniformNode extends InputNode {
  22979. static get type() {
  22980. return 'UniformNode';
  22981. }
  22982. constructor( value, nodeType = null ) {
  22983. super( value, nodeType );
  22984. this.isUniformNode = true;
  22985. this.name = '';
  22986. this.groupNode = objectGroup;
  22987. }
  22988. label( name ) {
  22989. this.name = name;
  22990. return this;
  22991. }
  22992. setGroup( group ) {
  22993. this.groupNode = group;
  22994. return this;
  22995. }
  22996. getGroup() {
  22997. return this.groupNode;
  22998. }
  22999. getUniformHash( builder ) {
  23000. return this.getHash( builder );
  23001. }
  23002. onUpdate( callback, updateType ) {
  23003. const self = this.getSelf();
  23004. callback = callback.bind( self );
  23005. return super.onUpdate( ( frame ) => {
  23006. const value = callback( frame, self );
  23007. if ( value !== undefined ) {
  23008. this.value = value;
  23009. }
  23010. }, updateType );
  23011. }
  23012. generate( builder, output ) {
  23013. const type = this.getNodeType( builder );
  23014. const hash = this.getUniformHash( builder );
  23015. let sharedNode = builder.getNodeFromHash( hash );
  23016. if ( sharedNode === undefined ) {
  23017. builder.setHashNode( this, hash );
  23018. sharedNode = this;
  23019. }
  23020. const sharedNodeType = sharedNode.getInputType( builder );
  23021. const nodeUniform = builder.getUniformFromNode( sharedNode, sharedNodeType, builder.shaderStage, this.name || builder.context.label );
  23022. const propertyName = builder.getPropertyName( nodeUniform );
  23023. if ( builder.context.label !== undefined ) delete builder.context.label;
  23024. return builder.format( propertyName, type, output );
  23025. }
  23026. }
  23027. const uniform = ( arg1, arg2 ) => {
  23028. const nodeType = getConstNodeType( arg2 || arg1 );
  23029. // @TODO: get ConstNode from .traverse() in the future
  23030. const value = ( arg1 && arg1.isNode === true ) ? ( arg1.node && arg1.node.value ) || arg1.value : arg1;
  23031. return nodeObject( new UniformNode( value, nodeType ) );
  23032. };
  23033. class PropertyNode extends Node {
  23034. static get type() {
  23035. return 'PropertyNode';
  23036. }
  23037. constructor( nodeType, name = null, varying = false ) {
  23038. super( nodeType );
  23039. this.name = name;
  23040. this.varying = varying;
  23041. this.isPropertyNode = true;
  23042. }
  23043. getHash( builder ) {
  23044. return this.name || super.getHash( builder );
  23045. }
  23046. isGlobal( /*builder*/ ) {
  23047. return true;
  23048. }
  23049. generate( builder ) {
  23050. let nodeVar;
  23051. if ( this.varying === true ) {
  23052. nodeVar = builder.getVaryingFromNode( this, this.name );
  23053. nodeVar.needsInterpolation = true;
  23054. } else {
  23055. nodeVar = builder.getVarFromNode( this, this.name );
  23056. }
  23057. return builder.getPropertyName( nodeVar );
  23058. }
  23059. }
  23060. const property = ( type, name ) => nodeObject( new PropertyNode( type, name ) );
  23061. const varyingProperty = ( type, name ) => nodeObject( new PropertyNode( type, name, true ) );
  23062. const diffuseColor = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec4', 'DiffuseColor' );
  23063. const emissive = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'EmissiveColor' );
  23064. const roughness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Roughness' );
  23065. const metalness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Metalness' );
  23066. const clearcoat = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Clearcoat' );
  23067. const clearcoatRoughness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'ClearcoatRoughness' );
  23068. const sheen = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'Sheen' );
  23069. const sheenRoughness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'SheenRoughness' );
  23070. const iridescence = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Iridescence' );
  23071. const iridescenceIOR = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'IridescenceIOR' );
  23072. const iridescenceThickness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'IridescenceThickness' );
  23073. const alphaT = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'AlphaT' );
  23074. const anisotropy = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Anisotropy' );
  23075. const anisotropyT = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'AnisotropyT' );
  23076. const anisotropyB = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'AnisotropyB' );
  23077. const specularColor = /*@__PURE__*/ nodeImmutable( PropertyNode, 'color', 'SpecularColor' );
  23078. const specularF90 = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'SpecularF90' );
  23079. const shininess = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Shininess' );
  23080. const output = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec4', 'Output' );
  23081. const dashSize = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'dashSize' );
  23082. const gapSize = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'gapSize' );
  23083. const pointWidth = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'pointWidth' );
  23084. const ior = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'IOR' );
  23085. const transmission = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Transmission' );
  23086. const thickness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Thickness' );
  23087. const attenuationDistance = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'AttenuationDistance' );
  23088. const attenuationColor = /*@__PURE__*/ nodeImmutable( PropertyNode, 'color', 'AttenuationColor' );
  23089. const dispersion = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Dispersion' );
  23090. class AssignNode extends TempNode {
  23091. static get type() {
  23092. return 'AssignNode';
  23093. }
  23094. constructor( targetNode, sourceNode ) {
  23095. super();
  23096. this.targetNode = targetNode;
  23097. this.sourceNode = sourceNode;
  23098. }
  23099. hasDependencies() {
  23100. return false;
  23101. }
  23102. getNodeType( builder, output ) {
  23103. return output !== 'void' ? this.targetNode.getNodeType( builder ) : 'void';
  23104. }
  23105. needsSplitAssign( builder ) {
  23106. const { targetNode } = this;
  23107. if ( builder.isAvailable( 'swizzleAssign' ) === false && targetNode.isSplitNode && targetNode.components.length > 1 ) {
  23108. const targetLength = builder.getTypeLength( targetNode.node.getNodeType( builder ) );
  23109. const assignDiferentVector = vectorComponents.join( '' ).slice( 0, targetLength ) !== targetNode.components;
  23110. return assignDiferentVector;
  23111. }
  23112. return false;
  23113. }
  23114. generate( builder, output ) {
  23115. const { targetNode, sourceNode } = this;
  23116. const needsSplitAssign = this.needsSplitAssign( builder );
  23117. const targetType = targetNode.getNodeType( builder );
  23118. const target = targetNode.context( { assign: true } ).build( builder );
  23119. const source = sourceNode.build( builder, targetType );
  23120. const sourceType = sourceNode.getNodeType( builder );
  23121. const nodeData = builder.getDataFromNode( this );
  23122. //
  23123. let snippet;
  23124. if ( nodeData.initialized === true ) {
  23125. if ( output !== 'void' ) {
  23126. snippet = target;
  23127. }
  23128. } else if ( needsSplitAssign ) {
  23129. const sourceVar = builder.getVarFromNode( this, null, targetType );
  23130. const sourceProperty = builder.getPropertyName( sourceVar );
  23131. builder.addLineFlowCode( `${ sourceProperty } = ${ source }`, this );
  23132. const targetRoot = targetNode.node.context( { assign: true } ).build( builder );
  23133. for ( let i = 0; i < targetNode.components.length; i ++ ) {
  23134. const component = targetNode.components[ i ];
  23135. builder.addLineFlowCode( `${ targetRoot }.${ component } = ${ sourceProperty }[ ${ i } ]`, this );
  23136. }
  23137. if ( output !== 'void' ) {
  23138. snippet = target;
  23139. }
  23140. } else {
  23141. snippet = `${ target } = ${ source }`;
  23142. if ( output === 'void' || sourceType === 'void' ) {
  23143. builder.addLineFlowCode( snippet, this );
  23144. if ( output !== 'void' ) {
  23145. snippet = target;
  23146. }
  23147. }
  23148. }
  23149. nodeData.initialized = true;
  23150. return builder.format( snippet, targetType, output );
  23151. }
  23152. }
  23153. const assign = /*@__PURE__*/ nodeProxy( AssignNode );
  23154. addMethodChaining( 'assign', assign );
  23155. class FunctionCallNode extends TempNode {
  23156. static get type() {
  23157. return 'FunctionCallNode';
  23158. }
  23159. constructor( functionNode = null, parameters = {} ) {
  23160. super();
  23161. this.functionNode = functionNode;
  23162. this.parameters = parameters;
  23163. }
  23164. setParameters( parameters ) {
  23165. this.parameters = parameters;
  23166. return this;
  23167. }
  23168. getParameters() {
  23169. return this.parameters;
  23170. }
  23171. getNodeType( builder ) {
  23172. return this.functionNode.getNodeType( builder );
  23173. }
  23174. generate( builder ) {
  23175. const params = [];
  23176. const functionNode = this.functionNode;
  23177. const inputs = functionNode.getInputs( builder );
  23178. const parameters = this.parameters;
  23179. const generateInput = ( node, inputNode ) => {
  23180. const type = inputNode.type;
  23181. const pointer = type === 'pointer';
  23182. let output;
  23183. if ( pointer ) output = '&' + node.build( builder );
  23184. else output = node.build( builder, type );
  23185. return output;
  23186. };
  23187. if ( Array.isArray( parameters ) ) {
  23188. for ( let i = 0; i < parameters.length; i ++ ) {
  23189. params.push( generateInput( parameters[ i ], inputs[ i ] ) );
  23190. }
  23191. } else {
  23192. for ( const inputNode of inputs ) {
  23193. const node = parameters[ inputNode.name ];
  23194. if ( node !== undefined ) {
  23195. params.push( generateInput( node, inputNode ) );
  23196. } else {
  23197. throw new Error( `FunctionCallNode: Input '${inputNode.name}' not found in FunctionNode.` );
  23198. }
  23199. }
  23200. }
  23201. const functionName = functionNode.build( builder, 'property' );
  23202. return `${functionName}( ${params.join( ', ' )} )`;
  23203. }
  23204. }
  23205. const call = ( func, ...params ) => {
  23206. params = params.length > 1 || ( params[ 0 ] && params[ 0 ].isNode === true ) ? nodeArray( params ) : nodeObjects( params[ 0 ] );
  23207. return nodeObject( new FunctionCallNode( nodeObject( func ), params ) );
  23208. };
  23209. addMethodChaining( 'call', call );
  23210. class OperatorNode extends TempNode {
  23211. static get type() {
  23212. return 'OperatorNode';
  23213. }
  23214. constructor( op, aNode, bNode, ...params ) {
  23215. super();
  23216. if ( params.length > 0 ) {
  23217. let finalOp = new OperatorNode( op, aNode, bNode );
  23218. for ( let i = 0; i < params.length - 1; i ++ ) {
  23219. finalOp = new OperatorNode( op, finalOp, params[ i ] );
  23220. }
  23221. aNode = finalOp;
  23222. bNode = params[ params.length - 1 ];
  23223. }
  23224. this.op = op;
  23225. this.aNode = aNode;
  23226. this.bNode = bNode;
  23227. }
  23228. getNodeType( builder, output ) {
  23229. const op = this.op;
  23230. const aNode = this.aNode;
  23231. const bNode = this.bNode;
  23232. const typeA = aNode.getNodeType( builder );
  23233. const typeB = typeof bNode !== 'undefined' ? bNode.getNodeType( builder ) : null;
  23234. if ( typeA === 'void' || typeB === 'void' ) {
  23235. return 'void';
  23236. } else if ( op === '%' ) {
  23237. return typeA;
  23238. } else if ( op === '~' || op === '&' || op === '|' || op === '^' || op === '>>' || op === '<<' ) {
  23239. return builder.getIntegerType( typeA );
  23240. } else if ( op === '!' || op === '==' || op === '&&' || op === '||' || op === '^^' ) {
  23241. return 'bool';
  23242. } else if ( op === '<' || op === '>' || op === '<=' || op === '>=' ) {
  23243. const typeLength = output ? builder.getTypeLength( output ) : Math.max( builder.getTypeLength( typeA ), builder.getTypeLength( typeB ) );
  23244. return typeLength > 1 ? `bvec${ typeLength }` : 'bool';
  23245. } else {
  23246. if ( typeA === 'float' && builder.isMatrix( typeB ) ) {
  23247. return typeB;
  23248. } else if ( builder.isMatrix( typeA ) && builder.isVector( typeB ) ) {
  23249. // matrix x vector
  23250. return builder.getVectorFromMatrix( typeA );
  23251. } else if ( builder.isVector( typeA ) && builder.isMatrix( typeB ) ) {
  23252. // vector x matrix
  23253. return builder.getVectorFromMatrix( typeB );
  23254. } else if ( builder.getTypeLength( typeB ) > builder.getTypeLength( typeA ) ) {
  23255. // anytype x anytype: use the greater length vector
  23256. return typeB;
  23257. }
  23258. return typeA;
  23259. }
  23260. }
  23261. generate( builder, output ) {
  23262. const op = this.op;
  23263. const aNode = this.aNode;
  23264. const bNode = this.bNode;
  23265. const type = this.getNodeType( builder, output );
  23266. let typeA = null;
  23267. let typeB = null;
  23268. if ( type !== 'void' ) {
  23269. typeA = aNode.getNodeType( builder );
  23270. typeB = typeof bNode !== 'undefined' ? bNode.getNodeType( builder ) : null;
  23271. if ( op === '<' || op === '>' || op === '<=' || op === '>=' || op === '==' ) {
  23272. if ( builder.isVector( typeA ) ) {
  23273. typeB = typeA;
  23274. } else if ( typeA !== typeB ) {
  23275. typeA = typeB = 'float';
  23276. }
  23277. } else if ( op === '>>' || op === '<<' ) {
  23278. typeA = type;
  23279. typeB = builder.changeComponentType( typeB, 'uint' );
  23280. } else if ( builder.isMatrix( typeA ) && builder.isVector( typeB ) ) {
  23281. // matrix x vector
  23282. typeB = builder.getVectorFromMatrix( typeA );
  23283. } else if ( builder.isVector( typeA ) && builder.isMatrix( typeB ) ) {
  23284. // vector x matrix
  23285. typeA = builder.getVectorFromMatrix( typeB );
  23286. } else {
  23287. // anytype x anytype
  23288. typeA = typeB = type;
  23289. }
  23290. } else {
  23291. typeA = typeB = type;
  23292. }
  23293. const a = aNode.build( builder, typeA );
  23294. const b = typeof bNode !== 'undefined' ? bNode.build( builder, typeB ) : null;
  23295. const outputLength = builder.getTypeLength( output );
  23296. const fnOpSnippet = builder.getFunctionOperator( op );
  23297. if ( output !== 'void' ) {
  23298. if ( op === '<' && outputLength > 1 ) {
  23299. if ( builder.useComparisonMethod ) {
  23300. return builder.format( `${ builder.getMethod( 'lessThan', output ) }( ${ a }, ${ b } )`, type, output );
  23301. } else {
  23302. return builder.format( `( ${ a } < ${ b } )`, type, output );
  23303. }
  23304. } else if ( op === '<=' && outputLength > 1 ) {
  23305. if ( builder.useComparisonMethod ) {
  23306. return builder.format( `${ builder.getMethod( 'lessThanEqual', output ) }( ${ a }, ${ b } )`, type, output );
  23307. } else {
  23308. return builder.format( `( ${ a } <= ${ b } )`, type, output );
  23309. }
  23310. } else if ( op === '>' && outputLength > 1 ) {
  23311. if ( builder.useComparisonMethod ) {
  23312. return builder.format( `${ builder.getMethod( 'greaterThan', output ) }( ${ a }, ${ b } )`, type, output );
  23313. } else {
  23314. return builder.format( `( ${ a } > ${ b } )`, type, output );
  23315. }
  23316. } else if ( op === '>=' && outputLength > 1 ) {
  23317. if ( builder.useComparisonMethod ) {
  23318. return builder.format( `${ builder.getMethod( 'greaterThanEqual', output ) }( ${ a }, ${ b } )`, type, output );
  23319. } else {
  23320. return builder.format( `( ${ a } >= ${ b } )`, type, output );
  23321. }
  23322. } else if ( op === '!' || op === '~' ) {
  23323. return builder.format( `(${op}${a})`, typeA, output );
  23324. } else if ( fnOpSnippet ) {
  23325. return builder.format( `${ fnOpSnippet }( ${ a }, ${ b } )`, type, output );
  23326. } else {
  23327. return builder.format( `( ${ a } ${ op } ${ b } )`, type, output );
  23328. }
  23329. } else if ( typeA !== 'void' ) {
  23330. if ( fnOpSnippet ) {
  23331. return builder.format( `${ fnOpSnippet }( ${ a }, ${ b } )`, type, output );
  23332. } else {
  23333. return builder.format( `${ a } ${ op } ${ b }`, type, output );
  23334. }
  23335. }
  23336. }
  23337. serialize( data ) {
  23338. super.serialize( data );
  23339. data.op = this.op;
  23340. }
  23341. deserialize( data ) {
  23342. super.deserialize( data );
  23343. this.op = data.op;
  23344. }
  23345. }
  23346. const add = /*@__PURE__*/ nodeProxy( OperatorNode, '+' );
  23347. const sub = /*@__PURE__*/ nodeProxy( OperatorNode, '-' );
  23348. const mul = /*@__PURE__*/ nodeProxy( OperatorNode, '*' );
  23349. const div = /*@__PURE__*/ nodeProxy( OperatorNode, '/' );
  23350. const modInt = /*@__PURE__*/ nodeProxy( OperatorNode, '%' );
  23351. const equal = /*@__PURE__*/ nodeProxy( OperatorNode, '==' );
  23352. const notEqual = /*@__PURE__*/ nodeProxy( OperatorNode, '!=' );
  23353. const lessThan = /*@__PURE__*/ nodeProxy( OperatorNode, '<' );
  23354. const greaterThan = /*@__PURE__*/ nodeProxy( OperatorNode, '>' );
  23355. const lessThanEqual = /*@__PURE__*/ nodeProxy( OperatorNode, '<=' );
  23356. const greaterThanEqual = /*@__PURE__*/ nodeProxy( OperatorNode, '>=' );
  23357. const and = /*@__PURE__*/ nodeProxy( OperatorNode, '&&' );
  23358. const or = /*@__PURE__*/ nodeProxy( OperatorNode, '||' );
  23359. const not = /*@__PURE__*/ nodeProxy( OperatorNode, '!' );
  23360. const xor = /*@__PURE__*/ nodeProxy( OperatorNode, '^^' );
  23361. const bitAnd = /*@__PURE__*/ nodeProxy( OperatorNode, '&' );
  23362. const bitNot = /*@__PURE__*/ nodeProxy( OperatorNode, '~' );
  23363. const bitOr = /*@__PURE__*/ nodeProxy( OperatorNode, '|' );
  23364. const bitXor = /*@__PURE__*/ nodeProxy( OperatorNode, '^' );
  23365. const shiftLeft = /*@__PURE__*/ nodeProxy( OperatorNode, '<<' );
  23366. const shiftRight = /*@__PURE__*/ nodeProxy( OperatorNode, '>>' );
  23367. addMethodChaining( 'add', add );
  23368. addMethodChaining( 'sub', sub );
  23369. addMethodChaining( 'mul', mul );
  23370. addMethodChaining( 'div', div );
  23371. addMethodChaining( 'modInt', modInt );
  23372. addMethodChaining( 'equal', equal );
  23373. addMethodChaining( 'notEqual', notEqual );
  23374. addMethodChaining( 'lessThan', lessThan );
  23375. addMethodChaining( 'greaterThan', greaterThan );
  23376. addMethodChaining( 'lessThanEqual', lessThanEqual );
  23377. addMethodChaining( 'greaterThanEqual', greaterThanEqual );
  23378. addMethodChaining( 'and', and );
  23379. addMethodChaining( 'or', or );
  23380. addMethodChaining( 'not', not );
  23381. addMethodChaining( 'xor', xor );
  23382. addMethodChaining( 'bitAnd', bitAnd );
  23383. addMethodChaining( 'bitNot', bitNot );
  23384. addMethodChaining( 'bitOr', bitOr );
  23385. addMethodChaining( 'bitXor', bitXor );
  23386. addMethodChaining( 'shiftLeft', shiftLeft );
  23387. addMethodChaining( 'shiftRight', shiftRight );
  23388. const remainder = ( ...params ) => { // @deprecated, r168
  23389. console.warn( 'TSL.OperatorNode: .remainder() has been renamed to .modInt().' );
  23390. return modInt( ...params );
  23391. };
  23392. addMethodChaining( 'remainder', remainder );
  23393. class MathNode extends TempNode {
  23394. static get type() {
  23395. return 'MathNode';
  23396. }
  23397. constructor( method, aNode, bNode = null, cNode = null ) {
  23398. super();
  23399. this.method = method;
  23400. this.aNode = aNode;
  23401. this.bNode = bNode;
  23402. this.cNode = cNode;
  23403. }
  23404. getInputType( builder ) {
  23405. const aType = this.aNode.getNodeType( builder );
  23406. const bType = this.bNode ? this.bNode.getNodeType( builder ) : null;
  23407. const cType = this.cNode ? this.cNode.getNodeType( builder ) : null;
  23408. const aLen = builder.isMatrix( aType ) ? 0 : builder.getTypeLength( aType );
  23409. const bLen = builder.isMatrix( bType ) ? 0 : builder.getTypeLength( bType );
  23410. const cLen = builder.isMatrix( cType ) ? 0 : builder.getTypeLength( cType );
  23411. if ( aLen > bLen && aLen > cLen ) {
  23412. return aType;
  23413. } else if ( bLen > cLen ) {
  23414. return bType;
  23415. } else if ( cLen > aLen ) {
  23416. return cType;
  23417. }
  23418. return aType;
  23419. }
  23420. getNodeType( builder ) {
  23421. const method = this.method;
  23422. if ( method === MathNode.LENGTH || method === MathNode.DISTANCE || method === MathNode.DOT ) {
  23423. return 'float';
  23424. } else if ( method === MathNode.CROSS ) {
  23425. return 'vec3';
  23426. } else if ( method === MathNode.ALL ) {
  23427. return 'bool';
  23428. } else if ( method === MathNode.EQUALS ) {
  23429. return builder.changeComponentType( this.aNode.getNodeType( builder ), 'bool' );
  23430. } else if ( method === MathNode.MOD ) {
  23431. return this.aNode.getNodeType( builder );
  23432. } else {
  23433. return this.getInputType( builder );
  23434. }
  23435. }
  23436. generate( builder, output ) {
  23437. const method = this.method;
  23438. const type = this.getNodeType( builder );
  23439. const inputType = this.getInputType( builder );
  23440. const a = this.aNode;
  23441. const b = this.bNode;
  23442. const c = this.cNode;
  23443. const isWebGL = builder.renderer.isWebGLRenderer === true;
  23444. if ( method === MathNode.TRANSFORM_DIRECTION ) {
  23445. // dir can be either a direction vector or a normal vector
  23446. // upper-left 3x3 of matrix is assumed to be orthogonal
  23447. let tA = a;
  23448. let tB = b;
  23449. if ( builder.isMatrix( tA.getNodeType( builder ) ) ) {
  23450. tB = vec4( vec3( tB ), 0.0 );
  23451. } else {
  23452. tA = vec4( vec3( tA ), 0.0 );
  23453. }
  23454. const mulNode = mul( tA, tB ).xyz;
  23455. return normalize( mulNode ).build( builder, output );
  23456. } else if ( method === MathNode.NEGATE ) {
  23457. return builder.format( '( - ' + a.build( builder, inputType ) + ' )', type, output );
  23458. } else if ( method === MathNode.ONE_MINUS ) {
  23459. return sub( 1.0, a ).build( builder, output );
  23460. } else if ( method === MathNode.RECIPROCAL ) {
  23461. return div( 1.0, a ).build( builder, output );
  23462. } else if ( method === MathNode.DIFFERENCE ) {
  23463. return abs( sub( a, b ) ).build( builder, output );
  23464. } else {
  23465. const params = [];
  23466. if ( method === MathNode.CROSS || method === MathNode.MOD ) {
  23467. params.push(
  23468. a.build( builder, type ),
  23469. b.build( builder, type )
  23470. );
  23471. } else if ( isWebGL && method === MathNode.STEP ) {
  23472. params.push(
  23473. a.build( builder, builder.getTypeLength( a.getNodeType( builder ) ) === 1 ? 'float' : inputType ),
  23474. b.build( builder, inputType )
  23475. );
  23476. } else if ( ( isWebGL && ( method === MathNode.MIN || method === MathNode.MAX ) ) || method === MathNode.MOD ) {
  23477. params.push(
  23478. a.build( builder, inputType ),
  23479. b.build( builder, builder.getTypeLength( b.getNodeType( builder ) ) === 1 ? 'float' : inputType )
  23480. );
  23481. } else if ( method === MathNode.REFRACT ) {
  23482. params.push(
  23483. a.build( builder, inputType ),
  23484. b.build( builder, inputType ),
  23485. c.build( builder, 'float' )
  23486. );
  23487. } else if ( method === MathNode.MIX ) {
  23488. params.push(
  23489. a.build( builder, inputType ),
  23490. b.build( builder, inputType ),
  23491. c.build( builder, builder.getTypeLength( c.getNodeType( builder ) ) === 1 ? 'float' : inputType )
  23492. );
  23493. } else {
  23494. params.push( a.build( builder, inputType ) );
  23495. if ( b !== null ) params.push( b.build( builder, inputType ) );
  23496. if ( c !== null ) params.push( c.build( builder, inputType ) );
  23497. }
  23498. return builder.format( `${ builder.getMethod( method, type ) }( ${params.join( ', ' )} )`, type, output );
  23499. }
  23500. }
  23501. serialize( data ) {
  23502. super.serialize( data );
  23503. data.method = this.method;
  23504. }
  23505. deserialize( data ) {
  23506. super.deserialize( data );
  23507. this.method = data.method;
  23508. }
  23509. }
  23510. // 1 input
  23511. MathNode.ALL = 'all';
  23512. MathNode.ANY = 'any';
  23513. MathNode.EQUALS = 'equals';
  23514. MathNode.RADIANS = 'radians';
  23515. MathNode.DEGREES = 'degrees';
  23516. MathNode.EXP = 'exp';
  23517. MathNode.EXP2 = 'exp2';
  23518. MathNode.LOG = 'log';
  23519. MathNode.LOG2 = 'log2';
  23520. MathNode.SQRT = 'sqrt';
  23521. MathNode.INVERSE_SQRT = 'inversesqrt';
  23522. MathNode.FLOOR = 'floor';
  23523. MathNode.CEIL = 'ceil';
  23524. MathNode.NORMALIZE = 'normalize';
  23525. MathNode.FRACT = 'fract';
  23526. MathNode.SIN = 'sin';
  23527. MathNode.COS = 'cos';
  23528. MathNode.TAN = 'tan';
  23529. MathNode.ASIN = 'asin';
  23530. MathNode.ACOS = 'acos';
  23531. MathNode.ATAN = 'atan';
  23532. MathNode.ABS = 'abs';
  23533. MathNode.SIGN = 'sign';
  23534. MathNode.LENGTH = 'length';
  23535. MathNode.NEGATE = 'negate';
  23536. MathNode.ONE_MINUS = 'oneMinus';
  23537. MathNode.DFDX = 'dFdx';
  23538. MathNode.DFDY = 'dFdy';
  23539. MathNode.ROUND = 'round';
  23540. MathNode.RECIPROCAL = 'reciprocal';
  23541. MathNode.TRUNC = 'trunc';
  23542. MathNode.FWIDTH = 'fwidth';
  23543. MathNode.BITCAST = 'bitcast';
  23544. MathNode.TRANSPOSE = 'transpose';
  23545. // 2 inputs
  23546. MathNode.ATAN2 = 'atan2';
  23547. MathNode.MIN = 'min';
  23548. MathNode.MAX = 'max';
  23549. MathNode.MOD = 'mod';
  23550. MathNode.STEP = 'step';
  23551. MathNode.REFLECT = 'reflect';
  23552. MathNode.DISTANCE = 'distance';
  23553. MathNode.DIFFERENCE = 'difference';
  23554. MathNode.DOT = 'dot';
  23555. MathNode.CROSS = 'cross';
  23556. MathNode.POW = 'pow';
  23557. MathNode.TRANSFORM_DIRECTION = 'transformDirection';
  23558. // 3 inputs
  23559. MathNode.MIX = 'mix';
  23560. MathNode.CLAMP = 'clamp';
  23561. MathNode.REFRACT = 'refract';
  23562. MathNode.SMOOTHSTEP = 'smoothstep';
  23563. MathNode.FACEFORWARD = 'faceforward';
  23564. const EPSILON = /*@__PURE__*/ float( 1e-6 );
  23565. const INFINITY = /*@__PURE__*/ float( 1e6 );
  23566. const PI = /*@__PURE__*/ float( Math.PI );
  23567. const PI2 = /*@__PURE__*/ float( Math.PI * 2 );
  23568. const all = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ALL );
  23569. const any = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ANY );
  23570. const equals = /*@__PURE__*/ nodeProxy( MathNode, MathNode.EQUALS );
  23571. const radians = /*@__PURE__*/ nodeProxy( MathNode, MathNode.RADIANS );
  23572. const degrees = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DEGREES );
  23573. const exp = /*@__PURE__*/ nodeProxy( MathNode, MathNode.EXP );
  23574. const exp2 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.EXP2 );
  23575. const log = /*@__PURE__*/ nodeProxy( MathNode, MathNode.LOG );
  23576. const log2 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.LOG2 );
  23577. const sqrt = /*@__PURE__*/ nodeProxy( MathNode, MathNode.SQRT );
  23578. const inverseSqrt = /*@__PURE__*/ nodeProxy( MathNode, MathNode.INVERSE_SQRT );
  23579. const floor = /*@__PURE__*/ nodeProxy( MathNode, MathNode.FLOOR );
  23580. const ceil = /*@__PURE__*/ nodeProxy( MathNode, MathNode.CEIL );
  23581. const normalize = /*@__PURE__*/ nodeProxy( MathNode, MathNode.NORMALIZE );
  23582. const fract = /*@__PURE__*/ nodeProxy( MathNode, MathNode.FRACT );
  23583. const sin = /*@__PURE__*/ nodeProxy( MathNode, MathNode.SIN );
  23584. const cos = /*@__PURE__*/ nodeProxy( MathNode, MathNode.COS );
  23585. const tan = /*@__PURE__*/ nodeProxy( MathNode, MathNode.TAN );
  23586. const asin = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ASIN );
  23587. const acos = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ACOS );
  23588. const atan = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ATAN );
  23589. const abs = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ABS );
  23590. const sign = /*@__PURE__*/ nodeProxy( MathNode, MathNode.SIGN );
  23591. const length = /*@__PURE__*/ nodeProxy( MathNode, MathNode.LENGTH );
  23592. const negate = /*@__PURE__*/ nodeProxy( MathNode, MathNode.NEGATE );
  23593. const oneMinus = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ONE_MINUS );
  23594. const dFdx = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DFDX );
  23595. const dFdy = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DFDY );
  23596. const round = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ROUND );
  23597. const reciprocal = /*@__PURE__*/ nodeProxy( MathNode, MathNode.RECIPROCAL );
  23598. const trunc = /*@__PURE__*/ nodeProxy( MathNode, MathNode.TRUNC );
  23599. const fwidth = /*@__PURE__*/ nodeProxy( MathNode, MathNode.FWIDTH );
  23600. const bitcast = /*@__PURE__*/ nodeProxy( MathNode, MathNode.BITCAST );
  23601. const transpose = /*@__PURE__*/ nodeProxy( MathNode, MathNode.TRANSPOSE );
  23602. const atan2 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ATAN2 );
  23603. const min$1 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.MIN );
  23604. const max$1 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.MAX );
  23605. const mod = /*@__PURE__*/ nodeProxy( MathNode, MathNode.MOD );
  23606. const step = /*@__PURE__*/ nodeProxy( MathNode, MathNode.STEP );
  23607. const reflect = /*@__PURE__*/ nodeProxy( MathNode, MathNode.REFLECT );
  23608. const distance = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DISTANCE );
  23609. const difference = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DIFFERENCE );
  23610. const dot = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DOT );
  23611. const cross = /*@__PURE__*/ nodeProxy( MathNode, MathNode.CROSS );
  23612. const pow = /*@__PURE__*/ nodeProxy( MathNode, MathNode.POW );
  23613. const pow2 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.POW, 2 );
  23614. const pow3 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.POW, 3 );
  23615. const pow4 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.POW, 4 );
  23616. const transformDirection = /*@__PURE__*/ nodeProxy( MathNode, MathNode.TRANSFORM_DIRECTION );
  23617. const cbrt = ( a ) => mul( sign( a ), pow( abs( a ), 1.0 / 3.0 ) );
  23618. const lengthSq = ( a ) => dot( a, a );
  23619. const mix = /*@__PURE__*/ nodeProxy( MathNode, MathNode.MIX );
  23620. const clamp = ( value, low = 0, high = 1 ) => nodeObject( new MathNode( MathNode.CLAMP, nodeObject( value ), nodeObject( low ), nodeObject( high ) ) );
  23621. const saturate = ( value ) => clamp( value );
  23622. const refract = /*@__PURE__*/ nodeProxy( MathNode, MathNode.REFRACT );
  23623. const smoothstep = /*@__PURE__*/ nodeProxy( MathNode, MathNode.SMOOTHSTEP );
  23624. const faceForward = /*@__PURE__*/ nodeProxy( MathNode, MathNode.FACEFORWARD );
  23625. const rand = /*@__PURE__*/ Fn( ( [ uv ] ) => {
  23626. const a = 12.9898, b = 78.233, c = 43758.5453;
  23627. const dt = dot( uv.xy, vec2( a, b ) ), sn = mod( dt, PI );
  23628. return fract( sin( sn ).mul( c ) );
  23629. } );
  23630. const mixElement = ( t, e1, e2 ) => mix( e1, e2, t );
  23631. const smoothstepElement = ( x, low, high ) => smoothstep( low, high, x );
  23632. addMethodChaining( 'all', all );
  23633. addMethodChaining( 'any', any );
  23634. addMethodChaining( 'equals', equals );
  23635. addMethodChaining( 'radians', radians );
  23636. addMethodChaining( 'degrees', degrees );
  23637. addMethodChaining( 'exp', exp );
  23638. addMethodChaining( 'exp2', exp2 );
  23639. addMethodChaining( 'log', log );
  23640. addMethodChaining( 'log2', log2 );
  23641. addMethodChaining( 'sqrt', sqrt );
  23642. addMethodChaining( 'inverseSqrt', inverseSqrt );
  23643. addMethodChaining( 'floor', floor );
  23644. addMethodChaining( 'ceil', ceil );
  23645. addMethodChaining( 'normalize', normalize );
  23646. addMethodChaining( 'fract', fract );
  23647. addMethodChaining( 'sin', sin );
  23648. addMethodChaining( 'cos', cos );
  23649. addMethodChaining( 'tan', tan );
  23650. addMethodChaining( 'asin', asin );
  23651. addMethodChaining( 'acos', acos );
  23652. addMethodChaining( 'atan', atan );
  23653. addMethodChaining( 'abs', abs );
  23654. addMethodChaining( 'sign', sign );
  23655. addMethodChaining( 'length', length );
  23656. addMethodChaining( 'lengthSq', lengthSq );
  23657. addMethodChaining( 'negate', negate );
  23658. addMethodChaining( 'oneMinus', oneMinus );
  23659. addMethodChaining( 'dFdx', dFdx );
  23660. addMethodChaining( 'dFdy', dFdy );
  23661. addMethodChaining( 'round', round );
  23662. addMethodChaining( 'reciprocal', reciprocal );
  23663. addMethodChaining( 'trunc', trunc );
  23664. addMethodChaining( 'fwidth', fwidth );
  23665. addMethodChaining( 'atan2', atan2 );
  23666. addMethodChaining( 'min', min$1 );
  23667. addMethodChaining( 'max', max$1 );
  23668. addMethodChaining( 'mod', mod );
  23669. addMethodChaining( 'step', step );
  23670. addMethodChaining( 'reflect', reflect );
  23671. addMethodChaining( 'distance', distance );
  23672. addMethodChaining( 'dot', dot );
  23673. addMethodChaining( 'cross', cross );
  23674. addMethodChaining( 'pow', pow );
  23675. addMethodChaining( 'pow2', pow2 );
  23676. addMethodChaining( 'pow3', pow3 );
  23677. addMethodChaining( 'pow4', pow4 );
  23678. addMethodChaining( 'transformDirection', transformDirection );
  23679. addMethodChaining( 'mix', mixElement );
  23680. addMethodChaining( 'clamp', clamp );
  23681. addMethodChaining( 'refract', refract );
  23682. addMethodChaining( 'smoothstep', smoothstepElement );
  23683. addMethodChaining( 'faceForward', faceForward );
  23684. addMethodChaining( 'difference', difference );
  23685. addMethodChaining( 'saturate', saturate );
  23686. addMethodChaining( 'cbrt', cbrt );
  23687. addMethodChaining( 'transpose', transpose );
  23688. addMethodChaining( 'rand', rand );
  23689. class ConditionalNode extends Node {
  23690. static get type() {
  23691. return 'ConditionalNode';
  23692. }
  23693. constructor( condNode, ifNode, elseNode = null ) {
  23694. super();
  23695. this.condNode = condNode;
  23696. this.ifNode = ifNode;
  23697. this.elseNode = elseNode;
  23698. }
  23699. getNodeType( builder ) {
  23700. const ifType = this.ifNode.getNodeType( builder );
  23701. if ( this.elseNode !== null ) {
  23702. const elseType = this.elseNode.getNodeType( builder );
  23703. if ( builder.getTypeLength( elseType ) > builder.getTypeLength( ifType ) ) {
  23704. return elseType;
  23705. }
  23706. }
  23707. return ifType;
  23708. }
  23709. setup( builder ) {
  23710. const condNode = this.condNode.cache();
  23711. const ifNode = this.ifNode.cache();
  23712. const elseNode = this.elseNode ? this.elseNode.cache() : null;
  23713. //
  23714. const currentNodeBlock = builder.context.nodeBlock;
  23715. builder.getDataFromNode( ifNode ).parentNodeBlock = currentNodeBlock;
  23716. if ( elseNode !== null ) builder.getDataFromNode( elseNode ).parentNodeBlock = currentNodeBlock;
  23717. //
  23718. const properties = builder.getNodeProperties( this );
  23719. properties.condNode = condNode;
  23720. properties.ifNode = ifNode.context( { nodeBlock: ifNode } );
  23721. properties.elseNode = elseNode ? elseNode.context( { nodeBlock: elseNode } ) : null;
  23722. }
  23723. generate( builder, output ) {
  23724. const type = this.getNodeType( builder );
  23725. const nodeData = builder.getDataFromNode( this );
  23726. if ( nodeData.nodeProperty !== undefined ) {
  23727. return nodeData.nodeProperty;
  23728. }
  23729. const { condNode, ifNode, elseNode } = builder.getNodeProperties( this );
  23730. const needsOutput = output !== 'void';
  23731. const nodeProperty = needsOutput ? property( type ).build( builder ) : '';
  23732. nodeData.nodeProperty = nodeProperty;
  23733. const nodeSnippet = condNode.build( builder, 'bool' );
  23734. builder.addFlowCode( `\n${ builder.tab }if ( ${ nodeSnippet } ) {\n\n` ).addFlowTab();
  23735. let ifSnippet = ifNode.build( builder, type );
  23736. if ( ifSnippet ) {
  23737. if ( needsOutput ) {
  23738. ifSnippet = nodeProperty + ' = ' + ifSnippet + ';';
  23739. } else {
  23740. ifSnippet = 'return ' + ifSnippet + ';';
  23741. }
  23742. }
  23743. builder.removeFlowTab().addFlowCode( builder.tab + '\t' + ifSnippet + '\n\n' + builder.tab + '}' );
  23744. if ( elseNode !== null ) {
  23745. builder.addFlowCode( ' else {\n\n' ).addFlowTab();
  23746. let elseSnippet = elseNode.build( builder, type );
  23747. if ( elseSnippet ) {
  23748. if ( needsOutput ) {
  23749. elseSnippet = nodeProperty + ' = ' + elseSnippet + ';';
  23750. } else {
  23751. elseSnippet = 'return ' + elseSnippet + ';';
  23752. }
  23753. }
  23754. builder.removeFlowTab().addFlowCode( builder.tab + '\t' + elseSnippet + '\n\n' + builder.tab + '}\n\n' );
  23755. } else {
  23756. builder.addFlowCode( '\n\n' );
  23757. }
  23758. return builder.format( nodeProperty, type, output );
  23759. }
  23760. }
  23761. const select = /*@__PURE__*/ nodeProxy( ConditionalNode );
  23762. addMethodChaining( 'select', select );
  23763. //
  23764. const cond = ( ...params ) => { // @deprecated, r168
  23765. console.warn( 'TSL.ConditionalNode: cond() has been renamed to select().' );
  23766. return select( ...params );
  23767. };
  23768. addMethodChaining( 'cond', cond );
  23769. class ContextNode extends Node {
  23770. static get type() {
  23771. return 'ContextNode';
  23772. }
  23773. constructor( node, value = {} ) {
  23774. super();
  23775. this.isContextNode = true;
  23776. this.node = node;
  23777. this.value = value;
  23778. }
  23779. getScope() {
  23780. return this.node.getScope();
  23781. }
  23782. getNodeType( builder ) {
  23783. return this.node.getNodeType( builder );
  23784. }
  23785. analyze( builder ) {
  23786. this.node.build( builder );
  23787. }
  23788. setup( builder ) {
  23789. const previousContext = builder.getContext();
  23790. builder.setContext( { ...builder.context, ...this.value } );
  23791. const node = this.node.build( builder );
  23792. builder.setContext( previousContext );
  23793. return node;
  23794. }
  23795. generate( builder, output ) {
  23796. const previousContext = builder.getContext();
  23797. builder.setContext( { ...builder.context, ...this.value } );
  23798. const snippet = this.node.build( builder, output );
  23799. builder.setContext( previousContext );
  23800. return snippet;
  23801. }
  23802. }
  23803. const context = /*@__PURE__*/ nodeProxy( ContextNode );
  23804. const label = ( node, name ) => context( node, { label: name } );
  23805. addMethodChaining( 'context', context );
  23806. addMethodChaining( 'label', label );
  23807. class VarNode extends Node {
  23808. static get type() {
  23809. return 'VarNode';
  23810. }
  23811. constructor( node, name = null ) {
  23812. super();
  23813. this.node = node;
  23814. this.name = name;
  23815. this.global = true;
  23816. this.isVarNode = true;
  23817. }
  23818. getHash( builder ) {
  23819. return this.name || super.getHash( builder );
  23820. }
  23821. getNodeType( builder ) {
  23822. return this.node.getNodeType( builder );
  23823. }
  23824. generate( builder ) {
  23825. const { node, name } = this;
  23826. const nodeVar = builder.getVarFromNode( this, name, builder.getVectorType( this.getNodeType( builder ) ) );
  23827. const propertyName = builder.getPropertyName( nodeVar );
  23828. const snippet = node.build( builder, nodeVar.type );
  23829. builder.addLineFlowCode( `${propertyName} = ${snippet}`, this );
  23830. return propertyName;
  23831. }
  23832. }
  23833. const createVar = /*@__PURE__*/ nodeProxy( VarNode );
  23834. addMethodChaining( 'toVar', ( ...params ) => createVar( ...params ).append() );
  23835. // Deprecated
  23836. const temp = ( node ) => { // @deprecated, r170
  23837. console.warn( 'TSL: "temp" is deprecated. Use ".toVar()" instead.' );
  23838. return createVar( node );
  23839. };
  23840. addMethodChaining( 'temp', temp );
  23841. class VaryingNode extends Node {
  23842. static get type() {
  23843. return 'VaryingNode';
  23844. }
  23845. constructor( node, name = null ) {
  23846. super();
  23847. this.node = node;
  23848. this.name = name;
  23849. this.isVaryingNode = true;
  23850. }
  23851. isGlobal() {
  23852. return true;
  23853. }
  23854. getHash( builder ) {
  23855. return this.name || super.getHash( builder );
  23856. }
  23857. getNodeType( builder ) {
  23858. // VaryingNode is auto type
  23859. return this.node.getNodeType( builder );
  23860. }
  23861. setupVarying( builder ) {
  23862. const properties = builder.getNodeProperties( this );
  23863. let varying = properties.varying;
  23864. if ( varying === undefined ) {
  23865. const name = this.name;
  23866. const type = this.getNodeType( builder );
  23867. properties.varying = varying = builder.getVaryingFromNode( this, name, type );
  23868. properties.node = this.node;
  23869. }
  23870. // this property can be used to check if the varying can be optimized for a variable
  23871. varying.needsInterpolation || ( varying.needsInterpolation = ( builder.shaderStage === 'fragment' ) );
  23872. return varying;
  23873. }
  23874. setup( builder ) {
  23875. this.setupVarying( builder );
  23876. }
  23877. analyze( builder ) {
  23878. this.setupVarying( builder );
  23879. return this.node.analyze( builder );
  23880. }
  23881. generate( builder ) {
  23882. const properties = builder.getNodeProperties( this );
  23883. const varying = this.setupVarying( builder );
  23884. if ( properties.propertyName === undefined ) {
  23885. const type = this.getNodeType( builder );
  23886. const propertyName = builder.getPropertyName( varying, NodeShaderStage.VERTEX );
  23887. // force node run in vertex stage
  23888. builder.flowNodeFromShaderStage( NodeShaderStage.VERTEX, this.node, type, propertyName );
  23889. properties.propertyName = propertyName;
  23890. }
  23891. return builder.getPropertyName( varying );
  23892. }
  23893. }
  23894. const varying = /*@__PURE__*/ nodeProxy( VaryingNode );
  23895. addMethodChaining( 'varying', varying );
  23896. const WORKING_COLOR_SPACE = 'WorkingColorSpace';
  23897. const OUTPUT_COLOR_SPACE = 'OutputColorSpace';
  23898. function getColorSpaceName( colorSpace ) {
  23899. let method = null;
  23900. if ( colorSpace === LinearSRGBColorSpace ) {
  23901. method = 'Linear';
  23902. } else if ( colorSpace === SRGBColorSpace ) {
  23903. method = 'sRGB';
  23904. }
  23905. return method;
  23906. }
  23907. function getColorSpaceMethod( source, target ) {
  23908. return getColorSpaceName( source ) + 'To' + getColorSpaceName( target );
  23909. }
  23910. class ColorSpaceNode extends TempNode {
  23911. static get type() {
  23912. return 'ColorSpaceNode';
  23913. }
  23914. constructor( colorNode, source, target ) {
  23915. super( 'vec4' );
  23916. this.colorNode = colorNode;
  23917. this.source = source;
  23918. this.target = target;
  23919. }
  23920. getColorSpace( builder, colorSpace ) {
  23921. if ( colorSpace === WORKING_COLOR_SPACE ) {
  23922. return ColorManagement.workingColorSpace;
  23923. } else if ( colorSpace === OUTPUT_COLOR_SPACE ) {
  23924. return builder.context.outputColorSpace || builder.renderer.outputColorSpace;
  23925. }
  23926. return colorSpace;
  23927. }
  23928. setup( builder ) {
  23929. const { renderer } = builder;
  23930. const { colorNode } = this;
  23931. const source = this.getColorSpace( builder, this.source );
  23932. const target = this.getColorSpace( builder, this.target );
  23933. if ( source === target ) return colorNode;
  23934. const colorSpace = getColorSpaceMethod( source, target );
  23935. let outputNode = null;
  23936. const colorSpaceFn = renderer.nodes.library.getColorSpaceFunction( colorSpace );
  23937. if ( colorSpaceFn !== null ) {
  23938. outputNode = vec4( colorSpaceFn( colorNode.rgb ), colorNode.a );
  23939. } else {
  23940. console.error( 'ColorSpaceNode: Unsupported Color Space configuration.', colorSpace );
  23941. outputNode = colorNode;
  23942. }
  23943. return outputNode;
  23944. }
  23945. }
  23946. const toOutputColorSpace = ( node ) => nodeObject( new ColorSpaceNode( nodeObject( node ), WORKING_COLOR_SPACE, OUTPUT_COLOR_SPACE ) );
  23947. const toWorkingColorSpace = ( node ) => nodeObject( new ColorSpaceNode( nodeObject( node ), OUTPUT_COLOR_SPACE, WORKING_COLOR_SPACE ) );
  23948. const workingToColorSpace = ( node, colorSpace ) => nodeObject( new ColorSpaceNode( nodeObject( node ), WORKING_COLOR_SPACE, colorSpace ) );
  23949. const colorSpaceToWorking = ( node, colorSpace ) => nodeObject( new ColorSpaceNode( nodeObject( node ), colorSpace, WORKING_COLOR_SPACE ) );
  23950. addMethodChaining( 'toOutputColorSpace', toOutputColorSpace );
  23951. addMethodChaining( 'toWorkingColorSpace', toWorkingColorSpace );
  23952. addMethodChaining( 'workingToColorSpace', workingToColorSpace );
  23953. addMethodChaining( 'colorSpaceToWorking', colorSpaceToWorking );
  23954. let ReferenceElementNode$1 = class ReferenceElementNode extends ArrayElementNode {
  23955. static get type() {
  23956. return 'ReferenceElementNode';
  23957. }
  23958. constructor( referenceNode, indexNode ) {
  23959. super( referenceNode, indexNode );
  23960. this.referenceNode = referenceNode;
  23961. this.isReferenceElementNode = true;
  23962. }
  23963. getNodeType() {
  23964. return this.referenceNode.uniformType;
  23965. }
  23966. generate( builder ) {
  23967. const snippet = super.generate( builder );
  23968. const arrayType = this.referenceNode.getNodeType();
  23969. const elementType = this.getNodeType();
  23970. return builder.format( snippet, arrayType, elementType );
  23971. }
  23972. };
  23973. class ReferenceBaseNode extends Node {
  23974. static get type() {
  23975. return 'ReferenceBaseNode';
  23976. }
  23977. constructor( property, uniformType, object = null, count = null ) {
  23978. super();
  23979. this.property = property;
  23980. this.uniformType = uniformType;
  23981. this.object = object;
  23982. this.count = count;
  23983. this.properties = property.split( '.' );
  23984. this.reference = object;
  23985. this.node = null;
  23986. this.group = null;
  23987. this.updateType = NodeUpdateType.OBJECT;
  23988. }
  23989. setGroup( group ) {
  23990. this.group = group;
  23991. return this;
  23992. }
  23993. element( indexNode ) {
  23994. return nodeObject( new ReferenceElementNode$1( this, nodeObject( indexNode ) ) );
  23995. }
  23996. setNodeType( uniformType ) {
  23997. const node = uniform( null, uniformType ).getSelf();
  23998. if ( this.group !== null ) {
  23999. node.setGroup( this.group );
  24000. }
  24001. this.node = node;
  24002. }
  24003. getNodeType( builder ) {
  24004. if ( this.node === null ) {
  24005. this.updateReference( builder );
  24006. this.updateValue();
  24007. }
  24008. return this.node.getNodeType( builder );
  24009. }
  24010. getValueFromReference( object = this.reference ) {
  24011. const { properties } = this;
  24012. let value = object[ properties[ 0 ] ];
  24013. for ( let i = 1; i < properties.length; i ++ ) {
  24014. value = value[ properties[ i ] ];
  24015. }
  24016. return value;
  24017. }
  24018. updateReference( state ) {
  24019. this.reference = this.object !== null ? this.object : state.object;
  24020. return this.reference;
  24021. }
  24022. setup() {
  24023. this.updateValue();
  24024. return this.node;
  24025. }
  24026. update( /*frame*/ ) {
  24027. this.updateValue();
  24028. }
  24029. updateValue() {
  24030. if ( this.node === null ) this.setNodeType( this.uniformType );
  24031. const value = this.getValueFromReference();
  24032. if ( Array.isArray( value ) ) {
  24033. this.node.array = value;
  24034. } else {
  24035. this.node.value = value;
  24036. }
  24037. }
  24038. }
  24039. const reference$1 = ( name, type, object ) => nodeObject( new ReferenceBaseNode( name, type, object ) );
  24040. class RendererReferenceNode extends ReferenceBaseNode {
  24041. static get type() {
  24042. return 'RendererReferenceNode';
  24043. }
  24044. constructor( property, inputType, renderer = null ) {
  24045. super( property, inputType, renderer );
  24046. this.renderer = renderer;
  24047. this.setGroup( renderGroup );
  24048. }
  24049. updateReference( state ) {
  24050. this.reference = this.renderer !== null ? this.renderer : state.renderer;
  24051. return this.reference;
  24052. }
  24053. }
  24054. const rendererReference = ( name, type, renderer ) => nodeObject( new RendererReferenceNode( name, type, renderer ) );
  24055. class ToneMappingNode extends TempNode {
  24056. static get type() {
  24057. return 'ToneMappingNode';
  24058. }
  24059. constructor( toneMapping, exposureNode = toneMappingExposure, colorNode = null ) {
  24060. super( 'vec3' );
  24061. this.toneMapping = toneMapping;
  24062. this.exposureNode = exposureNode;
  24063. this.colorNode = colorNode;
  24064. }
  24065. getCacheKey() {
  24066. return hash$1( super.getCacheKey(), this.toneMapping );
  24067. }
  24068. setup( builder ) {
  24069. const colorNode = this.colorNode || builder.context.color;
  24070. const toneMapping = this.toneMapping;
  24071. if ( toneMapping === NoToneMapping ) return colorNode;
  24072. let outputNode = null;
  24073. const toneMappingFn = builder.renderer.nodes.library.getToneMappingFunction( toneMapping );
  24074. if ( toneMappingFn !== null ) {
  24075. outputNode = vec4( toneMappingFn( colorNode.rgb, this.exposureNode ), colorNode.a );
  24076. } else {
  24077. console.error( 'ToneMappingNode: Unsupported Tone Mapping configuration.', toneMapping );
  24078. outputNode = colorNode;
  24079. }
  24080. return outputNode;
  24081. }
  24082. }
  24083. const toneMapping = ( mapping, exposure, color ) => nodeObject( new ToneMappingNode( mapping, nodeObject( exposure ), nodeObject( color ) ) );
  24084. const toneMappingExposure = /*@__PURE__*/ rendererReference( 'toneMappingExposure', 'float' );
  24085. addMethodChaining( 'toneMapping', ( color, mapping, exposure ) => toneMapping( mapping, exposure, color ) );
  24086. class BufferAttributeNode extends InputNode {
  24087. static get type() {
  24088. return 'BufferAttributeNode';
  24089. }
  24090. constructor( value, bufferType = null, bufferStride = 0, bufferOffset = 0 ) {
  24091. super( value, bufferType );
  24092. this.isBufferNode = true;
  24093. this.bufferType = bufferType;
  24094. this.bufferStride = bufferStride;
  24095. this.bufferOffset = bufferOffset;
  24096. this.usage = StaticDrawUsage;
  24097. this.instanced = false;
  24098. this.attribute = null;
  24099. this.global = true;
  24100. if ( value && value.isBufferAttribute === true ) {
  24101. this.attribute = value;
  24102. this.usage = value.usage;
  24103. this.instanced = value.isInstancedBufferAttribute;
  24104. }
  24105. }
  24106. getHash( builder ) {
  24107. if ( this.bufferStride === 0 && this.bufferOffset === 0 ) {
  24108. let bufferData = builder.globalCache.getData( this.value );
  24109. if ( bufferData === undefined ) {
  24110. bufferData = {
  24111. node: this
  24112. };
  24113. builder.globalCache.setData( this.value, bufferData );
  24114. }
  24115. return bufferData.node.uuid;
  24116. }
  24117. return this.uuid;
  24118. }
  24119. getNodeType( builder ) {
  24120. if ( this.bufferType === null ) {
  24121. this.bufferType = builder.getTypeFromAttribute( this.attribute );
  24122. }
  24123. return this.bufferType;
  24124. }
  24125. setup( builder ) {
  24126. if ( this.attribute !== null ) return;
  24127. const type = this.getNodeType( builder );
  24128. const array = this.value;
  24129. const itemSize = builder.getTypeLength( type );
  24130. const stride = this.bufferStride || itemSize;
  24131. const offset = this.bufferOffset;
  24132. const buffer = array.isInterleavedBuffer === true ? array : new InterleavedBuffer( array, stride );
  24133. const bufferAttribute = new InterleavedBufferAttribute( buffer, itemSize, offset );
  24134. buffer.setUsage( this.usage );
  24135. this.attribute = bufferAttribute;
  24136. this.attribute.isInstancedBufferAttribute = this.instanced; // @TODO: Add a possible: InstancedInterleavedBufferAttribute
  24137. }
  24138. generate( builder ) {
  24139. const nodeType = this.getNodeType( builder );
  24140. const nodeAttribute = builder.getBufferAttributeFromNode( this, nodeType );
  24141. const propertyName = builder.getPropertyName( nodeAttribute );
  24142. let output = null;
  24143. if ( builder.shaderStage === 'vertex' || builder.shaderStage === 'compute' ) {
  24144. this.name = propertyName;
  24145. output = propertyName;
  24146. } else {
  24147. const nodeVarying = varying( this );
  24148. output = nodeVarying.build( builder, nodeType );
  24149. }
  24150. return output;
  24151. }
  24152. getInputType( /*builder*/ ) {
  24153. return 'bufferAttribute';
  24154. }
  24155. setUsage( value ) {
  24156. this.usage = value;
  24157. if ( this.attribute && this.attribute.isBufferAttribute === true ) {
  24158. this.attribute.usage = value;
  24159. }
  24160. return this;
  24161. }
  24162. setInstanced( value ) {
  24163. this.instanced = value;
  24164. return this;
  24165. }
  24166. }
  24167. const bufferAttribute = ( array, type, stride, offset ) => nodeObject( new BufferAttributeNode( array, type, stride, offset ) );
  24168. const dynamicBufferAttribute = ( array, type, stride, offset ) => bufferAttribute( array, type, stride, offset ).setUsage( DynamicDrawUsage );
  24169. const instancedBufferAttribute = ( array, type, stride, offset ) => bufferAttribute( array, type, stride, offset ).setInstanced( true );
  24170. const instancedDynamicBufferAttribute = ( array, type, stride, offset ) => dynamicBufferAttribute( array, type, stride, offset ).setInstanced( true );
  24171. addMethodChaining( 'toAttribute', ( bufferNode ) => bufferAttribute( bufferNode.value ) );
  24172. class ComputeNode extends Node {
  24173. static get type() {
  24174. return 'ComputeNode';
  24175. }
  24176. constructor( computeNode, count, workgroupSize = [ 64 ] ) {
  24177. super( 'void' );
  24178. this.isComputeNode = true;
  24179. this.computeNode = computeNode;
  24180. this.count = count;
  24181. this.workgroupSize = workgroupSize;
  24182. this.dispatchCount = 0;
  24183. this.version = 1;
  24184. this.updateBeforeType = NodeUpdateType.OBJECT;
  24185. this.onInitFunction = null;
  24186. this.updateDispatchCount();
  24187. }
  24188. dispose() {
  24189. this.dispatchEvent( { type: 'dispose' } );
  24190. }
  24191. set needsUpdate( value ) {
  24192. if ( value === true ) this.version ++;
  24193. }
  24194. updateDispatchCount() {
  24195. const { count, workgroupSize } = this;
  24196. let size = workgroupSize[ 0 ];
  24197. for ( let i = 1; i < workgroupSize.length; i ++ )
  24198. size *= workgroupSize[ i ];
  24199. this.dispatchCount = Math.ceil( count / size );
  24200. }
  24201. onInit( callback ) {
  24202. this.onInitFunction = callback;
  24203. return this;
  24204. }
  24205. updateBefore( { renderer } ) {
  24206. renderer.compute( this );
  24207. }
  24208. generate( builder ) {
  24209. const { shaderStage } = builder;
  24210. if ( shaderStage === 'compute' ) {
  24211. const snippet = this.computeNode.build( builder, 'void' );
  24212. if ( snippet !== '' ) {
  24213. builder.addLineFlowCode( snippet, this );
  24214. }
  24215. }
  24216. }
  24217. }
  24218. const compute = ( node, count, workgroupSize ) => nodeObject( new ComputeNode( nodeObject( node ), count, workgroupSize ) );
  24219. addMethodChaining( 'compute', compute );
  24220. class CacheNode extends Node {
  24221. static get type() {
  24222. return 'CacheNode';
  24223. }
  24224. constructor( node, parent = true ) {
  24225. super();
  24226. this.node = node;
  24227. this.parent = parent;
  24228. this.isCacheNode = true;
  24229. }
  24230. getNodeType( builder ) {
  24231. return this.node.getNodeType( builder );
  24232. }
  24233. build( builder, ...params ) {
  24234. const previousCache = builder.getCache();
  24235. const cache = builder.getCacheFromNode( this, this.parent );
  24236. builder.setCache( cache );
  24237. const data = this.node.build( builder, ...params );
  24238. builder.setCache( previousCache );
  24239. return data;
  24240. }
  24241. }
  24242. const cache = ( node, ...params ) => nodeObject( new CacheNode( nodeObject( node ), ...params ) );
  24243. addMethodChaining( 'cache', cache );
  24244. class BypassNode extends Node {
  24245. static get type() {
  24246. return 'BypassNode';
  24247. }
  24248. constructor( returnNode, callNode ) {
  24249. super();
  24250. this.isBypassNode = true;
  24251. this.outputNode = returnNode;
  24252. this.callNode = callNode;
  24253. }
  24254. getNodeType( builder ) {
  24255. return this.outputNode.getNodeType( builder );
  24256. }
  24257. generate( builder ) {
  24258. const snippet = this.callNode.build( builder, 'void' );
  24259. if ( snippet !== '' ) {
  24260. builder.addLineFlowCode( snippet, this );
  24261. }
  24262. return this.outputNode.build( builder );
  24263. }
  24264. }
  24265. const bypass = /*@__PURE__*/ nodeProxy( BypassNode );
  24266. addMethodChaining( 'bypass', bypass );
  24267. class RemapNode extends Node {
  24268. static get type() {
  24269. return 'RemapNode';
  24270. }
  24271. constructor( node, inLowNode, inHighNode, outLowNode = float( 0 ), outHighNode = float( 1 ) ) {
  24272. super();
  24273. this.node = node;
  24274. this.inLowNode = inLowNode;
  24275. this.inHighNode = inHighNode;
  24276. this.outLowNode = outLowNode;
  24277. this.outHighNode = outHighNode;
  24278. this.doClamp = true;
  24279. }
  24280. setup() {
  24281. const { node, inLowNode, inHighNode, outLowNode, outHighNode, doClamp } = this;
  24282. let t = node.sub( inLowNode ).div( inHighNode.sub( inLowNode ) );
  24283. if ( doClamp === true ) t = t.clamp();
  24284. return t.mul( outHighNode.sub( outLowNode ) ).add( outLowNode );
  24285. }
  24286. }
  24287. const remap = /*@__PURE__*/ nodeProxy( RemapNode, null, null, { doClamp: false } );
  24288. const remapClamp = /*@__PURE__*/ nodeProxy( RemapNode );
  24289. addMethodChaining( 'remap', remap );
  24290. addMethodChaining( 'remapClamp', remapClamp );
  24291. class ExpressionNode extends Node {
  24292. static get type() {
  24293. return 'ExpressionNode';
  24294. }
  24295. constructor( snippet = '', nodeType = 'void' ) {
  24296. super( nodeType );
  24297. this.snippet = snippet;
  24298. }
  24299. generate( builder, output ) {
  24300. const type = this.getNodeType( builder );
  24301. const snippet = this.snippet;
  24302. if ( type === 'void' ) {
  24303. builder.addLineFlowCode( snippet, this );
  24304. } else {
  24305. return builder.format( `( ${ snippet } )`, type, output );
  24306. }
  24307. }
  24308. }
  24309. const expression = /*@__PURE__*/ nodeProxy( ExpressionNode );
  24310. const Discard = ( conditional ) => ( conditional ? select( conditional, expression( 'discard' ) ) : expression( 'discard' ) ).append();
  24311. const Return = () => expression( 'return' ).append();
  24312. addMethodChaining( 'discard', Discard );
  24313. class RenderOutputNode extends TempNode {
  24314. static get type() {
  24315. return 'RenderOutputNode';
  24316. }
  24317. constructor( colorNode, toneMapping, outputColorSpace ) {
  24318. super( 'vec4' );
  24319. this.colorNode = colorNode;
  24320. this.toneMapping = toneMapping;
  24321. this.outputColorSpace = outputColorSpace;
  24322. this.isRenderOutput = true;
  24323. }
  24324. setup( { context } ) {
  24325. let outputNode = this.colorNode || context.color;
  24326. // tone mapping
  24327. const toneMapping = ( this.toneMapping !== null ? this.toneMapping : context.toneMapping ) || NoToneMapping;
  24328. const outputColorSpace = ( this.outputColorSpace !== null ? this.outputColorSpace : context.outputColorSpace ) || NoColorSpace;
  24329. if ( toneMapping !== NoToneMapping ) {
  24330. outputNode = outputNode.toneMapping( toneMapping );
  24331. }
  24332. // working to output color space
  24333. if ( outputColorSpace !== NoColorSpace && outputColorSpace !== ColorManagement.workingColorSpace ) {
  24334. outputNode = outputNode.workingToColorSpace( outputColorSpace );
  24335. }
  24336. return outputNode;
  24337. }
  24338. }
  24339. const renderOutput = ( color, toneMapping = null, outputColorSpace = null ) => nodeObject( new RenderOutputNode( nodeObject( color ), toneMapping, outputColorSpace ) );
  24340. addMethodChaining( 'renderOutput', renderOutput );
  24341. // Non-PURE exports list, side-effects are required here.
  24342. // TSL Base Syntax
  24343. function addNodeElement( name/*, nodeElement*/ ) {
  24344. console.warn( 'THREE.TSLBase: AddNodeElement has been removed in favor of tree-shaking. Trying add', name );
  24345. }
  24346. class AttributeNode extends Node {
  24347. static get type() {
  24348. return 'AttributeNode';
  24349. }
  24350. constructor( attributeName, nodeType = null ) {
  24351. super( nodeType );
  24352. this.global = true;
  24353. this._attributeName = attributeName;
  24354. }
  24355. getHash( builder ) {
  24356. return this.getAttributeName( builder );
  24357. }
  24358. getNodeType( builder ) {
  24359. let nodeType = this.nodeType;
  24360. if ( nodeType === null ) {
  24361. const attributeName = this.getAttributeName( builder );
  24362. if ( builder.hasGeometryAttribute( attributeName ) ) {
  24363. const attribute = builder.geometry.getAttribute( attributeName );
  24364. nodeType = builder.getTypeFromAttribute( attribute );
  24365. } else {
  24366. nodeType = 'float';
  24367. }
  24368. }
  24369. return nodeType;
  24370. }
  24371. setAttributeName( attributeName ) {
  24372. this._attributeName = attributeName;
  24373. return this;
  24374. }
  24375. getAttributeName( /*builder*/ ) {
  24376. return this._attributeName;
  24377. }
  24378. generate( builder ) {
  24379. const attributeName = this.getAttributeName( builder );
  24380. const nodeType = this.getNodeType( builder );
  24381. const geometryAttribute = builder.hasGeometryAttribute( attributeName );
  24382. if ( geometryAttribute === true ) {
  24383. const attribute = builder.geometry.getAttribute( attributeName );
  24384. const attributeType = builder.getTypeFromAttribute( attribute );
  24385. const nodeAttribute = builder.getAttribute( attributeName, attributeType );
  24386. if ( builder.shaderStage === 'vertex' ) {
  24387. return builder.format( nodeAttribute.name, attributeType, nodeType );
  24388. } else {
  24389. const nodeVarying = varying( this );
  24390. return nodeVarying.build( builder, nodeType );
  24391. }
  24392. } else {
  24393. console.warn( `AttributeNode: Vertex attribute "${ attributeName }" not found on geometry.` );
  24394. return builder.generateConst( nodeType );
  24395. }
  24396. }
  24397. serialize( data ) {
  24398. super.serialize( data );
  24399. data.global = this.global;
  24400. data._attributeName = this._attributeName;
  24401. }
  24402. deserialize( data ) {
  24403. super.deserialize( data );
  24404. this.global = data.global;
  24405. this._attributeName = data._attributeName;
  24406. }
  24407. }
  24408. const attribute = ( name, nodeType ) => nodeObject( new AttributeNode( name, nodeType ) );
  24409. const uv = ( index ) => attribute( 'uv' + ( index > 0 ? index : '' ), 'vec2' );
  24410. class TextureSizeNode extends Node {
  24411. static get type() {
  24412. return 'TextureSizeNode';
  24413. }
  24414. constructor( textureNode, levelNode = null ) {
  24415. super( 'uvec2' );
  24416. this.isTextureSizeNode = true;
  24417. this.textureNode = textureNode;
  24418. this.levelNode = levelNode;
  24419. }
  24420. generate( builder, output ) {
  24421. const textureProperty = this.textureNode.build( builder, 'property' );
  24422. const level = this.levelNode === null ? '0' : this.levelNode.build( builder, 'int' );
  24423. return builder.format( `${ builder.getMethod( 'textureDimensions' ) }( ${ textureProperty }, ${ level } )`, this.getNodeType( builder ), output );
  24424. }
  24425. }
  24426. const textureSize = /*@__PURE__*/ nodeProxy( TextureSizeNode );
  24427. class MaxMipLevelNode extends UniformNode {
  24428. static get type() {
  24429. return 'MaxMipLevelNode';
  24430. }
  24431. constructor( textureNode ) {
  24432. super( 0 );
  24433. this._textureNode = textureNode;
  24434. this.updateType = NodeUpdateType.FRAME;
  24435. }
  24436. get textureNode() {
  24437. return this._textureNode;
  24438. }
  24439. get texture() {
  24440. return this._textureNode.value;
  24441. }
  24442. update() {
  24443. const texture = this.texture;
  24444. const images = texture.images;
  24445. const image = ( images && images.length > 0 ) ? ( ( images[ 0 ] && images[ 0 ].image ) || images[ 0 ] ) : texture.image;
  24446. if ( image && image.width !== undefined ) {
  24447. const { width, height } = image;
  24448. this.value = Math.log2( Math.max( width, height ) );
  24449. }
  24450. }
  24451. }
  24452. const maxMipLevel = /*@__PURE__*/ nodeProxy( MaxMipLevelNode );
  24453. class TextureNode extends UniformNode {
  24454. static get type() {
  24455. return 'TextureNode';
  24456. }
  24457. constructor( value, uvNode = null, levelNode = null, biasNode = null ) {
  24458. super( value );
  24459. this.isTextureNode = true;
  24460. this.uvNode = uvNode;
  24461. this.levelNode = levelNode;
  24462. this.biasNode = biasNode;
  24463. this.compareNode = null;
  24464. this.depthNode = null;
  24465. this.gradNode = null;
  24466. this.sampler = true;
  24467. this.updateMatrix = false;
  24468. this.updateType = NodeUpdateType.NONE;
  24469. this.referenceNode = null;
  24470. this._value = value;
  24471. this._matrixUniform = null;
  24472. this.setUpdateMatrix( uvNode === null );
  24473. }
  24474. set value( value ) {
  24475. if ( this.referenceNode ) {
  24476. this.referenceNode.value = value;
  24477. } else {
  24478. this._value = value;
  24479. }
  24480. }
  24481. get value() {
  24482. return this.referenceNode ? this.referenceNode.value : this._value;
  24483. }
  24484. getUniformHash( /*builder*/ ) {
  24485. return this.value.uuid;
  24486. }
  24487. getNodeType( /*builder*/ ) {
  24488. if ( this.value.isDepthTexture === true ) return 'float';
  24489. if ( this.value.type === UnsignedIntType ) {
  24490. return 'uvec4';
  24491. } else if ( this.value.type === IntType ) {
  24492. return 'ivec4';
  24493. }
  24494. return 'vec4';
  24495. }
  24496. getInputType( /*builder*/ ) {
  24497. return 'texture';
  24498. }
  24499. getDefaultUV() {
  24500. return uv( this.value.channel );
  24501. }
  24502. updateReference( /*state*/ ) {
  24503. return this.value;
  24504. }
  24505. getTransformedUV( uvNode ) {
  24506. if ( this._matrixUniform === null ) this._matrixUniform = uniform( this.value.matrix );
  24507. return this._matrixUniform.mul( vec3( uvNode, 1 ) ).xy;
  24508. }
  24509. setUpdateMatrix( value ) {
  24510. this.updateMatrix = value;
  24511. this.updateType = value ? NodeUpdateType.FRAME : NodeUpdateType.NONE;
  24512. return this;
  24513. }
  24514. setupUV( builder, uvNode ) {
  24515. const texture = this.value;
  24516. if ( builder.isFlipY() && ( texture.isRenderTargetTexture === true || texture.isFramebufferTexture === true || texture.isDepthTexture === true ) ) {
  24517. if ( this.sampler ) {
  24518. uvNode = uvNode.flipY();
  24519. } else {
  24520. uvNode = uvNode.setY( int( textureSize( this, this.levelNode ).y ).sub( uvNode.y ).sub( 1 ) );
  24521. }
  24522. }
  24523. return uvNode;
  24524. }
  24525. setup( builder ) {
  24526. const properties = builder.getNodeProperties( this );
  24527. properties.referenceNode = this.referenceNode;
  24528. //
  24529. let uvNode = this.uvNode;
  24530. if ( ( uvNode === null || builder.context.forceUVContext === true ) && builder.context.getUV ) {
  24531. uvNode = builder.context.getUV( this );
  24532. }
  24533. if ( ! uvNode ) uvNode = this.getDefaultUV();
  24534. if ( this.updateMatrix === true ) {
  24535. uvNode = this.getTransformedUV( uvNode );
  24536. }
  24537. uvNode = this.setupUV( builder, uvNode );
  24538. //
  24539. let levelNode = this.levelNode;
  24540. if ( levelNode === null && builder.context.getTextureLevel ) {
  24541. levelNode = builder.context.getTextureLevel( this );
  24542. }
  24543. //
  24544. properties.uvNode = uvNode;
  24545. properties.levelNode = levelNode;
  24546. properties.biasNode = this.biasNode;
  24547. properties.compareNode = this.compareNode;
  24548. properties.gradNode = this.gradNode;
  24549. properties.depthNode = this.depthNode;
  24550. }
  24551. generateUV( builder, uvNode ) {
  24552. return uvNode.build( builder, this.sampler === true ? 'vec2' : 'ivec2' );
  24553. }
  24554. generateSnippet( builder, textureProperty, uvSnippet, levelSnippet, biasSnippet, depthSnippet, compareSnippet, gradSnippet ) {
  24555. const texture = this.value;
  24556. let snippet;
  24557. if ( levelSnippet ) {
  24558. snippet = builder.generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet );
  24559. } else if ( biasSnippet ) {
  24560. snippet = builder.generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet, depthSnippet );
  24561. } else if ( gradSnippet ) {
  24562. snippet = builder.generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet, depthSnippet );
  24563. } else if ( compareSnippet ) {
  24564. snippet = builder.generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet );
  24565. } else if ( this.sampler === false ) {
  24566. snippet = builder.generateTextureLoad( texture, textureProperty, uvSnippet, depthSnippet );
  24567. } else {
  24568. snippet = builder.generateTexture( texture, textureProperty, uvSnippet, depthSnippet );
  24569. }
  24570. return snippet;
  24571. }
  24572. generate( builder, output ) {
  24573. const properties = builder.getNodeProperties( this );
  24574. const texture = this.value;
  24575. if ( ! texture || texture.isTexture !== true ) {
  24576. throw new Error( 'TextureNode: Need a three.js texture.' );
  24577. }
  24578. const textureProperty = super.generate( builder, 'property' );
  24579. if ( output === 'sampler' ) {
  24580. return textureProperty + '_sampler';
  24581. } else if ( builder.isReference( output ) ) {
  24582. return textureProperty;
  24583. } else {
  24584. const nodeData = builder.getDataFromNode( this );
  24585. let propertyName = nodeData.propertyName;
  24586. if ( propertyName === undefined ) {
  24587. const { uvNode, levelNode, biasNode, compareNode, depthNode, gradNode } = properties;
  24588. const uvSnippet = this.generateUV( builder, uvNode );
  24589. const levelSnippet = levelNode ? levelNode.build( builder, 'float' ) : null;
  24590. const biasSnippet = biasNode ? biasNode.build( builder, 'float' ) : null;
  24591. const depthSnippet = depthNode ? depthNode.build( builder, 'int' ) : null;
  24592. const compareSnippet = compareNode ? compareNode.build( builder, 'float' ) : null;
  24593. const gradSnippet = gradNode ? [ gradNode[ 0 ].build( builder, 'vec2' ), gradNode[ 1 ].build( builder, 'vec2' ) ] : null;
  24594. const nodeVar = builder.getVarFromNode( this );
  24595. propertyName = builder.getPropertyName( nodeVar );
  24596. const snippet = this.generateSnippet( builder, textureProperty, uvSnippet, levelSnippet, biasSnippet, depthSnippet, compareSnippet, gradSnippet );
  24597. builder.addLineFlowCode( `${propertyName} = ${snippet}`, this );
  24598. nodeData.snippet = snippet;
  24599. nodeData.propertyName = propertyName;
  24600. }
  24601. let snippet = propertyName;
  24602. const nodeType = this.getNodeType( builder );
  24603. if ( builder.needsToWorkingColorSpace( texture ) ) {
  24604. snippet = colorSpaceToWorking( expression( snippet, nodeType ), texture.colorSpace ).setup( builder ).build( builder, nodeType );
  24605. }
  24606. return builder.format( snippet, nodeType, output );
  24607. }
  24608. }
  24609. setSampler( value ) {
  24610. this.sampler = value;
  24611. return this;
  24612. }
  24613. getSampler() {
  24614. return this.sampler;
  24615. }
  24616. // @TODO: Move to TSL
  24617. uv( uvNode ) {
  24618. const textureNode = this.clone();
  24619. textureNode.uvNode = nodeObject( uvNode );
  24620. textureNode.referenceNode = this.getSelf();
  24621. return nodeObject( textureNode );
  24622. }
  24623. blur( amountNode ) {
  24624. const textureNode = this.clone();
  24625. textureNode.biasNode = nodeObject( amountNode ).mul( maxMipLevel( textureNode ) );
  24626. textureNode.referenceNode = this.getSelf();
  24627. return nodeObject( textureNode );
  24628. }
  24629. level( levelNode ) {
  24630. const textureNode = this.clone();
  24631. textureNode.levelNode = nodeObject( levelNode );
  24632. textureNode.referenceNode = this.getSelf();
  24633. return nodeObject( textureNode );
  24634. }
  24635. size( levelNode ) {
  24636. return textureSize( this, levelNode );
  24637. }
  24638. bias( biasNode ) {
  24639. const textureNode = this.clone();
  24640. textureNode.biasNode = nodeObject( biasNode );
  24641. textureNode.referenceNode = this.getSelf();
  24642. return nodeObject( textureNode );
  24643. }
  24644. compare( compareNode ) {
  24645. const textureNode = this.clone();
  24646. textureNode.compareNode = nodeObject( compareNode );
  24647. textureNode.referenceNode = this.getSelf();
  24648. return nodeObject( textureNode );
  24649. }
  24650. grad( gradNodeX, gradNodeY ) {
  24651. const textureNode = this.clone();
  24652. textureNode.gradNode = [ nodeObject( gradNodeX ), nodeObject( gradNodeY ) ];
  24653. textureNode.referenceNode = this.getSelf();
  24654. return nodeObject( textureNode );
  24655. }
  24656. depth( depthNode ) {
  24657. const textureNode = this.clone();
  24658. textureNode.depthNode = nodeObject( depthNode );
  24659. textureNode.referenceNode = this.getSelf();
  24660. return nodeObject( textureNode );
  24661. }
  24662. // --
  24663. serialize( data ) {
  24664. super.serialize( data );
  24665. data.value = this.value.toJSON( data.meta ).uuid;
  24666. data.sampler = this.sampler;
  24667. data.updateMatrix = this.updateMatrix;
  24668. data.updateType = this.updateType;
  24669. }
  24670. deserialize( data ) {
  24671. super.deserialize( data );
  24672. this.value = data.meta.textures[ data.value ];
  24673. this.sampler = data.sampler;
  24674. this.updateMatrix = data.updateMatrix;
  24675. this.updateType = data.updateType;
  24676. }
  24677. update() {
  24678. const texture = this.value;
  24679. const matrixUniform = this._matrixUniform;
  24680. if ( matrixUniform !== null ) matrixUniform.value = texture.matrix;
  24681. if ( texture.matrixAutoUpdate === true ) {
  24682. texture.updateMatrix();
  24683. }
  24684. }
  24685. clone() {
  24686. const newNode = new this.constructor( this.value, this.uvNode, this.levelNode, this.biasNode );
  24687. newNode.sampler = this.sampler;
  24688. return newNode;
  24689. }
  24690. }
  24691. const texture = /*@__PURE__*/ nodeProxy( TextureNode );
  24692. const textureLoad = ( ...params ) => texture( ...params ).setSampler( false );
  24693. //export const textureLevel = ( value, uv, level ) => texture( value, uv ).level( level );
  24694. const sampler = ( aTexture ) => ( aTexture.isNode === true ? aTexture : texture( aTexture ) ).convert( 'sampler' );
  24695. const cameraNear = /*@__PURE__*/ uniform( 'float' ).label( 'cameraNear' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.near );
  24696. const cameraFar = /*@__PURE__*/ uniform( 'float' ).label( 'cameraFar' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.far );
  24697. const cameraProjectionMatrix = /*@__PURE__*/ uniform( 'mat4' ).label( 'cameraProjectionMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.projectionMatrix );
  24698. const cameraProjectionMatrixInverse = /*@__PURE__*/ uniform( 'mat4' ).label( 'cameraProjectionMatrixInverse' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.projectionMatrixInverse );
  24699. const cameraViewMatrix = /*@__PURE__*/ uniform( 'mat4' ).label( 'cameraViewMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.matrixWorldInverse );
  24700. const cameraWorldMatrix = /*@__PURE__*/ uniform( 'mat4' ).label( 'cameraWorldMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.matrixWorld );
  24701. const cameraNormalMatrix = /*@__PURE__*/ uniform( 'mat3' ).label( 'cameraNormalMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.normalMatrix );
  24702. const cameraPosition = /*@__PURE__*/ uniform( new Vector3() ).label( 'cameraPosition' ).setGroup( renderGroup ).onRenderUpdate( ( { camera }, self ) => self.value.setFromMatrixPosition( camera.matrixWorld ) );
  24703. class Object3DNode extends Node {
  24704. static get type() {
  24705. return 'Object3DNode';
  24706. }
  24707. constructor( scope, object3d = null ) {
  24708. super();
  24709. this.scope = scope;
  24710. this.object3d = object3d;
  24711. this.updateType = NodeUpdateType.OBJECT;
  24712. this._uniformNode = new UniformNode( null );
  24713. }
  24714. getNodeType() {
  24715. const scope = this.scope;
  24716. if ( scope === Object3DNode.WORLD_MATRIX ) {
  24717. return 'mat4';
  24718. } else if ( scope === Object3DNode.POSITION || scope === Object3DNode.VIEW_POSITION || scope === Object3DNode.DIRECTION || scope === Object3DNode.SCALE ) {
  24719. return 'vec3';
  24720. }
  24721. }
  24722. update( frame ) {
  24723. const object = this.object3d;
  24724. const uniformNode = this._uniformNode;
  24725. const scope = this.scope;
  24726. if ( scope === Object3DNode.WORLD_MATRIX ) {
  24727. uniformNode.value = object.matrixWorld;
  24728. } else if ( scope === Object3DNode.POSITION ) {
  24729. uniformNode.value = uniformNode.value || new Vector3();
  24730. uniformNode.value.setFromMatrixPosition( object.matrixWorld );
  24731. } else if ( scope === Object3DNode.SCALE ) {
  24732. uniformNode.value = uniformNode.value || new Vector3();
  24733. uniformNode.value.setFromMatrixScale( object.matrixWorld );
  24734. } else if ( scope === Object3DNode.DIRECTION ) {
  24735. uniformNode.value = uniformNode.value || new Vector3();
  24736. object.getWorldDirection( uniformNode.value );
  24737. } else if ( scope === Object3DNode.VIEW_POSITION ) {
  24738. const camera = frame.camera;
  24739. uniformNode.value = uniformNode.value || new Vector3();
  24740. uniformNode.value.setFromMatrixPosition( object.matrixWorld );
  24741. uniformNode.value.applyMatrix4( camera.matrixWorldInverse );
  24742. }
  24743. }
  24744. generate( builder ) {
  24745. const scope = this.scope;
  24746. if ( scope === Object3DNode.WORLD_MATRIX ) {
  24747. this._uniformNode.nodeType = 'mat4';
  24748. } else if ( scope === Object3DNode.POSITION || scope === Object3DNode.VIEW_POSITION || scope === Object3DNode.DIRECTION || scope === Object3DNode.SCALE ) {
  24749. this._uniformNode.nodeType = 'vec3';
  24750. }
  24751. return this._uniformNode.build( builder );
  24752. }
  24753. serialize( data ) {
  24754. super.serialize( data );
  24755. data.scope = this.scope;
  24756. }
  24757. deserialize( data ) {
  24758. super.deserialize( data );
  24759. this.scope = data.scope;
  24760. }
  24761. }
  24762. Object3DNode.WORLD_MATRIX = 'worldMatrix';
  24763. Object3DNode.POSITION = 'position';
  24764. Object3DNode.SCALE = 'scale';
  24765. Object3DNode.VIEW_POSITION = 'viewPosition';
  24766. Object3DNode.DIRECTION = 'direction';
  24767. const objectDirection = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.DIRECTION );
  24768. const objectWorldMatrix = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.WORLD_MATRIX );
  24769. const objectPosition = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.POSITION );
  24770. const objectScale = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.SCALE );
  24771. const objectViewPosition = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.VIEW_POSITION );
  24772. class ModelNode extends Object3DNode {
  24773. static get type() {
  24774. return 'ModelNode';
  24775. }
  24776. constructor( scope ) {
  24777. super( scope );
  24778. }
  24779. update( frame ) {
  24780. this.object3d = frame.object;
  24781. super.update( frame );
  24782. }
  24783. }
  24784. const modelDirection = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.DIRECTION );
  24785. const modelWorldMatrix = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.WORLD_MATRIX );
  24786. const modelPosition = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.POSITION );
  24787. const modelScale = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.SCALE );
  24788. const modelViewPosition = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.VIEW_POSITION );
  24789. const modelNormalMatrix = /*@__PURE__*/ uniform( new Matrix3() ).onObjectUpdate( ( { object }, self ) => self.value.getNormalMatrix( object.matrixWorld ) );
  24790. const modelWorldMatrixInverse = /*@__PURE__*/ uniform( new Matrix4() ).onObjectUpdate( ( { object }, self ) => self.value.copy( object.matrixWorld ).invert() );
  24791. const modelViewMatrix = /*@__PURE__*/ cameraViewMatrix.mul( modelWorldMatrix ).toVar( 'modelViewMatrix' );
  24792. const highPrecisionModelViewMatrix = /*@__PURE__*/ ( Fn( ( builder ) => {
  24793. builder.context.isHighPrecisionModelViewMatrix = true;
  24794. return uniform( 'mat4' ).onObjectUpdate( ( { object, camera } ) => {
  24795. return object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  24796. } );
  24797. } ).once() )().toVar( 'highPrecisionModelViewMatrix' );
  24798. const highPrecisionModelNormalViewMatrix = /*@__PURE__*/ ( Fn( ( builder ) => {
  24799. const isHighPrecisionModelViewMatrix = builder.context.isHighPrecisionModelViewMatrix;
  24800. return uniform( 'mat3' ).onObjectUpdate( ( { object, camera } ) => {
  24801. if ( isHighPrecisionModelViewMatrix !== true ) {
  24802. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  24803. }
  24804. return object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  24805. } );
  24806. } ).once() )().toVar( 'highPrecisionModelNormalMatrix' );
  24807. const positionGeometry = /*@__PURE__*/ attribute( 'position', 'vec3' );
  24808. const positionLocal = /*@__PURE__*/ positionGeometry.varying( 'positionLocal' );
  24809. const positionPrevious = /*@__PURE__*/ positionGeometry.varying( 'positionPrevious' );
  24810. const positionWorld = /*@__PURE__*/ modelWorldMatrix.mul( positionLocal ).xyz.varying( 'v_positionWorld' );
  24811. const positionWorldDirection = /*@__PURE__*/ positionLocal.transformDirection( modelWorldMatrix ).varying( 'v_positionWorldDirection' ).normalize().toVar( 'positionWorldDirection' );
  24812. const positionView = /*@__PURE__*/ modelViewMatrix.mul( positionLocal ).xyz.varying( 'v_positionView' );
  24813. const positionViewDirection = /*@__PURE__*/ positionView.negate().varying( 'v_positionViewDirection' ).normalize().toVar( 'positionViewDirection' );
  24814. class FrontFacingNode extends Node {
  24815. static get type() {
  24816. return 'FrontFacingNode';
  24817. }
  24818. constructor() {
  24819. super( 'bool' );
  24820. this.isFrontFacingNode = true;
  24821. }
  24822. generate( builder ) {
  24823. const { renderer, material } = builder;
  24824. if ( renderer.coordinateSystem === WebGLCoordinateSystem ) {
  24825. if ( material.side === BackSide ) {
  24826. return 'false';
  24827. }
  24828. }
  24829. return builder.getFrontFacing();
  24830. }
  24831. }
  24832. const frontFacing = /*@__PURE__*/ nodeImmutable( FrontFacingNode );
  24833. const faceDirection = /*@__PURE__*/ float( frontFacing ).mul( 2.0 ).sub( 1.0 );
  24834. const normalGeometry = /*@__PURE__*/ attribute( 'normal', 'vec3' );
  24835. const normalLocal = /*@__PURE__*/ ( Fn( ( builder ) => {
  24836. if ( builder.geometry.hasAttribute( 'normal' ) === false ) {
  24837. console.warn( 'TSL.NormalNode: Vertex attribute "normal" not found on geometry.' );
  24838. return vec3( 0, 1, 0 );
  24839. }
  24840. return normalGeometry;
  24841. }, 'vec3' ).once() )().toVar( 'normalLocal' );
  24842. const normalFlat = /*@__PURE__*/ positionView.dFdx().cross( positionView.dFdy() ).normalize().toVar( 'normalFlat' );
  24843. const normalView = /*@__PURE__*/ ( Fn( ( builder ) => {
  24844. let node;
  24845. if ( builder.material.flatShading === true ) {
  24846. node = normalFlat;
  24847. } else {
  24848. node = varying( transformNormalToView( normalLocal ), 'v_normalView' ).normalize();
  24849. }
  24850. return node;
  24851. }, 'vec3' ).once() )().toVar( 'normalView' );
  24852. const normalWorld = /*@__PURE__*/ varying( normalView.transformDirection( cameraViewMatrix ), 'v_normalWorld' ).normalize().toVar( 'normalWorld' );
  24853. const transformedNormalView = /*@__PURE__*/ ( Fn( ( builder ) => {
  24854. return builder.context.setupNormal();
  24855. }, 'vec3' ).once() )().mul( faceDirection ).toVar( 'transformedNormalView' );
  24856. const transformedNormalWorld = /*@__PURE__*/ transformedNormalView.transformDirection( cameraViewMatrix ).toVar( 'transformedNormalWorld' );
  24857. const transformedClearcoatNormalView = /*@__PURE__*/ ( Fn( ( builder ) => {
  24858. return builder.context.setupClearcoatNormal();
  24859. }, 'vec3' ).once() )().mul( faceDirection ).toVar( 'transformedClearcoatNormalView' );
  24860. const transformNormal = /*@__PURE__*/ Fn( ( [ normal, matrix = modelWorldMatrix ] ) => {
  24861. const m = mat3( matrix );
  24862. const transformedNormal = normal.div( vec3( m[ 0 ].dot( m[ 0 ] ), m[ 1 ].dot( m[ 1 ] ), m[ 2 ].dot( m[ 2 ] ) ) );
  24863. return m.mul( transformedNormal ).xyz;
  24864. } );
  24865. const transformNormalToView = /*@__PURE__*/ Fn( ( [ normal ], builder ) => {
  24866. const modelNormalViewMatrix = builder.renderer.nodes.modelNormalViewMatrix;
  24867. if ( modelNormalViewMatrix !== null ) {
  24868. return modelNormalViewMatrix.transformDirection( normal );
  24869. }
  24870. //
  24871. const transformedNormal = modelNormalMatrix.mul( normal );
  24872. return cameraViewMatrix.transformDirection( transformedNormal );
  24873. } );
  24874. const materialRefractionRatio = /*@__PURE__*/ uniform( 0 ).onReference( ( { material } ) => material ).onRenderUpdate( ( { material } ) => material.refractionRatio );
  24875. const reflectView = /*@__PURE__*/ positionViewDirection.negate().reflect( transformedNormalView );
  24876. const refractView = /*@__PURE__*/ positionViewDirection.negate().refract( transformedNormalView, materialRefractionRatio );
  24877. const reflectVector = /*@__PURE__*/ reflectView.transformDirection( cameraViewMatrix ).toVar( 'reflectVector' );
  24878. const refractVector = /*@__PURE__*/ refractView.transformDirection( cameraViewMatrix ).toVar( 'reflectVector' );
  24879. class CubeTextureNode extends TextureNode {
  24880. static get type() {
  24881. return 'CubeTextureNode';
  24882. }
  24883. constructor( value, uvNode = null, levelNode = null, biasNode = null ) {
  24884. super( value, uvNode, levelNode, biasNode );
  24885. this.isCubeTextureNode = true;
  24886. }
  24887. getInputType( /*builder*/ ) {
  24888. return 'cubeTexture';
  24889. }
  24890. getDefaultUV() {
  24891. const texture = this.value;
  24892. if ( texture.mapping === CubeReflectionMapping ) {
  24893. return reflectVector;
  24894. } else if ( texture.mapping === CubeRefractionMapping ) {
  24895. return refractVector;
  24896. } else {
  24897. console.error( 'THREE.CubeTextureNode: Mapping "%s" not supported.', texture.mapping );
  24898. return vec3( 0, 0, 0 );
  24899. }
  24900. }
  24901. setUpdateMatrix( /*updateMatrix*/ ) { } // Ignore .updateMatrix for CubeTextureNode
  24902. setupUV( builder, uvNode ) {
  24903. const texture = this.value;
  24904. if ( builder.renderer.coordinateSystem === WebGPUCoordinateSystem || ! texture.isRenderTargetTexture ) {
  24905. return vec3( uvNode.x.negate(), uvNode.yz );
  24906. } else {
  24907. return uvNode;
  24908. }
  24909. }
  24910. generateUV( builder, cubeUV ) {
  24911. return cubeUV.build( builder, 'vec3' );
  24912. }
  24913. }
  24914. const cubeTexture = /*@__PURE__*/ nodeProxy( CubeTextureNode );
  24915. class BufferNode extends UniformNode {
  24916. static get type() {
  24917. return 'BufferNode';
  24918. }
  24919. constructor( value, bufferType, bufferCount = 0 ) {
  24920. super( value, bufferType );
  24921. this.isBufferNode = true;
  24922. this.bufferType = bufferType;
  24923. this.bufferCount = bufferCount;
  24924. }
  24925. getElementType( builder ) {
  24926. return this.getNodeType( builder );
  24927. }
  24928. getInputType( /*builder*/ ) {
  24929. return 'buffer';
  24930. }
  24931. }
  24932. const buffer = ( value, type, count ) => nodeObject( new BufferNode( value, type, count ) );
  24933. class UniformArrayElementNode extends ArrayElementNode {
  24934. static get type() {
  24935. return 'UniformArrayElementNode';
  24936. }
  24937. constructor( arrayBuffer, indexNode ) {
  24938. super( arrayBuffer, indexNode );
  24939. this.isArrayBufferElementNode = true;
  24940. }
  24941. generate( builder ) {
  24942. const snippet = super.generate( builder );
  24943. const type = this.getNodeType();
  24944. return builder.format( snippet, 'vec4', type );
  24945. }
  24946. }
  24947. class UniformArrayNode extends BufferNode {
  24948. static get type() {
  24949. return 'UniformArrayNode';
  24950. }
  24951. constructor( value, elementType = null ) {
  24952. super( null, 'vec4' );
  24953. this.array = value;
  24954. this.elementType = elementType;
  24955. this._elementType = null;
  24956. this._elementLength = 0;
  24957. this.updateType = NodeUpdateType.RENDER;
  24958. this.isArrayBufferNode = true;
  24959. }
  24960. getElementType() {
  24961. return this.elementType || this._elementType;
  24962. }
  24963. getElementLength() {
  24964. return this._elementLength;
  24965. }
  24966. update( /*frame*/ ) {
  24967. const { array, value } = this;
  24968. const elementLength = this.getElementLength();
  24969. const elementType = this.getElementType();
  24970. if ( elementLength === 1 ) {
  24971. for ( let i = 0; i < array.length; i ++ ) {
  24972. const index = i * 4;
  24973. value[ index ] = array[ i ];
  24974. }
  24975. } else if ( elementType === 'color' ) {
  24976. for ( let i = 0; i < array.length; i ++ ) {
  24977. const index = i * 4;
  24978. const vector = array[ i ];
  24979. value[ index ] = vector.r;
  24980. value[ index + 1 ] = vector.g;
  24981. value[ index + 2 ] = vector.b || 0;
  24982. //value[ index + 3 ] = vector.a || 0;
  24983. }
  24984. } else {
  24985. for ( let i = 0; i < array.length; i ++ ) {
  24986. const index = i * 4;
  24987. const vector = array[ i ];
  24988. value[ index ] = vector.x;
  24989. value[ index + 1 ] = vector.y;
  24990. value[ index + 2 ] = vector.z || 0;
  24991. value[ index + 3 ] = vector.w || 0;
  24992. }
  24993. }
  24994. }
  24995. setup( builder ) {
  24996. const length = this.array.length;
  24997. this._elementType = this.elementType === null ? getValueType( this.array[ 0 ] ) : this.elementType;
  24998. this._elementLength = builder.getTypeLength( this._elementType );
  24999. let arrayType = Float32Array;
  25000. if ( this._elementType.charAt( 0 ) === 'i' ) arrayType = Int32Array;
  25001. else if ( this._elementType.charAt( 0 ) === 'u' ) arrayType = Uint32Array;
  25002. this.value = new arrayType( length * 4 );
  25003. this.bufferCount = length;
  25004. this.bufferType = builder.changeComponentType( 'vec4', builder.getComponentType( this._elementType ) );
  25005. return super.setup( builder );
  25006. }
  25007. element( indexNode ) {
  25008. return nodeObject( new UniformArrayElementNode( this, nodeObject( indexNode ) ) );
  25009. }
  25010. }
  25011. const uniformArray = ( values, nodeType ) => nodeObject( new UniformArrayNode( values, nodeType ) );
  25012. //
  25013. const uniforms = ( values, nodeType ) => { // @deprecated, r168
  25014. console.warn( 'TSL.UniformArrayNode: uniforms() has been renamed to uniformArray().' );
  25015. return nodeObject( new UniformArrayNode( values, nodeType ) );
  25016. };
  25017. class ReferenceElementNode extends ArrayElementNode {
  25018. static get type() {
  25019. return 'ReferenceElementNode';
  25020. }
  25021. constructor( referenceNode, indexNode ) {
  25022. super( referenceNode, indexNode );
  25023. this.referenceNode = referenceNode;
  25024. this.isReferenceElementNode = true;
  25025. }
  25026. getNodeType() {
  25027. return this.referenceNode.uniformType;
  25028. }
  25029. generate( builder ) {
  25030. const snippet = super.generate( builder );
  25031. const arrayType = this.referenceNode.getNodeType();
  25032. const elementType = this.getNodeType();
  25033. return builder.format( snippet, arrayType, elementType );
  25034. }
  25035. }
  25036. // TODO: Extends this from ReferenceBaseNode
  25037. class ReferenceNode extends Node {
  25038. static get type() {
  25039. return 'ReferenceNode';
  25040. }
  25041. constructor( property, uniformType, object = null, count = null ) {
  25042. super();
  25043. this.property = property;
  25044. this.uniformType = uniformType;
  25045. this.object = object;
  25046. this.count = count;
  25047. this.properties = property.split( '.' );
  25048. this.reference = object;
  25049. this.node = null;
  25050. this.group = null;
  25051. this.name = null;
  25052. this.updateType = NodeUpdateType.OBJECT;
  25053. }
  25054. element( indexNode ) {
  25055. return nodeObject( new ReferenceElementNode( this, nodeObject( indexNode ) ) );
  25056. }
  25057. setGroup( group ) {
  25058. this.group = group;
  25059. return this;
  25060. }
  25061. label( name ) {
  25062. this.name = name;
  25063. return this;
  25064. }
  25065. setNodeType( uniformType ) {
  25066. let node = null;
  25067. if ( this.count !== null ) {
  25068. node = buffer( null, uniformType, this.count );
  25069. } else if ( Array.isArray( this.getValueFromReference() ) ) {
  25070. node = uniformArray( null, uniformType );
  25071. } else if ( uniformType === 'texture' ) {
  25072. node = texture( null );
  25073. } else if ( uniformType === 'cubeTexture' ) {
  25074. node = cubeTexture( null );
  25075. } else {
  25076. node = uniform( null, uniformType );
  25077. }
  25078. if ( this.group !== null ) {
  25079. node.setGroup( this.group );
  25080. }
  25081. if ( this.name !== null ) node.label( this.name );
  25082. this.node = node.getSelf();
  25083. }
  25084. getNodeType( builder ) {
  25085. if ( this.node === null ) {
  25086. this.updateReference( builder );
  25087. this.updateValue();
  25088. }
  25089. return this.node.getNodeType( builder );
  25090. }
  25091. getValueFromReference( object = this.reference ) {
  25092. const { properties } = this;
  25093. let value = object[ properties[ 0 ] ];
  25094. for ( let i = 1; i < properties.length; i ++ ) {
  25095. value = value[ properties[ i ] ];
  25096. }
  25097. return value;
  25098. }
  25099. updateReference( state ) {
  25100. this.reference = this.object !== null ? this.object : state.object;
  25101. return this.reference;
  25102. }
  25103. setup() {
  25104. this.updateValue();
  25105. return this.node;
  25106. }
  25107. update( /*frame*/ ) {
  25108. this.updateValue();
  25109. }
  25110. updateValue() {
  25111. if ( this.node === null ) this.setNodeType( this.uniformType );
  25112. const value = this.getValueFromReference();
  25113. if ( Array.isArray( value ) ) {
  25114. this.node.array = value;
  25115. } else {
  25116. this.node.value = value;
  25117. }
  25118. }
  25119. }
  25120. const reference = ( name, type, object ) => nodeObject( new ReferenceNode( name, type, object ) );
  25121. const referenceBuffer = ( name, type, count, object ) => nodeObject( new ReferenceNode( name, type, object, count ) );
  25122. class MaterialReferenceNode extends ReferenceNode {
  25123. static get type() {
  25124. return 'MaterialReferenceNode';
  25125. }
  25126. constructor( property, inputType, material = null ) {
  25127. super( property, inputType, material );
  25128. this.material = material;
  25129. //this.updateType = NodeUpdateType.RENDER;
  25130. this.isMaterialReferenceNode = true;
  25131. }
  25132. /*setNodeType( node ) {
  25133. super.setNodeType( node );
  25134. this.node.groupNode = renderGroup;
  25135. }*/
  25136. updateReference( state ) {
  25137. this.reference = this.material !== null ? this.material : state.material;
  25138. return this.reference;
  25139. }
  25140. }
  25141. const materialReference = ( name, type, material ) => nodeObject( new MaterialReferenceNode( name, type, material ) );
  25142. const tangentGeometry = /*@__PURE__*/ Fn( ( builder ) => {
  25143. if ( builder.geometry.hasAttribute( 'tangent' ) === false ) {
  25144. builder.geometry.computeTangents();
  25145. }
  25146. return attribute( 'tangent', 'vec4' );
  25147. } )();
  25148. const tangentLocal = /*@__PURE__*/ tangentGeometry.xyz.toVar( 'tangentLocal' );
  25149. const tangentView = /*@__PURE__*/ modelViewMatrix.mul( vec4( tangentLocal, 0 ) ).xyz.varying( 'v_tangentView' ).normalize().toVar( 'tangentView' );
  25150. const tangentWorld = /*@__PURE__*/ tangentView.transformDirection( cameraViewMatrix ).varying( 'v_tangentWorld' ).normalize().toVar( 'tangentWorld' );
  25151. const transformedTangentView = /*@__PURE__*/ tangentView.toVar( 'transformedTangentView' );
  25152. const transformedTangentWorld = /*@__PURE__*/ transformedTangentView.transformDirection( cameraViewMatrix ).normalize().toVar( 'transformedTangentWorld' );
  25153. const getBitangent = ( crossNormalTangent ) => crossNormalTangent.mul( tangentGeometry.w ).xyz;
  25154. const bitangentGeometry = /*@__PURE__*/ varying( getBitangent( normalGeometry.cross( tangentGeometry ) ), 'v_bitangentGeometry' ).normalize().toVar( 'bitangentGeometry' );
  25155. const bitangentLocal = /*@__PURE__*/ varying( getBitangent( normalLocal.cross( tangentLocal ) ), 'v_bitangentLocal' ).normalize().toVar( 'bitangentLocal' );
  25156. const bitangentView = /*@__PURE__*/ varying( getBitangent( normalView.cross( tangentView ) ), 'v_bitangentView' ).normalize().toVar( 'bitangentView' );
  25157. const bitangentWorld = /*@__PURE__*/ varying( getBitangent( normalWorld.cross( tangentWorld ) ), 'v_bitangentWorld' ).normalize().toVar( 'bitangentWorld' );
  25158. const transformedBitangentView = /*@__PURE__*/ getBitangent( transformedNormalView.cross( transformedTangentView ) ).normalize().toVar( 'transformedBitangentView' );
  25159. const transformedBitangentWorld = /*@__PURE__*/ transformedBitangentView.transformDirection( cameraViewMatrix ).normalize().toVar( 'transformedBitangentWorld' );
  25160. const TBNViewMatrix = /*@__PURE__*/ mat3( tangentView, bitangentView, normalView );
  25161. const parallaxDirection = /*@__PURE__*/ positionViewDirection.mul( TBNViewMatrix )/*.normalize()*/;
  25162. const parallaxUV = ( uv, scale ) => uv.sub( parallaxDirection.mul( scale ) );
  25163. const transformedBentNormalView = /*@__PURE__*/ ( () => {
  25164. // https://google.github.io/filament/Filament.md.html#lighting/imagebasedlights/anisotropy
  25165. let bentNormal = anisotropyB.cross( positionViewDirection );
  25166. bentNormal = bentNormal.cross( anisotropyB ).normalize();
  25167. bentNormal = mix( bentNormal, transformedNormalView, anisotropy.mul( roughness.oneMinus() ).oneMinus().pow2().pow2() ).normalize();
  25168. return bentNormal;
  25169. } )();
  25170. // Normal Mapping Without Precomputed Tangents
  25171. // http://www.thetenthplanet.de/archives/1180
  25172. const perturbNormal2Arb = /*@__PURE__*/ Fn( ( inputs ) => {
  25173. const { eye_pos, surf_norm, mapN, uv } = inputs;
  25174. const q0 = eye_pos.dFdx();
  25175. const q1 = eye_pos.dFdy();
  25176. const st0 = uv.dFdx();
  25177. const st1 = uv.dFdy();
  25178. const N = surf_norm; // normalized
  25179. const q1perp = q1.cross( N );
  25180. const q0perp = N.cross( q0 );
  25181. const T = q1perp.mul( st0.x ).add( q0perp.mul( st1.x ) );
  25182. const B = q1perp.mul( st0.y ).add( q0perp.mul( st1.y ) );
  25183. const det = T.dot( T ).max( B.dot( B ) );
  25184. const scale = faceDirection.mul( det.inverseSqrt() );
  25185. return add( T.mul( mapN.x, scale ), B.mul( mapN.y, scale ), N.mul( mapN.z ) ).normalize();
  25186. } );
  25187. class NormalMapNode extends TempNode {
  25188. static get type() {
  25189. return 'NormalMapNode';
  25190. }
  25191. constructor( node, scaleNode = null ) {
  25192. super( 'vec3' );
  25193. this.node = node;
  25194. this.scaleNode = scaleNode;
  25195. this.normalMapType = TangentSpaceNormalMap;
  25196. }
  25197. setup( builder ) {
  25198. const { normalMapType, scaleNode } = this;
  25199. let normalMap = this.node.mul( 2.0 ).sub( 1.0 );
  25200. if ( scaleNode !== null ) {
  25201. normalMap = vec3( normalMap.xy.mul( scaleNode ), normalMap.z );
  25202. }
  25203. let outputNode = null;
  25204. if ( normalMapType === ObjectSpaceNormalMap ) {
  25205. outputNode = transformNormalToView( normalMap );
  25206. } else if ( normalMapType === TangentSpaceNormalMap ) {
  25207. const tangent = builder.hasGeometryAttribute( 'tangent' );
  25208. if ( tangent === true ) {
  25209. outputNode = TBNViewMatrix.mul( normalMap ).normalize();
  25210. } else {
  25211. outputNode = perturbNormal2Arb( {
  25212. eye_pos: positionView,
  25213. surf_norm: normalView,
  25214. mapN: normalMap,
  25215. uv: uv()
  25216. } );
  25217. }
  25218. }
  25219. return outputNode;
  25220. }
  25221. }
  25222. const normalMap = /*@__PURE__*/ nodeProxy( NormalMapNode );
  25223. // Bump Mapping Unparametrized Surfaces on the GPU by Morten S. Mikkelsen
  25224. // https://mmikk.github.io/papers3d/mm_sfgrad_bump.pdf
  25225. const dHdxy_fwd = Fn( ( { textureNode, bumpScale } ) => {
  25226. // It's used to preserve the same TextureNode instance
  25227. const sampleTexture = ( callback ) => textureNode.cache().context( { getUV: ( texNode ) => callback( texNode.uvNode || uv() ), forceUVContext: true } );
  25228. const Hll = float( sampleTexture( ( uvNode ) => uvNode ) );
  25229. return vec2(
  25230. float( sampleTexture( ( uvNode ) => uvNode.add( uvNode.dFdx() ) ) ).sub( Hll ),
  25231. float( sampleTexture( ( uvNode ) => uvNode.add( uvNode.dFdy() ) ) ).sub( Hll )
  25232. ).mul( bumpScale );
  25233. } );
  25234. // Evaluate the derivative of the height w.r.t. screen-space using forward differencing (listing 2)
  25235. const perturbNormalArb = Fn( ( inputs ) => {
  25236. const { surf_pos, surf_norm, dHdxy } = inputs;
  25237. // normalize is done to ensure that the bump map looks the same regardless of the texture's scale
  25238. const vSigmaX = surf_pos.dFdx().normalize();
  25239. const vSigmaY = surf_pos.dFdy().normalize();
  25240. const vN = surf_norm; // normalized
  25241. const R1 = vSigmaY.cross( vN );
  25242. const R2 = vN.cross( vSigmaX );
  25243. const fDet = vSigmaX.dot( R1 ).mul( faceDirection );
  25244. const vGrad = fDet.sign().mul( dHdxy.x.mul( R1 ).add( dHdxy.y.mul( R2 ) ) );
  25245. return fDet.abs().mul( surf_norm ).sub( vGrad ).normalize();
  25246. } );
  25247. class BumpMapNode extends TempNode {
  25248. static get type() {
  25249. return 'BumpMapNode';
  25250. }
  25251. constructor( textureNode, scaleNode = null ) {
  25252. super( 'vec3' );
  25253. this.textureNode = textureNode;
  25254. this.scaleNode = scaleNode;
  25255. }
  25256. setup() {
  25257. const bumpScale = this.scaleNode !== null ? this.scaleNode : 1;
  25258. const dHdxy = dHdxy_fwd( { textureNode: this.textureNode, bumpScale } );
  25259. return perturbNormalArb( {
  25260. surf_pos: positionView,
  25261. surf_norm: normalView,
  25262. dHdxy
  25263. } );
  25264. }
  25265. }
  25266. const bumpMap = /*@__PURE__*/ nodeProxy( BumpMapNode );
  25267. const _propertyCache = new Map();
  25268. class MaterialNode extends Node {
  25269. static get type() {
  25270. return 'MaterialNode';
  25271. }
  25272. constructor( scope ) {
  25273. super();
  25274. this.scope = scope;
  25275. }
  25276. getCache( property, type ) {
  25277. let node = _propertyCache.get( property );
  25278. if ( node === undefined ) {
  25279. node = materialReference( property, type );
  25280. _propertyCache.set( property, node );
  25281. }
  25282. return node;
  25283. }
  25284. getFloat( property ) {
  25285. return this.getCache( property, 'float' );
  25286. }
  25287. getColor( property ) {
  25288. return this.getCache( property, 'color' );
  25289. }
  25290. getTexture( property ) {
  25291. return this.getCache( property === 'map' ? 'map' : property + 'Map', 'texture' );
  25292. }
  25293. setup( builder ) {
  25294. const material = builder.context.material;
  25295. const scope = this.scope;
  25296. let node = null;
  25297. if ( scope === MaterialNode.COLOR ) {
  25298. const colorNode = material.color !== undefined ? this.getColor( scope ) : vec3();
  25299. if ( material.map && material.map.isTexture === true ) {
  25300. node = colorNode.mul( this.getTexture( 'map' ) );
  25301. } else {
  25302. node = colorNode;
  25303. }
  25304. } else if ( scope === MaterialNode.OPACITY ) {
  25305. const opacityNode = this.getFloat( scope );
  25306. if ( material.alphaMap && material.alphaMap.isTexture === true ) {
  25307. node = opacityNode.mul( this.getTexture( 'alpha' ) );
  25308. } else {
  25309. node = opacityNode;
  25310. }
  25311. } else if ( scope === MaterialNode.SPECULAR_STRENGTH ) {
  25312. if ( material.specularMap && material.specularMap.isTexture === true ) {
  25313. node = this.getTexture( 'specular' ).r;
  25314. } else {
  25315. node = float( 1 );
  25316. }
  25317. } else if ( scope === MaterialNode.SPECULAR_INTENSITY ) {
  25318. const specularIntensity = this.getFloat( scope );
  25319. if ( material.specularMap ) {
  25320. node = specularIntensity.mul( this.getTexture( scope ).a );
  25321. } else {
  25322. node = specularIntensity;
  25323. }
  25324. } else if ( scope === MaterialNode.SPECULAR_COLOR ) {
  25325. const specularColorNode = this.getColor( scope );
  25326. if ( material.specularColorMap && material.specularColorMap.isTexture === true ) {
  25327. node = specularColorNode.mul( this.getTexture( scope ).rgb );
  25328. } else {
  25329. node = specularColorNode;
  25330. }
  25331. } else if ( scope === MaterialNode.ROUGHNESS ) { // TODO: cleanup similar branches
  25332. const roughnessNode = this.getFloat( scope );
  25333. if ( material.roughnessMap && material.roughnessMap.isTexture === true ) {
  25334. node = roughnessNode.mul( this.getTexture( scope ).g );
  25335. } else {
  25336. node = roughnessNode;
  25337. }
  25338. } else if ( scope === MaterialNode.METALNESS ) {
  25339. const metalnessNode = this.getFloat( scope );
  25340. if ( material.metalnessMap && material.metalnessMap.isTexture === true ) {
  25341. node = metalnessNode.mul( this.getTexture( scope ).b );
  25342. } else {
  25343. node = metalnessNode;
  25344. }
  25345. } else if ( scope === MaterialNode.EMISSIVE ) {
  25346. const emissiveIntensityNode = this.getFloat( 'emissiveIntensity' );
  25347. const emissiveNode = this.getColor( scope ).mul( emissiveIntensityNode );
  25348. if ( material.emissiveMap && material.emissiveMap.isTexture === true ) {
  25349. node = emissiveNode.mul( this.getTexture( scope ) );
  25350. } else {
  25351. node = emissiveNode;
  25352. }
  25353. } else if ( scope === MaterialNode.NORMAL ) {
  25354. if ( material.normalMap ) {
  25355. node = normalMap( this.getTexture( 'normal' ), this.getCache( 'normalScale', 'vec2' ) );
  25356. node.normalMapType = material.normalMapType;
  25357. } else if ( material.bumpMap ) {
  25358. node = bumpMap( this.getTexture( 'bump' ).r, this.getFloat( 'bumpScale' ) );
  25359. } else {
  25360. node = normalView;
  25361. }
  25362. } else if ( scope === MaterialNode.CLEARCOAT ) {
  25363. const clearcoatNode = this.getFloat( scope );
  25364. if ( material.clearcoatMap && material.clearcoatMap.isTexture === true ) {
  25365. node = clearcoatNode.mul( this.getTexture( scope ).r );
  25366. } else {
  25367. node = clearcoatNode;
  25368. }
  25369. } else if ( scope === MaterialNode.CLEARCOAT_ROUGHNESS ) {
  25370. const clearcoatRoughnessNode = this.getFloat( scope );
  25371. if ( material.clearcoatRoughnessMap && material.clearcoatRoughnessMap.isTexture === true ) {
  25372. node = clearcoatRoughnessNode.mul( this.getTexture( scope ).r );
  25373. } else {
  25374. node = clearcoatRoughnessNode;
  25375. }
  25376. } else if ( scope === MaterialNode.CLEARCOAT_NORMAL ) {
  25377. if ( material.clearcoatNormalMap ) {
  25378. node = normalMap( this.getTexture( scope ), this.getCache( scope + 'Scale', 'vec2' ) );
  25379. } else {
  25380. node = normalView;
  25381. }
  25382. } else if ( scope === MaterialNode.SHEEN ) {
  25383. const sheenNode = this.getColor( 'sheenColor' ).mul( this.getFloat( 'sheen' ) ); // Move this mul() to CPU
  25384. if ( material.sheenColorMap && material.sheenColorMap.isTexture === true ) {
  25385. node = sheenNode.mul( this.getTexture( 'sheenColor' ).rgb );
  25386. } else {
  25387. node = sheenNode;
  25388. }
  25389. } else if ( scope === MaterialNode.SHEEN_ROUGHNESS ) {
  25390. const sheenRoughnessNode = this.getFloat( scope );
  25391. if ( material.sheenRoughnessMap && material.sheenRoughnessMap.isTexture === true ) {
  25392. node = sheenRoughnessNode.mul( this.getTexture( scope ).a );
  25393. } else {
  25394. node = sheenRoughnessNode;
  25395. }
  25396. node = node.clamp( 0.07, 1.0 );
  25397. } else if ( scope === MaterialNode.ANISOTROPY ) {
  25398. if ( material.anisotropyMap && material.anisotropyMap.isTexture === true ) {
  25399. const anisotropyPolar = this.getTexture( scope );
  25400. const anisotropyMat = mat2( materialAnisotropyVector.x, materialAnisotropyVector.y, materialAnisotropyVector.y.negate(), materialAnisotropyVector.x );
  25401. node = anisotropyMat.mul( anisotropyPolar.rg.mul( 2.0 ).sub( vec2( 1.0 ) ).normalize().mul( anisotropyPolar.b ) );
  25402. } else {
  25403. node = materialAnisotropyVector;
  25404. }
  25405. } else if ( scope === MaterialNode.IRIDESCENCE_THICKNESS ) {
  25406. const iridescenceThicknessMaximum = reference( '1', 'float', material.iridescenceThicknessRange );
  25407. if ( material.iridescenceThicknessMap ) {
  25408. const iridescenceThicknessMinimum = reference( '0', 'float', material.iridescenceThicknessRange );
  25409. node = iridescenceThicknessMaximum.sub( iridescenceThicknessMinimum ).mul( this.getTexture( scope ).g ).add( iridescenceThicknessMinimum );
  25410. } else {
  25411. node = iridescenceThicknessMaximum;
  25412. }
  25413. } else if ( scope === MaterialNode.TRANSMISSION ) {
  25414. const transmissionNode = this.getFloat( scope );
  25415. if ( material.transmissionMap ) {
  25416. node = transmissionNode.mul( this.getTexture( scope ).r );
  25417. } else {
  25418. node = transmissionNode;
  25419. }
  25420. } else if ( scope === MaterialNode.THICKNESS ) {
  25421. const thicknessNode = this.getFloat( scope );
  25422. if ( material.thicknessMap ) {
  25423. node = thicknessNode.mul( this.getTexture( scope ).g );
  25424. } else {
  25425. node = thicknessNode;
  25426. }
  25427. } else if ( scope === MaterialNode.IOR ) {
  25428. node = this.getFloat( scope );
  25429. } else if ( scope === MaterialNode.LIGHT_MAP ) {
  25430. node = this.getTexture( scope ).rgb.mul( this.getFloat( 'lightMapIntensity' ) );
  25431. } else if ( scope === MaterialNode.AO_MAP ) {
  25432. node = this.getTexture( scope ).r.sub( 1.0 ).mul( this.getFloat( 'aoMapIntensity' ) ).add( 1.0 );
  25433. } else {
  25434. const outputType = this.getNodeType( builder );
  25435. node = this.getCache( scope, outputType );
  25436. }
  25437. return node;
  25438. }
  25439. }
  25440. MaterialNode.ALPHA_TEST = 'alphaTest';
  25441. MaterialNode.COLOR = 'color';
  25442. MaterialNode.OPACITY = 'opacity';
  25443. MaterialNode.SHININESS = 'shininess';
  25444. MaterialNode.SPECULAR = 'specular';
  25445. MaterialNode.SPECULAR_STRENGTH = 'specularStrength';
  25446. MaterialNode.SPECULAR_INTENSITY = 'specularIntensity';
  25447. MaterialNode.SPECULAR_COLOR = 'specularColor';
  25448. MaterialNode.REFLECTIVITY = 'reflectivity';
  25449. MaterialNode.ROUGHNESS = 'roughness';
  25450. MaterialNode.METALNESS = 'metalness';
  25451. MaterialNode.NORMAL = 'normal';
  25452. MaterialNode.CLEARCOAT = 'clearcoat';
  25453. MaterialNode.CLEARCOAT_ROUGHNESS = 'clearcoatRoughness';
  25454. MaterialNode.CLEARCOAT_NORMAL = 'clearcoatNormal';
  25455. MaterialNode.EMISSIVE = 'emissive';
  25456. MaterialNode.ROTATION = 'rotation';
  25457. MaterialNode.SHEEN = 'sheen';
  25458. MaterialNode.SHEEN_ROUGHNESS = 'sheenRoughness';
  25459. MaterialNode.ANISOTROPY = 'anisotropy';
  25460. MaterialNode.IRIDESCENCE = 'iridescence';
  25461. MaterialNode.IRIDESCENCE_IOR = 'iridescenceIOR';
  25462. MaterialNode.IRIDESCENCE_THICKNESS = 'iridescenceThickness';
  25463. MaterialNode.IOR = 'ior';
  25464. MaterialNode.TRANSMISSION = 'transmission';
  25465. MaterialNode.THICKNESS = 'thickness';
  25466. MaterialNode.ATTENUATION_DISTANCE = 'attenuationDistance';
  25467. MaterialNode.ATTENUATION_COLOR = 'attenuationColor';
  25468. MaterialNode.LINE_SCALE = 'scale';
  25469. MaterialNode.LINE_DASH_SIZE = 'dashSize';
  25470. MaterialNode.LINE_GAP_SIZE = 'gapSize';
  25471. MaterialNode.LINE_WIDTH = 'linewidth';
  25472. MaterialNode.LINE_DASH_OFFSET = 'dashOffset';
  25473. MaterialNode.POINT_WIDTH = 'pointWidth';
  25474. MaterialNode.DISPERSION = 'dispersion';
  25475. MaterialNode.LIGHT_MAP = 'light';
  25476. MaterialNode.AO_MAP = 'ao';
  25477. const materialAlphaTest = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ALPHA_TEST );
  25478. const materialColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.COLOR );
  25479. const materialShininess = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHININESS );
  25480. const materialEmissive = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.EMISSIVE );
  25481. const materialOpacity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.OPACITY );
  25482. const materialSpecular = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR );
  25483. const materialSpecularIntensity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_INTENSITY );
  25484. const materialSpecularColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_COLOR );
  25485. const materialSpecularStrength = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_STRENGTH );
  25486. const materialReflectivity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.REFLECTIVITY );
  25487. const materialRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ROUGHNESS );
  25488. const materialMetalness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.METALNESS );
  25489. const materialNormal = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.NORMAL ).context( { getUV: null } );
  25490. const materialClearcoat = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT );
  25491. const materialClearcoatRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT_ROUGHNESS );
  25492. const materialClearcoatNormal = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT_NORMAL ).context( { getUV: null } );
  25493. const materialRotation = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ROTATION );
  25494. const materialSheen = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHEEN );
  25495. const materialSheenRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHEEN_ROUGHNESS );
  25496. const materialAnisotropy = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ANISOTROPY );
  25497. const materialIridescence = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE );
  25498. const materialIridescenceIOR = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE_IOR );
  25499. const materialIridescenceThickness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE_THICKNESS );
  25500. const materialTransmission = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.TRANSMISSION );
  25501. const materialThickness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.THICKNESS );
  25502. const materialIOR = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IOR );
  25503. const materialAttenuationDistance = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ATTENUATION_DISTANCE );
  25504. const materialAttenuationColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ATTENUATION_COLOR );
  25505. const materialLineScale = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_SCALE );
  25506. const materialLineDashSize = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_DASH_SIZE );
  25507. const materialLineGapSize = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_GAP_SIZE );
  25508. const materialLineWidth = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_WIDTH );
  25509. const materialLineDashOffset = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_DASH_OFFSET );
  25510. const materialPointWidth = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.POINT_WIDTH );
  25511. const materialDispersion = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.DISPERSION );
  25512. const materialLightMap = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LIGHT_MAP );
  25513. const materialAOMap = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.AO_MAP );
  25514. const materialAnisotropyVector = /*@__PURE__*/ uniform( new Vector2() ).onReference( function ( frame ) {
  25515. return frame.material;
  25516. } ).onRenderUpdate( function ( { material } ) {
  25517. this.value.set( material.anisotropy * Math.cos( material.anisotropyRotation ), material.anisotropy * Math.sin( material.anisotropyRotation ) );
  25518. } );
  25519. class ModelViewProjectionNode extends TempNode {
  25520. static get type() {
  25521. return 'ModelViewProjectionNode';
  25522. }
  25523. constructor( positionNode = null ) {
  25524. super( 'vec4' );
  25525. this.positionNode = positionNode;
  25526. }
  25527. setup( builder ) {
  25528. if ( builder.shaderStage === 'fragment' ) {
  25529. return varying( builder.context.mvp );
  25530. }
  25531. const position = this.positionNode || positionLocal;
  25532. const viewMatrix = builder.renderer.nodes.modelViewMatrix || modelViewMatrix;
  25533. return cameraProjectionMatrix.mul( viewMatrix ).mul( position );
  25534. }
  25535. }
  25536. const modelViewProjection = /*@__PURE__*/ nodeProxy( ModelViewProjectionNode );
  25537. class IndexNode extends Node {
  25538. static get type() {
  25539. return 'IndexNode';
  25540. }
  25541. constructor( scope ) {
  25542. super( 'uint' );
  25543. this.scope = scope;
  25544. this.isInstanceIndexNode = true;
  25545. }
  25546. generate( builder ) {
  25547. const nodeType = this.getNodeType( builder );
  25548. const scope = this.scope;
  25549. let propertyName;
  25550. if ( scope === IndexNode.VERTEX ) {
  25551. // The index of a vertex within a mesh.
  25552. propertyName = builder.getVertexIndex();
  25553. } else if ( scope === IndexNode.INSTANCE ) {
  25554. // The index of either a mesh instance or an invocation of a compute shader.
  25555. propertyName = builder.getInstanceIndex();
  25556. } else if ( scope === IndexNode.DRAW ) {
  25557. // The index of a draw call.
  25558. propertyName = builder.getDrawIndex();
  25559. } else if ( scope === IndexNode.INVOCATION_LOCAL ) {
  25560. // The index of a compute invocation within the scope of a workgroup load.
  25561. propertyName = builder.getInvocationLocalIndex();
  25562. } else if ( scope === IndexNode.INVOCATION_SUBGROUP ) {
  25563. // The index of a compute invocation within the scope of a subgroup.
  25564. propertyName = builder.getInvocationSubgroupIndex();
  25565. } else if ( scope === IndexNode.SUBGROUP ) {
  25566. // The index of the subgroup the current compute invocation belongs to.
  25567. propertyName = builder.getSubgroupIndex();
  25568. } else {
  25569. throw new Error( 'THREE.IndexNode: Unknown scope: ' + scope );
  25570. }
  25571. let output;
  25572. if ( builder.shaderStage === 'vertex' || builder.shaderStage === 'compute' ) {
  25573. output = propertyName;
  25574. } else {
  25575. const nodeVarying = varying( this );
  25576. output = nodeVarying.build( builder, nodeType );
  25577. }
  25578. return output;
  25579. }
  25580. }
  25581. IndexNode.VERTEX = 'vertex';
  25582. IndexNode.INSTANCE = 'instance';
  25583. IndexNode.SUBGROUP = 'subgroup';
  25584. IndexNode.INVOCATION_LOCAL = 'invocationLocal';
  25585. IndexNode.INVOCATION_SUBGROUP = 'invocationSubgroup';
  25586. IndexNode.DRAW = 'draw';
  25587. const vertexIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.VERTEX );
  25588. const instanceIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INSTANCE );
  25589. const subgroupIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.SUBGROUP );
  25590. const invocationSubgroupIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INVOCATION_SUBGROUP );
  25591. const invocationLocalIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INVOCATION_LOCAL );
  25592. const drawIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.DRAW );
  25593. class InstanceNode extends Node {
  25594. static get type() {
  25595. return 'InstanceNode';
  25596. }
  25597. constructor( instanceMesh ) {
  25598. super( 'void' );
  25599. this.instanceMesh = instanceMesh;
  25600. this.instanceMatrixNode = null;
  25601. this.instanceColorNode = null;
  25602. this.updateType = NodeUpdateType.FRAME;
  25603. this.buffer = null;
  25604. this.bufferColor = null;
  25605. }
  25606. setup( builder ) {
  25607. let instanceMatrixNode = this.instanceMatrixNode;
  25608. let instanceColorNode = this.instanceColorNode;
  25609. const instanceMesh = this.instanceMesh;
  25610. if ( instanceMatrixNode === null ) {
  25611. const instanceAttribute = instanceMesh.instanceMatrix;
  25612. // Both WebGPU and WebGL backends have UBO max limited to 64kb. Matrix count number bigger than 1000 ( 16 * 4 * 1000 = 64kb ) will fallback to attribute.
  25613. if ( instanceMesh.count <= 1000 ) {
  25614. instanceMatrixNode = buffer( instanceAttribute.array, 'mat4', Math.max( instanceMesh.count, 1 ) ).element( instanceIndex );
  25615. } else {
  25616. const buffer = new InstancedInterleavedBuffer( instanceAttribute.array, 16, 1 );
  25617. this.buffer = buffer;
  25618. const bufferFn = instanceAttribute.usage === DynamicDrawUsage ? instancedDynamicBufferAttribute : instancedBufferAttribute;
  25619. const instanceBuffers = [
  25620. // F.Signature -> bufferAttribute( array, type, stride, offset )
  25621. bufferFn( buffer, 'vec4', 16, 0 ),
  25622. bufferFn( buffer, 'vec4', 16, 4 ),
  25623. bufferFn( buffer, 'vec4', 16, 8 ),
  25624. bufferFn( buffer, 'vec4', 16, 12 )
  25625. ];
  25626. instanceMatrixNode = mat4( ...instanceBuffers );
  25627. }
  25628. this.instanceMatrixNode = instanceMatrixNode;
  25629. }
  25630. const instanceColorAttribute = instanceMesh.instanceColor;
  25631. if ( instanceColorAttribute && instanceColorNode === null ) {
  25632. const buffer = new InstancedBufferAttribute( instanceColorAttribute.array, 3 );
  25633. const bufferFn = instanceColorAttribute.usage === DynamicDrawUsage ? instancedDynamicBufferAttribute : instancedBufferAttribute;
  25634. this.bufferColor = buffer;
  25635. instanceColorNode = vec3( bufferFn( buffer, 'vec3', 3, 0 ) );
  25636. this.instanceColorNode = instanceColorNode;
  25637. }
  25638. // POSITION
  25639. const instancePosition = instanceMatrixNode.mul( positionLocal ).xyz;
  25640. positionLocal.assign( instancePosition );
  25641. // NORMAL
  25642. if ( builder.hasGeometryAttribute( 'normal' ) ) {
  25643. const instanceNormal = transformNormal( normalLocal, instanceMatrixNode );
  25644. // ASSIGNS
  25645. normalLocal.assign( instanceNormal );
  25646. }
  25647. // COLOR
  25648. if ( this.instanceColorNode !== null ) {
  25649. varyingProperty( 'vec3', 'vInstanceColor' ).assign( this.instanceColorNode );
  25650. }
  25651. }
  25652. update( /*frame*/ ) {
  25653. if ( this.instanceMesh.instanceMatrix.usage !== DynamicDrawUsage && this.buffer != null && this.instanceMesh.instanceMatrix.version !== this.buffer.version ) {
  25654. this.buffer.version = this.instanceMesh.instanceMatrix.version;
  25655. }
  25656. if ( this.instanceMesh.instanceColor && this.instanceMesh.instanceColor.usage !== DynamicDrawUsage && this.bufferColor != null && this.instanceMesh.instanceColor.version !== this.bufferColor.version ) {
  25657. this.bufferColor.version = this.instanceMesh.instanceColor.version;
  25658. }
  25659. }
  25660. }
  25661. const instance = /*@__PURE__*/ nodeProxy( InstanceNode );
  25662. class BatchNode extends Node {
  25663. static get type() {
  25664. return 'BatchNode';
  25665. }
  25666. constructor( batchMesh ) {
  25667. super( 'void' );
  25668. this.batchMesh = batchMesh;
  25669. this.batchingIdNode = null;
  25670. }
  25671. setup( builder ) {
  25672. // POSITION
  25673. if ( this.batchingIdNode === null ) {
  25674. if ( builder.getDrawIndex() === null ) {
  25675. this.batchingIdNode = instanceIndex;
  25676. } else {
  25677. this.batchingIdNode = drawIndex;
  25678. }
  25679. }
  25680. const getIndirectIndex = Fn( ( [ id ] ) => {
  25681. const size = textureSize( textureLoad( this.batchMesh._indirectTexture ), 0 );
  25682. const x = int( id ).modInt( int( size ) );
  25683. const y = int( id ).div( int( size ) );
  25684. return textureLoad( this.batchMesh._indirectTexture, ivec2( x, y ) ).x;
  25685. } ).setLayout( {
  25686. name: 'getIndirectIndex',
  25687. type: 'uint',
  25688. inputs: [
  25689. { name: 'id', type: 'int' }
  25690. ]
  25691. } );
  25692. const indirectId = getIndirectIndex( int( this.batchingIdNode ) );
  25693. const matricesTexture = this.batchMesh._matricesTexture;
  25694. const size = textureSize( textureLoad( matricesTexture ), 0 );
  25695. const j = float( indirectId ).mul( 4 ).toInt().toVar();
  25696. const x = j.modInt( size );
  25697. const y = j.div( int( size ) );
  25698. const batchingMatrix = mat4(
  25699. textureLoad( matricesTexture, ivec2( x, y ) ),
  25700. textureLoad( matricesTexture, ivec2( x.add( 1 ), y ) ),
  25701. textureLoad( matricesTexture, ivec2( x.add( 2 ), y ) ),
  25702. textureLoad( matricesTexture, ivec2( x.add( 3 ), y ) )
  25703. );
  25704. const colorsTexture = this.batchMesh._colorsTexture;
  25705. if ( colorsTexture !== null ) {
  25706. const getBatchingColor = Fn( ( [ id ] ) => {
  25707. const size = textureSize( textureLoad( colorsTexture ), 0 ).x;
  25708. const j = id;
  25709. const x = j.modInt( size );
  25710. const y = j.div( size );
  25711. return textureLoad( colorsTexture, ivec2( x, y ) ).rgb;
  25712. } ).setLayout( {
  25713. name: 'getBatchingColor',
  25714. type: 'vec3',
  25715. inputs: [
  25716. { name: 'id', type: 'int' }
  25717. ]
  25718. } );
  25719. const color = getBatchingColor( indirectId );
  25720. varyingProperty( 'vec3', 'vBatchColor' ).assign( color );
  25721. }
  25722. const bm = mat3( batchingMatrix );
  25723. positionLocal.assign( batchingMatrix.mul( positionLocal ) );
  25724. const transformedNormal = normalLocal.div( vec3( bm[ 0 ].dot( bm[ 0 ] ), bm[ 1 ].dot( bm[ 1 ] ), bm[ 2 ].dot( bm[ 2 ] ) ) );
  25725. const batchingNormal = bm.mul( transformedNormal ).xyz;
  25726. normalLocal.assign( batchingNormal );
  25727. if ( builder.hasGeometryAttribute( 'tangent' ) ) {
  25728. tangentLocal.mulAssign( bm );
  25729. }
  25730. }
  25731. }
  25732. const batch = /*@__PURE__*/ nodeProxy( BatchNode );
  25733. const _frameId = new WeakMap();
  25734. class SkinningNode extends Node {
  25735. static get type() {
  25736. return 'SkinningNode';
  25737. }
  25738. constructor( skinnedMesh, useReference = false ) {
  25739. super( 'void' );
  25740. this.skinnedMesh = skinnedMesh;
  25741. this.useReference = useReference;
  25742. this.updateType = NodeUpdateType.OBJECT;
  25743. //
  25744. this.skinIndexNode = attribute( 'skinIndex', 'uvec4' );
  25745. this.skinWeightNode = attribute( 'skinWeight', 'vec4' );
  25746. let bindMatrixNode, bindMatrixInverseNode, boneMatricesNode;
  25747. if ( useReference ) {
  25748. bindMatrixNode = reference( 'bindMatrix', 'mat4' );
  25749. bindMatrixInverseNode = reference( 'bindMatrixInverse', 'mat4' );
  25750. boneMatricesNode = referenceBuffer( 'skeleton.boneMatrices', 'mat4', skinnedMesh.skeleton.bones.length );
  25751. } else {
  25752. bindMatrixNode = uniform( skinnedMesh.bindMatrix, 'mat4' );
  25753. bindMatrixInverseNode = uniform( skinnedMesh.bindMatrixInverse, 'mat4' );
  25754. boneMatricesNode = buffer( skinnedMesh.skeleton.boneMatrices, 'mat4', skinnedMesh.skeleton.bones.length );
  25755. }
  25756. this.bindMatrixNode = bindMatrixNode;
  25757. this.bindMatrixInverseNode = bindMatrixInverseNode;
  25758. this.boneMatricesNode = boneMatricesNode;
  25759. this.previousBoneMatricesNode = null;
  25760. }
  25761. getSkinnedPosition( boneMatrices = this.boneMatricesNode, position = positionLocal ) {
  25762. const { skinIndexNode, skinWeightNode, bindMatrixNode, bindMatrixInverseNode } = this;
  25763. const boneMatX = boneMatrices.element( skinIndexNode.x );
  25764. const boneMatY = boneMatrices.element( skinIndexNode.y );
  25765. const boneMatZ = boneMatrices.element( skinIndexNode.z );
  25766. const boneMatW = boneMatrices.element( skinIndexNode.w );
  25767. // POSITION
  25768. const skinVertex = bindMatrixNode.mul( position );
  25769. const skinned = add(
  25770. boneMatX.mul( skinWeightNode.x ).mul( skinVertex ),
  25771. boneMatY.mul( skinWeightNode.y ).mul( skinVertex ),
  25772. boneMatZ.mul( skinWeightNode.z ).mul( skinVertex ),
  25773. boneMatW.mul( skinWeightNode.w ).mul( skinVertex )
  25774. );
  25775. return bindMatrixInverseNode.mul( skinned ).xyz;
  25776. }
  25777. getSkinnedNormal( boneMatrices = this.boneMatricesNode, normal = normalLocal ) {
  25778. const { skinIndexNode, skinWeightNode, bindMatrixNode, bindMatrixInverseNode } = this;
  25779. const boneMatX = boneMatrices.element( skinIndexNode.x );
  25780. const boneMatY = boneMatrices.element( skinIndexNode.y );
  25781. const boneMatZ = boneMatrices.element( skinIndexNode.z );
  25782. const boneMatW = boneMatrices.element( skinIndexNode.w );
  25783. // NORMAL
  25784. let skinMatrix = add(
  25785. skinWeightNode.x.mul( boneMatX ),
  25786. skinWeightNode.y.mul( boneMatY ),
  25787. skinWeightNode.z.mul( boneMatZ ),
  25788. skinWeightNode.w.mul( boneMatW )
  25789. );
  25790. skinMatrix = bindMatrixInverseNode.mul( skinMatrix ).mul( bindMatrixNode );
  25791. return skinMatrix.transformDirection( normal ).xyz;
  25792. }
  25793. getPreviousSkinnedPosition( builder ) {
  25794. const skinnedMesh = builder.object;
  25795. if ( this.previousBoneMatricesNode === null ) {
  25796. skinnedMesh.skeleton.previousBoneMatrices = new Float32Array( skinnedMesh.skeleton.boneMatrices );
  25797. this.previousBoneMatricesNode = referenceBuffer( 'skeleton.previousBoneMatrices', 'mat4', skinnedMesh.skeleton.bones.length );
  25798. }
  25799. return this.getSkinnedPosition( this.previousBoneMatricesNode, positionPrevious );
  25800. }
  25801. needsPreviousBoneMatrices( builder ) {
  25802. const mrt = builder.renderer.getMRT();
  25803. return mrt && mrt.has( 'velocity' );
  25804. }
  25805. setup( builder ) {
  25806. if ( this.needsPreviousBoneMatrices( builder ) ) {
  25807. positionPrevious.assign( this.getPreviousSkinnedPosition( builder ) );
  25808. }
  25809. const skinPosition = this.getSkinnedPosition();
  25810. positionLocal.assign( skinPosition );
  25811. if ( builder.hasGeometryAttribute( 'normal' ) ) {
  25812. const skinNormal = this.getSkinnedNormal();
  25813. normalLocal.assign( skinNormal );
  25814. if ( builder.hasGeometryAttribute( 'tangent' ) ) {
  25815. tangentLocal.assign( skinNormal );
  25816. }
  25817. }
  25818. }
  25819. generate( builder, output ) {
  25820. if ( output !== 'void' ) {
  25821. return positionLocal.build( builder, output );
  25822. }
  25823. }
  25824. update( frame ) {
  25825. const object = this.useReference ? frame.object : this.skinnedMesh;
  25826. const skeleton = object.skeleton;
  25827. if ( _frameId.get( skeleton ) === frame.frameId ) return;
  25828. _frameId.set( skeleton, frame.frameId );
  25829. if ( this.previousBoneMatricesNode !== null ) skeleton.previousBoneMatrices.set( skeleton.boneMatrices );
  25830. skeleton.update();
  25831. }
  25832. }
  25833. const skinning = ( skinnedMesh ) => nodeObject( new SkinningNode( skinnedMesh ) );
  25834. const skinningReference = ( skinnedMesh ) => nodeObject( new SkinningNode( skinnedMesh, true ) );
  25835. class LoopNode extends Node {
  25836. static get type() {
  25837. return 'LoopNode';
  25838. }
  25839. constructor( params = [] ) {
  25840. super();
  25841. this.params = params;
  25842. }
  25843. getVarName( index ) {
  25844. return String.fromCharCode( 'i'.charCodeAt() + index );
  25845. }
  25846. getProperties( builder ) {
  25847. const properties = builder.getNodeProperties( this );
  25848. if ( properties.stackNode !== undefined ) return properties;
  25849. //
  25850. const inputs = {};
  25851. for ( let i = 0, l = this.params.length - 1; i < l; i ++ ) {
  25852. const param = this.params[ i ];
  25853. const name = ( param.isNode !== true && param.name ) || this.getVarName( i );
  25854. const type = ( param.isNode !== true && param.type ) || 'int';
  25855. inputs[ name ] = expression( name, type );
  25856. }
  25857. const stack = builder.addStack(); // TODO: cache() it
  25858. properties.returnsNode = this.params[ this.params.length - 1 ]( inputs, stack, builder );
  25859. properties.stackNode = stack;
  25860. builder.removeStack();
  25861. return properties;
  25862. }
  25863. getNodeType( builder ) {
  25864. const { returnsNode } = this.getProperties( builder );
  25865. return returnsNode ? returnsNode.getNodeType( builder ) : 'void';
  25866. }
  25867. setup( builder ) {
  25868. // setup properties
  25869. this.getProperties( builder );
  25870. }
  25871. generate( builder ) {
  25872. const properties = this.getProperties( builder );
  25873. const params = this.params;
  25874. const stackNode = properties.stackNode;
  25875. for ( let i = 0, l = params.length - 1; i < l; i ++ ) {
  25876. const param = params[ i ];
  25877. let start = null, end = null, name = null, type = null, condition = null, update = null;
  25878. if ( param.isNode ) {
  25879. type = 'int';
  25880. name = this.getVarName( i );
  25881. start = '0';
  25882. end = param.build( builder, type );
  25883. condition = '<';
  25884. } else {
  25885. type = param.type || 'int';
  25886. name = param.name || this.getVarName( i );
  25887. start = param.start;
  25888. end = param.end;
  25889. condition = param.condition;
  25890. update = param.update;
  25891. if ( typeof start === 'number' ) start = builder.generateConst( type, start );
  25892. else if ( start && start.isNode ) start = start.build( builder, type );
  25893. if ( typeof end === 'number' ) end = builder.generateConst( type, end );
  25894. else if ( end && end.isNode ) end = end.build( builder, type );
  25895. if ( start !== undefined && end === undefined ) {
  25896. start = start + ' - 1';
  25897. end = '0';
  25898. condition = '>=';
  25899. } else if ( end !== undefined && start === undefined ) {
  25900. start = '0';
  25901. condition = '<';
  25902. }
  25903. if ( condition === undefined ) {
  25904. if ( Number( start ) > Number( end ) ) {
  25905. condition = '>=';
  25906. } else {
  25907. condition = '<';
  25908. }
  25909. }
  25910. }
  25911. const internalParam = { start, end, condition };
  25912. //
  25913. const startSnippet = internalParam.start;
  25914. const endSnippet = internalParam.end;
  25915. let declarationSnippet = '';
  25916. let conditionalSnippet = '';
  25917. let updateSnippet = '';
  25918. if ( ! update ) {
  25919. if ( type === 'int' || type === 'uint' ) {
  25920. if ( condition.includes( '<' ) ) update = '++';
  25921. else update = '--';
  25922. } else {
  25923. if ( condition.includes( '<' ) ) update = '+= 1.';
  25924. else update = '-= 1.';
  25925. }
  25926. }
  25927. declarationSnippet += builder.getVar( type, name ) + ' = ' + startSnippet;
  25928. conditionalSnippet += name + ' ' + condition + ' ' + endSnippet;
  25929. updateSnippet += name + ' ' + update;
  25930. const forSnippet = `for ( ${ declarationSnippet }; ${ conditionalSnippet }; ${ updateSnippet } )`;
  25931. builder.addFlowCode( ( i === 0 ? '\n' : '' ) + builder.tab + forSnippet + ' {\n\n' ).addFlowTab();
  25932. }
  25933. const stackSnippet = stackNode.build( builder, 'void' );
  25934. const returnsSnippet = properties.returnsNode ? properties.returnsNode.build( builder ) : '';
  25935. builder.removeFlowTab().addFlowCode( '\n' + builder.tab + stackSnippet );
  25936. for ( let i = 0, l = this.params.length - 1; i < l; i ++ ) {
  25937. builder.addFlowCode( ( i === 0 ? '' : builder.tab ) + '}\n\n' ).removeFlowTab();
  25938. }
  25939. builder.addFlowTab();
  25940. return returnsSnippet;
  25941. }
  25942. }
  25943. const Loop = ( ...params ) => nodeObject( new LoopNode( nodeArray( params, 'int' ) ) ).append();
  25944. const Continue = () => expression( 'continue' ).append();
  25945. const Break = () => expression( 'break' ).append();
  25946. //
  25947. const loop = ( ...params ) => { // @deprecated, r168
  25948. console.warn( 'TSL.LoopNode: loop() has been renamed to Loop().' );
  25949. return Loop( ...params );
  25950. };
  25951. const _morphTextures = /*@__PURE__*/ new WeakMap();
  25952. const _morphVec4 = /*@__PURE__*/ new Vector4();
  25953. const getMorph = /*@__PURE__*/ Fn( ( { bufferMap, influence, stride, width, depth, offset } ) => {
  25954. const texelIndex = int( vertexIndex ).mul( stride ).add( offset );
  25955. const y = texelIndex.div( width );
  25956. const x = texelIndex.sub( y.mul( width ) );
  25957. const bufferAttrib = textureLoad( bufferMap, ivec2( x, y ) ).depth( depth );
  25958. return bufferAttrib.mul( influence );
  25959. } );
  25960. function getEntry( geometry ) {
  25961. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  25962. const hasMorphNormals = geometry.morphAttributes.normal !== undefined;
  25963. const hasMorphColors = geometry.morphAttributes.color !== undefined;
  25964. // instead of using attributes, the WebGL 2 code path encodes morph targets
  25965. // into an array of data textures. Each layer represents a single morph target.
  25966. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  25967. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  25968. let entry = _morphTextures.get( geometry );
  25969. if ( entry === undefined || entry.count !== morphTargetsCount ) {
  25970. if ( entry !== undefined ) entry.texture.dispose();
  25971. const morphTargets = geometry.morphAttributes.position || [];
  25972. const morphNormals = geometry.morphAttributes.normal || [];
  25973. const morphColors = geometry.morphAttributes.color || [];
  25974. let vertexDataCount = 0;
  25975. if ( hasMorphPosition === true ) vertexDataCount = 1;
  25976. if ( hasMorphNormals === true ) vertexDataCount = 2;
  25977. if ( hasMorphColors === true ) vertexDataCount = 3;
  25978. let width = geometry.attributes.position.count * vertexDataCount;
  25979. let height = 1;
  25980. const maxTextureSize = 4096; // @TODO: Use 'capabilities.maxTextureSize'
  25981. if ( width > maxTextureSize ) {
  25982. height = Math.ceil( width / maxTextureSize );
  25983. width = maxTextureSize;
  25984. }
  25985. const buffer = new Float32Array( width * height * 4 * morphTargetsCount );
  25986. const bufferTexture = new DataArrayTexture( buffer, width, height, morphTargetsCount );
  25987. bufferTexture.type = FloatType;
  25988. bufferTexture.needsUpdate = true;
  25989. // fill buffer
  25990. const vertexDataStride = vertexDataCount * 4;
  25991. for ( let i = 0; i < morphTargetsCount; i ++ ) {
  25992. const morphTarget = morphTargets[ i ];
  25993. const morphNormal = morphNormals[ i ];
  25994. const morphColor = morphColors[ i ];
  25995. const offset = width * height * 4 * i;
  25996. for ( let j = 0; j < morphTarget.count; j ++ ) {
  25997. const stride = j * vertexDataStride;
  25998. if ( hasMorphPosition === true ) {
  25999. _morphVec4.fromBufferAttribute( morphTarget, j );
  26000. buffer[ offset + stride + 0 ] = _morphVec4.x;
  26001. buffer[ offset + stride + 1 ] = _morphVec4.y;
  26002. buffer[ offset + stride + 2 ] = _morphVec4.z;
  26003. buffer[ offset + stride + 3 ] = 0;
  26004. }
  26005. if ( hasMorphNormals === true ) {
  26006. _morphVec4.fromBufferAttribute( morphNormal, j );
  26007. buffer[ offset + stride + 4 ] = _morphVec4.x;
  26008. buffer[ offset + stride + 5 ] = _morphVec4.y;
  26009. buffer[ offset + stride + 6 ] = _morphVec4.z;
  26010. buffer[ offset + stride + 7 ] = 0;
  26011. }
  26012. if ( hasMorphColors === true ) {
  26013. _morphVec4.fromBufferAttribute( morphColor, j );
  26014. buffer[ offset + stride + 8 ] = _morphVec4.x;
  26015. buffer[ offset + stride + 9 ] = _morphVec4.y;
  26016. buffer[ offset + stride + 10 ] = _morphVec4.z;
  26017. buffer[ offset + stride + 11 ] = ( morphColor.itemSize === 4 ) ? _morphVec4.w : 1;
  26018. }
  26019. }
  26020. }
  26021. entry = {
  26022. count: morphTargetsCount,
  26023. texture: bufferTexture,
  26024. stride: vertexDataCount,
  26025. size: new Vector2( width, height )
  26026. };
  26027. _morphTextures.set( geometry, entry );
  26028. function disposeTexture() {
  26029. bufferTexture.dispose();
  26030. _morphTextures.delete( geometry );
  26031. geometry.removeEventListener( 'dispose', disposeTexture );
  26032. }
  26033. geometry.addEventListener( 'dispose', disposeTexture );
  26034. }
  26035. return entry;
  26036. }
  26037. class MorphNode extends Node {
  26038. static get type() {
  26039. return 'MorphNode';
  26040. }
  26041. constructor( mesh ) {
  26042. super( 'void' );
  26043. this.mesh = mesh;
  26044. this.morphBaseInfluence = uniform( 1 );
  26045. this.updateType = NodeUpdateType.OBJECT;
  26046. }
  26047. setup( builder ) {
  26048. const { geometry } = builder;
  26049. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  26050. const hasMorphNormals = geometry.hasAttribute( 'normal' ) && geometry.morphAttributes.normal !== undefined;
  26051. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  26052. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  26053. // nodes
  26054. const { texture: bufferMap, stride, size } = getEntry( geometry );
  26055. if ( hasMorphPosition === true ) positionLocal.mulAssign( this.morphBaseInfluence );
  26056. if ( hasMorphNormals === true ) normalLocal.mulAssign( this.morphBaseInfluence );
  26057. const width = int( size.width );
  26058. Loop( morphTargetsCount, ( { i } ) => {
  26059. const influence = float( 0 ).toVar();
  26060. if ( this.mesh.count > 1 && ( this.mesh.morphTexture !== null && this.mesh.morphTexture !== undefined ) ) {
  26061. influence.assign( textureLoad( this.mesh.morphTexture, ivec2( int( i ).add( 1 ), int( instanceIndex ) ) ).r );
  26062. } else {
  26063. influence.assign( reference( 'morphTargetInfluences', 'float' ).element( i ).toVar() );
  26064. }
  26065. if ( hasMorphPosition === true ) {
  26066. positionLocal.addAssign( getMorph( {
  26067. bufferMap,
  26068. influence,
  26069. stride,
  26070. width,
  26071. depth: i,
  26072. offset: int( 0 )
  26073. } ) );
  26074. }
  26075. if ( hasMorphNormals === true ) {
  26076. normalLocal.addAssign( getMorph( {
  26077. bufferMap,
  26078. influence,
  26079. stride,
  26080. width,
  26081. depth: i,
  26082. offset: int( 1 )
  26083. } ) );
  26084. }
  26085. } );
  26086. }
  26087. update() {
  26088. const morphBaseInfluence = this.morphBaseInfluence;
  26089. if ( this.mesh.geometry.morphTargetsRelative ) {
  26090. morphBaseInfluence.value = 1;
  26091. } else {
  26092. morphBaseInfluence.value = 1 - this.mesh.morphTargetInfluences.reduce( ( a, b ) => a + b, 0 );
  26093. }
  26094. }
  26095. }
  26096. const morphReference = /*@__PURE__*/ nodeProxy( MorphNode );
  26097. const sortLights = ( lights ) => {
  26098. return lights.sort( ( a, b ) => a.id - b.id );
  26099. };
  26100. const getLightNodeById = ( id, lightNodes ) => {
  26101. for ( const lightNode of lightNodes ) {
  26102. if ( lightNode.isAnalyticLightNode && lightNode.light.id === id ) {
  26103. return lightNode;
  26104. }
  26105. }
  26106. return null;
  26107. };
  26108. const _lightsNodeRef = /*@__PURE__*/ new WeakMap();
  26109. class LightsNode extends Node {
  26110. static get type() {
  26111. return 'LightsNode';
  26112. }
  26113. constructor( lights = [] ) {
  26114. super( 'vec3' );
  26115. this.totalDiffuseNode = vec3().toVar( 'totalDiffuse' );
  26116. this.totalSpecularNode = vec3().toVar( 'totalSpecular' );
  26117. this.outgoingLightNode = vec3().toVar( 'outgoingLight' );
  26118. this._lights = lights;
  26119. this._lightNodes = null;
  26120. this._lightNodesHash = null;
  26121. this.global = true;
  26122. }
  26123. getHash( builder ) {
  26124. if ( this._lightNodesHash === null ) {
  26125. if ( this._lightNodes === null ) this.setupLightsNode( builder );
  26126. const hash = [];
  26127. for ( const lightNode of this._lightNodes ) {
  26128. hash.push( lightNode.getHash() );
  26129. }
  26130. this._lightNodesHash = 'lights-' + hash.join( ',' );
  26131. }
  26132. return this._lightNodesHash;
  26133. }
  26134. analyze( builder ) {
  26135. const properties = builder.getDataFromNode( this );
  26136. for ( const node of properties.nodes ) {
  26137. node.build( builder );
  26138. }
  26139. }
  26140. setupLightsNode( builder ) {
  26141. const lightNodes = [];
  26142. const previousLightNodes = this._lightNodes;
  26143. const lights = sortLights( this._lights );
  26144. const nodeLibrary = builder.renderer.nodes.library;
  26145. for ( const light of lights ) {
  26146. if ( light.isNode ) {
  26147. lightNodes.push( nodeObject( light ) );
  26148. } else {
  26149. let lightNode = null;
  26150. if ( previousLightNodes !== null ) {
  26151. lightNode = getLightNodeById( light.id, previousLightNodes ); // resuse existing light node
  26152. }
  26153. if ( lightNode === null ) {
  26154. const lightNodeClass = nodeLibrary.getLightNodeClass( light.constructor );
  26155. if ( lightNodeClass === null ) {
  26156. console.warn( `LightsNode.setupNodeLights: Light node not found for ${ light.constructor.name }` );
  26157. continue;
  26158. }
  26159. let lightNode = null;
  26160. if ( ! _lightsNodeRef.has( light ) ) {
  26161. lightNode = new lightNodeClass( light );
  26162. _lightsNodeRef.set( light, lightNode );
  26163. } else {
  26164. lightNode = _lightsNodeRef.get( light );
  26165. }
  26166. lightNodes.push( lightNode );
  26167. }
  26168. }
  26169. }
  26170. this._lightNodes = lightNodes;
  26171. }
  26172. setup( builder ) {
  26173. if ( this._lightNodes === null ) this.setupLightsNode( builder );
  26174. const context = builder.context;
  26175. const lightingModel = context.lightingModel;
  26176. let outgoingLightNode = this.outgoingLightNode;
  26177. if ( lightingModel ) {
  26178. const { _lightNodes, totalDiffuseNode, totalSpecularNode } = this;
  26179. context.outgoingLight = outgoingLightNode;
  26180. const stack = builder.addStack();
  26181. //
  26182. const properties = builder.getDataFromNode( this );
  26183. properties.nodes = stack.nodes;
  26184. //
  26185. lightingModel.start( context, stack, builder );
  26186. // lights
  26187. for ( const lightNode of _lightNodes ) {
  26188. lightNode.build( builder );
  26189. }
  26190. //
  26191. lightingModel.indirect( context, stack, builder );
  26192. //
  26193. const { backdrop, backdropAlpha } = context;
  26194. const { directDiffuse, directSpecular, indirectDiffuse, indirectSpecular } = context.reflectedLight;
  26195. let totalDiffuse = directDiffuse.add( indirectDiffuse );
  26196. if ( backdrop !== null ) {
  26197. if ( backdropAlpha !== null ) {
  26198. totalDiffuse = vec3( backdropAlpha.mix( totalDiffuse, backdrop ) );
  26199. } else {
  26200. totalDiffuse = vec3( backdrop );
  26201. }
  26202. context.material.transparent = true;
  26203. }
  26204. totalDiffuseNode.assign( totalDiffuse );
  26205. totalSpecularNode.assign( directSpecular.add( indirectSpecular ) );
  26206. outgoingLightNode.assign( totalDiffuseNode.add( totalSpecularNode ) );
  26207. //
  26208. lightingModel.finish( context, stack, builder );
  26209. //
  26210. outgoingLightNode = outgoingLightNode.bypass( builder.removeStack() );
  26211. }
  26212. return outgoingLightNode;
  26213. }
  26214. setLights( lights ) {
  26215. this._lights = lights;
  26216. this._lightNodes = null;
  26217. this._lightNodesHash = null;
  26218. return this;
  26219. }
  26220. getLights() {
  26221. return this._lights;
  26222. }
  26223. }
  26224. const lights = /*@__PURE__*/ nodeProxy( LightsNode );
  26225. class LightingNode extends Node {
  26226. static get type() {
  26227. return 'LightingNode';
  26228. }
  26229. constructor() {
  26230. super( 'vec3' );
  26231. this.isLightingNode = true;
  26232. }
  26233. generate( /*builder*/ ) {
  26234. console.warn( 'Abstract function.' );
  26235. }
  26236. }
  26237. class AONode extends LightingNode {
  26238. static get type() {
  26239. return 'AONode';
  26240. }
  26241. constructor( aoNode = null ) {
  26242. super();
  26243. this.aoNode = aoNode;
  26244. }
  26245. setup( builder ) {
  26246. builder.context.ambientOcclusion.mulAssign( this.aoNode );
  26247. }
  26248. }
  26249. class LightingContextNode extends ContextNode {
  26250. static get type() {
  26251. return 'LightingContextNode';
  26252. }
  26253. constructor( node, lightingModel = null, backdropNode = null, backdropAlphaNode = null ) {
  26254. super( node );
  26255. this.lightingModel = lightingModel;
  26256. this.backdropNode = backdropNode;
  26257. this.backdropAlphaNode = backdropAlphaNode;
  26258. this._value = null;
  26259. }
  26260. getContext() {
  26261. const { backdropNode, backdropAlphaNode } = this;
  26262. const directDiffuse = vec3().toVar( 'directDiffuse' ),
  26263. directSpecular = vec3().toVar( 'directSpecular' ),
  26264. indirectDiffuse = vec3().toVar( 'indirectDiffuse' ),
  26265. indirectSpecular = vec3().toVar( 'indirectSpecular' );
  26266. const reflectedLight = {
  26267. directDiffuse,
  26268. directSpecular,
  26269. indirectDiffuse,
  26270. indirectSpecular
  26271. };
  26272. const context = {
  26273. radiance: vec3().toVar( 'radiance' ),
  26274. irradiance: vec3().toVar( 'irradiance' ),
  26275. iblIrradiance: vec3().toVar( 'iblIrradiance' ),
  26276. ambientOcclusion: float( 1 ).toVar( 'ambientOcclusion' ),
  26277. reflectedLight,
  26278. backdrop: backdropNode,
  26279. backdropAlpha: backdropAlphaNode
  26280. };
  26281. return context;
  26282. }
  26283. setup( builder ) {
  26284. this.value = this._value || ( this._value = this.getContext() );
  26285. this.value.lightingModel = this.lightingModel || builder.context.lightingModel;
  26286. return super.setup( builder );
  26287. }
  26288. }
  26289. const lightingContext = /*@__PURE__*/ nodeProxy( LightingContextNode );
  26290. class IrradianceNode extends LightingNode {
  26291. static get type() {
  26292. return 'IrradianceNode';
  26293. }
  26294. constructor( node ) {
  26295. super();
  26296. this.node = node;
  26297. }
  26298. setup( builder ) {
  26299. builder.context.irradiance.addAssign( this.node );
  26300. }
  26301. }
  26302. let screenSizeVec, viewportVec;
  26303. class ScreenNode extends Node {
  26304. static get type() {
  26305. return 'ScreenNode';
  26306. }
  26307. constructor( scope ) {
  26308. super();
  26309. this.scope = scope;
  26310. this.isViewportNode = true;
  26311. }
  26312. getNodeType() {
  26313. if ( this.scope === ScreenNode.VIEWPORT ) return 'vec4';
  26314. else return 'vec2';
  26315. }
  26316. getUpdateType() {
  26317. let updateType = NodeUpdateType.NONE;
  26318. if ( this.scope === ScreenNode.SIZE || this.scope === ScreenNode.VIEWPORT ) {
  26319. updateType = NodeUpdateType.RENDER;
  26320. }
  26321. this.updateType = updateType;
  26322. return updateType;
  26323. }
  26324. update( { renderer } ) {
  26325. const renderTarget = renderer.getRenderTarget();
  26326. if ( this.scope === ScreenNode.VIEWPORT ) {
  26327. if ( renderTarget !== null ) {
  26328. viewportVec.copy( renderTarget.viewport );
  26329. } else {
  26330. renderer.getViewport( viewportVec );
  26331. viewportVec.multiplyScalar( renderer.getPixelRatio() );
  26332. }
  26333. } else {
  26334. if ( renderTarget !== null ) {
  26335. screenSizeVec.width = renderTarget.width;
  26336. screenSizeVec.height = renderTarget.height;
  26337. } else {
  26338. renderer.getDrawingBufferSize( screenSizeVec );
  26339. }
  26340. }
  26341. }
  26342. setup( /*builder*/ ) {
  26343. const scope = this.scope;
  26344. let output = null;
  26345. if ( scope === ScreenNode.SIZE ) {
  26346. output = uniform( screenSizeVec || ( screenSizeVec = new Vector2() ) );
  26347. } else if ( scope === ScreenNode.VIEWPORT ) {
  26348. output = uniform( viewportVec || ( viewportVec = new Vector4() ) );
  26349. } else {
  26350. output = vec2( screenCoordinate.div( screenSize ) );
  26351. }
  26352. return output;
  26353. }
  26354. generate( builder ) {
  26355. if ( this.scope === ScreenNode.COORDINATE ) {
  26356. let coord = builder.getFragCoord();
  26357. if ( builder.isFlipY() ) {
  26358. // follow webgpu standards
  26359. const size = builder.getNodeProperties( screenSize ).outputNode.build( builder );
  26360. coord = `${ builder.getType( 'vec2' ) }( ${ coord }.x, ${ size }.y - ${ coord }.y )`;
  26361. }
  26362. return coord;
  26363. }
  26364. return super.generate( builder );
  26365. }
  26366. }
  26367. ScreenNode.COORDINATE = 'coordinate';
  26368. ScreenNode.VIEWPORT = 'viewport';
  26369. ScreenNode.SIZE = 'size';
  26370. ScreenNode.UV = 'uv';
  26371. // Screen
  26372. const screenUV = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.UV );
  26373. const screenSize = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.SIZE );
  26374. const screenCoordinate = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.COORDINATE );
  26375. // Viewport
  26376. const viewport = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.VIEWPORT );
  26377. const viewportSize = viewport.zw;
  26378. const viewportCoordinate = /*@__PURE__*/ screenCoordinate.sub( viewport.xy );
  26379. const viewportUV = /*@__PURE__*/ viewportCoordinate.div( viewportSize );
  26380. // Deprecated
  26381. const viewportResolution = /*@__PURE__*/ ( Fn( () => { // @deprecated, r169
  26382. console.warn( 'TSL.ViewportNode: "viewportResolution" is deprecated. Use "screenSize" instead.' );
  26383. return screenSize;
  26384. }, 'vec2' ).once() )();
  26385. const viewportTopLeft = /*@__PURE__*/ ( Fn( () => { // @deprecated, r168
  26386. console.warn( 'TSL.ViewportNode: "viewportTopLeft" is deprecated. Use "screenUV" instead.' );
  26387. return screenUV;
  26388. }, 'vec2' ).once() )();
  26389. const viewportBottomLeft = /*@__PURE__*/ ( Fn( () => { // @deprecated, r168
  26390. console.warn( 'TSL.ViewportNode: "viewportBottomLeft" is deprecated. Use "screenUV.flipY()" instead.' );
  26391. return screenUV.flipY();
  26392. }, 'vec2' ).once() )();
  26393. const _size$4 = /*@__PURE__*/ new Vector2();
  26394. class ViewportTextureNode extends TextureNode {
  26395. static get type() {
  26396. return 'ViewportTextureNode';
  26397. }
  26398. constructor( uvNode = screenUV, levelNode = null, framebufferTexture = null ) {
  26399. if ( framebufferTexture === null ) {
  26400. framebufferTexture = new FramebufferTexture();
  26401. framebufferTexture.minFilter = LinearMipmapLinearFilter;
  26402. }
  26403. super( framebufferTexture, uvNode, levelNode );
  26404. this.generateMipmaps = false;
  26405. this.isOutputTextureNode = true;
  26406. this.updateBeforeType = NodeUpdateType.FRAME;
  26407. }
  26408. updateBefore( frame ) {
  26409. const renderer = frame.renderer;
  26410. renderer.getDrawingBufferSize( _size$4 );
  26411. //
  26412. const framebufferTexture = this.value;
  26413. if ( framebufferTexture.image.width !== _size$4.width || framebufferTexture.image.height !== _size$4.height ) {
  26414. framebufferTexture.image.width = _size$4.width;
  26415. framebufferTexture.image.height = _size$4.height;
  26416. framebufferTexture.needsUpdate = true;
  26417. }
  26418. //
  26419. const currentGenerateMipmaps = framebufferTexture.generateMipmaps;
  26420. framebufferTexture.generateMipmaps = this.generateMipmaps;
  26421. renderer.copyFramebufferToTexture( framebufferTexture );
  26422. framebufferTexture.generateMipmaps = currentGenerateMipmaps;
  26423. }
  26424. clone() {
  26425. const viewportTextureNode = new this.constructor( this.uvNode, this.levelNode, this.value );
  26426. viewportTextureNode.generateMipmaps = this.generateMipmaps;
  26427. return viewportTextureNode;
  26428. }
  26429. }
  26430. const viewportTexture = /*@__PURE__*/ nodeProxy( ViewportTextureNode );
  26431. const viewportMipTexture = /*@__PURE__*/ nodeProxy( ViewportTextureNode, null, null, { generateMipmaps: true } );
  26432. let sharedDepthbuffer = null;
  26433. class ViewportDepthTextureNode extends ViewportTextureNode {
  26434. static get type() {
  26435. return 'ViewportDepthTextureNode';
  26436. }
  26437. constructor( uvNode = screenUV, levelNode = null ) {
  26438. if ( sharedDepthbuffer === null ) {
  26439. sharedDepthbuffer = new DepthTexture();
  26440. }
  26441. super( uvNode, levelNode, sharedDepthbuffer );
  26442. }
  26443. }
  26444. const viewportDepthTexture = /*@__PURE__*/ nodeProxy( ViewportDepthTextureNode );
  26445. class ViewportDepthNode extends Node {
  26446. static get type() {
  26447. return 'ViewportDepthNode';
  26448. }
  26449. constructor( scope, valueNode = null ) {
  26450. super( 'float' );
  26451. this.scope = scope;
  26452. this.valueNode = valueNode;
  26453. this.isViewportDepthNode = true;
  26454. }
  26455. generate( builder ) {
  26456. const { scope } = this;
  26457. if ( scope === ViewportDepthNode.DEPTH_BASE ) {
  26458. return builder.getFragDepth();
  26459. }
  26460. return super.generate( builder );
  26461. }
  26462. setup( { camera } ) {
  26463. const { scope } = this;
  26464. const value = this.valueNode;
  26465. let node = null;
  26466. if ( scope === ViewportDepthNode.DEPTH_BASE ) {
  26467. if ( value !== null ) {
  26468. node = depthBase().assign( value );
  26469. }
  26470. } else if ( scope === ViewportDepthNode.DEPTH ) {
  26471. if ( camera.isPerspectiveCamera ) {
  26472. node = viewZToPerspectiveDepth( positionView.z, cameraNear, cameraFar );
  26473. } else {
  26474. node = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  26475. }
  26476. } else if ( scope === ViewportDepthNode.LINEAR_DEPTH ) {
  26477. if ( value !== null ) {
  26478. if ( camera.isPerspectiveCamera ) {
  26479. const viewZ = perspectiveDepthToViewZ( value, cameraNear, cameraFar );
  26480. node = viewZToOrthographicDepth( viewZ, cameraNear, cameraFar );
  26481. } else {
  26482. node = value;
  26483. }
  26484. } else {
  26485. node = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  26486. }
  26487. }
  26488. return node;
  26489. }
  26490. }
  26491. ViewportDepthNode.DEPTH_BASE = 'depthBase';
  26492. ViewportDepthNode.DEPTH = 'depth';
  26493. ViewportDepthNode.LINEAR_DEPTH = 'linearDepth';
  26494. // NOTE: viewZ, the z-coordinate in camera space, is negative for points in front of the camera
  26495. // -near maps to 0; -far maps to 1
  26496. const viewZToOrthographicDepth = ( viewZ, near, far ) => viewZ.add( near ).div( near.sub( far ) );
  26497. // maps orthographic depth in [ 0, 1 ] to viewZ
  26498. const orthographicDepthToViewZ = ( depth, near, far ) => near.sub( far ).mul( depth ).sub( near );
  26499. // NOTE: https://twitter.com/gonnavis/status/1377183786949959682
  26500. // -near maps to 0; -far maps to 1
  26501. const viewZToPerspectiveDepth = ( viewZ, near, far ) => near.add( viewZ ).mul( far ).div( far.sub( near ).mul( viewZ ) );
  26502. // maps perspective depth in [ 0, 1 ] to viewZ
  26503. const perspectiveDepthToViewZ = ( depth, near, far ) => near.mul( far ).div( far.sub( near ).mul( depth ).sub( far ) );
  26504. const perspectiveDepthToLogarithmicDepth = ( perspectiveW, near, far ) => {
  26505. // The final logarithmic depth formula used here is adapted from one described in an
  26506. // article by Thatcher Ulrich (see http://tulrich.com/geekstuff/log_depth_buffer.txt),
  26507. // which was an improvement upon an earlier formula one described in an
  26508. // Outerra article (https://outerra.blogspot.com/2009/08/logarithmic-z-buffer.html).
  26509. // Ulrich's formula is the following:
  26510. // z = K * log( w / cameraNear ) / log( cameraFar / cameraNear )
  26511. // where K = 2^k - 1, and k is the number of bits in the depth buffer.
  26512. // The Outerra variant ignored the camera near plane (it assumed it was 0) and instead
  26513. // opted for a "C-constant" for resolution adjustment of objects near the camera.
  26514. // Outerra states: "Notice that the 'C' variant doesn’t use a near plane distance, it has it
  26515. // set at 0" (quote from https://outerra.blogspot.com/2012/11/maximizing-depth-buffer-range-and.html).
  26516. // Ulrich's variant has the benefit of constant relative precision over the whole near-far range.
  26517. // It was debated here whether Outerra's "C-constant" or Ulrich's "near plane" variant should
  26518. // be used, and ultimately Ulrich's "near plane" version was chosen.
  26519. // Outerra eventually made another improvement to their original "C-constant" variant,
  26520. // but it still does not incorporate the camera near plane (for this version,
  26521. // see https://outerra.blogspot.com/2013/07/logarithmic-depth-buffer-optimizations.html).
  26522. // Here we make 4 changes to Ulrich's formula:
  26523. // 1. Clamp the camera near plane so we don't divide by 0.
  26524. // 2. Use log2 instead of log to avoid an extra multiply (shaders implement log using log2).
  26525. // 3. Assume K is 1 (K = maximum value in depth buffer; see Ulrich's formula above).
  26526. // 4. Add 1 to each division by cameraNear to ensure the depth curve is shifted to the left as cameraNear increases.
  26527. // For visual representation of this depth curve, see https://www.desmos.com/calculator/lz5rqfysih
  26528. near = near.max( 1e-6 ).toVar();
  26529. const numerator = log2( perspectiveW.div( near ).add( 1 ) );
  26530. const denominator = log2( far.div( near ).add( 1 ) );
  26531. return numerator.div( denominator );
  26532. };
  26533. const depthBase = /*@__PURE__*/ nodeProxy( ViewportDepthNode, ViewportDepthNode.DEPTH_BASE );
  26534. const depth = /*@__PURE__*/ nodeImmutable( ViewportDepthNode, ViewportDepthNode.DEPTH );
  26535. const linearDepth = /*@__PURE__*/ nodeProxy( ViewportDepthNode, ViewportDepthNode.LINEAR_DEPTH );
  26536. const viewportLinearDepth = /*@__PURE__*/ linearDepth( viewportDepthTexture() );
  26537. depth.assign = ( value ) => depthBase( value );
  26538. class ClippingNode extends Node {
  26539. static get type() {
  26540. return 'ClippingNode';
  26541. }
  26542. constructor( scope = ClippingNode.DEFAULT ) {
  26543. super();
  26544. this.scope = scope;
  26545. }
  26546. setup( builder ) {
  26547. super.setup( builder );
  26548. const clippingContext = builder.clippingContext;
  26549. const { localClipIntersection, localClippingCount, globalClippingCount } = clippingContext;
  26550. const numClippingPlanes = globalClippingCount + localClippingCount;
  26551. const numUnionClippingPlanes = localClipIntersection ? numClippingPlanes - localClippingCount : numClippingPlanes;
  26552. if ( this.scope === ClippingNode.ALPHA_TO_COVERAGE ) {
  26553. return this.setupAlphaToCoverage( clippingContext.planes, numClippingPlanes, numUnionClippingPlanes );
  26554. } else {
  26555. return this.setupDefault( clippingContext.planes, numClippingPlanes, numUnionClippingPlanes );
  26556. }
  26557. }
  26558. setupAlphaToCoverage( planes, numClippingPlanes, numUnionClippingPlanes ) {
  26559. return Fn( () => {
  26560. const clippingPlanes = uniformArray( planes );
  26561. const distanceToPlane = property( 'float', 'distanceToPlane' );
  26562. const distanceGradient = property( 'float', 'distanceToGradient' );
  26563. const clipOpacity = property( 'float', 'clipOpacity' );
  26564. clipOpacity.assign( 1 );
  26565. let plane;
  26566. Loop( numUnionClippingPlanes, ( { i } ) => {
  26567. plane = clippingPlanes.element( i );
  26568. distanceToPlane.assign( positionView.dot( plane.xyz ).negate().add( plane.w ) );
  26569. distanceGradient.assign( distanceToPlane.fwidth().div( 2.0 ) );
  26570. clipOpacity.mulAssign( smoothstep( distanceGradient.negate(), distanceGradient, distanceToPlane ) );
  26571. clipOpacity.equal( 0.0 ).discard();
  26572. } );
  26573. if ( numUnionClippingPlanes < numClippingPlanes ) {
  26574. const unionClipOpacity = property( 'float', 'unionclipOpacity' );
  26575. unionClipOpacity.assign( 1 );
  26576. Loop( { start: numUnionClippingPlanes, end: numClippingPlanes }, ( { i } ) => {
  26577. plane = clippingPlanes.element( i );
  26578. distanceToPlane.assign( positionView.dot( plane.xyz ).negate().add( plane.w ) );
  26579. distanceGradient.assign( distanceToPlane.fwidth().div( 2.0 ) );
  26580. unionClipOpacity.mulAssign( smoothstep( distanceGradient.negate(), distanceGradient, distanceToPlane ).oneMinus() );
  26581. } );
  26582. clipOpacity.mulAssign( unionClipOpacity.oneMinus() );
  26583. }
  26584. diffuseColor.a.mulAssign( clipOpacity );
  26585. diffuseColor.a.equal( 0.0 ).discard();
  26586. } )();
  26587. }
  26588. setupDefault( planes, numClippingPlanes, numUnionClippingPlanes ) {
  26589. return Fn( () => {
  26590. const clippingPlanes = uniformArray( planes );
  26591. let plane;
  26592. Loop( numUnionClippingPlanes, ( { i } ) => {
  26593. plane = clippingPlanes.element( i );
  26594. positionView.dot( plane.xyz ).greaterThan( plane.w ).discard();
  26595. } );
  26596. if ( numUnionClippingPlanes < numClippingPlanes ) {
  26597. const clipped = property( 'bool', 'clipped' );
  26598. clipped.assign( true );
  26599. Loop( { start: numUnionClippingPlanes, end: numClippingPlanes }, ( { i } ) => {
  26600. plane = clippingPlanes.element( i );
  26601. clipped.assign( positionView.dot( plane.xyz ).greaterThan( plane.w ).and( clipped ) );
  26602. } );
  26603. clipped.discard();
  26604. }
  26605. } )();
  26606. }
  26607. }
  26608. ClippingNode.ALPHA_TO_COVERAGE = 'alphaToCoverage';
  26609. ClippingNode.DEFAULT = 'default';
  26610. const clipping = () => nodeObject( new ClippingNode() );
  26611. const clippingAlpha = () => nodeObject( new ClippingNode( ClippingNode.ALPHA_TO_COVERAGE ) );
  26612. class NodeMaterial extends Material {
  26613. static get type() {
  26614. return 'NodeMaterial';
  26615. }
  26616. constructor() {
  26617. super();
  26618. this.isNodeMaterial = true;
  26619. this.type = this.constructor.type;
  26620. this.forceSinglePass = false;
  26621. this.fog = true;
  26622. this.lights = false;
  26623. this.lightsNode = null;
  26624. this.envNode = null;
  26625. this.aoNode = null;
  26626. this.colorNode = null;
  26627. this.normalNode = null;
  26628. this.opacityNode = null;
  26629. this.backdropNode = null;
  26630. this.backdropAlphaNode = null;
  26631. this.alphaTestNode = null;
  26632. this.positionNode = null;
  26633. this.geometryNode = null;
  26634. this.depthNode = null;
  26635. this.shadowNode = null;
  26636. this.shadowPositionNode = null;
  26637. this.outputNode = null;
  26638. this.mrtNode = null;
  26639. this.fragmentNode = null;
  26640. this.vertexNode = null;
  26641. }
  26642. customProgramCacheKey() {
  26643. return this.type + getCacheKey$1( this );
  26644. }
  26645. build( builder ) {
  26646. this.setup( builder );
  26647. }
  26648. setupObserver( builder ) {
  26649. return new NodeMaterialObserver( builder );
  26650. }
  26651. setup( builder ) {
  26652. builder.context.setupNormal = () => this.setupNormal( builder );
  26653. // < VERTEX STAGE >
  26654. builder.addStack();
  26655. builder.stack.outputNode = this.vertexNode || this.setupPosition( builder );
  26656. if ( this.geometryNode !== null ) {
  26657. builder.stack.outputNode = builder.stack.outputNode.bypass( this.geometryNode );
  26658. }
  26659. builder.addFlow( 'vertex', builder.removeStack() );
  26660. // < FRAGMENT STAGE >
  26661. builder.addStack();
  26662. let resultNode;
  26663. const clippingNode = this.setupClipping( builder );
  26664. if ( this.depthWrite === true ) this.setupDepth( builder );
  26665. if ( this.fragmentNode === null ) {
  26666. this.setupDiffuseColor( builder );
  26667. this.setupVariants( builder );
  26668. const outgoingLightNode = this.setupLighting( builder );
  26669. if ( clippingNode !== null ) builder.stack.add( clippingNode );
  26670. // force unsigned floats - useful for RenderTargets
  26671. const basicOutput = vec4( outgoingLightNode, diffuseColor.a ).max( 0 );
  26672. resultNode = this.setupOutput( builder, basicOutput );
  26673. // OUTPUT NODE
  26674. output.assign( resultNode );
  26675. //
  26676. if ( this.outputNode !== null ) resultNode = this.outputNode;
  26677. // MRT
  26678. const renderTarget = builder.renderer.getRenderTarget();
  26679. if ( renderTarget !== null ) {
  26680. const mrt = builder.renderer.getMRT();
  26681. const materialMRT = this.mrtNode;
  26682. if ( mrt !== null ) {
  26683. resultNode = mrt;
  26684. if ( materialMRT !== null ) {
  26685. resultNode = mrt.merge( materialMRT );
  26686. }
  26687. } else if ( materialMRT !== null ) {
  26688. resultNode = materialMRT;
  26689. }
  26690. }
  26691. } else {
  26692. let fragmentNode = this.fragmentNode;
  26693. if ( fragmentNode.isOutputStructNode !== true ) {
  26694. fragmentNode = vec4( fragmentNode );
  26695. }
  26696. resultNode = this.setupOutput( builder, fragmentNode );
  26697. }
  26698. builder.stack.outputNode = resultNode;
  26699. builder.addFlow( 'fragment', builder.removeStack() );
  26700. // < MONITOR >
  26701. builder.monitor = this.setupObserver( builder );
  26702. }
  26703. setupClipping( builder ) {
  26704. if ( builder.clippingContext === null ) return null;
  26705. const { globalClippingCount, localClippingCount } = builder.clippingContext;
  26706. let result = null;
  26707. if ( globalClippingCount || localClippingCount ) {
  26708. const samples = builder.renderer.samples;
  26709. if ( this.alphaToCoverage && samples > 1 ) {
  26710. // to be added to flow when the color/alpha value has been determined
  26711. result = clippingAlpha();
  26712. } else {
  26713. builder.stack.add( clipping() );
  26714. }
  26715. }
  26716. return result;
  26717. }
  26718. setupDepth( builder ) {
  26719. const { renderer, camera } = builder;
  26720. // Depth
  26721. let depthNode = this.depthNode;
  26722. if ( depthNode === null ) {
  26723. const mrt = renderer.getMRT();
  26724. if ( mrt && mrt.has( 'depth' ) ) {
  26725. depthNode = mrt.get( 'depth' );
  26726. } else if ( renderer.logarithmicDepthBuffer === true ) {
  26727. if ( camera.isPerspectiveCamera ) {
  26728. depthNode = perspectiveDepthToLogarithmicDepth( modelViewProjection().w, cameraNear, cameraFar );
  26729. } else {
  26730. depthNode = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  26731. }
  26732. }
  26733. }
  26734. if ( depthNode !== null ) {
  26735. depth.assign( depthNode ).append();
  26736. }
  26737. }
  26738. setupPosition( builder ) {
  26739. const { object } = builder;
  26740. const geometry = object.geometry;
  26741. builder.addStack();
  26742. // Vertex
  26743. if ( geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color ) {
  26744. morphReference( object ).append();
  26745. }
  26746. if ( object.isSkinnedMesh === true ) {
  26747. skinningReference( object ).append();
  26748. }
  26749. if ( this.displacementMap ) {
  26750. const displacementMap = materialReference( 'displacementMap', 'texture' );
  26751. const displacementScale = materialReference( 'displacementScale', 'float' );
  26752. const displacementBias = materialReference( 'displacementBias', 'float' );
  26753. positionLocal.addAssign( normalLocal.normalize().mul( ( displacementMap.x.mul( displacementScale ).add( displacementBias ) ) ) );
  26754. }
  26755. if ( object.isBatchedMesh ) {
  26756. batch( object ).append();
  26757. }
  26758. if ( ( object.instanceMatrix && object.instanceMatrix.isInstancedBufferAttribute === true ) ) {
  26759. instance( object ).append();
  26760. }
  26761. if ( this.positionNode !== null ) {
  26762. positionLocal.assign( this.positionNode );
  26763. }
  26764. const mvp = modelViewProjection();
  26765. builder.context.vertex = builder.removeStack();
  26766. builder.context.mvp = mvp;
  26767. return mvp;
  26768. }
  26769. setupDiffuseColor( { object, geometry } ) {
  26770. let colorNode = this.colorNode ? vec4( this.colorNode ) : materialColor;
  26771. // VERTEX COLORS
  26772. if ( this.vertexColors === true && geometry.hasAttribute( 'color' ) ) {
  26773. colorNode = vec4( colorNode.xyz.mul( attribute( 'color', 'vec3' ) ), colorNode.a );
  26774. }
  26775. // Instanced colors
  26776. if ( object.instanceColor ) {
  26777. const instanceColor = varyingProperty( 'vec3', 'vInstanceColor' );
  26778. colorNode = instanceColor.mul( colorNode );
  26779. }
  26780. if ( object.isBatchedMesh && object._colorsTexture ) {
  26781. const batchColor = varyingProperty( 'vec3', 'vBatchColor' );
  26782. colorNode = batchColor.mul( colorNode );
  26783. }
  26784. // COLOR
  26785. diffuseColor.assign( colorNode );
  26786. // OPACITY
  26787. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  26788. diffuseColor.a.assign( diffuseColor.a.mul( opacityNode ) );
  26789. // ALPHA TEST
  26790. if ( this.alphaTestNode !== null || this.alphaTest > 0 ) {
  26791. const alphaTestNode = this.alphaTestNode !== null ? float( this.alphaTestNode ) : materialAlphaTest;
  26792. diffuseColor.a.lessThanEqual( alphaTestNode ).discard();
  26793. }
  26794. if ( this.transparent === false && this.blending === NormalBlending && this.alphaToCoverage === false ) {
  26795. diffuseColor.a.assign( 1.0 );
  26796. }
  26797. }
  26798. setupVariants( /*builder*/ ) {
  26799. // Interface function.
  26800. }
  26801. setupOutgoingLight() {
  26802. return ( this.lights === true ) ? vec3( 0 ) : diffuseColor.rgb;
  26803. }
  26804. setupNormal() {
  26805. return this.normalNode ? vec3( this.normalNode ) : materialNormal;
  26806. }
  26807. setupEnvironment( /*builder*/ ) {
  26808. let node = null;
  26809. if ( this.envNode ) {
  26810. node = this.envNode;
  26811. } else if ( this.envMap ) {
  26812. node = this.envMap.isCubeTexture ? materialReference( 'envMap', 'cubeTexture' ) : materialReference( 'envMap', 'texture' );
  26813. }
  26814. return node;
  26815. }
  26816. setupLightMap( builder ) {
  26817. let node = null;
  26818. if ( builder.material.lightMap ) {
  26819. node = new IrradianceNode( materialLightMap );
  26820. }
  26821. return node;
  26822. }
  26823. setupLights( builder ) {
  26824. const materialLightsNode = [];
  26825. //
  26826. const envNode = this.setupEnvironment( builder );
  26827. if ( envNode && envNode.isLightingNode ) {
  26828. materialLightsNode.push( envNode );
  26829. }
  26830. const lightMapNode = this.setupLightMap( builder );
  26831. if ( lightMapNode && lightMapNode.isLightingNode ) {
  26832. materialLightsNode.push( lightMapNode );
  26833. }
  26834. if ( this.aoNode !== null || builder.material.aoMap ) {
  26835. const aoNode = this.aoNode !== null ? this.aoNode : materialAOMap;
  26836. materialLightsNode.push( new AONode( aoNode ) );
  26837. }
  26838. let lightsN = this.lightsNode || builder.lightsNode;
  26839. if ( materialLightsNode.length > 0 ) {
  26840. lightsN = lights( [ ...lightsN.getLights(), ...materialLightsNode ] );
  26841. }
  26842. return lightsN;
  26843. }
  26844. setupLightingModel( /*builder*/ ) {
  26845. // Interface function.
  26846. }
  26847. setupLighting( builder ) {
  26848. const { material } = builder;
  26849. const { backdropNode, backdropAlphaNode, emissiveNode } = this;
  26850. // OUTGOING LIGHT
  26851. const lights = this.lights === true || this.lightsNode !== null;
  26852. const lightsNode = lights ? this.setupLights( builder ) : null;
  26853. let outgoingLightNode = this.setupOutgoingLight( builder );
  26854. if ( lightsNode && lightsNode.getScope().getLights().length > 0 ) {
  26855. const lightingModel = this.setupLightingModel( builder );
  26856. outgoingLightNode = lightingContext( lightsNode, lightingModel, backdropNode, backdropAlphaNode );
  26857. } else if ( backdropNode !== null ) {
  26858. outgoingLightNode = vec3( backdropAlphaNode !== null ? mix( outgoingLightNode, backdropNode, backdropAlphaNode ) : backdropNode );
  26859. }
  26860. // EMISSIVE
  26861. if ( ( emissiveNode && emissiveNode.isNode === true ) || ( material.emissive && material.emissive.isColor === true ) ) {
  26862. emissive.assign( vec3( emissiveNode ? emissiveNode : materialEmissive ) );
  26863. outgoingLightNode = outgoingLightNode.add( emissive );
  26864. }
  26865. return outgoingLightNode;
  26866. }
  26867. setupOutput( builder, outputNode ) {
  26868. // FOG
  26869. if ( this.fog === true ) {
  26870. const fogNode = builder.fogNode;
  26871. if ( fogNode ) outputNode = vec4( fogNode.mix( outputNode.rgb, fogNode.colorNode ), outputNode.a );
  26872. }
  26873. return outputNode;
  26874. }
  26875. setDefaultValues( material ) {
  26876. // This approach is to reuse the native refreshUniforms*
  26877. // and turn available the use of features like transmission and environment in core
  26878. for ( const property in material ) {
  26879. const value = material[ property ];
  26880. if ( this[ property ] === undefined ) {
  26881. this[ property ] = value;
  26882. if ( value && value.clone ) this[ property ] = value.clone();
  26883. }
  26884. }
  26885. const descriptors = Object.getOwnPropertyDescriptors( material.constructor.prototype );
  26886. for ( const key in descriptors ) {
  26887. if ( Object.getOwnPropertyDescriptor( this.constructor.prototype, key ) === undefined &&
  26888. descriptors[ key ].get !== undefined ) {
  26889. Object.defineProperty( this.constructor.prototype, key, descriptors[ key ] );
  26890. }
  26891. }
  26892. }
  26893. toJSON( meta ) {
  26894. const isRoot = ( meta === undefined || typeof meta === 'string' );
  26895. if ( isRoot ) {
  26896. meta = {
  26897. textures: {},
  26898. images: {},
  26899. nodes: {}
  26900. };
  26901. }
  26902. const data = Material.prototype.toJSON.call( this, meta );
  26903. const nodeChildren = getNodeChildren( this );
  26904. data.inputNodes = {};
  26905. for ( const { property, childNode } of nodeChildren ) {
  26906. data.inputNodes[ property ] = childNode.toJSON( meta ).uuid;
  26907. }
  26908. // TODO: Copied from Object3D.toJSON
  26909. function extractFromCache( cache ) {
  26910. const values = [];
  26911. for ( const key in cache ) {
  26912. const data = cache[ key ];
  26913. delete data.metadata;
  26914. values.push( data );
  26915. }
  26916. return values;
  26917. }
  26918. if ( isRoot ) {
  26919. const textures = extractFromCache( meta.textures );
  26920. const images = extractFromCache( meta.images );
  26921. const nodes = extractFromCache( meta.nodes );
  26922. if ( textures.length > 0 ) data.textures = textures;
  26923. if ( images.length > 0 ) data.images = images;
  26924. if ( nodes.length > 0 ) data.nodes = nodes;
  26925. }
  26926. return data;
  26927. }
  26928. copy( source ) {
  26929. this.lightsNode = source.lightsNode;
  26930. this.envNode = source.envNode;
  26931. this.colorNode = source.colorNode;
  26932. this.normalNode = source.normalNode;
  26933. this.opacityNode = source.opacityNode;
  26934. this.backdropNode = source.backdropNode;
  26935. this.backdropAlphaNode = source.backdropAlphaNode;
  26936. this.alphaTestNode = source.alphaTestNode;
  26937. this.positionNode = source.positionNode;
  26938. this.geometryNode = source.geometryNode;
  26939. this.depthNode = source.depthNode;
  26940. this.shadowNode = source.shadowNode;
  26941. this.shadowPositionNode = source.shadowPositionNode;
  26942. this.outputNode = source.outputNode;
  26943. this.mrtNode = source.mrtNode;
  26944. this.fragmentNode = source.fragmentNode;
  26945. this.vertexNode = source.vertexNode;
  26946. return super.copy( source );
  26947. }
  26948. }
  26949. const _defaultValues$e = /*@__PURE__*/ new PointsMaterial();
  26950. class InstancedPointsNodeMaterial extends NodeMaterial {
  26951. static get type() {
  26952. return 'InstancedPointsNodeMaterial';
  26953. }
  26954. constructor( params = {} ) {
  26955. super();
  26956. this.lights = false;
  26957. this.useAlphaToCoverage = true;
  26958. this.useColor = params.vertexColors;
  26959. this.pointWidth = 1;
  26960. this.pointColorNode = null;
  26961. this.pointWidthNode = null;
  26962. this.setDefaultValues( _defaultValues$e );
  26963. this.setValues( params );
  26964. }
  26965. setup( builder ) {
  26966. this.setupShaders( builder );
  26967. super.setup( builder );
  26968. }
  26969. setupShaders( { renderer } ) {
  26970. const useAlphaToCoverage = this.alphaToCoverage;
  26971. const useColor = this.useColor;
  26972. this.vertexNode = Fn( () => {
  26973. const instancePosition = attribute( 'instancePosition' ).xyz;
  26974. // camera space
  26975. const mvPos = vec4( modelViewMatrix.mul( vec4( instancePosition, 1.0 ) ) );
  26976. const aspect = viewport.z.div( viewport.w );
  26977. // clip space
  26978. const clipPos = cameraProjectionMatrix.mul( mvPos );
  26979. // offset in ndc space
  26980. const offset = positionGeometry.xy.toVar();
  26981. offset.mulAssign( this.pointWidthNode ? this.pointWidthNode : materialPointWidth );
  26982. offset.assign( offset.div( viewport.z ) );
  26983. offset.y.assign( offset.y.mul( aspect ) );
  26984. // back to clip space
  26985. offset.assign( offset.mul( clipPos.w ) );
  26986. //clipPos.xy += offset;
  26987. clipPos.addAssign( vec4( offset, 0, 0 ) );
  26988. return clipPos;
  26989. } )();
  26990. this.fragmentNode = Fn( () => {
  26991. const alpha = float( 1 ).toVar();
  26992. const len2 = lengthSq( uv().mul( 2 ).sub( 1 ) );
  26993. if ( useAlphaToCoverage && renderer.samples > 1 ) {
  26994. const dlen = float( len2.fwidth() ).toVar();
  26995. alpha.assign( smoothstep( dlen.oneMinus(), dlen.add( 1 ), len2 ).oneMinus() );
  26996. } else {
  26997. len2.greaterThan( 1.0 ).discard();
  26998. }
  26999. let pointColorNode;
  27000. if ( this.pointColorNode ) {
  27001. pointColorNode = this.pointColorNode;
  27002. } else {
  27003. if ( useColor ) {
  27004. const instanceColor = attribute( 'instanceColor' );
  27005. pointColorNode = instanceColor.mul( materialColor );
  27006. } else {
  27007. pointColorNode = materialColor;
  27008. }
  27009. }
  27010. alpha.mulAssign( materialOpacity );
  27011. return vec4( pointColorNode, alpha );
  27012. } )();
  27013. }
  27014. get alphaToCoverage() {
  27015. return this.useAlphaToCoverage;
  27016. }
  27017. set alphaToCoverage( value ) {
  27018. if ( this.useAlphaToCoverage !== value ) {
  27019. this.useAlphaToCoverage = value;
  27020. this.needsUpdate = true;
  27021. }
  27022. }
  27023. }
  27024. const _defaultValues$d = /*@__PURE__*/ new LineBasicMaterial();
  27025. class LineBasicNodeMaterial extends NodeMaterial {
  27026. static get type() {
  27027. return 'LineBasicNodeMaterial';
  27028. }
  27029. constructor( parameters ) {
  27030. super();
  27031. this.isLineBasicNodeMaterial = true;
  27032. this.lights = false;
  27033. this.setDefaultValues( _defaultValues$d );
  27034. this.setValues( parameters );
  27035. }
  27036. }
  27037. const _defaultValues$c = /*@__PURE__*/ new LineDashedMaterial();
  27038. class LineDashedNodeMaterial extends NodeMaterial {
  27039. static get type() {
  27040. return 'LineDashedNodeMaterial';
  27041. }
  27042. constructor( parameters ) {
  27043. super();
  27044. this.isLineDashedNodeMaterial = true;
  27045. this.lights = false;
  27046. this.setDefaultValues( _defaultValues$c );
  27047. this.offsetNode = null;
  27048. this.dashScaleNode = null;
  27049. this.dashSizeNode = null;
  27050. this.gapSizeNode = null;
  27051. this.setValues( parameters );
  27052. }
  27053. setupVariants() {
  27054. const offsetNode = this.offsetNode;
  27055. const dashScaleNode = this.dashScaleNode ? float( this.dashScaleNode ) : materialLineScale;
  27056. const dashSizeNode = this.dashSizeNode ? float( this.dashSizeNode ) : materialLineDashSize;
  27057. const gapSizeNode = this.dashSizeNode ? float( this.dashGapNode ) : materialLineGapSize;
  27058. dashSize.assign( dashSizeNode );
  27059. gapSize.assign( gapSizeNode );
  27060. const vLineDistance = varying( attribute( 'lineDistance' ).mul( dashScaleNode ) );
  27061. const vLineDistanceOffset = offsetNode ? vLineDistance.add( offsetNode ) : vLineDistance;
  27062. vLineDistanceOffset.mod( dashSize.add( gapSize ) ).greaterThan( dashSize ).discard();
  27063. }
  27064. }
  27065. const _defaultValues$b = /*@__PURE__*/ new LineDashedMaterial();
  27066. class Line2NodeMaterial extends NodeMaterial {
  27067. static get type() {
  27068. return 'Line2NodeMaterial';
  27069. }
  27070. constructor( params = {} ) {
  27071. super();
  27072. this.lights = false;
  27073. this.setDefaultValues( _defaultValues$b );
  27074. this.useAlphaToCoverage = true;
  27075. this.useColor = params.vertexColors;
  27076. this.useDash = params.dashed;
  27077. this.useWorldUnits = false;
  27078. this.dashOffset = 0;
  27079. this.lineWidth = 1;
  27080. this.lineColorNode = null;
  27081. this.offsetNode = null;
  27082. this.dashScaleNode = null;
  27083. this.dashSizeNode = null;
  27084. this.gapSizeNode = null;
  27085. this.setValues( params );
  27086. }
  27087. setup( builder ) {
  27088. this.setupShaders( builder );
  27089. super.setup( builder );
  27090. }
  27091. setupShaders( { renderer } ) {
  27092. const useAlphaToCoverage = this.alphaToCoverage;
  27093. const useColor = this.useColor;
  27094. const useDash = this.dashed;
  27095. const useWorldUnits = this.worldUnits;
  27096. const trimSegment = Fn( ( { start, end } ) => {
  27097. const a = cameraProjectionMatrix.element( 2 ).element( 2 ); // 3nd entry in 3th column
  27098. const b = cameraProjectionMatrix.element( 3 ).element( 2 ); // 3nd entry in 4th column
  27099. const nearEstimate = b.mul( - 0.5 ).div( a );
  27100. const alpha = nearEstimate.sub( start.z ).div( end.z.sub( start.z ) );
  27101. return vec4( mix( start.xyz, end.xyz, alpha ), end.w );
  27102. } ).setLayout( {
  27103. name: 'trimSegment',
  27104. type: 'vec4',
  27105. inputs: [
  27106. { name: 'start', type: 'vec4' },
  27107. { name: 'end', type: 'vec4' }
  27108. ]
  27109. } );
  27110. this.vertexNode = Fn( () => {
  27111. const instanceStart = attribute( 'instanceStart' );
  27112. const instanceEnd = attribute( 'instanceEnd' );
  27113. // camera space
  27114. const start = vec4( modelViewMatrix.mul( vec4( instanceStart, 1.0 ) ) ).toVar( 'start' );
  27115. const end = vec4( modelViewMatrix.mul( vec4( instanceEnd, 1.0 ) ) ).toVar( 'end' );
  27116. if ( useWorldUnits ) {
  27117. varyingProperty( 'vec3', 'worldStart' ).assign( start.xyz );
  27118. varyingProperty( 'vec3', 'worldEnd' ).assign( end.xyz );
  27119. }
  27120. const aspect = viewport.z.div( viewport.w );
  27121. // special case for perspective projection, and segments that terminate either in, or behind, the camera plane
  27122. // clearly the gpu firmware has a way of addressing this issue when projecting into ndc space
  27123. // but we need to perform ndc-space calculations in the shader, so we must address this issue directly
  27124. // perhaps there is a more elegant solution -- WestLangley
  27125. const perspective = cameraProjectionMatrix.element( 2 ).element( 3 ).equal( - 1.0 ); // 4th entry in the 3rd column
  27126. If( perspective, () => {
  27127. If( start.z.lessThan( 0.0 ).and( end.z.greaterThan( 0.0 ) ), () => {
  27128. end.assign( trimSegment( { start: start, end: end } ) );
  27129. } ).ElseIf( end.z.lessThan( 0.0 ).and( start.z.greaterThanEqual( 0.0 ) ), () => {
  27130. start.assign( trimSegment( { start: end, end: start } ) );
  27131. } );
  27132. } );
  27133. // clip space
  27134. const clipStart = cameraProjectionMatrix.mul( start );
  27135. const clipEnd = cameraProjectionMatrix.mul( end );
  27136. // ndc space
  27137. const ndcStart = clipStart.xyz.div( clipStart.w );
  27138. const ndcEnd = clipEnd.xyz.div( clipEnd.w );
  27139. // direction
  27140. const dir = ndcEnd.xy.sub( ndcStart.xy ).toVar();
  27141. // account for clip-space aspect ratio
  27142. dir.x.assign( dir.x.mul( aspect ) );
  27143. dir.assign( dir.normalize() );
  27144. const clip = vec4().toVar();
  27145. if ( useWorldUnits ) {
  27146. // get the offset direction as perpendicular to the view vector
  27147. const worldDir = end.xyz.sub( start.xyz ).normalize();
  27148. const tmpFwd = mix( start.xyz, end.xyz, 0.5 ).normalize();
  27149. const worldUp = worldDir.cross( tmpFwd ).normalize();
  27150. const worldFwd = worldDir.cross( worldUp );
  27151. const worldPos = varyingProperty( 'vec4', 'worldPos' );
  27152. worldPos.assign( positionGeometry.y.lessThan( 0.5 ).select( start, end ) );
  27153. // height offset
  27154. const hw = materialLineWidth.mul( 0.5 );
  27155. worldPos.addAssign( vec4( positionGeometry.x.lessThan( 0.0 ).select( worldUp.mul( hw ), worldUp.mul( hw ).negate() ), 0 ) );
  27156. // don't extend the line if we're rendering dashes because we
  27157. // won't be rendering the endcaps
  27158. if ( ! useDash ) {
  27159. // cap extension
  27160. worldPos.addAssign( vec4( positionGeometry.y.lessThan( 0.5 ).select( worldDir.mul( hw ).negate(), worldDir.mul( hw ) ), 0 ) );
  27161. // add width to the box
  27162. worldPos.addAssign( vec4( worldFwd.mul( hw ), 0 ) );
  27163. // endcaps
  27164. If( positionGeometry.y.greaterThan( 1.0 ).or( positionGeometry.y.lessThan( 0.0 ) ), () => {
  27165. worldPos.subAssign( vec4( worldFwd.mul( 2.0 ).mul( hw ), 0 ) );
  27166. } );
  27167. }
  27168. // project the worldpos
  27169. clip.assign( cameraProjectionMatrix.mul( worldPos ) );
  27170. // shift the depth of the projected points so the line
  27171. // segments overlap neatly
  27172. const clipPose = vec3().toVar();
  27173. clipPose.assign( positionGeometry.y.lessThan( 0.5 ).select( ndcStart, ndcEnd ) );
  27174. clip.z.assign( clipPose.z.mul( clip.w ) );
  27175. } else {
  27176. const offset = vec2( dir.y, dir.x.negate() ).toVar( 'offset' );
  27177. // undo aspect ratio adjustment
  27178. dir.x.assign( dir.x.div( aspect ) );
  27179. offset.x.assign( offset.x.div( aspect ) );
  27180. // sign flip
  27181. offset.assign( positionGeometry.x.lessThan( 0.0 ).select( offset.negate(), offset ) );
  27182. // endcaps
  27183. If( positionGeometry.y.lessThan( 0.0 ), () => {
  27184. offset.assign( offset.sub( dir ) );
  27185. } ).ElseIf( positionGeometry.y.greaterThan( 1.0 ), () => {
  27186. offset.assign( offset.add( dir ) );
  27187. } );
  27188. // adjust for linewidth
  27189. offset.assign( offset.mul( materialLineWidth ) );
  27190. // adjust for clip-space to screen-space conversion // maybe resolution should be based on viewport ...
  27191. offset.assign( offset.div( viewport.w ) );
  27192. // select end
  27193. clip.assign( positionGeometry.y.lessThan( 0.5 ).select( clipStart, clipEnd ) );
  27194. // back to clip space
  27195. offset.assign( offset.mul( clip.w ) );
  27196. clip.assign( clip.add( vec4( offset, 0, 0 ) ) );
  27197. }
  27198. return clip;
  27199. } )();
  27200. const closestLineToLine = Fn( ( { p1, p2, p3, p4 } ) => {
  27201. const p13 = p1.sub( p3 );
  27202. const p43 = p4.sub( p3 );
  27203. const p21 = p2.sub( p1 );
  27204. const d1343 = p13.dot( p43 );
  27205. const d4321 = p43.dot( p21 );
  27206. const d1321 = p13.dot( p21 );
  27207. const d4343 = p43.dot( p43 );
  27208. const d2121 = p21.dot( p21 );
  27209. const denom = d2121.mul( d4343 ).sub( d4321.mul( d4321 ) );
  27210. const numer = d1343.mul( d4321 ).sub( d1321.mul( d4343 ) );
  27211. const mua = numer.div( denom ).clamp();
  27212. const mub = d1343.add( d4321.mul( mua ) ).div( d4343 ).clamp();
  27213. return vec2( mua, mub );
  27214. } );
  27215. this.fragmentNode = Fn( () => {
  27216. const vUv = uv();
  27217. if ( useDash ) {
  27218. const offsetNode = this.offsetNode ? float( this.offsetNodeNode ) : materialLineDashOffset;
  27219. const dashScaleNode = this.dashScaleNode ? float( this.dashScaleNode ) : materialLineScale;
  27220. const dashSizeNode = this.dashSizeNode ? float( this.dashSizeNode ) : materialLineDashSize;
  27221. const gapSizeNode = this.dashSizeNode ? float( this.dashGapNode ) : materialLineGapSize;
  27222. dashSize.assign( dashSizeNode );
  27223. gapSize.assign( gapSizeNode );
  27224. const instanceDistanceStart = attribute( 'instanceDistanceStart' );
  27225. const instanceDistanceEnd = attribute( 'instanceDistanceEnd' );
  27226. const lineDistance = positionGeometry.y.lessThan( 0.5 ).select( dashScaleNode.mul( instanceDistanceStart ), materialLineScale.mul( instanceDistanceEnd ) );
  27227. const vLineDistance = varying( lineDistance.add( materialLineDashOffset ) );
  27228. const vLineDistanceOffset = offsetNode ? vLineDistance.add( offsetNode ) : vLineDistance;
  27229. vUv.y.lessThan( - 1.0 ).or( vUv.y.greaterThan( 1.0 ) ).discard(); // discard endcaps
  27230. vLineDistanceOffset.mod( dashSize.add( gapSize ) ).greaterThan( dashSize ).discard(); // todo - FIX
  27231. }
  27232. const alpha = float( 1 ).toVar( 'alpha' );
  27233. if ( useWorldUnits ) {
  27234. const worldStart = varyingProperty( 'vec3', 'worldStart' );
  27235. const worldEnd = varyingProperty( 'vec3', 'worldEnd' );
  27236. // Find the closest points on the view ray and the line segment
  27237. const rayEnd = varyingProperty( 'vec4', 'worldPos' ).xyz.normalize().mul( 1e5 );
  27238. const lineDir = worldEnd.sub( worldStart );
  27239. const params = closestLineToLine( { p1: worldStart, p2: worldEnd, p3: vec3( 0.0, 0.0, 0.0 ), p4: rayEnd } );
  27240. const p1 = worldStart.add( lineDir.mul( params.x ) );
  27241. const p2 = rayEnd.mul( params.y );
  27242. const delta = p1.sub( p2 );
  27243. const len = delta.length();
  27244. const norm = len.div( materialLineWidth );
  27245. if ( ! useDash ) {
  27246. if ( useAlphaToCoverage && renderer.samples > 1 ) {
  27247. const dnorm = norm.fwidth();
  27248. alpha.assign( smoothstep( dnorm.negate().add( 0.5 ), dnorm.add( 0.5 ), norm ).oneMinus() );
  27249. } else {
  27250. norm.greaterThan( 0.5 ).discard();
  27251. }
  27252. }
  27253. } else {
  27254. // round endcaps
  27255. if ( useAlphaToCoverage && renderer.samples > 1 ) {
  27256. const a = vUv.x;
  27257. const b = vUv.y.greaterThan( 0.0 ).select( vUv.y.sub( 1.0 ), vUv.y.add( 1.0 ) );
  27258. const len2 = a.mul( a ).add( b.mul( b ) );
  27259. const dlen = float( len2.fwidth() ).toVar( 'dlen' );
  27260. If( vUv.y.abs().greaterThan( 1.0 ), () => {
  27261. alpha.assign( smoothstep( dlen.oneMinus(), dlen.add( 1 ), len2 ).oneMinus() );
  27262. } );
  27263. } else {
  27264. If( vUv.y.abs().greaterThan( 1.0 ), () => {
  27265. const a = vUv.x;
  27266. const b = vUv.y.greaterThan( 0.0 ).select( vUv.y.sub( 1.0 ), vUv.y.add( 1.0 ) );
  27267. const len2 = a.mul( a ).add( b.mul( b ) );
  27268. len2.greaterThan( 1.0 ).discard();
  27269. } );
  27270. }
  27271. }
  27272. let lineColorNode;
  27273. if ( this.lineColorNode ) {
  27274. lineColorNode = this.lineColorNode;
  27275. } else {
  27276. if ( useColor ) {
  27277. const instanceColorStart = attribute( 'instanceColorStart' );
  27278. const instanceColorEnd = attribute( 'instanceColorEnd' );
  27279. const instanceColor = positionGeometry.y.lessThan( 0.5 ).select( instanceColorStart, instanceColorEnd );
  27280. lineColorNode = instanceColor.mul( materialColor );
  27281. } else {
  27282. lineColorNode = materialColor;
  27283. }
  27284. }
  27285. return vec4( lineColorNode, alpha );
  27286. } )();
  27287. }
  27288. get worldUnits() {
  27289. return this.useWorldUnits;
  27290. }
  27291. set worldUnits( value ) {
  27292. if ( this.useWorldUnits !== value ) {
  27293. this.useWorldUnits = value;
  27294. this.needsUpdate = true;
  27295. }
  27296. }
  27297. get dashed() {
  27298. return this.useDash;
  27299. }
  27300. set dashed( value ) {
  27301. if ( this.useDash !== value ) {
  27302. this.useDash = value;
  27303. this.needsUpdate = true;
  27304. }
  27305. }
  27306. get alphaToCoverage() {
  27307. return this.useAlphaToCoverage;
  27308. }
  27309. set alphaToCoverage( value ) {
  27310. if ( this.useAlphaToCoverage !== value ) {
  27311. this.useAlphaToCoverage = value;
  27312. this.needsUpdate = true;
  27313. }
  27314. }
  27315. }
  27316. const directionToColor = ( node ) => nodeObject( node ).mul( 0.5 ).add( 0.5 );
  27317. const colorToDirection = ( node ) => nodeObject( node ).mul( 2.0 ).sub( 1 );
  27318. const _defaultValues$a = /*@__PURE__*/ new MeshNormalMaterial();
  27319. class MeshNormalNodeMaterial extends NodeMaterial {
  27320. static get type() {
  27321. return 'MeshNormalNodeMaterial';
  27322. }
  27323. constructor( parameters ) {
  27324. super();
  27325. this.lights = false;
  27326. this.isMeshNormalNodeMaterial = true;
  27327. this.setDefaultValues( _defaultValues$a );
  27328. this.setValues( parameters );
  27329. }
  27330. setupDiffuseColor() {
  27331. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  27332. diffuseColor.assign( vec4( directionToColor( transformedNormalView ), opacityNode ) );
  27333. }
  27334. }
  27335. class EquirectUVNode extends TempNode {
  27336. static get type() {
  27337. return 'EquirectUVNode';
  27338. }
  27339. constructor( dirNode = positionWorldDirection ) {
  27340. super( 'vec2' );
  27341. this.dirNode = dirNode;
  27342. }
  27343. setup() {
  27344. const dir = this.dirNode;
  27345. const u = dir.z.atan2( dir.x ).mul( 1 / ( Math.PI * 2 ) ).add( 0.5 );
  27346. const v = dir.y.clamp( - 1.0, 1.0 ).asin().mul( 1 / Math.PI ).add( 0.5 );
  27347. return vec2( u, v );
  27348. }
  27349. }
  27350. const equirectUV = /*@__PURE__*/ nodeProxy( EquirectUVNode );
  27351. // @TODO: Consider rename WebGLCubeRenderTarget to just CubeRenderTarget
  27352. class CubeRenderTarget extends WebGLCubeRenderTarget {
  27353. constructor( size = 1, options = {} ) {
  27354. super( size, options );
  27355. this.isCubeRenderTarget = true;
  27356. }
  27357. fromEquirectangularTexture( renderer, texture$1 ) {
  27358. const currentMinFilter = texture$1.minFilter;
  27359. const currentGenerateMipmaps = texture$1.generateMipmaps;
  27360. texture$1.generateMipmaps = true;
  27361. this.texture.type = texture$1.type;
  27362. this.texture.colorSpace = texture$1.colorSpace;
  27363. this.texture.generateMipmaps = texture$1.generateMipmaps;
  27364. this.texture.minFilter = texture$1.minFilter;
  27365. this.texture.magFilter = texture$1.magFilter;
  27366. const geometry = new BoxGeometry( 5, 5, 5 );
  27367. const uvNode = equirectUV( positionWorldDirection );
  27368. const material = new NodeMaterial();
  27369. material.colorNode = texture( texture$1, uvNode, 0 );
  27370. material.side = BackSide;
  27371. material.blending = NoBlending;
  27372. const mesh = new Mesh( geometry, material );
  27373. const scene = new Scene();
  27374. scene.add( mesh );
  27375. // Avoid blurred poles
  27376. if ( texture$1.minFilter === LinearMipmapLinearFilter ) texture$1.minFilter = LinearFilter;
  27377. const camera = new CubeCamera( 1, 10, this );
  27378. const currentMRT = renderer.getMRT();
  27379. renderer.setMRT( null );
  27380. camera.update( renderer, scene );
  27381. renderer.setMRT( currentMRT );
  27382. texture$1.minFilter = currentMinFilter;
  27383. texture$1.currentGenerateMipmaps = currentGenerateMipmaps;
  27384. mesh.geometry.dispose();
  27385. mesh.material.dispose();
  27386. return this;
  27387. }
  27388. }
  27389. const _cache$1 = new WeakMap();
  27390. class CubeMapNode extends TempNode {
  27391. static get type() {
  27392. return 'CubeMapNode';
  27393. }
  27394. constructor( envNode ) {
  27395. super( 'vec3' );
  27396. this.envNode = envNode;
  27397. this._cubeTexture = null;
  27398. this._cubeTextureNode = cubeTexture();
  27399. const defaultTexture = new CubeTexture();
  27400. defaultTexture.isRenderTargetTexture = true;
  27401. this._defaultTexture = defaultTexture;
  27402. this.updateBeforeType = NodeUpdateType.RENDER;
  27403. }
  27404. updateBefore( frame ) {
  27405. const { renderer, material } = frame;
  27406. const envNode = this.envNode;
  27407. if ( envNode.isTextureNode || envNode.isMaterialReferenceNode ) {
  27408. const texture = ( envNode.isTextureNode ) ? envNode.value : material[ envNode.property ];
  27409. if ( texture && texture.isTexture ) {
  27410. const mapping = texture.mapping;
  27411. if ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) {
  27412. // check for converted cubemap map
  27413. if ( _cache$1.has( texture ) ) {
  27414. const cubeMap = _cache$1.get( texture );
  27415. mapTextureMapping( cubeMap, texture.mapping );
  27416. this._cubeTexture = cubeMap;
  27417. } else {
  27418. // create cube map from equirectangular map
  27419. const image = texture.image;
  27420. if ( isEquirectangularMapReady$1( image ) ) {
  27421. const renderTarget = new CubeRenderTarget( image.height );
  27422. renderTarget.fromEquirectangularTexture( renderer, texture );
  27423. mapTextureMapping( renderTarget.texture, texture.mapping );
  27424. this._cubeTexture = renderTarget.texture;
  27425. _cache$1.set( texture, renderTarget.texture );
  27426. texture.addEventListener( 'dispose', onTextureDispose );
  27427. } else {
  27428. // default cube texture as fallback when equirectangular texture is not yet loaded
  27429. this._cubeTexture = this._defaultTexture;
  27430. }
  27431. }
  27432. //
  27433. this._cubeTextureNode.value = this._cubeTexture;
  27434. } else {
  27435. // envNode already refers to a cube map
  27436. this._cubeTextureNode = this.envNode;
  27437. }
  27438. }
  27439. }
  27440. }
  27441. setup( builder ) {
  27442. this.updateBefore( builder );
  27443. return this._cubeTextureNode;
  27444. }
  27445. }
  27446. function isEquirectangularMapReady$1( image ) {
  27447. if ( image === null || image === undefined ) return false;
  27448. return image.height > 0;
  27449. }
  27450. function onTextureDispose( event ) {
  27451. const texture = event.target;
  27452. texture.removeEventListener( 'dispose', onTextureDispose );
  27453. const renderTarget = _cache$1.get( texture );
  27454. if ( renderTarget !== undefined ) {
  27455. _cache$1.delete( texture );
  27456. renderTarget.dispose();
  27457. }
  27458. }
  27459. function mapTextureMapping( texture, mapping ) {
  27460. if ( mapping === EquirectangularReflectionMapping ) {
  27461. texture.mapping = CubeReflectionMapping;
  27462. } else if ( mapping === EquirectangularRefractionMapping ) {
  27463. texture.mapping = CubeRefractionMapping;
  27464. }
  27465. }
  27466. const cubeMapNode = /*@__PURE__*/ nodeProxy( CubeMapNode );
  27467. class BasicEnvironmentNode extends LightingNode {
  27468. static get type() {
  27469. return 'BasicEnvironmentNode';
  27470. }
  27471. constructor( envNode = null ) {
  27472. super();
  27473. this.envNode = envNode;
  27474. }
  27475. setup( builder ) {
  27476. // environment property is used in the finish() method of BasicLightingModel
  27477. builder.context.environment = cubeMapNode( this.envNode );
  27478. }
  27479. }
  27480. class BasicLightMapNode extends LightingNode {
  27481. static get type() {
  27482. return 'BasicLightMapNode';
  27483. }
  27484. constructor( lightMapNode = null ) {
  27485. super();
  27486. this.lightMapNode = lightMapNode;
  27487. }
  27488. setup( builder ) {
  27489. // irradianceLightMap property is used in the indirectDiffuse() method of BasicLightingModel
  27490. const RECIPROCAL_PI = float( 1 / Math.PI );
  27491. builder.context.irradianceLightMap = this.lightMapNode.mul( RECIPROCAL_PI );
  27492. }
  27493. }
  27494. class LightingModel {
  27495. start( /*input, stack, builder*/ ) { }
  27496. finish( /*input, stack, builder*/ ) { }
  27497. direct( /*input, stack, builder*/ ) { }
  27498. directRectArea( /*input, stack, builder*/ ) {}
  27499. indirect( /*input, stack, builder*/ ) { }
  27500. ambientOcclusion( /*input, stack, builder*/ ) { }
  27501. }
  27502. class BasicLightingModel extends LightingModel {
  27503. constructor() {
  27504. super();
  27505. }
  27506. indirect( context, stack, builder ) {
  27507. const ambientOcclusion = context.ambientOcclusion;
  27508. const reflectedLight = context.reflectedLight;
  27509. const irradianceLightMap = builder.context.irradianceLightMap;
  27510. reflectedLight.indirectDiffuse.assign( vec4( 0.0 ) );
  27511. // accumulation (baked indirect lighting only)
  27512. if ( irradianceLightMap ) {
  27513. reflectedLight.indirectDiffuse.addAssign( irradianceLightMap );
  27514. } else {
  27515. reflectedLight.indirectDiffuse.addAssign( vec4( 1.0, 1.0, 1.0, 0.0 ) );
  27516. }
  27517. // modulation
  27518. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  27519. reflectedLight.indirectDiffuse.mulAssign( diffuseColor.rgb );
  27520. }
  27521. finish( context, stack, builder ) {
  27522. const material = builder.material;
  27523. const outgoingLight = context.outgoingLight;
  27524. const envNode = builder.context.environment;
  27525. if ( envNode ) {
  27526. switch ( material.combine ) {
  27527. case MultiplyOperation:
  27528. outgoingLight.rgb.assign( mix( outgoingLight.rgb, outgoingLight.rgb.mul( envNode.rgb ), materialSpecularStrength.mul( materialReflectivity ) ) );
  27529. break;
  27530. case MixOperation:
  27531. outgoingLight.rgb.assign( mix( outgoingLight.rgb, envNode.rgb, materialSpecularStrength.mul( materialReflectivity ) ) );
  27532. break;
  27533. case AddOperation:
  27534. outgoingLight.rgb.addAssign( envNode.rgb.mul( materialSpecularStrength.mul( materialReflectivity ) ) );
  27535. break;
  27536. default:
  27537. console.warn( 'THREE.BasicLightingModel: Unsupported .combine value:', material.combine );
  27538. break;
  27539. }
  27540. }
  27541. }
  27542. }
  27543. const _defaultValues$9 = /*@__PURE__*/ new MeshBasicMaterial();
  27544. class MeshBasicNodeMaterial extends NodeMaterial {
  27545. static get type() {
  27546. return 'MeshBasicNodeMaterial';
  27547. }
  27548. constructor( parameters ) {
  27549. super();
  27550. this.isMeshBasicNodeMaterial = true;
  27551. this.lights = true;
  27552. this.setDefaultValues( _defaultValues$9 );
  27553. this.setValues( parameters );
  27554. }
  27555. setupNormal() {
  27556. return normalView; // see #28839
  27557. }
  27558. setupEnvironment( builder ) {
  27559. const envNode = super.setupEnvironment( builder );
  27560. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  27561. }
  27562. setupLightMap( builder ) {
  27563. let node = null;
  27564. if ( builder.material.lightMap ) {
  27565. node = new BasicLightMapNode( materialLightMap );
  27566. }
  27567. return node;
  27568. }
  27569. setupOutgoingLight() {
  27570. return diffuseColor.rgb;
  27571. }
  27572. setupLightingModel() {
  27573. return new BasicLightingModel();
  27574. }
  27575. }
  27576. const F_Schlick = /*@__PURE__*/ Fn( ( { f0, f90, dotVH } ) => {
  27577. // Original approximation by Christophe Schlick '94
  27578. // float fresnel = pow( 1.0 - dotVH, 5.0 );
  27579. // Optimized variant (presented by Epic at SIGGRAPH '13)
  27580. // https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf
  27581. const fresnel = dotVH.mul( - 5.55473 ).sub( 6.98316 ).mul( dotVH ).exp2();
  27582. return f0.mul( fresnel.oneMinus() ).add( f90.mul( fresnel ) );
  27583. } ); // validated
  27584. const BRDF_Lambert = /*@__PURE__*/ Fn( ( inputs ) => {
  27585. return inputs.diffuseColor.mul( 1 / Math.PI ); // punctual light
  27586. } ); // validated
  27587. const G_BlinnPhong_Implicit = () => float( 0.25 );
  27588. const D_BlinnPhong = /*@__PURE__*/ Fn( ( { dotNH } ) => {
  27589. return shininess.mul( float( 0.5 ) ).add( 1.0 ).mul( float( 1 / Math.PI ) ).mul( dotNH.pow( shininess ) );
  27590. } );
  27591. const BRDF_BlinnPhong = /*@__PURE__*/ Fn( ( { lightDirection } ) => {
  27592. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  27593. const dotNH = transformedNormalView.dot( halfDir ).clamp();
  27594. const dotVH = positionViewDirection.dot( halfDir ).clamp();
  27595. const F = F_Schlick( { f0: specularColor, f90: 1.0, dotVH } );
  27596. const G = G_BlinnPhong_Implicit();
  27597. const D = D_BlinnPhong( { dotNH } );
  27598. return F.mul( G ).mul( D );
  27599. } );
  27600. class PhongLightingModel extends BasicLightingModel {
  27601. constructor( specular = true ) {
  27602. super();
  27603. this.specular = specular;
  27604. }
  27605. direct( { lightDirection, lightColor, reflectedLight } ) {
  27606. const dotNL = transformedNormalView.dot( lightDirection ).clamp();
  27607. const irradiance = dotNL.mul( lightColor );
  27608. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  27609. if ( this.specular === true ) {
  27610. reflectedLight.directSpecular.addAssign( irradiance.mul( BRDF_BlinnPhong( { lightDirection } ) ).mul( materialSpecularStrength ) );
  27611. }
  27612. }
  27613. indirect( { ambientOcclusion, irradiance, reflectedLight } ) {
  27614. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  27615. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  27616. }
  27617. }
  27618. const _defaultValues$8 = /*@__PURE__*/ new MeshLambertMaterial();
  27619. class MeshLambertNodeMaterial extends NodeMaterial {
  27620. static get type() {
  27621. return 'MeshLambertNodeMaterial';
  27622. }
  27623. constructor( parameters ) {
  27624. super();
  27625. this.isMeshLambertNodeMaterial = true;
  27626. this.lights = true;
  27627. this.setDefaultValues( _defaultValues$8 );
  27628. this.setValues( parameters );
  27629. }
  27630. setupEnvironment( builder ) {
  27631. const envNode = super.setupEnvironment( builder );
  27632. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  27633. }
  27634. setupLightingModel( /*builder*/ ) {
  27635. return new PhongLightingModel( false ); // ( specular ) -> force lambert
  27636. }
  27637. }
  27638. const _defaultValues$7 = /*@__PURE__*/ new MeshPhongMaterial();
  27639. class MeshPhongNodeMaterial extends NodeMaterial {
  27640. static get type() {
  27641. return 'MeshPhongNodeMaterial';
  27642. }
  27643. constructor( parameters ) {
  27644. super();
  27645. this.isMeshPhongNodeMaterial = true;
  27646. this.lights = true;
  27647. this.shininessNode = null;
  27648. this.specularNode = null;
  27649. this.setDefaultValues( _defaultValues$7 );
  27650. this.setValues( parameters );
  27651. }
  27652. setupEnvironment( builder ) {
  27653. const envNode = super.setupEnvironment( builder );
  27654. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  27655. }
  27656. setupLightingModel( /*builder*/ ) {
  27657. return new PhongLightingModel();
  27658. }
  27659. setupVariants() {
  27660. // SHININESS
  27661. const shininessNode = ( this.shininessNode ? float( this.shininessNode ) : materialShininess ).max( 1e-4 ); // to prevent pow( 0.0, 0.0 )
  27662. shininess.assign( shininessNode );
  27663. // SPECULAR COLOR
  27664. const specularNode = this.specularNode || materialSpecular;
  27665. specularColor.assign( specularNode );
  27666. }
  27667. copy( source ) {
  27668. this.shininessNode = source.shininessNode;
  27669. this.specularNode = source.specularNode;
  27670. return super.copy( source );
  27671. }
  27672. }
  27673. const getGeometryRoughness = /*@__PURE__*/ Fn( ( builder ) => {
  27674. if ( builder.geometry.hasAttribute( 'normal' ) === false ) {
  27675. return float( 0 );
  27676. }
  27677. const dxy = normalView.dFdx().abs().max( normalView.dFdy().abs() );
  27678. const geometryRoughness = dxy.x.max( dxy.y ).max( dxy.z );
  27679. return geometryRoughness;
  27680. } );
  27681. const getRoughness = /*@__PURE__*/ Fn( ( inputs ) => {
  27682. const { roughness } = inputs;
  27683. const geometryRoughness = getGeometryRoughness();
  27684. let roughnessFactor = roughness.max( 0.0525 ); // 0.0525 corresponds to the base mip of a 256 cubemap.
  27685. roughnessFactor = roughnessFactor.add( geometryRoughness );
  27686. roughnessFactor = roughnessFactor.min( 1.0 );
  27687. return roughnessFactor;
  27688. } );
  27689. // Moving Frostbite to Physically Based Rendering 3.0 - page 12, listing 2
  27690. // https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  27691. const V_GGX_SmithCorrelated = /*@__PURE__*/ Fn( ( { alpha, dotNL, dotNV } ) => {
  27692. const a2 = alpha.pow2();
  27693. const gv = dotNL.mul( a2.add( a2.oneMinus().mul( dotNV.pow2() ) ).sqrt() );
  27694. const gl = dotNV.mul( a2.add( a2.oneMinus().mul( dotNL.pow2() ) ).sqrt() );
  27695. return div( 0.5, gv.add( gl ).max( EPSILON ) );
  27696. } ).setLayout( {
  27697. name: 'V_GGX_SmithCorrelated',
  27698. type: 'float',
  27699. inputs: [
  27700. { name: 'alpha', type: 'float' },
  27701. { name: 'dotNL', type: 'float' },
  27702. { name: 'dotNV', type: 'float' }
  27703. ]
  27704. } ); // validated
  27705. // https://google.github.io/filament/Filament.md.html#materialsystem/anisotropicmodel/anisotropicspecularbrdf
  27706. const V_GGX_SmithCorrelated_Anisotropic = /*@__PURE__*/ Fn( ( { alphaT, alphaB, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL } ) => {
  27707. const gv = dotNL.mul( vec3( alphaT.mul( dotTV ), alphaB.mul( dotBV ), dotNV ).length() );
  27708. const gl = dotNV.mul( vec3( alphaT.mul( dotTL ), alphaB.mul( dotBL ), dotNL ).length() );
  27709. const v = div( 0.5, gv.add( gl ) );
  27710. return v.saturate();
  27711. } ).setLayout( {
  27712. name: 'V_GGX_SmithCorrelated_Anisotropic',
  27713. type: 'float',
  27714. inputs: [
  27715. { name: 'alphaT', type: 'float', qualifier: 'in' },
  27716. { name: 'alphaB', type: 'float', qualifier: 'in' },
  27717. { name: 'dotTV', type: 'float', qualifier: 'in' },
  27718. { name: 'dotBV', type: 'float', qualifier: 'in' },
  27719. { name: 'dotTL', type: 'float', qualifier: 'in' },
  27720. { name: 'dotBL', type: 'float', qualifier: 'in' },
  27721. { name: 'dotNV', type: 'float', qualifier: 'in' },
  27722. { name: 'dotNL', type: 'float', qualifier: 'in' }
  27723. ]
  27724. } );
  27725. // Microfacet Models for Refraction through Rough Surfaces - equation (33)
  27726. // http://graphicrants.blogspot.com/2013/08/specular-brdf-reference.html
  27727. // alpha is "roughness squared" in Disney’s reparameterization
  27728. const D_GGX = /*@__PURE__*/ Fn( ( { alpha, dotNH } ) => {
  27729. const a2 = alpha.pow2();
  27730. const denom = dotNH.pow2().mul( a2.oneMinus() ).oneMinus(); // avoid alpha = 0 with dotNH = 1
  27731. return a2.div( denom.pow2() ).mul( 1 / Math.PI );
  27732. } ).setLayout( {
  27733. name: 'D_GGX',
  27734. type: 'float',
  27735. inputs: [
  27736. { name: 'alpha', type: 'float' },
  27737. { name: 'dotNH', type: 'float' }
  27738. ]
  27739. } ); // validated
  27740. const RECIPROCAL_PI = /*@__PURE__*/ float( 1 / Math.PI );
  27741. // https://google.github.io/filament/Filament.md.html#materialsystem/anisotropicmodel/anisotropicspecularbrdf
  27742. const D_GGX_Anisotropic = /*@__PURE__*/ Fn( ( { alphaT, alphaB, dotNH, dotTH, dotBH } ) => {
  27743. const a2 = alphaT.mul( alphaB );
  27744. const v = vec3( alphaB.mul( dotTH ), alphaT.mul( dotBH ), a2.mul( dotNH ) );
  27745. const v2 = v.dot( v );
  27746. const w2 = a2.div( v2 );
  27747. return RECIPROCAL_PI.mul( a2.mul( w2.pow2() ) );
  27748. } ).setLayout( {
  27749. name: 'D_GGX_Anisotropic',
  27750. type: 'float',
  27751. inputs: [
  27752. { name: 'alphaT', type: 'float', qualifier: 'in' },
  27753. { name: 'alphaB', type: 'float', qualifier: 'in' },
  27754. { name: 'dotNH', type: 'float', qualifier: 'in' },
  27755. { name: 'dotTH', type: 'float', qualifier: 'in' },
  27756. { name: 'dotBH', type: 'float', qualifier: 'in' }
  27757. ]
  27758. } );
  27759. // GGX Distribution, Schlick Fresnel, GGX_SmithCorrelated Visibility
  27760. const BRDF_GGX = /*@__PURE__*/ Fn( ( inputs ) => {
  27761. const { lightDirection, f0, f90, roughness, f, USE_IRIDESCENCE, USE_ANISOTROPY } = inputs;
  27762. const normalView = inputs.normalView || transformedNormalView;
  27763. const alpha = roughness.pow2(); // UE4's roughness
  27764. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  27765. const dotNL = normalView.dot( lightDirection ).clamp();
  27766. const dotNV = normalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  27767. const dotNH = normalView.dot( halfDir ).clamp();
  27768. const dotVH = positionViewDirection.dot( halfDir ).clamp();
  27769. let F = F_Schlick( { f0, f90, dotVH } );
  27770. let V, D;
  27771. if ( defined( USE_IRIDESCENCE ) ) {
  27772. F = iridescence.mix( F, f );
  27773. }
  27774. if ( defined( USE_ANISOTROPY ) ) {
  27775. const dotTL = anisotropyT.dot( lightDirection );
  27776. const dotTV = anisotropyT.dot( positionViewDirection );
  27777. const dotTH = anisotropyT.dot( halfDir );
  27778. const dotBL = anisotropyB.dot( lightDirection );
  27779. const dotBV = anisotropyB.dot( positionViewDirection );
  27780. const dotBH = anisotropyB.dot( halfDir );
  27781. V = V_GGX_SmithCorrelated_Anisotropic( { alphaT, alphaB: alpha, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL } );
  27782. D = D_GGX_Anisotropic( { alphaT, alphaB: alpha, dotNH, dotTH, dotBH } );
  27783. } else {
  27784. V = V_GGX_SmithCorrelated( { alpha, dotNL, dotNV } );
  27785. D = D_GGX( { alpha, dotNH } );
  27786. }
  27787. return F.mul( V ).mul( D );
  27788. } ); // validated
  27789. // Analytical approximation of the DFG LUT, one half of the
  27790. // split-sum approximation used in indirect specular lighting.
  27791. // via 'environmentBRDF' from "Physically Based Shading on Mobile"
  27792. // https://www.unrealengine.com/blog/physically-based-shading-on-mobile
  27793. const DFGApprox = /*@__PURE__*/ Fn( ( { roughness, dotNV } ) => {
  27794. const c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 );
  27795. const c1 = vec4( 1, 0.0425, 1.04, - 0.04 );
  27796. const r = roughness.mul( c0 ).add( c1 );
  27797. const a004 = r.x.mul( r.x ).min( dotNV.mul( - 9.28 ).exp2() ).mul( r.x ).add( r.y );
  27798. const fab = vec2( - 1.04, 1.04 ).mul( a004 ).add( r.zw );
  27799. return fab;
  27800. } ).setLayout( {
  27801. name: 'DFGApprox',
  27802. type: 'vec2',
  27803. inputs: [
  27804. { name: 'roughness', type: 'float' },
  27805. { name: 'dotNV', type: 'vec3' }
  27806. ]
  27807. } );
  27808. const EnvironmentBRDF = /*@__PURE__*/ Fn( ( inputs ) => {
  27809. const { dotNV, specularColor, specularF90, roughness } = inputs;
  27810. const fab = DFGApprox( { dotNV, roughness } );
  27811. return specularColor.mul( fab.x ).add( specularF90.mul( fab.y ) );
  27812. } );
  27813. const Schlick_to_F0 = /*@__PURE__*/ Fn( ( { f, f90, dotVH } ) => {
  27814. const x = dotVH.oneMinus().saturate();
  27815. const x2 = x.mul( x );
  27816. const x5 = x.mul( x2, x2 ).clamp( 0, .9999 );
  27817. return f.sub( vec3( f90 ).mul( x5 ) ).div( x5.oneMinus() );
  27818. } ).setLayout( {
  27819. name: 'Schlick_to_F0',
  27820. type: 'vec3',
  27821. inputs: [
  27822. { name: 'f', type: 'vec3' },
  27823. { name: 'f90', type: 'float' },
  27824. { name: 'dotVH', type: 'float' }
  27825. ]
  27826. } );
  27827. // https://github.com/google/filament/blob/master/shaders/src/brdf.fs
  27828. const D_Charlie = /*@__PURE__*/ Fn( ( { roughness, dotNH } ) => {
  27829. const alpha = roughness.pow2();
  27830. // Estevez and Kulla 2017, "Production Friendly Microfacet Sheen BRDF"
  27831. const invAlpha = float( 1.0 ).div( alpha );
  27832. const cos2h = dotNH.pow2();
  27833. const sin2h = cos2h.oneMinus().max( 0.0078125 ); // 2^(-14/2), so sin2h^2 > 0 in fp16
  27834. return float( 2.0 ).add( invAlpha ).mul( sin2h.pow( invAlpha.mul( 0.5 ) ) ).div( 2.0 * Math.PI );
  27835. } ).setLayout( {
  27836. name: 'D_Charlie',
  27837. type: 'float',
  27838. inputs: [
  27839. { name: 'roughness', type: 'float' },
  27840. { name: 'dotNH', type: 'float' }
  27841. ]
  27842. } );
  27843. // https://github.com/google/filament/blob/master/shaders/src/brdf.fs
  27844. const V_Neubelt = /*@__PURE__*/ Fn( ( { dotNV, dotNL } ) => {
  27845. // Neubelt and Pettineo 2013, "Crafting a Next-gen Material Pipeline for The Order: 1886"
  27846. return float( 1.0 ).div( float( 4.0 ).mul( dotNL.add( dotNV ).sub( dotNL.mul( dotNV ) ) ) );
  27847. } ).setLayout( {
  27848. name: 'V_Neubelt',
  27849. type: 'float',
  27850. inputs: [
  27851. { name: 'dotNV', type: 'float' },
  27852. { name: 'dotNL', type: 'float' }
  27853. ]
  27854. } );
  27855. const BRDF_Sheen = /*@__PURE__*/ Fn( ( { lightDirection } ) => {
  27856. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  27857. const dotNL = transformedNormalView.dot( lightDirection ).clamp();
  27858. const dotNV = transformedNormalView.dot( positionViewDirection ).clamp();
  27859. const dotNH = transformedNormalView.dot( halfDir ).clamp();
  27860. const D = D_Charlie( { roughness: sheenRoughness, dotNH } );
  27861. const V = V_Neubelt( { dotNV, dotNL } );
  27862. return sheen.mul( D ).mul( V );
  27863. } );
  27864. // Rect Area Light
  27865. // Real-Time Polygonal-Light Shading with Linearly Transformed Cosines
  27866. // by Eric Heitz, Jonathan Dupuy, Stephen Hill and David Neubelt
  27867. // code: https://github.com/selfshadow/ltc_code/
  27868. const LTC_Uv = /*@__PURE__*/ Fn( ( { N, V, roughness } ) => {
  27869. const LUT_SIZE = 64.0;
  27870. const LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;
  27871. const LUT_BIAS = 0.5 / LUT_SIZE;
  27872. const dotNV = N.dot( V ).saturate();
  27873. // texture parameterized by sqrt( GGX alpha ) and sqrt( 1 - cos( theta ) )
  27874. const uv = vec2( roughness, dotNV.oneMinus().sqrt() );
  27875. uv.assign( uv.mul( LUT_SCALE ).add( LUT_BIAS ) );
  27876. return uv;
  27877. } ).setLayout( {
  27878. name: 'LTC_Uv',
  27879. type: 'vec2',
  27880. inputs: [
  27881. { name: 'N', type: 'vec3' },
  27882. { name: 'V', type: 'vec3' },
  27883. { name: 'roughness', type: 'float' }
  27884. ]
  27885. } );
  27886. const LTC_ClippedSphereFormFactor = /*@__PURE__*/ Fn( ( { f } ) => {
  27887. // Real-Time Area Lighting: a Journey from Research to Production (p.102)
  27888. // An approximation of the form factor of a horizon-clipped rectangle.
  27889. const l = f.length();
  27890. return max$1( l.mul( l ).add( f.z ).div( l.add( 1.0 ) ), 0 );
  27891. } ).setLayout( {
  27892. name: 'LTC_ClippedSphereFormFactor',
  27893. type: 'float',
  27894. inputs: [
  27895. { name: 'f', type: 'vec3' }
  27896. ]
  27897. } );
  27898. const LTC_EdgeVectorFormFactor = /*@__PURE__*/ Fn( ( { v1, v2 } ) => {
  27899. const x = v1.dot( v2 );
  27900. const y = x.abs().toVar();
  27901. // rational polynomial approximation to theta / sin( theta ) / 2PI
  27902. const a = y.mul( 0.0145206 ).add( 0.4965155 ).mul( y ).add( 0.8543985 ).toVar();
  27903. const b = y.add( 4.1616724 ).mul( y ).add( 3.4175940 ).toVar();
  27904. const v = a.div( b );
  27905. const theta_sintheta = x.greaterThan( 0.0 ).select( v, max$1( x.mul( x ).oneMinus(), 1e-7 ).inverseSqrt().mul( 0.5 ).sub( v ) );
  27906. return v1.cross( v2 ).mul( theta_sintheta );
  27907. } ).setLayout( {
  27908. name: 'LTC_EdgeVectorFormFactor',
  27909. type: 'vec3',
  27910. inputs: [
  27911. { name: 'v1', type: 'vec3' },
  27912. { name: 'v2', type: 'vec3' }
  27913. ]
  27914. } );
  27915. const LTC_Evaluate = /*@__PURE__*/ Fn( ( { N, V, P, mInv, p0, p1, p2, p3 } ) => {
  27916. // bail if point is on back side of plane of light
  27917. // assumes ccw winding order of light vertices
  27918. const v1 = p1.sub( p0 ).toVar();
  27919. const v2 = p3.sub( p0 ).toVar();
  27920. const lightNormal = v1.cross( v2 );
  27921. const result = vec3().toVar();
  27922. If( lightNormal.dot( P.sub( p0 ) ).greaterThanEqual( 0.0 ), () => {
  27923. // construct orthonormal basis around N
  27924. const T1 = V.sub( N.mul( V.dot( N ) ) ).normalize();
  27925. const T2 = N.cross( T1 ).negate(); // negated from paper; possibly due to a different handedness of world coordinate system
  27926. // compute transform
  27927. const mat = mInv.mul( mat3( T1, T2, N ).transpose() ).toVar();
  27928. // transform rect
  27929. // & project rect onto sphere
  27930. const coords0 = mat.mul( p0.sub( P ) ).normalize().toVar();
  27931. const coords1 = mat.mul( p1.sub( P ) ).normalize().toVar();
  27932. const coords2 = mat.mul( p2.sub( P ) ).normalize().toVar();
  27933. const coords3 = mat.mul( p3.sub( P ) ).normalize().toVar();
  27934. // calculate vector form factor
  27935. const vectorFormFactor = vec3( 0 ).toVar();
  27936. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords0, v2: coords1 } ) );
  27937. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords1, v2: coords2 } ) );
  27938. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords2, v2: coords3 } ) );
  27939. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords3, v2: coords0 } ) );
  27940. // adjust for horizon clipping
  27941. result.assign( vec3( LTC_ClippedSphereFormFactor( { f: vectorFormFactor } ) ) );
  27942. } );
  27943. return result;
  27944. } ).setLayout( {
  27945. name: 'LTC_Evaluate',
  27946. type: 'vec3',
  27947. inputs: [
  27948. { name: 'N', type: 'vec3' },
  27949. { name: 'V', type: 'vec3' },
  27950. { name: 'P', type: 'vec3' },
  27951. { name: 'mInv', type: 'mat3' },
  27952. { name: 'p0', type: 'vec3' },
  27953. { name: 'p1', type: 'vec3' },
  27954. { name: 'p2', type: 'vec3' },
  27955. { name: 'p3', type: 'vec3' }
  27956. ]
  27957. } );
  27958. // Mipped Bicubic Texture Filtering by N8
  27959. // https://www.shadertoy.com/view/Dl2SDW
  27960. const bC = 1.0 / 6.0;
  27961. const w0 = ( a ) => mul( bC, mul( a, mul( a, a.negate().add( 3.0 ) ).sub( 3.0 ) ).add( 1.0 ) );
  27962. const w1 = ( a ) => mul( bC, mul( a, mul( a, mul( 3.0, a ).sub( 6.0 ) ) ).add( 4.0 ) );
  27963. const w2 = ( a ) => mul( bC, mul( a, mul( a, mul( - 3.0, a ).add( 3.0 ) ).add( 3.0 ) ).add( 1.0 ) );
  27964. const w3 = ( a ) => mul( bC, pow( a, 3 ) );
  27965. const g0 = ( a ) => w0( a ).add( w1( a ) );
  27966. const g1 = ( a ) => w2( a ).add( w3( a ) );
  27967. // h0 and h1 are the two offset functions
  27968. const h0 = ( a ) => add( - 1.0, w1( a ).div( w0( a ).add( w1( a ) ) ) );
  27969. const h1 = ( a ) => add( 1.0, w3( a ).div( w2( a ).add( w3( a ) ) ) );
  27970. const bicubic = ( textureNode, texelSize, lod ) => {
  27971. const uv = textureNode.uvNode;
  27972. const uvScaled = mul( uv, texelSize.zw ).add( 0.5 );
  27973. const iuv = floor( uvScaled );
  27974. const fuv = fract( uvScaled );
  27975. const g0x = g0( fuv.x );
  27976. const g1x = g1( fuv.x );
  27977. const h0x = h0( fuv.x );
  27978. const h1x = h1( fuv.x );
  27979. const h0y = h0( fuv.y );
  27980. const h1y = h1( fuv.y );
  27981. const p0 = vec2( iuv.x.add( h0x ), iuv.y.add( h0y ) ).sub( 0.5 ).mul( texelSize.xy );
  27982. const p1 = vec2( iuv.x.add( h1x ), iuv.y.add( h0y ) ).sub( 0.5 ).mul( texelSize.xy );
  27983. const p2 = vec2( iuv.x.add( h0x ), iuv.y.add( h1y ) ).sub( 0.5 ).mul( texelSize.xy );
  27984. const p3 = vec2( iuv.x.add( h1x ), iuv.y.add( h1y ) ).sub( 0.5 ).mul( texelSize.xy );
  27985. const a = g0( fuv.y ).mul( add( g0x.mul( textureNode.uv( p0 ).level( lod ) ), g1x.mul( textureNode.uv( p1 ).level( lod ) ) ) );
  27986. const b = g1( fuv.y ).mul( add( g0x.mul( textureNode.uv( p2 ).level( lod ) ), g1x.mul( textureNode.uv( p3 ).level( lod ) ) ) );
  27987. return a.add( b );
  27988. };
  27989. const textureBicubic = /*@__PURE__*/ Fn( ( [ textureNode, lodNode = float( 3 ) ] ) => {
  27990. const fLodSize = vec2( textureNode.size( int( lodNode ) ) );
  27991. const cLodSize = vec2( textureNode.size( int( lodNode.add( 1.0 ) ) ) );
  27992. const fLodSizeInv = div( 1.0, fLodSize );
  27993. const cLodSizeInv = div( 1.0, cLodSize );
  27994. const fSample = bicubic( textureNode, vec4( fLodSizeInv, fLodSize ), floor( lodNode ) );
  27995. const cSample = bicubic( textureNode, vec4( cLodSizeInv, cLodSize ), ceil( lodNode ) );
  27996. return fract( lodNode ).mix( fSample, cSample );
  27997. } );
  27998. //
  27999. // Transmission
  28000. //
  28001. const getVolumeTransmissionRay = /*@__PURE__*/ Fn( ( [ n, v, thickness, ior, modelMatrix ] ) => {
  28002. // Direction of refracted light.
  28003. const refractionVector = vec3( refract( v.negate(), normalize( n ), div( 1.0, ior ) ) );
  28004. // Compute rotation-independant scaling of the model matrix.
  28005. const modelScale = vec3(
  28006. length( modelMatrix[ 0 ].xyz ),
  28007. length( modelMatrix[ 1 ].xyz ),
  28008. length( modelMatrix[ 2 ].xyz )
  28009. );
  28010. // The thickness is specified in local space.
  28011. return normalize( refractionVector ).mul( thickness.mul( modelScale ) );
  28012. } ).setLayout( {
  28013. name: 'getVolumeTransmissionRay',
  28014. type: 'vec3',
  28015. inputs: [
  28016. { name: 'n', type: 'vec3' },
  28017. { name: 'v', type: 'vec3' },
  28018. { name: 'thickness', type: 'float' },
  28019. { name: 'ior', type: 'float' },
  28020. { name: 'modelMatrix', type: 'mat4' }
  28021. ]
  28022. } );
  28023. const applyIorToRoughness = /*@__PURE__*/ Fn( ( [ roughness, ior ] ) => {
  28024. // Scale roughness with IOR so that an IOR of 1.0 results in no microfacet refraction and
  28025. // an IOR of 1.5 results in the default amount of microfacet refraction.
  28026. return roughness.mul( clamp( ior.mul( 2.0 ).sub( 2.0 ), 0.0, 1.0 ) );
  28027. } ).setLayout( {
  28028. name: 'applyIorToRoughness',
  28029. type: 'float',
  28030. inputs: [
  28031. { name: 'roughness', type: 'float' },
  28032. { name: 'ior', type: 'float' }
  28033. ]
  28034. } );
  28035. const singleViewportMipTexture = /*@__PURE__*/ viewportMipTexture();
  28036. const getTransmissionSample = /*@__PURE__*/ Fn( ( [ fragCoord, roughness, ior ] ) => {
  28037. const transmissionSample = singleViewportMipTexture.uv( fragCoord );
  28038. //const transmissionSample = viewportMipTexture( fragCoord );
  28039. const lod = log2( float( screenSize.x ) ).mul( applyIorToRoughness( roughness, ior ) );
  28040. return textureBicubic( transmissionSample, lod );
  28041. } );
  28042. const volumeAttenuation = /*@__PURE__*/ Fn( ( [ transmissionDistance, attenuationColor, attenuationDistance ] ) => {
  28043. If( attenuationDistance.notEqual( 0 ), () => {
  28044. // Compute light attenuation using Beer's law.
  28045. const attenuationCoefficient = log( attenuationColor ).negate().div( attenuationDistance );
  28046. const transmittance = exp( attenuationCoefficient.negate().mul( transmissionDistance ) );
  28047. return transmittance;
  28048. } );
  28049. // Attenuation distance is +∞, i.e. the transmitted color is not attenuated at all.
  28050. return vec3( 1.0 );
  28051. } ).setLayout( {
  28052. name: 'volumeAttenuation',
  28053. type: 'vec3',
  28054. inputs: [
  28055. { name: 'transmissionDistance', type: 'float' },
  28056. { name: 'attenuationColor', type: 'vec3' },
  28057. { name: 'attenuationDistance', type: 'float' }
  28058. ]
  28059. } );
  28060. const getIBLVolumeRefraction = /*@__PURE__*/ Fn( ( [ n, v, roughness, diffuseColor, specularColor, specularF90, position, modelMatrix, viewMatrix, projMatrix, ior, thickness, attenuationColor, attenuationDistance, dispersion ] ) => {
  28061. let transmittedLight, transmittance;
  28062. if ( dispersion ) {
  28063. transmittedLight = vec4().toVar();
  28064. transmittance = vec3().toVar();
  28065. const halfSpread = ior.sub( 1.0 ).mul( dispersion.mul( 0.025 ) );
  28066. const iors = vec3( ior.sub( halfSpread ), ior, ior.add( halfSpread ) );
  28067. Loop( { start: 0, end: 3 }, ( { i } ) => {
  28068. const ior = iors.element( i );
  28069. const transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );
  28070. const refractedRayExit = position.add( transmissionRay );
  28071. // Project refracted vector on the framebuffer, while mapping to normalized device coordinates.
  28072. const ndcPos = projMatrix.mul( viewMatrix.mul( vec4( refractedRayExit, 1.0 ) ) );
  28073. const refractionCoords = vec2( ndcPos.xy.div( ndcPos.w ) ).toVar();
  28074. refractionCoords.addAssign( 1.0 );
  28075. refractionCoords.divAssign( 2.0 );
  28076. refractionCoords.assign( vec2( refractionCoords.x, refractionCoords.y.oneMinus() ) ); // webgpu
  28077. // Sample framebuffer to get pixel the refracted ray hits.
  28078. const transmissionSample = getTransmissionSample( refractionCoords, roughness, ior );
  28079. transmittedLight.element( i ).assign( transmissionSample.element( i ) );
  28080. transmittedLight.a.addAssign( transmissionSample.a );
  28081. transmittance.element( i ).assign( diffuseColor.element( i ).mul( volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance ).element( i ) ) );
  28082. } );
  28083. transmittedLight.a.divAssign( 3.0 );
  28084. } else {
  28085. const transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );
  28086. const refractedRayExit = position.add( transmissionRay );
  28087. // Project refracted vector on the framebuffer, while mapping to normalized device coordinates.
  28088. const ndcPos = projMatrix.mul( viewMatrix.mul( vec4( refractedRayExit, 1.0 ) ) );
  28089. const refractionCoords = vec2( ndcPos.xy.div( ndcPos.w ) ).toVar();
  28090. refractionCoords.addAssign( 1.0 );
  28091. refractionCoords.divAssign( 2.0 );
  28092. refractionCoords.assign( vec2( refractionCoords.x, refractionCoords.y.oneMinus() ) ); // webgpu
  28093. // Sample framebuffer to get pixel the refracted ray hits.
  28094. transmittedLight = getTransmissionSample( refractionCoords, roughness, ior );
  28095. transmittance = diffuseColor.mul( volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance ) );
  28096. }
  28097. const attenuatedColor = transmittance.rgb.mul( transmittedLight.rgb );
  28098. const dotNV = n.dot( v ).clamp();
  28099. // Get the specular component.
  28100. const F = vec3( EnvironmentBRDF( { // n, v, specularColor, specularF90, roughness
  28101. dotNV,
  28102. specularColor,
  28103. specularF90,
  28104. roughness
  28105. } ) );
  28106. // As less light is transmitted, the opacity should be increased. This simple approximation does a decent job
  28107. // of modulating a CSS background, and has no effect when the buffer is opaque, due to a solid object or clear color.
  28108. const transmittanceFactor = transmittance.r.add( transmittance.g, transmittance.b ).div( 3.0 );
  28109. return vec4( F.oneMinus().mul( attenuatedColor ), transmittedLight.a.oneMinus().mul( transmittanceFactor ).oneMinus() );
  28110. } );
  28111. //
  28112. // Iridescence
  28113. //
  28114. // XYZ to linear-sRGB color space
  28115. const XYZ_TO_REC709 = /*@__PURE__*/ mat3(
  28116. 3.2404542, - 0.9692660, 0.0556434,
  28117. - 1.5371385, 1.8760108, - 0.2040259,
  28118. - 0.4985314, 0.0415560, 1.0572252
  28119. );
  28120. // Assume air interface for top
  28121. // Note: We don't handle the case fresnel0 == 1
  28122. const Fresnel0ToIor = ( fresnel0 ) => {
  28123. const sqrtF0 = fresnel0.sqrt();
  28124. return vec3( 1.0 ).add( sqrtF0 ).div( vec3( 1.0 ).sub( sqrtF0 ) );
  28125. };
  28126. // ior is a value between 1.0 and 3.0. 1.0 is air interface
  28127. const IorToFresnel0 = ( transmittedIor, incidentIor ) => {
  28128. return transmittedIor.sub( incidentIor ).div( transmittedIor.add( incidentIor ) ).pow2();
  28129. };
  28130. // Fresnel equations for dielectric/dielectric interfaces.
  28131. // Ref: https://belcour.github.io/blog/research/2017/05/01/brdf-thin-film.html
  28132. // Evaluation XYZ sensitivity curves in Fourier space
  28133. const evalSensitivity = ( OPD, shift ) => {
  28134. const phase = OPD.mul( 2.0 * Math.PI * 1.0e-9 );
  28135. const val = vec3( 5.4856e-13, 4.4201e-13, 5.2481e-13 );
  28136. const pos = vec3( 1.6810e+06, 1.7953e+06, 2.2084e+06 );
  28137. const VAR = vec3( 4.3278e+09, 9.3046e+09, 6.6121e+09 );
  28138. const x = float( 9.7470e-14 * Math.sqrt( 2.0 * Math.PI * 4.5282e+09 ) ).mul( phase.mul( 2.2399e+06 ).add( shift.x ).cos() ).mul( phase.pow2().mul( - 4.5282e+09 ).exp() );
  28139. let xyz = val.mul( VAR.mul( 2.0 * Math.PI ).sqrt() ).mul( pos.mul( phase ).add( shift ).cos() ).mul( phase.pow2().negate().mul( VAR ).exp() );
  28140. xyz = vec3( xyz.x.add( x ), xyz.y, xyz.z ).div( 1.0685e-7 );
  28141. const rgb = XYZ_TO_REC709.mul( xyz );
  28142. return rgb;
  28143. };
  28144. const evalIridescence = /*@__PURE__*/ Fn( ( { outsideIOR, eta2, cosTheta1, thinFilmThickness, baseF0 } ) => {
  28145. // Force iridescenceIOR -> outsideIOR when thinFilmThickness -> 0.0
  28146. const iridescenceIOR = mix( outsideIOR, eta2, smoothstep( 0.0, 0.03, thinFilmThickness ) );
  28147. // Evaluate the cosTheta on the base layer (Snell law)
  28148. const sinTheta2Sq = outsideIOR.div( iridescenceIOR ).pow2().mul( float( 1 ).sub( cosTheta1.pow2() ) );
  28149. // Handle TIR:
  28150. const cosTheta2Sq = float( 1 ).sub( sinTheta2Sq );
  28151. /*if ( cosTheta2Sq < 0.0 ) {
  28152. return vec3( 1.0 );
  28153. }*/
  28154. const cosTheta2 = cosTheta2Sq.sqrt();
  28155. // First interface
  28156. const R0 = IorToFresnel0( iridescenceIOR, outsideIOR );
  28157. const R12 = F_Schlick( { f0: R0, f90: 1.0, dotVH: cosTheta1 } );
  28158. //const R21 = R12;
  28159. const T121 = R12.oneMinus();
  28160. const phi12 = iridescenceIOR.lessThan( outsideIOR ).select( Math.PI, 0.0 );
  28161. const phi21 = float( Math.PI ).sub( phi12 );
  28162. // Second interface
  28163. const baseIOR = Fresnel0ToIor( baseF0.clamp( 0.0, 0.9999 ) ); // guard against 1.0
  28164. const R1 = IorToFresnel0( baseIOR, iridescenceIOR.toVec3() );
  28165. const R23 = F_Schlick( { f0: R1, f90: 1.0, dotVH: cosTheta2 } );
  28166. const phi23 = vec3(
  28167. baseIOR.x.lessThan( iridescenceIOR ).select( Math.PI, 0.0 ),
  28168. baseIOR.y.lessThan( iridescenceIOR ).select( Math.PI, 0.0 ),
  28169. baseIOR.z.lessThan( iridescenceIOR ).select( Math.PI, 0.0 )
  28170. );
  28171. // Phase shift
  28172. const OPD = iridescenceIOR.mul( thinFilmThickness, cosTheta2, 2.0 );
  28173. const phi = vec3( phi21 ).add( phi23 );
  28174. // Compound terms
  28175. const R123 = R12.mul( R23 ).clamp( 1e-5, 0.9999 );
  28176. const r123 = R123.sqrt();
  28177. const Rs = T121.pow2().mul( R23 ).div( vec3( 1.0 ).sub( R123 ) );
  28178. // Reflectance term for m = 0 (DC term amplitude)
  28179. const C0 = R12.add( Rs );
  28180. let I = C0;
  28181. // Reflectance term for m > 0 (pairs of diracs)
  28182. let Cm = Rs.sub( T121 );
  28183. for ( let m = 1; m <= 2; ++ m ) {
  28184. Cm = Cm.mul( r123 );
  28185. const Sm = evalSensitivity( float( m ).mul( OPD ), float( m ).mul( phi ) ).mul( 2.0 );
  28186. I = I.add( Cm.mul( Sm ) );
  28187. }
  28188. // Since out of gamut colors might be produced, negative color values are clamped to 0.
  28189. return I.max( vec3( 0.0 ) );
  28190. } ).setLayout( {
  28191. name: 'evalIridescence',
  28192. type: 'vec3',
  28193. inputs: [
  28194. { name: 'outsideIOR', type: 'float' },
  28195. { name: 'eta2', type: 'float' },
  28196. { name: 'cosTheta1', type: 'float' },
  28197. { name: 'thinFilmThickness', type: 'float' },
  28198. { name: 'baseF0', type: 'vec3' }
  28199. ]
  28200. } );
  28201. //
  28202. // Sheen
  28203. //
  28204. // This is a curve-fit approxmation to the "Charlie sheen" BRDF integrated over the hemisphere from
  28205. // Estevez and Kulla 2017, "Production Friendly Microfacet Sheen BRDF". The analysis can be found
  28206. // in the Sheen section of https://drive.google.com/file/d/1T0D1VSyR4AllqIJTQAraEIzjlb5h4FKH/view?usp=sharing
  28207. const IBLSheenBRDF = /*@__PURE__*/ Fn( ( { normal, viewDir, roughness } ) => {
  28208. const dotNV = normal.dot( viewDir ).saturate();
  28209. const r2 = roughness.pow2();
  28210. const a = select(
  28211. roughness.lessThan( 0.25 ),
  28212. float( - 339.2 ).mul( r2 ).add( float( 161.4 ).mul( roughness ) ).sub( 25.9 ),
  28213. float( - 8.48 ).mul( r2 ).add( float( 14.3 ).mul( roughness ) ).sub( 9.95 )
  28214. );
  28215. const b = select(
  28216. roughness.lessThan( 0.25 ),
  28217. float( 44.0 ).mul( r2 ).sub( float( 23.7 ).mul( roughness ) ).add( 3.26 ),
  28218. float( 1.97 ).mul( r2 ).sub( float( 3.27 ).mul( roughness ) ).add( 0.72 )
  28219. );
  28220. const DG = select( roughness.lessThan( 0.25 ), 0.0, float( 0.1 ).mul( roughness ).sub( 0.025 ) ).add( a.mul( dotNV ).add( b ).exp() );
  28221. return DG.mul( 1.0 / Math.PI ).saturate();
  28222. } );
  28223. const clearcoatF0 = vec3( 0.04 );
  28224. const clearcoatF90 = float( 1 );
  28225. //
  28226. class PhysicalLightingModel extends LightingModel {
  28227. constructor( clearcoat = false, sheen = false, iridescence = false, anisotropy = false, transmission = false, dispersion = false ) {
  28228. super();
  28229. this.clearcoat = clearcoat;
  28230. this.sheen = sheen;
  28231. this.iridescence = iridescence;
  28232. this.anisotropy = anisotropy;
  28233. this.transmission = transmission;
  28234. this.dispersion = dispersion;
  28235. this.clearcoatRadiance = null;
  28236. this.clearcoatSpecularDirect = null;
  28237. this.clearcoatSpecularIndirect = null;
  28238. this.sheenSpecularDirect = null;
  28239. this.sheenSpecularIndirect = null;
  28240. this.iridescenceFresnel = null;
  28241. this.iridescenceF0 = null;
  28242. }
  28243. start( context ) {
  28244. if ( this.clearcoat === true ) {
  28245. this.clearcoatRadiance = vec3().toVar( 'clearcoatRadiance' );
  28246. this.clearcoatSpecularDirect = vec3().toVar( 'clearcoatSpecularDirect' );
  28247. this.clearcoatSpecularIndirect = vec3().toVar( 'clearcoatSpecularIndirect' );
  28248. }
  28249. if ( this.sheen === true ) {
  28250. this.sheenSpecularDirect = vec3().toVar( 'sheenSpecularDirect' );
  28251. this.sheenSpecularIndirect = vec3().toVar( 'sheenSpecularIndirect' );
  28252. }
  28253. if ( this.iridescence === true ) {
  28254. const dotNVi = transformedNormalView.dot( positionViewDirection ).clamp();
  28255. this.iridescenceFresnel = evalIridescence( {
  28256. outsideIOR: float( 1.0 ),
  28257. eta2: iridescenceIOR,
  28258. cosTheta1: dotNVi,
  28259. thinFilmThickness: iridescenceThickness,
  28260. baseF0: specularColor
  28261. } );
  28262. this.iridescenceF0 = Schlick_to_F0( { f: this.iridescenceFresnel, f90: 1.0, dotVH: dotNVi } );
  28263. }
  28264. if ( this.transmission === true ) {
  28265. const position = positionWorld;
  28266. const v = cameraPosition.sub( positionWorld ).normalize(); // TODO: Create Node for this, same issue in MaterialX
  28267. const n = transformedNormalWorld;
  28268. context.backdrop = getIBLVolumeRefraction(
  28269. n,
  28270. v,
  28271. roughness,
  28272. diffuseColor,
  28273. specularColor,
  28274. specularF90, // specularF90
  28275. position, // positionWorld
  28276. modelWorldMatrix, // modelMatrix
  28277. cameraViewMatrix, // viewMatrix
  28278. cameraProjectionMatrix, // projMatrix
  28279. ior,
  28280. thickness,
  28281. attenuationColor,
  28282. attenuationDistance,
  28283. this.dispersion ? dispersion : null
  28284. );
  28285. context.backdropAlpha = transmission;
  28286. diffuseColor.a.mulAssign( mix( 1, context.backdrop.a, transmission ) );
  28287. }
  28288. }
  28289. // Fdez-Agüera's "Multiple-Scattering Microfacet Model for Real-Time Image Based Lighting"
  28290. // Approximates multiscattering in order to preserve energy.
  28291. // http://www.jcgt.org/published/0008/01/03/
  28292. computeMultiscattering( singleScatter, multiScatter, specularF90 ) {
  28293. const dotNV = transformedNormalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  28294. const fab = DFGApprox( { roughness, dotNV } );
  28295. const Fr = this.iridescenceF0 ? iridescence.mix( specularColor, this.iridescenceF0 ) : specularColor;
  28296. const FssEss = Fr.mul( fab.x ).add( specularF90.mul( fab.y ) );
  28297. const Ess = fab.x.add( fab.y );
  28298. const Ems = Ess.oneMinus();
  28299. const Favg = specularColor.add( specularColor.oneMinus().mul( 0.047619 ) ); // 1/21
  28300. const Fms = FssEss.mul( Favg ).div( Ems.mul( Favg ).oneMinus() );
  28301. singleScatter.addAssign( FssEss );
  28302. multiScatter.addAssign( Fms.mul( Ems ) );
  28303. }
  28304. direct( { lightDirection, lightColor, reflectedLight } ) {
  28305. const dotNL = transformedNormalView.dot( lightDirection ).clamp();
  28306. const irradiance = dotNL.mul( lightColor );
  28307. if ( this.sheen === true ) {
  28308. this.sheenSpecularDirect.addAssign( irradiance.mul( BRDF_Sheen( { lightDirection } ) ) );
  28309. }
  28310. if ( this.clearcoat === true ) {
  28311. const dotNLcc = transformedClearcoatNormalView.dot( lightDirection ).clamp();
  28312. const ccIrradiance = dotNLcc.mul( lightColor );
  28313. this.clearcoatSpecularDirect.addAssign( ccIrradiance.mul( BRDF_GGX( { lightDirection, f0: clearcoatF0, f90: clearcoatF90, roughness: clearcoatRoughness, normalView: transformedClearcoatNormalView } ) ) );
  28314. }
  28315. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  28316. reflectedLight.directSpecular.addAssign( irradiance.mul( BRDF_GGX( { lightDirection, f0: specularColor, f90: 1, roughness, iridescence: this.iridescence, f: this.iridescenceFresnel, USE_IRIDESCENCE: this.iridescence, USE_ANISOTROPY: this.anisotropy } ) ) );
  28317. }
  28318. directRectArea( { lightColor, lightPosition, halfWidth, halfHeight, reflectedLight, ltc_1, ltc_2 } ) {
  28319. const p0 = lightPosition.add( halfWidth ).sub( halfHeight ); // counterclockwise; light shines in local neg z direction
  28320. const p1 = lightPosition.sub( halfWidth ).sub( halfHeight );
  28321. const p2 = lightPosition.sub( halfWidth ).add( halfHeight );
  28322. const p3 = lightPosition.add( halfWidth ).add( halfHeight );
  28323. const N = transformedNormalView;
  28324. const V = positionViewDirection;
  28325. const P = positionView.toVar();
  28326. const uv = LTC_Uv( { N, V, roughness } );
  28327. const t1 = ltc_1.uv( uv ).toVar();
  28328. const t2 = ltc_2.uv( uv ).toVar();
  28329. const mInv = mat3(
  28330. vec3( t1.x, 0, t1.y ),
  28331. vec3( 0, 1, 0 ),
  28332. vec3( t1.z, 0, t1.w )
  28333. ).toVar();
  28334. // LTC Fresnel Approximation by Stephen Hill
  28335. // http://blog.selfshadow.com/publications/s2016-advances/s2016_ltc_fresnel.pdf
  28336. const fresnel = specularColor.mul( t2.x ).add( specularColor.oneMinus().mul( t2.y ) ).toVar();
  28337. reflectedLight.directSpecular.addAssign( lightColor.mul( fresnel ).mul( LTC_Evaluate( { N, V, P, mInv, p0, p1, p2, p3 } ) ) );
  28338. reflectedLight.directDiffuse.addAssign( lightColor.mul( diffuseColor ).mul( LTC_Evaluate( { N, V, P, mInv: mat3( 1, 0, 0, 0, 1, 0, 0, 0, 1 ), p0, p1, p2, p3 } ) ) );
  28339. }
  28340. indirect( context, stack, builder ) {
  28341. this.indirectDiffuse( context, stack, builder );
  28342. this.indirectSpecular( context, stack, builder );
  28343. this.ambientOcclusion( context, stack, builder );
  28344. }
  28345. indirectDiffuse( { irradiance, reflectedLight } ) {
  28346. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  28347. }
  28348. indirectSpecular( { radiance, iblIrradiance, reflectedLight } ) {
  28349. if ( this.sheen === true ) {
  28350. this.sheenSpecularIndirect.addAssign( iblIrradiance.mul(
  28351. sheen,
  28352. IBLSheenBRDF( {
  28353. normal: transformedNormalView,
  28354. viewDir: positionViewDirection,
  28355. roughness: sheenRoughness
  28356. } )
  28357. ) );
  28358. }
  28359. if ( this.clearcoat === true ) {
  28360. const dotNVcc = transformedClearcoatNormalView.dot( positionViewDirection ).clamp();
  28361. const clearcoatEnv = EnvironmentBRDF( {
  28362. dotNV: dotNVcc,
  28363. specularColor: clearcoatF0,
  28364. specularF90: clearcoatF90,
  28365. roughness: clearcoatRoughness
  28366. } );
  28367. this.clearcoatSpecularIndirect.addAssign( this.clearcoatRadiance.mul( clearcoatEnv ) );
  28368. }
  28369. // Both indirect specular and indirect diffuse light accumulate here
  28370. const singleScattering = vec3().toVar( 'singleScattering' );
  28371. const multiScattering = vec3().toVar( 'multiScattering' );
  28372. const cosineWeightedIrradiance = iblIrradiance.mul( 1 / Math.PI );
  28373. this.computeMultiscattering( singleScattering, multiScattering, specularF90 );
  28374. const totalScattering = singleScattering.add( multiScattering );
  28375. const diffuse = diffuseColor.mul( totalScattering.r.max( totalScattering.g ).max( totalScattering.b ).oneMinus() );
  28376. reflectedLight.indirectSpecular.addAssign( radiance.mul( singleScattering ) );
  28377. reflectedLight.indirectSpecular.addAssign( multiScattering.mul( cosineWeightedIrradiance ) );
  28378. reflectedLight.indirectDiffuse.addAssign( diffuse.mul( cosineWeightedIrradiance ) );
  28379. }
  28380. ambientOcclusion( { ambientOcclusion, reflectedLight } ) {
  28381. const dotNV = transformedNormalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  28382. const aoNV = dotNV.add( ambientOcclusion );
  28383. const aoExp = roughness.mul( - 16.0 ).oneMinus().negate().exp2();
  28384. const aoNode = ambientOcclusion.sub( aoNV.pow( aoExp ).oneMinus() ).clamp();
  28385. if ( this.clearcoat === true ) {
  28386. this.clearcoatSpecularIndirect.mulAssign( ambientOcclusion );
  28387. }
  28388. if ( this.sheen === true ) {
  28389. this.sheenSpecularIndirect.mulAssign( ambientOcclusion );
  28390. }
  28391. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  28392. reflectedLight.indirectSpecular.mulAssign( aoNode );
  28393. }
  28394. finish( context ) {
  28395. const { outgoingLight } = context;
  28396. if ( this.clearcoat === true ) {
  28397. const dotNVcc = transformedClearcoatNormalView.dot( positionViewDirection ).clamp();
  28398. const Fcc = F_Schlick( {
  28399. dotVH: dotNVcc,
  28400. f0: clearcoatF0,
  28401. f90: clearcoatF90
  28402. } );
  28403. const clearcoatLight = outgoingLight.mul( clearcoat.mul( Fcc ).oneMinus() ).add( this.clearcoatSpecularDirect.add( this.clearcoatSpecularIndirect ).mul( clearcoat ) );
  28404. outgoingLight.assign( clearcoatLight );
  28405. }
  28406. if ( this.sheen === true ) {
  28407. const sheenEnergyComp = sheen.r.max( sheen.g ).max( sheen.b ).mul( 0.157 ).oneMinus();
  28408. const sheenLight = outgoingLight.mul( sheenEnergyComp ).add( this.sheenSpecularDirect, this.sheenSpecularIndirect );
  28409. outgoingLight.assign( sheenLight );
  28410. }
  28411. }
  28412. }
  28413. // These defines must match with PMREMGenerator
  28414. const cubeUV_r0 = /*@__PURE__*/ float( 1.0 );
  28415. const cubeUV_m0 = /*@__PURE__*/ float( - 2.0 );
  28416. const cubeUV_r1 = /*@__PURE__*/ float( 0.8 );
  28417. const cubeUV_m1 = /*@__PURE__*/ float( - 1.0 );
  28418. const cubeUV_r4 = /*@__PURE__*/ float( 0.4 );
  28419. const cubeUV_m4 = /*@__PURE__*/ float( 2.0 );
  28420. const cubeUV_r5 = /*@__PURE__*/ float( 0.305 );
  28421. const cubeUV_m5 = /*@__PURE__*/ float( 3.0 );
  28422. const cubeUV_r6 = /*@__PURE__*/ float( 0.21 );
  28423. const cubeUV_m6 = /*@__PURE__*/ float( 4.0 );
  28424. const cubeUV_minMipLevel = /*@__PURE__*/ float( 4.0 );
  28425. const cubeUV_minTileSize = /*@__PURE__*/ float( 16.0 );
  28426. // These shader functions convert between the UV coordinates of a single face of
  28427. // a cubemap, the 0-5 integer index of a cube face, and the direction vector for
  28428. // sampling a textureCube (not generally normalized ).
  28429. const getFace = /*@__PURE__*/ Fn( ( [ direction ] ) => {
  28430. const absDirection = vec3( abs( direction ) ).toVar();
  28431. const face = float( - 1.0 ).toVar();
  28432. If( absDirection.x.greaterThan( absDirection.z ), () => {
  28433. If( absDirection.x.greaterThan( absDirection.y ), () => {
  28434. face.assign( select( direction.x.greaterThan( 0.0 ), 0.0, 3.0 ) );
  28435. } ).Else( () => {
  28436. face.assign( select( direction.y.greaterThan( 0.0 ), 1.0, 4.0 ) );
  28437. } );
  28438. } ).Else( () => {
  28439. If( absDirection.z.greaterThan( absDirection.y ), () => {
  28440. face.assign( select( direction.z.greaterThan( 0.0 ), 2.0, 5.0 ) );
  28441. } ).Else( () => {
  28442. face.assign( select( direction.y.greaterThan( 0.0 ), 1.0, 4.0 ) );
  28443. } );
  28444. } );
  28445. return face;
  28446. } ).setLayout( {
  28447. name: 'getFace',
  28448. type: 'float',
  28449. inputs: [
  28450. { name: 'direction', type: 'vec3' }
  28451. ]
  28452. } );
  28453. // RH coordinate system; PMREM face-indexing convention
  28454. const getUV = /*@__PURE__*/ Fn( ( [ direction, face ] ) => {
  28455. const uv = vec2().toVar();
  28456. If( face.equal( 0.0 ), () => {
  28457. uv.assign( vec2( direction.z, direction.y ).div( abs( direction.x ) ) ); // pos x
  28458. } ).ElseIf( face.equal( 1.0 ), () => {
  28459. uv.assign( vec2( direction.x.negate(), direction.z.negate() ).div( abs( direction.y ) ) ); // pos y
  28460. } ).ElseIf( face.equal( 2.0 ), () => {
  28461. uv.assign( vec2( direction.x.negate(), direction.y ).div( abs( direction.z ) ) ); // pos z
  28462. } ).ElseIf( face.equal( 3.0 ), () => {
  28463. uv.assign( vec2( direction.z.negate(), direction.y ).div( abs( direction.x ) ) ); // neg x
  28464. } ).ElseIf( face.equal( 4.0 ), () => {
  28465. uv.assign( vec2( direction.x.negate(), direction.z ).div( abs( direction.y ) ) ); // neg y
  28466. } ).Else( () => {
  28467. uv.assign( vec2( direction.x, direction.y ).div( abs( direction.z ) ) ); // neg z
  28468. } );
  28469. return mul( 0.5, uv.add( 1.0 ) );
  28470. } ).setLayout( {
  28471. name: 'getUV',
  28472. type: 'vec2',
  28473. inputs: [
  28474. { name: 'direction', type: 'vec3' },
  28475. { name: 'face', type: 'float' }
  28476. ]
  28477. } );
  28478. const roughnessToMip = /*@__PURE__*/ Fn( ( [ roughness ] ) => {
  28479. const mip = float( 0.0 ).toVar();
  28480. If( roughness.greaterThanEqual( cubeUV_r1 ), () => {
  28481. mip.assign( cubeUV_r0.sub( roughness ).mul( cubeUV_m1.sub( cubeUV_m0 ) ).div( cubeUV_r0.sub( cubeUV_r1 ) ).add( cubeUV_m0 ) );
  28482. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r4 ), () => {
  28483. mip.assign( cubeUV_r1.sub( roughness ).mul( cubeUV_m4.sub( cubeUV_m1 ) ).div( cubeUV_r1.sub( cubeUV_r4 ) ).add( cubeUV_m1 ) );
  28484. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r5 ), () => {
  28485. mip.assign( cubeUV_r4.sub( roughness ).mul( cubeUV_m5.sub( cubeUV_m4 ) ).div( cubeUV_r4.sub( cubeUV_r5 ) ).add( cubeUV_m4 ) );
  28486. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r6 ), () => {
  28487. mip.assign( cubeUV_r5.sub( roughness ).mul( cubeUV_m6.sub( cubeUV_m5 ) ).div( cubeUV_r5.sub( cubeUV_r6 ) ).add( cubeUV_m5 ) );
  28488. } ).Else( () => {
  28489. mip.assign( float( - 2.0 ).mul( log2( mul( 1.16, roughness ) ) ) ); // 1.16 = 1.79^0.25
  28490. } );
  28491. return mip;
  28492. } ).setLayout( {
  28493. name: 'roughnessToMip',
  28494. type: 'float',
  28495. inputs: [
  28496. { name: 'roughness', type: 'float' }
  28497. ]
  28498. } );
  28499. // RH coordinate system; PMREM face-indexing convention
  28500. const getDirection = /*@__PURE__*/ Fn( ( [ uv_immutable, face ] ) => {
  28501. const uv = uv_immutable.toVar();
  28502. uv.assign( mul( 2.0, uv ).sub( 1.0 ) );
  28503. const direction = vec3( uv, 1.0 ).toVar();
  28504. If( face.equal( 0.0 ), () => {
  28505. direction.assign( direction.zyx ); // ( 1, v, u ) pos x
  28506. } ).ElseIf( face.equal( 1.0 ), () => {
  28507. direction.assign( direction.xzy );
  28508. direction.xz.mulAssign( - 1.0 ); // ( -u, 1, -v ) pos y
  28509. } ).ElseIf( face.equal( 2.0 ), () => {
  28510. direction.x.mulAssign( - 1.0 ); // ( -u, v, 1 ) pos z
  28511. } ).ElseIf( face.equal( 3.0 ), () => {
  28512. direction.assign( direction.zyx );
  28513. direction.xz.mulAssign( - 1.0 ); // ( -1, v, -u ) neg x
  28514. } ).ElseIf( face.equal( 4.0 ), () => {
  28515. direction.assign( direction.xzy );
  28516. direction.xy.mulAssign( - 1.0 ); // ( -u, -1, v ) neg y
  28517. } ).ElseIf( face.equal( 5.0 ), () => {
  28518. direction.z.mulAssign( - 1.0 ); // ( u, v, -1 ) neg zS
  28519. } );
  28520. return direction;
  28521. } ).setLayout( {
  28522. name: 'getDirection',
  28523. type: 'vec3',
  28524. inputs: [
  28525. { name: 'uv', type: 'vec2' },
  28526. { name: 'face', type: 'float' }
  28527. ]
  28528. } );
  28529. //
  28530. const textureCubeUV = /*@__PURE__*/ Fn( ( [ envMap, sampleDir_immutable, roughness_immutable, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ] ) => {
  28531. const roughness = float( roughness_immutable );
  28532. const sampleDir = vec3( sampleDir_immutable );
  28533. const mip = clamp( roughnessToMip( roughness ), cubeUV_m0, CUBEUV_MAX_MIP );
  28534. const mipF = fract( mip );
  28535. const mipInt = floor( mip );
  28536. const color0 = vec3( bilinearCubeUV( envMap, sampleDir, mipInt, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ) ).toVar();
  28537. If( mipF.notEqual( 0.0 ), () => {
  28538. const color1 = vec3( bilinearCubeUV( envMap, sampleDir, mipInt.add( 1.0 ), CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ) ).toVar();
  28539. color0.assign( mix( color0, color1, mipF ) );
  28540. } );
  28541. return color0;
  28542. } );
  28543. const bilinearCubeUV = /*@__PURE__*/ Fn( ( [ envMap, direction_immutable, mipInt_immutable, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ] ) => {
  28544. const mipInt = float( mipInt_immutable ).toVar();
  28545. const direction = vec3( direction_immutable );
  28546. const face = float( getFace( direction ) ).toVar();
  28547. const filterInt = float( max$1( cubeUV_minMipLevel.sub( mipInt ), 0.0 ) ).toVar();
  28548. mipInt.assign( max$1( mipInt, cubeUV_minMipLevel ) );
  28549. const faceSize = float( exp2( mipInt ) ).toVar();
  28550. const uv = vec2( getUV( direction, face ).mul( faceSize.sub( 2.0 ) ).add( 1.0 ) ).toVar();
  28551. If( face.greaterThan( 2.0 ), () => {
  28552. uv.y.addAssign( faceSize );
  28553. face.subAssign( 3.0 );
  28554. } );
  28555. uv.x.addAssign( face.mul( faceSize ) );
  28556. uv.x.addAssign( filterInt.mul( mul( 3.0, cubeUV_minTileSize ) ) );
  28557. uv.y.addAssign( mul( 4.0, exp2( CUBEUV_MAX_MIP ).sub( faceSize ) ) );
  28558. uv.x.mulAssign( CUBEUV_TEXEL_WIDTH );
  28559. uv.y.mulAssign( CUBEUV_TEXEL_HEIGHT );
  28560. return envMap.uv( uv ).grad( vec2(), vec2() ); // disable anisotropic filtering
  28561. } );
  28562. const getSample = /*@__PURE__*/ Fn( ( { envMap, mipInt, outputDirection, theta, axis, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) => {
  28563. const cosTheta = cos( theta );
  28564. // Rodrigues' axis-angle rotation
  28565. const sampleDirection = outputDirection.mul( cosTheta )
  28566. .add( axis.cross( outputDirection ).mul( sin( theta ) ) )
  28567. .add( axis.mul( axis.dot( outputDirection ).mul( cosTheta.oneMinus() ) ) );
  28568. return bilinearCubeUV( envMap, sampleDirection, mipInt, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP );
  28569. } );
  28570. const blur = /*@__PURE__*/ Fn( ( { n, latitudinal, poleAxis, outputDirection, weights, samples, dTheta, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) => {
  28571. const axis = vec3( select( latitudinal, poleAxis, cross( poleAxis, outputDirection ) ) ).toVar();
  28572. If( all( axis.equals( vec3( 0.0 ) ) ), () => {
  28573. axis.assign( vec3( outputDirection.z, 0.0, outputDirection.x.negate() ) );
  28574. } );
  28575. axis.assign( normalize( axis ) );
  28576. const gl_FragColor = vec3().toVar();
  28577. gl_FragColor.addAssign( weights.element( int( 0 ) ).mul( getSample( { theta: 0.0, axis, outputDirection, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) ) );
  28578. Loop( { start: int( 1 ), end: n }, ( { i } ) => {
  28579. If( i.greaterThanEqual( samples ), () => {
  28580. Break();
  28581. } );
  28582. const theta = float( dTheta.mul( float( i ) ) ).toVar();
  28583. gl_FragColor.addAssign( weights.element( i ).mul( getSample( { theta: theta.mul( - 1.0 ), axis, outputDirection, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) ) );
  28584. gl_FragColor.addAssign( weights.element( i ).mul( getSample( { theta, axis, outputDirection, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) ) );
  28585. } );
  28586. return vec4( gl_FragColor, 1 );
  28587. } );
  28588. let _generator = null;
  28589. const _cache = new WeakMap();
  28590. function _generateCubeUVSize( imageHeight ) {
  28591. const maxMip = Math.log2( imageHeight ) - 2;
  28592. const texelHeight = 1.0 / imageHeight;
  28593. const texelWidth = 1.0 / ( 3 * Math.max( Math.pow( 2, maxMip ), 7 * 16 ) );
  28594. return { texelWidth, texelHeight, maxMip };
  28595. }
  28596. function _getPMREMFromTexture( texture ) {
  28597. let cacheTexture = _cache.get( texture );
  28598. const pmremVersion = cacheTexture !== undefined ? cacheTexture.pmremVersion : - 1;
  28599. if ( pmremVersion !== texture.pmremVersion ) {
  28600. const image = texture.image;
  28601. if ( texture.isCubeTexture ) {
  28602. if ( isCubeMapReady( image ) ) {
  28603. cacheTexture = _generator.fromCubemap( texture, cacheTexture );
  28604. } else {
  28605. return null;
  28606. }
  28607. } else {
  28608. if ( isEquirectangularMapReady( image ) ) {
  28609. cacheTexture = _generator.fromEquirectangular( texture, cacheTexture );
  28610. } else {
  28611. return null;
  28612. }
  28613. }
  28614. cacheTexture.pmremVersion = texture.pmremVersion;
  28615. _cache.set( texture, cacheTexture );
  28616. }
  28617. return cacheTexture.texture;
  28618. }
  28619. class PMREMNode extends TempNode {
  28620. static get type() {
  28621. return 'PMREMNode';
  28622. }
  28623. constructor( value, uvNode = null, levelNode = null ) {
  28624. super( 'vec3' );
  28625. this._value = value;
  28626. this._pmrem = null;
  28627. this.uvNode = uvNode;
  28628. this.levelNode = levelNode;
  28629. this._generator = null;
  28630. const defaultTexture = new Texture();
  28631. defaultTexture.isRenderTargetTexture = true;
  28632. this._texture = texture( defaultTexture );
  28633. this._width = uniform( 0 );
  28634. this._height = uniform( 0 );
  28635. this._maxMip = uniform( 0 );
  28636. this.updateBeforeType = NodeUpdateType.RENDER;
  28637. }
  28638. set value( value ) {
  28639. this._value = value;
  28640. this._pmrem = null;
  28641. }
  28642. get value() {
  28643. return this._value;
  28644. }
  28645. updateFromTexture( texture ) {
  28646. const cubeUVSize = _generateCubeUVSize( texture.image.height );
  28647. this._texture.value = texture;
  28648. this._width.value = cubeUVSize.texelWidth;
  28649. this._height.value = cubeUVSize.texelHeight;
  28650. this._maxMip.value = cubeUVSize.maxMip;
  28651. }
  28652. updateBefore() {
  28653. let pmrem = this._pmrem;
  28654. const pmremVersion = pmrem ? pmrem.pmremVersion : - 1;
  28655. const texture = this._value;
  28656. if ( pmremVersion !== texture.pmremVersion ) {
  28657. if ( texture.isPMREMTexture === true ) {
  28658. pmrem = texture;
  28659. } else {
  28660. pmrem = _getPMREMFromTexture( texture );
  28661. }
  28662. if ( pmrem !== null ) {
  28663. this._pmrem = pmrem;
  28664. this.updateFromTexture( pmrem );
  28665. }
  28666. }
  28667. }
  28668. setup( builder ) {
  28669. if ( _generator === null ) {
  28670. _generator = builder.createPMREMGenerator();
  28671. }
  28672. //
  28673. this.updateBefore( builder );
  28674. //
  28675. let uvNode = this.uvNode;
  28676. if ( uvNode === null && builder.context.getUV ) {
  28677. uvNode = builder.context.getUV( this );
  28678. }
  28679. //
  28680. const texture = this.value;
  28681. if ( builder.renderer.coordinateSystem === WebGLCoordinateSystem && texture.isPMREMTexture !== true && texture.isRenderTargetTexture === true ) {
  28682. uvNode = vec3( uvNode.x.negate(), uvNode.yz );
  28683. }
  28684. //
  28685. let levelNode = this.levelNode;
  28686. if ( levelNode === null && builder.context.getTextureLevel ) {
  28687. levelNode = builder.context.getTextureLevel( this );
  28688. }
  28689. //
  28690. return textureCubeUV( this._texture, uvNode, levelNode, this._width, this._height, this._maxMip );
  28691. }
  28692. }
  28693. function isCubeMapReady( image ) {
  28694. if ( image === null || image === undefined ) return false;
  28695. let count = 0;
  28696. const length = 6;
  28697. for ( let i = 0; i < length; i ++ ) {
  28698. if ( image[ i ] !== undefined ) count ++;
  28699. }
  28700. return count === length;
  28701. }
  28702. function isEquirectangularMapReady( image ) {
  28703. if ( image === null || image === undefined ) return false;
  28704. return image.height > 0;
  28705. }
  28706. const pmremTexture = /*@__PURE__*/ nodeProxy( PMREMNode );
  28707. const _envNodeCache = new WeakMap();
  28708. class EnvironmentNode extends LightingNode {
  28709. static get type() {
  28710. return 'EnvironmentNode';
  28711. }
  28712. constructor( envNode = null ) {
  28713. super();
  28714. this.envNode = envNode;
  28715. }
  28716. setup( builder ) {
  28717. const { material } = builder;
  28718. let envNode = this.envNode;
  28719. if ( envNode.isTextureNode || envNode.isMaterialReferenceNode ) {
  28720. const value = ( envNode.isTextureNode ) ? envNode.value : material[ envNode.property ];
  28721. let cacheEnvNode = _envNodeCache.get( value );
  28722. if ( cacheEnvNode === undefined ) {
  28723. cacheEnvNode = pmremTexture( value );
  28724. _envNodeCache.set( value, cacheEnvNode );
  28725. }
  28726. envNode = cacheEnvNode;
  28727. }
  28728. //
  28729. const envMap = material.envMap;
  28730. const intensity = envMap ? reference( 'envMapIntensity', 'float', builder.material ) : reference( 'environmentIntensity', 'float', builder.scene ); // @TODO: Add materialEnvIntensity in MaterialNode
  28731. const useAnisotropy = material.useAnisotropy === true || material.anisotropy > 0;
  28732. const radianceNormalView = useAnisotropy ? transformedBentNormalView : transformedNormalView;
  28733. const radiance = envNode.context( createRadianceContext( roughness, radianceNormalView ) ).mul( intensity );
  28734. const irradiance = envNode.context( createIrradianceContext( transformedNormalWorld ) ).mul( Math.PI ).mul( intensity );
  28735. const isolateRadiance = cache( radiance );
  28736. const isolateIrradiance = cache( irradiance );
  28737. //
  28738. builder.context.radiance.addAssign( isolateRadiance );
  28739. builder.context.iblIrradiance.addAssign( isolateIrradiance );
  28740. //
  28741. const clearcoatRadiance = builder.context.lightingModel.clearcoatRadiance;
  28742. if ( clearcoatRadiance ) {
  28743. const clearcoatRadianceContext = envNode.context( createRadianceContext( clearcoatRoughness, transformedClearcoatNormalView ) ).mul( intensity );
  28744. const isolateClearcoatRadiance = cache( clearcoatRadianceContext );
  28745. clearcoatRadiance.addAssign( isolateClearcoatRadiance );
  28746. }
  28747. }
  28748. }
  28749. const createRadianceContext = ( roughnessNode, normalViewNode ) => {
  28750. let reflectVec = null;
  28751. return {
  28752. getUV: () => {
  28753. if ( reflectVec === null ) {
  28754. reflectVec = positionViewDirection.negate().reflect( normalViewNode );
  28755. // Mixing the reflection with the normal is more accurate and keeps rough objects from gathering light from behind their tangent plane.
  28756. reflectVec = roughnessNode.mul( roughnessNode ).mix( reflectVec, normalViewNode ).normalize();
  28757. reflectVec = reflectVec.transformDirection( cameraViewMatrix );
  28758. }
  28759. return reflectVec;
  28760. },
  28761. getTextureLevel: () => {
  28762. return roughnessNode;
  28763. }
  28764. };
  28765. };
  28766. const createIrradianceContext = ( normalWorldNode ) => {
  28767. return {
  28768. getUV: () => {
  28769. return normalWorldNode;
  28770. },
  28771. getTextureLevel: () => {
  28772. return float( 1.0 );
  28773. }
  28774. };
  28775. };
  28776. const _defaultValues$6 = /*@__PURE__*/ new MeshStandardMaterial();
  28777. class MeshStandardNodeMaterial extends NodeMaterial {
  28778. static get type() {
  28779. return 'MeshStandardNodeMaterial';
  28780. }
  28781. constructor( parameters ) {
  28782. super();
  28783. this.isMeshStandardNodeMaterial = true;
  28784. this.lights = true;
  28785. this.emissiveNode = null;
  28786. this.metalnessNode = null;
  28787. this.roughnessNode = null;
  28788. this.setDefaultValues( _defaultValues$6 );
  28789. this.setValues( parameters );
  28790. }
  28791. setupEnvironment( builder ) {
  28792. let envNode = super.setupEnvironment( builder );
  28793. if ( envNode === null && builder.environmentNode ) {
  28794. envNode = builder.environmentNode;
  28795. }
  28796. return envNode ? new EnvironmentNode( envNode ) : null;
  28797. }
  28798. setupLightingModel( /*builder*/ ) {
  28799. return new PhysicalLightingModel();
  28800. }
  28801. setupSpecular() {
  28802. const specularColorNode = mix( vec3( 0.04 ), diffuseColor.rgb, metalness );
  28803. specularColor.assign( specularColorNode );
  28804. specularF90.assign( 1.0 );
  28805. }
  28806. setupVariants() {
  28807. // METALNESS
  28808. const metalnessNode = this.metalnessNode ? float( this.metalnessNode ) : materialMetalness;
  28809. metalness.assign( metalnessNode );
  28810. // ROUGHNESS
  28811. let roughnessNode = this.roughnessNode ? float( this.roughnessNode ) : materialRoughness;
  28812. roughnessNode = getRoughness( { roughness: roughnessNode } );
  28813. roughness.assign( roughnessNode );
  28814. // SPECULAR COLOR
  28815. this.setupSpecular();
  28816. // DIFFUSE COLOR
  28817. diffuseColor.assign( vec4( diffuseColor.rgb.mul( metalnessNode.oneMinus() ), diffuseColor.a ) );
  28818. }
  28819. copy( source ) {
  28820. this.emissiveNode = source.emissiveNode;
  28821. this.metalnessNode = source.metalnessNode;
  28822. this.roughnessNode = source.roughnessNode;
  28823. return super.copy( source );
  28824. }
  28825. }
  28826. const _defaultValues$5 = /*@__PURE__*/ new MeshPhysicalMaterial();
  28827. class MeshPhysicalNodeMaterial extends MeshStandardNodeMaterial {
  28828. static get type() {
  28829. return 'MeshPhysicalNodeMaterial';
  28830. }
  28831. constructor( parameters ) {
  28832. super();
  28833. this.isMeshPhysicalNodeMaterial = true;
  28834. this.clearcoatNode = null;
  28835. this.clearcoatRoughnessNode = null;
  28836. this.clearcoatNormalNode = null;
  28837. this.sheenNode = null;
  28838. this.sheenRoughnessNode = null;
  28839. this.iridescenceNode = null;
  28840. this.iridescenceIORNode = null;
  28841. this.iridescenceThicknessNode = null;
  28842. this.specularIntensityNode = null;
  28843. this.specularColorNode = null;
  28844. this.iorNode = null;
  28845. this.transmissionNode = null;
  28846. this.thicknessNode = null;
  28847. this.attenuationDistanceNode = null;
  28848. this.attenuationColorNode = null;
  28849. this.dispersionNode = null;
  28850. this.anisotropyNode = null;
  28851. this.setDefaultValues( _defaultValues$5 );
  28852. this.setValues( parameters );
  28853. }
  28854. get useClearcoat() {
  28855. return this.clearcoat > 0 || this.clearcoatNode !== null;
  28856. }
  28857. get useIridescence() {
  28858. return this.iridescence > 0 || this.iridescenceNode !== null;
  28859. }
  28860. get useSheen() {
  28861. return this.sheen > 0 || this.sheenNode !== null;
  28862. }
  28863. get useAnisotropy() {
  28864. return this.anisotropy > 0 || this.anisotropyNode !== null;
  28865. }
  28866. get useTransmission() {
  28867. return this.transmission > 0 || this.transmissionNode !== null;
  28868. }
  28869. get useDispersion() {
  28870. return this.dispersion > 0 || this.dispersionNode !== null;
  28871. }
  28872. setupSpecular() {
  28873. const iorNode = this.iorNode ? float( this.iorNode ) : materialIOR;
  28874. ior.assign( iorNode );
  28875. specularColor.assign( mix( min$1( pow2( ior.sub( 1.0 ).div( ior.add( 1.0 ) ) ).mul( materialSpecularColor ), vec3( 1.0 ) ).mul( materialSpecularIntensity ), diffuseColor.rgb, metalness ) );
  28876. specularF90.assign( mix( materialSpecularIntensity, 1.0, metalness ) );
  28877. }
  28878. setupLightingModel( /*builder*/ ) {
  28879. return new PhysicalLightingModel( this.useClearcoat, this.useSheen, this.useIridescence, this.useAnisotropy, this.useTransmission, this.useDispersion );
  28880. }
  28881. setupVariants( builder ) {
  28882. super.setupVariants( builder );
  28883. // CLEARCOAT
  28884. if ( this.useClearcoat ) {
  28885. const clearcoatNode = this.clearcoatNode ? float( this.clearcoatNode ) : materialClearcoat;
  28886. const clearcoatRoughnessNode = this.clearcoatRoughnessNode ? float( this.clearcoatRoughnessNode ) : materialClearcoatRoughness;
  28887. clearcoat.assign( clearcoatNode );
  28888. clearcoatRoughness.assign( getRoughness( { roughness: clearcoatRoughnessNode } ) );
  28889. }
  28890. // SHEEN
  28891. if ( this.useSheen ) {
  28892. const sheenNode = this.sheenNode ? vec3( this.sheenNode ) : materialSheen;
  28893. const sheenRoughnessNode = this.sheenRoughnessNode ? float( this.sheenRoughnessNode ) : materialSheenRoughness;
  28894. sheen.assign( sheenNode );
  28895. sheenRoughness.assign( sheenRoughnessNode );
  28896. }
  28897. // IRIDESCENCE
  28898. if ( this.useIridescence ) {
  28899. const iridescenceNode = this.iridescenceNode ? float( this.iridescenceNode ) : materialIridescence;
  28900. const iridescenceIORNode = this.iridescenceIORNode ? float( this.iridescenceIORNode ) : materialIridescenceIOR;
  28901. const iridescenceThicknessNode = this.iridescenceThicknessNode ? float( this.iridescenceThicknessNode ) : materialIridescenceThickness;
  28902. iridescence.assign( iridescenceNode );
  28903. iridescenceIOR.assign( iridescenceIORNode );
  28904. iridescenceThickness.assign( iridescenceThicknessNode );
  28905. }
  28906. // ANISOTROPY
  28907. if ( this.useAnisotropy ) {
  28908. const anisotropyV = ( this.anisotropyNode ? vec2( this.anisotropyNode ) : materialAnisotropy ).toVar();
  28909. anisotropy.assign( anisotropyV.length() );
  28910. If( anisotropy.equal( 0.0 ), () => {
  28911. anisotropyV.assign( vec2( 1.0, 0.0 ) );
  28912. } ).Else( () => {
  28913. anisotropyV.divAssign( vec2( anisotropy ) );
  28914. anisotropy.assign( anisotropy.saturate() );
  28915. } );
  28916. // Roughness along the anisotropy bitangent is the material roughness, while the tangent roughness increases with anisotropy.
  28917. alphaT.assign( anisotropy.pow2().mix( roughness.pow2(), 1.0 ) );
  28918. anisotropyT.assign( TBNViewMatrix[ 0 ].mul( anisotropyV.x ).add( TBNViewMatrix[ 1 ].mul( anisotropyV.y ) ) );
  28919. anisotropyB.assign( TBNViewMatrix[ 1 ].mul( anisotropyV.x ).sub( TBNViewMatrix[ 0 ].mul( anisotropyV.y ) ) );
  28920. }
  28921. // TRANSMISSION
  28922. if ( this.useTransmission ) {
  28923. const transmissionNode = this.transmissionNode ? float( this.transmissionNode ) : materialTransmission;
  28924. const thicknessNode = this.thicknessNode ? float( this.thicknessNode ) : materialThickness;
  28925. const attenuationDistanceNode = this.attenuationDistanceNode ? float( this.attenuationDistanceNode ) : materialAttenuationDistance;
  28926. const attenuationColorNode = this.attenuationColorNode ? vec3( this.attenuationColorNode ) : materialAttenuationColor;
  28927. transmission.assign( transmissionNode );
  28928. thickness.assign( thicknessNode );
  28929. attenuationDistance.assign( attenuationDistanceNode );
  28930. attenuationColor.assign( attenuationColorNode );
  28931. if ( this.useDispersion ) {
  28932. const dispersionNode = this.dispersionNode ? float( this.dispersionNode ) : materialDispersion;
  28933. dispersion.assign( dispersionNode );
  28934. }
  28935. }
  28936. }
  28937. setupClearcoatNormal() {
  28938. return this.clearcoatNormalNode ? vec3( this.clearcoatNormalNode ) : materialClearcoatNormal;
  28939. }
  28940. setup( builder ) {
  28941. builder.context.setupClearcoatNormal = () => this.setupClearcoatNormal( builder );
  28942. super.setup( builder );
  28943. }
  28944. copy( source ) {
  28945. this.clearcoatNode = source.clearcoatNode;
  28946. this.clearcoatRoughnessNode = source.clearcoatRoughnessNode;
  28947. this.clearcoatNormalNode = source.clearcoatNormalNode;
  28948. this.sheenNode = source.sheenNode;
  28949. this.sheenRoughnessNode = source.sheenRoughnessNode;
  28950. this.iridescenceNode = source.iridescenceNode;
  28951. this.iridescenceIORNode = source.iridescenceIORNode;
  28952. this.iridescenceThicknessNode = source.iridescenceThicknessNode;
  28953. this.specularIntensityNode = source.specularIntensityNode;
  28954. this.specularColorNode = source.specularColorNode;
  28955. this.transmissionNode = source.transmissionNode;
  28956. this.thicknessNode = source.thicknessNode;
  28957. this.attenuationDistanceNode = source.attenuationDistanceNode;
  28958. this.attenuationColorNode = source.attenuationColorNode;
  28959. this.dispersionNode = source.dispersionNode;
  28960. this.anisotropyNode = source.anisotropyNode;
  28961. return super.copy( source );
  28962. }
  28963. }
  28964. class SSSLightingModel extends PhysicalLightingModel {
  28965. constructor( useClearcoat, useSheen, useIridescence, useSSS ) {
  28966. super( useClearcoat, useSheen, useIridescence );
  28967. this.useSSS = useSSS;
  28968. }
  28969. direct( { lightDirection, lightColor, reflectedLight }, stack, builder ) {
  28970. if ( this.useSSS === true ) {
  28971. const material = builder.material;
  28972. const { thicknessColorNode, thicknessDistortionNode, thicknessAmbientNode, thicknessAttenuationNode, thicknessPowerNode, thicknessScaleNode } = material;
  28973. const scatteringHalf = lightDirection.add( transformedNormalView.mul( thicknessDistortionNode ) ).normalize();
  28974. const scatteringDot = float( positionViewDirection.dot( scatteringHalf.negate() ).saturate().pow( thicknessPowerNode ).mul( thicknessScaleNode ) );
  28975. const scatteringIllu = vec3( scatteringDot.add( thicknessAmbientNode ).mul( thicknessColorNode ) );
  28976. reflectedLight.directDiffuse.addAssign( scatteringIllu.mul( thicknessAttenuationNode.mul( lightColor ) ) );
  28977. }
  28978. super.direct( { lightDirection, lightColor, reflectedLight }, stack, builder );
  28979. }
  28980. }
  28981. class MeshSSSNodeMaterial extends MeshPhysicalNodeMaterial {
  28982. static get type() {
  28983. return 'MeshSSSNodeMaterial';
  28984. }
  28985. constructor( parameters ) {
  28986. super( parameters );
  28987. this.thicknessColorNode = null;
  28988. this.thicknessDistortionNode = float( 0.1 );
  28989. this.thicknessAmbientNode = float( 0.0 );
  28990. this.thicknessAttenuationNode = float( .1 );
  28991. this.thicknessPowerNode = float( 2.0 );
  28992. this.thicknessScaleNode = float( 10.0 );
  28993. }
  28994. get useSSS() {
  28995. return this.thicknessColorNode !== null;
  28996. }
  28997. setupLightingModel( /*builder*/ ) {
  28998. return new SSSLightingModel( this.useClearcoat, this.useSheen, this.useIridescence, this.useSSS );
  28999. }
  29000. copy( source ) {
  29001. this.thicknessColorNode = source.thicknessColorNode;
  29002. this.thicknessDistortionNode = source.thicknessDistortionNode;
  29003. this.thicknessAmbientNode = source.thicknessAmbientNode;
  29004. this.thicknessAttenuationNode = source.thicknessAttenuationNode;
  29005. this.thicknessPowerNode = source.thicknessPowerNode;
  29006. this.thicknessScaleNode = source.thicknessScaleNode;
  29007. return super.copy( source );
  29008. }
  29009. }
  29010. const getGradientIrradiance = /*@__PURE__*/ Fn( ( { normal, lightDirection, builder } ) => {
  29011. // dotNL will be from -1.0 to 1.0
  29012. const dotNL = normal.dot( lightDirection );
  29013. const coord = vec2( dotNL.mul( 0.5 ).add( 0.5 ), 0.0 );
  29014. if ( builder.material.gradientMap ) {
  29015. const gradientMap = materialReference( 'gradientMap', 'texture' ).context( { getUV: () => coord } );
  29016. return vec3( gradientMap.r );
  29017. } else {
  29018. const fw = coord.fwidth().mul( 0.5 );
  29019. return mix( vec3( 0.7 ), vec3( 1.0 ), smoothstep( float( 0.7 ).sub( fw.x ), float( 0.7 ).add( fw.x ), coord.x ) );
  29020. }
  29021. } );
  29022. class ToonLightingModel extends LightingModel {
  29023. direct( { lightDirection, lightColor, reflectedLight }, stack, builder ) {
  29024. const irradiance = getGradientIrradiance( { normal: normalGeometry, lightDirection, builder } ).mul( lightColor );
  29025. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  29026. }
  29027. indirect( { ambientOcclusion, irradiance, reflectedLight } ) {
  29028. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  29029. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  29030. }
  29031. }
  29032. const _defaultValues$4 = /*@__PURE__*/ new MeshToonMaterial();
  29033. class MeshToonNodeMaterial extends NodeMaterial {
  29034. static get type() {
  29035. return 'MeshToonNodeMaterial';
  29036. }
  29037. constructor( parameters ) {
  29038. super();
  29039. this.isMeshToonNodeMaterial = true;
  29040. this.lights = true;
  29041. this.setDefaultValues( _defaultValues$4 );
  29042. this.setValues( parameters );
  29043. }
  29044. setupLightingModel( /*builder*/ ) {
  29045. return new ToonLightingModel();
  29046. }
  29047. }
  29048. class MatcapUVNode extends TempNode {
  29049. static get type() {
  29050. return 'MatcapUVNode';
  29051. }
  29052. constructor() {
  29053. super( 'vec2' );
  29054. }
  29055. setup() {
  29056. const x = vec3( positionViewDirection.z, 0, positionViewDirection.x.negate() ).normalize();
  29057. const y = positionViewDirection.cross( x );
  29058. return vec2( x.dot( transformedNormalView ), y.dot( transformedNormalView ) ).mul( 0.495 ).add( 0.5 ); // 0.495 to remove artifacts caused by undersized matcap disks
  29059. }
  29060. }
  29061. const matcapUV = /*@__PURE__*/ nodeImmutable( MatcapUVNode );
  29062. const _defaultValues$3 = /*@__PURE__*/ new MeshMatcapMaterial();
  29063. class MeshMatcapNodeMaterial extends NodeMaterial {
  29064. static get type() {
  29065. return 'MeshMatcapNodeMaterial';
  29066. }
  29067. constructor( parameters ) {
  29068. super();
  29069. this.lights = false;
  29070. this.isMeshMatcapNodeMaterial = true;
  29071. this.setDefaultValues( _defaultValues$3 );
  29072. this.setValues( parameters );
  29073. }
  29074. setupVariants( builder ) {
  29075. const uv = matcapUV;
  29076. let matcapColor;
  29077. if ( builder.material.matcap ) {
  29078. matcapColor = materialReference( 'matcap', 'texture' ).context( { getUV: () => uv } );
  29079. } else {
  29080. matcapColor = vec3( mix( 0.2, 0.8, uv.y ) ); // default if matcap is missing
  29081. }
  29082. diffuseColor.rgb.mulAssign( matcapColor.rgb );
  29083. }
  29084. }
  29085. const _defaultValues$2 = /*@__PURE__*/ new PointsMaterial();
  29086. class PointsNodeMaterial extends NodeMaterial {
  29087. static get type() {
  29088. return 'PointsNodeMaterial';
  29089. }
  29090. constructor( parameters ) {
  29091. super();
  29092. this.isPointsNodeMaterial = true;
  29093. this.lights = false;
  29094. this.transparent = true;
  29095. this.sizeNode = null;
  29096. this.setDefaultValues( _defaultValues$2 );
  29097. this.setValues( parameters );
  29098. }
  29099. copy( source ) {
  29100. this.sizeNode = source.sizeNode;
  29101. return super.copy( source );
  29102. }
  29103. }
  29104. class RotateNode extends TempNode {
  29105. static get type() {
  29106. return 'RotateNode';
  29107. }
  29108. constructor( positionNode, rotationNode ) {
  29109. super();
  29110. this.positionNode = positionNode;
  29111. this.rotationNode = rotationNode;
  29112. }
  29113. getNodeType( builder ) {
  29114. return this.positionNode.getNodeType( builder );
  29115. }
  29116. setup( builder ) {
  29117. const { rotationNode, positionNode } = this;
  29118. const nodeType = this.getNodeType( builder );
  29119. if ( nodeType === 'vec2' ) {
  29120. const cosAngle = rotationNode.cos();
  29121. const sinAngle = rotationNode.sin();
  29122. const rotationMatrix = mat2(
  29123. cosAngle, sinAngle,
  29124. sinAngle.negate(), cosAngle
  29125. );
  29126. return rotationMatrix.mul( positionNode );
  29127. } else {
  29128. const rotation = rotationNode;
  29129. const rotationXMatrix = mat4( vec4( 1.0, 0.0, 0.0, 0.0 ), vec4( 0.0, cos( rotation.x ), sin( rotation.x ).negate(), 0.0 ), vec4( 0.0, sin( rotation.x ), cos( rotation.x ), 0.0 ), vec4( 0.0, 0.0, 0.0, 1.0 ) );
  29130. const rotationYMatrix = mat4( vec4( cos( rotation.y ), 0.0, sin( rotation.y ), 0.0 ), vec4( 0.0, 1.0, 0.0, 0.0 ), vec4( sin( rotation.y ).negate(), 0.0, cos( rotation.y ), 0.0 ), vec4( 0.0, 0.0, 0.0, 1.0 ) );
  29131. const rotationZMatrix = mat4( vec4( cos( rotation.z ), sin( rotation.z ).negate(), 0.0, 0.0 ), vec4( sin( rotation.z ), cos( rotation.z ), 0.0, 0.0 ), vec4( 0.0, 0.0, 1.0, 0.0 ), vec4( 0.0, 0.0, 0.0, 1.0 ) );
  29132. return rotationXMatrix.mul( rotationYMatrix ).mul( rotationZMatrix ).mul( vec4( positionNode, 1.0 ) ).xyz;
  29133. }
  29134. }
  29135. }
  29136. const rotate = /*@__PURE__*/ nodeProxy( RotateNode );
  29137. const _defaultValues$1 = /*@__PURE__*/ new SpriteMaterial();
  29138. class SpriteNodeMaterial extends NodeMaterial {
  29139. static get type() {
  29140. return 'SpriteNodeMaterial';
  29141. }
  29142. constructor( parameters ) {
  29143. super();
  29144. this.isSpriteNodeMaterial = true;
  29145. this.lights = false;
  29146. this._useSizeAttenuation = true;
  29147. this.positionNode = null;
  29148. this.rotationNode = null;
  29149. this.scaleNode = null;
  29150. this.setDefaultValues( _defaultValues$1 );
  29151. this.setValues( parameters );
  29152. }
  29153. setupPosition( { object, camera, context } ) {
  29154. const sizeAttenuation = this.sizeAttenuation;
  29155. // < VERTEX STAGE >
  29156. const { positionNode, rotationNode, scaleNode } = this;
  29157. const vertex = positionLocal;
  29158. let mvPosition = modelViewMatrix.mul( vec3( positionNode || 0 ) );
  29159. let scale = vec2( modelWorldMatrix[ 0 ].xyz.length(), modelWorldMatrix[ 1 ].xyz.length() );
  29160. if ( scaleNode !== null ) {
  29161. scale = scale.mul( scaleNode );
  29162. }
  29163. if ( ! sizeAttenuation ) {
  29164. if ( camera.isPerspectiveCamera ) {
  29165. scale = scale.mul( mvPosition.z.negate() );
  29166. } else {
  29167. const orthoScale = float( 2.0 ).div( cameraProjectionMatrix.element( 1 ).element( 1 ) );
  29168. scale = scale.mul( orthoScale.mul( 2 ) );
  29169. }
  29170. }
  29171. let alignedPosition = vertex.xy;
  29172. if ( object.center && object.center.isVector2 === true ) {
  29173. const center = reference$1( 'center', 'vec2' );
  29174. alignedPosition = alignedPosition.sub( center.sub( 0.5 ) );
  29175. }
  29176. alignedPosition = alignedPosition.mul( scale );
  29177. const rotation = float( rotationNode || materialRotation );
  29178. const rotatedPosition = rotate( alignedPosition, rotation );
  29179. mvPosition = vec4( mvPosition.xy.add( rotatedPosition ), mvPosition.zw );
  29180. const modelViewProjection = cameraProjectionMatrix.mul( mvPosition );
  29181. context.vertex = vertex;
  29182. return modelViewProjection;
  29183. }
  29184. copy( source ) {
  29185. this.positionNode = source.positionNode;
  29186. this.rotationNode = source.rotationNode;
  29187. this.scaleNode = source.scaleNode;
  29188. return super.copy( source );
  29189. }
  29190. get sizeAttenuation() {
  29191. return this._useSizeAttenuation;
  29192. }
  29193. set sizeAttenuation( value ) {
  29194. if ( this._useSizeAttenuation !== value ) {
  29195. this._useSizeAttenuation = value;
  29196. this.needsUpdate = true;
  29197. }
  29198. }
  29199. }
  29200. class ShadowMaskModel extends LightingModel {
  29201. constructor() {
  29202. super();
  29203. this.shadowNode = float( 1 ).toVar( 'shadowMask' );
  29204. }
  29205. direct( { shadowMask } ) {
  29206. this.shadowNode.mulAssign( shadowMask );
  29207. }
  29208. finish( context ) {
  29209. diffuseColor.a.mulAssign( this.shadowNode.oneMinus() );
  29210. context.outgoingLight.rgb.assign( diffuseColor.rgb ); // TODO: Optimize LightsNode to avoid this assignment
  29211. }
  29212. }
  29213. const _defaultValues = /*@__PURE__*/ new ShadowMaterial();
  29214. class ShadowNodeMaterial extends NodeMaterial {
  29215. static get type() {
  29216. return 'ShadowNodeMaterial';
  29217. }
  29218. constructor( parameters ) {
  29219. super();
  29220. this.isShadowNodeMaterial = true;
  29221. this.lights = true;
  29222. this.setDefaultValues( _defaultValues );
  29223. this.setValues( parameters );
  29224. }
  29225. setupLightingModel( /*builder*/ ) {
  29226. return new ShadowMaskModel();
  29227. }
  29228. }
  29229. const normal = Fn( ( { texture, uv } ) => {
  29230. const epsilon = 0.0001;
  29231. const ret = vec3().toVar();
  29232. If( uv.x.lessThan( epsilon ), () => {
  29233. ret.assign( vec3( 1, 0, 0 ) );
  29234. } ).ElseIf( uv.y.lessThan( epsilon ), () => {
  29235. ret.assign( vec3( 0, 1, 0 ) );
  29236. } ).ElseIf( uv.z.lessThan( epsilon ), () => {
  29237. ret.assign( vec3( 0, 0, 1 ) );
  29238. } ).ElseIf( uv.x.greaterThan( 1 - epsilon ), () => {
  29239. ret.assign( vec3( - 1, 0, 0 ) );
  29240. } ).ElseIf( uv.y.greaterThan( 1 - epsilon ), () => {
  29241. ret.assign( vec3( 0, - 1, 0 ) );
  29242. } ).ElseIf( uv.z.greaterThan( 1 - epsilon ), () => {
  29243. ret.assign( vec3( 0, 0, - 1 ) );
  29244. } ).Else( () => {
  29245. const step = 0.01;
  29246. const x = texture.uv( uv.add( vec3( - step, 0.0, 0.0 ) ) ).r.sub( texture.uv( uv.add( vec3( step, 0.0, 0.0 ) ) ).r );
  29247. const y = texture.uv( uv.add( vec3( 0.0, - step, 0.0 ) ) ).r.sub( texture.uv( uv.add( vec3( 0.0, step, 0.0 ) ) ).r );
  29248. const z = texture.uv( uv.add( vec3( 0.0, 0.0, - step ) ) ).r.sub( texture.uv( uv.add( vec3( 0.0, 0.0, step ) ) ).r );
  29249. ret.assign( vec3( x, y, z ) );
  29250. } );
  29251. return ret.normalize();
  29252. } );
  29253. class Texture3DNode extends TextureNode {
  29254. static get type() {
  29255. return 'Texture3DNode';
  29256. }
  29257. constructor( value, uvNode = null, levelNode = null ) {
  29258. super( value, uvNode, levelNode );
  29259. this.isTexture3DNode = true;
  29260. }
  29261. getInputType( /*builder*/ ) {
  29262. return 'texture3D';
  29263. }
  29264. getDefaultUV() {
  29265. return vec3( 0.5, 0.5, 0.5 );
  29266. }
  29267. setUpdateMatrix( /*updateMatrix*/ ) { } // Ignore .updateMatrix for 3d TextureNode
  29268. setupUV( builder, uvNode ) {
  29269. return uvNode;
  29270. }
  29271. generateUV( builder, uvNode ) {
  29272. return uvNode.build( builder, 'vec3' );
  29273. }
  29274. normal( uvNode ) {
  29275. return normal( { texture: this, uv: uvNode } );
  29276. }
  29277. }
  29278. const texture3D = /*@__PURE__*/ nodeProxy( Texture3DNode );
  29279. class VolumeNodeMaterial extends NodeMaterial {
  29280. static get type() {
  29281. return 'VolumeNodeMaterial';
  29282. }
  29283. constructor( params = {} ) {
  29284. super();
  29285. this.lights = false;
  29286. this.isVolumeNodeMaterial = true;
  29287. this.testNode = null;
  29288. this.setValues( params );
  29289. }
  29290. setup( builder ) {
  29291. const map = texture3D( this.map, null, 0 );
  29292. const hitBox = Fn( ( { orig, dir } ) => {
  29293. const box_min = vec3( - 0.5 );
  29294. const box_max = vec3( 0.5 );
  29295. const inv_dir = dir.reciprocal();
  29296. const tmin_tmp = box_min.sub( orig ).mul( inv_dir );
  29297. const tmax_tmp = box_max.sub( orig ).mul( inv_dir );
  29298. const tmin = min$1( tmin_tmp, tmax_tmp );
  29299. const tmax = max$1( tmin_tmp, tmax_tmp );
  29300. const t0 = max$1( tmin.x, max$1( tmin.y, tmin.z ) );
  29301. const t1 = min$1( tmax.x, min$1( tmax.y, tmax.z ) );
  29302. return vec2( t0, t1 );
  29303. } );
  29304. this.fragmentNode = Fn( () => {
  29305. const vOrigin = varying( vec3( modelWorldMatrixInverse.mul( vec4( cameraPosition, 1.0 ) ) ) );
  29306. const vDirection = varying( positionGeometry.sub( vOrigin ) );
  29307. const rayDir = vDirection.normalize();
  29308. const bounds = vec2( hitBox( { orig: vOrigin, dir: rayDir } ) ).toVar();
  29309. bounds.x.greaterThan( bounds.y ).discard();
  29310. bounds.assign( vec2( max$1( bounds.x, 0.0 ), bounds.y ) );
  29311. const p = vec3( vOrigin.add( bounds.x.mul( rayDir ) ) ).toVar();
  29312. const inc = vec3( rayDir.abs().reciprocal() ).toVar();
  29313. const delta = float( min$1( inc.x, min$1( inc.y, inc.z ) ) ).toVar( 'delta' ); // used 'delta' name in loop
  29314. delta.divAssign( materialReference( 'steps', 'float' ) );
  29315. const ac = vec4( materialReference( 'base', 'color' ), 0.0 ).toVar();
  29316. Loop( { type: 'float', start: bounds.x, end: bounds.y, update: '+= delta' }, () => {
  29317. const d = property( 'float', 'd' ).assign( map.uv( p.add( 0.5 ) ).r );
  29318. if ( this.testNode !== null ) {
  29319. this.testNode( { map: map, mapValue: d, probe: p, finalColor: ac } ).append();
  29320. } else {
  29321. // default to show surface of mesh
  29322. ac.a.assign( 1 );
  29323. Break();
  29324. }
  29325. p.addAssign( rayDir.mul( delta ) );
  29326. } );
  29327. ac.a.equal( 0 ).discard();
  29328. return vec4( ac );
  29329. } )();
  29330. super.setup( builder );
  29331. }
  29332. }
  29333. class Animation {
  29334. constructor( nodes, info ) {
  29335. this.nodes = nodes;
  29336. this.info = info;
  29337. this.animationLoop = null;
  29338. this.requestId = null;
  29339. this._init();
  29340. }
  29341. _init() {
  29342. const update = ( time, frame ) => {
  29343. this.requestId = self.requestAnimationFrame( update );
  29344. if ( this.info.autoReset === true ) this.info.reset();
  29345. this.nodes.nodeFrame.update();
  29346. this.info.frame = this.nodes.nodeFrame.frameId;
  29347. if ( this.animationLoop !== null ) this.animationLoop( time, frame );
  29348. };
  29349. update();
  29350. }
  29351. dispose() {
  29352. self.cancelAnimationFrame( this.requestId );
  29353. this.requestId = null;
  29354. }
  29355. setAnimationLoop( callback ) {
  29356. this.animationLoop = callback;
  29357. }
  29358. }
  29359. class ChainMap {
  29360. constructor() {
  29361. this.weakMap = new WeakMap();
  29362. }
  29363. get( keys ) {
  29364. let map = this.weakMap;
  29365. for ( let i = 0; i < keys.length; i ++ ) {
  29366. map = map.get( keys[ i ] );
  29367. if ( map === undefined ) return undefined;
  29368. }
  29369. return map.get( keys[ keys.length - 1 ] );
  29370. }
  29371. set( keys, value ) {
  29372. let map = this.weakMap;
  29373. for ( let i = 0; i < keys.length; i ++ ) {
  29374. const key = keys[ i ];
  29375. if ( map.has( key ) === false ) map.set( key, new WeakMap() );
  29376. map = map.get( key );
  29377. }
  29378. return map.set( keys[ keys.length - 1 ], value );
  29379. }
  29380. delete( keys ) {
  29381. let map = this.weakMap;
  29382. for ( let i = 0; i < keys.length; i ++ ) {
  29383. map = map.get( keys[ i ] );
  29384. if ( map === undefined ) return false;
  29385. }
  29386. return map.delete( keys[ keys.length - 1 ] );
  29387. }
  29388. }
  29389. const _plane = /*@__PURE__*/ new Plane();
  29390. class ClippingContext {
  29391. constructor() {
  29392. this.version = 0;
  29393. this.globalClippingCount = 0;
  29394. this.localClippingCount = 0;
  29395. this.localClippingEnabled = false;
  29396. this.localClipIntersection = false;
  29397. this.planes = [];
  29398. this.parentVersion = 0;
  29399. this.viewNormalMatrix = new Matrix3();
  29400. this.cacheKey = 0;
  29401. }
  29402. projectPlanes( source, offset ) {
  29403. const l = source.length;
  29404. const planes = this.planes;
  29405. for ( let i = 0; i < l; i ++ ) {
  29406. _plane.copy( source[ i ] ).applyMatrix4( this.viewMatrix, this.viewNormalMatrix );
  29407. const v = planes[ offset + i ];
  29408. const normal = _plane.normal;
  29409. v.x = - normal.x;
  29410. v.y = - normal.y;
  29411. v.z = - normal.z;
  29412. v.w = _plane.constant;
  29413. }
  29414. }
  29415. updateGlobal( renderer, camera ) {
  29416. const rendererClippingPlanes = renderer.clippingPlanes;
  29417. this.viewMatrix = camera.matrixWorldInverse;
  29418. this.viewNormalMatrix.getNormalMatrix( this.viewMatrix );
  29419. let update = false;
  29420. if ( Array.isArray( rendererClippingPlanes ) && rendererClippingPlanes.length !== 0 ) {
  29421. const l = rendererClippingPlanes.length;
  29422. if ( l !== this.globalClippingCount ) {
  29423. const planes = [];
  29424. for ( let i = 0; i < l; i ++ ) {
  29425. planes.push( new Vector4() );
  29426. }
  29427. this.globalClippingCount = l;
  29428. this.planes = planes;
  29429. update = true;
  29430. }
  29431. this.projectPlanes( rendererClippingPlanes, 0 );
  29432. } else if ( this.globalClippingCount !== 0 ) {
  29433. this.globalClippingCount = 0;
  29434. this.planes = [];
  29435. update = true;
  29436. }
  29437. if ( renderer.localClippingEnabled !== this.localClippingEnabled ) {
  29438. this.localClippingEnabled = renderer.localClippingEnabled;
  29439. update = true;
  29440. }
  29441. if ( update ) {
  29442. this.version ++;
  29443. this.cacheKey = hash$1( this.globalClippingCount, this.localClippingEnabled === true ? 1 : 0 );
  29444. }
  29445. }
  29446. update( parent, material ) {
  29447. let update = false;
  29448. if ( this !== parent && parent.version !== this.parentVersion ) {
  29449. this.globalClippingCount = material.isShadowNodeMaterial ? 0 : parent.globalClippingCount;
  29450. this.localClippingEnabled = parent.localClippingEnabled;
  29451. this.planes = Array.from( parent.planes );
  29452. this.parentVersion = parent.version;
  29453. this.viewMatrix = parent.viewMatrix;
  29454. this.viewNormalMatrix = parent.viewNormalMatrix;
  29455. update = true;
  29456. }
  29457. if ( this.localClippingEnabled ) {
  29458. const localClippingPlanes = material.clippingPlanes;
  29459. if ( ( Array.isArray( localClippingPlanes ) && localClippingPlanes.length !== 0 ) ) {
  29460. const l = localClippingPlanes.length;
  29461. const planes = this.planes;
  29462. const offset = this.globalClippingCount;
  29463. if ( update || l !== this.localClippingCount ) {
  29464. planes.length = offset + l;
  29465. for ( let i = 0; i < l; i ++ ) {
  29466. planes[ offset + i ] = new Vector4();
  29467. }
  29468. this.localClippingCount = l;
  29469. update = true;
  29470. }
  29471. this.projectPlanes( localClippingPlanes, offset );
  29472. } else if ( this.localClippingCount !== 0 ) {
  29473. this.localClippingCount = 0;
  29474. update = true;
  29475. }
  29476. if ( this.localClipIntersection !== material.clipIntersection ) {
  29477. this.localClipIntersection = material.clipIntersection;
  29478. update = true;
  29479. }
  29480. }
  29481. if ( update ) {
  29482. this.version += parent.version;
  29483. this.cacheKey = hash$1( parent.cacheKey, this.localClippingCount, this.localClipIntersection === true ? 1 : 0 );
  29484. }
  29485. }
  29486. }
  29487. let _id$7 = 0;
  29488. function getKeys( obj ) {
  29489. const keys = Object.keys( obj );
  29490. let proto = Object.getPrototypeOf( obj );
  29491. while ( proto ) {
  29492. const descriptors = Object.getOwnPropertyDescriptors( proto );
  29493. for ( const key in descriptors ) {
  29494. if ( descriptors[ key ] !== undefined ) {
  29495. const descriptor = descriptors[ key ];
  29496. if ( descriptor && typeof descriptor.get === 'function' ) {
  29497. keys.push( key );
  29498. }
  29499. }
  29500. }
  29501. proto = Object.getPrototypeOf( proto );
  29502. }
  29503. return keys;
  29504. }
  29505. class RenderObject {
  29506. constructor( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext ) {
  29507. this._nodes = nodes;
  29508. this._geometries = geometries;
  29509. this.id = _id$7 ++;
  29510. this.renderer = renderer;
  29511. this.object = object;
  29512. this.material = material;
  29513. this.scene = scene;
  29514. this.camera = camera;
  29515. this.lightsNode = lightsNode;
  29516. this.context = renderContext;
  29517. this.geometry = object.geometry;
  29518. this.version = material.version;
  29519. this.drawRange = null;
  29520. this.attributes = null;
  29521. this.pipeline = null;
  29522. this.vertexBuffers = null;
  29523. this.drawParams = null;
  29524. this.bundle = null;
  29525. this.updateClipping( renderContext.clippingContext );
  29526. this.clippingContextVersion = this.clippingContext.version;
  29527. this.initialNodesCacheKey = this.getDynamicCacheKey();
  29528. this.initialCacheKey = this.getCacheKey();
  29529. this._nodeBuilderState = null;
  29530. this._bindings = null;
  29531. this._monitor = null;
  29532. this.onDispose = null;
  29533. this.isRenderObject = true;
  29534. this.onMaterialDispose = () => {
  29535. this.dispose();
  29536. };
  29537. this.material.addEventListener( 'dispose', this.onMaterialDispose );
  29538. }
  29539. updateClipping( parent ) {
  29540. const material = this.material;
  29541. let clippingContext = this.clippingContext;
  29542. if ( Array.isArray( material.clippingPlanes ) ) {
  29543. if ( clippingContext === parent || ! clippingContext ) {
  29544. clippingContext = new ClippingContext();
  29545. this.clippingContext = clippingContext;
  29546. }
  29547. clippingContext.update( parent, material );
  29548. } else if ( this.clippingContext !== parent ) {
  29549. this.clippingContext = parent;
  29550. }
  29551. }
  29552. get clippingNeedsUpdate() {
  29553. if ( this.clippingContext.version === this.clippingContextVersion ) return false;
  29554. this.clippingContextVersion = this.clippingContext.version;
  29555. return true;
  29556. }
  29557. getNodeBuilderState() {
  29558. return this._nodeBuilderState || ( this._nodeBuilderState = this._nodes.getForRender( this ) );
  29559. }
  29560. getMonitor() {
  29561. return this._monitor || ( this._monitor = this.getNodeBuilderState().monitor );
  29562. }
  29563. getBindings() {
  29564. return this._bindings || ( this._bindings = this.getNodeBuilderState().createBindings() );
  29565. }
  29566. getIndex() {
  29567. return this._geometries.getIndex( this );
  29568. }
  29569. getIndirect() {
  29570. return this._geometries.getIndirect( this );
  29571. }
  29572. getChainArray() {
  29573. return [ this.object, this.material, this.context, this.lightsNode ];
  29574. }
  29575. getAttributes() {
  29576. if ( this.attributes !== null ) return this.attributes;
  29577. const nodeAttributes = this.getNodeBuilderState().nodeAttributes;
  29578. const geometry = this.geometry;
  29579. const attributes = [];
  29580. const vertexBuffers = new Set();
  29581. for ( const nodeAttribute of nodeAttributes ) {
  29582. const attribute = nodeAttribute.node && nodeAttribute.node.attribute ? nodeAttribute.node.attribute : geometry.getAttribute( nodeAttribute.name );
  29583. if ( attribute === undefined ) continue;
  29584. attributes.push( attribute );
  29585. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  29586. vertexBuffers.add( bufferAttribute );
  29587. }
  29588. this.attributes = attributes;
  29589. this.vertexBuffers = Array.from( vertexBuffers.values() );
  29590. return attributes;
  29591. }
  29592. getVertexBuffers() {
  29593. if ( this.vertexBuffers === null ) this.getAttributes();
  29594. return this.vertexBuffers;
  29595. }
  29596. getDrawParameters() {
  29597. const { object, material, geometry, group, drawRange } = this;
  29598. const drawParams = this.drawParams || ( this.drawParams = {
  29599. vertexCount: 0,
  29600. firstVertex: 0,
  29601. instanceCount: 0,
  29602. firstInstance: 0
  29603. } );
  29604. const index = this.getIndex();
  29605. const hasIndex = ( index !== null );
  29606. const instanceCount = geometry.isInstancedBufferGeometry ? geometry.instanceCount : ( object.count > 1 ? object.count : 1 );
  29607. if ( instanceCount === 0 ) return null;
  29608. drawParams.instanceCount = instanceCount;
  29609. if ( object.isBatchedMesh === true ) return drawParams;
  29610. let rangeFactor = 1;
  29611. if ( material.wireframe === true && ! object.isPoints && ! object.isLineSegments && ! object.isLine && ! object.isLineLoop ) {
  29612. rangeFactor = 2;
  29613. }
  29614. let firstVertex = drawRange.start * rangeFactor;
  29615. let lastVertex = ( drawRange.start + drawRange.count ) * rangeFactor;
  29616. if ( group !== null ) {
  29617. firstVertex = Math.max( firstVertex, group.start * rangeFactor );
  29618. lastVertex = Math.min( lastVertex, ( group.start + group.count ) * rangeFactor );
  29619. }
  29620. const position = geometry.attributes.position;
  29621. let itemCount = Infinity;
  29622. if ( hasIndex ) {
  29623. itemCount = index.count;
  29624. } else if ( position !== undefined && position !== null ) {
  29625. itemCount = position.count;
  29626. }
  29627. firstVertex = Math.max( firstVertex, 0 );
  29628. lastVertex = Math.min( lastVertex, itemCount );
  29629. const count = lastVertex - firstVertex;
  29630. if ( count < 0 || count === Infinity ) return null;
  29631. drawParams.vertexCount = count;
  29632. drawParams.firstVertex = firstVertex;
  29633. return drawParams;
  29634. }
  29635. getGeometryCacheKey() {
  29636. const { geometry } = this;
  29637. let cacheKey = '';
  29638. for ( const name of Object.keys( geometry.attributes ).sort() ) {
  29639. const attribute = geometry.attributes[ name ];
  29640. cacheKey += name + ',';
  29641. if ( attribute.data ) cacheKey += attribute.data.stride + ',';
  29642. if ( attribute.offset ) cacheKey += attribute.offset + ',';
  29643. if ( attribute.itemSize ) cacheKey += attribute.itemSize + ',';
  29644. if ( attribute.normalized ) cacheKey += 'n,';
  29645. }
  29646. if ( geometry.index ) {
  29647. cacheKey += 'index,';
  29648. }
  29649. return cacheKey;
  29650. }
  29651. getMaterialCacheKey() {
  29652. const { object, material } = this;
  29653. let cacheKey = material.customProgramCacheKey();
  29654. for ( const property of getKeys( material ) ) {
  29655. if ( /^(is[A-Z]|_)|^(visible|version|uuid|name|opacity|userData)$/.test( property ) ) continue;
  29656. const value = material[ property ];
  29657. let valueKey;
  29658. if ( value !== null ) {
  29659. // some material values require a formatting
  29660. const type = typeof value;
  29661. if ( type === 'number' ) {
  29662. valueKey = value !== 0 ? '1' : '0'; // Convert to on/off, important for clearcoat, transmission, etc
  29663. } else if ( type === 'object' ) {
  29664. valueKey = '{';
  29665. if ( value.isTexture ) {
  29666. valueKey += value.mapping;
  29667. }
  29668. valueKey += '}';
  29669. } else {
  29670. valueKey = String( value );
  29671. }
  29672. } else {
  29673. valueKey = String( value );
  29674. }
  29675. cacheKey += /*property + ':' +*/ valueKey + ',';
  29676. }
  29677. cacheKey += this.clippingContext.cacheKey + ',';
  29678. if ( object.geometry ) {
  29679. cacheKey += this.getGeometryCacheKey();
  29680. }
  29681. if ( object.skeleton ) {
  29682. cacheKey += object.skeleton.bones.length + ',';
  29683. }
  29684. if ( object.morphTargetInfluences ) {
  29685. cacheKey += object.morphTargetInfluences.length + ',';
  29686. }
  29687. if ( object.isBatchedMesh ) {
  29688. cacheKey += object._matricesTexture.uuid + ',';
  29689. if ( object._colorsTexture !== null ) {
  29690. cacheKey += object._colorsTexture.uuid + ',';
  29691. }
  29692. }
  29693. if ( object.count > 1 ) {
  29694. // TODO: https://github.com/mrdoob/three.js/pull/29066#issuecomment-2269400850
  29695. cacheKey += object.uuid + ',';
  29696. }
  29697. return hashString( cacheKey );
  29698. }
  29699. get needsUpdate() {
  29700. return /*this.object.static !== true &&*/ ( this.initialNodesCacheKey !== this.getDynamicCacheKey() || this.clippingNeedsUpdate );
  29701. }
  29702. getDynamicCacheKey() {
  29703. // Environment Nodes Cache Key
  29704. let cacheKey = this._nodes.getCacheKey( this.scene, this.lightsNode );
  29705. if ( this.object.receiveShadow ) {
  29706. cacheKey += 1;
  29707. }
  29708. return cacheKey;
  29709. }
  29710. getCacheKey() {
  29711. return this.getMaterialCacheKey() + this.getDynamicCacheKey();
  29712. }
  29713. dispose() {
  29714. this.material.removeEventListener( 'dispose', this.onMaterialDispose );
  29715. this.onDispose();
  29716. }
  29717. }
  29718. const chainArray = [];
  29719. class RenderObjects {
  29720. constructor( renderer, nodes, geometries, pipelines, bindings, info ) {
  29721. this.renderer = renderer;
  29722. this.nodes = nodes;
  29723. this.geometries = geometries;
  29724. this.pipelines = pipelines;
  29725. this.bindings = bindings;
  29726. this.info = info;
  29727. this.chainMaps = {};
  29728. }
  29729. get( object, material, scene, camera, lightsNode, renderContext, passId ) {
  29730. const chainMap = this.getChainMap( passId );
  29731. // reuse chainArray
  29732. chainArray[ 0 ] = object;
  29733. chainArray[ 1 ] = material;
  29734. chainArray[ 2 ] = renderContext;
  29735. chainArray[ 3 ] = lightsNode;
  29736. let renderObject = chainMap.get( chainArray );
  29737. if ( renderObject === undefined ) {
  29738. renderObject = this.createRenderObject( this.nodes, this.geometries, this.renderer, object, material, scene, camera, lightsNode, renderContext, passId );
  29739. chainMap.set( chainArray, renderObject );
  29740. } else {
  29741. renderObject.updateClipping( renderContext.clippingContext );
  29742. if ( renderObject.version !== material.version || renderObject.needsUpdate ) {
  29743. if ( renderObject.initialCacheKey !== renderObject.getCacheKey() ) {
  29744. renderObject.dispose();
  29745. renderObject = this.get( object, material, scene, camera, lightsNode, renderContext, passId );
  29746. } else {
  29747. renderObject.version = material.version;
  29748. }
  29749. }
  29750. }
  29751. return renderObject;
  29752. }
  29753. getChainMap( passId = 'default' ) {
  29754. return this.chainMaps[ passId ] || ( this.chainMaps[ passId ] = new ChainMap() );
  29755. }
  29756. dispose() {
  29757. this.chainMaps = {};
  29758. }
  29759. createRenderObject( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext, passId ) {
  29760. const chainMap = this.getChainMap( passId );
  29761. const renderObject = new RenderObject( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext );
  29762. renderObject.onDispose = () => {
  29763. this.pipelines.delete( renderObject );
  29764. this.bindings.delete( renderObject );
  29765. this.nodes.delete( renderObject );
  29766. chainMap.delete( renderObject.getChainArray() );
  29767. };
  29768. return renderObject;
  29769. }
  29770. }
  29771. class DataMap {
  29772. constructor() {
  29773. this.data = new WeakMap();
  29774. }
  29775. get( object ) {
  29776. let map = this.data.get( object );
  29777. if ( map === undefined ) {
  29778. map = {};
  29779. this.data.set( object, map );
  29780. }
  29781. return map;
  29782. }
  29783. delete( object ) {
  29784. let map;
  29785. if ( this.data.has( object ) ) {
  29786. map = this.data.get( object );
  29787. this.data.delete( object );
  29788. }
  29789. return map;
  29790. }
  29791. has( object ) {
  29792. return this.data.has( object );
  29793. }
  29794. dispose() {
  29795. this.data = new WeakMap();
  29796. }
  29797. }
  29798. const AttributeType = {
  29799. VERTEX: 1,
  29800. INDEX: 2,
  29801. STORAGE: 3,
  29802. INDIRECT: 4
  29803. };
  29804. // size of a chunk in bytes (STD140 layout)
  29805. const GPU_CHUNK_BYTES = 16;
  29806. // @TODO: Move to src/constants.js
  29807. const BlendColorFactor = 211;
  29808. const OneMinusBlendColorFactor = 212;
  29809. class Attributes extends DataMap {
  29810. constructor( backend ) {
  29811. super();
  29812. this.backend = backend;
  29813. }
  29814. delete( attribute ) {
  29815. const attributeData = super.delete( attribute );
  29816. if ( attributeData !== undefined ) {
  29817. this.backend.destroyAttribute( attribute );
  29818. }
  29819. return attributeData;
  29820. }
  29821. update( attribute, type ) {
  29822. const data = this.get( attribute );
  29823. if ( data.version === undefined ) {
  29824. if ( type === AttributeType.VERTEX ) {
  29825. this.backend.createAttribute( attribute );
  29826. } else if ( type === AttributeType.INDEX ) {
  29827. this.backend.createIndexAttribute( attribute );
  29828. } else if ( type === AttributeType.STORAGE ) {
  29829. this.backend.createStorageAttribute( attribute );
  29830. } else if ( type === AttributeType.INDIRECT ) {
  29831. this.backend.createIndirectStorageAttribute( attribute );
  29832. }
  29833. data.version = this._getBufferAttribute( attribute ).version;
  29834. } else {
  29835. const bufferAttribute = this._getBufferAttribute( attribute );
  29836. if ( data.version < bufferAttribute.version || bufferAttribute.usage === DynamicDrawUsage ) {
  29837. this.backend.updateAttribute( attribute );
  29838. data.version = bufferAttribute.version;
  29839. }
  29840. }
  29841. }
  29842. _getBufferAttribute( attribute ) {
  29843. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  29844. return attribute;
  29845. }
  29846. }
  29847. function arrayNeedsUint32( array ) {
  29848. // assumes larger values usually on last
  29849. for ( let i = array.length - 1; i >= 0; -- i ) {
  29850. if ( array[ i ] >= 65535 ) return true; // account for PRIMITIVE_RESTART_FIXED_INDEX, #24565
  29851. }
  29852. return false;
  29853. }
  29854. function getWireframeVersion( geometry ) {
  29855. return ( geometry.index !== null ) ? geometry.index.version : geometry.attributes.position.version;
  29856. }
  29857. function getWireframeIndex( geometry ) {
  29858. const indices = [];
  29859. const geometryIndex = geometry.index;
  29860. const geometryPosition = geometry.attributes.position;
  29861. if ( geometryIndex !== null ) {
  29862. const array = geometryIndex.array;
  29863. for ( let i = 0, l = array.length; i < l; i += 3 ) {
  29864. const a = array[ i + 0 ];
  29865. const b = array[ i + 1 ];
  29866. const c = array[ i + 2 ];
  29867. indices.push( a, b, b, c, c, a );
  29868. }
  29869. } else {
  29870. const array = geometryPosition.array;
  29871. for ( let i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) {
  29872. const a = i + 0;
  29873. const b = i + 1;
  29874. const c = i + 2;
  29875. indices.push( a, b, b, c, c, a );
  29876. }
  29877. }
  29878. const attribute = new ( arrayNeedsUint32( indices ) ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 );
  29879. attribute.version = getWireframeVersion( geometry );
  29880. return attribute;
  29881. }
  29882. class Geometries extends DataMap {
  29883. constructor( attributes, info ) {
  29884. super();
  29885. this.attributes = attributes;
  29886. this.info = info;
  29887. this.wireframes = new WeakMap();
  29888. this.attributeCall = new WeakMap();
  29889. }
  29890. has( renderObject ) {
  29891. const geometry = renderObject.geometry;
  29892. return super.has( geometry ) && this.get( geometry ).initialized === true;
  29893. }
  29894. updateForRender( renderObject ) {
  29895. if ( this.has( renderObject ) === false ) this.initGeometry( renderObject );
  29896. this.updateAttributes( renderObject );
  29897. }
  29898. initGeometry( renderObject ) {
  29899. const geometry = renderObject.geometry;
  29900. const geometryData = this.get( geometry );
  29901. geometryData.initialized = true;
  29902. this.info.memory.geometries ++;
  29903. const onDispose = () => {
  29904. this.info.memory.geometries --;
  29905. const index = geometry.index;
  29906. const geometryAttributes = renderObject.getAttributes();
  29907. if ( index !== null ) {
  29908. this.attributes.delete( index );
  29909. }
  29910. for ( const geometryAttribute of geometryAttributes ) {
  29911. this.attributes.delete( geometryAttribute );
  29912. }
  29913. const wireframeAttribute = this.wireframes.get( geometry );
  29914. if ( wireframeAttribute !== undefined ) {
  29915. this.attributes.delete( wireframeAttribute );
  29916. }
  29917. geometry.removeEventListener( 'dispose', onDispose );
  29918. };
  29919. geometry.addEventListener( 'dispose', onDispose );
  29920. }
  29921. updateAttributes( renderObject ) {
  29922. // attributes
  29923. const attributes = renderObject.getAttributes();
  29924. for ( const attribute of attributes ) {
  29925. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) {
  29926. this.updateAttribute( attribute, AttributeType.STORAGE );
  29927. } else {
  29928. this.updateAttribute( attribute, AttributeType.VERTEX );
  29929. }
  29930. }
  29931. // indexes
  29932. const index = this.getIndex( renderObject );
  29933. if ( index !== null ) {
  29934. this.updateAttribute( index, AttributeType.INDEX );
  29935. }
  29936. // indirect
  29937. const indirect = renderObject.geometry.indirect;
  29938. if ( indirect !== null ) {
  29939. this.updateAttribute( indirect, AttributeType.INDIRECT );
  29940. }
  29941. }
  29942. updateAttribute( attribute, type ) {
  29943. const callId = this.info.render.calls;
  29944. if ( ! attribute.isInterleavedBufferAttribute ) {
  29945. if ( this.attributeCall.get( attribute ) !== callId ) {
  29946. this.attributes.update( attribute, type );
  29947. this.attributeCall.set( attribute, callId );
  29948. }
  29949. } else {
  29950. if ( this.attributeCall.get( attribute ) === undefined ) {
  29951. this.attributes.update( attribute, type );
  29952. this.attributeCall.set( attribute, callId );
  29953. } else if ( this.attributeCall.get( attribute.data ) !== callId ) {
  29954. this.attributes.update( attribute, type );
  29955. this.attributeCall.set( attribute.data, callId );
  29956. this.attributeCall.set( attribute, callId );
  29957. }
  29958. }
  29959. }
  29960. getIndirect( renderObject ) {
  29961. return renderObject.geometry.indirect;
  29962. }
  29963. getIndex( renderObject ) {
  29964. const { geometry, material } = renderObject;
  29965. let index = geometry.index;
  29966. if ( material.wireframe === true ) {
  29967. const wireframes = this.wireframes;
  29968. let wireframeAttribute = wireframes.get( geometry );
  29969. if ( wireframeAttribute === undefined ) {
  29970. wireframeAttribute = getWireframeIndex( geometry );
  29971. wireframes.set( geometry, wireframeAttribute );
  29972. } else if ( wireframeAttribute.version !== getWireframeVersion( geometry ) ) {
  29973. this.attributes.delete( wireframeAttribute );
  29974. wireframeAttribute = getWireframeIndex( geometry );
  29975. wireframes.set( geometry, wireframeAttribute );
  29976. }
  29977. index = wireframeAttribute;
  29978. }
  29979. return index;
  29980. }
  29981. }
  29982. class Info {
  29983. constructor() {
  29984. this.autoReset = true;
  29985. this.frame = 0;
  29986. this.calls = 0;
  29987. this.render = {
  29988. calls: 0,
  29989. frameCalls: 0,
  29990. drawCalls: 0,
  29991. triangles: 0,
  29992. points: 0,
  29993. lines: 0,
  29994. timestamp: 0,
  29995. previousFrameCalls: 0,
  29996. timestampCalls: 0
  29997. };
  29998. this.compute = {
  29999. calls: 0,
  30000. frameCalls: 0,
  30001. timestamp: 0,
  30002. previousFrameCalls: 0,
  30003. timestampCalls: 0
  30004. };
  30005. this.memory = {
  30006. geometries: 0,
  30007. textures: 0
  30008. };
  30009. }
  30010. update( object, count, instanceCount ) {
  30011. this.render.drawCalls ++;
  30012. if ( object.isMesh || object.isSprite ) {
  30013. this.render.triangles += instanceCount * ( count / 3 );
  30014. } else if ( object.isPoints ) {
  30015. this.render.points += instanceCount * count;
  30016. } else if ( object.isLineSegments ) {
  30017. this.render.lines += instanceCount * ( count / 2 );
  30018. } else if ( object.isLine ) {
  30019. this.render.lines += instanceCount * ( count - 1 );
  30020. } else {
  30021. console.error( 'THREE.WebGPUInfo: Unknown object type.' );
  30022. }
  30023. }
  30024. updateTimestamp( type, time ) {
  30025. if ( this[ type ].timestampCalls === 0 ) {
  30026. this[ type ].timestamp = 0;
  30027. }
  30028. this[ type ].timestamp += time;
  30029. this[ type ].timestampCalls ++;
  30030. if ( this[ type ].timestampCalls >= this[ type ].previousFrameCalls ) {
  30031. this[ type ].timestampCalls = 0;
  30032. }
  30033. }
  30034. reset() {
  30035. const previousRenderFrameCalls = this.render.frameCalls;
  30036. this.render.previousFrameCalls = previousRenderFrameCalls;
  30037. const previousComputeFrameCalls = this.compute.frameCalls;
  30038. this.compute.previousFrameCalls = previousComputeFrameCalls;
  30039. this.render.drawCalls = 0;
  30040. this.render.frameCalls = 0;
  30041. this.compute.frameCalls = 0;
  30042. this.render.triangles = 0;
  30043. this.render.points = 0;
  30044. this.render.lines = 0;
  30045. }
  30046. dispose() {
  30047. this.reset();
  30048. this.calls = 0;
  30049. this.render.calls = 0;
  30050. this.compute.calls = 0;
  30051. this.render.timestamp = 0;
  30052. this.compute.timestamp = 0;
  30053. this.memory.geometries = 0;
  30054. this.memory.textures = 0;
  30055. }
  30056. }
  30057. class Pipeline {
  30058. constructor( cacheKey ) {
  30059. this.cacheKey = cacheKey;
  30060. this.usedTimes = 0;
  30061. }
  30062. }
  30063. class RenderPipeline extends Pipeline {
  30064. constructor( cacheKey, vertexProgram, fragmentProgram ) {
  30065. super( cacheKey );
  30066. this.vertexProgram = vertexProgram;
  30067. this.fragmentProgram = fragmentProgram;
  30068. }
  30069. }
  30070. class ComputePipeline extends Pipeline {
  30071. constructor( cacheKey, computeProgram ) {
  30072. super( cacheKey );
  30073. this.computeProgram = computeProgram;
  30074. this.isComputePipeline = true;
  30075. }
  30076. }
  30077. let _id$6 = 0;
  30078. class ProgrammableStage {
  30079. constructor( code, type, transforms = null, attributes = null ) {
  30080. this.id = _id$6 ++;
  30081. this.code = code;
  30082. this.stage = type;
  30083. this.transforms = transforms;
  30084. this.attributes = attributes;
  30085. this.usedTimes = 0;
  30086. }
  30087. }
  30088. class Pipelines extends DataMap {
  30089. constructor( backend, nodes ) {
  30090. super();
  30091. this.backend = backend;
  30092. this.nodes = nodes;
  30093. this.bindings = null; // set by the bindings
  30094. this.caches = new Map();
  30095. this.programs = {
  30096. vertex: new Map(),
  30097. fragment: new Map(),
  30098. compute: new Map()
  30099. };
  30100. }
  30101. getForCompute( computeNode, bindings ) {
  30102. const { backend } = this;
  30103. const data = this.get( computeNode );
  30104. if ( this._needsComputeUpdate( computeNode ) ) {
  30105. const previousPipeline = data.pipeline;
  30106. if ( previousPipeline ) {
  30107. previousPipeline.usedTimes --;
  30108. previousPipeline.computeProgram.usedTimes --;
  30109. }
  30110. // get shader
  30111. const nodeBuilderState = this.nodes.getForCompute( computeNode );
  30112. // programmable stage
  30113. let stageCompute = this.programs.compute.get( nodeBuilderState.computeShader );
  30114. if ( stageCompute === undefined ) {
  30115. if ( previousPipeline && previousPipeline.computeProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.computeProgram );
  30116. stageCompute = new ProgrammableStage( nodeBuilderState.computeShader, 'compute', nodeBuilderState.transforms, nodeBuilderState.nodeAttributes );
  30117. this.programs.compute.set( nodeBuilderState.computeShader, stageCompute );
  30118. backend.createProgram( stageCompute );
  30119. }
  30120. // determine compute pipeline
  30121. const cacheKey = this._getComputeCacheKey( computeNode, stageCompute );
  30122. let pipeline = this.caches.get( cacheKey );
  30123. if ( pipeline === undefined ) {
  30124. if ( previousPipeline && previousPipeline.usedTimes === 0 ) this._releasePipeline( previousPipeline );
  30125. pipeline = this._getComputePipeline( computeNode, stageCompute, cacheKey, bindings );
  30126. }
  30127. // keep track of all used times
  30128. pipeline.usedTimes ++;
  30129. stageCompute.usedTimes ++;
  30130. //
  30131. data.version = computeNode.version;
  30132. data.pipeline = pipeline;
  30133. }
  30134. return data.pipeline;
  30135. }
  30136. getForRender( renderObject, promises = null ) {
  30137. const { backend } = this;
  30138. const data = this.get( renderObject );
  30139. if ( this._needsRenderUpdate( renderObject ) ) {
  30140. const previousPipeline = data.pipeline;
  30141. if ( previousPipeline ) {
  30142. previousPipeline.usedTimes --;
  30143. previousPipeline.vertexProgram.usedTimes --;
  30144. previousPipeline.fragmentProgram.usedTimes --;
  30145. }
  30146. // get shader
  30147. const nodeBuilderState = renderObject.getNodeBuilderState();
  30148. // programmable stages
  30149. let stageVertex = this.programs.vertex.get( nodeBuilderState.vertexShader );
  30150. if ( stageVertex === undefined ) {
  30151. if ( previousPipeline && previousPipeline.vertexProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.vertexProgram );
  30152. stageVertex = new ProgrammableStage( nodeBuilderState.vertexShader, 'vertex' );
  30153. this.programs.vertex.set( nodeBuilderState.vertexShader, stageVertex );
  30154. backend.createProgram( stageVertex );
  30155. }
  30156. let stageFragment = this.programs.fragment.get( nodeBuilderState.fragmentShader );
  30157. if ( stageFragment === undefined ) {
  30158. if ( previousPipeline && previousPipeline.fragmentProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.fragmentProgram );
  30159. stageFragment = new ProgrammableStage( nodeBuilderState.fragmentShader, 'fragment' );
  30160. this.programs.fragment.set( nodeBuilderState.fragmentShader, stageFragment );
  30161. backend.createProgram( stageFragment );
  30162. }
  30163. // determine render pipeline
  30164. const cacheKey = this._getRenderCacheKey( renderObject, stageVertex, stageFragment );
  30165. let pipeline = this.caches.get( cacheKey );
  30166. if ( pipeline === undefined ) {
  30167. if ( previousPipeline && previousPipeline.usedTimes === 0 ) this._releasePipeline( previousPipeline );
  30168. pipeline = this._getRenderPipeline( renderObject, stageVertex, stageFragment, cacheKey, promises );
  30169. } else {
  30170. renderObject.pipeline = pipeline;
  30171. }
  30172. // keep track of all used times
  30173. pipeline.usedTimes ++;
  30174. stageVertex.usedTimes ++;
  30175. stageFragment.usedTimes ++;
  30176. //
  30177. data.pipeline = pipeline;
  30178. }
  30179. return data.pipeline;
  30180. }
  30181. delete( object ) {
  30182. const pipeline = this.get( object ).pipeline;
  30183. if ( pipeline ) {
  30184. // pipeline
  30185. pipeline.usedTimes --;
  30186. if ( pipeline.usedTimes === 0 ) this._releasePipeline( pipeline );
  30187. // programs
  30188. if ( pipeline.isComputePipeline ) {
  30189. pipeline.computeProgram.usedTimes --;
  30190. if ( pipeline.computeProgram.usedTimes === 0 ) this._releaseProgram( pipeline.computeProgram );
  30191. } else {
  30192. pipeline.fragmentProgram.usedTimes --;
  30193. pipeline.vertexProgram.usedTimes --;
  30194. if ( pipeline.vertexProgram.usedTimes === 0 ) this._releaseProgram( pipeline.vertexProgram );
  30195. if ( pipeline.fragmentProgram.usedTimes === 0 ) this._releaseProgram( pipeline.fragmentProgram );
  30196. }
  30197. }
  30198. return super.delete( object );
  30199. }
  30200. dispose() {
  30201. super.dispose();
  30202. this.caches = new Map();
  30203. this.programs = {
  30204. vertex: new Map(),
  30205. fragment: new Map(),
  30206. compute: new Map()
  30207. };
  30208. }
  30209. updateForRender( renderObject ) {
  30210. this.getForRender( renderObject );
  30211. }
  30212. _getComputePipeline( computeNode, stageCompute, cacheKey, bindings ) {
  30213. // check for existing pipeline
  30214. cacheKey = cacheKey || this._getComputeCacheKey( computeNode, stageCompute );
  30215. let pipeline = this.caches.get( cacheKey );
  30216. if ( pipeline === undefined ) {
  30217. pipeline = new ComputePipeline( cacheKey, stageCompute );
  30218. this.caches.set( cacheKey, pipeline );
  30219. this.backend.createComputePipeline( pipeline, bindings );
  30220. }
  30221. return pipeline;
  30222. }
  30223. _getRenderPipeline( renderObject, stageVertex, stageFragment, cacheKey, promises ) {
  30224. // check for existing pipeline
  30225. cacheKey = cacheKey || this._getRenderCacheKey( renderObject, stageVertex, stageFragment );
  30226. let pipeline = this.caches.get( cacheKey );
  30227. if ( pipeline === undefined ) {
  30228. pipeline = new RenderPipeline( cacheKey, stageVertex, stageFragment );
  30229. this.caches.set( cacheKey, pipeline );
  30230. renderObject.pipeline = pipeline;
  30231. this.backend.createRenderPipeline( renderObject, promises );
  30232. }
  30233. return pipeline;
  30234. }
  30235. _getComputeCacheKey( computeNode, stageCompute ) {
  30236. return computeNode.id + ',' + stageCompute.id;
  30237. }
  30238. _getRenderCacheKey( renderObject, stageVertex, stageFragment ) {
  30239. return stageVertex.id + ',' + stageFragment.id + ',' + this.backend.getRenderCacheKey( renderObject );
  30240. }
  30241. _releasePipeline( pipeline ) {
  30242. this.caches.delete( pipeline.cacheKey );
  30243. }
  30244. _releaseProgram( program ) {
  30245. const code = program.code;
  30246. const stage = program.stage;
  30247. this.programs[ stage ].delete( code );
  30248. }
  30249. _needsComputeUpdate( computeNode ) {
  30250. const data = this.get( computeNode );
  30251. return data.pipeline === undefined || data.version !== computeNode.version;
  30252. }
  30253. _needsRenderUpdate( renderObject ) {
  30254. const data = this.get( renderObject );
  30255. return data.pipeline === undefined || this.backend.needsRenderUpdate( renderObject );
  30256. }
  30257. }
  30258. class Bindings extends DataMap {
  30259. constructor( backend, nodes, textures, attributes, pipelines, info ) {
  30260. super();
  30261. this.backend = backend;
  30262. this.textures = textures;
  30263. this.pipelines = pipelines;
  30264. this.attributes = attributes;
  30265. this.nodes = nodes;
  30266. this.info = info;
  30267. this.pipelines.bindings = this; // assign bindings to pipelines
  30268. }
  30269. getForRender( renderObject ) {
  30270. const bindings = renderObject.getBindings();
  30271. for ( const bindGroup of bindings ) {
  30272. const groupData = this.get( bindGroup );
  30273. if ( groupData.bindGroup === undefined ) {
  30274. // each object defines an array of bindings (ubos, textures, samplers etc.)
  30275. this._init( bindGroup );
  30276. this.backend.createBindings( bindGroup, bindings );
  30277. groupData.bindGroup = bindGroup;
  30278. }
  30279. }
  30280. return bindings;
  30281. }
  30282. getForCompute( computeNode ) {
  30283. const bindings = this.nodes.getForCompute( computeNode ).bindings;
  30284. for ( const bindGroup of bindings ) {
  30285. const groupData = this.get( bindGroup );
  30286. if ( groupData.bindGroup === undefined ) {
  30287. this._init( bindGroup );
  30288. this.backend.createBindings( bindGroup, bindings );
  30289. groupData.bindGroup = bindGroup;
  30290. }
  30291. }
  30292. return bindings;
  30293. }
  30294. updateForCompute( computeNode ) {
  30295. this._updateBindings( this.getForCompute( computeNode ) );
  30296. }
  30297. updateForRender( renderObject ) {
  30298. this._updateBindings( this.getForRender( renderObject ) );
  30299. }
  30300. _updateBindings( bindings ) {
  30301. for ( const bindGroup of bindings ) {
  30302. this._update( bindGroup, bindings );
  30303. }
  30304. }
  30305. _init( bindGroup ) {
  30306. for ( const binding of bindGroup.bindings ) {
  30307. if ( binding.isSampledTexture ) {
  30308. this.textures.updateTexture( binding.texture );
  30309. } else if ( binding.isStorageBuffer ) {
  30310. const attribute = binding.attribute;
  30311. const attributeType = attribute.isIndirectStorageBufferAttribute ? AttributeType.INDIRECT : AttributeType.STORAGE;
  30312. this.attributes.update( attribute, attributeType );
  30313. }
  30314. }
  30315. }
  30316. _update( bindGroup, bindings ) {
  30317. const { backend } = this;
  30318. let needsBindingsUpdate = false;
  30319. // iterate over all bindings and check if buffer updates or a new binding group is required
  30320. for ( const binding of bindGroup.bindings ) {
  30321. if ( binding.isNodeUniformsGroup ) {
  30322. const updated = this.nodes.updateGroup( binding );
  30323. if ( ! updated ) continue;
  30324. }
  30325. if ( binding.isUniformBuffer ) {
  30326. const updated = binding.update();
  30327. if ( updated ) {
  30328. backend.updateBinding( binding );
  30329. }
  30330. } else if ( binding.isSampler ) {
  30331. binding.update();
  30332. } else if ( binding.isSampledTexture ) {
  30333. if ( binding.needsBindingsUpdate( this.textures.get( binding.texture ).generation ) ) needsBindingsUpdate = true;
  30334. const updated = binding.update();
  30335. const texture = binding.texture;
  30336. if ( updated ) {
  30337. this.textures.updateTexture( texture );
  30338. }
  30339. const textureData = backend.get( texture );
  30340. if ( backend.isWebGPUBackend === true && textureData.texture === undefined && textureData.externalTexture === undefined ) {
  30341. // TODO: Remove this once we found why updated === false isn't bound to a texture in the WebGPU backend
  30342. console.error( 'Bindings._update: binding should be available:', binding, updated, texture, binding.textureNode.value, needsBindingsUpdate );
  30343. this.textures.updateTexture( texture );
  30344. needsBindingsUpdate = true;
  30345. }
  30346. if ( texture.isStorageTexture === true ) {
  30347. const textureData = this.get( texture );
  30348. if ( binding.store === true ) {
  30349. textureData.needsMipmap = true;
  30350. } else if ( texture.generateMipmaps === true && this.textures.needsMipmaps( texture ) && textureData.needsMipmap === true ) {
  30351. this.backend.generateMipmaps( texture );
  30352. textureData.needsMipmap = false;
  30353. }
  30354. }
  30355. }
  30356. }
  30357. if ( needsBindingsUpdate === true ) {
  30358. this.backend.updateBindings( bindGroup, bindings );
  30359. }
  30360. }
  30361. }
  30362. class NodeAttribute {
  30363. constructor( name, type, node = null ) {
  30364. this.isNodeAttribute = true;
  30365. this.name = name;
  30366. this.type = type;
  30367. this.node = node;
  30368. }
  30369. }
  30370. class NodeUniform {
  30371. constructor( name, type, node ) {
  30372. this.isNodeUniform = true;
  30373. this.name = name;
  30374. this.type = type;
  30375. this.node = node.getSelf();
  30376. }
  30377. get value() {
  30378. return this.node.value;
  30379. }
  30380. set value( val ) {
  30381. this.node.value = val;
  30382. }
  30383. get id() {
  30384. return this.node.id;
  30385. }
  30386. get groupNode() {
  30387. return this.node.groupNode;
  30388. }
  30389. }
  30390. class NodeVar {
  30391. constructor( name, type ) {
  30392. this.isNodeVar = true;
  30393. this.name = name;
  30394. this.type = type;
  30395. }
  30396. }
  30397. class NodeVarying extends NodeVar {
  30398. constructor( name, type ) {
  30399. super( name, type );
  30400. this.needsInterpolation = false;
  30401. this.isNodeVarying = true;
  30402. }
  30403. }
  30404. class NodeCode {
  30405. constructor( name, type, code = '' ) {
  30406. this.name = name;
  30407. this.type = type;
  30408. this.code = code;
  30409. Object.defineProperty( this, 'isNodeCode', { value: true } );
  30410. }
  30411. }
  30412. let id$1 = 0;
  30413. class NodeCache {
  30414. constructor( parent = null ) {
  30415. this.id = id$1 ++;
  30416. this.nodesData = new WeakMap();
  30417. this.parent = parent;
  30418. }
  30419. getData( node ) {
  30420. let data = this.nodesData.get( node );
  30421. if ( data === undefined && this.parent !== null ) {
  30422. data = this.parent.getData( node );
  30423. }
  30424. return data;
  30425. }
  30426. setData( node, data ) {
  30427. this.nodesData.set( node, data );
  30428. }
  30429. }
  30430. class ParameterNode extends PropertyNode {
  30431. static get type() {
  30432. return 'ParameterNode';
  30433. }
  30434. constructor( nodeType, name = null ) {
  30435. super( nodeType, name );
  30436. this.isParameterNode = true;
  30437. }
  30438. getHash() {
  30439. return this.uuid;
  30440. }
  30441. generate() {
  30442. return this.name;
  30443. }
  30444. }
  30445. const parameter = ( type, name ) => nodeObject( new ParameterNode( type, name ) );
  30446. class CodeNode extends Node {
  30447. static get type() {
  30448. return 'CodeNode';
  30449. }
  30450. constructor( code = '', includes = [], language = '' ) {
  30451. super( 'code' );
  30452. this.isCodeNode = true;
  30453. this.code = code;
  30454. this.language = language;
  30455. this.includes = includes;
  30456. }
  30457. isGlobal() {
  30458. return true;
  30459. }
  30460. setIncludes( includes ) {
  30461. this.includes = includes;
  30462. return this;
  30463. }
  30464. getIncludes( /*builder*/ ) {
  30465. return this.includes;
  30466. }
  30467. generate( builder ) {
  30468. const includes = this.getIncludes( builder );
  30469. for ( const include of includes ) {
  30470. include.build( builder );
  30471. }
  30472. const nodeCode = builder.getCodeFromNode( this, this.getNodeType( builder ) );
  30473. nodeCode.code = this.code;
  30474. return nodeCode.code;
  30475. }
  30476. serialize( data ) {
  30477. super.serialize( data );
  30478. data.code = this.code;
  30479. data.language = this.language;
  30480. }
  30481. deserialize( data ) {
  30482. super.deserialize( data );
  30483. this.code = data.code;
  30484. this.language = data.language;
  30485. }
  30486. }
  30487. const code = /*@__PURE__*/ nodeProxy( CodeNode );
  30488. const js = ( src, includes ) => code( src, includes, 'js' );
  30489. const wgsl = ( src, includes ) => code( src, includes, 'wgsl' );
  30490. const glsl = ( src, includes ) => code( src, includes, 'glsl' );
  30491. class FunctionNode extends CodeNode {
  30492. static get type() {
  30493. return 'FunctionNode';
  30494. }
  30495. constructor( code = '', includes = [], language = '' ) {
  30496. super( code, includes, language );
  30497. }
  30498. getNodeType( builder ) {
  30499. return this.getNodeFunction( builder ).type;
  30500. }
  30501. getInputs( builder ) {
  30502. return this.getNodeFunction( builder ).inputs;
  30503. }
  30504. getNodeFunction( builder ) {
  30505. const nodeData = builder.getDataFromNode( this );
  30506. let nodeFunction = nodeData.nodeFunction;
  30507. if ( nodeFunction === undefined ) {
  30508. nodeFunction = builder.parser.parseFunction( this.code );
  30509. nodeData.nodeFunction = nodeFunction;
  30510. }
  30511. return nodeFunction;
  30512. }
  30513. generate( builder, output ) {
  30514. super.generate( builder );
  30515. const nodeFunction = this.getNodeFunction( builder );
  30516. const name = nodeFunction.name;
  30517. const type = nodeFunction.type;
  30518. const nodeCode = builder.getCodeFromNode( this, type );
  30519. if ( name !== '' ) {
  30520. // use a custom property name
  30521. nodeCode.name = name;
  30522. }
  30523. const propertyName = builder.getPropertyName( nodeCode );
  30524. const code = this.getNodeFunction( builder ).getCode( propertyName );
  30525. nodeCode.code = code + '\n';
  30526. if ( output === 'property' ) {
  30527. return propertyName;
  30528. } else {
  30529. return builder.format( `${ propertyName }()`, type, output );
  30530. }
  30531. }
  30532. }
  30533. const nativeFn = ( code, includes = [], language = '' ) => {
  30534. for ( let i = 0; i < includes.length; i ++ ) {
  30535. const include = includes[ i ];
  30536. // TSL Function: glslFn, wgslFn
  30537. if ( typeof include === 'function' ) {
  30538. includes[ i ] = include.functionNode;
  30539. }
  30540. }
  30541. const functionNode = nodeObject( new FunctionNode( code, includes, language ) );
  30542. const fn = ( ...params ) => functionNode.call( ...params );
  30543. fn.functionNode = functionNode;
  30544. return fn;
  30545. };
  30546. const glslFn = ( code, includes ) => nativeFn( code, includes, 'glsl' );
  30547. const wgslFn = ( code, includes ) => nativeFn( code, includes, 'wgsl' );
  30548. class Uniform {
  30549. constructor( name, value ) {
  30550. this.name = name;
  30551. this.value = value;
  30552. this.boundary = 0; // used to build the uniform buffer according to the STD140 layout
  30553. this.itemSize = 0;
  30554. this.offset = 0; // this property is set by WebGPUUniformsGroup and marks the start position in the uniform buffer
  30555. }
  30556. setValue( value ) {
  30557. this.value = value;
  30558. }
  30559. getValue() {
  30560. return this.value;
  30561. }
  30562. }
  30563. class NumberUniform extends Uniform {
  30564. constructor( name, value = 0 ) {
  30565. super( name, value );
  30566. this.isNumberUniform = true;
  30567. this.boundary = 4;
  30568. this.itemSize = 1;
  30569. }
  30570. }
  30571. class Vector2Uniform extends Uniform {
  30572. constructor( name, value = new Vector2() ) {
  30573. super( name, value );
  30574. this.isVector2Uniform = true;
  30575. this.boundary = 8;
  30576. this.itemSize = 2;
  30577. }
  30578. }
  30579. class Vector3Uniform extends Uniform {
  30580. constructor( name, value = new Vector3() ) {
  30581. super( name, value );
  30582. this.isVector3Uniform = true;
  30583. this.boundary = 16;
  30584. this.itemSize = 3;
  30585. }
  30586. }
  30587. class Vector4Uniform extends Uniform {
  30588. constructor( name, value = new Vector4() ) {
  30589. super( name, value );
  30590. this.isVector4Uniform = true;
  30591. this.boundary = 16;
  30592. this.itemSize = 4;
  30593. }
  30594. }
  30595. class ColorUniform extends Uniform {
  30596. constructor( name, value = new Color() ) {
  30597. super( name, value );
  30598. this.isColorUniform = true;
  30599. this.boundary = 16;
  30600. this.itemSize = 3;
  30601. }
  30602. }
  30603. class Matrix3Uniform extends Uniform {
  30604. constructor( name, value = new Matrix3() ) {
  30605. super( name, value );
  30606. this.isMatrix3Uniform = true;
  30607. this.boundary = 48;
  30608. this.itemSize = 12;
  30609. }
  30610. }
  30611. class Matrix4Uniform extends Uniform {
  30612. constructor( name, value = new Matrix4() ) {
  30613. super( name, value );
  30614. this.isMatrix4Uniform = true;
  30615. this.boundary = 64;
  30616. this.itemSize = 16;
  30617. }
  30618. }
  30619. class NumberNodeUniform extends NumberUniform {
  30620. constructor( nodeUniform ) {
  30621. super( nodeUniform.name, nodeUniform.value );
  30622. this.nodeUniform = nodeUniform;
  30623. }
  30624. getValue() {
  30625. return this.nodeUniform.value;
  30626. }
  30627. }
  30628. class Vector2NodeUniform extends Vector2Uniform {
  30629. constructor( nodeUniform ) {
  30630. super( nodeUniform.name, nodeUniform.value );
  30631. this.nodeUniform = nodeUniform;
  30632. }
  30633. getValue() {
  30634. return this.nodeUniform.value;
  30635. }
  30636. }
  30637. class Vector3NodeUniform extends Vector3Uniform {
  30638. constructor( nodeUniform ) {
  30639. super( nodeUniform.name, nodeUniform.value );
  30640. this.nodeUniform = nodeUniform;
  30641. }
  30642. getValue() {
  30643. return this.nodeUniform.value;
  30644. }
  30645. }
  30646. class Vector4NodeUniform extends Vector4Uniform {
  30647. constructor( nodeUniform ) {
  30648. super( nodeUniform.name, nodeUniform.value );
  30649. this.nodeUniform = nodeUniform;
  30650. }
  30651. getValue() {
  30652. return this.nodeUniform.value;
  30653. }
  30654. }
  30655. class ColorNodeUniform extends ColorUniform {
  30656. constructor( nodeUniform ) {
  30657. super( nodeUniform.name, nodeUniform.value );
  30658. this.nodeUniform = nodeUniform;
  30659. }
  30660. getValue() {
  30661. return this.nodeUniform.value;
  30662. }
  30663. }
  30664. class Matrix3NodeUniform extends Matrix3Uniform {
  30665. constructor( nodeUniform ) {
  30666. super( nodeUniform.name, nodeUniform.value );
  30667. this.nodeUniform = nodeUniform;
  30668. }
  30669. getValue() {
  30670. return this.nodeUniform.value;
  30671. }
  30672. }
  30673. class Matrix4NodeUniform extends Matrix4Uniform {
  30674. constructor( nodeUniform ) {
  30675. super( nodeUniform.name, nodeUniform.value );
  30676. this.nodeUniform = nodeUniform;
  30677. }
  30678. getValue() {
  30679. return this.nodeUniform.value;
  30680. }
  30681. }
  30682. class StackNode extends Node {
  30683. static get type() {
  30684. return 'StackNode';
  30685. }
  30686. constructor( parent = null ) {
  30687. super();
  30688. this.nodes = [];
  30689. this.outputNode = null;
  30690. this.parent = parent;
  30691. this._currentCond = null;
  30692. this.isStackNode = true;
  30693. }
  30694. getNodeType( builder ) {
  30695. return this.outputNode ? this.outputNode.getNodeType( builder ) : 'void';
  30696. }
  30697. add( node ) {
  30698. this.nodes.push( node );
  30699. return this;
  30700. }
  30701. If( boolNode, method ) {
  30702. const methodNode = new ShaderNode( method );
  30703. this._currentCond = select( boolNode, methodNode );
  30704. return this.add( this._currentCond );
  30705. }
  30706. ElseIf( boolNode, method ) {
  30707. const methodNode = new ShaderNode( method );
  30708. const ifNode = select( boolNode, methodNode );
  30709. this._currentCond.elseNode = ifNode;
  30710. this._currentCond = ifNode;
  30711. return this;
  30712. }
  30713. Else( method ) {
  30714. this._currentCond.elseNode = new ShaderNode( method );
  30715. return this;
  30716. }
  30717. build( builder, ...params ) {
  30718. const previousStack = getCurrentStack();
  30719. setCurrentStack( this );
  30720. for ( const node of this.nodes ) {
  30721. node.build( builder, 'void' );
  30722. }
  30723. setCurrentStack( previousStack );
  30724. return this.outputNode ? this.outputNode.build( builder, ...params ) : super.build( builder, ...params );
  30725. }
  30726. //
  30727. else( ...params ) { // @deprecated, r168
  30728. console.warn( 'TSL.StackNode: .else() has been renamed to .Else().' );
  30729. return this.Else( ...params );
  30730. }
  30731. elseif( ...params ) { // @deprecated, r168
  30732. console.warn( 'TSL.StackNode: .elseif() has been renamed to .ElseIf().' );
  30733. return this.ElseIf( ...params );
  30734. }
  30735. }
  30736. const stack = /*@__PURE__*/ nodeProxy( StackNode );
  30737. const LOD_MIN = 4;
  30738. // The standard deviations (radians) associated with the extra mips. These are
  30739. // chosen to approximate a Trowbridge-Reitz distribution function times the
  30740. // geometric shadowing function. These sigma values squared must match the
  30741. // variance #defines in cube_uv_reflection_fragment.glsl.js.
  30742. const EXTRA_LOD_SIGMA = [ 0.125, 0.215, 0.35, 0.446, 0.526, 0.582 ];
  30743. // The maximum length of the blur for loop. Smaller sigmas will use fewer
  30744. // samples and exit early, but not recompile the shader.
  30745. const MAX_SAMPLES = 20;
  30746. const _flatCamera = /*@__PURE__*/ new OrthographicCamera( - 1, 1, 1, - 1, 0, 1 );
  30747. const _cubeCamera = /*@__PURE__*/ new PerspectiveCamera( 90, 1 );
  30748. const _clearColor$1 = /*@__PURE__*/ new Color();
  30749. let _oldTarget = null;
  30750. let _oldActiveCubeFace = 0;
  30751. let _oldActiveMipmapLevel = 0;
  30752. // Golden Ratio
  30753. const PHI = ( 1 + Math.sqrt( 5 ) ) / 2;
  30754. const INV_PHI = 1 / PHI;
  30755. // Vertices of a dodecahedron (except the opposites, which represent the
  30756. // same axis), used as axis directions evenly spread on a sphere.
  30757. const _axisDirections = [
  30758. /*@__PURE__*/ new Vector3( - PHI, INV_PHI, 0 ),
  30759. /*@__PURE__*/ new Vector3( PHI, INV_PHI, 0 ),
  30760. /*@__PURE__*/ new Vector3( - INV_PHI, 0, PHI ),
  30761. /*@__PURE__*/ new Vector3( INV_PHI, 0, PHI ),
  30762. /*@__PURE__*/ new Vector3( 0, PHI, - INV_PHI ),
  30763. /*@__PURE__*/ new Vector3( 0, PHI, INV_PHI ),
  30764. /*@__PURE__*/ new Vector3( - 1, 1, - 1 ),
  30765. /*@__PURE__*/ new Vector3( 1, 1, - 1 ),
  30766. /*@__PURE__*/ new Vector3( - 1, 1, 1 ),
  30767. /*@__PURE__*/ new Vector3( 1, 1, 1 )
  30768. ];
  30769. //
  30770. // WebGPU Face indices
  30771. const _faceLib = [
  30772. 3, 1, 5,
  30773. 0, 4, 2
  30774. ];
  30775. const direction = getDirection( uv(), attribute( 'faceIndex' ) ).normalize();
  30776. const outputDirection = vec3( direction.x, direction.y.negate(), direction.z );
  30777. /**
  30778. * This class generates a Prefiltered, Mipmapped Radiance Environment Map
  30779. * (PMREM) from a cubeMap environment texture. This allows different levels of
  30780. * blur to be quickly accessed based on material roughness. It is packed into a
  30781. * special CubeUV format that allows us to perform custom interpolation so that
  30782. * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap
  30783. * chain, it only goes down to the LOD_MIN level (above), and then creates extra
  30784. * even more filtered 'mips' at the same LOD_MIN resolution, associated with
  30785. * higher roughness levels. In this way we maintain resolution to smoothly
  30786. * interpolate diffuse lighting while limiting sampling computation.
  30787. *
  30788. * Paper: Fast, Accurate Image-Based Lighting
  30789. * https://drive.google.com/file/d/15y8r_UpKlU9SvV4ILb0C3qCPecS8pvLz/view
  30790. */
  30791. class PMREMGenerator {
  30792. constructor( renderer ) {
  30793. this._renderer = renderer;
  30794. this._pingPongRenderTarget = null;
  30795. this._lodMax = 0;
  30796. this._cubeSize = 0;
  30797. this._lodPlanes = [];
  30798. this._sizeLods = [];
  30799. this._sigmas = [];
  30800. this._lodMeshes = [];
  30801. this._blurMaterial = null;
  30802. this._cubemapMaterial = null;
  30803. this._equirectMaterial = null;
  30804. this._backgroundBox = null;
  30805. }
  30806. /**
  30807. * Generates a PMREM from a supplied Scene, which can be faster than using an
  30808. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  30809. * in radians to be applied to the scene before PMREM generation. Optional near
  30810. * and far planes ensure the scene is rendered in its entirety (the cubeCamera
  30811. * is placed at the origin).
  30812. */
  30813. fromScene( scene, sigma = 0, near = 0.1, far = 100 ) {
  30814. _oldTarget = this._renderer.getRenderTarget();
  30815. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  30816. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  30817. this._setSize( 256 );
  30818. const cubeUVRenderTarget = this._allocateTargets();
  30819. cubeUVRenderTarget.depthBuffer = true;
  30820. this._sceneToCubeUV( scene, near, far, cubeUVRenderTarget );
  30821. if ( sigma > 0 ) {
  30822. this._blur( cubeUVRenderTarget, 0, 0, sigma );
  30823. }
  30824. this._applyPMREM( cubeUVRenderTarget );
  30825. this._cleanup( cubeUVRenderTarget );
  30826. return cubeUVRenderTarget;
  30827. }
  30828. /**
  30829. * Generates a PMREM from an equirectangular texture, which can be either LDR
  30830. * or HDR. The ideal input image size is 1k (1024 x 512),
  30831. * as this matches best with the 256 x 256 cubemap output.
  30832. */
  30833. fromEquirectangular( equirectangular, renderTarget = null ) {
  30834. return this._fromTexture( equirectangular, renderTarget );
  30835. }
  30836. /**
  30837. * Generates a PMREM from an cubemap texture, which can be either LDR
  30838. * or HDR. The ideal input cube size is 256 x 256,
  30839. * as this matches best with the 256 x 256 cubemap output.
  30840. */
  30841. fromCubemap( cubemap, renderTarget = null ) {
  30842. return this._fromTexture( cubemap, renderTarget );
  30843. }
  30844. /**
  30845. * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during
  30846. * your texture's network fetch for increased concurrency.
  30847. */
  30848. async compileCubemapShader() {
  30849. if ( this._cubemapMaterial === null ) {
  30850. this._cubemapMaterial = _getCubemapMaterial();
  30851. await this._compileMaterial( this._cubemapMaterial );
  30852. }
  30853. }
  30854. /**
  30855. * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during
  30856. * your texture's network fetch for increased concurrency.
  30857. */
  30858. async compileEquirectangularShader() {
  30859. if ( this._equirectMaterial === null ) {
  30860. this._equirectMaterial = _getEquirectMaterial();
  30861. await this._compileMaterial( this._equirectMaterial );
  30862. }
  30863. }
  30864. /**
  30865. * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class,
  30866. * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on
  30867. * one of them will cause any others to also become unusable.
  30868. */
  30869. dispose() {
  30870. this._dispose();
  30871. if ( this._cubemapMaterial !== null ) this._cubemapMaterial.dispose();
  30872. if ( this._equirectMaterial !== null ) this._equirectMaterial.dispose();
  30873. if ( this._backgroundBox !== null ) {
  30874. this._backgroundBox.geometry.dispose();
  30875. this._backgroundBox.material.dispose();
  30876. }
  30877. }
  30878. // private interface
  30879. _setSize( cubeSize ) {
  30880. this._lodMax = Math.floor( Math.log2( cubeSize ) );
  30881. this._cubeSize = Math.pow( 2, this._lodMax );
  30882. }
  30883. _dispose() {
  30884. if ( this._blurMaterial !== null ) this._blurMaterial.dispose();
  30885. if ( this._pingPongRenderTarget !== null ) this._pingPongRenderTarget.dispose();
  30886. for ( let i = 0; i < this._lodPlanes.length; i ++ ) {
  30887. this._lodPlanes[ i ].dispose();
  30888. }
  30889. }
  30890. _cleanup( outputTarget ) {
  30891. this._renderer.setRenderTarget( _oldTarget, _oldActiveCubeFace, _oldActiveMipmapLevel );
  30892. outputTarget.scissorTest = false;
  30893. _setViewport( outputTarget, 0, 0, outputTarget.width, outputTarget.height );
  30894. }
  30895. _fromTexture( texture, renderTarget ) {
  30896. if ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping ) {
  30897. this._setSize( texture.image.length === 0 ? 16 : ( texture.image[ 0 ].width || texture.image[ 0 ].image.width ) );
  30898. } else { // Equirectangular
  30899. this._setSize( texture.image.width / 4 );
  30900. }
  30901. _oldTarget = this._renderer.getRenderTarget();
  30902. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  30903. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  30904. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  30905. this._textureToCubeUV( texture, cubeUVRenderTarget );
  30906. this._applyPMREM( cubeUVRenderTarget );
  30907. this._cleanup( cubeUVRenderTarget );
  30908. return cubeUVRenderTarget;
  30909. }
  30910. _allocateTargets() {
  30911. const width = 3 * Math.max( this._cubeSize, 16 * 7 );
  30912. const height = 4 * this._cubeSize;
  30913. const params = {
  30914. magFilter: LinearFilter,
  30915. minFilter: LinearFilter,
  30916. generateMipmaps: false,
  30917. type: HalfFloatType,
  30918. format: RGBAFormat,
  30919. colorSpace: LinearSRGBColorSpace,
  30920. //depthBuffer: false
  30921. };
  30922. const cubeUVRenderTarget = _createRenderTarget( width, height, params );
  30923. if ( this._pingPongRenderTarget === null || this._pingPongRenderTarget.width !== width || this._pingPongRenderTarget.height !== height ) {
  30924. if ( this._pingPongRenderTarget !== null ) {
  30925. this._dispose();
  30926. }
  30927. this._pingPongRenderTarget = _createRenderTarget( width, height, params );
  30928. const { _lodMax } = this;
  30929. ( { sizeLods: this._sizeLods, lodPlanes: this._lodPlanes, sigmas: this._sigmas, lodMeshes: this._lodMeshes } = _createPlanes( _lodMax ) );
  30930. this._blurMaterial = _getBlurShader( _lodMax, width, height );
  30931. }
  30932. return cubeUVRenderTarget;
  30933. }
  30934. async _compileMaterial( material ) {
  30935. const tmpMesh = new Mesh( this._lodPlanes[ 0 ], material );
  30936. await this._renderer.compile( tmpMesh, _flatCamera );
  30937. }
  30938. _sceneToCubeUV( scene, near, far, cubeUVRenderTarget ) {
  30939. const cubeCamera = _cubeCamera;
  30940. cubeCamera.near = near;
  30941. cubeCamera.far = far;
  30942. // px, py, pz, nx, ny, nz
  30943. const upSign = [ - 1, 1, - 1, - 1, - 1, - 1 ];
  30944. const forwardSign = [ 1, 1, 1, - 1, - 1, - 1 ];
  30945. const renderer = this._renderer;
  30946. const originalAutoClear = renderer.autoClear;
  30947. renderer.getClearColor( _clearColor$1 );
  30948. renderer.autoClear = false;
  30949. let backgroundBox = this._backgroundBox;
  30950. if ( backgroundBox === null ) {
  30951. const backgroundMaterial = new MeshBasicMaterial( {
  30952. name: 'PMREM.Background',
  30953. side: BackSide,
  30954. depthWrite: false,
  30955. depthTest: false
  30956. } );
  30957. backgroundBox = new Mesh( new BoxGeometry(), backgroundMaterial );
  30958. }
  30959. let useSolidColor = false;
  30960. const background = scene.background;
  30961. if ( background ) {
  30962. if ( background.isColor ) {
  30963. backgroundBox.material.color.copy( background );
  30964. scene.background = null;
  30965. useSolidColor = true;
  30966. }
  30967. } else {
  30968. backgroundBox.material.color.copy( _clearColor$1 );
  30969. useSolidColor = true;
  30970. }
  30971. renderer.setRenderTarget( cubeUVRenderTarget );
  30972. renderer.clear();
  30973. if ( useSolidColor ) {
  30974. renderer.render( backgroundBox, cubeCamera );
  30975. }
  30976. for ( let i = 0; i < 6; i ++ ) {
  30977. const col = i % 3;
  30978. if ( col === 0 ) {
  30979. cubeCamera.up.set( 0, upSign[ i ], 0 );
  30980. cubeCamera.lookAt( forwardSign[ i ], 0, 0 );
  30981. } else if ( col === 1 ) {
  30982. cubeCamera.up.set( 0, 0, upSign[ i ] );
  30983. cubeCamera.lookAt( 0, forwardSign[ i ], 0 );
  30984. } else {
  30985. cubeCamera.up.set( 0, upSign[ i ], 0 );
  30986. cubeCamera.lookAt( 0, 0, forwardSign[ i ] );
  30987. }
  30988. const size = this._cubeSize;
  30989. _setViewport( cubeUVRenderTarget, col * size, i > 2 ? size : 0, size, size );
  30990. renderer.render( scene, cubeCamera );
  30991. }
  30992. renderer.autoClear = originalAutoClear;
  30993. scene.background = background;
  30994. }
  30995. _textureToCubeUV( texture, cubeUVRenderTarget ) {
  30996. const renderer = this._renderer;
  30997. const isCubeTexture = ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping );
  30998. if ( isCubeTexture ) {
  30999. if ( this._cubemapMaterial === null ) {
  31000. this._cubemapMaterial = _getCubemapMaterial( texture );
  31001. }
  31002. } else {
  31003. if ( this._equirectMaterial === null ) {
  31004. this._equirectMaterial = _getEquirectMaterial( texture );
  31005. }
  31006. }
  31007. const material = isCubeTexture ? this._cubemapMaterial : this._equirectMaterial;
  31008. material.fragmentNode.value = texture;
  31009. const mesh = this._lodMeshes[ 0 ];
  31010. mesh.material = material;
  31011. const size = this._cubeSize;
  31012. _setViewport( cubeUVRenderTarget, 0, 0, 3 * size, 2 * size );
  31013. renderer.setRenderTarget( cubeUVRenderTarget );
  31014. renderer.render( mesh, _flatCamera );
  31015. }
  31016. _applyPMREM( cubeUVRenderTarget ) {
  31017. const renderer = this._renderer;
  31018. const autoClear = renderer.autoClear;
  31019. renderer.autoClear = false;
  31020. const n = this._lodPlanes.length;
  31021. for ( let i = 1; i < n; i ++ ) {
  31022. const sigma = Math.sqrt( this._sigmas[ i ] * this._sigmas[ i ] - this._sigmas[ i - 1 ] * this._sigmas[ i - 1 ] );
  31023. const poleAxis = _axisDirections[ ( n - i - 1 ) % _axisDirections.length ];
  31024. this._blur( cubeUVRenderTarget, i - 1, i, sigma, poleAxis );
  31025. }
  31026. renderer.autoClear = autoClear;
  31027. }
  31028. /**
  31029. * This is a two-pass Gaussian blur for a cubemap. Normally this is done
  31030. * vertically and horizontally, but this breaks down on a cube. Here we apply
  31031. * the blur latitudinally (around the poles), and then longitudinally (towards
  31032. * the poles) to approximate the orthogonally-separable blur. It is least
  31033. * accurate at the poles, but still does a decent job.
  31034. */
  31035. _blur( cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis ) {
  31036. const pingPongRenderTarget = this._pingPongRenderTarget;
  31037. this._halfBlur(
  31038. cubeUVRenderTarget,
  31039. pingPongRenderTarget,
  31040. lodIn,
  31041. lodOut,
  31042. sigma,
  31043. 'latitudinal',
  31044. poleAxis );
  31045. this._halfBlur(
  31046. pingPongRenderTarget,
  31047. cubeUVRenderTarget,
  31048. lodOut,
  31049. lodOut,
  31050. sigma,
  31051. 'longitudinal',
  31052. poleAxis );
  31053. }
  31054. _halfBlur( targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis ) {
  31055. const renderer = this._renderer;
  31056. const blurMaterial = this._blurMaterial;
  31057. if ( direction !== 'latitudinal' && direction !== 'longitudinal' ) {
  31058. console.error( 'blur direction must be either latitudinal or longitudinal!' );
  31059. }
  31060. // Number of standard deviations at which to cut off the discrete approximation.
  31061. const STANDARD_DEVIATIONS = 3;
  31062. const blurMesh = this._lodMeshes[ lodOut ];
  31063. blurMesh.material = blurMaterial;
  31064. const blurUniforms = blurMaterial.uniforms;
  31065. const pixels = this._sizeLods[ lodIn ] - 1;
  31066. const radiansPerPixel = isFinite( sigmaRadians ) ? Math.PI / ( 2 * pixels ) : 2 * Math.PI / ( 2 * MAX_SAMPLES - 1 );
  31067. const sigmaPixels = sigmaRadians / radiansPerPixel;
  31068. const samples = isFinite( sigmaRadians ) ? 1 + Math.floor( STANDARD_DEVIATIONS * sigmaPixels ) : MAX_SAMPLES;
  31069. if ( samples > MAX_SAMPLES ) {
  31070. console.warn( `sigmaRadians, ${
  31071. sigmaRadians}, is too large and will clip, as it requested ${
  31072. samples} samples when the maximum is set to ${MAX_SAMPLES}` );
  31073. }
  31074. const weights = [];
  31075. let sum = 0;
  31076. for ( let i = 0; i < MAX_SAMPLES; ++ i ) {
  31077. const x = i / sigmaPixels;
  31078. const weight = Math.exp( - x * x / 2 );
  31079. weights.push( weight );
  31080. if ( i === 0 ) {
  31081. sum += weight;
  31082. } else if ( i < samples ) {
  31083. sum += 2 * weight;
  31084. }
  31085. }
  31086. for ( let i = 0; i < weights.length; i ++ ) {
  31087. weights[ i ] = weights[ i ] / sum;
  31088. }
  31089. targetIn.texture.frame = ( targetIn.texture.frame || 0 ) + 1;
  31090. blurUniforms.envMap.value = targetIn.texture;
  31091. blurUniforms.samples.value = samples;
  31092. blurUniforms.weights.array = weights;
  31093. blurUniforms.latitudinal.value = direction === 'latitudinal' ? 1 : 0;
  31094. if ( poleAxis ) {
  31095. blurUniforms.poleAxis.value = poleAxis;
  31096. }
  31097. const { _lodMax } = this;
  31098. blurUniforms.dTheta.value = radiansPerPixel;
  31099. blurUniforms.mipInt.value = _lodMax - lodIn;
  31100. const outputSize = this._sizeLods[ lodOut ];
  31101. const x = 3 * outputSize * ( lodOut > _lodMax - LOD_MIN ? lodOut - _lodMax + LOD_MIN : 0 );
  31102. const y = 4 * ( this._cubeSize - outputSize );
  31103. _setViewport( targetOut, x, y, 3 * outputSize, 2 * outputSize );
  31104. renderer.setRenderTarget( targetOut );
  31105. renderer.render( blurMesh, _flatCamera );
  31106. }
  31107. }
  31108. function _createPlanes( lodMax ) {
  31109. const lodPlanes = [];
  31110. const sizeLods = [];
  31111. const sigmas = [];
  31112. const lodMeshes = [];
  31113. let lod = lodMax;
  31114. const totalLods = lodMax - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length;
  31115. for ( let i = 0; i < totalLods; i ++ ) {
  31116. const sizeLod = Math.pow( 2, lod );
  31117. sizeLods.push( sizeLod );
  31118. let sigma = 1.0 / sizeLod;
  31119. if ( i > lodMax - LOD_MIN ) {
  31120. sigma = EXTRA_LOD_SIGMA[ i - lodMax + LOD_MIN - 1 ];
  31121. } else if ( i === 0 ) {
  31122. sigma = 0;
  31123. }
  31124. sigmas.push( sigma );
  31125. const texelSize = 1.0 / ( sizeLod - 2 );
  31126. const min = - texelSize;
  31127. const max = 1 + texelSize;
  31128. const uv1 = [ min, min, max, min, max, max, min, min, max, max, min, max ];
  31129. const cubeFaces = 6;
  31130. const vertices = 6;
  31131. const positionSize = 3;
  31132. const uvSize = 2;
  31133. const faceIndexSize = 1;
  31134. const position = new Float32Array( positionSize * vertices * cubeFaces );
  31135. const uv = new Float32Array( uvSize * vertices * cubeFaces );
  31136. const faceIndex = new Float32Array( faceIndexSize * vertices * cubeFaces );
  31137. for ( let face = 0; face < cubeFaces; face ++ ) {
  31138. const x = ( face % 3 ) * 2 / 3 - 1;
  31139. const y = face > 2 ? 0 : - 1;
  31140. const coordinates = [
  31141. x, y, 0,
  31142. x + 2 / 3, y, 0,
  31143. x + 2 / 3, y + 1, 0,
  31144. x, y, 0,
  31145. x + 2 / 3, y + 1, 0,
  31146. x, y + 1, 0
  31147. ];
  31148. const faceIdx = _faceLib[ face ];
  31149. position.set( coordinates, positionSize * vertices * faceIdx );
  31150. uv.set( uv1, uvSize * vertices * faceIdx );
  31151. const fill = [ faceIdx, faceIdx, faceIdx, faceIdx, faceIdx, faceIdx ];
  31152. faceIndex.set( fill, faceIndexSize * vertices * faceIdx );
  31153. }
  31154. const planes = new BufferGeometry();
  31155. planes.setAttribute( 'position', new BufferAttribute( position, positionSize ) );
  31156. planes.setAttribute( 'uv', new BufferAttribute( uv, uvSize ) );
  31157. planes.setAttribute( 'faceIndex', new BufferAttribute( faceIndex, faceIndexSize ) );
  31158. lodPlanes.push( planes );
  31159. lodMeshes.push( new Mesh( planes, null ) );
  31160. if ( lod > LOD_MIN ) {
  31161. lod --;
  31162. }
  31163. }
  31164. return { lodPlanes, sizeLods, sigmas, lodMeshes };
  31165. }
  31166. function _createRenderTarget( width, height, params ) {
  31167. const cubeUVRenderTarget = new RenderTarget( width, height, params );
  31168. cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping;
  31169. cubeUVRenderTarget.texture.name = 'PMREM.cubeUv';
  31170. cubeUVRenderTarget.texture.isPMREMTexture = true;
  31171. cubeUVRenderTarget.scissorTest = true;
  31172. return cubeUVRenderTarget;
  31173. }
  31174. function _setViewport( target, x, y, width, height ) {
  31175. target.viewport.set( x, y, width, height );
  31176. target.scissor.set( x, y, width, height );
  31177. }
  31178. function _getMaterial( type ) {
  31179. const material = new NodeMaterial();
  31180. material.depthTest = false;
  31181. material.depthWrite = false;
  31182. material.blending = NoBlending;
  31183. material.name = `PMREM_${ type }`;
  31184. return material;
  31185. }
  31186. function _getBlurShader( lodMax, width, height ) {
  31187. const weights = uniformArray( new Array( MAX_SAMPLES ).fill( 0 ) );
  31188. const poleAxis = uniform( new Vector3( 0, 1, 0 ) );
  31189. const dTheta = uniform( 0 );
  31190. const n = float( MAX_SAMPLES );
  31191. const latitudinal = uniform( 0 ); // false, bool
  31192. const samples = uniform( 1 ); // int
  31193. const envMap = texture( null );
  31194. const mipInt = uniform( 0 ); // int
  31195. const CUBEUV_TEXEL_WIDTH = float( 1 / width );
  31196. const CUBEUV_TEXEL_HEIGHT = float( 1 / height );
  31197. const CUBEUV_MAX_MIP = float( lodMax );
  31198. const materialUniforms = {
  31199. n,
  31200. latitudinal,
  31201. weights,
  31202. poleAxis,
  31203. outputDirection,
  31204. dTheta,
  31205. samples,
  31206. envMap,
  31207. mipInt,
  31208. CUBEUV_TEXEL_WIDTH,
  31209. CUBEUV_TEXEL_HEIGHT,
  31210. CUBEUV_MAX_MIP
  31211. };
  31212. const material = _getMaterial( 'blur' );
  31213. material.uniforms = materialUniforms; // TODO: Move to outside of the material
  31214. material.fragmentNode = blur( { ...materialUniforms, latitudinal: latitudinal.equal( 1 ) } );
  31215. return material;
  31216. }
  31217. function _getCubemapMaterial( envTexture ) {
  31218. const material = _getMaterial( 'cubemap' );
  31219. material.fragmentNode = cubeTexture( envTexture, outputDirection );
  31220. return material;
  31221. }
  31222. function _getEquirectMaterial( envTexture ) {
  31223. const material = _getMaterial( 'equirect' );
  31224. material.fragmentNode = texture( envTexture, equirectUV( outputDirection ), 0 );
  31225. return material;
  31226. }
  31227. let _id$5 = 0;
  31228. class BindGroup {
  31229. constructor( name = '', bindings = [], index = 0, bindingsReference = [] ) {
  31230. this.name = name;
  31231. this.bindings = bindings;
  31232. this.index = index;
  31233. this.bindingsReference = bindingsReference;
  31234. this.id = _id$5 ++;
  31235. }
  31236. }
  31237. const rendererCache = new WeakMap();
  31238. const typeFromLength = new Map( [
  31239. [ 2, 'vec2' ],
  31240. [ 3, 'vec3' ],
  31241. [ 4, 'vec4' ],
  31242. [ 9, 'mat3' ],
  31243. [ 16, 'mat4' ]
  31244. ] );
  31245. const typeFromArray = new Map( [
  31246. [ Int8Array, 'int' ],
  31247. [ Int16Array, 'int' ],
  31248. [ Int32Array, 'int' ],
  31249. [ Uint8Array, 'uint' ],
  31250. [ Uint16Array, 'uint' ],
  31251. [ Uint32Array, 'uint' ],
  31252. [ Float32Array, 'float' ]
  31253. ] );
  31254. const toFloat = ( value ) => {
  31255. if ( /e/g.test( value ) ) {
  31256. return String( value ).replace( /\+/g, '' );
  31257. } else {
  31258. value = Number( value );
  31259. return value + ( value % 1 ? '' : '.0' );
  31260. }
  31261. };
  31262. class NodeBuilder {
  31263. constructor( object, renderer, parser ) {
  31264. this.object = object;
  31265. this.material = ( object && object.material ) || null;
  31266. this.geometry = ( object && object.geometry ) || null;
  31267. this.renderer = renderer;
  31268. this.parser = parser;
  31269. this.scene = null;
  31270. this.camera = null;
  31271. this.nodes = [];
  31272. this.updateNodes = [];
  31273. this.updateBeforeNodes = [];
  31274. this.updateAfterNodes = [];
  31275. this.hashNodes = {};
  31276. this.monitor = null;
  31277. this.lightsNode = null;
  31278. this.environmentNode = null;
  31279. this.fogNode = null;
  31280. this.clippingContext = null;
  31281. this.vertexShader = null;
  31282. this.fragmentShader = null;
  31283. this.computeShader = null;
  31284. this.flowNodes = { vertex: [], fragment: [], compute: [] };
  31285. this.flowCode = { vertex: '', fragment: '', compute: '' };
  31286. this.uniforms = { vertex: [], fragment: [], compute: [], index: 0 };
  31287. this.structs = { vertex: [], fragment: [], compute: [], index: 0 };
  31288. this.bindings = { vertex: {}, fragment: {}, compute: {} };
  31289. this.bindingsIndexes = {};
  31290. this.bindGroups = null;
  31291. this.attributes = [];
  31292. this.bufferAttributes = [];
  31293. this.varyings = [];
  31294. this.codes = {};
  31295. this.vars = {};
  31296. this.flow = { code: '' };
  31297. this.chaining = [];
  31298. this.stack = stack();
  31299. this.stacks = [];
  31300. this.tab = '\t';
  31301. this.currentFunctionNode = null;
  31302. this.context = {
  31303. material: this.material
  31304. };
  31305. this.cache = new NodeCache();
  31306. this.globalCache = this.cache;
  31307. this.flowsData = new WeakMap();
  31308. this.shaderStage = null;
  31309. this.buildStage = null;
  31310. this.useComparisonMethod = false;
  31311. }
  31312. getBindGroupsCache() {
  31313. let bindGroupsCache = rendererCache.get( this.renderer );
  31314. if ( bindGroupsCache === undefined ) {
  31315. bindGroupsCache = new ChainMap();
  31316. rendererCache.set( this.renderer, bindGroupsCache );
  31317. }
  31318. return bindGroupsCache;
  31319. }
  31320. createRenderTarget( width, height, options ) {
  31321. return new RenderTarget( width, height, options );
  31322. }
  31323. createCubeRenderTarget( size, options ) {
  31324. return new CubeRenderTarget( size, options );
  31325. }
  31326. createPMREMGenerator() {
  31327. // TODO: Move Materials.js to outside of the Nodes.js in order to remove this function and improve tree-shaking support
  31328. return new PMREMGenerator( this.renderer );
  31329. }
  31330. includes( node ) {
  31331. return this.nodes.includes( node );
  31332. }
  31333. _getBindGroup( groupName, bindings ) {
  31334. const bindGroupsCache = this.getBindGroupsCache();
  31335. //
  31336. const bindingsArray = [];
  31337. let sharedGroup = true;
  31338. for ( const binding of bindings ) {
  31339. bindingsArray.push( binding );
  31340. sharedGroup = sharedGroup && binding.groupNode.shared !== true;
  31341. }
  31342. //
  31343. let bindGroup;
  31344. if ( sharedGroup ) {
  31345. bindGroup = bindGroupsCache.get( bindingsArray );
  31346. if ( bindGroup === undefined ) {
  31347. bindGroup = new BindGroup( groupName, bindingsArray, this.bindingsIndexes[ groupName ].group, bindingsArray );
  31348. bindGroupsCache.set( bindingsArray, bindGroup );
  31349. }
  31350. } else {
  31351. bindGroup = new BindGroup( groupName, bindingsArray, this.bindingsIndexes[ groupName ].group, bindingsArray );
  31352. }
  31353. return bindGroup;
  31354. }
  31355. getBindGroupArray( groupName, shaderStage ) {
  31356. const bindings = this.bindings[ shaderStage ];
  31357. let bindGroup = bindings[ groupName ];
  31358. if ( bindGroup === undefined ) {
  31359. if ( this.bindingsIndexes[ groupName ] === undefined ) {
  31360. this.bindingsIndexes[ groupName ] = { binding: 0, group: Object.keys( this.bindingsIndexes ).length };
  31361. }
  31362. bindings[ groupName ] = bindGroup = [];
  31363. }
  31364. return bindGroup;
  31365. }
  31366. getBindings() {
  31367. let bindingsGroups = this.bindGroups;
  31368. if ( bindingsGroups === null ) {
  31369. const groups = {};
  31370. const bindings = this.bindings;
  31371. for ( const shaderStage of shaderStages ) {
  31372. for ( const groupName in bindings[ shaderStage ] ) {
  31373. const uniforms = bindings[ shaderStage ][ groupName ];
  31374. const groupUniforms = groups[ groupName ] || ( groups[ groupName ] = [] );
  31375. groupUniforms.push( ...uniforms );
  31376. }
  31377. }
  31378. bindingsGroups = [];
  31379. for ( const groupName in groups ) {
  31380. const group = groups[ groupName ];
  31381. const bindingsGroup = this._getBindGroup( groupName, group );
  31382. bindingsGroups.push( bindingsGroup );
  31383. }
  31384. this.bindGroups = bindingsGroups;
  31385. }
  31386. return bindingsGroups;
  31387. }
  31388. sortBindingGroups() {
  31389. const bindingsGroups = this.getBindings();
  31390. bindingsGroups.sort( ( a, b ) => ( a.bindings[ 0 ].groupNode.order - b.bindings[ 0 ].groupNode.order ) );
  31391. for ( let i = 0; i < bindingsGroups.length; i ++ ) {
  31392. const bindingGroup = bindingsGroups[ i ];
  31393. this.bindingsIndexes[ bindingGroup.name ].group = i;
  31394. bindingGroup.index = i;
  31395. }
  31396. }
  31397. setHashNode( node, hash ) {
  31398. this.hashNodes[ hash ] = node;
  31399. }
  31400. addNode( node ) {
  31401. if ( this.nodes.includes( node ) === false ) {
  31402. this.nodes.push( node );
  31403. this.setHashNode( node, node.getHash( this ) );
  31404. }
  31405. }
  31406. buildUpdateNodes() {
  31407. for ( const node of this.nodes ) {
  31408. const updateType = node.getUpdateType();
  31409. const updateBeforeType = node.getUpdateBeforeType();
  31410. const updateAfterType = node.getUpdateAfterType();
  31411. if ( updateType !== NodeUpdateType.NONE ) {
  31412. this.updateNodes.push( node.getSelf() );
  31413. }
  31414. if ( updateBeforeType !== NodeUpdateType.NONE ) {
  31415. this.updateBeforeNodes.push( node.getSelf() );
  31416. }
  31417. if ( updateAfterType !== NodeUpdateType.NONE ) {
  31418. this.updateAfterNodes.push( node.getSelf() );
  31419. }
  31420. }
  31421. }
  31422. get currentNode() {
  31423. return this.chaining[ this.chaining.length - 1 ];
  31424. }
  31425. isFilteredTexture( texture ) {
  31426. return ( texture.magFilter === LinearFilter || texture.magFilter === LinearMipmapNearestFilter || texture.magFilter === NearestMipmapLinearFilter || texture.magFilter === LinearMipmapLinearFilter ||
  31427. texture.minFilter === LinearFilter || texture.minFilter === LinearMipmapNearestFilter || texture.minFilter === NearestMipmapLinearFilter || texture.minFilter === LinearMipmapLinearFilter );
  31428. }
  31429. addChain( node ) {
  31430. /*
  31431. if ( this.chaining.indexOf( node ) !== - 1 ) {
  31432. console.warn( 'Recursive node: ', node );
  31433. }
  31434. */
  31435. this.chaining.push( node );
  31436. }
  31437. removeChain( node ) {
  31438. const lastChain = this.chaining.pop();
  31439. if ( lastChain !== node ) {
  31440. throw new Error( 'NodeBuilder: Invalid node chaining!' );
  31441. }
  31442. }
  31443. getMethod( method ) {
  31444. return method;
  31445. }
  31446. getNodeFromHash( hash ) {
  31447. return this.hashNodes[ hash ];
  31448. }
  31449. addFlow( shaderStage, node ) {
  31450. this.flowNodes[ shaderStage ].push( node );
  31451. return node;
  31452. }
  31453. setContext( context ) {
  31454. this.context = context;
  31455. }
  31456. getContext() {
  31457. return this.context;
  31458. }
  31459. getSharedContext() {
  31460. ({ ...this.context });
  31461. return this.context;
  31462. }
  31463. setCache( cache ) {
  31464. this.cache = cache;
  31465. }
  31466. getCache() {
  31467. return this.cache;
  31468. }
  31469. getCacheFromNode( node, parent = true ) {
  31470. const data = this.getDataFromNode( node );
  31471. if ( data.cache === undefined ) data.cache = new NodeCache( parent ? this.getCache() : null );
  31472. return data.cache;
  31473. }
  31474. isAvailable( /*name*/ ) {
  31475. return false;
  31476. }
  31477. getVertexIndex() {
  31478. console.warn( 'Abstract function.' );
  31479. }
  31480. getInstanceIndex() {
  31481. console.warn( 'Abstract function.' );
  31482. }
  31483. getDrawIndex() {
  31484. console.warn( 'Abstract function.' );
  31485. }
  31486. getFrontFacing() {
  31487. console.warn( 'Abstract function.' );
  31488. }
  31489. getFragCoord() {
  31490. console.warn( 'Abstract function.' );
  31491. }
  31492. isFlipY() {
  31493. return false;
  31494. }
  31495. increaseUsage( node ) {
  31496. const nodeData = this.getDataFromNode( node );
  31497. nodeData.usageCount = nodeData.usageCount === undefined ? 1 : nodeData.usageCount + 1;
  31498. return nodeData.usageCount;
  31499. }
  31500. generateTexture( /* texture, textureProperty, uvSnippet */ ) {
  31501. console.warn( 'Abstract function.' );
  31502. }
  31503. generateTextureLod( /* texture, textureProperty, uvSnippet, levelSnippet */ ) {
  31504. console.warn( 'Abstract function.' );
  31505. }
  31506. generateConst( type, value = null ) {
  31507. if ( value === null ) {
  31508. if ( type === 'float' || type === 'int' || type === 'uint' ) value = 0;
  31509. else if ( type === 'bool' ) value = false;
  31510. else if ( type === 'color' ) value = new Color();
  31511. else if ( type === 'vec2' ) value = new Vector2();
  31512. else if ( type === 'vec3' ) value = new Vector3();
  31513. else if ( type === 'vec4' ) value = new Vector4();
  31514. }
  31515. if ( type === 'float' ) return toFloat( value );
  31516. if ( type === 'int' ) return `${ Math.round( value ) }`;
  31517. if ( type === 'uint' ) return value >= 0 ? `${ Math.round( value ) }u` : '0u';
  31518. if ( type === 'bool' ) return value ? 'true' : 'false';
  31519. if ( type === 'color' ) return `${ this.getType( 'vec3' ) }( ${ toFloat( value.r ) }, ${ toFloat( value.g ) }, ${ toFloat( value.b ) } )`;
  31520. const typeLength = this.getTypeLength( type );
  31521. const componentType = this.getComponentType( type );
  31522. const generateConst = value => this.generateConst( componentType, value );
  31523. if ( typeLength === 2 ) {
  31524. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) } )`;
  31525. } else if ( typeLength === 3 ) {
  31526. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) }, ${ generateConst( value.z ) } )`;
  31527. } else if ( typeLength === 4 ) {
  31528. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) }, ${ generateConst( value.z ) }, ${ generateConst( value.w ) } )`;
  31529. } else if ( typeLength > 4 && value && ( value.isMatrix3 || value.isMatrix4 ) ) {
  31530. return `${ this.getType( type ) }( ${ value.elements.map( generateConst ).join( ', ' ) } )`;
  31531. } else if ( typeLength > 4 ) {
  31532. return `${ this.getType( type ) }()`;
  31533. }
  31534. throw new Error( `NodeBuilder: Type '${type}' not found in generate constant attempt.` );
  31535. }
  31536. getType( type ) {
  31537. if ( type === 'color' ) return 'vec3';
  31538. return type;
  31539. }
  31540. hasGeometryAttribute( name ) {
  31541. return this.geometry && this.geometry.getAttribute( name ) !== undefined;
  31542. }
  31543. getAttribute( name, type ) {
  31544. const attributes = this.attributes;
  31545. // find attribute
  31546. for ( const attribute of attributes ) {
  31547. if ( attribute.name === name ) {
  31548. return attribute;
  31549. }
  31550. }
  31551. // create a new if no exist
  31552. const attribute = new NodeAttribute( name, type );
  31553. attributes.push( attribute );
  31554. return attribute;
  31555. }
  31556. getPropertyName( node/*, shaderStage*/ ) {
  31557. return node.name;
  31558. }
  31559. isVector( type ) {
  31560. return /vec\d/.test( type );
  31561. }
  31562. isMatrix( type ) {
  31563. return /mat\d/.test( type );
  31564. }
  31565. isReference( type ) {
  31566. return type === 'void' || type === 'property' || type === 'sampler' || type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'depthTexture' || type === 'texture3D';
  31567. }
  31568. needsToWorkingColorSpace( /*texture*/ ) {
  31569. return false;
  31570. }
  31571. getComponentTypeFromTexture( texture ) {
  31572. const type = texture.type;
  31573. if ( texture.isDataTexture ) {
  31574. if ( type === IntType ) return 'int';
  31575. if ( type === UnsignedIntType ) return 'uint';
  31576. }
  31577. return 'float';
  31578. }
  31579. getElementType( type ) {
  31580. if ( type === 'mat2' ) return 'vec2';
  31581. if ( type === 'mat3' ) return 'vec3';
  31582. if ( type === 'mat4' ) return 'vec4';
  31583. return this.getComponentType( type );
  31584. }
  31585. getComponentType( type ) {
  31586. type = this.getVectorType( type );
  31587. if ( type === 'float' || type === 'bool' || type === 'int' || type === 'uint' ) return type;
  31588. const componentType = /(b|i|u|)(vec|mat)([2-4])/.exec( type );
  31589. if ( componentType === null ) return null;
  31590. if ( componentType[ 1 ] === 'b' ) return 'bool';
  31591. if ( componentType[ 1 ] === 'i' ) return 'int';
  31592. if ( componentType[ 1 ] === 'u' ) return 'uint';
  31593. return 'float';
  31594. }
  31595. getVectorType( type ) {
  31596. if ( type === 'color' ) return 'vec3';
  31597. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) return 'vec4';
  31598. return type;
  31599. }
  31600. getTypeFromLength( length, componentType = 'float' ) {
  31601. if ( length === 1 ) return componentType;
  31602. const baseType = typeFromLength.get( length );
  31603. const prefix = componentType === 'float' ? '' : componentType[ 0 ];
  31604. return prefix + baseType;
  31605. }
  31606. getTypeFromArray( array ) {
  31607. return typeFromArray.get( array.constructor );
  31608. }
  31609. getTypeFromAttribute( attribute ) {
  31610. let dataAttribute = attribute;
  31611. if ( attribute.isInterleavedBufferAttribute ) dataAttribute = attribute.data;
  31612. const array = dataAttribute.array;
  31613. const itemSize = attribute.itemSize;
  31614. const normalized = attribute.normalized;
  31615. let arrayType;
  31616. if ( ! ( attribute instanceof Float16BufferAttribute ) && normalized !== true ) {
  31617. arrayType = this.getTypeFromArray( array );
  31618. }
  31619. return this.getTypeFromLength( itemSize, arrayType );
  31620. }
  31621. getTypeLength( type ) {
  31622. const vecType = this.getVectorType( type );
  31623. const vecNum = /vec([2-4])/.exec( vecType );
  31624. if ( vecNum !== null ) return Number( vecNum[ 1 ] );
  31625. if ( vecType === 'float' || vecType === 'bool' || vecType === 'int' || vecType === 'uint' ) return 1;
  31626. if ( /mat2/.test( type ) === true ) return 4;
  31627. if ( /mat3/.test( type ) === true ) return 9;
  31628. if ( /mat4/.test( type ) === true ) return 16;
  31629. return 0;
  31630. }
  31631. getVectorFromMatrix( type ) {
  31632. return type.replace( 'mat', 'vec' );
  31633. }
  31634. changeComponentType( type, newComponentType ) {
  31635. return this.getTypeFromLength( this.getTypeLength( type ), newComponentType );
  31636. }
  31637. getIntegerType( type ) {
  31638. const componentType = this.getComponentType( type );
  31639. if ( componentType === 'int' || componentType === 'uint' ) return type;
  31640. return this.changeComponentType( type, 'int' );
  31641. }
  31642. addStack() {
  31643. this.stack = stack( this.stack );
  31644. this.stacks.push( getCurrentStack() || this.stack );
  31645. setCurrentStack( this.stack );
  31646. return this.stack;
  31647. }
  31648. removeStack() {
  31649. const lastStack = this.stack;
  31650. this.stack = lastStack.parent;
  31651. setCurrentStack( this.stacks.pop() );
  31652. return lastStack;
  31653. }
  31654. getDataFromNode( node, shaderStage = this.shaderStage, cache = null ) {
  31655. cache = cache === null ? ( node.isGlobal( this ) ? this.globalCache : this.cache ) : cache;
  31656. let nodeData = cache.getData( node );
  31657. if ( nodeData === undefined ) {
  31658. nodeData = {};
  31659. cache.setData( node, nodeData );
  31660. }
  31661. if ( nodeData[ shaderStage ] === undefined ) nodeData[ shaderStage ] = {};
  31662. return nodeData[ shaderStage ];
  31663. }
  31664. getNodeProperties( node, shaderStage = 'any' ) {
  31665. const nodeData = this.getDataFromNode( node, shaderStage );
  31666. return nodeData.properties || ( nodeData.properties = { outputNode: null } );
  31667. }
  31668. getBufferAttributeFromNode( node, type ) {
  31669. const nodeData = this.getDataFromNode( node );
  31670. let bufferAttribute = nodeData.bufferAttribute;
  31671. if ( bufferAttribute === undefined ) {
  31672. const index = this.uniforms.index ++;
  31673. bufferAttribute = new NodeAttribute( 'nodeAttribute' + index, type, node );
  31674. this.bufferAttributes.push( bufferAttribute );
  31675. nodeData.bufferAttribute = bufferAttribute;
  31676. }
  31677. return bufferAttribute;
  31678. }
  31679. getStructTypeFromNode( node, shaderStage = this.shaderStage ) {
  31680. const nodeData = this.getDataFromNode( node, shaderStage );
  31681. if ( nodeData.structType === undefined ) {
  31682. const index = this.structs.index ++;
  31683. node.name = `StructType${ index }`;
  31684. this.structs[ shaderStage ].push( node );
  31685. nodeData.structType = node;
  31686. }
  31687. return node;
  31688. }
  31689. getUniformFromNode( node, type, shaderStage = this.shaderStage, name = null ) {
  31690. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  31691. let nodeUniform = nodeData.uniform;
  31692. if ( nodeUniform === undefined ) {
  31693. const index = this.uniforms.index ++;
  31694. nodeUniform = new NodeUniform( name || ( 'nodeUniform' + index ), type, node );
  31695. this.uniforms[ shaderStage ].push( nodeUniform );
  31696. nodeData.uniform = nodeUniform;
  31697. }
  31698. return nodeUniform;
  31699. }
  31700. getVarFromNode( node, name = null, type = node.getNodeType( this ), shaderStage = this.shaderStage ) {
  31701. const nodeData = this.getDataFromNode( node, shaderStage );
  31702. let nodeVar = nodeData.variable;
  31703. if ( nodeVar === undefined ) {
  31704. const vars = this.vars[ shaderStage ] || ( this.vars[ shaderStage ] = [] );
  31705. if ( name === null ) name = 'nodeVar' + vars.length;
  31706. nodeVar = new NodeVar( name, type );
  31707. vars.push( nodeVar );
  31708. nodeData.variable = nodeVar;
  31709. }
  31710. return nodeVar;
  31711. }
  31712. getVaryingFromNode( node, name = null, type = node.getNodeType( this ) ) {
  31713. const nodeData = this.getDataFromNode( node, 'any' );
  31714. let nodeVarying = nodeData.varying;
  31715. if ( nodeVarying === undefined ) {
  31716. const varyings = this.varyings;
  31717. const index = varyings.length;
  31718. if ( name === null ) name = 'nodeVarying' + index;
  31719. nodeVarying = new NodeVarying( name, type );
  31720. varyings.push( nodeVarying );
  31721. nodeData.varying = nodeVarying;
  31722. }
  31723. return nodeVarying;
  31724. }
  31725. getCodeFromNode( node, type, shaderStage = this.shaderStage ) {
  31726. const nodeData = this.getDataFromNode( node );
  31727. let nodeCode = nodeData.code;
  31728. if ( nodeCode === undefined ) {
  31729. const codes = this.codes[ shaderStage ] || ( this.codes[ shaderStage ] = [] );
  31730. const index = codes.length;
  31731. nodeCode = new NodeCode( 'nodeCode' + index, type );
  31732. codes.push( nodeCode );
  31733. nodeData.code = nodeCode;
  31734. }
  31735. return nodeCode;
  31736. }
  31737. addFlowCodeHierarchy( node, nodeBlock ) {
  31738. const { flowCodes, flowCodeBlock } = this.getDataFromNode( node );
  31739. let needsFlowCode = true;
  31740. let nodeBlockHierarchy = nodeBlock;
  31741. while ( nodeBlockHierarchy ) {
  31742. if ( flowCodeBlock.get( nodeBlockHierarchy ) === true ) {
  31743. needsFlowCode = false;
  31744. break;
  31745. }
  31746. nodeBlockHierarchy = this.getDataFromNode( nodeBlockHierarchy ).parentNodeBlock;
  31747. }
  31748. if ( needsFlowCode ) {
  31749. for ( const flowCode of flowCodes ) {
  31750. this.addLineFlowCode( flowCode );
  31751. }
  31752. }
  31753. }
  31754. addLineFlowCodeBlock( node, code, nodeBlock ) {
  31755. const nodeData = this.getDataFromNode( node );
  31756. const flowCodes = nodeData.flowCodes || ( nodeData.flowCodes = [] );
  31757. const codeBlock = nodeData.flowCodeBlock || ( nodeData.flowCodeBlock = new WeakMap() );
  31758. flowCodes.push( code );
  31759. codeBlock.set( nodeBlock, true );
  31760. }
  31761. addLineFlowCode( code, node = null ) {
  31762. if ( code === '' ) return this;
  31763. if ( node !== null && this.context.nodeBlock ) {
  31764. this.addLineFlowCodeBlock( node, code, this.context.nodeBlock );
  31765. }
  31766. code = this.tab + code;
  31767. if ( ! /;\s*$/.test( code ) ) {
  31768. code = code + ';\n';
  31769. }
  31770. this.flow.code += code;
  31771. return this;
  31772. }
  31773. addFlowCode( code ) {
  31774. this.flow.code += code;
  31775. return this;
  31776. }
  31777. addFlowTab() {
  31778. this.tab += '\t';
  31779. return this;
  31780. }
  31781. removeFlowTab() {
  31782. this.tab = this.tab.slice( 0, - 1 );
  31783. return this;
  31784. }
  31785. getFlowData( node/*, shaderStage*/ ) {
  31786. return this.flowsData.get( node );
  31787. }
  31788. flowNode( node ) {
  31789. const output = node.getNodeType( this );
  31790. const flowData = this.flowChildNode( node, output );
  31791. this.flowsData.set( node, flowData );
  31792. return flowData;
  31793. }
  31794. buildFunctionNode( shaderNode ) {
  31795. const fn = new FunctionNode();
  31796. const previous = this.currentFunctionNode;
  31797. this.currentFunctionNode = fn;
  31798. fn.code = this.buildFunctionCode( shaderNode );
  31799. this.currentFunctionNode = previous;
  31800. return fn;
  31801. }
  31802. flowShaderNode( shaderNode ) {
  31803. const layout = shaderNode.layout;
  31804. const inputs = {
  31805. [ Symbol.iterator ]() {
  31806. let index = 0;
  31807. const values = Object.values( this );
  31808. return {
  31809. next: () => ( {
  31810. value: values[ index ],
  31811. done: index ++ >= values.length
  31812. } )
  31813. };
  31814. }
  31815. };
  31816. for ( const input of layout.inputs ) {
  31817. inputs[ input.name ] = new ParameterNode( input.type, input.name );
  31818. }
  31819. //
  31820. shaderNode.layout = null;
  31821. const callNode = shaderNode.call( inputs );
  31822. const flowData = this.flowStagesNode( callNode, layout.type );
  31823. shaderNode.layout = layout;
  31824. return flowData;
  31825. }
  31826. flowStagesNode( node, output = null ) {
  31827. const previousFlow = this.flow;
  31828. const previousVars = this.vars;
  31829. const previousCache = this.cache;
  31830. const previousBuildStage = this.buildStage;
  31831. const previousStack = this.stack;
  31832. const flow = {
  31833. code: ''
  31834. };
  31835. this.flow = flow;
  31836. this.vars = {};
  31837. this.cache = new NodeCache();
  31838. this.stack = stack();
  31839. for ( const buildStage of defaultBuildStages ) {
  31840. this.setBuildStage( buildStage );
  31841. flow.result = node.build( this, output );
  31842. }
  31843. flow.vars = this.getVars( this.shaderStage );
  31844. this.flow = previousFlow;
  31845. this.vars = previousVars;
  31846. this.cache = previousCache;
  31847. this.stack = previousStack;
  31848. this.setBuildStage( previousBuildStage );
  31849. return flow;
  31850. }
  31851. getFunctionOperator() {
  31852. return null;
  31853. }
  31854. flowChildNode( node, output = null ) {
  31855. const previousFlow = this.flow;
  31856. const flow = {
  31857. code: ''
  31858. };
  31859. this.flow = flow;
  31860. flow.result = node.build( this, output );
  31861. this.flow = previousFlow;
  31862. return flow;
  31863. }
  31864. flowNodeFromShaderStage( shaderStage, node, output = null, propertyName = null ) {
  31865. const previousShaderStage = this.shaderStage;
  31866. this.setShaderStage( shaderStage );
  31867. const flowData = this.flowChildNode( node, output );
  31868. if ( propertyName !== null ) {
  31869. flowData.code += `${ this.tab + propertyName } = ${ flowData.result };\n`;
  31870. }
  31871. this.flowCode[ shaderStage ] = this.flowCode[ shaderStage ] + flowData.code;
  31872. this.setShaderStage( previousShaderStage );
  31873. return flowData;
  31874. }
  31875. getAttributesArray() {
  31876. return this.attributes.concat( this.bufferAttributes );
  31877. }
  31878. getAttributes( /*shaderStage*/ ) {
  31879. console.warn( 'Abstract function.' );
  31880. }
  31881. getVaryings( /*shaderStage*/ ) {
  31882. console.warn( 'Abstract function.' );
  31883. }
  31884. getVar( type, name ) {
  31885. return `${ this.getType( type ) } ${ name }`;
  31886. }
  31887. getVars( shaderStage ) {
  31888. let snippet = '';
  31889. const vars = this.vars[ shaderStage ];
  31890. if ( vars !== undefined ) {
  31891. for ( const variable of vars ) {
  31892. snippet += `${ this.getVar( variable.type, variable.name ) }; `;
  31893. }
  31894. }
  31895. return snippet;
  31896. }
  31897. getUniforms( /*shaderStage*/ ) {
  31898. console.warn( 'Abstract function.' );
  31899. }
  31900. getCodes( shaderStage ) {
  31901. const codes = this.codes[ shaderStage ];
  31902. let code = '';
  31903. if ( codes !== undefined ) {
  31904. for ( const nodeCode of codes ) {
  31905. code += nodeCode.code + '\n';
  31906. }
  31907. }
  31908. return code;
  31909. }
  31910. getHash() {
  31911. return this.vertexShader + this.fragmentShader + this.computeShader;
  31912. }
  31913. setShaderStage( shaderStage ) {
  31914. this.shaderStage = shaderStage;
  31915. }
  31916. getShaderStage() {
  31917. return this.shaderStage;
  31918. }
  31919. setBuildStage( buildStage ) {
  31920. this.buildStage = buildStage;
  31921. }
  31922. getBuildStage() {
  31923. return this.buildStage;
  31924. }
  31925. buildCode() {
  31926. console.warn( 'Abstract function.' );
  31927. }
  31928. build() {
  31929. const { object, material, renderer } = this;
  31930. if ( material !== null ) {
  31931. let nodeMaterial = renderer.nodes.library.fromMaterial( material );
  31932. if ( nodeMaterial === null ) {
  31933. console.error( `NodeMaterial: Material "${ material.type }" is not compatible.` );
  31934. nodeMaterial = new NodeMaterial();
  31935. }
  31936. nodeMaterial.build( this );
  31937. } else {
  31938. this.addFlow( 'compute', object );
  31939. }
  31940. // setup() -> stage 1: create possible new nodes and returns an output reference node
  31941. // analyze() -> stage 2: analyze nodes to possible optimization and validation
  31942. // generate() -> stage 3: generate shader
  31943. for ( const buildStage of defaultBuildStages ) {
  31944. this.setBuildStage( buildStage );
  31945. if ( this.context.vertex && this.context.vertex.isNode ) {
  31946. this.flowNodeFromShaderStage( 'vertex', this.context.vertex );
  31947. }
  31948. for ( const shaderStage of shaderStages ) {
  31949. this.setShaderStage( shaderStage );
  31950. const flowNodes = this.flowNodes[ shaderStage ];
  31951. for ( const node of flowNodes ) {
  31952. if ( buildStage === 'generate' ) {
  31953. this.flowNode( node );
  31954. } else {
  31955. node.build( this );
  31956. }
  31957. }
  31958. }
  31959. }
  31960. this.setBuildStage( null );
  31961. this.setShaderStage( null );
  31962. // stage 4: build code for a specific output
  31963. this.buildCode();
  31964. this.buildUpdateNodes();
  31965. return this;
  31966. }
  31967. getNodeUniform( uniformNode, type ) {
  31968. if ( type === 'float' || type === 'int' || type === 'uint' ) return new NumberNodeUniform( uniformNode );
  31969. if ( type === 'vec2' || type === 'ivec2' || type === 'uvec2' ) return new Vector2NodeUniform( uniformNode );
  31970. if ( type === 'vec3' || type === 'ivec3' || type === 'uvec3' ) return new Vector3NodeUniform( uniformNode );
  31971. if ( type === 'vec4' || type === 'ivec4' || type === 'uvec4' ) return new Vector4NodeUniform( uniformNode );
  31972. if ( type === 'color' ) return new ColorNodeUniform( uniformNode );
  31973. if ( type === 'mat3' ) return new Matrix3NodeUniform( uniformNode );
  31974. if ( type === 'mat4' ) return new Matrix4NodeUniform( uniformNode );
  31975. throw new Error( `Uniform "${type}" not declared.` );
  31976. }
  31977. createNodeMaterial( type = 'NodeMaterial' ) { // @deprecated, r168
  31978. throw new Error( `THREE.NodeBuilder: createNodeMaterial() was deprecated. Use new ${ type }() instead.` );
  31979. }
  31980. format( snippet, fromType, toType ) {
  31981. fromType = this.getVectorType( fromType );
  31982. toType = this.getVectorType( toType );
  31983. if ( fromType === toType || toType === null || this.isReference( toType ) ) {
  31984. return snippet;
  31985. }
  31986. const fromTypeLength = this.getTypeLength( fromType );
  31987. const toTypeLength = this.getTypeLength( toType );
  31988. if ( fromTypeLength === 16 && toTypeLength === 9 ) {
  31989. return `${ this.getType( toType ) }(${ snippet }[0].xyz, ${ snippet }[1].xyz, ${ snippet }[2].xyz)`;
  31990. }
  31991. if ( fromTypeLength === 9 && toTypeLength === 4 ) {
  31992. return `${ this.getType( toType ) }(${ snippet }[0].xy, ${ snippet }[1].xy)`;
  31993. }
  31994. if ( fromTypeLength > 4 ) { // fromType is matrix-like
  31995. // @TODO: ignore for now
  31996. return snippet;
  31997. }
  31998. if ( toTypeLength > 4 || toTypeLength === 0 ) { // toType is matrix-like or unknown
  31999. // @TODO: ignore for now
  32000. return snippet;
  32001. }
  32002. if ( fromTypeLength === toTypeLength ) {
  32003. return `${ this.getType( toType ) }( ${ snippet } )`;
  32004. }
  32005. if ( fromTypeLength > toTypeLength ) {
  32006. return this.format( `${ snippet }.${ 'xyz'.slice( 0, toTypeLength ) }`, this.getTypeFromLength( toTypeLength, this.getComponentType( fromType ) ), toType );
  32007. }
  32008. if ( toTypeLength === 4 && fromTypeLength > 1 ) { // toType is vec4-like
  32009. return `${ this.getType( toType ) }( ${ this.format( snippet, fromType, 'vec3' ) }, 1.0 )`;
  32010. }
  32011. if ( fromTypeLength === 2 ) { // fromType is vec2-like and toType is vec3-like
  32012. return `${ this.getType( toType ) }( ${ this.format( snippet, fromType, 'vec2' ) }, 0.0 )`;
  32013. }
  32014. if ( fromTypeLength === 1 && toTypeLength > 1 && fromType !== this.getComponentType( toType ) ) { // fromType is float-like
  32015. // convert a number value to vector type, e.g:
  32016. // vec3( 1u ) -> vec3( float( 1u ) )
  32017. snippet = `${ this.getType( this.getComponentType( toType ) ) }( ${ snippet } )`;
  32018. }
  32019. return `${ this.getType( toType ) }( ${ snippet } )`; // fromType is float-like
  32020. }
  32021. getSignature() {
  32022. return `// Three.js r${ REVISION } - Node System\n`;
  32023. }
  32024. }
  32025. class NodeFrame {
  32026. constructor() {
  32027. this.time = 0;
  32028. this.deltaTime = 0;
  32029. this.frameId = 0;
  32030. this.renderId = 0;
  32031. this.startTime = null;
  32032. this.updateMap = new WeakMap();
  32033. this.updateBeforeMap = new WeakMap();
  32034. this.updateAfterMap = new WeakMap();
  32035. this.renderer = null;
  32036. this.material = null;
  32037. this.camera = null;
  32038. this.object = null;
  32039. this.scene = null;
  32040. }
  32041. _getMaps( referenceMap, nodeRef ) {
  32042. let maps = referenceMap.get( nodeRef );
  32043. if ( maps === undefined ) {
  32044. maps = {
  32045. renderMap: new WeakMap(),
  32046. frameMap: new WeakMap()
  32047. };
  32048. referenceMap.set( nodeRef, maps );
  32049. }
  32050. return maps;
  32051. }
  32052. updateBeforeNode( node ) {
  32053. const updateType = node.getUpdateBeforeType();
  32054. const reference = node.updateReference( this );
  32055. if ( updateType === NodeUpdateType.FRAME ) {
  32056. const { frameMap } = this._getMaps( this.updateBeforeMap, reference );
  32057. if ( frameMap.get( reference ) !== this.frameId ) {
  32058. if ( node.updateBefore( this ) !== false ) {
  32059. frameMap.set( reference, this.frameId );
  32060. }
  32061. }
  32062. } else if ( updateType === NodeUpdateType.RENDER ) {
  32063. const { renderMap } = this._getMaps( this.updateBeforeMap, reference );
  32064. if ( renderMap.get( reference ) !== this.renderId ) {
  32065. if ( node.updateBefore( this ) !== false ) {
  32066. renderMap.set( reference, this.renderId );
  32067. }
  32068. }
  32069. } else if ( updateType === NodeUpdateType.OBJECT ) {
  32070. node.updateBefore( this );
  32071. }
  32072. }
  32073. updateAfterNode( node ) {
  32074. const updateType = node.getUpdateAfterType();
  32075. const reference = node.updateReference( this );
  32076. if ( updateType === NodeUpdateType.FRAME ) {
  32077. const { frameMap } = this._getMaps( this.updateAfterMap, reference );
  32078. if ( frameMap.get( reference ) !== this.frameId ) {
  32079. if ( node.updateAfter( this ) !== false ) {
  32080. frameMap.set( reference, this.frameId );
  32081. }
  32082. }
  32083. } else if ( updateType === NodeUpdateType.RENDER ) {
  32084. const { renderMap } = this._getMaps( this.updateAfterMap, reference );
  32085. if ( renderMap.get( reference ) !== this.renderId ) {
  32086. if ( node.updateAfter( this ) !== false ) {
  32087. renderMap.set( reference, this.renderId );
  32088. }
  32089. }
  32090. } else if ( updateType === NodeUpdateType.OBJECT ) {
  32091. node.updateAfter( this );
  32092. }
  32093. }
  32094. updateNode( node ) {
  32095. const updateType = node.getUpdateType();
  32096. const reference = node.updateReference( this );
  32097. if ( updateType === NodeUpdateType.FRAME ) {
  32098. const { frameMap } = this._getMaps( this.updateMap, reference );
  32099. if ( frameMap.get( reference ) !== this.frameId ) {
  32100. if ( node.update( this ) !== false ) {
  32101. frameMap.set( reference, this.frameId );
  32102. }
  32103. }
  32104. } else if ( updateType === NodeUpdateType.RENDER ) {
  32105. const { renderMap } = this._getMaps( this.updateMap, reference );
  32106. if ( renderMap.get( reference ) !== this.renderId ) {
  32107. if ( node.update( this ) !== false ) {
  32108. renderMap.set( reference, this.renderId );
  32109. }
  32110. }
  32111. } else if ( updateType === NodeUpdateType.OBJECT ) {
  32112. node.update( this );
  32113. }
  32114. }
  32115. update() {
  32116. this.frameId ++;
  32117. if ( this.lastTime === undefined ) this.lastTime = performance.now();
  32118. this.deltaTime = ( performance.now() - this.lastTime ) / 1000;
  32119. this.lastTime = performance.now();
  32120. this.time += this.deltaTime;
  32121. }
  32122. }
  32123. class NodeFunctionInput {
  32124. constructor( type, name, count = null, qualifier = '', isConst = false ) {
  32125. this.type = type;
  32126. this.name = name;
  32127. this.count = count;
  32128. this.qualifier = qualifier;
  32129. this.isConst = isConst;
  32130. }
  32131. }
  32132. NodeFunctionInput.isNodeFunctionInput = true;
  32133. class StructTypeNode extends Node {
  32134. static get type() {
  32135. return 'StructTypeNode';
  32136. }
  32137. constructor( types ) {
  32138. super();
  32139. this.types = types;
  32140. this.isStructTypeNode = true;
  32141. }
  32142. getMemberTypes() {
  32143. return this.types;
  32144. }
  32145. }
  32146. class OutputStructNode extends Node {
  32147. static get type() {
  32148. return 'OutputStructNode';
  32149. }
  32150. constructor( ...members ) {
  32151. super();
  32152. this.members = members;
  32153. this.isOutputStructNode = true;
  32154. }
  32155. setup( builder ) {
  32156. super.setup( builder );
  32157. const members = this.members;
  32158. const types = [];
  32159. for ( let i = 0; i < members.length; i ++ ) {
  32160. types.push( members[ i ].getNodeType( builder ) );
  32161. }
  32162. this.nodeType = builder.getStructTypeFromNode( new StructTypeNode( types ) ).name;
  32163. }
  32164. generate( builder, output ) {
  32165. const propertyName = builder.getOutputStructName();
  32166. const members = this.members;
  32167. const structPrefix = propertyName !== '' ? propertyName + '.' : '';
  32168. for ( let i = 0; i < members.length; i ++ ) {
  32169. const snippet = members[ i ].build( builder, output );
  32170. builder.addLineFlowCode( `${ structPrefix }m${ i } = ${ snippet }`, this );
  32171. }
  32172. return propertyName;
  32173. }
  32174. }
  32175. const outputStruct = /*@__PURE__*/ nodeProxy( OutputStructNode );
  32176. function getTextureIndex( textures, name ) {
  32177. for ( let i = 0; i < textures.length; i ++ ) {
  32178. if ( textures[ i ].name === name ) {
  32179. return i;
  32180. }
  32181. }
  32182. return - 1;
  32183. }
  32184. class MRTNode extends OutputStructNode {
  32185. static get type() {
  32186. return 'MRTNode';
  32187. }
  32188. constructor( outputNodes ) {
  32189. super();
  32190. this.outputNodes = outputNodes;
  32191. this.isMRTNode = true;
  32192. }
  32193. has( name ) {
  32194. return this.outputNodes[ name ] !== undefined;
  32195. }
  32196. get( name ) {
  32197. return this.outputNodes[ name ];
  32198. }
  32199. merge( mrtNode ) {
  32200. const outputs = { ...this.outputNodes, ...mrtNode.outputNodes };
  32201. return mrt( outputs );
  32202. }
  32203. setup( builder ) {
  32204. const outputNodes = this.outputNodes;
  32205. const mrt = builder.renderer.getRenderTarget();
  32206. const members = [];
  32207. const textures = mrt.textures;
  32208. for ( const name in outputNodes ) {
  32209. const index = getTextureIndex( textures, name );
  32210. members[ index ] = vec4( outputNodes[ name ] );
  32211. }
  32212. this.members = members;
  32213. return super.setup( builder );
  32214. }
  32215. }
  32216. const mrt = /*@__PURE__*/ nodeProxy( MRTNode );
  32217. class FunctionOverloadingNode extends Node {
  32218. static get type() {
  32219. return 'FunctionOverloadingNode';
  32220. }
  32221. constructor( functionNodes = [], ...parametersNodes ) {
  32222. super();
  32223. this.functionNodes = functionNodes;
  32224. this.parametersNodes = parametersNodes;
  32225. this._candidateFnCall = null;
  32226. this.global = true;
  32227. }
  32228. getNodeType() {
  32229. return this.functionNodes[ 0 ].shaderNode.layout.type;
  32230. }
  32231. setup( builder ) {
  32232. const params = this.parametersNodes;
  32233. let candidateFnCall = this._candidateFnCall;
  32234. if ( candidateFnCall === null ) {
  32235. let candidateFn = null;
  32236. let candidateScore = - 1;
  32237. for ( const functionNode of this.functionNodes ) {
  32238. const shaderNode = functionNode.shaderNode;
  32239. const layout = shaderNode.layout;
  32240. if ( layout === null ) {
  32241. throw new Error( 'FunctionOverloadingNode: FunctionNode must be a layout.' );
  32242. }
  32243. const inputs = layout.inputs;
  32244. if ( params.length === inputs.length ) {
  32245. let score = 0;
  32246. for ( let i = 0; i < params.length; i ++ ) {
  32247. const param = params[ i ];
  32248. const input = inputs[ i ];
  32249. if ( param.getNodeType( builder ) === input.type ) {
  32250. score ++;
  32251. } else {
  32252. score = 0;
  32253. }
  32254. }
  32255. if ( score > candidateScore ) {
  32256. candidateFn = functionNode;
  32257. candidateScore = score;
  32258. }
  32259. }
  32260. }
  32261. this._candidateFnCall = candidateFnCall = candidateFn( ...params );
  32262. }
  32263. return candidateFnCall;
  32264. }
  32265. }
  32266. const overloadingBaseFn = /*@__PURE__*/ nodeProxy( FunctionOverloadingNode );
  32267. const overloadingFn = ( functionNodes ) => ( ...params ) => overloadingBaseFn( functionNodes, ...params );
  32268. class SpriteSheetUVNode extends Node {
  32269. static get type() {
  32270. return 'SpriteSheetUVNode';
  32271. }
  32272. constructor( countNode, uvNode = uv(), frameNode = float( 0 ) ) {
  32273. super( 'vec2' );
  32274. this.countNode = countNode;
  32275. this.uvNode = uvNode;
  32276. this.frameNode = frameNode;
  32277. }
  32278. setup() {
  32279. const { frameNode, uvNode, countNode } = this;
  32280. const { width, height } = countNode;
  32281. const frameNum = frameNode.mod( width.mul( height ) ).floor();
  32282. const column = frameNum.mod( width );
  32283. const row = height.sub( frameNum.add( 1 ).div( width ).ceil() );
  32284. const scale = countNode.reciprocal();
  32285. const uvFrameOffset = vec2( column, row );
  32286. return uvNode.add( uvFrameOffset ).mul( scale );
  32287. }
  32288. }
  32289. const spritesheetUV = /*@__PURE__*/ nodeProxy( SpriteSheetUVNode );
  32290. class StorageArrayElementNode extends ArrayElementNode {
  32291. static get type() {
  32292. return 'StorageArrayElementNode';
  32293. }
  32294. constructor( storageBufferNode, indexNode ) {
  32295. super( storageBufferNode, indexNode );
  32296. this.isStorageArrayElementNode = true;
  32297. }
  32298. set storageBufferNode( value ) {
  32299. this.node = value;
  32300. }
  32301. get storageBufferNode() {
  32302. return this.node;
  32303. }
  32304. setup( builder ) {
  32305. if ( builder.isAvailable( 'storageBuffer' ) === false ) {
  32306. if ( this.node.bufferObject === true ) {
  32307. builder.setupPBO( this.node );
  32308. }
  32309. }
  32310. return super.setup( builder );
  32311. }
  32312. generate( builder, output ) {
  32313. let snippet;
  32314. const isAssignContext = builder.context.assign;
  32315. //
  32316. if ( builder.isAvailable( 'storageBuffer' ) === false ) {
  32317. if ( this.node.bufferObject === true && isAssignContext !== true ) {
  32318. snippet = builder.generatePBO( this );
  32319. } else {
  32320. snippet = this.node.build( builder );
  32321. }
  32322. } else {
  32323. snippet = super.generate( builder );
  32324. }
  32325. if ( isAssignContext !== true ) {
  32326. const type = this.getNodeType( builder );
  32327. snippet = builder.format( snippet, type, output );
  32328. }
  32329. return snippet;
  32330. }
  32331. }
  32332. const storageElement = /*@__PURE__*/ nodeProxy( StorageArrayElementNode );
  32333. class TriplanarTexturesNode extends Node {
  32334. static get type() {
  32335. return 'TriplanarTexturesNode';
  32336. }
  32337. constructor( textureXNode, textureYNode = null, textureZNode = null, scaleNode = float( 1 ), positionNode = positionLocal, normalNode = normalLocal ) {
  32338. super( 'vec4' );
  32339. this.textureXNode = textureXNode;
  32340. this.textureYNode = textureYNode;
  32341. this.textureZNode = textureZNode;
  32342. this.scaleNode = scaleNode;
  32343. this.positionNode = positionNode;
  32344. this.normalNode = normalNode;
  32345. }
  32346. setup() {
  32347. const { textureXNode, textureYNode, textureZNode, scaleNode, positionNode, normalNode } = this;
  32348. // Ref: https://github.com/keijiro/StandardTriplanar
  32349. // Blending factor of triplanar mapping
  32350. let bf = normalNode.abs().normalize();
  32351. bf = bf.div( bf.dot( vec3( 1.0 ) ) );
  32352. // Triplanar mapping
  32353. const tx = positionNode.yz.mul( scaleNode );
  32354. const ty = positionNode.zx.mul( scaleNode );
  32355. const tz = positionNode.xy.mul( scaleNode );
  32356. // Base color
  32357. const textureX = textureXNode.value;
  32358. const textureY = textureYNode !== null ? textureYNode.value : textureX;
  32359. const textureZ = textureZNode !== null ? textureZNode.value : textureX;
  32360. const cx = texture( textureX, tx ).mul( bf.x );
  32361. const cy = texture( textureY, ty ).mul( bf.y );
  32362. const cz = texture( textureZ, tz ).mul( bf.z );
  32363. return add( cx, cy, cz );
  32364. }
  32365. }
  32366. const triplanarTextures = /*@__PURE__*/ nodeProxy( TriplanarTexturesNode );
  32367. const triplanarTexture = ( ...params ) => triplanarTextures( ...params );
  32368. const _reflectorPlane = new Plane();
  32369. const _normal = new Vector3();
  32370. const _reflectorWorldPosition = new Vector3();
  32371. const _cameraWorldPosition = new Vector3();
  32372. const _rotationMatrix = new Matrix4();
  32373. const _lookAtPosition = new Vector3( 0, 0, - 1 );
  32374. const clipPlane = new Vector4();
  32375. const _view = new Vector3();
  32376. const _target = new Vector3();
  32377. const _q = new Vector4();
  32378. const _size$3 = new Vector2();
  32379. const _defaultRT = new RenderTarget();
  32380. const _defaultUV = screenUV.flipX();
  32381. let _inReflector = false;
  32382. class ReflectorNode extends TextureNode {
  32383. static get type() {
  32384. return 'ReflectorNode';
  32385. }
  32386. constructor( parameters = {} ) {
  32387. super( _defaultRT.texture, _defaultUV );
  32388. const {
  32389. target = new Object3D(),
  32390. resolution = 1,
  32391. generateMipmaps = false,
  32392. bounces = true
  32393. } = parameters;
  32394. //
  32395. this.target = target;
  32396. this.resolution = resolution;
  32397. this.generateMipmaps = generateMipmaps;
  32398. this.bounces = bounces;
  32399. this.updateBeforeType = bounces ? NodeUpdateType.RENDER : NodeUpdateType.FRAME;
  32400. this.virtualCameras = new WeakMap();
  32401. this.renderTargets = new WeakMap();
  32402. }
  32403. _updateResolution( renderTarget, renderer ) {
  32404. const resolution = this.resolution;
  32405. renderer.getDrawingBufferSize( _size$3 );
  32406. renderTarget.setSize( Math.round( _size$3.width * resolution ), Math.round( _size$3.height * resolution ) );
  32407. }
  32408. setup( builder ) {
  32409. this._updateResolution( _defaultRT, builder.renderer );
  32410. return super.setup( builder );
  32411. }
  32412. getVirtualCamera( camera ) {
  32413. let virtualCamera = this.virtualCameras.get( camera );
  32414. if ( virtualCamera === undefined ) {
  32415. virtualCamera = camera.clone();
  32416. this.virtualCameras.set( camera, virtualCamera );
  32417. }
  32418. return virtualCamera;
  32419. }
  32420. getRenderTarget( camera ) {
  32421. let renderTarget = this.renderTargets.get( camera );
  32422. if ( renderTarget === undefined ) {
  32423. renderTarget = new RenderTarget( 0, 0, { type: HalfFloatType } );
  32424. if ( this.generateMipmaps === true ) {
  32425. renderTarget.texture.minFilter = LinearMipMapLinearFilter;
  32426. renderTarget.texture.generateMipmaps = true;
  32427. }
  32428. this.renderTargets.set( camera, renderTarget );
  32429. }
  32430. return renderTarget;
  32431. }
  32432. updateBefore( frame ) {
  32433. if ( this.bounces === false && _inReflector ) return false;
  32434. _inReflector = true;
  32435. const { scene, camera, renderer, material } = frame;
  32436. const { target } = this;
  32437. const virtualCamera = this.getVirtualCamera( camera );
  32438. const renderTarget = this.getRenderTarget( virtualCamera );
  32439. renderer.getDrawingBufferSize( _size$3 );
  32440. this._updateResolution( renderTarget, renderer );
  32441. //
  32442. _reflectorWorldPosition.setFromMatrixPosition( target.matrixWorld );
  32443. _cameraWorldPosition.setFromMatrixPosition( camera.matrixWorld );
  32444. _rotationMatrix.extractRotation( target.matrixWorld );
  32445. _normal.set( 0, 0, 1 );
  32446. _normal.applyMatrix4( _rotationMatrix );
  32447. _view.subVectors( _reflectorWorldPosition, _cameraWorldPosition );
  32448. // Avoid rendering when reflector is facing away
  32449. if ( _view.dot( _normal ) > 0 ) return;
  32450. _view.reflect( _normal ).negate();
  32451. _view.add( _reflectorWorldPosition );
  32452. _rotationMatrix.extractRotation( camera.matrixWorld );
  32453. _lookAtPosition.set( 0, 0, - 1 );
  32454. _lookAtPosition.applyMatrix4( _rotationMatrix );
  32455. _lookAtPosition.add( _cameraWorldPosition );
  32456. _target.subVectors( _reflectorWorldPosition, _lookAtPosition );
  32457. _target.reflect( _normal ).negate();
  32458. _target.add( _reflectorWorldPosition );
  32459. //
  32460. virtualCamera.coordinateSystem = camera.coordinateSystem;
  32461. virtualCamera.position.copy( _view );
  32462. virtualCamera.up.set( 0, 1, 0 );
  32463. virtualCamera.up.applyMatrix4( _rotationMatrix );
  32464. virtualCamera.up.reflect( _normal );
  32465. virtualCamera.lookAt( _target );
  32466. virtualCamera.near = camera.near;
  32467. virtualCamera.far = camera.far;
  32468. virtualCamera.updateMatrixWorld();
  32469. virtualCamera.projectionMatrix.copy( camera.projectionMatrix );
  32470. // Now update projection matrix with new clip plane, implementing code from: http://www.terathon.com/code/oblique.html
  32471. // Paper explaining this technique: http://www.terathon.com/lengyel/Lengyel-Oblique.pdf
  32472. _reflectorPlane.setFromNormalAndCoplanarPoint( _normal, _reflectorWorldPosition );
  32473. _reflectorPlane.applyMatrix4( virtualCamera.matrixWorldInverse );
  32474. clipPlane.set( _reflectorPlane.normal.x, _reflectorPlane.normal.y, _reflectorPlane.normal.z, _reflectorPlane.constant );
  32475. const projectionMatrix = virtualCamera.projectionMatrix;
  32476. _q.x = ( Math.sign( clipPlane.x ) + projectionMatrix.elements[ 8 ] ) / projectionMatrix.elements[ 0 ];
  32477. _q.y = ( Math.sign( clipPlane.y ) + projectionMatrix.elements[ 9 ] ) / projectionMatrix.elements[ 5 ];
  32478. _q.z = - 1.0;
  32479. _q.w = ( 1.0 + projectionMatrix.elements[ 10 ] ) / projectionMatrix.elements[ 14 ];
  32480. // Calculate the scaled plane vector
  32481. clipPlane.multiplyScalar( 1.0 / clipPlane.dot( _q ) );
  32482. const clipBias = 0;
  32483. // Replacing the third row of the projection matrix
  32484. projectionMatrix.elements[ 2 ] = clipPlane.x;
  32485. projectionMatrix.elements[ 6 ] = clipPlane.y;
  32486. projectionMatrix.elements[ 10 ] = clipPlane.z - clipBias;
  32487. projectionMatrix.elements[ 14 ] = clipPlane.w;
  32488. //
  32489. this.value = renderTarget.texture;
  32490. material.visible = false;
  32491. const currentRenderTarget = renderer.getRenderTarget();
  32492. const currentMRT = renderer.getMRT();
  32493. renderer.setMRT( null );
  32494. renderer.setRenderTarget( renderTarget );
  32495. renderer.render( scene, virtualCamera );
  32496. renderer.setMRT( currentMRT );
  32497. renderer.setRenderTarget( currentRenderTarget );
  32498. material.visible = true;
  32499. _inReflector = false;
  32500. }
  32501. }
  32502. const reflector = ( parameters ) => nodeObject( new ReflectorNode( parameters ) );
  32503. // Helper for passes that need to fill the viewport with a single quad.
  32504. const _camera = /*@__PURE__*/ new OrthographicCamera( - 1, 1, 1, - 1, 0, 1 );
  32505. // https://github.com/mrdoob/three.js/pull/21358
  32506. class QuadGeometry extends BufferGeometry {
  32507. constructor( flipY = false ) {
  32508. super();
  32509. const uv = flipY === false ? [ 0, - 1, 0, 1, 2, 1 ] : [ 0, 2, 0, 0, 2, 0 ];
  32510. this.setAttribute( 'position', new Float32BufferAttribute( [ - 1, 3, 0, - 1, - 1, 0, 3, - 1, 0 ], 3 ) );
  32511. this.setAttribute( 'uv', new Float32BufferAttribute( uv, 2 ) );
  32512. }
  32513. }
  32514. const _geometry = /*@__PURE__*/ new QuadGeometry();
  32515. class QuadMesh extends Mesh {
  32516. constructor( material = null ) {
  32517. super( _geometry, material );
  32518. this.camera = _camera;
  32519. this.isQuadMesh = true;
  32520. }
  32521. renderAsync( renderer ) {
  32522. return renderer.renderAsync( this, _camera );
  32523. }
  32524. render( renderer ) {
  32525. renderer.render( this, _camera );
  32526. }
  32527. }
  32528. const _size$2 = /*@__PURE__*/ new Vector2();
  32529. class RTTNode extends TextureNode {
  32530. static get type() {
  32531. return 'RTTNode';
  32532. }
  32533. constructor( node, width = null, height = null, options = { type: HalfFloatType } ) {
  32534. const renderTarget = new RenderTarget( width, height, options );
  32535. super( renderTarget.texture, uv() );
  32536. this.node = node;
  32537. this.width = width;
  32538. this.height = height;
  32539. this.renderTarget = renderTarget;
  32540. this.textureNeedsUpdate = true;
  32541. this.autoUpdate = true;
  32542. this.updateMap = new WeakMap();
  32543. this._rttNode = null;
  32544. this._quadMesh = new QuadMesh( new NodeMaterial() );
  32545. this.updateBeforeType = NodeUpdateType.RENDER;
  32546. }
  32547. get autoSize() {
  32548. return this.width === null;
  32549. }
  32550. setup( builder ) {
  32551. this._rttNode = this.node.context( builder.getSharedContext() );
  32552. this._quadMesh.material.name = 'RTT';
  32553. this._quadMesh.material.needsUpdate = true;
  32554. return super.setup( builder );
  32555. }
  32556. setSize( width, height ) {
  32557. this.width = width;
  32558. this.height = height;
  32559. const effectiveWidth = width * this.pixelRatio;
  32560. const effectiveHeight = height * this.pixelRatio;
  32561. this.renderTarget.setSize( effectiveWidth, effectiveHeight );
  32562. this.textureNeedsUpdate = true;
  32563. }
  32564. setPixelRatio( pixelRatio ) {
  32565. this.pixelRatio = pixelRatio;
  32566. this.setSize( this.width, this.height );
  32567. }
  32568. updateBefore( { renderer } ) {
  32569. if ( this.textureNeedsUpdate === false && this.autoUpdate === false ) return;
  32570. this.textureNeedsUpdate = false;
  32571. //
  32572. if ( this.autoSize === true ) {
  32573. this.pixelRatio = renderer.getPixelRatio();
  32574. const size = renderer.getSize( _size$2 );
  32575. this.setSize( size.width, size.height );
  32576. }
  32577. //
  32578. this._quadMesh.material.fragmentNode = this._rttNode;
  32579. //
  32580. const currentRenderTarget = renderer.getRenderTarget();
  32581. renderer.setRenderTarget( this.renderTarget );
  32582. this._quadMesh.render( renderer );
  32583. renderer.setRenderTarget( currentRenderTarget );
  32584. }
  32585. clone() {
  32586. const newNode = new TextureNode( this.value, this.uvNode, this.levelNode );
  32587. newNode.sampler = this.sampler;
  32588. newNode.referenceNode = this;
  32589. return newNode;
  32590. }
  32591. }
  32592. const rtt = ( node, ...params ) => nodeObject( new RTTNode( nodeObject( node ), ...params ) );
  32593. const convertToTexture = ( node, ...params ) => node.isTextureNode ? node : rtt( node, ...params );
  32594. class VertexColorNode extends AttributeNode {
  32595. static get type() {
  32596. return 'VertexColorNode';
  32597. }
  32598. constructor( index = 0 ) {
  32599. super( null, 'vec4' );
  32600. this.isVertexColorNode = true;
  32601. this.index = index;
  32602. }
  32603. getAttributeName( /*builder*/ ) {
  32604. const index = this.index;
  32605. return 'color' + ( index > 0 ? index : '' );
  32606. }
  32607. generate( builder ) {
  32608. const attributeName = this.getAttributeName( builder );
  32609. const geometryAttribute = builder.hasGeometryAttribute( attributeName );
  32610. let result;
  32611. if ( geometryAttribute === true ) {
  32612. result = super.generate( builder );
  32613. } else {
  32614. // Vertex color fallback should be white
  32615. result = builder.generateConst( this.nodeType, new Vector4( 1, 1, 1, 1 ) );
  32616. }
  32617. return result;
  32618. }
  32619. serialize( data ) {
  32620. super.serialize( data );
  32621. data.index = this.index;
  32622. }
  32623. deserialize( data ) {
  32624. super.deserialize( data );
  32625. this.index = data.index;
  32626. }
  32627. }
  32628. const vertexColor = ( ...params ) => nodeObject( new VertexColorNode( ...params ) );
  32629. class PointUVNode extends Node {
  32630. static get type() {
  32631. return 'PointUVNode';
  32632. }
  32633. constructor() {
  32634. super( 'vec2' );
  32635. this.isPointUVNode = true;
  32636. }
  32637. generate( /*builder*/ ) {
  32638. return 'vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y )';
  32639. }
  32640. }
  32641. const pointUV = /*@__PURE__*/ nodeImmutable( PointUVNode );
  32642. class SceneNode extends Node {
  32643. static get type() {
  32644. return 'SceneNode';
  32645. }
  32646. constructor( scope = SceneNode.BACKGROUND_BLURRINESS, scene = null ) {
  32647. super();
  32648. this.scope = scope;
  32649. this.scene = scene;
  32650. }
  32651. setup( builder ) {
  32652. const scope = this.scope;
  32653. const scene = this.scene !== null ? this.scene : builder.scene;
  32654. let output;
  32655. if ( scope === SceneNode.BACKGROUND_BLURRINESS ) {
  32656. output = reference( 'backgroundBlurriness', 'float', scene );
  32657. } else if ( scope === SceneNode.BACKGROUND_INTENSITY ) {
  32658. output = reference( 'backgroundIntensity', 'float', scene );
  32659. } else {
  32660. console.error( 'THREE.SceneNode: Unknown scope:', scope );
  32661. }
  32662. return output;
  32663. }
  32664. }
  32665. SceneNode.BACKGROUND_BLURRINESS = 'backgroundBlurriness';
  32666. SceneNode.BACKGROUND_INTENSITY = 'backgroundIntensity';
  32667. const backgroundBlurriness = /*@__PURE__*/ nodeImmutable( SceneNode, SceneNode.BACKGROUND_BLURRINESS );
  32668. const backgroundIntensity = /*@__PURE__*/ nodeImmutable( SceneNode, SceneNode.BACKGROUND_INTENSITY );
  32669. const GPUPrimitiveTopology = {
  32670. PointList: 'point-list',
  32671. LineList: 'line-list',
  32672. LineStrip: 'line-strip',
  32673. TriangleList: 'triangle-list',
  32674. TriangleStrip: 'triangle-strip',
  32675. };
  32676. const GPUCompareFunction = {
  32677. Never: 'never',
  32678. Less: 'less',
  32679. Equal: 'equal',
  32680. LessEqual: 'less-equal',
  32681. Greater: 'greater',
  32682. NotEqual: 'not-equal',
  32683. GreaterEqual: 'greater-equal',
  32684. Always: 'always'
  32685. };
  32686. const GPUStoreOp = {
  32687. Store: 'store',
  32688. Discard: 'discard'
  32689. };
  32690. const GPULoadOp = {
  32691. Load: 'load',
  32692. Clear: 'clear'
  32693. };
  32694. const GPUFrontFace = {
  32695. CCW: 'ccw',
  32696. CW: 'cw'
  32697. };
  32698. const GPUCullMode = {
  32699. None: 'none',
  32700. Front: 'front',
  32701. Back: 'back'
  32702. };
  32703. const GPUIndexFormat = {
  32704. Uint16: 'uint16',
  32705. Uint32: 'uint32'
  32706. };
  32707. const GPUTextureFormat = {
  32708. // 8-bit formats
  32709. R8Unorm: 'r8unorm',
  32710. R8Snorm: 'r8snorm',
  32711. R8Uint: 'r8uint',
  32712. R8Sint: 'r8sint',
  32713. // 16-bit formats
  32714. R16Uint: 'r16uint',
  32715. R16Sint: 'r16sint',
  32716. R16Float: 'r16float',
  32717. RG8Unorm: 'rg8unorm',
  32718. RG8Snorm: 'rg8snorm',
  32719. RG8Uint: 'rg8uint',
  32720. RG8Sint: 'rg8sint',
  32721. // 32-bit formats
  32722. R32Uint: 'r32uint',
  32723. R32Sint: 'r32sint',
  32724. R32Float: 'r32float',
  32725. RG16Uint: 'rg16uint',
  32726. RG16Sint: 'rg16sint',
  32727. RG16Float: 'rg16float',
  32728. RGBA8Unorm: 'rgba8unorm',
  32729. RGBA8UnormSRGB: 'rgba8unorm-srgb',
  32730. RGBA8Snorm: 'rgba8snorm',
  32731. RGBA8Uint: 'rgba8uint',
  32732. RGBA8Sint: 'rgba8sint',
  32733. BGRA8Unorm: 'bgra8unorm',
  32734. BGRA8UnormSRGB: 'bgra8unorm-srgb',
  32735. // Packed 32-bit formats
  32736. RGB9E5UFloat: 'rgb9e5ufloat',
  32737. RGB10A2Unorm: 'rgb10a2unorm',
  32738. RG11B10uFloat: 'rgb10a2unorm',
  32739. // 64-bit formats
  32740. RG32Uint: 'rg32uint',
  32741. RG32Sint: 'rg32sint',
  32742. RG32Float: 'rg32float',
  32743. RGBA16Uint: 'rgba16uint',
  32744. RGBA16Sint: 'rgba16sint',
  32745. RGBA16Float: 'rgba16float',
  32746. // 128-bit formats
  32747. RGBA32Uint: 'rgba32uint',
  32748. RGBA32Sint: 'rgba32sint',
  32749. RGBA32Float: 'rgba32float',
  32750. // Depth and stencil formats
  32751. Stencil8: 'stencil8',
  32752. Depth16Unorm: 'depth16unorm',
  32753. Depth24Plus: 'depth24plus',
  32754. Depth24PlusStencil8: 'depth24plus-stencil8',
  32755. Depth32Float: 'depth32float',
  32756. // 'depth32float-stencil8' extension
  32757. Depth32FloatStencil8: 'depth32float-stencil8',
  32758. // BC compressed formats usable if 'texture-compression-bc' is both
  32759. // supported by the device/user agent and enabled in requestDevice.
  32760. BC1RGBAUnorm: 'bc1-rgba-unorm',
  32761. BC1RGBAUnormSRGB: 'bc1-rgba-unorm-srgb',
  32762. BC2RGBAUnorm: 'bc2-rgba-unorm',
  32763. BC2RGBAUnormSRGB: 'bc2-rgba-unorm-srgb',
  32764. BC3RGBAUnorm: 'bc3-rgba-unorm',
  32765. BC3RGBAUnormSRGB: 'bc3-rgba-unorm-srgb',
  32766. BC4RUnorm: 'bc4-r-unorm',
  32767. BC4RSnorm: 'bc4-r-snorm',
  32768. BC5RGUnorm: 'bc5-rg-unorm',
  32769. BC5RGSnorm: 'bc5-rg-snorm',
  32770. BC6HRGBUFloat: 'bc6h-rgb-ufloat',
  32771. BC6HRGBFloat: 'bc6h-rgb-float',
  32772. BC7RGBAUnorm: 'bc7-rgba-unorm',
  32773. BC7RGBAUnormSRGB: 'bc7-rgba-srgb',
  32774. // ETC2 compressed formats usable if 'texture-compression-etc2' is both
  32775. // supported by the device/user agent and enabled in requestDevice.
  32776. ETC2RGB8Unorm: 'etc2-rgb8unorm',
  32777. ETC2RGB8UnormSRGB: 'etc2-rgb8unorm-srgb',
  32778. ETC2RGB8A1Unorm: 'etc2-rgb8a1unorm',
  32779. ETC2RGB8A1UnormSRGB: 'etc2-rgb8a1unorm-srgb',
  32780. ETC2RGBA8Unorm: 'etc2-rgba8unorm',
  32781. ETC2RGBA8UnormSRGB: 'etc2-rgba8unorm-srgb',
  32782. EACR11Unorm: 'eac-r11unorm',
  32783. EACR11Snorm: 'eac-r11snorm',
  32784. EACRG11Unorm: 'eac-rg11unorm',
  32785. EACRG11Snorm: 'eac-rg11snorm',
  32786. // ASTC compressed formats usable if 'texture-compression-astc' is both
  32787. // supported by the device/user agent and enabled in requestDevice.
  32788. ASTC4x4Unorm: 'astc-4x4-unorm',
  32789. ASTC4x4UnormSRGB: 'astc-4x4-unorm-srgb',
  32790. ASTC5x4Unorm: 'astc-5x4-unorm',
  32791. ASTC5x4UnormSRGB: 'astc-5x4-unorm-srgb',
  32792. ASTC5x5Unorm: 'astc-5x5-unorm',
  32793. ASTC5x5UnormSRGB: 'astc-5x5-unorm-srgb',
  32794. ASTC6x5Unorm: 'astc-6x5-unorm',
  32795. ASTC6x5UnormSRGB: 'astc-6x5-unorm-srgb',
  32796. ASTC6x6Unorm: 'astc-6x6-unorm',
  32797. ASTC6x6UnormSRGB: 'astc-6x6-unorm-srgb',
  32798. ASTC8x5Unorm: 'astc-8x5-unorm',
  32799. ASTC8x5UnormSRGB: 'astc-8x5-unorm-srgb',
  32800. ASTC8x6Unorm: 'astc-8x6-unorm',
  32801. ASTC8x6UnormSRGB: 'astc-8x6-unorm-srgb',
  32802. ASTC8x8Unorm: 'astc-8x8-unorm',
  32803. ASTC8x8UnormSRGB: 'astc-8x8-unorm-srgb',
  32804. ASTC10x5Unorm: 'astc-10x5-unorm',
  32805. ASTC10x5UnormSRGB: 'astc-10x5-unorm-srgb',
  32806. ASTC10x6Unorm: 'astc-10x6-unorm',
  32807. ASTC10x6UnormSRGB: 'astc-10x6-unorm-srgb',
  32808. ASTC10x8Unorm: 'astc-10x8-unorm',
  32809. ASTC10x8UnormSRGB: 'astc-10x8-unorm-srgb',
  32810. ASTC10x10Unorm: 'astc-10x10-unorm',
  32811. ASTC10x10UnormSRGB: 'astc-10x10-unorm-srgb',
  32812. ASTC12x10Unorm: 'astc-12x10-unorm',
  32813. ASTC12x10UnormSRGB: 'astc-12x10-unorm-srgb',
  32814. ASTC12x12Unorm: 'astc-12x12-unorm',
  32815. ASTC12x12UnormSRGB: 'astc-12x12-unorm-srgb',
  32816. };
  32817. const GPUAddressMode = {
  32818. ClampToEdge: 'clamp-to-edge',
  32819. Repeat: 'repeat',
  32820. MirrorRepeat: 'mirror-repeat'
  32821. };
  32822. const GPUFilterMode = {
  32823. Linear: 'linear',
  32824. Nearest: 'nearest'
  32825. };
  32826. const GPUBlendFactor = {
  32827. Zero: 'zero',
  32828. One: 'one',
  32829. Src: 'src',
  32830. OneMinusSrc: 'one-minus-src',
  32831. SrcAlpha: 'src-alpha',
  32832. OneMinusSrcAlpha: 'one-minus-src-alpha',
  32833. Dst: 'dst',
  32834. OneMinusDstColor: 'one-minus-dst',
  32835. DstAlpha: 'dst-alpha',
  32836. OneMinusDstAlpha: 'one-minus-dst-alpha',
  32837. SrcAlphaSaturated: 'src-alpha-saturated',
  32838. Constant: 'constant',
  32839. OneMinusConstant: 'one-minus-constant'
  32840. };
  32841. const GPUBlendOperation = {
  32842. Add: 'add',
  32843. Subtract: 'subtract',
  32844. ReverseSubtract: 'reverse-subtract',
  32845. Min: 'min',
  32846. Max: 'max'
  32847. };
  32848. const GPUColorWriteFlags = {
  32849. None: 0,
  32850. Red: 0x1,
  32851. Green: 0x2,
  32852. Blue: 0x4,
  32853. Alpha: 0x8,
  32854. All: 0xF
  32855. };
  32856. const GPUStencilOperation = {
  32857. Keep: 'keep',
  32858. Zero: 'zero',
  32859. Replace: 'replace',
  32860. Invert: 'invert',
  32861. IncrementClamp: 'increment-clamp',
  32862. DecrementClamp: 'decrement-clamp',
  32863. IncrementWrap: 'increment-wrap',
  32864. DecrementWrap: 'decrement-wrap'
  32865. };
  32866. const GPUBufferBindingType = {
  32867. Uniform: 'uniform',
  32868. Storage: 'storage',
  32869. ReadOnlyStorage: 'read-only-storage'
  32870. };
  32871. const GPUStorageTextureAccess = {
  32872. WriteOnly: 'write-only',
  32873. ReadOnly: 'read-only',
  32874. ReadWrite: 'read-write',
  32875. };
  32876. const GPUTextureSampleType = {
  32877. Float: 'float',
  32878. UnfilterableFloat: 'unfilterable-float',
  32879. Depth: 'depth',
  32880. SInt: 'sint',
  32881. UInt: 'uint'
  32882. };
  32883. const GPUTextureDimension = {
  32884. OneD: '1d',
  32885. TwoD: '2d',
  32886. ThreeD: '3d'
  32887. };
  32888. const GPUTextureViewDimension = {
  32889. OneD: '1d',
  32890. TwoD: '2d',
  32891. TwoDArray: '2d-array',
  32892. Cube: 'cube',
  32893. CubeArray: 'cube-array',
  32894. ThreeD: '3d'
  32895. };
  32896. const GPUTextureAspect = {
  32897. All: 'all',
  32898. StencilOnly: 'stencil-only',
  32899. DepthOnly: 'depth-only'
  32900. };
  32901. const GPUInputStepMode = {
  32902. Vertex: 'vertex',
  32903. Instance: 'instance'
  32904. };
  32905. const GPUFeatureName = {
  32906. DepthClipControl: 'depth-clip-control',
  32907. Depth32FloatStencil8: 'depth32float-stencil8',
  32908. TextureCompressionBC: 'texture-compression-bc',
  32909. TextureCompressionETC2: 'texture-compression-etc2',
  32910. TextureCompressionASTC: 'texture-compression-astc',
  32911. TimestampQuery: 'timestamp-query',
  32912. IndirectFirstInstance: 'indirect-first-instance',
  32913. ShaderF16: 'shader-f16',
  32914. RG11B10UFloat: 'rg11b10ufloat-renderable',
  32915. BGRA8UNormStorage: 'bgra8unorm-storage',
  32916. Float32Filterable: 'float32-filterable',
  32917. ClipDistances: 'clip-distances',
  32918. DualSourceBlending: 'dual-source-blending',
  32919. Subgroups: 'subgroups'
  32920. };
  32921. class StorageBufferNode extends BufferNode {
  32922. static get type() {
  32923. return 'StorageBufferNode';
  32924. }
  32925. constructor( value, bufferType, bufferCount = 0 ) {
  32926. super( value, bufferType, bufferCount );
  32927. this.isStorageBufferNode = true;
  32928. this.access = GPUBufferBindingType.Storage;
  32929. this.isAtomic = false;
  32930. this.bufferObject = false;
  32931. this.bufferCount = bufferCount;
  32932. this._attribute = null;
  32933. this._varying = null;
  32934. this.global = true;
  32935. if ( value.isStorageBufferAttribute !== true && value.isStorageInstancedBufferAttribute !== true ) {
  32936. // TOOD: Improve it, possibly adding a new property to the BufferAttribute to identify it as a storage buffer read-only attribute in Renderer
  32937. if ( value.isInstancedBufferAttribute ) value.isStorageInstancedBufferAttribute = true;
  32938. else value.isStorageBufferAttribute = true;
  32939. }
  32940. }
  32941. getHash( builder ) {
  32942. if ( this.bufferCount === 0 ) {
  32943. let bufferData = builder.globalCache.getData( this.value );
  32944. if ( bufferData === undefined ) {
  32945. bufferData = {
  32946. node: this
  32947. };
  32948. builder.globalCache.setData( this.value, bufferData );
  32949. }
  32950. return bufferData.node.uuid;
  32951. }
  32952. return this.uuid;
  32953. }
  32954. getInputType( /*builder*/ ) {
  32955. return this.value.isIndirectStorageBufferAttribute ? 'indirectStorageBuffer' : 'storageBuffer';
  32956. }
  32957. element( indexNode ) {
  32958. return storageElement( this, indexNode );
  32959. }
  32960. setBufferObject( value ) {
  32961. this.bufferObject = value;
  32962. return this;
  32963. }
  32964. setAccess( value ) {
  32965. this.access = value;
  32966. return this;
  32967. }
  32968. toReadOnly() {
  32969. return this.setAccess( GPUBufferBindingType.ReadOnlyStorage );
  32970. }
  32971. setAtomic( value ) {
  32972. this.isAtomic = value;
  32973. return this;
  32974. }
  32975. toAtomic() {
  32976. return this.setAtomic( true );
  32977. }
  32978. getAttributeData() {
  32979. if ( this._attribute === null ) {
  32980. this._attribute = bufferAttribute( this.value );
  32981. this._varying = varying( this._attribute );
  32982. }
  32983. return {
  32984. attribute: this._attribute,
  32985. varying: this._varying
  32986. };
  32987. }
  32988. getNodeType( builder ) {
  32989. if ( builder.isAvailable( 'storageBuffer' ) || builder.isAvailable( 'indirectStorageBuffer' ) ) {
  32990. return super.getNodeType( builder );
  32991. }
  32992. const { attribute } = this.getAttributeData();
  32993. return attribute.getNodeType( builder );
  32994. }
  32995. generate( builder ) {
  32996. if ( builder.isAvailable( 'storageBuffer' ) || builder.isAvailable( 'indirectStorageBuffer' ) ) {
  32997. return super.generate( builder );
  32998. }
  32999. const { attribute, varying } = this.getAttributeData();
  33000. const output = varying.build( builder );
  33001. builder.registerTransform( output, attribute );
  33002. return output;
  33003. }
  33004. }
  33005. // Read-Write Storage
  33006. const storage = ( value, type, count ) => nodeObject( new StorageBufferNode( value, type, count ) );
  33007. const storageObject = ( value, type, count ) => nodeObject( new StorageBufferNode( value, type, count ).setBufferObject( true ) );
  33008. class StorageTextureNode extends TextureNode {
  33009. static get type() {
  33010. return 'StorageTextureNode';
  33011. }
  33012. constructor( value, uvNode, storeNode = null ) {
  33013. super( value, uvNode );
  33014. this.storeNode = storeNode;
  33015. this.isStorageTextureNode = true;
  33016. this.access = GPUStorageTextureAccess.WriteOnly;
  33017. }
  33018. getInputType( /*builder*/ ) {
  33019. return 'storageTexture';
  33020. }
  33021. setup( builder ) {
  33022. super.setup( builder );
  33023. const properties = builder.getNodeProperties( this );
  33024. properties.storeNode = this.storeNode;
  33025. }
  33026. setAccess( value ) {
  33027. this.access = value;
  33028. return this;
  33029. }
  33030. generate( builder, output ) {
  33031. let snippet;
  33032. if ( this.storeNode !== null ) {
  33033. snippet = this.generateStore( builder );
  33034. } else {
  33035. snippet = super.generate( builder, output );
  33036. }
  33037. return snippet;
  33038. }
  33039. toReadOnly() {
  33040. return this.setAccess( GPUStorageTextureAccess.ReadOnly );
  33041. }
  33042. toWriteOnly() {
  33043. return this.setAccess( GPUStorageTextureAccess.WriteOnly );
  33044. }
  33045. generateStore( builder ) {
  33046. const properties = builder.getNodeProperties( this );
  33047. const { uvNode, storeNode } = properties;
  33048. const textureProperty = super.generate( builder, 'property' );
  33049. const uvSnippet = uvNode.build( builder, 'uvec2' );
  33050. const storeSnippet = storeNode.build( builder, 'vec4' );
  33051. const snippet = builder.generateTextureStore( builder, textureProperty, uvSnippet, storeSnippet );
  33052. builder.addLineFlowCode( snippet, this );
  33053. }
  33054. }
  33055. const storageTexture = /*@__PURE__*/ nodeProxy( StorageTextureNode );
  33056. const textureStore = ( value, uvNode, storeNode ) => {
  33057. const node = storageTexture( value, uvNode, storeNode );
  33058. if ( storeNode !== null ) node.append();
  33059. return node;
  33060. };
  33061. class UserDataNode extends ReferenceNode {
  33062. static get type() {
  33063. return 'UserDataNode';
  33064. }
  33065. constructor( property, inputType, userData = null ) {
  33066. super( property, inputType, userData );
  33067. this.userData = userData;
  33068. }
  33069. updateReference( state ) {
  33070. this.reference = this.userData !== null ? this.userData : state.object.userData;
  33071. return this.reference;
  33072. }
  33073. }
  33074. const userData = ( name, inputType, userData ) => nodeObject( new UserDataNode( name, inputType, userData ) );
  33075. class PosterizeNode extends TempNode {
  33076. static get type() {
  33077. return 'PosterizeNode';
  33078. }
  33079. constructor( sourceNode, stepsNode ) {
  33080. super();
  33081. this.sourceNode = sourceNode;
  33082. this.stepsNode = stepsNode;
  33083. }
  33084. setup() {
  33085. const { sourceNode, stepsNode } = this;
  33086. return sourceNode.mul( stepsNode ).floor().div( stepsNode );
  33087. }
  33088. }
  33089. const posterize = /*@__PURE__*/ nodeProxy( PosterizeNode );
  33090. let _sharedFramebuffer = null;
  33091. class ViewportSharedTextureNode extends ViewportTextureNode {
  33092. static get type() {
  33093. return 'ViewportSharedTextureNode';
  33094. }
  33095. constructor( uvNode = screenUV, levelNode = null ) {
  33096. if ( _sharedFramebuffer === null ) {
  33097. _sharedFramebuffer = new FramebufferTexture();
  33098. }
  33099. super( uvNode, levelNode, _sharedFramebuffer );
  33100. }
  33101. updateReference() {
  33102. return this;
  33103. }
  33104. }
  33105. const viewportSharedTexture = /*@__PURE__*/ nodeProxy( ViewportSharedTextureNode );
  33106. const _size$1 = /*@__PURE__*/ new Vector2();
  33107. class PassTextureNode extends TextureNode {
  33108. static get type() {
  33109. return 'PassTextureNode';
  33110. }
  33111. constructor( passNode, texture ) {
  33112. super( texture );
  33113. this.passNode = passNode;
  33114. this.setUpdateMatrix( false );
  33115. }
  33116. setup( builder ) {
  33117. if ( builder.object.isQuadMesh ) this.passNode.build( builder );
  33118. return super.setup( builder );
  33119. }
  33120. clone() {
  33121. return new this.constructor( this.passNode, this.value );
  33122. }
  33123. }
  33124. class PassMultipleTextureNode extends PassTextureNode {
  33125. static get type() {
  33126. return 'PassMultipleTextureNode';
  33127. }
  33128. constructor( passNode, textureName, previousTexture = false ) {
  33129. super( passNode, null );
  33130. this.textureName = textureName;
  33131. this.previousTexture = previousTexture;
  33132. }
  33133. updateTexture() {
  33134. this.value = this.previousTexture ? this.passNode.getPreviousTexture( this.textureName ) : this.passNode.getTexture( this.textureName );
  33135. }
  33136. setup( builder ) {
  33137. this.updateTexture();
  33138. return super.setup( builder );
  33139. }
  33140. clone() {
  33141. return new this.constructor( this.passNode, this.textureName, this.previousTexture );
  33142. }
  33143. }
  33144. class PassNode extends TempNode {
  33145. static get type() {
  33146. return 'PassNode';
  33147. }
  33148. constructor( scope, scene, camera, options = {} ) {
  33149. super( 'vec4' );
  33150. this.scope = scope;
  33151. this.scene = scene;
  33152. this.camera = camera;
  33153. this.options = options;
  33154. this._pixelRatio = 1;
  33155. this._width = 1;
  33156. this._height = 1;
  33157. const depthTexture = new DepthTexture();
  33158. depthTexture.isRenderTargetTexture = true;
  33159. //depthTexture.type = FloatType;
  33160. depthTexture.name = 'depth';
  33161. const renderTarget = new RenderTarget( this._width * this._pixelRatio, this._height * this._pixelRatio, { type: HalfFloatType, ...options, } );
  33162. renderTarget.texture.name = 'output';
  33163. renderTarget.depthTexture = depthTexture;
  33164. this.renderTarget = renderTarget;
  33165. this.updateBeforeType = NodeUpdateType.FRAME;
  33166. this._textures = {
  33167. output: renderTarget.texture,
  33168. depth: depthTexture
  33169. };
  33170. this._textureNodes = {};
  33171. this._linearDepthNodes = {};
  33172. this._viewZNodes = {};
  33173. this._previousTextures = {};
  33174. this._previousTextureNodes = {};
  33175. this._cameraNear = uniform( 0 );
  33176. this._cameraFar = uniform( 0 );
  33177. this._mrt = null;
  33178. this.isPassNode = true;
  33179. }
  33180. setMRT( mrt ) {
  33181. this._mrt = mrt;
  33182. return this;
  33183. }
  33184. getMRT() {
  33185. return this._mrt;
  33186. }
  33187. isGlobal() {
  33188. return true;
  33189. }
  33190. getTexture( name ) {
  33191. let texture = this._textures[ name ];
  33192. if ( texture === undefined ) {
  33193. const refTexture = this.renderTarget.texture;
  33194. texture = refTexture.clone();
  33195. texture.isRenderTargetTexture = true;
  33196. texture.name = name;
  33197. this._textures[ name ] = texture;
  33198. this.renderTarget.textures.push( texture );
  33199. }
  33200. return texture;
  33201. }
  33202. getPreviousTexture( name ) {
  33203. let texture = this._previousTextures[ name ];
  33204. if ( texture === undefined ) {
  33205. texture = this.getTexture( name ).clone();
  33206. texture.isRenderTargetTexture = true;
  33207. this._previousTextures[ name ] = texture;
  33208. }
  33209. return texture;
  33210. }
  33211. toggleTexture( name ) {
  33212. const prevTexture = this._previousTextures[ name ];
  33213. if ( prevTexture !== undefined ) {
  33214. const texture = this._textures[ name ];
  33215. const index = this.renderTarget.textures.indexOf( texture );
  33216. this.renderTarget.textures[ index ] = prevTexture;
  33217. this._textures[ name ] = prevTexture;
  33218. this._previousTextures[ name ] = texture;
  33219. this._textureNodes[ name ].updateTexture();
  33220. this._previousTextureNodes[ name ].updateTexture();
  33221. }
  33222. }
  33223. getTextureNode( name = 'output' ) {
  33224. let textureNode = this._textureNodes[ name ];
  33225. if ( textureNode === undefined ) {
  33226. this._textureNodes[ name ] = textureNode = nodeObject( new PassMultipleTextureNode( this, name ) );
  33227. this._textureNodes[ name ].updateTexture();
  33228. }
  33229. return textureNode;
  33230. }
  33231. getPreviousTextureNode( name = 'output' ) {
  33232. let textureNode = this._previousTextureNodes[ name ];
  33233. if ( textureNode === undefined ) {
  33234. if ( this._textureNodes[ name ] === undefined ) this.getTextureNode( name );
  33235. this._previousTextureNodes[ name ] = textureNode = nodeObject( new PassMultipleTextureNode( this, name, true ) );
  33236. this._previousTextureNodes[ name ].updateTexture();
  33237. }
  33238. return textureNode;
  33239. }
  33240. getViewZNode( name = 'depth' ) {
  33241. let viewZNode = this._viewZNodes[ name ];
  33242. if ( viewZNode === undefined ) {
  33243. const cameraNear = this._cameraNear;
  33244. const cameraFar = this._cameraFar;
  33245. this._viewZNodes[ name ] = viewZNode = perspectiveDepthToViewZ( this.getTextureNode( name ), cameraNear, cameraFar );
  33246. }
  33247. return viewZNode;
  33248. }
  33249. getLinearDepthNode( name = 'depth' ) {
  33250. let linearDepthNode = this._linearDepthNodes[ name ];
  33251. if ( linearDepthNode === undefined ) {
  33252. const cameraNear = this._cameraNear;
  33253. const cameraFar = this._cameraFar;
  33254. const viewZNode = this.getViewZNode( name );
  33255. // TODO: just if ( builder.camera.isPerspectiveCamera )
  33256. this._linearDepthNodes[ name ] = linearDepthNode = viewZToOrthographicDepth( viewZNode, cameraNear, cameraFar );
  33257. }
  33258. return linearDepthNode;
  33259. }
  33260. setup( { renderer } ) {
  33261. this.renderTarget.samples = this.options.samples === undefined ? renderer.samples : this.options.samples;
  33262. // Disable MSAA for WebGL backend for now
  33263. if ( renderer.backend.isWebGLBackend === true ) {
  33264. this.renderTarget.samples = 0;
  33265. }
  33266. this.renderTarget.depthTexture.isMultisampleRenderTargetTexture = this.renderTarget.samples > 1;
  33267. return this.scope === PassNode.COLOR ? this.getTextureNode() : this.getLinearDepthNode();
  33268. }
  33269. updateBefore( frame ) {
  33270. const { renderer } = frame;
  33271. const { scene, camera } = this;
  33272. this._pixelRatio = renderer.getPixelRatio();
  33273. const size = renderer.getSize( _size$1 );
  33274. this.setSize( size.width, size.height );
  33275. const currentRenderTarget = renderer.getRenderTarget();
  33276. const currentMRT = renderer.getMRT();
  33277. this._cameraNear.value = camera.near;
  33278. this._cameraFar.value = camera.far;
  33279. for ( const name in this._previousTextures ) {
  33280. this.toggleTexture( name );
  33281. }
  33282. renderer.setRenderTarget( this.renderTarget );
  33283. renderer.setMRT( this._mrt );
  33284. renderer.render( scene, camera );
  33285. renderer.setRenderTarget( currentRenderTarget );
  33286. renderer.setMRT( currentMRT );
  33287. }
  33288. setSize( width, height ) {
  33289. this._width = width;
  33290. this._height = height;
  33291. const effectiveWidth = this._width * this._pixelRatio;
  33292. const effectiveHeight = this._height * this._pixelRatio;
  33293. this.renderTarget.setSize( effectiveWidth, effectiveHeight );
  33294. }
  33295. setPixelRatio( pixelRatio ) {
  33296. this._pixelRatio = pixelRatio;
  33297. this.setSize( this._width, this._height );
  33298. }
  33299. dispose() {
  33300. this.renderTarget.dispose();
  33301. }
  33302. }
  33303. PassNode.COLOR = 'color';
  33304. PassNode.DEPTH = 'depth';
  33305. const pass = ( scene, camera, options ) => nodeObject( new PassNode( PassNode.COLOR, scene, camera, options ) );
  33306. const passTexture = ( pass, texture ) => nodeObject( new PassTextureNode( pass, texture ) );
  33307. const depthPass = ( scene, camera ) => nodeObject( new PassNode( PassNode.DEPTH, scene, camera ) );
  33308. class ToonOutlinePassNode extends PassNode {
  33309. static get type() {
  33310. return 'ToonOutlinePassNode';
  33311. }
  33312. constructor( scene, camera, colorNode, thicknessNode, alphaNode ) {
  33313. super( PassNode.COLOR, scene, camera );
  33314. this.colorNode = colorNode;
  33315. this.thicknessNode = thicknessNode;
  33316. this.alphaNode = alphaNode;
  33317. this._materialCache = new WeakMap();
  33318. }
  33319. updateBefore( frame ) {
  33320. const { renderer } = frame;
  33321. const currentRenderObjectFunction = renderer.getRenderObjectFunction();
  33322. renderer.setRenderObjectFunction( ( object, scene, camera, geometry, material, group, lightsNode ) => {
  33323. // only render outline for supported materials
  33324. if ( material.isMeshToonMaterial || material.isMeshToonNodeMaterial ) {
  33325. if ( material.wireframe === false ) {
  33326. const outlineMaterial = this._getOutlineMaterial( material );
  33327. renderer.renderObject( object, scene, camera, geometry, outlineMaterial, group, lightsNode );
  33328. }
  33329. }
  33330. // default
  33331. renderer.renderObject( object, scene, camera, geometry, material, group, lightsNode );
  33332. } );
  33333. super.updateBefore( frame );
  33334. renderer.setRenderObjectFunction( currentRenderObjectFunction );
  33335. }
  33336. _createMaterial() {
  33337. const material = new NodeMaterial();
  33338. material.isMeshToonOutlineMaterial = true;
  33339. material.name = 'Toon_Outline';
  33340. material.side = BackSide;
  33341. // vertex node
  33342. const outlineNormal = normalLocal.negate();
  33343. const mvp = cameraProjectionMatrix.mul( modelViewMatrix );
  33344. const ratio = float( 1.0 ); // TODO: support outline thickness ratio for each vertex
  33345. const pos = mvp.mul( vec4( positionLocal, 1.0 ) );
  33346. const pos2 = mvp.mul( vec4( positionLocal.add( outlineNormal ), 1.0 ) );
  33347. const norm = normalize( pos.sub( pos2 ) ); // NOTE: subtract pos2 from pos because BackSide objectNormal is negative
  33348. material.vertexNode = pos.add( norm.mul( this.thicknessNode ).mul( pos.w ).mul( ratio ) );
  33349. // color node
  33350. material.colorNode = vec4( this.colorNode, this.alphaNode );
  33351. return material;
  33352. }
  33353. _getOutlineMaterial( originalMaterial ) {
  33354. let outlineMaterial = this._materialCache.get( originalMaterial );
  33355. if ( outlineMaterial === undefined ) {
  33356. outlineMaterial = this._createMaterial();
  33357. this._materialCache.set( originalMaterial, outlineMaterial );
  33358. }
  33359. return outlineMaterial;
  33360. }
  33361. }
  33362. const toonOutlinePass = ( scene, camera, color = new Color( 0, 0, 0 ), thickness = 0.003, alpha = 1 ) => nodeObject( new ToonOutlinePassNode( scene, camera, nodeObject( color ), nodeObject( thickness ), nodeObject( alpha ) ) );
  33363. class ScriptableValueNode extends Node {
  33364. static get type() {
  33365. return 'ScriptableValueNode';
  33366. }
  33367. constructor( value = null ) {
  33368. super();
  33369. this._value = value;
  33370. this._cache = null;
  33371. this.inputType = null;
  33372. this.outpuType = null;
  33373. this.events = new EventDispatcher();
  33374. this.isScriptableValueNode = true;
  33375. }
  33376. get isScriptableOutputNode() {
  33377. return this.outputType !== null;
  33378. }
  33379. set value( val ) {
  33380. if ( this._value === val ) return;
  33381. if ( this._cache && this.inputType === 'URL' && this.value.value instanceof ArrayBuffer ) {
  33382. URL.revokeObjectURL( this._cache );
  33383. this._cache = null;
  33384. }
  33385. this._value = val;
  33386. this.events.dispatchEvent( { type: 'change' } );
  33387. this.refresh();
  33388. }
  33389. get value() {
  33390. return this._value;
  33391. }
  33392. refresh() {
  33393. this.events.dispatchEvent( { type: 'refresh' } );
  33394. }
  33395. getValue() {
  33396. const value = this.value;
  33397. if ( value && this._cache === null && this.inputType === 'URL' && value.value instanceof ArrayBuffer ) {
  33398. this._cache = URL.createObjectURL( new Blob( [ value.value ] ) );
  33399. } else if ( value && value.value !== null && value.value !== undefined && (
  33400. ( ( this.inputType === 'URL' || this.inputType === 'String' ) && typeof value.value === 'string' ) ||
  33401. ( this.inputType === 'Number' && typeof value.value === 'number' ) ||
  33402. ( this.inputType === 'Vector2' && value.value.isVector2 ) ||
  33403. ( this.inputType === 'Vector3' && value.value.isVector3 ) ||
  33404. ( this.inputType === 'Vector4' && value.value.isVector4 ) ||
  33405. ( this.inputType === 'Color' && value.value.isColor ) ||
  33406. ( this.inputType === 'Matrix3' && value.value.isMatrix3 ) ||
  33407. ( this.inputType === 'Matrix4' && value.value.isMatrix4 )
  33408. ) ) {
  33409. return value.value;
  33410. }
  33411. return this._cache || value;
  33412. }
  33413. getNodeType( builder ) {
  33414. return this.value && this.value.isNode ? this.value.getNodeType( builder ) : 'float';
  33415. }
  33416. setup() {
  33417. return this.value && this.value.isNode ? this.value : float();
  33418. }
  33419. serialize( data ) {
  33420. super.serialize( data );
  33421. if ( this.value !== null ) {
  33422. if ( this.inputType === 'ArrayBuffer' ) {
  33423. data.value = arrayBufferToBase64( this.value );
  33424. } else {
  33425. data.value = this.value ? this.value.toJSON( data.meta ).uuid : null;
  33426. }
  33427. } else {
  33428. data.value = null;
  33429. }
  33430. data.inputType = this.inputType;
  33431. data.outputType = this.outputType;
  33432. }
  33433. deserialize( data ) {
  33434. super.deserialize( data );
  33435. let value = null;
  33436. if ( data.value !== null ) {
  33437. if ( data.inputType === 'ArrayBuffer' ) {
  33438. value = base64ToArrayBuffer( data.value );
  33439. } else if ( data.inputType === 'Texture' ) {
  33440. value = data.meta.textures[ data.value ];
  33441. } else {
  33442. value = data.meta.nodes[ data.value ] || null;
  33443. }
  33444. }
  33445. this.value = value;
  33446. this.inputType = data.inputType;
  33447. this.outputType = data.outputType;
  33448. }
  33449. }
  33450. const scriptableValue = /*@__PURE__*/ nodeProxy( ScriptableValueNode );
  33451. class Resources extends Map {
  33452. get( key, callback = null, ...params ) {
  33453. if ( this.has( key ) ) return super.get( key );
  33454. if ( callback !== null ) {
  33455. const value = callback( ...params );
  33456. this.set( key, value );
  33457. return value;
  33458. }
  33459. }
  33460. }
  33461. class Parameters {
  33462. constructor( scriptableNode ) {
  33463. this.scriptableNode = scriptableNode;
  33464. }
  33465. get parameters() {
  33466. return this.scriptableNode.parameters;
  33467. }
  33468. get layout() {
  33469. return this.scriptableNode.getLayout();
  33470. }
  33471. getInputLayout( id ) {
  33472. return this.scriptableNode.getInputLayout( id );
  33473. }
  33474. get( name ) {
  33475. const param = this.parameters[ name ];
  33476. const value = param ? param.getValue() : null;
  33477. return value;
  33478. }
  33479. }
  33480. const global = new Resources();
  33481. class ScriptableNode extends Node {
  33482. static get type() {
  33483. return 'ScriptableNode';
  33484. }
  33485. constructor( codeNode = null, parameters = {} ) {
  33486. super();
  33487. this.codeNode = codeNode;
  33488. this.parameters = parameters;
  33489. this._local = new Resources();
  33490. this._output = scriptableValue();
  33491. this._outputs = {};
  33492. this._source = this.source;
  33493. this._method = null;
  33494. this._object = null;
  33495. this._value = null;
  33496. this._needsOutputUpdate = true;
  33497. this.onRefresh = this.onRefresh.bind( this );
  33498. this.isScriptableNode = true;
  33499. }
  33500. get source() {
  33501. return this.codeNode ? this.codeNode.code : '';
  33502. }
  33503. setLocal( name, value ) {
  33504. return this._local.set( name, value );
  33505. }
  33506. getLocal( name ) {
  33507. return this._local.get( name );
  33508. }
  33509. onRefresh() {
  33510. this._refresh();
  33511. }
  33512. getInputLayout( id ) {
  33513. for ( const element of this.getLayout() ) {
  33514. if ( element.inputType && ( element.id === id || element.name === id ) ) {
  33515. return element;
  33516. }
  33517. }
  33518. }
  33519. getOutputLayout( id ) {
  33520. for ( const element of this.getLayout() ) {
  33521. if ( element.outputType && ( element.id === id || element.name === id ) ) {
  33522. return element;
  33523. }
  33524. }
  33525. }
  33526. setOutput( name, value ) {
  33527. const outputs = this._outputs;
  33528. if ( outputs[ name ] === undefined ) {
  33529. outputs[ name ] = scriptableValue( value );
  33530. } else {
  33531. outputs[ name ].value = value;
  33532. }
  33533. return this;
  33534. }
  33535. getOutput( name ) {
  33536. return this._outputs[ name ];
  33537. }
  33538. getParameter( name ) {
  33539. return this.parameters[ name ];
  33540. }
  33541. setParameter( name, value ) {
  33542. const parameters = this.parameters;
  33543. if ( value && value.isScriptableNode ) {
  33544. this.deleteParameter( name );
  33545. parameters[ name ] = value;
  33546. parameters[ name ].getDefaultOutput().events.addEventListener( 'refresh', this.onRefresh );
  33547. } else if ( value && value.isScriptableValueNode ) {
  33548. this.deleteParameter( name );
  33549. parameters[ name ] = value;
  33550. parameters[ name ].events.addEventListener( 'refresh', this.onRefresh );
  33551. } else if ( parameters[ name ] === undefined ) {
  33552. parameters[ name ] = scriptableValue( value );
  33553. parameters[ name ].events.addEventListener( 'refresh', this.onRefresh );
  33554. } else {
  33555. parameters[ name ].value = value;
  33556. }
  33557. return this;
  33558. }
  33559. getValue() {
  33560. return this.getDefaultOutput().getValue();
  33561. }
  33562. deleteParameter( name ) {
  33563. let valueNode = this.parameters[ name ];
  33564. if ( valueNode ) {
  33565. if ( valueNode.isScriptableNode ) valueNode = valueNode.getDefaultOutput();
  33566. valueNode.events.removeEventListener( 'refresh', this.onRefresh );
  33567. }
  33568. return this;
  33569. }
  33570. clearParameters() {
  33571. for ( const name of Object.keys( this.parameters ) ) {
  33572. this.deleteParameter( name );
  33573. }
  33574. this.needsUpdate = true;
  33575. return this;
  33576. }
  33577. call( name, ...params ) {
  33578. const object = this.getObject();
  33579. const method = object[ name ];
  33580. if ( typeof method === 'function' ) {
  33581. return method( ...params );
  33582. }
  33583. }
  33584. async callAsync( name, ...params ) {
  33585. const object = this.getObject();
  33586. const method = object[ name ];
  33587. if ( typeof method === 'function' ) {
  33588. return method.constructor.name === 'AsyncFunction' ? await method( ...params ) : method( ...params );
  33589. }
  33590. }
  33591. getNodeType( builder ) {
  33592. return this.getDefaultOutputNode().getNodeType( builder );
  33593. }
  33594. refresh( output = null ) {
  33595. if ( output !== null ) {
  33596. this.getOutput( output ).refresh();
  33597. } else {
  33598. this._refresh();
  33599. }
  33600. }
  33601. getObject() {
  33602. if ( this.needsUpdate ) this.dispose();
  33603. if ( this._object !== null ) return this._object;
  33604. //
  33605. const refresh = () => this.refresh();
  33606. const setOutput = ( id, value ) => this.setOutput( id, value );
  33607. const parameters = new Parameters( this );
  33608. const THREE = global.get( 'THREE' );
  33609. const TSL = global.get( 'TSL' );
  33610. const method = this.getMethod( this.codeNode );
  33611. const params = [ parameters, this._local, global, refresh, setOutput, THREE, TSL ];
  33612. this._object = method( ...params );
  33613. const layout = this._object.layout;
  33614. if ( layout ) {
  33615. if ( layout.cache === false ) {
  33616. this._local.clear();
  33617. }
  33618. // default output
  33619. this._output.outputType = layout.outputType || null;
  33620. if ( Array.isArray( layout.elements ) ) {
  33621. for ( const element of layout.elements ) {
  33622. const id = element.id || element.name;
  33623. if ( element.inputType ) {
  33624. if ( this.getParameter( id ) === undefined ) this.setParameter( id, null );
  33625. this.getParameter( id ).inputType = element.inputType;
  33626. }
  33627. if ( element.outputType ) {
  33628. if ( this.getOutput( id ) === undefined ) this.setOutput( id, null );
  33629. this.getOutput( id ).outputType = element.outputType;
  33630. }
  33631. }
  33632. }
  33633. }
  33634. return this._object;
  33635. }
  33636. deserialize( data ) {
  33637. super.deserialize( data );
  33638. for ( const name in this.parameters ) {
  33639. let valueNode = this.parameters[ name ];
  33640. if ( valueNode.isScriptableNode ) valueNode = valueNode.getDefaultOutput();
  33641. valueNode.events.addEventListener( 'refresh', this.onRefresh );
  33642. }
  33643. }
  33644. getLayout() {
  33645. return this.getObject().layout;
  33646. }
  33647. getDefaultOutputNode() {
  33648. const output = this.getDefaultOutput().value;
  33649. if ( output && output.isNode ) {
  33650. return output;
  33651. }
  33652. return float();
  33653. }
  33654. getDefaultOutput() {
  33655. return this._exec()._output;
  33656. }
  33657. getMethod() {
  33658. if ( this.needsUpdate ) this.dispose();
  33659. if ( this._method !== null ) return this._method;
  33660. //
  33661. const parametersProps = [ 'parameters', 'local', 'global', 'refresh', 'setOutput', 'THREE', 'TSL' ];
  33662. const interfaceProps = [ 'layout', 'init', 'main', 'dispose' ];
  33663. const properties = interfaceProps.join( ', ' );
  33664. const declarations = 'var ' + properties + '; var output = {};\n';
  33665. const returns = '\nreturn { ...output, ' + properties + ' };';
  33666. const code = declarations + this.codeNode.code + returns;
  33667. //
  33668. this._method = new Function( ...parametersProps, code );
  33669. return this._method;
  33670. }
  33671. dispose() {
  33672. if ( this._method === null ) return;
  33673. if ( this._object && typeof this._object.dispose === 'function' ) {
  33674. this._object.dispose();
  33675. }
  33676. this._method = null;
  33677. this._object = null;
  33678. this._source = null;
  33679. this._value = null;
  33680. this._needsOutputUpdate = true;
  33681. this._output.value = null;
  33682. this._outputs = {};
  33683. }
  33684. setup() {
  33685. return this.getDefaultOutputNode();
  33686. }
  33687. getCacheKey( force ) {
  33688. const values = [ hashString( this.source ), this.getDefaultOutputNode().getCacheKey( force ) ];
  33689. for ( const param in this.parameters ) {
  33690. values.push( this.parameters[ param ].getCacheKey( force ) );
  33691. }
  33692. return hashArray( values );
  33693. }
  33694. set needsUpdate( value ) {
  33695. if ( value === true ) this.dispose();
  33696. }
  33697. get needsUpdate() {
  33698. return this.source !== this._source;
  33699. }
  33700. _exec() {
  33701. if ( this.codeNode === null ) return this;
  33702. if ( this._needsOutputUpdate === true ) {
  33703. this._value = this.call( 'main' );
  33704. this._needsOutputUpdate = false;
  33705. }
  33706. this._output.value = this._value;
  33707. return this;
  33708. }
  33709. _refresh() {
  33710. this.needsUpdate = true;
  33711. this._exec();
  33712. this._output.refresh();
  33713. }
  33714. }
  33715. const scriptable = /*@__PURE__*/ nodeProxy( ScriptableNode );
  33716. class FogNode extends Node {
  33717. static get type() {
  33718. return 'FogNode';
  33719. }
  33720. constructor( colorNode, factorNode ) {
  33721. super( 'float' );
  33722. this.isFogNode = true;
  33723. this.colorNode = colorNode;
  33724. this.factorNode = factorNode;
  33725. }
  33726. getViewZNode( builder ) {
  33727. let viewZ;
  33728. const getViewZ = builder.context.getViewZ;
  33729. if ( getViewZ !== undefined ) {
  33730. viewZ = getViewZ( this );
  33731. }
  33732. return ( viewZ || positionView.z ).negate();
  33733. }
  33734. setup() {
  33735. return this.factorNode;
  33736. }
  33737. }
  33738. const fog = /*@__PURE__*/ nodeProxy( FogNode );
  33739. class FogRangeNode extends FogNode {
  33740. static get type() {
  33741. return 'FogRangeNode';
  33742. }
  33743. constructor( colorNode, nearNode, farNode ) {
  33744. super( colorNode );
  33745. this.isFogRangeNode = true;
  33746. this.nearNode = nearNode;
  33747. this.farNode = farNode;
  33748. }
  33749. setup( builder ) {
  33750. const viewZ = this.getViewZNode( builder );
  33751. return smoothstep( this.nearNode, this.farNode, viewZ );
  33752. }
  33753. }
  33754. const rangeFog = /*@__PURE__*/ nodeProxy( FogRangeNode );
  33755. class FogExp2Node extends FogNode {
  33756. static get type() {
  33757. return 'FogExp2Node';
  33758. }
  33759. constructor( colorNode, densityNode ) {
  33760. super( colorNode );
  33761. this.isFogExp2Node = true;
  33762. this.densityNode = densityNode;
  33763. }
  33764. setup( builder ) {
  33765. const viewZ = this.getViewZNode( builder );
  33766. const density = this.densityNode;
  33767. return density.mul( density, viewZ, viewZ ).negate().exp().oneMinus();
  33768. }
  33769. }
  33770. const densityFog = /*@__PURE__*/ nodeProxy( FogExp2Node );
  33771. let min = null;
  33772. let max = null;
  33773. class RangeNode extends Node {
  33774. static get type() {
  33775. return 'RangeNode';
  33776. }
  33777. constructor( minNode = float(), maxNode = float() ) {
  33778. super();
  33779. this.minNode = minNode;
  33780. this.maxNode = maxNode;
  33781. }
  33782. getVectorLength( builder ) {
  33783. const minLength = builder.getTypeLength( getValueType( this.minNode.value ) );
  33784. const maxLength = builder.getTypeLength( getValueType( this.maxNode.value ) );
  33785. return minLength > maxLength ? minLength : maxLength;
  33786. }
  33787. getNodeType( builder ) {
  33788. return builder.object.count > 1 ? builder.getTypeFromLength( this.getVectorLength( builder ) ) : 'float';
  33789. }
  33790. setup( builder ) {
  33791. const object = builder.object;
  33792. let output = null;
  33793. if ( object.count > 1 ) {
  33794. const minValue = this.minNode.value;
  33795. const maxValue = this.maxNode.value;
  33796. const minLength = builder.getTypeLength( getValueType( minValue ) );
  33797. const maxLength = builder.getTypeLength( getValueType( maxValue ) );
  33798. min = min || new Vector4();
  33799. max = max || new Vector4();
  33800. min.setScalar( 0 );
  33801. max.setScalar( 0 );
  33802. if ( minLength === 1 ) min.setScalar( minValue );
  33803. else if ( minValue.isColor ) min.set( minValue.r, minValue.g, minValue.b );
  33804. else min.set( minValue.x, minValue.y, minValue.z || 0, minValue.w || 0 );
  33805. if ( maxLength === 1 ) max.setScalar( maxValue );
  33806. else if ( maxValue.isColor ) max.set( maxValue.r, maxValue.g, maxValue.b );
  33807. else max.set( maxValue.x, maxValue.y, maxValue.z || 0, maxValue.w || 0 );
  33808. const stride = 4;
  33809. const length = stride * object.count;
  33810. const array = new Float32Array( length );
  33811. for ( let i = 0; i < length; i ++ ) {
  33812. const index = i % stride;
  33813. const minElementValue = min.getComponent( index );
  33814. const maxElementValue = max.getComponent( index );
  33815. array[ i ] = MathUtils.lerp( minElementValue, maxElementValue, Math.random() );
  33816. }
  33817. const nodeType = this.getNodeType( builder );
  33818. if ( object.count <= 4096 ) {
  33819. output = buffer( array, 'vec4', object.count ).element( instanceIndex ).convert( nodeType );
  33820. } else {
  33821. // TODO: Improve anonymous buffer attribute creation removing this part
  33822. const bufferAttribute = new InstancedBufferAttribute( array, 4 );
  33823. builder.geometry.setAttribute( '__range' + this.id, bufferAttribute );
  33824. output = instancedBufferAttribute( bufferAttribute ).convert( nodeType );
  33825. }
  33826. } else {
  33827. output = float( 0 );
  33828. }
  33829. return output;
  33830. }
  33831. }
  33832. const range = /*@__PURE__*/ nodeProxy( RangeNode );
  33833. const BasicShadowMap = Fn( ( { depthTexture, shadowCoord } ) => {
  33834. return texture( depthTexture, shadowCoord.xy ).compare( shadowCoord.z );
  33835. } );
  33836. const PCFShadowMap = Fn( ( { depthTexture, shadowCoord, shadow } ) => {
  33837. const depthCompare = ( uv, compare ) => texture( depthTexture, uv ).compare( compare );
  33838. const mapSize = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  33839. const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup );
  33840. const texelSize = vec2( 1 ).div( mapSize );
  33841. const dx0 = texelSize.x.negate().mul( radius );
  33842. const dy0 = texelSize.y.negate().mul( radius );
  33843. const dx1 = texelSize.x.mul( radius );
  33844. const dy1 = texelSize.y.mul( radius );
  33845. const dx2 = dx0.div( 2 );
  33846. const dy2 = dy0.div( 2 );
  33847. const dx3 = dx1.div( 2 );
  33848. const dy3 = dy1.div( 2 );
  33849. return add(
  33850. depthCompare( shadowCoord.xy.add( vec2( dx0, dy0 ) ), shadowCoord.z ),
  33851. depthCompare( shadowCoord.xy.add( vec2( 0, dy0 ) ), shadowCoord.z ),
  33852. depthCompare( shadowCoord.xy.add( vec2( dx1, dy0 ) ), shadowCoord.z ),
  33853. depthCompare( shadowCoord.xy.add( vec2( dx2, dy2 ) ), shadowCoord.z ),
  33854. depthCompare( shadowCoord.xy.add( vec2( 0, dy2 ) ), shadowCoord.z ),
  33855. depthCompare( shadowCoord.xy.add( vec2( dx3, dy2 ) ), shadowCoord.z ),
  33856. depthCompare( shadowCoord.xy.add( vec2( dx0, 0 ) ), shadowCoord.z ),
  33857. depthCompare( shadowCoord.xy.add( vec2( dx2, 0 ) ), shadowCoord.z ),
  33858. depthCompare( shadowCoord.xy, shadowCoord.z ),
  33859. depthCompare( shadowCoord.xy.add( vec2( dx3, 0 ) ), shadowCoord.z ),
  33860. depthCompare( shadowCoord.xy.add( vec2( dx1, 0 ) ), shadowCoord.z ),
  33861. depthCompare( shadowCoord.xy.add( vec2( dx2, dy3 ) ), shadowCoord.z ),
  33862. depthCompare( shadowCoord.xy.add( vec2( 0, dy3 ) ), shadowCoord.z ),
  33863. depthCompare( shadowCoord.xy.add( vec2( dx3, dy3 ) ), shadowCoord.z ),
  33864. depthCompare( shadowCoord.xy.add( vec2( dx0, dy1 ) ), shadowCoord.z ),
  33865. depthCompare( shadowCoord.xy.add( vec2( 0, dy1 ) ), shadowCoord.z ),
  33866. depthCompare( shadowCoord.xy.add( vec2( dx1, dy1 ) ), shadowCoord.z )
  33867. ).mul( 1 / 17 );
  33868. } );
  33869. const PCFSoftShadowMap = Fn( ( { depthTexture, shadowCoord, shadow } ) => {
  33870. const depthCompare = ( uv, compare ) => texture( depthTexture, uv ).compare( compare );
  33871. const mapSize = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  33872. const texelSize = vec2( 1 ).div( mapSize );
  33873. const dx = texelSize.x;
  33874. const dy = texelSize.y;
  33875. const uv = shadowCoord.xy;
  33876. const f = fract( uv.mul( mapSize ).add( 0.5 ) );
  33877. uv.subAssign( f.mul( texelSize ) );
  33878. return add(
  33879. depthCompare( uv, shadowCoord.z ),
  33880. depthCompare( uv.add( vec2( dx, 0 ) ), shadowCoord.z ),
  33881. depthCompare( uv.add( vec2( 0, dy ) ), shadowCoord.z ),
  33882. depthCompare( uv.add( texelSize ), shadowCoord.z ),
  33883. mix(
  33884. depthCompare( uv.add( vec2( dx.negate(), 0 ) ), shadowCoord.z ),
  33885. depthCompare( uv.add( vec2( dx.mul( 2 ), 0 ) ), shadowCoord.z ),
  33886. f.x
  33887. ),
  33888. mix(
  33889. depthCompare( uv.add( vec2( dx.negate(), dy ) ), shadowCoord.z ),
  33890. depthCompare( uv.add( vec2( dx.mul( 2 ), dy ) ), shadowCoord.z ),
  33891. f.x
  33892. ),
  33893. mix(
  33894. depthCompare( uv.add( vec2( 0, dy.negate() ) ), shadowCoord.z ),
  33895. depthCompare( uv.add( vec2( 0, dy.mul( 2 ) ) ), shadowCoord.z ),
  33896. f.y
  33897. ),
  33898. mix(
  33899. depthCompare( uv.add( vec2( dx, dy.negate() ) ), shadowCoord.z ),
  33900. depthCompare( uv.add( vec2( dx, dy.mul( 2 ) ) ), shadowCoord.z ),
  33901. f.y
  33902. ),
  33903. mix(
  33904. mix(
  33905. depthCompare( uv.add( vec2( dx.negate(), dy.negate() ) ), shadowCoord.z ),
  33906. depthCompare( uv.add( vec2( dx.mul( 2 ), dy.negate() ) ), shadowCoord.z ),
  33907. f.x
  33908. ),
  33909. mix(
  33910. depthCompare( uv.add( vec2( dx.negate(), dy.mul( 2 ) ) ), shadowCoord.z ),
  33911. depthCompare( uv.add( vec2( dx.mul( 2 ), dy.mul( 2 ) ) ), shadowCoord.z ),
  33912. f.x
  33913. ),
  33914. f.y
  33915. )
  33916. ).mul( 1 / 9 );
  33917. } );
  33918. // VSM
  33919. const VSMShadowMapNode = Fn( ( { depthTexture, shadowCoord } ) => {
  33920. const occlusion = float( 1 ).toVar();
  33921. const distribution = texture( depthTexture ).uv( shadowCoord.xy ).rg;
  33922. const hardShadow = step( shadowCoord.z, distribution.x );
  33923. If( hardShadow.notEqual( float( 1.0 ) ), () => {
  33924. const distance = shadowCoord.z.sub( distribution.x );
  33925. const variance = max$1( 0, distribution.y.mul( distribution.y ) );
  33926. let softnessProbability = variance.div( variance.add( distance.mul( distance ) ) ); // Chebeyshevs inequality
  33927. softnessProbability = clamp( sub( softnessProbability, 0.3 ).div( 0.95 - 0.3 ) );
  33928. occlusion.assign( clamp( max$1( hardShadow, softnessProbability ) ) );
  33929. } );
  33930. return occlusion;
  33931. } );
  33932. const VSMPassVertical = Fn( ( { samples, radius, size, shadowPass } ) => {
  33933. const mean = float( 0 ).toVar();
  33934. const squaredMean = float( 0 ).toVar();
  33935. const uvStride = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( 2 ).div( samples.sub( 1 ) ) );
  33936. const uvStart = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( - 1 ) );
  33937. Loop( { start: int( 0 ), end: int( samples ), type: 'int', condition: '<' }, ( { i } ) => {
  33938. const uvOffset = uvStart.add( float( i ).mul( uvStride ) );
  33939. const depth = shadowPass.uv( add( screenCoordinate.xy, vec2( 0, uvOffset ).mul( radius ) ).div( size ) ).x;
  33940. mean.addAssign( depth );
  33941. squaredMean.addAssign( depth.mul( depth ) );
  33942. } );
  33943. mean.divAssign( samples );
  33944. squaredMean.divAssign( samples );
  33945. const std_dev = sqrt( squaredMean.sub( mean.mul( mean ) ) );
  33946. return vec2( mean, std_dev );
  33947. } );
  33948. const VSMPassHorizontal = Fn( ( { samples, radius, size, shadowPass } ) => {
  33949. const mean = float( 0 ).toVar();
  33950. const squaredMean = float( 0 ).toVar();
  33951. const uvStride = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( 2 ).div( samples.sub( 1 ) ) );
  33952. const uvStart = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( - 1 ) );
  33953. Loop( { start: int( 0 ), end: int( samples ), type: 'int', condition: '<' }, ( { i } ) => {
  33954. const uvOffset = uvStart.add( float( i ).mul( uvStride ) );
  33955. const distribution = shadowPass.uv( add( screenCoordinate.xy, vec2( uvOffset, 0 ).mul( radius ) ).div( size ) );
  33956. mean.addAssign( distribution.x );
  33957. squaredMean.addAssign( add( distribution.y.mul( distribution.y ), distribution.x.mul( distribution.x ) ) );
  33958. } );
  33959. mean.divAssign( samples );
  33960. squaredMean.divAssign( samples );
  33961. const std_dev = sqrt( squaredMean.sub( mean.mul( mean ) ) );
  33962. return vec2( mean, std_dev );
  33963. } );
  33964. const _shadowFilterLib = [ BasicShadowMap, PCFShadowMap, PCFSoftShadowMap, VSMShadowMapNode ];
  33965. //
  33966. let _overrideMaterial = null;
  33967. const _quadMesh$1 = /*@__PURE__*/ new QuadMesh();
  33968. class ShadowNode extends Node {
  33969. static get type() {
  33970. return 'ShadowNode';
  33971. }
  33972. constructor( light, shadow = null ) {
  33973. super();
  33974. this.light = light;
  33975. this.shadow = shadow || light.shadow;
  33976. this.shadowMap = null;
  33977. this.vsmShadowMapVertical = null;
  33978. this.vsmShadowMapHorizontal = null;
  33979. this.vsmMaterialVertical = null;
  33980. this.vsmMaterialHorizontal = null;
  33981. this.updateBeforeType = NodeUpdateType.RENDER;
  33982. this._node = null;
  33983. this.isShadowNode = true;
  33984. }
  33985. setupShadow( builder ) {
  33986. const { object, renderer } = builder;
  33987. if ( _overrideMaterial === null ) {
  33988. _overrideMaterial = new NodeMaterial();
  33989. _overrideMaterial.fragmentNode = vec4( 0, 0, 0, 1 );
  33990. _overrideMaterial.isShadowNodeMaterial = true; // Use to avoid other overrideMaterial override material.fragmentNode unintentionally when using material.shadowNode
  33991. _overrideMaterial.name = 'ShadowMaterial';
  33992. }
  33993. const shadow = this.shadow;
  33994. const shadowMapType = renderer.shadowMap.type;
  33995. const depthTexture = new DepthTexture( shadow.mapSize.width, shadow.mapSize.height );
  33996. depthTexture.compareFunction = LessCompare;
  33997. const shadowMap = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height );
  33998. shadowMap.depthTexture = depthTexture;
  33999. shadow.camera.updateProjectionMatrix();
  34000. // VSM
  34001. if ( shadowMapType === VSMShadowMap ) {
  34002. depthTexture.compareFunction = null; // VSM does not use textureSampleCompare()/texture2DCompare()
  34003. this.vsmShadowMapVertical = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType } );
  34004. this.vsmShadowMapHorizontal = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType } );
  34005. const shadowPassVertical = texture( depthTexture );
  34006. const shadowPassHorizontal = texture( this.vsmShadowMapVertical.texture );
  34007. const samples = reference( 'blurSamples', 'float', shadow ).setGroup( renderGroup );
  34008. const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup );
  34009. const size = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  34010. let material = this.vsmMaterialVertical || ( this.vsmMaterialVertical = new NodeMaterial() );
  34011. material.fragmentNode = VSMPassVertical( { samples, radius, size, shadowPass: shadowPassVertical } ).context( builder.getSharedContext() );
  34012. material.name = 'VSMVertical';
  34013. material = this.vsmMaterialHorizontal || ( this.vsmMaterialHorizontal = new NodeMaterial() );
  34014. material.fragmentNode = VSMPassHorizontal( { samples, radius, size, shadowPass: shadowPassHorizontal } ).context( builder.getSharedContext() );
  34015. material.name = 'VSMHorizontal';
  34016. }
  34017. //
  34018. const shadowIntensity = reference( 'intensity', 'float', shadow ).setGroup( renderGroup );
  34019. const bias = reference( 'bias', 'float', shadow ).setGroup( renderGroup );
  34020. const normalBias = reference( 'normalBias', 'float', shadow ).setGroup( renderGroup );
  34021. const position = object.material.shadowPositionNode || positionWorld;
  34022. let shadowCoord = uniform( shadow.matrix ).setGroup( renderGroup ).mul( position.add( transformedNormalWorld.mul( normalBias ) ) );
  34023. let coordZ;
  34024. if ( shadow.camera.isOrthographicCamera || renderer.logarithmicDepthBuffer !== true ) {
  34025. shadowCoord = shadowCoord.xyz.div( shadowCoord.w );
  34026. coordZ = shadowCoord.z;
  34027. if ( renderer.coordinateSystem === WebGPUCoordinateSystem ) {
  34028. coordZ = coordZ.mul( 2 ).sub( 1 ); // WebGPU: Conversion [ 0, 1 ] to [ - 1, 1 ]
  34029. }
  34030. } else {
  34031. const w = shadowCoord.w;
  34032. shadowCoord = shadowCoord.xy.div( w ); // <-- Only divide X/Y coords since we don't need Z
  34033. // The normally available "cameraNear" and "cameraFar" nodes cannot be used here because they do not get
  34034. // updated to use the shadow camera. So, we have to declare our own "local" ones here.
  34035. // TODO: How do we get the cameraNear/cameraFar nodes to use the shadow camera so we don't have to declare local ones here?
  34036. const cameraNearLocal = uniform( 'float' ).onRenderUpdate( () => shadow.camera.near );
  34037. const cameraFarLocal = uniform( 'float' ).onRenderUpdate( () => shadow.camera.far );
  34038. coordZ = perspectiveDepthToLogarithmicDepth( w, cameraNearLocal, cameraFarLocal );
  34039. }
  34040. shadowCoord = vec3(
  34041. shadowCoord.x,
  34042. shadowCoord.y.oneMinus(), // follow webgpu standards
  34043. coordZ.add( bias )
  34044. );
  34045. const frustumTest = shadowCoord.x.greaterThanEqual( 0 )
  34046. .and( shadowCoord.x.lessThanEqual( 1 ) )
  34047. .and( shadowCoord.y.greaterThanEqual( 0 ) )
  34048. .and( shadowCoord.y.lessThanEqual( 1 ) )
  34049. .and( shadowCoord.z.lessThanEqual( 1 ) );
  34050. //
  34051. const filterFn = shadow.filterNode || _shadowFilterLib[ renderer.shadowMap.type ] || null;
  34052. if ( filterFn === null ) {
  34053. throw new Error( 'THREE.WebGPURenderer: Shadow map type not supported yet.' );
  34054. }
  34055. const shadowColor = texture( shadowMap.texture, shadowCoord );
  34056. const shadowNode = frustumTest.select( filterFn( { depthTexture: ( shadowMapType === VSMShadowMap ) ? this.vsmShadowMapHorizontal.texture : depthTexture, shadowCoord, shadow } ), float( 1 ) );
  34057. this.shadowMap = shadowMap;
  34058. this.shadow.map = shadowMap;
  34059. return mix( 1, shadowNode.rgb.mix( shadowColor, 1 ), shadowIntensity.mul( shadowColor.a ) );
  34060. }
  34061. setup( builder ) {
  34062. if ( builder.renderer.shadowMap.enabled === false ) return;
  34063. return this._node !== null ? this._node : ( this._node = this.setupShadow( builder ) );
  34064. }
  34065. updateShadow( frame ) {
  34066. const { shadowMap, light, shadow } = this;
  34067. const { renderer, scene, camera } = frame;
  34068. const shadowType = renderer.shadowMap.type;
  34069. const depthVersion = shadowMap.depthTexture.version;
  34070. this._depthVersionCached = depthVersion;
  34071. const currentOverrideMaterial = scene.overrideMaterial;
  34072. scene.overrideMaterial = _overrideMaterial;
  34073. shadowMap.setSize( shadow.mapSize.width, shadow.mapSize.height );
  34074. shadow.updateMatrices( light );
  34075. shadow.camera.layers.mask = camera.layers.mask;
  34076. const currentRenderTarget = renderer.getRenderTarget();
  34077. const currentRenderObjectFunction = renderer.getRenderObjectFunction();
  34078. renderer.setRenderObjectFunction( ( object, ...params ) => {
  34079. if ( object.castShadow === true || ( object.receiveShadow && shadowType === VSMShadowMap ) ) {
  34080. renderer.renderObject( object, ...params );
  34081. }
  34082. } );
  34083. renderer.setRenderTarget( shadowMap );
  34084. renderer.render( scene, shadow.camera );
  34085. renderer.setRenderObjectFunction( currentRenderObjectFunction );
  34086. // vsm blur pass
  34087. if ( light.isPointLight !== true && shadowType === VSMShadowMap ) {
  34088. this.vsmPass( renderer );
  34089. }
  34090. renderer.setRenderTarget( currentRenderTarget );
  34091. scene.overrideMaterial = currentOverrideMaterial;
  34092. }
  34093. vsmPass( renderer ) {
  34094. const { shadow } = this;
  34095. this.vsmShadowMapVertical.setSize( shadow.mapSize.width, shadow.mapSize.height );
  34096. this.vsmShadowMapHorizontal.setSize( shadow.mapSize.width, shadow.mapSize.height );
  34097. renderer.setRenderTarget( this.vsmShadowMapVertical );
  34098. _quadMesh$1.material = this.vsmMaterialVertical;
  34099. _quadMesh$1.render( renderer );
  34100. renderer.setRenderTarget( this.vsmShadowMapHorizontal );
  34101. _quadMesh$1.material = this.vsmMaterialHorizontal;
  34102. _quadMesh$1.render( renderer );
  34103. }
  34104. dispose() {
  34105. this.shadowMap.dispose();
  34106. this.shadowMap = null;
  34107. if ( this.vsmShadowMapVertical !== null ) {
  34108. this.vsmShadowMapVertical.dispose();
  34109. this.vsmShadowMapVertical = null;
  34110. this.vsmMaterialVertical.dispose();
  34111. this.vsmMaterialVertical = null;
  34112. }
  34113. if ( this.vsmShadowMapHorizontal !== null ) {
  34114. this.vsmShadowMapHorizontal.dispose();
  34115. this.vsmShadowMapHorizontal = null;
  34116. this.vsmMaterialHorizontal.dispose();
  34117. this.vsmMaterialHorizontal = null;
  34118. }
  34119. this.updateBeforeType = NodeUpdateType.NONE;
  34120. }
  34121. updateBefore( frame ) {
  34122. const { shadow } = this;
  34123. const needsUpdate = shadow.needsUpdate || shadow.autoUpdate;
  34124. if ( needsUpdate ) {
  34125. this.updateShadow( frame );
  34126. if ( this.shadowMap.depthTexture.version === this._depthVersionCached ) {
  34127. shadow.needsUpdate = false;
  34128. }
  34129. }
  34130. }
  34131. }
  34132. const shadow = ( light, shadow ) => nodeObject( new ShadowNode( light, shadow ) );
  34133. class AnalyticLightNode extends LightingNode {
  34134. static get type() {
  34135. return 'AnalyticLightNode';
  34136. }
  34137. constructor( light = null ) {
  34138. super();
  34139. this.updateType = NodeUpdateType.FRAME;
  34140. this.light = light;
  34141. this.color = new Color();
  34142. this.colorNode = uniform( this.color ).setGroup( renderGroup );
  34143. this.baseColorNode = null;
  34144. this.shadowNode = null;
  34145. this.shadowColorNode = null;
  34146. this.isAnalyticLightNode = true;
  34147. }
  34148. getCacheKey() {
  34149. return hash$1( super.getCacheKey(), this.light.id, this.light.castShadow ? 1 : 0 );
  34150. }
  34151. getHash() {
  34152. return this.light.uuid;
  34153. }
  34154. setupShadow( builder ) {
  34155. const { renderer } = builder;
  34156. if ( renderer.shadowMap.enabled === false ) return;
  34157. let shadowColorNode = this.shadowColorNode;
  34158. if ( shadowColorNode === null ) {
  34159. const shadowNode = shadow( this.light );
  34160. this.shadowNode = shadowNode;
  34161. this.shadowColorNode = shadowColorNode = this.colorNode.mul( shadowNode );
  34162. this.baseColorNode = this.colorNode;
  34163. }
  34164. //
  34165. this.colorNode = shadowColorNode;
  34166. }
  34167. setup( builder ) {
  34168. this.colorNode = this.baseColorNode || this.colorNode;
  34169. if ( this.light.castShadow ) {
  34170. if ( builder.object.receiveShadow ) {
  34171. this.setupShadow( builder );
  34172. }
  34173. } else if ( this.shadowNode !== null ) {
  34174. this.shadowNode.dispose();
  34175. }
  34176. }
  34177. update( /*frame*/ ) {
  34178. const { light } = this;
  34179. this.color.copy( light.color ).multiplyScalar( light.intensity );
  34180. }
  34181. }
  34182. const getDistanceAttenuation = /*@__PURE__*/ Fn( ( inputs ) => {
  34183. const { lightDistance, cutoffDistance, decayExponent } = inputs;
  34184. // based upon Frostbite 3 Moving to Physically-based Rendering
  34185. // page 32, equation 26: E[window1]
  34186. // https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  34187. const distanceFalloff = lightDistance.pow( decayExponent ).max( 0.01 ).reciprocal();
  34188. return cutoffDistance.greaterThan( 0 ).select(
  34189. distanceFalloff.mul( lightDistance.div( cutoffDistance ).pow4().oneMinus().clamp().pow2() ),
  34190. distanceFalloff
  34191. );
  34192. } ); // validated
  34193. let uniformsLib;
  34194. function getLightData( light ) {
  34195. uniformsLib = uniformsLib || new WeakMap();
  34196. let uniforms = uniformsLib.get( light );
  34197. if ( uniforms === undefined ) uniformsLib.set( light, uniforms = {} );
  34198. return uniforms;
  34199. }
  34200. function lightPosition( light ) {
  34201. const data = getLightData( light );
  34202. return data.position || ( data.position = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( _, self ) => self.value.setFromMatrixPosition( light.matrixWorld ) ) );
  34203. }
  34204. function lightTargetPosition( light ) {
  34205. const data = getLightData( light );
  34206. return data.targetPosition || ( data.targetPosition = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( _, self ) => self.value.setFromMatrixPosition( light.target.matrixWorld ) ) );
  34207. }
  34208. function lightViewPosition( light ) {
  34209. const data = getLightData( light );
  34210. return data.viewPosition || ( data.viewPosition = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( { camera }, self ) => {
  34211. self.value = self.value || new Vector3();
  34212. self.value.setFromMatrixPosition( light.matrixWorld );
  34213. self.value.applyMatrix4( camera.matrixWorldInverse );
  34214. } ) );
  34215. }
  34216. const lightTargetDirection = ( light ) => cameraViewMatrix.transformDirection( lightPosition( light ).sub( lightTargetPosition( light ) ) );
  34217. const hash = /*@__PURE__*/ Fn( ( [ seed ] ) => {
  34218. // Taken from https://www.shadertoy.com/view/XlGcRh, originally from pcg-random.org
  34219. const state = seed.toUint().mul( 747796405 ).add( 2891336453 );
  34220. const word = state.shiftRight( state.shiftRight( 28 ).add( 4 ) ).bitXor( state ).mul( 277803737 );
  34221. const result = word.shiftRight( 22 ).bitXor( word );
  34222. return result.toFloat().mul( 1 / 2 ** 32 ); // Convert to range [0, 1)
  34223. } );
  34224. // remapping functions https://iquilezles.org/articles/functions/
  34225. const parabola = ( x, k ) => pow( mul( 4.0, x.mul( sub( 1.0, x ) ) ), k );
  34226. const gain = ( x, k ) => x.lessThan( 0.5 ) ? parabola( x.mul( 2.0 ), k ).div( 2.0 ) : sub( 1.0, parabola( mul( sub( 1.0, x ), 2.0 ), k ).div( 2.0 ) );
  34227. const pcurve = ( x, a, b ) => pow( div( pow( x, a ), add( pow( x, a ), pow( sub( 1.0, x ), b ) ) ), 1.0 / a );
  34228. const sinc = ( x, k ) => sin( PI.mul( k.mul( x ).sub( 1.0 ) ) ).div( PI.mul( k.mul( x ).sub( 1.0 ) ) );
  34229. // https://github.com/cabbibo/glsl-tri-noise-3d
  34230. const tri = /*@__PURE__*/ Fn( ( [ x ] ) => {
  34231. return x.fract().sub( .5 ).abs();
  34232. } ).setLayout( {
  34233. name: 'tri',
  34234. type: 'float',
  34235. inputs: [
  34236. { name: 'x', type: 'float' }
  34237. ]
  34238. } );
  34239. const tri3 = /*@__PURE__*/ Fn( ( [ p ] ) => {
  34240. return vec3( tri( p.z.add( tri( p.y.mul( 1. ) ) ) ), tri( p.z.add( tri( p.x.mul( 1. ) ) ) ), tri( p.y.add( tri( p.x.mul( 1. ) ) ) ) );
  34241. } ).setLayout( {
  34242. name: 'tri3',
  34243. type: 'vec3',
  34244. inputs: [
  34245. { name: 'p', type: 'vec3' }
  34246. ]
  34247. } );
  34248. const triNoise3D = /*@__PURE__*/ Fn( ( [ p_immutable, spd, time ] ) => {
  34249. const p = vec3( p_immutable ).toVar();
  34250. const z = float( 1.4 ).toVar();
  34251. const rz = float( 0.0 ).toVar();
  34252. const bp = vec3( p ).toVar();
  34253. Loop( { start: float( 0.0 ), end: float( 3.0 ), type: 'float', condition: '<=' }, () => {
  34254. const dg = vec3( tri3( bp.mul( 2.0 ) ) ).toVar();
  34255. p.addAssign( dg.add( time.mul( float( 0.1 ).mul( spd ) ) ) );
  34256. bp.mulAssign( 1.8 );
  34257. z.mulAssign( 1.5 );
  34258. p.mulAssign( 1.2 );
  34259. const t = float( tri( p.z.add( tri( p.x.add( tri( p.y ) ) ) ) ) ).toVar();
  34260. rz.addAssign( t.div( z ) );
  34261. bp.addAssign( 0.14 );
  34262. } );
  34263. return rz;
  34264. } ).setLayout( {
  34265. name: 'triNoise3D',
  34266. type: 'float',
  34267. inputs: [
  34268. { name: 'p', type: 'vec3' },
  34269. { name: 'spd', type: 'float' },
  34270. { name: 'time', type: 'float' }
  34271. ]
  34272. } );
  34273. const time = /*@__PURE__*/ uniform( 0 ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.time );
  34274. const deltaTime = /*@__PURE__*/ uniform( 0 ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.deltaTime );
  34275. const frameId = /*@__PURE__*/ uniform( 0, 'uint' ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.frameId );
  34276. // Deprecated
  34277. const timerLocal = ( timeScale = 1 ) => { // @deprecated, r170
  34278. console.warn( 'TSL: timerLocal() is deprecated. Use "time" instead.' );
  34279. return time.mul( timeScale );
  34280. };
  34281. const timerGlobal = ( timeScale = 1 ) => { // @deprecated, r170
  34282. console.warn( 'TSL: timerGlobal() is deprecated. Use "time" instead.' );
  34283. return time.mul( timeScale );
  34284. };
  34285. const timerDelta = ( timeScale = 1 ) => { // @deprecated, r170
  34286. console.warn( 'TSL: timerDelta() is deprecated. Use "deltaTime" instead.' );
  34287. return deltaTime.mul( timeScale );
  34288. };
  34289. const oscSine = ( t = time ) => t.add( 0.75 ).mul( Math.PI * 2 ).sin().mul( 0.5 ).add( 0.5 );
  34290. const oscSquare = ( t = time ) => t.fract().round();
  34291. const oscTriangle = ( t = time ) => t.add( 0.5 ).fract().mul( 2 ).sub( 1 ).abs();
  34292. const oscSawtooth = ( t = time ) => t.fract();
  34293. const rotateUV = /*@__PURE__*/ Fn( ( [ uv, rotation, center = vec2( 0.5 ) ] ) => {
  34294. return rotate( uv.sub( center ), rotation ).add( center );
  34295. } );
  34296. const spherizeUV = /*@__PURE__*/ Fn( ( [ uv, strength, center = vec2( 0.5 ) ] ) => {
  34297. const delta = uv.sub( center );
  34298. const delta2 = delta.dot( delta );
  34299. const delta4 = delta2.mul( delta2 );
  34300. const deltaOffset = delta4.mul( strength );
  34301. return uv.add( delta.mul( deltaOffset ) );
  34302. } );
  34303. const billboarding = /*@__PURE__*/ Fn( ( { position = null, horizontal = true, vertical = false } ) => {
  34304. let worldMatrix;
  34305. if ( position !== null ) {
  34306. worldMatrix = modelWorldMatrix.toVar();
  34307. worldMatrix[ 3 ][ 0 ] = position.x;
  34308. worldMatrix[ 3 ][ 1 ] = position.y;
  34309. worldMatrix[ 3 ][ 2 ] = position.z;
  34310. } else {
  34311. worldMatrix = modelWorldMatrix;
  34312. }
  34313. const modelViewMatrix = cameraViewMatrix.mul( worldMatrix );
  34314. if ( defined( horizontal ) ) {
  34315. modelViewMatrix[ 0 ][ 0 ] = modelWorldMatrix[ 0 ].length();
  34316. modelViewMatrix[ 0 ][ 1 ] = 0;
  34317. modelViewMatrix[ 0 ][ 2 ] = 0;
  34318. }
  34319. if ( defined( vertical ) ) {
  34320. modelViewMatrix[ 1 ][ 0 ] = 0;
  34321. modelViewMatrix[ 1 ][ 1 ] = modelWorldMatrix[ 1 ].length();
  34322. modelViewMatrix[ 1 ][ 2 ] = 0;
  34323. }
  34324. modelViewMatrix[ 2 ][ 0 ] = 0;
  34325. modelViewMatrix[ 2 ][ 1 ] = 0;
  34326. modelViewMatrix[ 2 ][ 2 ] = 1;
  34327. return cameraProjectionMatrix.mul( modelViewMatrix ).mul( positionLocal );
  34328. } );
  34329. const viewportSafeUV = /*@__PURE__*/ Fn( ( [ uv = null ] ) => {
  34330. const depth = linearDepth();
  34331. const depthDiff = linearDepth( viewportDepthTexture( uv ) ).sub( depth );
  34332. const finalUV = depthDiff.lessThan( 0 ).select( screenUV, uv );
  34333. return finalUV;
  34334. } );
  34335. /**
  34336. * Computes a position in view space based on a fragment's screen position expressed as uv coordinates, the fragments
  34337. * depth value and the camera's inverse projection matrix.
  34338. *
  34339. * @param {vec2} screenPosition - The fragment's screen position expressed as uv coordinates.
  34340. * @param {float} depth - The fragment's depth value.
  34341. * @param {mat4} projectionMatrixInverse - The camera's inverse projection matrix.
  34342. * @return {vec3} The fragments position in view space.
  34343. */
  34344. const getViewPosition = /*@__PURE__*/ Fn( ( [ screenPosition, depth, projectionMatrixInverse ], builder ) => {
  34345. let clipSpacePosition;
  34346. if ( builder.renderer.coordinateSystem === WebGPUCoordinateSystem ) {
  34347. screenPosition = vec2( screenPosition.x, screenPosition.y.oneMinus() ).mul( 2.0 ).sub( 1.0 );
  34348. clipSpacePosition = vec4( vec3( screenPosition, depth ), 1.0 );
  34349. } else {
  34350. clipSpacePosition = vec4( vec3( screenPosition.x, screenPosition.y.oneMinus(), depth ).mul( 2.0 ).sub( 1.0 ), 1.0 );
  34351. }
  34352. const viewSpacePosition = vec4( projectionMatrixInverse.mul( clipSpacePosition ) );
  34353. return viewSpacePosition.xyz.div( viewSpacePosition.w );
  34354. } );
  34355. /**
  34356. * Computes a screen position expressed as uv coordinates based on a fragment's position in view space
  34357. * and the camera's projection matrix
  34358. *
  34359. * @param {vec3} viewPosition - The fragments position in view space.
  34360. * @param {mat4} projectionMatrix - The camera's projection matrix.
  34361. * @return {vec2} Teh fragment's screen position expressed as uv coordinates.
  34362. */
  34363. const getScreenPosition = /*@__PURE__*/ Fn( ( [ viewPosition, projectionMatrix ] ) => {
  34364. const sampleClipPos = projectionMatrix.mul( vec4( viewPosition, 1.0 ) );
  34365. const sampleUv = sampleClipPos.xy.div( sampleClipPos.w ).mul( 0.5 ).add( 0.5 ).toVar();
  34366. return vec2( sampleUv.x, sampleUv.y.oneMinus() );
  34367. } );
  34368. const _objectData = new WeakMap();
  34369. class VelocityNode extends TempNode {
  34370. static get type() {
  34371. return 'VelocityNode';
  34372. }
  34373. constructor() {
  34374. super( 'vec2' );
  34375. this.updateType = NodeUpdateType.OBJECT;
  34376. this.updateAfterType = NodeUpdateType.OBJECT;
  34377. this.previousModelWorldMatrix = uniform( new Matrix4() );
  34378. this.previousProjectionMatrix = uniform( new Matrix4() ).setGroup( renderGroup );
  34379. this.previousCameraViewMatrix = uniform( new Matrix4() );
  34380. }
  34381. update( { frameId, camera, object } ) {
  34382. const previousModelMatrix = getPreviousMatrix( object );
  34383. this.previousModelWorldMatrix.value.copy( previousModelMatrix );
  34384. //
  34385. const cameraData = getData( camera );
  34386. if ( cameraData.frameId !== frameId ) {
  34387. cameraData.frameId = frameId;
  34388. if ( cameraData.previousProjectionMatrix === undefined ) {
  34389. cameraData.previousProjectionMatrix = new Matrix4();
  34390. cameraData.previousCameraViewMatrix = new Matrix4();
  34391. cameraData.currentProjectionMatrix = new Matrix4();
  34392. cameraData.currentCameraViewMatrix = new Matrix4();
  34393. cameraData.previousProjectionMatrix.copy( camera.projectionMatrix );
  34394. cameraData.previousCameraViewMatrix.copy( camera.matrixWorldInverse );
  34395. } else {
  34396. cameraData.previousProjectionMatrix.copy( cameraData.currentProjectionMatrix );
  34397. cameraData.previousCameraViewMatrix.copy( cameraData.currentCameraViewMatrix );
  34398. }
  34399. cameraData.currentProjectionMatrix.copy( camera.projectionMatrix );
  34400. cameraData.currentCameraViewMatrix.copy( camera.matrixWorldInverse );
  34401. this.previousProjectionMatrix.value.copy( cameraData.previousProjectionMatrix );
  34402. this.previousCameraViewMatrix.value.copy( cameraData.previousCameraViewMatrix );
  34403. }
  34404. }
  34405. updateAfter( { object } ) {
  34406. getPreviousMatrix( object ).copy( object.matrixWorld );
  34407. }
  34408. setup( /*builder*/ ) {
  34409. const previousModelViewMatrix = this.previousCameraViewMatrix.mul( this.previousModelWorldMatrix );
  34410. const clipPositionCurrent = cameraProjectionMatrix.mul( modelViewMatrix ).mul( positionLocal );
  34411. const clipPositionPrevious = this.previousProjectionMatrix.mul( previousModelViewMatrix ).mul( positionPrevious );
  34412. const ndcPositionCurrent = clipPositionCurrent.xy.div( clipPositionCurrent.w );
  34413. const ndcPositionPrevious = clipPositionPrevious.xy.div( clipPositionPrevious.w );
  34414. const velocity = sub( ndcPositionCurrent, ndcPositionPrevious );
  34415. return velocity;
  34416. }
  34417. }
  34418. function getData( object ) {
  34419. let objectData = _objectData.get( object );
  34420. if ( objectData === undefined ) {
  34421. objectData = {};
  34422. _objectData.set( object, objectData );
  34423. }
  34424. return objectData;
  34425. }
  34426. function getPreviousMatrix( object, index = 0 ) {
  34427. const objectData = getData( object );
  34428. let matrix = objectData[ index ];
  34429. if ( matrix === undefined ) {
  34430. objectData[ index ] = matrix = new Matrix4();
  34431. }
  34432. return matrix;
  34433. }
  34434. const velocity = /*@__PURE__*/ nodeImmutable( VelocityNode );
  34435. const burn = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  34436. return min$1( 1.0, base.oneMinus().div( blend ) ).oneMinus();
  34437. } ).setLayout( {
  34438. name: 'burnBlend',
  34439. type: 'vec3',
  34440. inputs: [
  34441. { name: 'base', type: 'vec3' },
  34442. { name: 'blend', type: 'vec3' }
  34443. ]
  34444. } );
  34445. const dodge = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  34446. return min$1( base.div( blend.oneMinus() ), 1.0 );
  34447. } ).setLayout( {
  34448. name: 'dodgeBlend',
  34449. type: 'vec3',
  34450. inputs: [
  34451. { name: 'base', type: 'vec3' },
  34452. { name: 'blend', type: 'vec3' }
  34453. ]
  34454. } );
  34455. const screen = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  34456. return base.oneMinus().mul( blend.oneMinus() ).oneMinus();
  34457. } ).setLayout( {
  34458. name: 'screenBlend',
  34459. type: 'vec3',
  34460. inputs: [
  34461. { name: 'base', type: 'vec3' },
  34462. { name: 'blend', type: 'vec3' }
  34463. ]
  34464. } );
  34465. const overlay = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  34466. return mix( base.mul( 2.0 ).mul( blend ), base.oneMinus().mul( 2.0 ).mul( blend.oneMinus() ).oneMinus(), step( 0.5, base ) );
  34467. } ).setLayout( {
  34468. name: 'overlayBlend',
  34469. type: 'vec3',
  34470. inputs: [
  34471. { name: 'base', type: 'vec3' },
  34472. { name: 'blend', type: 'vec3' }
  34473. ]
  34474. } );
  34475. const grayscale = /*@__PURE__*/ Fn( ( [ color ] ) => {
  34476. return luminance( color.rgb );
  34477. } );
  34478. const saturation = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  34479. return adjustment.mix( luminance( color.rgb ), color.rgb );
  34480. } );
  34481. const vibrance = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  34482. const average = add( color.r, color.g, color.b ).div( 3.0 );
  34483. const mx = color.r.max( color.g.max( color.b ) );
  34484. const amt = mx.sub( average ).mul( adjustment ).mul( - 3.0 );
  34485. return mix( color.rgb, mx, amt );
  34486. } );
  34487. const hue = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  34488. const k = vec3( 0.57735, 0.57735, 0.57735 );
  34489. const cosAngle = adjustment.cos();
  34490. return vec3( color.rgb.mul( cosAngle ).add( k.cross( color.rgb ).mul( adjustment.sin() ).add( k.mul( dot( k, color.rgb ).mul( cosAngle.oneMinus() ) ) ) ) );
  34491. } );
  34492. const luminance = (
  34493. color,
  34494. luminanceCoefficients = vec3( ColorManagement.getLuminanceCoefficients( new Vector3() ) )
  34495. ) => dot( color, luminanceCoefficients );
  34496. const threshold = ( color, threshold ) => mix( vec3( 0.0 ), color, luminance( color ).sub( threshold ).max( 0 ) );
  34497. /**
  34498. * Color Decision List (CDL) v1.2
  34499. *
  34500. * Compact representation of color grading information, defined by slope, offset, power, and
  34501. * saturation. The CDL should be typically be given input in a log space (such as LogC, ACEScc,
  34502. * or AgX Log), and will return output in the same space. Output may require clamping >=0.
  34503. *
  34504. * @param {vec4} color Input (-Infinity < input < +Infinity)
  34505. * @param {number | vec3} slope Slope (0 ≤ slope < +Infinity)
  34506. * @param {number | vec3} offset Offset (-Infinity < offset < +Infinity; typically -1 < offset < 1)
  34507. * @param {number | vec3} power Power (0 < power < +Infinity)
  34508. * @param {number} saturation Saturation (0 ≤ saturation < +Infinity; typically 0 ≤ saturation < 4)
  34509. * @param {vec3} luminanceCoefficients Luminance coefficients for saturation term, typically Rec. 709
  34510. * @return Output, -Infinity < output < +Infinity
  34511. *
  34512. * References:
  34513. * - ASC CDL v1.2
  34514. * - https://blender.stackexchange.com/a/55239/43930
  34515. * - https://docs.acescentral.com/specifications/acescc/
  34516. */
  34517. const cdl = /*@__PURE__*/ Fn( ( [
  34518. color,
  34519. slope = vec3( 1 ),
  34520. offset = vec3( 0 ),
  34521. power = vec3( 1 ),
  34522. saturation = float( 1 ),
  34523. // ASC CDL v1.2 explicitly requires Rec. 709 luminance coefficients.
  34524. luminanceCoefficients = vec3( ColorManagement.getLuminanceCoefficients( new Vector3(), LinearSRGBColorSpace ) )
  34525. ] ) => {
  34526. // NOTE: The ASC CDL v1.2 defines a [0, 1] clamp on the slope+offset term, and another on the
  34527. // saturation term. Per the ACEScc specification and Filament, limits may be omitted to support
  34528. // values outside [0, 1], requiring a workaround for negative values in the power expression.
  34529. const luma = color.rgb.dot( vec3( luminanceCoefficients ) );
  34530. const v = max$1( color.rgb.mul( slope ).add( offset ), 0.0 ).toVar();
  34531. const pv = v.pow( power ).toVar();
  34532. If( v.r.greaterThan( 0.0 ), () => { v.r.assign( pv.r ); } ); // eslint-disable-line
  34533. If( v.g.greaterThan( 0.0 ), () => { v.g.assign( pv.g ); } ); // eslint-disable-line
  34534. If( v.b.greaterThan( 0.0 ), () => { v.b.assign( pv.b ); } ); // eslint-disable-line
  34535. v.assign( luma.add( v.sub( luma ).mul( saturation ) ) );
  34536. return vec4( v.rgb, color.a );
  34537. } );
  34538. const sRGBToLinearSRGB = /*@__PURE__*/ Fn( ( [ color ] ) => {
  34539. const a = color.mul( 0.9478672986 ).add( 0.0521327014 ).pow( 2.4 );
  34540. const b = color.mul( 0.0773993808 );
  34541. const factor = color.lessThanEqual( 0.04045 );
  34542. const rgbResult = mix( a, b, factor );
  34543. return rgbResult;
  34544. } ).setLayout( {
  34545. name: 'sRGBToLinearSRGB',
  34546. type: 'vec3',
  34547. inputs: [
  34548. { name: 'color', type: 'vec3' }
  34549. ]
  34550. } );
  34551. const linearSRGBTosRGB = /*@__PURE__*/ Fn( ( [ color ] ) => {
  34552. const a = color.pow( 0.41666 ).mul( 1.055 ).sub( 0.055 );
  34553. const b = color.mul( 12.92 );
  34554. const factor = color.lessThanEqual( 0.0031308 );
  34555. const rgbResult = mix( a, b, factor );
  34556. return rgbResult;
  34557. } ).setLayout( {
  34558. name: 'linearSRGBTosRGB',
  34559. type: 'vec3',
  34560. inputs: [
  34561. { name: 'color', type: 'vec3' }
  34562. ]
  34563. } );
  34564. // exposure only
  34565. const linearToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  34566. return color.mul( exposure ).clamp();
  34567. } ).setLayout( {
  34568. name: 'linearToneMapping',
  34569. type: 'vec3',
  34570. inputs: [
  34571. { name: 'color', type: 'vec3' },
  34572. { name: 'exposure', type: 'float' }
  34573. ]
  34574. } );
  34575. // source: https://www.cs.utah.edu/docs/techreports/2002/pdf/UUCS-02-001.pdf
  34576. const reinhardToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  34577. color = color.mul( exposure );
  34578. return color.div( color.add( 1.0 ) ).clamp();
  34579. } ).setLayout( {
  34580. name: 'reinhardToneMapping',
  34581. type: 'vec3',
  34582. inputs: [
  34583. { name: 'color', type: 'vec3' },
  34584. { name: 'exposure', type: 'float' }
  34585. ]
  34586. } );
  34587. // source: http://filmicworlds.com/blog/filmic-tonemapping-operators/
  34588. const cineonToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  34589. // filmic operator by Jim Hejl and Richard Burgess-Dawson
  34590. color = color.mul( exposure );
  34591. color = color.sub( 0.004 ).max( 0.0 );
  34592. const a = color.mul( color.mul( 6.2 ).add( 0.5 ) );
  34593. const b = color.mul( color.mul( 6.2 ).add( 1.7 ) ).add( 0.06 );
  34594. return a.div( b ).pow( 2.2 );
  34595. } ).setLayout( {
  34596. name: 'cineonToneMapping',
  34597. type: 'vec3',
  34598. inputs: [
  34599. { name: 'color', type: 'vec3' },
  34600. { name: 'exposure', type: 'float' }
  34601. ]
  34602. } );
  34603. // source: https://github.com/selfshadow/ltc_code/blob/master/webgl/shaders/ltc/ltc_blit.fs
  34604. const RRTAndODTFit = /*@__PURE__*/ Fn( ( [ color ] ) => {
  34605. const a = color.mul( color.add( 0.0245786 ) ).sub( 0.000090537 );
  34606. const b = color.mul( color.add( 0.4329510 ).mul( 0.983729 ) ).add( 0.238081 );
  34607. return a.div( b );
  34608. } );
  34609. // source: https://github.com/selfshadow/ltc_code/blob/master/webgl/shaders/ltc/ltc_blit.fs
  34610. const acesFilmicToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  34611. // sRGB => XYZ => D65_2_D60 => AP1 => RRT_SAT
  34612. const ACESInputMat = mat3(
  34613. 0.59719, 0.35458, 0.04823,
  34614. 0.07600, 0.90834, 0.01566,
  34615. 0.02840, 0.13383, 0.83777
  34616. );
  34617. // ODT_SAT => XYZ => D60_2_D65 => sRGB
  34618. const ACESOutputMat = mat3(
  34619. 1.60475, - 0.53108, - 0.07367,
  34620. - 0.10208, 1.10813, - 0.00605,
  34621. - 0.00327, - 0.07276, 1.07602
  34622. );
  34623. color = color.mul( exposure ).div( 0.6 );
  34624. color = ACESInputMat.mul( color );
  34625. // Apply RRT and ODT
  34626. color = RRTAndODTFit( color );
  34627. color = ACESOutputMat.mul( color );
  34628. // Clamp to [0, 1]
  34629. return color.clamp();
  34630. } ).setLayout( {
  34631. name: 'acesFilmicToneMapping',
  34632. type: 'vec3',
  34633. inputs: [
  34634. { name: 'color', type: 'vec3' },
  34635. { name: 'exposure', type: 'float' }
  34636. ]
  34637. } );
  34638. const LINEAR_REC2020_TO_LINEAR_SRGB = /*@__PURE__*/ mat3( vec3( 1.6605, - 0.1246, - 0.0182 ), vec3( - 0.5876, 1.1329, - 0.1006 ), vec3( - 0.0728, - 0.0083, 1.1187 ) );
  34639. const LINEAR_SRGB_TO_LINEAR_REC2020 = /*@__PURE__*/ mat3( vec3( 0.6274, 0.0691, 0.0164 ), vec3( 0.3293, 0.9195, 0.0880 ), vec3( 0.0433, 0.0113, 0.8956 ) );
  34640. const agxDefaultContrastApprox = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  34641. const x = vec3( x_immutable ).toVar();
  34642. const x2 = vec3( x.mul( x ) ).toVar();
  34643. const x4 = vec3( x2.mul( x2 ) ).toVar();
  34644. return float( 15.5 ).mul( x4.mul( x2 ) ).sub( mul( 40.14, x4.mul( x ) ) ).add( mul( 31.96, x4 ).sub( mul( 6.868, x2.mul( x ) ) ).add( mul( 0.4298, x2 ).add( mul( 0.1191, x ).sub( 0.00232 ) ) ) );
  34645. } );
  34646. const agxToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  34647. const colortone = vec3( color ).toVar();
  34648. const AgXInsetMatrix = mat3( vec3( 0.856627153315983, 0.137318972929847, 0.11189821299995 ), vec3( 0.0951212405381588, 0.761241990602591, 0.0767994186031903 ), vec3( 0.0482516061458583, 0.101439036467562, 0.811302368396859 ) );
  34649. const AgXOutsetMatrix = mat3( vec3( 1.1271005818144368, - 0.1413297634984383, - 0.14132976349843826 ), vec3( - 0.11060664309660323, 1.157823702216272, - 0.11060664309660294 ), vec3( - 0.016493938717834573, - 0.016493938717834257, 1.2519364065950405 ) );
  34650. const AgxMinEv = float( - 12.47393 );
  34651. const AgxMaxEv = float( 4.026069 );
  34652. colortone.mulAssign( exposure );
  34653. colortone.assign( LINEAR_SRGB_TO_LINEAR_REC2020.mul( colortone ) );
  34654. colortone.assign( AgXInsetMatrix.mul( colortone ) );
  34655. colortone.assign( max$1( colortone, 1e-10 ) );
  34656. colortone.assign( log2( colortone ) );
  34657. colortone.assign( colortone.sub( AgxMinEv ).div( AgxMaxEv.sub( AgxMinEv ) ) );
  34658. colortone.assign( clamp( colortone, 0.0, 1.0 ) );
  34659. colortone.assign( agxDefaultContrastApprox( colortone ) );
  34660. colortone.assign( AgXOutsetMatrix.mul( colortone ) );
  34661. colortone.assign( pow( max$1( vec3( 0.0 ), colortone ), vec3( 2.2 ) ) );
  34662. colortone.assign( LINEAR_REC2020_TO_LINEAR_SRGB.mul( colortone ) );
  34663. colortone.assign( clamp( colortone, 0.0, 1.0 ) );
  34664. return colortone;
  34665. } ).setLayout( {
  34666. name: 'agxToneMapping',
  34667. type: 'vec3',
  34668. inputs: [
  34669. { name: 'color', type: 'vec3' },
  34670. { name: 'exposure', type: 'float' }
  34671. ]
  34672. } );
  34673. // https://modelviewer.dev/examples/tone-mapping
  34674. const neutralToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  34675. const StartCompression = float( 0.8 - 0.04 );
  34676. const Desaturation = float( 0.15 );
  34677. color = color.mul( exposure );
  34678. const x = min$1( color.r, min$1( color.g, color.b ) );
  34679. const offset = select( x.lessThan( 0.08 ), x.sub( mul( 6.25, x.mul( x ) ) ), 0.04 );
  34680. color.subAssign( offset );
  34681. const peak = max$1( color.r, max$1( color.g, color.b ) );
  34682. If( peak.lessThan( StartCompression ), () => {
  34683. return color;
  34684. } );
  34685. const d = sub( 1, StartCompression );
  34686. const newPeak = sub( 1, d.mul( d ).div( peak.add( d.sub( StartCompression ) ) ) );
  34687. color.mulAssign( newPeak.div( peak ) );
  34688. const g = sub( 1, div( 1, Desaturation.mul( peak.sub( newPeak ) ).add( 1 ) ) );
  34689. return mix( color, vec3( newPeak ), g );
  34690. } ).setLayout( {
  34691. name: 'neutralToneMapping',
  34692. type: 'vec3',
  34693. inputs: [
  34694. { name: 'color', type: 'vec3' },
  34695. { name: 'exposure', type: 'float' }
  34696. ]
  34697. } );
  34698. class ComputeBuiltinNode extends Node {
  34699. static get type() {
  34700. return 'ComputeBuiltinNode';
  34701. }
  34702. constructor( builtinName, nodeType ) {
  34703. super( nodeType );
  34704. this._builtinName = builtinName;
  34705. }
  34706. getHash( builder ) {
  34707. return this.getBuiltinName( builder );
  34708. }
  34709. getNodeType( /*builder*/ ) {
  34710. return this.nodeType;
  34711. }
  34712. setBuiltinName( builtinName ) {
  34713. this._builtinName = builtinName;
  34714. return this;
  34715. }
  34716. getBuiltinName( /*builder*/ ) {
  34717. return this._builtinName;
  34718. }
  34719. hasBuiltin( builder ) {
  34720. builder.hasBuiltin( this._builtinName );
  34721. }
  34722. generate( builder, output ) {
  34723. const builtinName = this.getBuiltinName( builder );
  34724. const nodeType = this.getNodeType( builder );
  34725. if ( builder.shaderStage === 'compute' ) {
  34726. return builder.format( builtinName, nodeType, output );
  34727. } else {
  34728. console.warn( `ComputeBuiltinNode: Compute built-in value ${builtinName} can not be accessed in the ${builder.shaderStage} stage` );
  34729. return builder.generateConst( nodeType );
  34730. }
  34731. }
  34732. serialize( data ) {
  34733. super.serialize( data );
  34734. data.global = this.global;
  34735. data._builtinName = this._builtinName;
  34736. }
  34737. deserialize( data ) {
  34738. super.deserialize( data );
  34739. this.global = data.global;
  34740. this._builtinName = data._builtinName;
  34741. }
  34742. }
  34743. const computeBuiltin = ( name, nodeType ) => nodeObject( new ComputeBuiltinNode( name, nodeType ) );
  34744. const numWorkgroups = /*@__PURE__*/ computeBuiltin( 'numWorkgroups', 'uvec3' );
  34745. const workgroupId = /*@__PURE__*/ computeBuiltin( 'workgroupId', 'uvec3' );
  34746. const localId = /*@__PURE__*/ computeBuiltin( 'localId', 'uvec3' );
  34747. const subgroupSize = /*@__PURE__*/ computeBuiltin( 'subgroupSize', 'uint' );
  34748. class BarrierNode extends Node {
  34749. constructor( scope ) {
  34750. super();
  34751. this.scope = scope;
  34752. }
  34753. generate( builder ) {
  34754. const { scope } = this;
  34755. const { renderer } = builder;
  34756. if ( renderer.backend.isWebGLBackend === true ) {
  34757. builder.addFlowCode( `\t// ${scope}Barrier \n` );
  34758. } else {
  34759. builder.addLineFlowCode( `${scope}Barrier()`, this );
  34760. }
  34761. }
  34762. }
  34763. const barrier = nodeProxy( BarrierNode );
  34764. const workgroupBarrier = () => barrier( 'workgroup' ).append();
  34765. const storageBarrier = () => barrier( 'storage' ).append();
  34766. const textureBarrier = () => barrier( 'texture' ).append();
  34767. class WorkgroupInfoElementNode extends ArrayElementNode {
  34768. constructor( workgroupInfoNode, indexNode ) {
  34769. super( workgroupInfoNode, indexNode );
  34770. this.isWorkgroupInfoElementNode = true;
  34771. }
  34772. generate( builder, output ) {
  34773. let snippet;
  34774. const isAssignContext = builder.context.assign;
  34775. snippet = super.generate( builder );
  34776. if ( isAssignContext !== true ) {
  34777. const type = this.getNodeType( builder );
  34778. snippet = builder.format( snippet, type, output );
  34779. }
  34780. // TODO: Possibly activate clip distance index on index access rather than from clipping context
  34781. return snippet;
  34782. }
  34783. }
  34784. class WorkgroupInfoNode extends Node {
  34785. constructor( scope, bufferType, bufferCount = 0 ) {
  34786. super( bufferType );
  34787. this.bufferType = bufferType;
  34788. this.bufferCount = bufferCount;
  34789. this.isWorkgroupInfoNode = true;
  34790. this.scope = scope;
  34791. }
  34792. label( name ) {
  34793. this.name = name;
  34794. return this;
  34795. }
  34796. getHash() {
  34797. return this.uuid;
  34798. }
  34799. setScope( scope ) {
  34800. this.scope = scope;
  34801. return this;
  34802. }
  34803. getInputType( /*builder*/ ) {
  34804. return `${this.scope}Array`;
  34805. }
  34806. element( indexNode ) {
  34807. return nodeObject( new WorkgroupInfoElementNode( this, indexNode ) );
  34808. }
  34809. generate( builder ) {
  34810. return builder.getScopedArray( this.name || `${this.scope}Array_${this.id}`, this.scope.toLowerCase(), this.bufferType, this.bufferCount );
  34811. }
  34812. }
  34813. const workgroupArray = ( type, count ) => nodeObject( new WorkgroupInfoNode( 'Workgroup', type, count ) );
  34814. class AtomicFunctionNode extends TempNode {
  34815. static get type() {
  34816. return 'AtomicFunctionNode';
  34817. }
  34818. constructor( method, pointerNode, valueNode, storeNode = null ) {
  34819. super( 'uint' );
  34820. this.method = method;
  34821. this.pointerNode = pointerNode;
  34822. this.valueNode = valueNode;
  34823. this.storeNode = storeNode;
  34824. }
  34825. getInputType( builder ) {
  34826. return this.pointerNode.getNodeType( builder );
  34827. }
  34828. getNodeType( builder ) {
  34829. return this.getInputType( builder );
  34830. }
  34831. generate( builder ) {
  34832. const method = this.method;
  34833. const type = this.getNodeType( builder );
  34834. const inputType = this.getInputType( builder );
  34835. const a = this.pointerNode;
  34836. const b = this.valueNode;
  34837. const params = [];
  34838. params.push( `&${ a.build( builder, inputType ) }` );
  34839. params.push( b.build( builder, inputType ) );
  34840. const methodSnippet = `${ builder.getMethod( method, type ) }( ${params.join( ', ' )} )`;
  34841. if ( this.storeNode !== null ) {
  34842. const varSnippet = this.storeNode.build( builder, inputType );
  34843. builder.addLineFlowCode( `${varSnippet} = ${methodSnippet}`, this );
  34844. } else {
  34845. builder.addLineFlowCode( methodSnippet, this );
  34846. }
  34847. }
  34848. }
  34849. AtomicFunctionNode.ATOMIC_LOAD = 'atomicLoad';
  34850. AtomicFunctionNode.ATOMIC_STORE = 'atomicStore';
  34851. AtomicFunctionNode.ATOMIC_ADD = 'atomicAdd';
  34852. AtomicFunctionNode.ATOMIC_SUB = 'atomicSub';
  34853. AtomicFunctionNode.ATOMIC_MAX = 'atomicMax';
  34854. AtomicFunctionNode.ATOMIC_MIN = 'atomicMin';
  34855. AtomicFunctionNode.ATOMIC_AND = 'atomicAnd';
  34856. AtomicFunctionNode.ATOMIC_OR = 'atomicOr';
  34857. AtomicFunctionNode.ATOMIC_XOR = 'atomicXor';
  34858. const atomicNode = nodeProxy( AtomicFunctionNode );
  34859. const atomicFunc = ( method, pointerNode, valueNode, storeNode ) => {
  34860. const node = atomicNode( method, pointerNode, valueNode, storeNode );
  34861. node.append();
  34862. return node;
  34863. };
  34864. const atomicStore = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_STORE, pointerNode, valueNode, storeNode );
  34865. const atomicAdd = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_ADD, pointerNode, valueNode, storeNode );
  34866. const atomicSub = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_SUB, pointerNode, valueNode, storeNode );
  34867. const atomicMax = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_MAX, pointerNode, valueNode, storeNode );
  34868. const atomicMin = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_MIN, pointerNode, valueNode, storeNode );
  34869. const atomicAnd = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_AND, pointerNode, valueNode, storeNode );
  34870. const atomicOr = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_OR, pointerNode, valueNode, storeNode );
  34871. const atomicXor = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_XOR, pointerNode, valueNode, storeNode );
  34872. const checker = /*@__PURE__*/ Fn( ( [ coord = uv() ] ) => {
  34873. const uv = coord.mul( 2.0 );
  34874. const cx = uv.x.floor();
  34875. const cy = uv.y.floor();
  34876. const result = cx.add( cy ).mod( 2.0 );
  34877. return result.sign();
  34878. } );
  34879. // Three.js Transpiler
  34880. // https://raw.githubusercontent.com/AcademySoftwareFoundation/MaterialX/main/libraries/stdlib/genglsl/lib/mx_noise.glsl
  34881. const mx_select = /*@__PURE__*/ Fn( ( [ b_immutable, t_immutable, f_immutable ] ) => {
  34882. const f = float( f_immutable ).toVar();
  34883. const t = float( t_immutable ).toVar();
  34884. const b = bool( b_immutable ).toVar();
  34885. return select( b, t, f );
  34886. } ).setLayout( {
  34887. name: 'mx_select',
  34888. type: 'float',
  34889. inputs: [
  34890. { name: 'b', type: 'bool' },
  34891. { name: 't', type: 'float' },
  34892. { name: 'f', type: 'float' }
  34893. ]
  34894. } );
  34895. const mx_negate_if = /*@__PURE__*/ Fn( ( [ val_immutable, b_immutable ] ) => {
  34896. const b = bool( b_immutable ).toVar();
  34897. const val = float( val_immutable ).toVar();
  34898. return select( b, val.negate(), val );
  34899. } ).setLayout( {
  34900. name: 'mx_negate_if',
  34901. type: 'float',
  34902. inputs: [
  34903. { name: 'val', type: 'float' },
  34904. { name: 'b', type: 'bool' }
  34905. ]
  34906. } );
  34907. const mx_floor = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  34908. const x = float( x_immutable ).toVar();
  34909. return int( floor( x ) );
  34910. } ).setLayout( {
  34911. name: 'mx_floor',
  34912. type: 'int',
  34913. inputs: [
  34914. { name: 'x', type: 'float' }
  34915. ]
  34916. } );
  34917. const mx_floorfrac = /*@__PURE__*/ Fn( ( [ x_immutable, i ] ) => {
  34918. const x = float( x_immutable ).toVar();
  34919. i.assign( mx_floor( x ) );
  34920. return x.sub( float( i ) );
  34921. } );
  34922. const mx_bilerp_0 = /*@__PURE__*/ Fn( ( [ v0_immutable, v1_immutable, v2_immutable, v3_immutable, s_immutable, t_immutable ] ) => {
  34923. const t = float( t_immutable ).toVar();
  34924. const s = float( s_immutable ).toVar();
  34925. const v3 = float( v3_immutable ).toVar();
  34926. const v2 = float( v2_immutable ).toVar();
  34927. const v1 = float( v1_immutable ).toVar();
  34928. const v0 = float( v0_immutable ).toVar();
  34929. const s1 = float( sub( 1.0, s ) ).toVar();
  34930. return sub( 1.0, t ).mul( v0.mul( s1 ).add( v1.mul( s ) ) ).add( t.mul( v2.mul( s1 ).add( v3.mul( s ) ) ) );
  34931. } ).setLayout( {
  34932. name: 'mx_bilerp_0',
  34933. type: 'float',
  34934. inputs: [
  34935. { name: 'v0', type: 'float' },
  34936. { name: 'v1', type: 'float' },
  34937. { name: 'v2', type: 'float' },
  34938. { name: 'v3', type: 'float' },
  34939. { name: 's', type: 'float' },
  34940. { name: 't', type: 'float' }
  34941. ]
  34942. } );
  34943. const mx_bilerp_1 = /*@__PURE__*/ Fn( ( [ v0_immutable, v1_immutable, v2_immutable, v3_immutable, s_immutable, t_immutable ] ) => {
  34944. const t = float( t_immutable ).toVar();
  34945. const s = float( s_immutable ).toVar();
  34946. const v3 = vec3( v3_immutable ).toVar();
  34947. const v2 = vec3( v2_immutable ).toVar();
  34948. const v1 = vec3( v1_immutable ).toVar();
  34949. const v0 = vec3( v0_immutable ).toVar();
  34950. const s1 = float( sub( 1.0, s ) ).toVar();
  34951. return sub( 1.0, t ).mul( v0.mul( s1 ).add( v1.mul( s ) ) ).add( t.mul( v2.mul( s1 ).add( v3.mul( s ) ) ) );
  34952. } ).setLayout( {
  34953. name: 'mx_bilerp_1',
  34954. type: 'vec3',
  34955. inputs: [
  34956. { name: 'v0', type: 'vec3' },
  34957. { name: 'v1', type: 'vec3' },
  34958. { name: 'v2', type: 'vec3' },
  34959. { name: 'v3', type: 'vec3' },
  34960. { name: 's', type: 'float' },
  34961. { name: 't', type: 'float' }
  34962. ]
  34963. } );
  34964. const mx_bilerp = /*@__PURE__*/ overloadingFn( [ mx_bilerp_0, mx_bilerp_1 ] );
  34965. const mx_trilerp_0 = /*@__PURE__*/ Fn( ( [ v0_immutable, v1_immutable, v2_immutable, v3_immutable, v4_immutable, v5_immutable, v6_immutable, v7_immutable, s_immutable, t_immutable, r_immutable ] ) => {
  34966. const r = float( r_immutable ).toVar();
  34967. const t = float( t_immutable ).toVar();
  34968. const s = float( s_immutable ).toVar();
  34969. const v7 = float( v7_immutable ).toVar();
  34970. const v6 = float( v6_immutable ).toVar();
  34971. const v5 = float( v5_immutable ).toVar();
  34972. const v4 = float( v4_immutable ).toVar();
  34973. const v3 = float( v3_immutable ).toVar();
  34974. const v2 = float( v2_immutable ).toVar();
  34975. const v1 = float( v1_immutable ).toVar();
  34976. const v0 = float( v0_immutable ).toVar();
  34977. const s1 = float( sub( 1.0, s ) ).toVar();
  34978. const t1 = float( sub( 1.0, t ) ).toVar();
  34979. const r1 = float( sub( 1.0, r ) ).toVar();
  34980. return r1.mul( t1.mul( v0.mul( s1 ).add( v1.mul( s ) ) ).add( t.mul( v2.mul( s1 ).add( v3.mul( s ) ) ) ) ).add( r.mul( t1.mul( v4.mul( s1 ).add( v5.mul( s ) ) ).add( t.mul( v6.mul( s1 ).add( v7.mul( s ) ) ) ) ) );
  34981. } ).setLayout( {
  34982. name: 'mx_trilerp_0',
  34983. type: 'float',
  34984. inputs: [
  34985. { name: 'v0', type: 'float' },
  34986. { name: 'v1', type: 'float' },
  34987. { name: 'v2', type: 'float' },
  34988. { name: 'v3', type: 'float' },
  34989. { name: 'v4', type: 'float' },
  34990. { name: 'v5', type: 'float' },
  34991. { name: 'v6', type: 'float' },
  34992. { name: 'v7', type: 'float' },
  34993. { name: 's', type: 'float' },
  34994. { name: 't', type: 'float' },
  34995. { name: 'r', type: 'float' }
  34996. ]
  34997. } );
  34998. const mx_trilerp_1 = /*@__PURE__*/ Fn( ( [ v0_immutable, v1_immutable, v2_immutable, v3_immutable, v4_immutable, v5_immutable, v6_immutable, v7_immutable, s_immutable, t_immutable, r_immutable ] ) => {
  34999. const r = float( r_immutable ).toVar();
  35000. const t = float( t_immutable ).toVar();
  35001. const s = float( s_immutable ).toVar();
  35002. const v7 = vec3( v7_immutable ).toVar();
  35003. const v6 = vec3( v6_immutable ).toVar();
  35004. const v5 = vec3( v5_immutable ).toVar();
  35005. const v4 = vec3( v4_immutable ).toVar();
  35006. const v3 = vec3( v3_immutable ).toVar();
  35007. const v2 = vec3( v2_immutable ).toVar();
  35008. const v1 = vec3( v1_immutable ).toVar();
  35009. const v0 = vec3( v0_immutable ).toVar();
  35010. const s1 = float( sub( 1.0, s ) ).toVar();
  35011. const t1 = float( sub( 1.0, t ) ).toVar();
  35012. const r1 = float( sub( 1.0, r ) ).toVar();
  35013. return r1.mul( t1.mul( v0.mul( s1 ).add( v1.mul( s ) ) ).add( t.mul( v2.mul( s1 ).add( v3.mul( s ) ) ) ) ).add( r.mul( t1.mul( v4.mul( s1 ).add( v5.mul( s ) ) ).add( t.mul( v6.mul( s1 ).add( v7.mul( s ) ) ) ) ) );
  35014. } ).setLayout( {
  35015. name: 'mx_trilerp_1',
  35016. type: 'vec3',
  35017. inputs: [
  35018. { name: 'v0', type: 'vec3' },
  35019. { name: 'v1', type: 'vec3' },
  35020. { name: 'v2', type: 'vec3' },
  35021. { name: 'v3', type: 'vec3' },
  35022. { name: 'v4', type: 'vec3' },
  35023. { name: 'v5', type: 'vec3' },
  35024. { name: 'v6', type: 'vec3' },
  35025. { name: 'v7', type: 'vec3' },
  35026. { name: 's', type: 'float' },
  35027. { name: 't', type: 'float' },
  35028. { name: 'r', type: 'float' }
  35029. ]
  35030. } );
  35031. const mx_trilerp = /*@__PURE__*/ overloadingFn( [ mx_trilerp_0, mx_trilerp_1 ] );
  35032. const mx_gradient_float_0 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable ] ) => {
  35033. const y = float( y_immutable ).toVar();
  35034. const x = float( x_immutable ).toVar();
  35035. const hash = uint( hash_immutable ).toVar();
  35036. const h = uint( hash.bitAnd( uint( 7 ) ) ).toVar();
  35037. const u = float( mx_select( h.lessThan( uint( 4 ) ), x, y ) ).toVar();
  35038. const v = float( mul( 2.0, mx_select( h.lessThan( uint( 4 ) ), y, x ) ) ).toVar();
  35039. return mx_negate_if( u, bool( h.bitAnd( uint( 1 ) ) ) ).add( mx_negate_if( v, bool( h.bitAnd( uint( 2 ) ) ) ) );
  35040. } ).setLayout( {
  35041. name: 'mx_gradient_float_0',
  35042. type: 'float',
  35043. inputs: [
  35044. { name: 'hash', type: 'uint' },
  35045. { name: 'x', type: 'float' },
  35046. { name: 'y', type: 'float' }
  35047. ]
  35048. } );
  35049. const mx_gradient_float_1 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable, z_immutable ] ) => {
  35050. const z = float( z_immutable ).toVar();
  35051. const y = float( y_immutable ).toVar();
  35052. const x = float( x_immutable ).toVar();
  35053. const hash = uint( hash_immutable ).toVar();
  35054. const h = uint( hash.bitAnd( uint( 15 ) ) ).toVar();
  35055. const u = float( mx_select( h.lessThan( uint( 8 ) ), x, y ) ).toVar();
  35056. const v = float( mx_select( h.lessThan( uint( 4 ) ), y, mx_select( h.equal( uint( 12 ) ).or( h.equal( uint( 14 ) ) ), x, z ) ) ).toVar();
  35057. return mx_negate_if( u, bool( h.bitAnd( uint( 1 ) ) ) ).add( mx_negate_if( v, bool( h.bitAnd( uint( 2 ) ) ) ) );
  35058. } ).setLayout( {
  35059. name: 'mx_gradient_float_1',
  35060. type: 'float',
  35061. inputs: [
  35062. { name: 'hash', type: 'uint' },
  35063. { name: 'x', type: 'float' },
  35064. { name: 'y', type: 'float' },
  35065. { name: 'z', type: 'float' }
  35066. ]
  35067. } );
  35068. const mx_gradient_float = /*@__PURE__*/ overloadingFn( [ mx_gradient_float_0, mx_gradient_float_1 ] );
  35069. const mx_gradient_vec3_0 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable ] ) => {
  35070. const y = float( y_immutable ).toVar();
  35071. const x = float( x_immutable ).toVar();
  35072. const hash = uvec3( hash_immutable ).toVar();
  35073. return vec3( mx_gradient_float( hash.x, x, y ), mx_gradient_float( hash.y, x, y ), mx_gradient_float( hash.z, x, y ) );
  35074. } ).setLayout( {
  35075. name: 'mx_gradient_vec3_0',
  35076. type: 'vec3',
  35077. inputs: [
  35078. { name: 'hash', type: 'uvec3' },
  35079. { name: 'x', type: 'float' },
  35080. { name: 'y', type: 'float' }
  35081. ]
  35082. } );
  35083. const mx_gradient_vec3_1 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable, z_immutable ] ) => {
  35084. const z = float( z_immutable ).toVar();
  35085. const y = float( y_immutable ).toVar();
  35086. const x = float( x_immutable ).toVar();
  35087. const hash = uvec3( hash_immutable ).toVar();
  35088. return vec3( mx_gradient_float( hash.x, x, y, z ), mx_gradient_float( hash.y, x, y, z ), mx_gradient_float( hash.z, x, y, z ) );
  35089. } ).setLayout( {
  35090. name: 'mx_gradient_vec3_1',
  35091. type: 'vec3',
  35092. inputs: [
  35093. { name: 'hash', type: 'uvec3' },
  35094. { name: 'x', type: 'float' },
  35095. { name: 'y', type: 'float' },
  35096. { name: 'z', type: 'float' }
  35097. ]
  35098. } );
  35099. const mx_gradient_vec3 = /*@__PURE__*/ overloadingFn( [ mx_gradient_vec3_0, mx_gradient_vec3_1 ] );
  35100. const mx_gradient_scale2d_0 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  35101. const v = float( v_immutable ).toVar();
  35102. return mul( 0.6616, v );
  35103. } ).setLayout( {
  35104. name: 'mx_gradient_scale2d_0',
  35105. type: 'float',
  35106. inputs: [
  35107. { name: 'v', type: 'float' }
  35108. ]
  35109. } );
  35110. const mx_gradient_scale3d_0 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  35111. const v = float( v_immutable ).toVar();
  35112. return mul( 0.9820, v );
  35113. } ).setLayout( {
  35114. name: 'mx_gradient_scale3d_0',
  35115. type: 'float',
  35116. inputs: [
  35117. { name: 'v', type: 'float' }
  35118. ]
  35119. } );
  35120. const mx_gradient_scale2d_1 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  35121. const v = vec3( v_immutable ).toVar();
  35122. return mul( 0.6616, v );
  35123. } ).setLayout( {
  35124. name: 'mx_gradient_scale2d_1',
  35125. type: 'vec3',
  35126. inputs: [
  35127. { name: 'v', type: 'vec3' }
  35128. ]
  35129. } );
  35130. const mx_gradient_scale2d = /*@__PURE__*/ overloadingFn( [ mx_gradient_scale2d_0, mx_gradient_scale2d_1 ] );
  35131. const mx_gradient_scale3d_1 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  35132. const v = vec3( v_immutable ).toVar();
  35133. return mul( 0.9820, v );
  35134. } ).setLayout( {
  35135. name: 'mx_gradient_scale3d_1',
  35136. type: 'vec3',
  35137. inputs: [
  35138. { name: 'v', type: 'vec3' }
  35139. ]
  35140. } );
  35141. const mx_gradient_scale3d = /*@__PURE__*/ overloadingFn( [ mx_gradient_scale3d_0, mx_gradient_scale3d_1 ] );
  35142. const mx_rotl32 = /*@__PURE__*/ Fn( ( [ x_immutable, k_immutable ] ) => {
  35143. const k = int( k_immutable ).toVar();
  35144. const x = uint( x_immutable ).toVar();
  35145. return x.shiftLeft( k ).bitOr( x.shiftRight( int( 32 ).sub( k ) ) );
  35146. } ).setLayout( {
  35147. name: 'mx_rotl32',
  35148. type: 'uint',
  35149. inputs: [
  35150. { name: 'x', type: 'uint' },
  35151. { name: 'k', type: 'int' }
  35152. ]
  35153. } );
  35154. const mx_bjmix = /*@__PURE__*/ Fn( ( [ a, b, c ] ) => {
  35155. a.subAssign( c );
  35156. a.bitXorAssign( mx_rotl32( c, int( 4 ) ) );
  35157. c.addAssign( b );
  35158. b.subAssign( a );
  35159. b.bitXorAssign( mx_rotl32( a, int( 6 ) ) );
  35160. a.addAssign( c );
  35161. c.subAssign( b );
  35162. c.bitXorAssign( mx_rotl32( b, int( 8 ) ) );
  35163. b.addAssign( a );
  35164. a.subAssign( c );
  35165. a.bitXorAssign( mx_rotl32( c, int( 16 ) ) );
  35166. c.addAssign( b );
  35167. b.subAssign( a );
  35168. b.bitXorAssign( mx_rotl32( a, int( 19 ) ) );
  35169. a.addAssign( c );
  35170. c.subAssign( b );
  35171. c.bitXorAssign( mx_rotl32( b, int( 4 ) ) );
  35172. b.addAssign( a );
  35173. } );
  35174. const mx_bjfinal = /*@__PURE__*/ Fn( ( [ a_immutable, b_immutable, c_immutable ] ) => {
  35175. const c = uint( c_immutable ).toVar();
  35176. const b = uint( b_immutable ).toVar();
  35177. const a = uint( a_immutable ).toVar();
  35178. c.bitXorAssign( b );
  35179. c.subAssign( mx_rotl32( b, int( 14 ) ) );
  35180. a.bitXorAssign( c );
  35181. a.subAssign( mx_rotl32( c, int( 11 ) ) );
  35182. b.bitXorAssign( a );
  35183. b.subAssign( mx_rotl32( a, int( 25 ) ) );
  35184. c.bitXorAssign( b );
  35185. c.subAssign( mx_rotl32( b, int( 16 ) ) );
  35186. a.bitXorAssign( c );
  35187. a.subAssign( mx_rotl32( c, int( 4 ) ) );
  35188. b.bitXorAssign( a );
  35189. b.subAssign( mx_rotl32( a, int( 14 ) ) );
  35190. c.bitXorAssign( b );
  35191. c.subAssign( mx_rotl32( b, int( 24 ) ) );
  35192. return c;
  35193. } ).setLayout( {
  35194. name: 'mx_bjfinal',
  35195. type: 'uint',
  35196. inputs: [
  35197. { name: 'a', type: 'uint' },
  35198. { name: 'b', type: 'uint' },
  35199. { name: 'c', type: 'uint' }
  35200. ]
  35201. } );
  35202. const mx_bits_to_01 = /*@__PURE__*/ Fn( ( [ bits_immutable ] ) => {
  35203. const bits = uint( bits_immutable ).toVar();
  35204. return float( bits ).div( float( uint( int( 0xffffffff ) ) ) );
  35205. } ).setLayout( {
  35206. name: 'mx_bits_to_01',
  35207. type: 'float',
  35208. inputs: [
  35209. { name: 'bits', type: 'uint' }
  35210. ]
  35211. } );
  35212. const mx_fade = /*@__PURE__*/ Fn( ( [ t_immutable ] ) => {
  35213. const t = float( t_immutable ).toVar();
  35214. return t.mul( t ).mul( t ).mul( t.mul( t.mul( 6.0 ).sub( 15.0 ) ).add( 10.0 ) );
  35215. } ).setLayout( {
  35216. name: 'mx_fade',
  35217. type: 'float',
  35218. inputs: [
  35219. { name: 't', type: 'float' }
  35220. ]
  35221. } );
  35222. const mx_hash_int_0 = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  35223. const x = int( x_immutable ).toVar();
  35224. const len = uint( uint( 1 ) ).toVar();
  35225. const seed = uint( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ).toVar();
  35226. return mx_bjfinal( seed.add( uint( x ) ), seed, seed );
  35227. } ).setLayout( {
  35228. name: 'mx_hash_int_0',
  35229. type: 'uint',
  35230. inputs: [
  35231. { name: 'x', type: 'int' }
  35232. ]
  35233. } );
  35234. const mx_hash_int_1 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable ] ) => {
  35235. const y = int( y_immutable ).toVar();
  35236. const x = int( x_immutable ).toVar();
  35237. const len = uint( uint( 2 ) ).toVar();
  35238. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  35239. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  35240. a.addAssign( uint( x ) );
  35241. b.addAssign( uint( y ) );
  35242. return mx_bjfinal( a, b, c );
  35243. } ).setLayout( {
  35244. name: 'mx_hash_int_1',
  35245. type: 'uint',
  35246. inputs: [
  35247. { name: 'x', type: 'int' },
  35248. { name: 'y', type: 'int' }
  35249. ]
  35250. } );
  35251. const mx_hash_int_2 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable ] ) => {
  35252. const z = int( z_immutable ).toVar();
  35253. const y = int( y_immutable ).toVar();
  35254. const x = int( x_immutable ).toVar();
  35255. const len = uint( uint( 3 ) ).toVar();
  35256. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  35257. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  35258. a.addAssign( uint( x ) );
  35259. b.addAssign( uint( y ) );
  35260. c.addAssign( uint( z ) );
  35261. return mx_bjfinal( a, b, c );
  35262. } ).setLayout( {
  35263. name: 'mx_hash_int_2',
  35264. type: 'uint',
  35265. inputs: [
  35266. { name: 'x', type: 'int' },
  35267. { name: 'y', type: 'int' },
  35268. { name: 'z', type: 'int' }
  35269. ]
  35270. } );
  35271. const mx_hash_int_3 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable, xx_immutable ] ) => {
  35272. const xx = int( xx_immutable ).toVar();
  35273. const z = int( z_immutable ).toVar();
  35274. const y = int( y_immutable ).toVar();
  35275. const x = int( x_immutable ).toVar();
  35276. const len = uint( uint( 4 ) ).toVar();
  35277. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  35278. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  35279. a.addAssign( uint( x ) );
  35280. b.addAssign( uint( y ) );
  35281. c.addAssign( uint( z ) );
  35282. mx_bjmix( a, b, c );
  35283. a.addAssign( uint( xx ) );
  35284. return mx_bjfinal( a, b, c );
  35285. } ).setLayout( {
  35286. name: 'mx_hash_int_3',
  35287. type: 'uint',
  35288. inputs: [
  35289. { name: 'x', type: 'int' },
  35290. { name: 'y', type: 'int' },
  35291. { name: 'z', type: 'int' },
  35292. { name: 'xx', type: 'int' }
  35293. ]
  35294. } );
  35295. const mx_hash_int_4 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable, xx_immutable, yy_immutable ] ) => {
  35296. const yy = int( yy_immutable ).toVar();
  35297. const xx = int( xx_immutable ).toVar();
  35298. const z = int( z_immutable ).toVar();
  35299. const y = int( y_immutable ).toVar();
  35300. const x = int( x_immutable ).toVar();
  35301. const len = uint( uint( 5 ) ).toVar();
  35302. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  35303. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  35304. a.addAssign( uint( x ) );
  35305. b.addAssign( uint( y ) );
  35306. c.addAssign( uint( z ) );
  35307. mx_bjmix( a, b, c );
  35308. a.addAssign( uint( xx ) );
  35309. b.addAssign( uint( yy ) );
  35310. return mx_bjfinal( a, b, c );
  35311. } ).setLayout( {
  35312. name: 'mx_hash_int_4',
  35313. type: 'uint',
  35314. inputs: [
  35315. { name: 'x', type: 'int' },
  35316. { name: 'y', type: 'int' },
  35317. { name: 'z', type: 'int' },
  35318. { name: 'xx', type: 'int' },
  35319. { name: 'yy', type: 'int' }
  35320. ]
  35321. } );
  35322. const mx_hash_int = /*@__PURE__*/ overloadingFn( [ mx_hash_int_0, mx_hash_int_1, mx_hash_int_2, mx_hash_int_3, mx_hash_int_4 ] );
  35323. const mx_hash_vec3_0 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable ] ) => {
  35324. const y = int( y_immutable ).toVar();
  35325. const x = int( x_immutable ).toVar();
  35326. const h = uint( mx_hash_int( x, y ) ).toVar();
  35327. const result = uvec3().toVar();
  35328. result.x.assign( h.bitAnd( int( 0xFF ) ) );
  35329. result.y.assign( h.shiftRight( int( 8 ) ).bitAnd( int( 0xFF ) ) );
  35330. result.z.assign( h.shiftRight( int( 16 ) ).bitAnd( int( 0xFF ) ) );
  35331. return result;
  35332. } ).setLayout( {
  35333. name: 'mx_hash_vec3_0',
  35334. type: 'uvec3',
  35335. inputs: [
  35336. { name: 'x', type: 'int' },
  35337. { name: 'y', type: 'int' }
  35338. ]
  35339. } );
  35340. const mx_hash_vec3_1 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable ] ) => {
  35341. const z = int( z_immutable ).toVar();
  35342. const y = int( y_immutable ).toVar();
  35343. const x = int( x_immutable ).toVar();
  35344. const h = uint( mx_hash_int( x, y, z ) ).toVar();
  35345. const result = uvec3().toVar();
  35346. result.x.assign( h.bitAnd( int( 0xFF ) ) );
  35347. result.y.assign( h.shiftRight( int( 8 ) ).bitAnd( int( 0xFF ) ) );
  35348. result.z.assign( h.shiftRight( int( 16 ) ).bitAnd( int( 0xFF ) ) );
  35349. return result;
  35350. } ).setLayout( {
  35351. name: 'mx_hash_vec3_1',
  35352. type: 'uvec3',
  35353. inputs: [
  35354. { name: 'x', type: 'int' },
  35355. { name: 'y', type: 'int' },
  35356. { name: 'z', type: 'int' }
  35357. ]
  35358. } );
  35359. const mx_hash_vec3 = /*@__PURE__*/ overloadingFn( [ mx_hash_vec3_0, mx_hash_vec3_1 ] );
  35360. const mx_perlin_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  35361. const p = vec2( p_immutable ).toVar();
  35362. const X = int().toVar(), Y = int().toVar();
  35363. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  35364. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  35365. const u = float( mx_fade( fx ) ).toVar();
  35366. const v = float( mx_fade( fy ) ).toVar();
  35367. const result = float( mx_bilerp( mx_gradient_float( mx_hash_int( X, Y ), fx, fy ), mx_gradient_float( mx_hash_int( X.add( int( 1 ) ), Y ), fx.sub( 1.0 ), fy ), mx_gradient_float( mx_hash_int( X, Y.add( int( 1 ) ) ), fx, fy.sub( 1.0 ) ), mx_gradient_float( mx_hash_int( X.add( int( 1 ) ), Y.add( int( 1 ) ) ), fx.sub( 1.0 ), fy.sub( 1.0 ) ), u, v ) ).toVar();
  35368. return mx_gradient_scale2d( result );
  35369. } ).setLayout( {
  35370. name: 'mx_perlin_noise_float_0',
  35371. type: 'float',
  35372. inputs: [
  35373. { name: 'p', type: 'vec2' }
  35374. ]
  35375. } );
  35376. const mx_perlin_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  35377. const p = vec3( p_immutable ).toVar();
  35378. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  35379. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  35380. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  35381. const fz = float( mx_floorfrac( p.z, Z ) ).toVar();
  35382. const u = float( mx_fade( fx ) ).toVar();
  35383. const v = float( mx_fade( fy ) ).toVar();
  35384. const w = float( mx_fade( fz ) ).toVar();
  35385. const result = float( mx_trilerp( mx_gradient_float( mx_hash_int( X, Y, Z ), fx, fy, fz ), mx_gradient_float( mx_hash_int( X.add( int( 1 ) ), Y, Z ), fx.sub( 1.0 ), fy, fz ), mx_gradient_float( mx_hash_int( X, Y.add( int( 1 ) ), Z ), fx, fy.sub( 1.0 ), fz ), mx_gradient_float( mx_hash_int( X.add( int( 1 ) ), Y.add( int( 1 ) ), Z ), fx.sub( 1.0 ), fy.sub( 1.0 ), fz ), mx_gradient_float( mx_hash_int( X, Y, Z.add( int( 1 ) ) ), fx, fy, fz.sub( 1.0 ) ), mx_gradient_float( mx_hash_int( X.add( int( 1 ) ), Y, Z.add( int( 1 ) ) ), fx.sub( 1.0 ), fy, fz.sub( 1.0 ) ), mx_gradient_float( mx_hash_int( X, Y.add( int( 1 ) ), Z.add( int( 1 ) ) ), fx, fy.sub( 1.0 ), fz.sub( 1.0 ) ), mx_gradient_float( mx_hash_int( X.add( int( 1 ) ), Y.add( int( 1 ) ), Z.add( int( 1 ) ) ), fx.sub( 1.0 ), fy.sub( 1.0 ), fz.sub( 1.0 ) ), u, v, w ) ).toVar();
  35386. return mx_gradient_scale3d( result );
  35387. } ).setLayout( {
  35388. name: 'mx_perlin_noise_float_1',
  35389. type: 'float',
  35390. inputs: [
  35391. { name: 'p', type: 'vec3' }
  35392. ]
  35393. } );
  35394. const mx_perlin_noise_float = /*@__PURE__*/ overloadingFn( [ mx_perlin_noise_float_0, mx_perlin_noise_float_1 ] );
  35395. const mx_perlin_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  35396. const p = vec2( p_immutable ).toVar();
  35397. const X = int().toVar(), Y = int().toVar();
  35398. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  35399. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  35400. const u = float( mx_fade( fx ) ).toVar();
  35401. const v = float( mx_fade( fy ) ).toVar();
  35402. const result = vec3( mx_bilerp( mx_gradient_vec3( mx_hash_vec3( X, Y ), fx, fy ), mx_gradient_vec3( mx_hash_vec3( X.add( int( 1 ) ), Y ), fx.sub( 1.0 ), fy ), mx_gradient_vec3( mx_hash_vec3( X, Y.add( int( 1 ) ) ), fx, fy.sub( 1.0 ) ), mx_gradient_vec3( mx_hash_vec3( X.add( int( 1 ) ), Y.add( int( 1 ) ) ), fx.sub( 1.0 ), fy.sub( 1.0 ) ), u, v ) ).toVar();
  35403. return mx_gradient_scale2d( result );
  35404. } ).setLayout( {
  35405. name: 'mx_perlin_noise_vec3_0',
  35406. type: 'vec3',
  35407. inputs: [
  35408. { name: 'p', type: 'vec2' }
  35409. ]
  35410. } );
  35411. const mx_perlin_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  35412. const p = vec3( p_immutable ).toVar();
  35413. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  35414. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  35415. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  35416. const fz = float( mx_floorfrac( p.z, Z ) ).toVar();
  35417. const u = float( mx_fade( fx ) ).toVar();
  35418. const v = float( mx_fade( fy ) ).toVar();
  35419. const w = float( mx_fade( fz ) ).toVar();
  35420. const result = vec3( mx_trilerp( mx_gradient_vec3( mx_hash_vec3( X, Y, Z ), fx, fy, fz ), mx_gradient_vec3( mx_hash_vec3( X.add( int( 1 ) ), Y, Z ), fx.sub( 1.0 ), fy, fz ), mx_gradient_vec3( mx_hash_vec3( X, Y.add( int( 1 ) ), Z ), fx, fy.sub( 1.0 ), fz ), mx_gradient_vec3( mx_hash_vec3( X.add( int( 1 ) ), Y.add( int( 1 ) ), Z ), fx.sub( 1.0 ), fy.sub( 1.0 ), fz ), mx_gradient_vec3( mx_hash_vec3( X, Y, Z.add( int( 1 ) ) ), fx, fy, fz.sub( 1.0 ) ), mx_gradient_vec3( mx_hash_vec3( X.add( int( 1 ) ), Y, Z.add( int( 1 ) ) ), fx.sub( 1.0 ), fy, fz.sub( 1.0 ) ), mx_gradient_vec3( mx_hash_vec3( X, Y.add( int( 1 ) ), Z.add( int( 1 ) ) ), fx, fy.sub( 1.0 ), fz.sub( 1.0 ) ), mx_gradient_vec3( mx_hash_vec3( X.add( int( 1 ) ), Y.add( int( 1 ) ), Z.add( int( 1 ) ) ), fx.sub( 1.0 ), fy.sub( 1.0 ), fz.sub( 1.0 ) ), u, v, w ) ).toVar();
  35421. return mx_gradient_scale3d( result );
  35422. } ).setLayout( {
  35423. name: 'mx_perlin_noise_vec3_1',
  35424. type: 'vec3',
  35425. inputs: [
  35426. { name: 'p', type: 'vec3' }
  35427. ]
  35428. } );
  35429. const mx_perlin_noise_vec3 = /*@__PURE__*/ overloadingFn( [ mx_perlin_noise_vec3_0, mx_perlin_noise_vec3_1 ] );
  35430. const mx_cell_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  35431. const p = float( p_immutable ).toVar();
  35432. const ix = int( mx_floor( p ) ).toVar();
  35433. return mx_bits_to_01( mx_hash_int( ix ) );
  35434. } ).setLayout( {
  35435. name: 'mx_cell_noise_float_0',
  35436. type: 'float',
  35437. inputs: [
  35438. { name: 'p', type: 'float' }
  35439. ]
  35440. } );
  35441. const mx_cell_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  35442. const p = vec2( p_immutable ).toVar();
  35443. const ix = int( mx_floor( p.x ) ).toVar();
  35444. const iy = int( mx_floor( p.y ) ).toVar();
  35445. return mx_bits_to_01( mx_hash_int( ix, iy ) );
  35446. } ).setLayout( {
  35447. name: 'mx_cell_noise_float_1',
  35448. type: 'float',
  35449. inputs: [
  35450. { name: 'p', type: 'vec2' }
  35451. ]
  35452. } );
  35453. const mx_cell_noise_float_2 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  35454. const p = vec3( p_immutable ).toVar();
  35455. const ix = int( mx_floor( p.x ) ).toVar();
  35456. const iy = int( mx_floor( p.y ) ).toVar();
  35457. const iz = int( mx_floor( p.z ) ).toVar();
  35458. return mx_bits_to_01( mx_hash_int( ix, iy, iz ) );
  35459. } ).setLayout( {
  35460. name: 'mx_cell_noise_float_2',
  35461. type: 'float',
  35462. inputs: [
  35463. { name: 'p', type: 'vec3' }
  35464. ]
  35465. } );
  35466. const mx_cell_noise_float_3 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  35467. const p = vec4( p_immutable ).toVar();
  35468. const ix = int( mx_floor( p.x ) ).toVar();
  35469. const iy = int( mx_floor( p.y ) ).toVar();
  35470. const iz = int( mx_floor( p.z ) ).toVar();
  35471. const iw = int( mx_floor( p.w ) ).toVar();
  35472. return mx_bits_to_01( mx_hash_int( ix, iy, iz, iw ) );
  35473. } ).setLayout( {
  35474. name: 'mx_cell_noise_float_3',
  35475. type: 'float',
  35476. inputs: [
  35477. { name: 'p', type: 'vec4' }
  35478. ]
  35479. } );
  35480. const mx_cell_noise_float$1 = /*@__PURE__*/ overloadingFn( [ mx_cell_noise_float_0, mx_cell_noise_float_1, mx_cell_noise_float_2, mx_cell_noise_float_3 ] );
  35481. const mx_cell_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  35482. const p = float( p_immutable ).toVar();
  35483. const ix = int( mx_floor( p ) ).toVar();
  35484. return vec3( mx_bits_to_01( mx_hash_int( ix, int( 0 ) ) ), mx_bits_to_01( mx_hash_int( ix, int( 1 ) ) ), mx_bits_to_01( mx_hash_int( ix, int( 2 ) ) ) );
  35485. } ).setLayout( {
  35486. name: 'mx_cell_noise_vec3_0',
  35487. type: 'vec3',
  35488. inputs: [
  35489. { name: 'p', type: 'float' }
  35490. ]
  35491. } );
  35492. const mx_cell_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  35493. const p = vec2( p_immutable ).toVar();
  35494. const ix = int( mx_floor( p.x ) ).toVar();
  35495. const iy = int( mx_floor( p.y ) ).toVar();
  35496. return vec3( mx_bits_to_01( mx_hash_int( ix, iy, int( 0 ) ) ), mx_bits_to_01( mx_hash_int( ix, iy, int( 1 ) ) ), mx_bits_to_01( mx_hash_int( ix, iy, int( 2 ) ) ) );
  35497. } ).setLayout( {
  35498. name: 'mx_cell_noise_vec3_1',
  35499. type: 'vec3',
  35500. inputs: [
  35501. { name: 'p', type: 'vec2' }
  35502. ]
  35503. } );
  35504. const mx_cell_noise_vec3_2 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  35505. const p = vec3( p_immutable ).toVar();
  35506. const ix = int( mx_floor( p.x ) ).toVar();
  35507. const iy = int( mx_floor( p.y ) ).toVar();
  35508. const iz = int( mx_floor( p.z ) ).toVar();
  35509. return vec3( mx_bits_to_01( mx_hash_int( ix, iy, iz, int( 0 ) ) ), mx_bits_to_01( mx_hash_int( ix, iy, iz, int( 1 ) ) ), mx_bits_to_01( mx_hash_int( ix, iy, iz, int( 2 ) ) ) );
  35510. } ).setLayout( {
  35511. name: 'mx_cell_noise_vec3_2',
  35512. type: 'vec3',
  35513. inputs: [
  35514. { name: 'p', type: 'vec3' }
  35515. ]
  35516. } );
  35517. const mx_cell_noise_vec3_3 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  35518. const p = vec4( p_immutable ).toVar();
  35519. const ix = int( mx_floor( p.x ) ).toVar();
  35520. const iy = int( mx_floor( p.y ) ).toVar();
  35521. const iz = int( mx_floor( p.z ) ).toVar();
  35522. const iw = int( mx_floor( p.w ) ).toVar();
  35523. return vec3( mx_bits_to_01( mx_hash_int( ix, iy, iz, iw, int( 0 ) ) ), mx_bits_to_01( mx_hash_int( ix, iy, iz, iw, int( 1 ) ) ), mx_bits_to_01( mx_hash_int( ix, iy, iz, iw, int( 2 ) ) ) );
  35524. } ).setLayout( {
  35525. name: 'mx_cell_noise_vec3_3',
  35526. type: 'vec3',
  35527. inputs: [
  35528. { name: 'p', type: 'vec4' }
  35529. ]
  35530. } );
  35531. const mx_cell_noise_vec3 = /*@__PURE__*/ overloadingFn( [ mx_cell_noise_vec3_0, mx_cell_noise_vec3_1, mx_cell_noise_vec3_2, mx_cell_noise_vec3_3 ] );
  35532. const mx_fractal_noise_float$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  35533. const diminish = float( diminish_immutable ).toVar();
  35534. const lacunarity = float( lacunarity_immutable ).toVar();
  35535. const octaves = int( octaves_immutable ).toVar();
  35536. const p = vec3( p_immutable ).toVar();
  35537. const result = float( 0.0 ).toVar();
  35538. const amplitude = float( 1.0 ).toVar();
  35539. Loop( octaves, () => {
  35540. result.addAssign( amplitude.mul( mx_perlin_noise_float( p ) ) );
  35541. amplitude.mulAssign( diminish );
  35542. p.mulAssign( lacunarity );
  35543. } );
  35544. return result;
  35545. } ).setLayout( {
  35546. name: 'mx_fractal_noise_float',
  35547. type: 'float',
  35548. inputs: [
  35549. { name: 'p', type: 'vec3' },
  35550. { name: 'octaves', type: 'int' },
  35551. { name: 'lacunarity', type: 'float' },
  35552. { name: 'diminish', type: 'float' }
  35553. ]
  35554. } );
  35555. const mx_fractal_noise_vec3$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  35556. const diminish = float( diminish_immutable ).toVar();
  35557. const lacunarity = float( lacunarity_immutable ).toVar();
  35558. const octaves = int( octaves_immutable ).toVar();
  35559. const p = vec3( p_immutable ).toVar();
  35560. const result = vec3( 0.0 ).toVar();
  35561. const amplitude = float( 1.0 ).toVar();
  35562. Loop( octaves, () => {
  35563. result.addAssign( amplitude.mul( mx_perlin_noise_vec3( p ) ) );
  35564. amplitude.mulAssign( diminish );
  35565. p.mulAssign( lacunarity );
  35566. } );
  35567. return result;
  35568. } ).setLayout( {
  35569. name: 'mx_fractal_noise_vec3',
  35570. type: 'vec3',
  35571. inputs: [
  35572. { name: 'p', type: 'vec3' },
  35573. { name: 'octaves', type: 'int' },
  35574. { name: 'lacunarity', type: 'float' },
  35575. { name: 'diminish', type: 'float' }
  35576. ]
  35577. } );
  35578. const mx_fractal_noise_vec2$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  35579. const diminish = float( diminish_immutable ).toVar();
  35580. const lacunarity = float( lacunarity_immutable ).toVar();
  35581. const octaves = int( octaves_immutable ).toVar();
  35582. const p = vec3( p_immutable ).toVar();
  35583. return vec2( mx_fractal_noise_float$1( p, octaves, lacunarity, diminish ), mx_fractal_noise_float$1( p.add( vec3( int( 19 ), int( 193 ), int( 17 ) ) ), octaves, lacunarity, diminish ) );
  35584. } ).setLayout( {
  35585. name: 'mx_fractal_noise_vec2',
  35586. type: 'vec2',
  35587. inputs: [
  35588. { name: 'p', type: 'vec3' },
  35589. { name: 'octaves', type: 'int' },
  35590. { name: 'lacunarity', type: 'float' },
  35591. { name: 'diminish', type: 'float' }
  35592. ]
  35593. } );
  35594. const mx_fractal_noise_vec4$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  35595. const diminish = float( diminish_immutable ).toVar();
  35596. const lacunarity = float( lacunarity_immutable ).toVar();
  35597. const octaves = int( octaves_immutable ).toVar();
  35598. const p = vec3( p_immutable ).toVar();
  35599. const c = vec3( mx_fractal_noise_vec3$1( p, octaves, lacunarity, diminish ) ).toVar();
  35600. const f = float( mx_fractal_noise_float$1( p.add( vec3( int( 19 ), int( 193 ), int( 17 ) ) ), octaves, lacunarity, diminish ) ).toVar();
  35601. return vec4( c, f );
  35602. } ).setLayout( {
  35603. name: 'mx_fractal_noise_vec4',
  35604. type: 'vec4',
  35605. inputs: [
  35606. { name: 'p', type: 'vec3' },
  35607. { name: 'octaves', type: 'int' },
  35608. { name: 'lacunarity', type: 'float' },
  35609. { name: 'diminish', type: 'float' }
  35610. ]
  35611. } );
  35612. const mx_worley_distance_0 = /*@__PURE__*/ Fn( ( [ p_immutable, x_immutable, y_immutable, xoff_immutable, yoff_immutable, jitter_immutable, metric_immutable ] ) => {
  35613. const metric = int( metric_immutable ).toVar();
  35614. const jitter = float( jitter_immutable ).toVar();
  35615. const yoff = int( yoff_immutable ).toVar();
  35616. const xoff = int( xoff_immutable ).toVar();
  35617. const y = int( y_immutable ).toVar();
  35618. const x = int( x_immutable ).toVar();
  35619. const p = vec2( p_immutable ).toVar();
  35620. const tmp = vec3( mx_cell_noise_vec3( vec2( x.add( xoff ), y.add( yoff ) ) ) ).toVar();
  35621. const off = vec2( tmp.x, tmp.y ).toVar();
  35622. off.subAssign( 0.5 );
  35623. off.mulAssign( jitter );
  35624. off.addAssign( 0.5 );
  35625. const cellpos = vec2( vec2( float( x ), float( y ) ).add( off ) ).toVar();
  35626. const diff = vec2( cellpos.sub( p ) ).toVar();
  35627. If( metric.equal( int( 2 ) ), () => {
  35628. return abs( diff.x ).add( abs( diff.y ) );
  35629. } );
  35630. If( metric.equal( int( 3 ) ), () => {
  35631. return max$1( abs( diff.x ), abs( diff.y ) );
  35632. } );
  35633. return dot( diff, diff );
  35634. } ).setLayout( {
  35635. name: 'mx_worley_distance_0',
  35636. type: 'float',
  35637. inputs: [
  35638. { name: 'p', type: 'vec2' },
  35639. { name: 'x', type: 'int' },
  35640. { name: 'y', type: 'int' },
  35641. { name: 'xoff', type: 'int' },
  35642. { name: 'yoff', type: 'int' },
  35643. { name: 'jitter', type: 'float' },
  35644. { name: 'metric', type: 'int' }
  35645. ]
  35646. } );
  35647. const mx_worley_distance_1 = /*@__PURE__*/ Fn( ( [ p_immutable, x_immutable, y_immutable, z_immutable, xoff_immutable, yoff_immutable, zoff_immutable, jitter_immutable, metric_immutable ] ) => {
  35648. const metric = int( metric_immutable ).toVar();
  35649. const jitter = float( jitter_immutable ).toVar();
  35650. const zoff = int( zoff_immutable ).toVar();
  35651. const yoff = int( yoff_immutable ).toVar();
  35652. const xoff = int( xoff_immutable ).toVar();
  35653. const z = int( z_immutable ).toVar();
  35654. const y = int( y_immutable ).toVar();
  35655. const x = int( x_immutable ).toVar();
  35656. const p = vec3( p_immutable ).toVar();
  35657. const off = vec3( mx_cell_noise_vec3( vec3( x.add( xoff ), y.add( yoff ), z.add( zoff ) ) ) ).toVar();
  35658. off.subAssign( 0.5 );
  35659. off.mulAssign( jitter );
  35660. off.addAssign( 0.5 );
  35661. const cellpos = vec3( vec3( float( x ), float( y ), float( z ) ).add( off ) ).toVar();
  35662. const diff = vec3( cellpos.sub( p ) ).toVar();
  35663. If( metric.equal( int( 2 ) ), () => {
  35664. return abs( diff.x ).add( abs( diff.y ) ).add( abs( diff.z ) );
  35665. } );
  35666. If( metric.equal( int( 3 ) ), () => {
  35667. return max$1( max$1( abs( diff.x ), abs( diff.y ) ), abs( diff.z ) );
  35668. } );
  35669. return dot( diff, diff );
  35670. } ).setLayout( {
  35671. name: 'mx_worley_distance_1',
  35672. type: 'float',
  35673. inputs: [
  35674. { name: 'p', type: 'vec3' },
  35675. { name: 'x', type: 'int' },
  35676. { name: 'y', type: 'int' },
  35677. { name: 'z', type: 'int' },
  35678. { name: 'xoff', type: 'int' },
  35679. { name: 'yoff', type: 'int' },
  35680. { name: 'zoff', type: 'int' },
  35681. { name: 'jitter', type: 'float' },
  35682. { name: 'metric', type: 'int' }
  35683. ]
  35684. } );
  35685. const mx_worley_distance = /*@__PURE__*/ overloadingFn( [ mx_worley_distance_0, mx_worley_distance_1 ] );
  35686. const mx_worley_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  35687. const metric = int( metric_immutable ).toVar();
  35688. const jitter = float( jitter_immutable ).toVar();
  35689. const p = vec2( p_immutable ).toVar();
  35690. const X = int().toVar(), Y = int().toVar();
  35691. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  35692. const sqdist = float( 1e6 ).toVar();
  35693. Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  35694. Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  35695. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  35696. sqdist.assign( min$1( sqdist, dist ) );
  35697. } );
  35698. } );
  35699. If( metric.equal( int( 0 ) ), () => {
  35700. sqdist.assign( sqrt( sqdist ) );
  35701. } );
  35702. return sqdist;
  35703. } ).setLayout( {
  35704. name: 'mx_worley_noise_float_0',
  35705. type: 'float',
  35706. inputs: [
  35707. { name: 'p', type: 'vec2' },
  35708. { name: 'jitter', type: 'float' },
  35709. { name: 'metric', type: 'int' }
  35710. ]
  35711. } );
  35712. const mx_worley_noise_vec2_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  35713. const metric = int( metric_immutable ).toVar();
  35714. const jitter = float( jitter_immutable ).toVar();
  35715. const p = vec2( p_immutable ).toVar();
  35716. const X = int().toVar(), Y = int().toVar();
  35717. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  35718. const sqdist = vec2( 1e6, 1e6 ).toVar();
  35719. Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  35720. Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  35721. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  35722. If( dist.lessThan( sqdist.x ), () => {
  35723. sqdist.y.assign( sqdist.x );
  35724. sqdist.x.assign( dist );
  35725. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  35726. sqdist.y.assign( dist );
  35727. } );
  35728. } );
  35729. } );
  35730. If( metric.equal( int( 0 ) ), () => {
  35731. sqdist.assign( sqrt( sqdist ) );
  35732. } );
  35733. return sqdist;
  35734. } ).setLayout( {
  35735. name: 'mx_worley_noise_vec2_0',
  35736. type: 'vec2',
  35737. inputs: [
  35738. { name: 'p', type: 'vec2' },
  35739. { name: 'jitter', type: 'float' },
  35740. { name: 'metric', type: 'int' }
  35741. ]
  35742. } );
  35743. const mx_worley_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  35744. const metric = int( metric_immutable ).toVar();
  35745. const jitter = float( jitter_immutable ).toVar();
  35746. const p = vec2( p_immutable ).toVar();
  35747. const X = int().toVar(), Y = int().toVar();
  35748. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  35749. const sqdist = vec3( 1e6, 1e6, 1e6 ).toVar();
  35750. Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  35751. Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  35752. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  35753. If( dist.lessThan( sqdist.x ), () => {
  35754. sqdist.z.assign( sqdist.y );
  35755. sqdist.y.assign( sqdist.x );
  35756. sqdist.x.assign( dist );
  35757. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  35758. sqdist.z.assign( sqdist.y );
  35759. sqdist.y.assign( dist );
  35760. } ).ElseIf( dist.lessThan( sqdist.z ), () => {
  35761. sqdist.z.assign( dist );
  35762. } );
  35763. } );
  35764. } );
  35765. If( metric.equal( int( 0 ) ), () => {
  35766. sqdist.assign( sqrt( sqdist ) );
  35767. } );
  35768. return sqdist;
  35769. } ).setLayout( {
  35770. name: 'mx_worley_noise_vec3_0',
  35771. type: 'vec3',
  35772. inputs: [
  35773. { name: 'p', type: 'vec2' },
  35774. { name: 'jitter', type: 'float' },
  35775. { name: 'metric', type: 'int' }
  35776. ]
  35777. } );
  35778. const mx_worley_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  35779. const metric = int( metric_immutable ).toVar();
  35780. const jitter = float( jitter_immutable ).toVar();
  35781. const p = vec3( p_immutable ).toVar();
  35782. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  35783. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  35784. const sqdist = float( 1e6 ).toVar();
  35785. Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  35786. Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  35787. Loop( { start: - 1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  35788. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  35789. sqdist.assign( min$1( sqdist, dist ) );
  35790. } );
  35791. } );
  35792. } );
  35793. If( metric.equal( int( 0 ) ), () => {
  35794. sqdist.assign( sqrt( sqdist ) );
  35795. } );
  35796. return sqdist;
  35797. } ).setLayout( {
  35798. name: 'mx_worley_noise_float_1',
  35799. type: 'float',
  35800. inputs: [
  35801. { name: 'p', type: 'vec3' },
  35802. { name: 'jitter', type: 'float' },
  35803. { name: 'metric', type: 'int' }
  35804. ]
  35805. } );
  35806. const mx_worley_noise_float$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_float_0, mx_worley_noise_float_1 ] );
  35807. const mx_worley_noise_vec2_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  35808. const metric = int( metric_immutable ).toVar();
  35809. const jitter = float( jitter_immutable ).toVar();
  35810. const p = vec3( p_immutable ).toVar();
  35811. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  35812. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  35813. const sqdist = vec2( 1e6, 1e6 ).toVar();
  35814. Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  35815. Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  35816. Loop( { start: - 1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  35817. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  35818. If( dist.lessThan( sqdist.x ), () => {
  35819. sqdist.y.assign( sqdist.x );
  35820. sqdist.x.assign( dist );
  35821. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  35822. sqdist.y.assign( dist );
  35823. } );
  35824. } );
  35825. } );
  35826. } );
  35827. If( metric.equal( int( 0 ) ), () => {
  35828. sqdist.assign( sqrt( sqdist ) );
  35829. } );
  35830. return sqdist;
  35831. } ).setLayout( {
  35832. name: 'mx_worley_noise_vec2_1',
  35833. type: 'vec2',
  35834. inputs: [
  35835. { name: 'p', type: 'vec3' },
  35836. { name: 'jitter', type: 'float' },
  35837. { name: 'metric', type: 'int' }
  35838. ]
  35839. } );
  35840. const mx_worley_noise_vec2$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_vec2_0, mx_worley_noise_vec2_1 ] );
  35841. const mx_worley_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  35842. const metric = int( metric_immutable ).toVar();
  35843. const jitter = float( jitter_immutable ).toVar();
  35844. const p = vec3( p_immutable ).toVar();
  35845. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  35846. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  35847. const sqdist = vec3( 1e6, 1e6, 1e6 ).toVar();
  35848. Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  35849. Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  35850. Loop( { start: - 1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  35851. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  35852. If( dist.lessThan( sqdist.x ), () => {
  35853. sqdist.z.assign( sqdist.y );
  35854. sqdist.y.assign( sqdist.x );
  35855. sqdist.x.assign( dist );
  35856. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  35857. sqdist.z.assign( sqdist.y );
  35858. sqdist.y.assign( dist );
  35859. } ).ElseIf( dist.lessThan( sqdist.z ), () => {
  35860. sqdist.z.assign( dist );
  35861. } );
  35862. } );
  35863. } );
  35864. } );
  35865. If( metric.equal( int( 0 ) ), () => {
  35866. sqdist.assign( sqrt( sqdist ) );
  35867. } );
  35868. return sqdist;
  35869. } ).setLayout( {
  35870. name: 'mx_worley_noise_vec3_1',
  35871. type: 'vec3',
  35872. inputs: [
  35873. { name: 'p', type: 'vec3' },
  35874. { name: 'jitter', type: 'float' },
  35875. { name: 'metric', type: 'int' }
  35876. ]
  35877. } );
  35878. const mx_worley_noise_vec3$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_vec3_0, mx_worley_noise_vec3_1 ] );
  35879. // Three.js Transpiler
  35880. // https://github.com/AcademySoftwareFoundation/MaterialX/blob/main/libraries/stdlib/genglsl/lib/mx_hsv.glsl
  35881. const mx_hsvtorgb = /*@__PURE__*/ Fn( ( [ hsv ] ) => {
  35882. const s = hsv.y;
  35883. const v = hsv.z;
  35884. const result = vec3().toVar();
  35885. If( s.lessThan( 0.0001 ), () => {
  35886. result.assign( vec3( v, v, v ) );
  35887. } ).Else( () => {
  35888. let h = hsv.x;
  35889. h = h.sub( floor( h ) ).mul( 6.0 ).toVar(); // TODO: check what .toVar() is needed in node system cache
  35890. const hi = int( trunc( h ) );
  35891. const f = h.sub( float( hi ) );
  35892. const p = v.mul( s.oneMinus() );
  35893. const q = v.mul( s.mul( f ).oneMinus() );
  35894. const t = v.mul( s.mul( f.oneMinus() ).oneMinus() );
  35895. If( hi.equal( int( 0 ) ), () => {
  35896. result.assign( vec3( v, t, p ) );
  35897. } ).ElseIf( hi.equal( int( 1 ) ), () => {
  35898. result.assign( vec3( q, v, p ) );
  35899. } ).ElseIf( hi.equal( int( 2 ) ), () => {
  35900. result.assign( vec3( p, v, t ) );
  35901. } ).ElseIf( hi.equal( int( 3 ) ), () => {
  35902. result.assign( vec3( p, q, v ) );
  35903. } ).ElseIf( hi.equal( int( 4 ) ), () => {
  35904. result.assign( vec3( t, p, v ) );
  35905. } ).Else( () => {
  35906. result.assign( vec3( v, p, q ) );
  35907. } );
  35908. } );
  35909. return result;
  35910. } ).setLayout( {
  35911. name: 'mx_hsvtorgb',
  35912. type: 'vec3',
  35913. inputs: [
  35914. { name: 'hsv', type: 'vec3' }
  35915. ]
  35916. } );
  35917. const mx_rgbtohsv = /*@__PURE__*/ Fn( ( [ c_immutable ] ) => {
  35918. const c = vec3( c_immutable ).toVar();
  35919. const r = float( c.x ).toVar();
  35920. const g = float( c.y ).toVar();
  35921. const b = float( c.z ).toVar();
  35922. const mincomp = float( min$1( r, min$1( g, b ) ) ).toVar();
  35923. const maxcomp = float( max$1( r, max$1( g, b ) ) ).toVar();
  35924. const delta = float( maxcomp.sub( mincomp ) ).toVar();
  35925. const h = float().toVar(), s = float().toVar(), v = float().toVar();
  35926. v.assign( maxcomp );
  35927. If( maxcomp.greaterThan( 0.0 ), () => {
  35928. s.assign( delta.div( maxcomp ) );
  35929. } ).Else( () => {
  35930. s.assign( 0.0 );
  35931. } );
  35932. If( s.lessThanEqual( 0.0 ), () => {
  35933. h.assign( 0.0 );
  35934. } ).Else( () => {
  35935. If( r.greaterThanEqual( maxcomp ), () => {
  35936. h.assign( g.sub( b ).div( delta ) );
  35937. } ).ElseIf( g.greaterThanEqual( maxcomp ), () => {
  35938. h.assign( add( 2.0, b.sub( r ).div( delta ) ) );
  35939. } ).Else( () => {
  35940. h.assign( add( 4.0, r.sub( g ).div( delta ) ) );
  35941. } );
  35942. h.mulAssign( 1.0 / 6.0 );
  35943. If( h.lessThan( 0.0 ), () => {
  35944. h.addAssign( 1.0 );
  35945. } );
  35946. } );
  35947. return vec3( h, s, v );
  35948. } ).setLayout( {
  35949. name: 'mx_rgbtohsv',
  35950. type: 'vec3',
  35951. inputs: [
  35952. { name: 'c', type: 'vec3' }
  35953. ]
  35954. } );
  35955. // Three.js Transpiler
  35956. // https://github.com/AcademySoftwareFoundation/MaterialX/blob/main/libraries/stdlib/genglsl/lib/mx_transform_color.glsl
  35957. const mx_srgb_texture_to_lin_rec709 = /*@__PURE__*/ Fn( ( [ color_immutable ] ) => {
  35958. const color = vec3( color_immutable ).toVar();
  35959. const isAbove = bvec3( greaterThan( color, vec3( 0.04045 ) ) ).toVar();
  35960. const linSeg = vec3( color.div( 12.92 ) ).toVar();
  35961. const powSeg = vec3( pow( max$1( color.add( vec3( 0.055 ) ), vec3( 0.0 ) ).div( 1.055 ), vec3( 2.4 ) ) ).toVar();
  35962. return mix( linSeg, powSeg, isAbove );
  35963. } ).setLayout( {
  35964. name: 'mx_srgb_texture_to_lin_rec709',
  35965. type: 'vec3',
  35966. inputs: [
  35967. { name: 'color', type: 'vec3' }
  35968. ]
  35969. } );
  35970. const mx_aastep = ( threshold, value ) => {
  35971. threshold = float( threshold );
  35972. value = float( value );
  35973. const afwidth = vec2( value.dFdx(), value.dFdy() ).length().mul( 0.70710678118654757 );
  35974. return smoothstep( threshold.sub( afwidth ), threshold.add( afwidth ), value );
  35975. };
  35976. const _ramp = ( a, b, uv, p ) => mix( a, b, uv[ p ].clamp() );
  35977. const mx_ramplr = ( valuel, valuer, texcoord = uv() ) => _ramp( valuel, valuer, texcoord, 'x' );
  35978. const mx_ramptb = ( valuet, valueb, texcoord = uv() ) => _ramp( valuet, valueb, texcoord, 'y' );
  35979. const _split = ( a, b, center, uv, p ) => mix( a, b, mx_aastep( center, uv[ p ] ) );
  35980. const mx_splitlr = ( valuel, valuer, center, texcoord = uv() ) => _split( valuel, valuer, center, texcoord, 'x' );
  35981. const mx_splittb = ( valuet, valueb, center, texcoord = uv() ) => _split( valuet, valueb, center, texcoord, 'y' );
  35982. const mx_transform_uv = ( uv_scale = 1, uv_offset = 0, uv_geo = uv() ) => uv_geo.mul( uv_scale ).add( uv_offset );
  35983. const mx_safepower = ( in1, in2 = 1 ) => {
  35984. in1 = float( in1 );
  35985. return in1.abs().pow( in2 ).mul( in1.sign() );
  35986. };
  35987. const mx_contrast = ( input, amount = 1, pivot = .5 ) => float( input ).sub( pivot ).mul( amount ).add( pivot );
  35988. const mx_noise_float = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_float( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  35989. //export const mx_noise_vec2 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_vec3( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  35990. const mx_noise_vec3 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_vec3( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  35991. const mx_noise_vec4 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => {
  35992. texcoord = texcoord.convert( 'vec2|vec3' ); // overloading type
  35993. const noise_vec4 = vec4( mx_perlin_noise_vec3( texcoord ), mx_perlin_noise_float( texcoord.add( vec2( 19, 73 ) ) ) );
  35994. return noise_vec4.mul( amplitude ).add( pivot );
  35995. };
  35996. const mx_worley_noise_float = ( texcoord = uv(), jitter = 1 ) => mx_worley_noise_float$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  35997. const mx_worley_noise_vec2 = ( texcoord = uv(), jitter = 1 ) => mx_worley_noise_vec2$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  35998. const mx_worley_noise_vec3 = ( texcoord = uv(), jitter = 1 ) => mx_worley_noise_vec3$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  35999. const mx_cell_noise_float = ( texcoord = uv() ) => mx_cell_noise_float$1( texcoord.convert( 'vec2|vec3' ) );
  36000. const mx_fractal_noise_float = ( position = uv(), octaves = 3, lacunarity = 2, diminish = .5, amplitude = 1 ) => mx_fractal_noise_float$1( position, int( octaves ), lacunarity, diminish ).mul( amplitude );
  36001. const mx_fractal_noise_vec2 = ( position = uv(), octaves = 3, lacunarity = 2, diminish = .5, amplitude = 1 ) => mx_fractal_noise_vec2$1( position, int( octaves ), lacunarity, diminish ).mul( amplitude );
  36002. const mx_fractal_noise_vec3 = ( position = uv(), octaves = 3, lacunarity = 2, diminish = .5, amplitude = 1 ) => mx_fractal_noise_vec3$1( position, int( octaves ), lacunarity, diminish ).mul( amplitude );
  36003. const mx_fractal_noise_vec4 = ( position = uv(), octaves = 3, lacunarity = 2, diminish = .5, amplitude = 1 ) => mx_fractal_noise_vec4$1( position, int( octaves ), lacunarity, diminish ).mul( amplitude );
  36004. const getShIrradianceAt = /*@__PURE__*/ Fn( ( [ normal, shCoefficients ] ) => {
  36005. // normal is assumed to have unit length
  36006. const x = normal.x, y = normal.y, z = normal.z;
  36007. // band 0
  36008. let result = shCoefficients.element( 0 ).mul( 0.886227 );
  36009. // band 1
  36010. result = result.add( shCoefficients.element( 1 ).mul( 2.0 * 0.511664 ).mul( y ) );
  36011. result = result.add( shCoefficients.element( 2 ).mul( 2.0 * 0.511664 ).mul( z ) );
  36012. result = result.add( shCoefficients.element( 3 ).mul( 2.0 * 0.511664 ).mul( x ) );
  36013. // band 2
  36014. result = result.add( shCoefficients.element( 4 ).mul( 2.0 * 0.429043 ).mul( x ).mul( y ) );
  36015. result = result.add( shCoefficients.element( 5 ).mul( 2.0 * 0.429043 ).mul( y ).mul( z ) );
  36016. result = result.add( shCoefficients.element( 6 ).mul( z.mul( z ).mul( 0.743125 ).sub( 0.247708 ) ) );
  36017. result = result.add( shCoefficients.element( 7 ).mul( 2.0 * 0.429043 ).mul( x ).mul( z ) );
  36018. result = result.add( shCoefficients.element( 8 ).mul( 0.429043 ).mul( mul( x, x ).sub( mul( y, y ) ) ) );
  36019. return result;
  36020. } );
  36021. class PointLightNode extends AnalyticLightNode {
  36022. static get type() {
  36023. return 'PointLightNode';
  36024. }
  36025. constructor( light = null ) {
  36026. super( light );
  36027. this.cutoffDistanceNode = uniform( 0 ).setGroup( renderGroup );
  36028. this.decayExponentNode = uniform( 0 ).setGroup( renderGroup );
  36029. }
  36030. update( frame ) {
  36031. const { light } = this;
  36032. super.update( frame );
  36033. this.cutoffDistanceNode.value = light.distance;
  36034. this.decayExponentNode.value = light.decay;
  36035. }
  36036. setup( builder ) {
  36037. const { colorNode, cutoffDistanceNode, decayExponentNode, light } = this;
  36038. const lightingModel = builder.context.lightingModel;
  36039. const lVector = lightViewPosition( light ).sub( positionView ); // @TODO: Add it into LightNode
  36040. const lightDirection = lVector.normalize();
  36041. const lightDistance = lVector.length();
  36042. const lightAttenuation = getDistanceAttenuation( {
  36043. lightDistance,
  36044. cutoffDistance: cutoffDistanceNode,
  36045. decayExponent: decayExponentNode
  36046. } );
  36047. const lightColor = colorNode.mul( lightAttenuation );
  36048. const reflectedLight = builder.context.reflectedLight;
  36049. lightingModel.direct( {
  36050. lightDirection,
  36051. lightColor,
  36052. reflectedLight
  36053. }, builder.stack, builder );
  36054. }
  36055. }
  36056. class DirectionalLightNode extends AnalyticLightNode {
  36057. static get type() {
  36058. return 'DirectionalLightNode';
  36059. }
  36060. constructor( light = null ) {
  36061. super( light );
  36062. }
  36063. setup( builder ) {
  36064. super.setup( builder );
  36065. const lightingModel = builder.context.lightingModel;
  36066. const lightColor = this.colorNode;
  36067. const lightDirection = lightTargetDirection( this.light );
  36068. const reflectedLight = builder.context.reflectedLight;
  36069. lightingModel.direct( {
  36070. lightDirection,
  36071. lightColor,
  36072. reflectedLight
  36073. }, builder.stack, builder );
  36074. }
  36075. }
  36076. const _matrix41 = /*@__PURE__*/ new Matrix4();
  36077. const _matrix42 = /*@__PURE__*/ new Matrix4();
  36078. let ltcLib = null;
  36079. class RectAreaLightNode extends AnalyticLightNode {
  36080. static get type() {
  36081. return 'RectAreaLightNode';
  36082. }
  36083. constructor( light = null ) {
  36084. super( light );
  36085. this.halfHeight = uniform( new Vector3() ).setGroup( renderGroup );
  36086. this.halfWidth = uniform( new Vector3() ).setGroup( renderGroup );
  36087. }
  36088. update( frame ) {
  36089. super.update( frame );
  36090. const { light } = this;
  36091. const viewMatrix = frame.camera.matrixWorldInverse;
  36092. _matrix42.identity();
  36093. _matrix41.copy( light.matrixWorld );
  36094. _matrix41.premultiply( viewMatrix );
  36095. _matrix42.extractRotation( _matrix41 );
  36096. this.halfWidth.value.set( light.width * 0.5, 0.0, 0.0 );
  36097. this.halfHeight.value.set( 0.0, light.height * 0.5, 0.0 );
  36098. this.halfWidth.value.applyMatrix4( _matrix42 );
  36099. this.halfHeight.value.applyMatrix4( _matrix42 );
  36100. }
  36101. setup( builder ) {
  36102. super.setup( builder );
  36103. let ltc_1, ltc_2;
  36104. if ( builder.isAvailable( 'float32Filterable' ) ) {
  36105. ltc_1 = texture( ltcLib.LTC_FLOAT_1 );
  36106. ltc_2 = texture( ltcLib.LTC_FLOAT_2 );
  36107. } else {
  36108. ltc_1 = texture( ltcLib.LTC_HALF_1 );
  36109. ltc_2 = texture( ltcLib.LTC_HALF_2 );
  36110. }
  36111. const { colorNode, light } = this;
  36112. const lightingModel = builder.context.lightingModel;
  36113. const lightPosition = lightViewPosition( light );
  36114. const reflectedLight = builder.context.reflectedLight;
  36115. lightingModel.directRectArea( {
  36116. lightColor: colorNode,
  36117. lightPosition,
  36118. halfWidth: this.halfWidth,
  36119. halfHeight: this.halfHeight,
  36120. reflectedLight,
  36121. ltc_1,
  36122. ltc_2
  36123. }, builder.stack, builder );
  36124. }
  36125. static setLTC( ltc ) {
  36126. ltcLib = ltc;
  36127. }
  36128. }
  36129. class SpotLightNode extends AnalyticLightNode {
  36130. static get type() {
  36131. return 'SpotLightNode';
  36132. }
  36133. constructor( light = null ) {
  36134. super( light );
  36135. this.coneCosNode = uniform( 0 ).setGroup( renderGroup );
  36136. this.penumbraCosNode = uniform( 0 ).setGroup( renderGroup );
  36137. this.cutoffDistanceNode = uniform( 0 ).setGroup( renderGroup );
  36138. this.decayExponentNode = uniform( 0 ).setGroup( renderGroup );
  36139. }
  36140. update( frame ) {
  36141. super.update( frame );
  36142. const { light } = this;
  36143. this.coneCosNode.value = Math.cos( light.angle );
  36144. this.penumbraCosNode.value = Math.cos( light.angle * ( 1 - light.penumbra ) );
  36145. this.cutoffDistanceNode.value = light.distance;
  36146. this.decayExponentNode.value = light.decay;
  36147. }
  36148. getSpotAttenuation( angleCosine ) {
  36149. const { coneCosNode, penumbraCosNode } = this;
  36150. return smoothstep( coneCosNode, penumbraCosNode, angleCosine );
  36151. }
  36152. setup( builder ) {
  36153. super.setup( builder );
  36154. const lightingModel = builder.context.lightingModel;
  36155. const { colorNode, cutoffDistanceNode, decayExponentNode, light } = this;
  36156. const lVector = lightViewPosition( light ).sub( positionView ); // @TODO: Add it into LightNode
  36157. const lightDirection = lVector.normalize();
  36158. const angleCos = lightDirection.dot( lightTargetDirection( light ) );
  36159. const spotAttenuation = this.getSpotAttenuation( angleCos );
  36160. const lightDistance = lVector.length();
  36161. const lightAttenuation = getDistanceAttenuation( {
  36162. lightDistance,
  36163. cutoffDistance: cutoffDistanceNode,
  36164. decayExponent: decayExponentNode
  36165. } );
  36166. const lightColor = colorNode.mul( spotAttenuation ).mul( lightAttenuation );
  36167. const reflectedLight = builder.context.reflectedLight;
  36168. lightingModel.direct( {
  36169. lightDirection,
  36170. lightColor,
  36171. reflectedLight
  36172. }, builder.stack, builder );
  36173. }
  36174. }
  36175. class IESSpotLightNode extends SpotLightNode {
  36176. static get type() {
  36177. return 'IESSpotLightNode';
  36178. }
  36179. getSpotAttenuation( angleCosine ) {
  36180. const iesMap = this.light.iesMap;
  36181. let spotAttenuation = null;
  36182. if ( iesMap && iesMap.isTexture === true ) {
  36183. const angle = angleCosine.acos().mul( 1.0 / Math.PI );
  36184. spotAttenuation = texture( iesMap, vec2( angle, 0 ), 0 ).r;
  36185. } else {
  36186. spotAttenuation = super.getSpotAttenuation( angleCosine );
  36187. }
  36188. return spotAttenuation;
  36189. }
  36190. }
  36191. class AmbientLightNode extends AnalyticLightNode {
  36192. static get type() {
  36193. return 'AmbientLightNode';
  36194. }
  36195. constructor( light = null ) {
  36196. super( light );
  36197. }
  36198. setup( { context } ) {
  36199. context.irradiance.addAssign( this.colorNode );
  36200. }
  36201. }
  36202. class HemisphereLightNode extends AnalyticLightNode {
  36203. static get type() {
  36204. return 'HemisphereLightNode';
  36205. }
  36206. constructor( light = null ) {
  36207. super( light );
  36208. this.lightPositionNode = lightPosition( light );
  36209. this.lightDirectionNode = this.lightPositionNode.normalize();
  36210. this.groundColorNode = uniform( new Color() ).setGroup( renderGroup );
  36211. }
  36212. update( frame ) {
  36213. const { light } = this;
  36214. super.update( frame );
  36215. this.lightPositionNode.object3d = light;
  36216. this.groundColorNode.value.copy( light.groundColor ).multiplyScalar( light.intensity );
  36217. }
  36218. setup( builder ) {
  36219. const { colorNode, groundColorNode, lightDirectionNode } = this;
  36220. const dotNL = normalView.dot( lightDirectionNode );
  36221. const hemiDiffuseWeight = dotNL.mul( 0.5 ).add( 0.5 );
  36222. const irradiance = mix( groundColorNode, colorNode, hemiDiffuseWeight );
  36223. builder.context.irradiance.addAssign( irradiance );
  36224. }
  36225. }
  36226. class LightProbeNode extends AnalyticLightNode {
  36227. static get type() {
  36228. return 'LightProbeNode';
  36229. }
  36230. constructor( light = null ) {
  36231. super( light );
  36232. const array = [];
  36233. for ( let i = 0; i < 9; i ++ ) array.push( new Vector3() );
  36234. this.lightProbe = uniformArray( array );
  36235. }
  36236. update( frame ) {
  36237. const { light } = this;
  36238. super.update( frame );
  36239. //
  36240. for ( let i = 0; i < 9; i ++ ) {
  36241. this.lightProbe.array[ i ].copy( light.sh.coefficients[ i ] ).multiplyScalar( light.intensity );
  36242. }
  36243. }
  36244. setup( builder ) {
  36245. const irradiance = getShIrradianceAt( normalWorld, this.lightProbe );
  36246. builder.context.irradiance.addAssign( irradiance );
  36247. }
  36248. }
  36249. class NodeParser {
  36250. parseFunction( /*source*/ ) {
  36251. console.warn( 'Abstract function.' );
  36252. }
  36253. }
  36254. class NodeFunction {
  36255. constructor( type, inputs, name = '', precision = '' ) {
  36256. this.type = type;
  36257. this.inputs = inputs;
  36258. this.name = name;
  36259. this.precision = precision;
  36260. }
  36261. getCode( /*name = this.name*/ ) {
  36262. console.warn( 'Abstract function.' );
  36263. }
  36264. }
  36265. NodeFunction.isNodeFunction = true;
  36266. const declarationRegexp$1 = /^\s*(highp|mediump|lowp)?\s*([a-z_0-9]+)\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)/i;
  36267. const propertiesRegexp$1 = /[a-z_0-9]+/ig;
  36268. const pragmaMain = '#pragma main';
  36269. const parse$1 = ( source ) => {
  36270. source = source.trim();
  36271. const pragmaMainIndex = source.indexOf( pragmaMain );
  36272. const mainCode = pragmaMainIndex !== - 1 ? source.slice( pragmaMainIndex + pragmaMain.length ) : source;
  36273. const declaration = mainCode.match( declarationRegexp$1 );
  36274. if ( declaration !== null && declaration.length === 5 ) {
  36275. // tokenizer
  36276. const inputsCode = declaration[ 4 ];
  36277. const propsMatches = [];
  36278. let nameMatch = null;
  36279. while ( ( nameMatch = propertiesRegexp$1.exec( inputsCode ) ) !== null ) {
  36280. propsMatches.push( nameMatch );
  36281. }
  36282. // parser
  36283. const inputs = [];
  36284. let i = 0;
  36285. while ( i < propsMatches.length ) {
  36286. const isConst = propsMatches[ i ][ 0 ] === 'const';
  36287. if ( isConst === true ) {
  36288. i ++;
  36289. }
  36290. let qualifier = propsMatches[ i ][ 0 ];
  36291. if ( qualifier === 'in' || qualifier === 'out' || qualifier === 'inout' ) {
  36292. i ++;
  36293. } else {
  36294. qualifier = '';
  36295. }
  36296. const type = propsMatches[ i ++ ][ 0 ];
  36297. let count = Number.parseInt( propsMatches[ i ][ 0 ] );
  36298. if ( Number.isNaN( count ) === false ) i ++;
  36299. else count = null;
  36300. const name = propsMatches[ i ++ ][ 0 ];
  36301. inputs.push( new NodeFunctionInput( type, name, count, qualifier, isConst ) );
  36302. }
  36303. //
  36304. const blockCode = mainCode.substring( declaration[ 0 ].length );
  36305. const name = declaration[ 3 ] !== undefined ? declaration[ 3 ] : '';
  36306. const type = declaration[ 2 ];
  36307. const precision = declaration[ 1 ] !== undefined ? declaration[ 1 ] : '';
  36308. const headerCode = pragmaMainIndex !== - 1 ? source.slice( 0, pragmaMainIndex ) : '';
  36309. return {
  36310. type,
  36311. inputs,
  36312. name,
  36313. precision,
  36314. inputsCode,
  36315. blockCode,
  36316. headerCode
  36317. };
  36318. } else {
  36319. throw new Error( 'FunctionNode: Function is not a GLSL code.' );
  36320. }
  36321. };
  36322. class GLSLNodeFunction extends NodeFunction {
  36323. constructor( source ) {
  36324. const { type, inputs, name, precision, inputsCode, blockCode, headerCode } = parse$1( source );
  36325. super( type, inputs, name, precision );
  36326. this.inputsCode = inputsCode;
  36327. this.blockCode = blockCode;
  36328. this.headerCode = headerCode;
  36329. }
  36330. getCode( name = this.name ) {
  36331. let code;
  36332. const blockCode = this.blockCode;
  36333. if ( blockCode !== '' ) {
  36334. const { type, inputsCode, headerCode, precision } = this;
  36335. let declarationCode = `${ type } ${ name } ( ${ inputsCode.trim() } )`;
  36336. if ( precision !== '' ) {
  36337. declarationCode = `${ precision } ${ declarationCode }`;
  36338. }
  36339. code = headerCode + declarationCode + blockCode;
  36340. } else {
  36341. // interface function
  36342. code = '';
  36343. }
  36344. return code;
  36345. }
  36346. }
  36347. class GLSLNodeParser extends NodeParser {
  36348. parseFunction( source ) {
  36349. return new GLSLNodeFunction( source );
  36350. }
  36351. }
  36352. function painterSortStable( a, b ) {
  36353. if ( a.groupOrder !== b.groupOrder ) {
  36354. return a.groupOrder - b.groupOrder;
  36355. } else if ( a.renderOrder !== b.renderOrder ) {
  36356. return a.renderOrder - b.renderOrder;
  36357. } else if ( a.material.id !== b.material.id ) {
  36358. return a.material.id - b.material.id;
  36359. } else if ( a.z !== b.z ) {
  36360. return a.z - b.z;
  36361. } else {
  36362. return a.id - b.id;
  36363. }
  36364. }
  36365. function reversePainterSortStable( a, b ) {
  36366. if ( a.groupOrder !== b.groupOrder ) {
  36367. return a.groupOrder - b.groupOrder;
  36368. } else if ( a.renderOrder !== b.renderOrder ) {
  36369. return a.renderOrder - b.renderOrder;
  36370. } else if ( a.z !== b.z ) {
  36371. return b.z - a.z;
  36372. } else {
  36373. return a.id - b.id;
  36374. }
  36375. }
  36376. class RenderList {
  36377. constructor() {
  36378. this.renderItems = [];
  36379. this.renderItemsIndex = 0;
  36380. this.opaque = [];
  36381. this.transparent = [];
  36382. this.bundles = [];
  36383. this.lightsNode = new LightsNode( [] );
  36384. this.lightsArray = [];
  36385. this.occlusionQueryCount = 0;
  36386. }
  36387. begin() {
  36388. this.renderItemsIndex = 0;
  36389. this.opaque.length = 0;
  36390. this.transparent.length = 0;
  36391. this.bundles.length = 0;
  36392. this.lightsArray.length = 0;
  36393. this.occlusionQueryCount = 0;
  36394. return this;
  36395. }
  36396. getNextRenderItem( object, geometry, material, groupOrder, z, group ) {
  36397. let renderItem = this.renderItems[ this.renderItemsIndex ];
  36398. if ( renderItem === undefined ) {
  36399. renderItem = {
  36400. id: object.id,
  36401. object: object,
  36402. geometry: geometry,
  36403. material: material,
  36404. groupOrder: groupOrder,
  36405. renderOrder: object.renderOrder,
  36406. z: z,
  36407. group: group
  36408. };
  36409. this.renderItems[ this.renderItemsIndex ] = renderItem;
  36410. } else {
  36411. renderItem.id = object.id;
  36412. renderItem.object = object;
  36413. renderItem.geometry = geometry;
  36414. renderItem.material = material;
  36415. renderItem.groupOrder = groupOrder;
  36416. renderItem.renderOrder = object.renderOrder;
  36417. renderItem.z = z;
  36418. renderItem.group = group;
  36419. }
  36420. this.renderItemsIndex ++;
  36421. return renderItem;
  36422. }
  36423. push( object, geometry, material, groupOrder, z, group ) {
  36424. const renderItem = this.getNextRenderItem( object, geometry, material, groupOrder, z, group );
  36425. if ( object.occlusionTest === true ) this.occlusionQueryCount ++;
  36426. ( material.transparent === true || material.transmission > 0 ? this.transparent : this.opaque ).push( renderItem );
  36427. }
  36428. unshift( object, geometry, material, groupOrder, z, group ) {
  36429. const renderItem = this.getNextRenderItem( object, geometry, material, groupOrder, z, group );
  36430. ( material.transparent === true ? this.transparent : this.opaque ).unshift( renderItem );
  36431. }
  36432. pushBundle( group ) {
  36433. this.bundles.push( group );
  36434. }
  36435. pushLight( light ) {
  36436. this.lightsArray.push( light );
  36437. }
  36438. sort( customOpaqueSort, customTransparentSort ) {
  36439. if ( this.opaque.length > 1 ) this.opaque.sort( customOpaqueSort || painterSortStable );
  36440. if ( this.transparent.length > 1 ) this.transparent.sort( customTransparentSort || reversePainterSortStable );
  36441. }
  36442. finish() {
  36443. // update lights
  36444. this.lightsNode.setLights( this.lightsArray );
  36445. // Clear references from inactive renderItems in the list
  36446. for ( let i = this.renderItemsIndex, il = this.renderItems.length; i < il; i ++ ) {
  36447. const renderItem = this.renderItems[ i ];
  36448. if ( renderItem.id === null ) break;
  36449. renderItem.id = null;
  36450. renderItem.object = null;
  36451. renderItem.geometry = null;
  36452. renderItem.material = null;
  36453. renderItem.groupOrder = null;
  36454. renderItem.renderOrder = null;
  36455. renderItem.z = null;
  36456. renderItem.group = null;
  36457. }
  36458. }
  36459. }
  36460. class RenderLists {
  36461. constructor() {
  36462. this.lists = new ChainMap();
  36463. }
  36464. get( scene, camera ) {
  36465. const lists = this.lists;
  36466. const keys = [ scene, camera ];
  36467. let list = lists.get( keys );
  36468. if ( list === undefined ) {
  36469. list = new RenderList();
  36470. lists.set( keys, list );
  36471. }
  36472. return list;
  36473. }
  36474. dispose() {
  36475. this.lists = new ChainMap();
  36476. }
  36477. }
  36478. let id = 0;
  36479. class RenderContext {
  36480. constructor() {
  36481. this.id = id ++;
  36482. this.color = true;
  36483. this.clearColor = true;
  36484. this.clearColorValue = { r: 0, g: 0, b: 0, a: 1 };
  36485. this.depth = true;
  36486. this.clearDepth = true;
  36487. this.clearDepthValue = 1;
  36488. this.stencil = false;
  36489. this.clearStencil = true;
  36490. this.clearStencilValue = 1;
  36491. this.viewport = false;
  36492. this.viewportValue = new Vector4();
  36493. this.scissor = false;
  36494. this.scissorValue = new Vector4();
  36495. this.textures = null;
  36496. this.depthTexture = null;
  36497. this.activeCubeFace = 0;
  36498. this.sampleCount = 1;
  36499. this.width = 0;
  36500. this.height = 0;
  36501. this.isRenderContext = true;
  36502. }
  36503. getCacheKey() {
  36504. return getCacheKey( this );
  36505. }
  36506. }
  36507. function getCacheKey( renderContext ) {
  36508. const { textures, activeCubeFace } = renderContext;
  36509. const values = [ activeCubeFace ];
  36510. for ( const texture of textures ) {
  36511. values.push( texture.id );
  36512. }
  36513. return hashArray( values );
  36514. }
  36515. class RenderContexts {
  36516. constructor() {
  36517. this.chainMaps = {};
  36518. }
  36519. get( scene, camera, renderTarget = null ) {
  36520. const chainKey = [ scene, camera ];
  36521. let attachmentState;
  36522. if ( renderTarget === null ) {
  36523. attachmentState = 'default';
  36524. } else {
  36525. const format = renderTarget.texture.format;
  36526. const count = renderTarget.textures.length;
  36527. attachmentState = `${ count }:${ format }:${ renderTarget.samples }:${ renderTarget.depthBuffer }:${ renderTarget.stencilBuffer }`;
  36528. }
  36529. const chainMap = this.getChainMap( attachmentState );
  36530. let renderState = chainMap.get( chainKey );
  36531. if ( renderState === undefined ) {
  36532. renderState = new RenderContext();
  36533. chainMap.set( chainKey, renderState );
  36534. }
  36535. if ( renderTarget !== null ) renderState.sampleCount = renderTarget.samples === 0 ? 1 : renderTarget.samples;
  36536. return renderState;
  36537. }
  36538. getChainMap( attachmentState ) {
  36539. return this.chainMaps[ attachmentState ] || ( this.chainMaps[ attachmentState ] = new ChainMap() );
  36540. }
  36541. dispose() {
  36542. this.chainMaps = {};
  36543. }
  36544. }
  36545. const _size = /*@__PURE__*/ new Vector3();
  36546. class Textures extends DataMap {
  36547. constructor( renderer, backend, info ) {
  36548. super();
  36549. this.renderer = renderer;
  36550. this.backend = backend;
  36551. this.info = info;
  36552. }
  36553. updateRenderTarget( renderTarget, activeMipmapLevel = 0 ) {
  36554. const renderTargetData = this.get( renderTarget );
  36555. const sampleCount = renderTarget.samples === 0 ? 1 : renderTarget.samples;
  36556. const depthTextureMips = renderTargetData.depthTextureMips || ( renderTargetData.depthTextureMips = {} );
  36557. const textures = renderTarget.textures;
  36558. const size = this.getSize( textures[ 0 ] );
  36559. const mipWidth = size.width >> activeMipmapLevel;
  36560. const mipHeight = size.height >> activeMipmapLevel;
  36561. let depthTexture = renderTarget.depthTexture || depthTextureMips[ activeMipmapLevel ];
  36562. const useDepthTexture = renderTarget.depthBuffer === true || renderTarget.stencilBuffer === true;
  36563. let textureNeedsUpdate = false;
  36564. if ( depthTexture === undefined && useDepthTexture ) {
  36565. depthTexture = new DepthTexture();
  36566. depthTexture.format = renderTarget.stencilBuffer ? DepthStencilFormat : DepthFormat;
  36567. depthTexture.type = renderTarget.stencilBuffer ? UnsignedInt248Type : UnsignedIntType; // FloatType
  36568. depthTexture.image.width = mipWidth;
  36569. depthTexture.image.height = mipHeight;
  36570. depthTextureMips[ activeMipmapLevel ] = depthTexture;
  36571. }
  36572. if ( renderTargetData.width !== size.width || size.height !== renderTargetData.height ) {
  36573. textureNeedsUpdate = true;
  36574. if ( depthTexture ) {
  36575. depthTexture.needsUpdate = true;
  36576. depthTexture.image.width = mipWidth;
  36577. depthTexture.image.height = mipHeight;
  36578. }
  36579. }
  36580. renderTargetData.width = size.width;
  36581. renderTargetData.height = size.height;
  36582. renderTargetData.textures = textures;
  36583. renderTargetData.depthTexture = depthTexture || null;
  36584. renderTargetData.depth = renderTarget.depthBuffer;
  36585. renderTargetData.stencil = renderTarget.stencilBuffer;
  36586. renderTargetData.renderTarget = renderTarget;
  36587. if ( renderTargetData.sampleCount !== sampleCount ) {
  36588. textureNeedsUpdate = true;
  36589. if ( depthTexture ) {
  36590. depthTexture.needsUpdate = true;
  36591. }
  36592. renderTargetData.sampleCount = sampleCount;
  36593. }
  36594. //
  36595. const options = { sampleCount };
  36596. for ( let i = 0; i < textures.length; i ++ ) {
  36597. const texture = textures[ i ];
  36598. if ( textureNeedsUpdate ) texture.needsUpdate = true;
  36599. this.updateTexture( texture, options );
  36600. }
  36601. if ( depthTexture ) {
  36602. this.updateTexture( depthTexture, options );
  36603. }
  36604. // dispose handler
  36605. if ( renderTargetData.initialized !== true ) {
  36606. renderTargetData.initialized = true;
  36607. // dispose
  36608. const onDispose = () => {
  36609. renderTarget.removeEventListener( 'dispose', onDispose );
  36610. for ( let i = 0; i < textures.length; i ++ ) {
  36611. this._destroyTexture( textures[ i ] );
  36612. }
  36613. if ( depthTexture ) {
  36614. this._destroyTexture( depthTexture );
  36615. }
  36616. this.delete( renderTarget );
  36617. };
  36618. renderTarget.addEventListener( 'dispose', onDispose );
  36619. }
  36620. }
  36621. updateTexture( texture, options = {} ) {
  36622. const textureData = this.get( texture );
  36623. if ( textureData.initialized === true && textureData.version === texture.version ) return;
  36624. const isRenderTarget = texture.isRenderTargetTexture || texture.isDepthTexture || texture.isFramebufferTexture;
  36625. const backend = this.backend;
  36626. if ( isRenderTarget && textureData.initialized === true ) {
  36627. // it's an update
  36628. backend.destroySampler( texture );
  36629. backend.destroyTexture( texture );
  36630. }
  36631. //
  36632. if ( texture.isFramebufferTexture ) {
  36633. const renderer = this.renderer;
  36634. const renderTarget = renderer.getRenderTarget();
  36635. if ( renderTarget ) {
  36636. texture.type = renderTarget.texture.type;
  36637. } else {
  36638. texture.type = UnsignedByteType;
  36639. }
  36640. }
  36641. //
  36642. const { width, height, depth } = this.getSize( texture );
  36643. options.width = width;
  36644. options.height = height;
  36645. options.depth = depth;
  36646. options.needsMipmaps = this.needsMipmaps( texture );
  36647. options.levels = options.needsMipmaps ? this.getMipLevels( texture, width, height ) : 1;
  36648. //
  36649. if ( isRenderTarget || texture.isStorageTexture === true ) {
  36650. backend.createSampler( texture );
  36651. backend.createTexture( texture, options );
  36652. textureData.generation = texture.version;
  36653. } else {
  36654. const needsCreate = textureData.initialized !== true;
  36655. if ( needsCreate ) backend.createSampler( texture );
  36656. if ( texture.version > 0 ) {
  36657. const image = texture.image;
  36658. if ( image === undefined ) {
  36659. console.warn( 'THREE.Renderer: Texture marked for update but image is undefined.' );
  36660. } else if ( image.complete === false ) {
  36661. console.warn( 'THREE.Renderer: Texture marked for update but image is incomplete.' );
  36662. } else {
  36663. if ( texture.images ) {
  36664. const images = [];
  36665. for ( const image of texture.images ) {
  36666. images.push( image );
  36667. }
  36668. options.images = images;
  36669. } else {
  36670. options.image = image;
  36671. }
  36672. if ( textureData.isDefaultTexture === undefined || textureData.isDefaultTexture === true ) {
  36673. backend.createTexture( texture, options );
  36674. textureData.isDefaultTexture = false;
  36675. textureData.generation = texture.version;
  36676. }
  36677. if ( texture.source.dataReady === true ) backend.updateTexture( texture, options );
  36678. if ( options.needsMipmaps && texture.mipmaps.length === 0 ) backend.generateMipmaps( texture );
  36679. }
  36680. } else {
  36681. // async update
  36682. backend.createDefaultTexture( texture );
  36683. textureData.isDefaultTexture = true;
  36684. textureData.generation = texture.version;
  36685. }
  36686. }
  36687. // dispose handler
  36688. if ( textureData.initialized !== true ) {
  36689. textureData.initialized = true;
  36690. textureData.generation = texture.version;
  36691. //
  36692. this.info.memory.textures ++;
  36693. // dispose
  36694. const onDispose = () => {
  36695. texture.removeEventListener( 'dispose', onDispose );
  36696. this._destroyTexture( texture );
  36697. this.info.memory.textures --;
  36698. };
  36699. texture.addEventListener( 'dispose', onDispose );
  36700. }
  36701. //
  36702. textureData.version = texture.version;
  36703. }
  36704. getSize( texture, target = _size ) {
  36705. let image = texture.images ? texture.images[ 0 ] : texture.image;
  36706. if ( image ) {
  36707. if ( image.image !== undefined ) image = image.image;
  36708. target.width = image.width;
  36709. target.height = image.height;
  36710. target.depth = texture.isCubeTexture ? 6 : ( image.depth || 1 );
  36711. } else {
  36712. target.width = target.height = target.depth = 1;
  36713. }
  36714. return target;
  36715. }
  36716. getMipLevels( texture, width, height ) {
  36717. let mipLevelCount;
  36718. if ( texture.isCompressedTexture ) {
  36719. mipLevelCount = texture.mipmaps.length;
  36720. } else {
  36721. mipLevelCount = Math.floor( Math.log2( Math.max( width, height ) ) ) + 1;
  36722. }
  36723. return mipLevelCount;
  36724. }
  36725. needsMipmaps( texture ) {
  36726. if ( this.isEnvironmentTexture( texture ) ) return true;
  36727. return ( texture.isCompressedTexture === true ) || ( ( texture.minFilter !== NearestFilter ) && ( texture.minFilter !== LinearFilter ) );
  36728. }
  36729. isEnvironmentTexture( texture ) {
  36730. const mapping = texture.mapping;
  36731. return ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) || ( mapping === CubeReflectionMapping || mapping === CubeRefractionMapping );
  36732. }
  36733. _destroyTexture( texture ) {
  36734. this.backend.destroySampler( texture );
  36735. this.backend.destroyTexture( texture );
  36736. this.delete( texture );
  36737. }
  36738. }
  36739. class Color4 extends Color {
  36740. constructor( r, g, b, a = 1 ) {
  36741. super( r, g, b );
  36742. this.a = a;
  36743. }
  36744. set( r, g, b, a = 1 ) {
  36745. this.a = a;
  36746. return super.set( r, g, b );
  36747. }
  36748. copy( color ) {
  36749. if ( color.a !== undefined ) this.a = color.a;
  36750. return super.copy( color );
  36751. }
  36752. clone() {
  36753. return new this.constructor( this.r, this.g, this.b, this.a );
  36754. }
  36755. }
  36756. const _clearColor = /*@__PURE__*/ new Color4();
  36757. class Background extends DataMap {
  36758. constructor( renderer, nodes ) {
  36759. super();
  36760. this.renderer = renderer;
  36761. this.nodes = nodes;
  36762. }
  36763. update( scene, renderList, renderContext ) {
  36764. const renderer = this.renderer;
  36765. const background = this.nodes.getBackgroundNode( scene ) || scene.background;
  36766. let forceClear = false;
  36767. if ( background === null ) {
  36768. // no background settings, use clear color configuration from the renderer
  36769. renderer._clearColor.getRGB( _clearColor, LinearSRGBColorSpace );
  36770. _clearColor.a = renderer._clearColor.a;
  36771. } else if ( background.isColor === true ) {
  36772. // background is an opaque color
  36773. background.getRGB( _clearColor, LinearSRGBColorSpace );
  36774. _clearColor.a = 1;
  36775. forceClear = true;
  36776. } else if ( background.isNode === true ) {
  36777. const sceneData = this.get( scene );
  36778. const backgroundNode = background;
  36779. _clearColor.copy( renderer._clearColor );
  36780. let backgroundMesh = sceneData.backgroundMesh;
  36781. if ( backgroundMesh === undefined ) {
  36782. const backgroundMeshNode = context( vec4( backgroundNode ).mul( backgroundIntensity ), {
  36783. // @TODO: Add Texture2D support using node context
  36784. getUV: () => normalWorld,
  36785. getTextureLevel: () => backgroundBlurriness
  36786. } );
  36787. let viewProj = modelViewProjection();
  36788. viewProj = viewProj.setZ( viewProj.w );
  36789. const nodeMaterial = new NodeMaterial();
  36790. nodeMaterial.name = 'Background.material';
  36791. nodeMaterial.side = BackSide;
  36792. nodeMaterial.depthTest = false;
  36793. nodeMaterial.depthWrite = false;
  36794. nodeMaterial.fog = false;
  36795. nodeMaterial.lights = false;
  36796. nodeMaterial.vertexNode = viewProj;
  36797. nodeMaterial.colorNode = backgroundMeshNode;
  36798. sceneData.backgroundMeshNode = backgroundMeshNode;
  36799. sceneData.backgroundMesh = backgroundMesh = new Mesh( new SphereGeometry( 1, 32, 32 ), nodeMaterial );
  36800. backgroundMesh.frustumCulled = false;
  36801. backgroundMesh.name = 'Background.mesh';
  36802. backgroundMesh.onBeforeRender = function ( renderer, scene, camera ) {
  36803. this.matrixWorld.copyPosition( camera.matrixWorld );
  36804. };
  36805. }
  36806. const backgroundCacheKey = backgroundNode.getCacheKey();
  36807. if ( sceneData.backgroundCacheKey !== backgroundCacheKey ) {
  36808. sceneData.backgroundMeshNode.node = vec4( backgroundNode ).mul( backgroundIntensity );
  36809. sceneData.backgroundMeshNode.needsUpdate = true;
  36810. backgroundMesh.material.needsUpdate = true;
  36811. sceneData.backgroundCacheKey = backgroundCacheKey;
  36812. }
  36813. renderList.unshift( backgroundMesh, backgroundMesh.geometry, backgroundMesh.material, 0, 0, null );
  36814. } else {
  36815. console.error( 'THREE.Renderer: Unsupported background configuration.', background );
  36816. }
  36817. //
  36818. if ( renderer.autoClear === true || forceClear === true ) {
  36819. const clearColorValue = renderContext.clearColorValue;
  36820. clearColorValue.r = _clearColor.r;
  36821. clearColorValue.g = _clearColor.g;
  36822. clearColorValue.b = _clearColor.b;
  36823. clearColorValue.a = _clearColor.a;
  36824. // premultiply alpha
  36825. if ( renderer.backend.isWebGLBackend === true || renderer.alpha === true ) {
  36826. clearColorValue.r *= clearColorValue.a;
  36827. clearColorValue.g *= clearColorValue.a;
  36828. clearColorValue.b *= clearColorValue.a;
  36829. }
  36830. //
  36831. renderContext.depthClearValue = renderer._clearDepth;
  36832. renderContext.stencilClearValue = renderer._clearStencil;
  36833. renderContext.clearColor = renderer.autoClearColor === true;
  36834. renderContext.clearDepth = renderer.autoClearDepth === true;
  36835. renderContext.clearStencil = renderer.autoClearStencil === true;
  36836. } else {
  36837. renderContext.clearColor = false;
  36838. renderContext.clearDepth = false;
  36839. renderContext.clearStencil = false;
  36840. }
  36841. }
  36842. }
  36843. class NodeBuilderState {
  36844. constructor( vertexShader, fragmentShader, computeShader, nodeAttributes, bindings, updateNodes, updateBeforeNodes, updateAfterNodes, monitor, transforms = [] ) {
  36845. this.vertexShader = vertexShader;
  36846. this.fragmentShader = fragmentShader;
  36847. this.computeShader = computeShader;
  36848. this.transforms = transforms;
  36849. this.nodeAttributes = nodeAttributes;
  36850. this.bindings = bindings;
  36851. this.updateNodes = updateNodes;
  36852. this.updateBeforeNodes = updateBeforeNodes;
  36853. this.updateAfterNodes = updateAfterNodes;
  36854. this.monitor = monitor;
  36855. this.usedTimes = 0;
  36856. }
  36857. createBindings() {
  36858. const bindings = [];
  36859. for ( const instanceGroup of this.bindings ) {
  36860. const shared = instanceGroup.bindings[ 0 ].groupNode.shared;
  36861. if ( shared !== true ) {
  36862. const bindingsGroup = new BindGroup( instanceGroup.name, [], instanceGroup.index, instanceGroup );
  36863. bindings.push( bindingsGroup );
  36864. for ( const instanceBinding of instanceGroup.bindings ) {
  36865. bindingsGroup.bindings.push( instanceBinding.clone() );
  36866. }
  36867. } else {
  36868. bindings.push( instanceGroup );
  36869. }
  36870. }
  36871. return bindings;
  36872. }
  36873. }
  36874. const outputNodeMap = new WeakMap();
  36875. class Nodes extends DataMap {
  36876. constructor( renderer, backend ) {
  36877. super();
  36878. this.renderer = renderer;
  36879. this.backend = backend;
  36880. this.nodeFrame = new NodeFrame();
  36881. this.nodeBuilderCache = new Map();
  36882. this.callHashCache = new ChainMap();
  36883. this.groupsData = new ChainMap();
  36884. }
  36885. updateGroup( nodeUniformsGroup ) {
  36886. const groupNode = nodeUniformsGroup.groupNode;
  36887. const name = groupNode.name;
  36888. // objectGroup is every updated
  36889. if ( name === objectGroup.name ) return true;
  36890. // renderGroup is updated once per render/compute call
  36891. if ( name === renderGroup.name ) {
  36892. const uniformsGroupData = this.get( nodeUniformsGroup );
  36893. const renderId = this.nodeFrame.renderId;
  36894. if ( uniformsGroupData.renderId !== renderId ) {
  36895. uniformsGroupData.renderId = renderId;
  36896. return true;
  36897. }
  36898. return false;
  36899. }
  36900. // frameGroup is updated once per frame
  36901. if ( name === frameGroup.name ) {
  36902. const uniformsGroupData = this.get( nodeUniformsGroup );
  36903. const frameId = this.nodeFrame.frameId;
  36904. if ( uniformsGroupData.frameId !== frameId ) {
  36905. uniformsGroupData.frameId = frameId;
  36906. return true;
  36907. }
  36908. return false;
  36909. }
  36910. // other groups are updated just when groupNode.needsUpdate is true
  36911. const groupChain = [ groupNode, nodeUniformsGroup ];
  36912. let groupData = this.groupsData.get( groupChain );
  36913. if ( groupData === undefined ) this.groupsData.set( groupChain, groupData = {} );
  36914. if ( groupData.version !== groupNode.version ) {
  36915. groupData.version = groupNode.version;
  36916. return true;
  36917. }
  36918. return false;
  36919. }
  36920. getForRenderCacheKey( renderObject ) {
  36921. return renderObject.initialCacheKey;
  36922. }
  36923. getForRender( renderObject ) {
  36924. const renderObjectData = this.get( renderObject );
  36925. let nodeBuilderState = renderObjectData.nodeBuilderState;
  36926. if ( nodeBuilderState === undefined ) {
  36927. const { nodeBuilderCache } = this;
  36928. const cacheKey = this.getForRenderCacheKey( renderObject );
  36929. nodeBuilderState = nodeBuilderCache.get( cacheKey );
  36930. if ( nodeBuilderState === undefined ) {
  36931. const nodeBuilder = this.backend.createNodeBuilder( renderObject.object, this.renderer );
  36932. nodeBuilder.scene = renderObject.scene;
  36933. nodeBuilder.material = renderObject.material;
  36934. nodeBuilder.camera = renderObject.camera;
  36935. nodeBuilder.context.material = renderObject.material;
  36936. nodeBuilder.lightsNode = renderObject.lightsNode;
  36937. nodeBuilder.environmentNode = this.getEnvironmentNode( renderObject.scene );
  36938. nodeBuilder.fogNode = this.getFogNode( renderObject.scene );
  36939. nodeBuilder.clippingContext = renderObject.clippingContext;
  36940. nodeBuilder.build();
  36941. nodeBuilderState = this._createNodeBuilderState( nodeBuilder );
  36942. nodeBuilderCache.set( cacheKey, nodeBuilderState );
  36943. }
  36944. nodeBuilderState.usedTimes ++;
  36945. renderObjectData.nodeBuilderState = nodeBuilderState;
  36946. }
  36947. return nodeBuilderState;
  36948. }
  36949. delete( object ) {
  36950. if ( object.isRenderObject ) {
  36951. const nodeBuilderState = this.get( object ).nodeBuilderState;
  36952. nodeBuilderState.usedTimes --;
  36953. if ( nodeBuilderState.usedTimes === 0 ) {
  36954. this.nodeBuilderCache.delete( this.getForRenderCacheKey( object ) );
  36955. }
  36956. }
  36957. return super.delete( object );
  36958. }
  36959. getForCompute( computeNode ) {
  36960. const computeData = this.get( computeNode );
  36961. let nodeBuilderState = computeData.nodeBuilderState;
  36962. if ( nodeBuilderState === undefined ) {
  36963. const nodeBuilder = this.backend.createNodeBuilder( computeNode, this.renderer );
  36964. nodeBuilder.build();
  36965. nodeBuilderState = this._createNodeBuilderState( nodeBuilder );
  36966. computeData.nodeBuilderState = nodeBuilderState;
  36967. }
  36968. return nodeBuilderState;
  36969. }
  36970. _createNodeBuilderState( nodeBuilder ) {
  36971. return new NodeBuilderState(
  36972. nodeBuilder.vertexShader,
  36973. nodeBuilder.fragmentShader,
  36974. nodeBuilder.computeShader,
  36975. nodeBuilder.getAttributesArray(),
  36976. nodeBuilder.getBindings(),
  36977. nodeBuilder.updateNodes,
  36978. nodeBuilder.updateBeforeNodes,
  36979. nodeBuilder.updateAfterNodes,
  36980. nodeBuilder.monitor,
  36981. nodeBuilder.transforms
  36982. );
  36983. }
  36984. getEnvironmentNode( scene ) {
  36985. return scene.environmentNode || this.get( scene ).environmentNode || null;
  36986. }
  36987. getBackgroundNode( scene ) {
  36988. return scene.backgroundNode || this.get( scene ).backgroundNode || null;
  36989. }
  36990. getFogNode( scene ) {
  36991. return scene.fogNode || this.get( scene ).fogNode || null;
  36992. }
  36993. getCacheKey( scene, lightsNode ) {
  36994. const chain = [ scene, lightsNode ];
  36995. const callId = this.renderer.info.calls;
  36996. let cacheKeyData = this.callHashCache.get( chain );
  36997. if ( cacheKeyData === undefined || cacheKeyData.callId !== callId ) {
  36998. const environmentNode = this.getEnvironmentNode( scene );
  36999. const fogNode = this.getFogNode( scene );
  37000. const values = [];
  37001. if ( lightsNode ) values.push( lightsNode.getCacheKey( true ) );
  37002. if ( environmentNode ) values.push( environmentNode.getCacheKey() );
  37003. if ( fogNode ) values.push( fogNode.getCacheKey() );
  37004. values.push( this.renderer.shadowMap.enabled ? 1 : 0 );
  37005. cacheKeyData = {
  37006. callId,
  37007. cacheKey: hashArray( values )
  37008. };
  37009. this.callHashCache.set( chain, cacheKeyData );
  37010. }
  37011. return cacheKeyData.cacheKey;
  37012. }
  37013. updateScene( scene ) {
  37014. this.updateEnvironment( scene );
  37015. this.updateFog( scene );
  37016. this.updateBackground( scene );
  37017. }
  37018. get isToneMappingState() {
  37019. return this.renderer.getRenderTarget() ? false : true;
  37020. }
  37021. updateBackground( scene ) {
  37022. const sceneData = this.get( scene );
  37023. const background = scene.background;
  37024. if ( background ) {
  37025. const forceUpdate = ( scene.backgroundBlurriness === 0 && sceneData.backgroundBlurriness > 0 ) || ( scene.backgroundBlurriness > 0 && sceneData.backgroundBlurriness === 0 );
  37026. if ( sceneData.background !== background || forceUpdate ) {
  37027. let backgroundNode = null;
  37028. if ( background.isCubeTexture === true || ( background.mapping === EquirectangularReflectionMapping || background.mapping === EquirectangularRefractionMapping || background.mapping === CubeUVReflectionMapping ) ) {
  37029. if ( scene.backgroundBlurriness > 0 || background.mapping === CubeUVReflectionMapping ) {
  37030. backgroundNode = pmremTexture( background, normalWorld );
  37031. } else {
  37032. let envMap;
  37033. if ( background.isCubeTexture === true ) {
  37034. envMap = cubeTexture( background );
  37035. } else {
  37036. envMap = texture( background );
  37037. }
  37038. backgroundNode = cubeMapNode( envMap );
  37039. }
  37040. } else if ( background.isTexture === true ) {
  37041. backgroundNode = texture( background, screenUV.flipY() ).setUpdateMatrix( true );
  37042. } else if ( background.isColor !== true ) {
  37043. console.error( 'WebGPUNodes: Unsupported background configuration.', background );
  37044. }
  37045. sceneData.backgroundNode = backgroundNode;
  37046. sceneData.background = background;
  37047. sceneData.backgroundBlurriness = scene.backgroundBlurriness;
  37048. }
  37049. } else if ( sceneData.backgroundNode ) {
  37050. delete sceneData.backgroundNode;
  37051. delete sceneData.background;
  37052. }
  37053. }
  37054. updateFog( scene ) {
  37055. const sceneData = this.get( scene );
  37056. const fog = scene.fog;
  37057. if ( fog ) {
  37058. if ( sceneData.fog !== fog ) {
  37059. let fogNode = null;
  37060. if ( fog.isFogExp2 ) {
  37061. const color = reference( 'color', 'color', fog ).setGroup( renderGroup );
  37062. const density = reference( 'density', 'float', fog ).setGroup( renderGroup );
  37063. fogNode = densityFog( color, density );
  37064. } else if ( fog.isFog ) {
  37065. const color = reference( 'color', 'color', fog ).setGroup( renderGroup );
  37066. const near = reference( 'near', 'float', fog ).setGroup( renderGroup );
  37067. const far = reference( 'far', 'float', fog ).setGroup( renderGroup );
  37068. fogNode = rangeFog( color, near, far );
  37069. } else {
  37070. console.error( 'WebGPUNodes: Unsupported fog configuration.', fog );
  37071. }
  37072. sceneData.fogNode = fogNode;
  37073. sceneData.fog = fog;
  37074. }
  37075. } else {
  37076. delete sceneData.fogNode;
  37077. delete sceneData.fog;
  37078. }
  37079. }
  37080. updateEnvironment( scene ) {
  37081. const sceneData = this.get( scene );
  37082. const environment = scene.environment;
  37083. if ( environment ) {
  37084. if ( sceneData.environment !== environment ) {
  37085. let environmentNode = null;
  37086. if ( environment.isCubeTexture === true ) {
  37087. environmentNode = cubeTexture( environment );
  37088. } else if ( environment.isTexture === true ) {
  37089. environmentNode = texture( environment );
  37090. } else {
  37091. console.error( 'Nodes: Unsupported environment configuration.', environment );
  37092. }
  37093. sceneData.environmentNode = environmentNode;
  37094. sceneData.environment = environment;
  37095. }
  37096. } else if ( sceneData.environmentNode ) {
  37097. delete sceneData.environmentNode;
  37098. delete sceneData.environment;
  37099. }
  37100. }
  37101. getNodeFrame( renderer = this.renderer, scene = null, object = null, camera = null, material = null ) {
  37102. const nodeFrame = this.nodeFrame;
  37103. nodeFrame.renderer = renderer;
  37104. nodeFrame.scene = scene;
  37105. nodeFrame.object = object;
  37106. nodeFrame.camera = camera;
  37107. nodeFrame.material = material;
  37108. return nodeFrame;
  37109. }
  37110. getNodeFrameForRender( renderObject ) {
  37111. return this.getNodeFrame( renderObject.renderer, renderObject.scene, renderObject.object, renderObject.camera, renderObject.material );
  37112. }
  37113. getOutputCacheKey() {
  37114. const renderer = this.renderer;
  37115. return renderer.toneMapping + ',' + renderer.currentColorSpace;
  37116. }
  37117. hasOutputChange( outputTarget ) {
  37118. const cacheKey = outputNodeMap.get( outputTarget );
  37119. return cacheKey !== this.getOutputCacheKey();
  37120. }
  37121. getOutputNode( outputTexture ) {
  37122. const renderer = this.renderer;
  37123. const cacheKey = this.getOutputCacheKey();
  37124. const output = texture( outputTexture, screenUV ).renderOutput( renderer.toneMapping, renderer.currentColorSpace );
  37125. outputNodeMap.set( outputTexture, cacheKey );
  37126. return output;
  37127. }
  37128. updateBefore( renderObject ) {
  37129. const nodeBuilder = renderObject.getNodeBuilderState();
  37130. for ( const node of nodeBuilder.updateBeforeNodes ) {
  37131. // update frame state for each node
  37132. this.getNodeFrameForRender( renderObject ).updateBeforeNode( node );
  37133. }
  37134. }
  37135. updateAfter( renderObject ) {
  37136. const nodeBuilder = renderObject.getNodeBuilderState();
  37137. for ( const node of nodeBuilder.updateAfterNodes ) {
  37138. // update frame state for each node
  37139. this.getNodeFrameForRender( renderObject ).updateAfterNode( node );
  37140. }
  37141. }
  37142. updateForCompute( computeNode ) {
  37143. const nodeFrame = this.getNodeFrame();
  37144. const nodeBuilder = this.getForCompute( computeNode );
  37145. for ( const node of nodeBuilder.updateNodes ) {
  37146. nodeFrame.updateNode( node );
  37147. }
  37148. }
  37149. updateForRender( renderObject ) {
  37150. const nodeFrame = this.getNodeFrameForRender( renderObject );
  37151. const nodeBuilder = renderObject.getNodeBuilderState();
  37152. for ( const node of nodeBuilder.updateNodes ) {
  37153. nodeFrame.updateNode( node );
  37154. }
  37155. }
  37156. needsRefresh( renderObject ) {
  37157. const nodeFrame = this.getNodeFrameForRender( renderObject );
  37158. const monitor = renderObject.getMonitor();
  37159. return monitor.needsRefresh( renderObject, nodeFrame );
  37160. }
  37161. dispose() {
  37162. super.dispose();
  37163. this.nodeFrame = new NodeFrame();
  37164. this.nodeBuilderCache = new Map();
  37165. }
  37166. }
  37167. class RenderBundle {
  37168. constructor( scene, camera ) {
  37169. this.scene = scene;
  37170. this.camera = camera;
  37171. }
  37172. clone() {
  37173. return Object.assign( new this.constructor(), this );
  37174. }
  37175. }
  37176. class RenderBundles {
  37177. constructor() {
  37178. this.lists = new ChainMap();
  37179. }
  37180. get( scene, camera ) {
  37181. const lists = this.lists;
  37182. const keys = [ scene, camera ];
  37183. let list = lists.get( keys );
  37184. if ( list === undefined ) {
  37185. list = new RenderBundle( scene, camera );
  37186. lists.set( keys, list );
  37187. }
  37188. return list;
  37189. }
  37190. dispose() {
  37191. this.lists = new ChainMap();
  37192. }
  37193. }
  37194. class NodeLibrary {
  37195. constructor() {
  37196. this.lightNodes = new WeakMap();
  37197. this.materialNodes = new Map();
  37198. this.toneMappingNodes = new Map();
  37199. this.colorSpaceNodes = new Map();
  37200. }
  37201. fromMaterial( material ) {
  37202. if ( material.isNodeMaterial ) return material;
  37203. let nodeMaterial = null;
  37204. const nodeMaterialClass = this.getMaterialNodeClass( material.type );
  37205. if ( nodeMaterialClass !== null ) {
  37206. nodeMaterial = new nodeMaterialClass();
  37207. for ( const key in material ) {
  37208. nodeMaterial[ key ] = material[ key ];
  37209. }
  37210. }
  37211. return nodeMaterial;
  37212. }
  37213. addColorSpace( colorSpaceNode, colorSpace ) {
  37214. this.addType( colorSpaceNode, colorSpace, this.colorSpaceNodes );
  37215. }
  37216. getColorSpaceFunction( colorSpace ) {
  37217. return this.colorSpaceNodes.get( colorSpace ) || null;
  37218. }
  37219. addToneMapping( toneMappingNode, toneMapping ) {
  37220. this.addType( toneMappingNode, toneMapping, this.toneMappingNodes );
  37221. }
  37222. getToneMappingFunction( toneMapping ) {
  37223. return this.toneMappingNodes.get( toneMapping ) || null;
  37224. }
  37225. getMaterialNodeClass( materialType ) {
  37226. return this.materialNodes.get( materialType ) || null;
  37227. }
  37228. addMaterial( materialNodeClass, materialClass ) {
  37229. this.addType( materialNodeClass, materialClass.type, this.materialNodes );
  37230. }
  37231. getLightNodeClass( light ) {
  37232. return this.lightNodes.get( light ) || null;
  37233. }
  37234. addLight( lightNodeClass, lightClass ) {
  37235. this.addClass( lightNodeClass, lightClass, this.lightNodes );
  37236. }
  37237. addType( nodeClass, type, library ) {
  37238. if ( library.has( type ) ) {
  37239. console.warn( `Redefinition of node ${ type }` );
  37240. return;
  37241. }
  37242. if ( typeof nodeClass !== 'function' ) throw new Error( `Node class ${ nodeClass.name } is not a class.` );
  37243. if ( typeof type === 'function' || typeof type === 'object' ) throw new Error( `Base class ${ type } is not a class.` );
  37244. library.set( type, nodeClass );
  37245. }
  37246. addClass( nodeClass, baseClass, library ) {
  37247. if ( library.has( baseClass ) ) {
  37248. console.warn( `Redefinition of node ${ baseClass.name }` );
  37249. return;
  37250. }
  37251. if ( typeof nodeClass !== 'function' ) throw new Error( `Node class ${ nodeClass.name } is not a class.` );
  37252. if ( typeof baseClass !== 'function' ) throw new Error( `Base class ${ baseClass.name } is not a class.` );
  37253. library.set( baseClass, nodeClass );
  37254. }
  37255. }
  37256. const _scene = /*@__PURE__*/ new Scene();
  37257. const _drawingBufferSize = /*@__PURE__*/ new Vector2();
  37258. const _screen = /*@__PURE__*/ new Vector4();
  37259. const _frustum = /*@__PURE__*/ new Frustum();
  37260. const _projScreenMatrix = /*@__PURE__*/ new Matrix4();
  37261. const _vector4 = /*@__PURE__*/ new Vector4();
  37262. class Renderer {
  37263. constructor( backend, parameters = {} ) {
  37264. this.isRenderer = true;
  37265. //
  37266. const {
  37267. logarithmicDepthBuffer = false,
  37268. alpha = true,
  37269. depth = true,
  37270. stencil = false,
  37271. antialias = false,
  37272. samples = 0,
  37273. getFallback = null
  37274. } = parameters;
  37275. // public
  37276. this.domElement = backend.getDomElement();
  37277. this.backend = backend;
  37278. this.samples = samples || ( antialias === true ) ? 4 : 0;
  37279. this.autoClear = true;
  37280. this.autoClearColor = true;
  37281. this.autoClearDepth = true;
  37282. this.autoClearStencil = true;
  37283. this.alpha = alpha;
  37284. this.logarithmicDepthBuffer = logarithmicDepthBuffer;
  37285. this.outputColorSpace = SRGBColorSpace;
  37286. this.toneMapping = NoToneMapping;
  37287. this.toneMappingExposure = 1.0;
  37288. this.sortObjects = true;
  37289. this.depth = depth;
  37290. this.stencil = stencil;
  37291. this.clippingPlanes = [];
  37292. this.info = new Info();
  37293. this.nodes = {
  37294. library: new NodeLibrary(),
  37295. modelViewMatrix: null,
  37296. modelNormalViewMatrix: null
  37297. };
  37298. // internals
  37299. this._getFallback = getFallback;
  37300. this._pixelRatio = 1;
  37301. this._width = this.domElement.width;
  37302. this._height = this.domElement.height;
  37303. this._viewport = new Vector4( 0, 0, this._width, this._height );
  37304. this._scissor = new Vector4( 0, 0, this._width, this._height );
  37305. this._scissorTest = false;
  37306. this._attributes = null;
  37307. this._geometries = null;
  37308. this._nodes = null;
  37309. this._animation = null;
  37310. this._bindings = null;
  37311. this._objects = null;
  37312. this._pipelines = null;
  37313. this._bundles = null;
  37314. this._renderLists = null;
  37315. this._renderContexts = null;
  37316. this._textures = null;
  37317. this._background = null;
  37318. this._quad = new QuadMesh( new NodeMaterial() );
  37319. this._quad.material.type = 'Renderer_output';
  37320. this._currentRenderContext = null;
  37321. this._opaqueSort = null;
  37322. this._transparentSort = null;
  37323. this._frameBufferTarget = null;
  37324. const alphaClear = this.alpha === true ? 0 : 1;
  37325. this._clearColor = new Color4( 0, 0, 0, alphaClear );
  37326. this._clearDepth = 1;
  37327. this._clearStencil = 0;
  37328. this._renderTarget = null;
  37329. this._activeCubeFace = 0;
  37330. this._activeMipmapLevel = 0;
  37331. this._mrt = null;
  37332. this._renderObjectFunction = null;
  37333. this._currentRenderObjectFunction = null;
  37334. this._currentRenderBundle = null;
  37335. this._handleObjectFunction = this._renderObjectDirect;
  37336. this._initialized = false;
  37337. this._initPromise = null;
  37338. this._compilationPromises = null;
  37339. this.transparent = true;
  37340. this.opaque = true;
  37341. this.shadowMap = {
  37342. enabled: false,
  37343. type: PCFShadowMap$1
  37344. };
  37345. this.xr = {
  37346. enabled: false
  37347. };
  37348. this.debug = {
  37349. checkShaderErrors: true,
  37350. onShaderError: null,
  37351. getShaderAsync: async ( scene, camera, object ) => {
  37352. await this.compileAsync( scene, camera );
  37353. const renderList = this._renderLists.get( scene, camera );
  37354. const renderContext = this._renderContexts.get( scene, camera, this._renderTarget );
  37355. const material = scene.overrideMaterial || object.material;
  37356. const renderObject = this._objects.get( object, material, scene, camera, renderList.lightsNode, renderContext );
  37357. const { fragmentShader, vertexShader } = renderObject.getNodeBuilderState();
  37358. return { fragmentShader, vertexShader };
  37359. }
  37360. };
  37361. }
  37362. async init() {
  37363. if ( this._initialized ) {
  37364. throw new Error( 'Renderer: Backend has already been initialized.' );
  37365. }
  37366. if ( this._initPromise !== null ) {
  37367. return this._initPromise;
  37368. }
  37369. this._initPromise = new Promise( async ( resolve, reject ) => {
  37370. let backend = this.backend;
  37371. try {
  37372. await backend.init( this );
  37373. } catch ( error ) {
  37374. if ( this._getFallback !== null ) {
  37375. // try the fallback
  37376. try {
  37377. this.backend = backend = this._getFallback( error );
  37378. await backend.init( this );
  37379. } catch ( error ) {
  37380. reject( error );
  37381. return;
  37382. }
  37383. } else {
  37384. reject( error );
  37385. return;
  37386. }
  37387. }
  37388. this._nodes = new Nodes( this, backend );
  37389. this._animation = new Animation( this._nodes, this.info );
  37390. this._attributes = new Attributes( backend );
  37391. this._background = new Background( this, this._nodes );
  37392. this._geometries = new Geometries( this._attributes, this.info );
  37393. this._textures = new Textures( this, backend, this.info );
  37394. this._pipelines = new Pipelines( backend, this._nodes );
  37395. this._bindings = new Bindings( backend, this._nodes, this._textures, this._attributes, this._pipelines, this.info );
  37396. this._objects = new RenderObjects( this, this._nodes, this._geometries, this._pipelines, this._bindings, this.info );
  37397. this._renderLists = new RenderLists();
  37398. this._bundles = new RenderBundles();
  37399. this._renderContexts = new RenderContexts();
  37400. //
  37401. this._initialized = true;
  37402. resolve();
  37403. } );
  37404. return this._initPromise;
  37405. }
  37406. get coordinateSystem() {
  37407. return this.backend.coordinateSystem;
  37408. }
  37409. async compileAsync( scene, camera, targetScene = null ) {
  37410. if ( this._initialized === false ) await this.init();
  37411. // preserve render tree
  37412. const nodeFrame = this._nodes.nodeFrame;
  37413. const previousRenderId = nodeFrame.renderId;
  37414. const previousRenderContext = this._currentRenderContext;
  37415. const previousRenderObjectFunction = this._currentRenderObjectFunction;
  37416. const previousCompilationPromises = this._compilationPromises;
  37417. //
  37418. const sceneRef = ( scene.isScene === true ) ? scene : _scene;
  37419. if ( targetScene === null ) targetScene = scene;
  37420. const renderTarget = this._renderTarget;
  37421. const renderContext = this._renderContexts.get( targetScene, camera, renderTarget );
  37422. const activeMipmapLevel = this._activeMipmapLevel;
  37423. const compilationPromises = [];
  37424. this._currentRenderContext = renderContext;
  37425. this._currentRenderObjectFunction = this.renderObject;
  37426. this._handleObjectFunction = this._createObjectPipeline;
  37427. this._compilationPromises = compilationPromises;
  37428. nodeFrame.renderId ++;
  37429. //
  37430. nodeFrame.update();
  37431. //
  37432. renderContext.depth = this.depth;
  37433. renderContext.stencil = this.stencil;
  37434. if ( ! renderContext.clippingContext ) renderContext.clippingContext = new ClippingContext();
  37435. renderContext.clippingContext.updateGlobal( this, camera );
  37436. //
  37437. sceneRef.onBeforeRender( this, scene, camera, renderTarget );
  37438. //
  37439. const renderList = this._renderLists.get( scene, camera );
  37440. renderList.begin();
  37441. this._projectObject( scene, camera, 0, renderList );
  37442. // include lights from target scene
  37443. if ( targetScene !== scene ) {
  37444. targetScene.traverseVisible( function ( object ) {
  37445. if ( object.isLight && object.layers.test( camera.layers ) ) {
  37446. renderList.pushLight( object );
  37447. }
  37448. } );
  37449. }
  37450. renderList.finish();
  37451. //
  37452. if ( renderTarget !== null ) {
  37453. this._textures.updateRenderTarget( renderTarget, activeMipmapLevel );
  37454. const renderTargetData = this._textures.get( renderTarget );
  37455. renderContext.textures = renderTargetData.textures;
  37456. renderContext.depthTexture = renderTargetData.depthTexture;
  37457. } else {
  37458. renderContext.textures = null;
  37459. renderContext.depthTexture = null;
  37460. }
  37461. //
  37462. this._nodes.updateScene( sceneRef );
  37463. //
  37464. this._background.update( sceneRef, renderList, renderContext );
  37465. // process render lists
  37466. const opaqueObjects = renderList.opaque;
  37467. const transparentObjects = renderList.transparent;
  37468. const lightsNode = renderList.lightsNode;
  37469. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  37470. if ( this.transparent === true && transparentObjects.length > 0 ) this._renderObjects( transparentObjects, camera, sceneRef, lightsNode );
  37471. // restore render tree
  37472. nodeFrame.renderId = previousRenderId;
  37473. this._currentRenderContext = previousRenderContext;
  37474. this._currentRenderObjectFunction = previousRenderObjectFunction;
  37475. this._compilationPromises = previousCompilationPromises;
  37476. this._handleObjectFunction = this._renderObjectDirect;
  37477. // wait for all promises setup by backends awaiting compilation/linking/pipeline creation to complete
  37478. await Promise.all( compilationPromises );
  37479. }
  37480. async renderAsync( scene, camera ) {
  37481. if ( this._initialized === false ) await this.init();
  37482. const renderContext = this._renderScene( scene, camera );
  37483. await this.backend.resolveTimestampAsync( renderContext, 'render' );
  37484. }
  37485. setMRT( mrt ) {
  37486. this._mrt = mrt;
  37487. return this;
  37488. }
  37489. getMRT() {
  37490. return this._mrt;
  37491. }
  37492. _renderBundle( bundle, sceneRef, lightsNode ) {
  37493. const { bundleGroup, camera, renderList } = bundle;
  37494. const renderContext = this._currentRenderContext;
  37495. //
  37496. const renderBundle = this._bundles.get( bundleGroup, camera );
  37497. const renderBundleData = this.backend.get( renderBundle );
  37498. if ( renderBundleData.renderContexts === undefined ) renderBundleData.renderContexts = new Set();
  37499. //
  37500. const needsUpdate = bundleGroup.version !== renderBundleData.version;
  37501. const renderBundleNeedsUpdate = renderBundleData.renderContexts.has( renderContext ) === false || needsUpdate;
  37502. renderBundleData.renderContexts.add( renderContext );
  37503. if ( renderBundleNeedsUpdate ) {
  37504. this.backend.beginBundle( renderContext );
  37505. if ( renderBundleData.renderObjects === undefined || needsUpdate ) {
  37506. renderBundleData.renderObjects = [];
  37507. }
  37508. this._currentRenderBundle = renderBundle;
  37509. const opaqueObjects = renderList.opaque;
  37510. if ( opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  37511. this._currentRenderBundle = null;
  37512. //
  37513. this.backend.finishBundle( renderContext, renderBundle );
  37514. renderBundleData.version = bundleGroup.version;
  37515. } else {
  37516. const { renderObjects } = renderBundleData;
  37517. for ( let i = 0, l = renderObjects.length; i < l; i ++ ) {
  37518. const renderObject = renderObjects[ i ];
  37519. if ( this._nodes.needsRefresh( renderObject ) ) {
  37520. this._nodes.updateBefore( renderObject );
  37521. this._nodes.updateForRender( renderObject );
  37522. this._bindings.updateForRender( renderObject );
  37523. this._nodes.updateAfter( renderObject );
  37524. }
  37525. }
  37526. }
  37527. this.backend.addBundle( renderContext, renderBundle );
  37528. }
  37529. render( scene, camera ) {
  37530. if ( this._initialized === false ) {
  37531. console.warn( 'THREE.Renderer: .render() called before the backend is initialized. Try using .renderAsync() instead.' );
  37532. return this.renderAsync( scene, camera );
  37533. }
  37534. this._renderScene( scene, camera );
  37535. }
  37536. _getFrameBufferTarget() {
  37537. const { currentToneMapping, currentColorSpace } = this;
  37538. const useToneMapping = currentToneMapping !== NoToneMapping;
  37539. const useColorSpace = currentColorSpace !== LinearSRGBColorSpace;
  37540. if ( useToneMapping === false && useColorSpace === false ) return null;
  37541. const { width, height } = this.getDrawingBufferSize( _drawingBufferSize );
  37542. const { depth, stencil } = this;
  37543. let frameBufferTarget = this._frameBufferTarget;
  37544. if ( frameBufferTarget === null ) {
  37545. frameBufferTarget = new RenderTarget( width, height, {
  37546. depthBuffer: depth,
  37547. stencilBuffer: stencil,
  37548. type: HalfFloatType, // FloatType
  37549. format: RGBAFormat,
  37550. colorSpace: LinearSRGBColorSpace,
  37551. generateMipmaps: false,
  37552. minFilter: LinearFilter,
  37553. magFilter: LinearFilter,
  37554. samples: this.samples
  37555. } );
  37556. frameBufferTarget.isPostProcessingRenderTarget = true;
  37557. this._frameBufferTarget = frameBufferTarget;
  37558. }
  37559. frameBufferTarget.depthBuffer = depth;
  37560. frameBufferTarget.stencilBuffer = stencil;
  37561. frameBufferTarget.setSize( width, height );
  37562. frameBufferTarget.viewport.copy( this._viewport );
  37563. frameBufferTarget.scissor.copy( this._scissor );
  37564. frameBufferTarget.viewport.multiplyScalar( this._pixelRatio );
  37565. frameBufferTarget.scissor.multiplyScalar( this._pixelRatio );
  37566. frameBufferTarget.scissorTest = this._scissorTest;
  37567. return frameBufferTarget;
  37568. }
  37569. _renderScene( scene, camera, useFrameBufferTarget = true ) {
  37570. const frameBufferTarget = useFrameBufferTarget ? this._getFrameBufferTarget() : null;
  37571. // preserve render tree
  37572. const nodeFrame = this._nodes.nodeFrame;
  37573. const previousRenderId = nodeFrame.renderId;
  37574. const previousRenderContext = this._currentRenderContext;
  37575. const previousRenderObjectFunction = this._currentRenderObjectFunction;
  37576. //
  37577. const sceneRef = ( scene.isScene === true ) ? scene : _scene;
  37578. const outputRenderTarget = this._renderTarget;
  37579. const activeCubeFace = this._activeCubeFace;
  37580. const activeMipmapLevel = this._activeMipmapLevel;
  37581. //
  37582. let renderTarget;
  37583. if ( frameBufferTarget !== null ) {
  37584. renderTarget = frameBufferTarget;
  37585. this.setRenderTarget( renderTarget );
  37586. } else {
  37587. renderTarget = outputRenderTarget;
  37588. }
  37589. //
  37590. const renderContext = this._renderContexts.get( scene, camera, renderTarget );
  37591. this._currentRenderContext = renderContext;
  37592. this._currentRenderObjectFunction = this._renderObjectFunction || this.renderObject;
  37593. //
  37594. this.info.calls ++;
  37595. this.info.render.calls ++;
  37596. this.info.render.frameCalls ++;
  37597. nodeFrame.renderId = this.info.calls;
  37598. //
  37599. const coordinateSystem = this.coordinateSystem;
  37600. if ( camera.coordinateSystem !== coordinateSystem ) {
  37601. camera.coordinateSystem = coordinateSystem;
  37602. camera.updateProjectionMatrix();
  37603. }
  37604. //
  37605. if ( scene.matrixWorldAutoUpdate === true ) scene.updateMatrixWorld();
  37606. if ( camera.parent === null && camera.matrixWorldAutoUpdate === true ) camera.updateMatrixWorld();
  37607. //
  37608. let viewport = this._viewport;
  37609. let scissor = this._scissor;
  37610. let pixelRatio = this._pixelRatio;
  37611. if ( renderTarget !== null ) {
  37612. viewport = renderTarget.viewport;
  37613. scissor = renderTarget.scissor;
  37614. pixelRatio = 1;
  37615. }
  37616. this.getDrawingBufferSize( _drawingBufferSize );
  37617. _screen.set( 0, 0, _drawingBufferSize.width, _drawingBufferSize.height );
  37618. const minDepth = ( viewport.minDepth === undefined ) ? 0 : viewport.minDepth;
  37619. const maxDepth = ( viewport.maxDepth === undefined ) ? 1 : viewport.maxDepth;
  37620. renderContext.viewportValue.copy( viewport ).multiplyScalar( pixelRatio ).floor();
  37621. renderContext.viewportValue.width >>= activeMipmapLevel;
  37622. renderContext.viewportValue.height >>= activeMipmapLevel;
  37623. renderContext.viewportValue.minDepth = minDepth;
  37624. renderContext.viewportValue.maxDepth = maxDepth;
  37625. renderContext.viewport = renderContext.viewportValue.equals( _screen ) === false;
  37626. renderContext.scissorValue.copy( scissor ).multiplyScalar( pixelRatio ).floor();
  37627. renderContext.scissor = this._scissorTest && renderContext.scissorValue.equals( _screen ) === false;
  37628. renderContext.scissorValue.width >>= activeMipmapLevel;
  37629. renderContext.scissorValue.height >>= activeMipmapLevel;
  37630. if ( ! renderContext.clippingContext ) renderContext.clippingContext = new ClippingContext();
  37631. renderContext.clippingContext.updateGlobal( this, camera );
  37632. //
  37633. sceneRef.onBeforeRender( this, scene, camera, renderTarget );
  37634. //
  37635. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  37636. _frustum.setFromProjectionMatrix( _projScreenMatrix, coordinateSystem );
  37637. const renderList = this._renderLists.get( scene, camera );
  37638. renderList.begin();
  37639. this._projectObject( scene, camera, 0, renderList );
  37640. renderList.finish();
  37641. if ( this.sortObjects === true ) {
  37642. renderList.sort( this._opaqueSort, this._transparentSort );
  37643. }
  37644. //
  37645. if ( renderTarget !== null ) {
  37646. this._textures.updateRenderTarget( renderTarget, activeMipmapLevel );
  37647. const renderTargetData = this._textures.get( renderTarget );
  37648. renderContext.textures = renderTargetData.textures;
  37649. renderContext.depthTexture = renderTargetData.depthTexture;
  37650. renderContext.width = renderTargetData.width;
  37651. renderContext.height = renderTargetData.height;
  37652. renderContext.renderTarget = renderTarget;
  37653. renderContext.depth = renderTarget.depthBuffer;
  37654. renderContext.stencil = renderTarget.stencilBuffer;
  37655. } else {
  37656. renderContext.textures = null;
  37657. renderContext.depthTexture = null;
  37658. renderContext.width = this.domElement.width;
  37659. renderContext.height = this.domElement.height;
  37660. renderContext.depth = this.depth;
  37661. renderContext.stencil = this.stencil;
  37662. }
  37663. renderContext.width >>= activeMipmapLevel;
  37664. renderContext.height >>= activeMipmapLevel;
  37665. renderContext.activeCubeFace = activeCubeFace;
  37666. renderContext.activeMipmapLevel = activeMipmapLevel;
  37667. renderContext.occlusionQueryCount = renderList.occlusionQueryCount;
  37668. //
  37669. this._nodes.updateScene( sceneRef );
  37670. //
  37671. this._background.update( sceneRef, renderList, renderContext );
  37672. //
  37673. this.backend.beginRender( renderContext );
  37674. // process render lists
  37675. const {
  37676. bundles,
  37677. lightsNode,
  37678. transparent: transparentObjects,
  37679. opaque: opaqueObjects
  37680. } = renderList;
  37681. if ( bundles.length > 0 ) this._renderBundles( bundles, sceneRef, lightsNode );
  37682. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  37683. if ( this.transparent === true && transparentObjects.length > 0 ) this._renderObjects( transparentObjects, camera, sceneRef, lightsNode );
  37684. // finish render pass
  37685. this.backend.finishRender( renderContext );
  37686. // restore render tree
  37687. nodeFrame.renderId = previousRenderId;
  37688. this._currentRenderContext = previousRenderContext;
  37689. this._currentRenderObjectFunction = previousRenderObjectFunction;
  37690. //
  37691. if ( frameBufferTarget !== null ) {
  37692. this.setRenderTarget( outputRenderTarget, activeCubeFace, activeMipmapLevel );
  37693. const quad = this._quad;
  37694. if ( this._nodes.hasOutputChange( renderTarget.texture ) ) {
  37695. quad.material.fragmentNode = this._nodes.getOutputNode( renderTarget.texture );
  37696. quad.material.needsUpdate = true;
  37697. }
  37698. this._renderScene( quad, quad.camera, false );
  37699. }
  37700. //
  37701. sceneRef.onAfterRender( this, scene, camera, renderTarget );
  37702. //
  37703. return renderContext;
  37704. }
  37705. getMaxAnisotropy() {
  37706. return this.backend.getMaxAnisotropy();
  37707. }
  37708. getActiveCubeFace() {
  37709. return this._activeCubeFace;
  37710. }
  37711. getActiveMipmapLevel() {
  37712. return this._activeMipmapLevel;
  37713. }
  37714. async setAnimationLoop( callback ) {
  37715. if ( this._initialized === false ) await this.init();
  37716. this._animation.setAnimationLoop( callback );
  37717. }
  37718. async getArrayBufferAsync( attribute ) {
  37719. return await this.backend.getArrayBufferAsync( attribute );
  37720. }
  37721. getContext() {
  37722. return this.backend.getContext();
  37723. }
  37724. getPixelRatio() {
  37725. return this._pixelRatio;
  37726. }
  37727. getDrawingBufferSize( target ) {
  37728. return target.set( this._width * this._pixelRatio, this._height * this._pixelRatio ).floor();
  37729. }
  37730. getSize( target ) {
  37731. return target.set( this._width, this._height );
  37732. }
  37733. setPixelRatio( value = 1 ) {
  37734. if ( this._pixelRatio === value ) return;
  37735. this._pixelRatio = value;
  37736. this.setSize( this._width, this._height, false );
  37737. }
  37738. setDrawingBufferSize( width, height, pixelRatio ) {
  37739. this._width = width;
  37740. this._height = height;
  37741. this._pixelRatio = pixelRatio;
  37742. this.domElement.width = Math.floor( width * pixelRatio );
  37743. this.domElement.height = Math.floor( height * pixelRatio );
  37744. this.setViewport( 0, 0, width, height );
  37745. if ( this._initialized ) this.backend.updateSize();
  37746. }
  37747. setSize( width, height, updateStyle = true ) {
  37748. this._width = width;
  37749. this._height = height;
  37750. this.domElement.width = Math.floor( width * this._pixelRatio );
  37751. this.domElement.height = Math.floor( height * this._pixelRatio );
  37752. if ( updateStyle === true ) {
  37753. this.domElement.style.width = width + 'px';
  37754. this.domElement.style.height = height + 'px';
  37755. }
  37756. this.setViewport( 0, 0, width, height );
  37757. if ( this._initialized ) this.backend.updateSize();
  37758. }
  37759. setOpaqueSort( method ) {
  37760. this._opaqueSort = method;
  37761. }
  37762. setTransparentSort( method ) {
  37763. this._transparentSort = method;
  37764. }
  37765. getScissor( target ) {
  37766. const scissor = this._scissor;
  37767. target.x = scissor.x;
  37768. target.y = scissor.y;
  37769. target.width = scissor.width;
  37770. target.height = scissor.height;
  37771. return target;
  37772. }
  37773. setScissor( x, y, width, height ) {
  37774. const scissor = this._scissor;
  37775. if ( x.isVector4 ) {
  37776. scissor.copy( x );
  37777. } else {
  37778. scissor.set( x, y, width, height );
  37779. }
  37780. }
  37781. getScissorTest() {
  37782. return this._scissorTest;
  37783. }
  37784. setScissorTest( boolean ) {
  37785. this._scissorTest = boolean;
  37786. this.backend.setScissorTest( boolean );
  37787. }
  37788. getViewport( target ) {
  37789. return target.copy( this._viewport );
  37790. }
  37791. setViewport( x, y, width, height, minDepth = 0, maxDepth = 1 ) {
  37792. const viewport = this._viewport;
  37793. if ( x.isVector4 ) {
  37794. viewport.copy( x );
  37795. } else {
  37796. viewport.set( x, y, width, height );
  37797. }
  37798. viewport.minDepth = minDepth;
  37799. viewport.maxDepth = maxDepth;
  37800. }
  37801. getClearColor( target ) {
  37802. return target.copy( this._clearColor );
  37803. }
  37804. setClearColor( color, alpha = 1 ) {
  37805. this._clearColor.set( color );
  37806. this._clearColor.a = alpha;
  37807. }
  37808. getClearAlpha() {
  37809. return this._clearColor.a;
  37810. }
  37811. setClearAlpha( alpha ) {
  37812. this._clearColor.a = alpha;
  37813. }
  37814. getClearDepth() {
  37815. return this._clearDepth;
  37816. }
  37817. setClearDepth( depth ) {
  37818. this._clearDepth = depth;
  37819. }
  37820. getClearStencil() {
  37821. return this._clearStencil;
  37822. }
  37823. setClearStencil( stencil ) {
  37824. this._clearStencil = stencil;
  37825. }
  37826. isOccluded( object ) {
  37827. const renderContext = this._currentRenderContext;
  37828. return renderContext && this.backend.isOccluded( renderContext, object );
  37829. }
  37830. clear( color = true, depth = true, stencil = true ) {
  37831. if ( this._initialized === false ) {
  37832. console.warn( 'THREE.Renderer: .clear() called before the backend is initialized. Try using .clearAsync() instead.' );
  37833. return this.clearAsync( color, depth, stencil );
  37834. }
  37835. const renderTarget = this._renderTarget || this._getFrameBufferTarget();
  37836. let renderTargetData = null;
  37837. if ( renderTarget !== null ) {
  37838. this._textures.updateRenderTarget( renderTarget );
  37839. renderTargetData = this._textures.get( renderTarget );
  37840. }
  37841. this.backend.clear( color, depth, stencil, renderTargetData );
  37842. if ( renderTarget !== null && this._renderTarget === null ) {
  37843. // If a color space transform or tone mapping is required,
  37844. // the clear operation clears the intermediate renderTarget texture, but does not update the screen canvas.
  37845. const quad = this._quad;
  37846. if ( this._nodes.hasOutputChange( renderTarget.texture ) ) {
  37847. quad.material.fragmentNode = this._nodes.getOutputNode( renderTarget.texture );
  37848. quad.material.needsUpdate = true;
  37849. }
  37850. this._renderScene( quad, quad.camera, false );
  37851. }
  37852. }
  37853. clearColor() {
  37854. return this.clear( true, false, false );
  37855. }
  37856. clearDepth() {
  37857. return this.clear( false, true, false );
  37858. }
  37859. clearStencil() {
  37860. return this.clear( false, false, true );
  37861. }
  37862. async clearAsync( color = true, depth = true, stencil = true ) {
  37863. if ( this._initialized === false ) await this.init();
  37864. this.clear( color, depth, stencil );
  37865. }
  37866. clearColorAsync() {
  37867. return this.clearAsync( true, false, false );
  37868. }
  37869. clearDepthAsync() {
  37870. return this.clearAsync( false, true, false );
  37871. }
  37872. clearStencilAsync() {
  37873. return this.clearAsync( false, false, true );
  37874. }
  37875. get currentToneMapping() {
  37876. return this._renderTarget !== null ? NoToneMapping : this.toneMapping;
  37877. }
  37878. get currentColorSpace() {
  37879. return this._renderTarget !== null ? LinearSRGBColorSpace : this.outputColorSpace;
  37880. }
  37881. dispose() {
  37882. this.info.dispose();
  37883. this._animation.dispose();
  37884. this._objects.dispose();
  37885. this._pipelines.dispose();
  37886. this._nodes.dispose();
  37887. this._bindings.dispose();
  37888. this._renderLists.dispose();
  37889. this._renderContexts.dispose();
  37890. this._textures.dispose();
  37891. this.setRenderTarget( null );
  37892. this.setAnimationLoop( null );
  37893. }
  37894. setRenderTarget( renderTarget, activeCubeFace = 0, activeMipmapLevel = 0 ) {
  37895. this._renderTarget = renderTarget;
  37896. this._activeCubeFace = activeCubeFace;
  37897. this._activeMipmapLevel = activeMipmapLevel;
  37898. }
  37899. getRenderTarget() {
  37900. return this._renderTarget;
  37901. }
  37902. setRenderObjectFunction( renderObjectFunction ) {
  37903. this._renderObjectFunction = renderObjectFunction;
  37904. }
  37905. getRenderObjectFunction() {
  37906. return this._renderObjectFunction;
  37907. }
  37908. compute( computeNodes ) {
  37909. if ( this._initialized === false ) {
  37910. console.warn( 'THREE.Renderer: .compute() called before the backend is initialized. Try using .computeAsync() instead.' );
  37911. return this.computeAsync( computeNodes );
  37912. }
  37913. //
  37914. const nodeFrame = this._nodes.nodeFrame;
  37915. const previousRenderId = nodeFrame.renderId;
  37916. //
  37917. this.info.calls ++;
  37918. this.info.compute.calls ++;
  37919. this.info.compute.frameCalls ++;
  37920. nodeFrame.renderId = this.info.calls;
  37921. //
  37922. const backend = this.backend;
  37923. const pipelines = this._pipelines;
  37924. const bindings = this._bindings;
  37925. const nodes = this._nodes;
  37926. const computeList = Array.isArray( computeNodes ) ? computeNodes : [ computeNodes ];
  37927. if ( computeList[ 0 ] === undefined || computeList[ 0 ].isComputeNode !== true ) {
  37928. throw new Error( 'THREE.Renderer: .compute() expects a ComputeNode.' );
  37929. }
  37930. backend.beginCompute( computeNodes );
  37931. for ( const computeNode of computeList ) {
  37932. // onInit
  37933. if ( pipelines.has( computeNode ) === false ) {
  37934. const dispose = () => {
  37935. computeNode.removeEventListener( 'dispose', dispose );
  37936. pipelines.delete( computeNode );
  37937. bindings.delete( computeNode );
  37938. nodes.delete( computeNode );
  37939. };
  37940. computeNode.addEventListener( 'dispose', dispose );
  37941. //
  37942. const onInitFn = computeNode.onInitFunction;
  37943. if ( onInitFn !== null ) {
  37944. onInitFn.call( computeNode, { renderer: this } );
  37945. }
  37946. }
  37947. nodes.updateForCompute( computeNode );
  37948. bindings.updateForCompute( computeNode );
  37949. const computeBindings = bindings.getForCompute( computeNode );
  37950. const computePipeline = pipelines.getForCompute( computeNode, computeBindings );
  37951. backend.compute( computeNodes, computeNode, computeBindings, computePipeline );
  37952. }
  37953. backend.finishCompute( computeNodes );
  37954. //
  37955. nodeFrame.renderId = previousRenderId;
  37956. }
  37957. async computeAsync( computeNodes ) {
  37958. if ( this._initialized === false ) await this.init();
  37959. this.compute( computeNodes );
  37960. await this.backend.resolveTimestampAsync( computeNodes, 'compute' );
  37961. }
  37962. async hasFeatureAsync( name ) {
  37963. if ( this._initialized === false ) await this.init();
  37964. return this.backend.hasFeature( name );
  37965. }
  37966. hasFeature( name ) {
  37967. if ( this._initialized === false ) {
  37968. console.warn( 'THREE.Renderer: .hasFeature() called before the backend is initialized. Try using .hasFeatureAsync() instead.' );
  37969. return false;
  37970. }
  37971. return this.backend.hasFeature( name );
  37972. }
  37973. copyFramebufferToTexture( framebufferTexture, rectangle = null ) {
  37974. const renderContext = this._currentRenderContext;
  37975. this._textures.updateTexture( framebufferTexture );
  37976. rectangle = rectangle === null ? _vector4.set( 0, 0, framebufferTexture.image.width, framebufferTexture.image.height ) : rectangle;
  37977. this.backend.copyFramebufferToTexture( framebufferTexture, renderContext, rectangle );
  37978. }
  37979. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, level = 0 ) {
  37980. this._textures.updateTexture( srcTexture );
  37981. this._textures.updateTexture( dstTexture );
  37982. this.backend.copyTextureToTexture( srcTexture, dstTexture, srcRegion, dstPosition, level );
  37983. }
  37984. readRenderTargetPixelsAsync( renderTarget, x, y, width, height, index = 0, faceIndex = 0 ) {
  37985. return this.backend.copyTextureToBuffer( renderTarget.textures[ index ], x, y, width, height, faceIndex );
  37986. }
  37987. _projectObject( object, camera, groupOrder, renderList ) {
  37988. if ( object.visible === false ) return;
  37989. const visible = object.layers.test( camera.layers );
  37990. if ( visible ) {
  37991. if ( object.isGroup ) {
  37992. groupOrder = object.renderOrder;
  37993. } else if ( object.isLOD ) {
  37994. if ( object.autoUpdate === true ) object.update( camera );
  37995. } else if ( object.isLight ) {
  37996. renderList.pushLight( object );
  37997. } else if ( object.isSprite ) {
  37998. if ( ! object.frustumCulled || _frustum.intersectsSprite( object ) ) {
  37999. if ( this.sortObjects === true ) {
  38000. _vector4.setFromMatrixPosition( object.matrixWorld ).applyMatrix4( _projScreenMatrix );
  38001. }
  38002. const { geometry, material } = object;
  38003. if ( material.visible ) {
  38004. renderList.push( object, geometry, material, groupOrder, _vector4.z, null );
  38005. }
  38006. }
  38007. } else if ( object.isLineLoop ) {
  38008. console.error( 'THREE.Renderer: Objects of type THREE.LineLoop are not supported. Please use THREE.Line or THREE.LineSegments.' );
  38009. } else if ( object.isMesh || object.isLine || object.isPoints ) {
  38010. if ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) {
  38011. const { geometry, material } = object;
  38012. if ( this.sortObjects === true ) {
  38013. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  38014. _vector4
  38015. .copy( geometry.boundingSphere.center )
  38016. .applyMatrix4( object.matrixWorld )
  38017. .applyMatrix4( _projScreenMatrix );
  38018. }
  38019. if ( Array.isArray( material ) ) {
  38020. const groups = geometry.groups;
  38021. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  38022. const group = groups[ i ];
  38023. const groupMaterial = material[ group.materialIndex ];
  38024. if ( groupMaterial && groupMaterial.visible ) {
  38025. renderList.push( object, geometry, groupMaterial, groupOrder, _vector4.z, group );
  38026. }
  38027. }
  38028. } else if ( material.visible ) {
  38029. renderList.push( object, geometry, material, groupOrder, _vector4.z, null );
  38030. }
  38031. }
  38032. }
  38033. }
  38034. if ( object.isBundleGroup === true && this.backend.beginBundle !== undefined ) {
  38035. const baseRenderList = renderList;
  38036. // replace render list
  38037. renderList = this._renderLists.get( object, camera );
  38038. renderList.begin();
  38039. baseRenderList.pushBundle( {
  38040. bundleGroup: object,
  38041. camera,
  38042. renderList,
  38043. } );
  38044. renderList.finish();
  38045. }
  38046. const children = object.children;
  38047. for ( let i = 0, l = children.length; i < l; i ++ ) {
  38048. this._projectObject( children[ i ], camera, groupOrder, renderList );
  38049. }
  38050. }
  38051. _renderBundles( bundles, sceneRef, lightsNode ) {
  38052. for ( const bundle of bundles ) {
  38053. this._renderBundle( bundle, sceneRef, lightsNode );
  38054. }
  38055. }
  38056. _renderObjects( renderList, camera, scene, lightsNode ) {
  38057. // process renderable objects
  38058. for ( let i = 0, il = renderList.length; i < il; i ++ ) {
  38059. const renderItem = renderList[ i ];
  38060. // @TODO: Add support for multiple materials per object. This will require to extract
  38061. // the material from the renderItem object and pass it with its group data to renderObject().
  38062. const { object, geometry, material, group } = renderItem;
  38063. if ( camera.isArrayCamera ) {
  38064. const cameras = camera.cameras;
  38065. for ( let j = 0, jl = cameras.length; j < jl; j ++ ) {
  38066. const camera2 = cameras[ j ];
  38067. if ( object.layers.test( camera2.layers ) ) {
  38068. const vp = camera2.viewport;
  38069. const minDepth = ( vp.minDepth === undefined ) ? 0 : vp.minDepth;
  38070. const maxDepth = ( vp.maxDepth === undefined ) ? 1 : vp.maxDepth;
  38071. const viewportValue = this._currentRenderContext.viewportValue;
  38072. viewportValue.copy( vp ).multiplyScalar( this._pixelRatio ).floor();
  38073. viewportValue.minDepth = minDepth;
  38074. viewportValue.maxDepth = maxDepth;
  38075. this.backend.updateViewport( this._currentRenderContext );
  38076. this._currentRenderObjectFunction( object, scene, camera2, geometry, material, group, lightsNode );
  38077. }
  38078. }
  38079. } else {
  38080. this._currentRenderObjectFunction( object, scene, camera, geometry, material, group, lightsNode );
  38081. }
  38082. }
  38083. }
  38084. renderObject( object, scene, camera, geometry, material, group, lightsNode ) {
  38085. let overridePositionNode;
  38086. let overrideFragmentNode;
  38087. let overrideDepthNode;
  38088. //
  38089. object.onBeforeRender( this, scene, camera, geometry, material, group );
  38090. //
  38091. if ( scene.overrideMaterial !== null ) {
  38092. const overrideMaterial = scene.overrideMaterial;
  38093. if ( material.positionNode && material.positionNode.isNode ) {
  38094. overridePositionNode = overrideMaterial.positionNode;
  38095. overrideMaterial.positionNode = material.positionNode;
  38096. }
  38097. if ( overrideMaterial.isShadowNodeMaterial ) {
  38098. overrideMaterial.side = material.shadowSide === null ? material.side : material.shadowSide;
  38099. if ( material.depthNode && material.depthNode.isNode ) {
  38100. overrideDepthNode = overrideMaterial.depthNode;
  38101. overrideMaterial.depthNode = material.depthNode;
  38102. }
  38103. if ( material.shadowNode && material.shadowNode.isNode ) {
  38104. overrideFragmentNode = overrideMaterial.fragmentNode;
  38105. overrideMaterial.fragmentNode = material.shadowNode;
  38106. }
  38107. if ( this.localClippingEnabled ) {
  38108. if ( material.clipShadows ) {
  38109. if ( overrideMaterial.clippingPlanes !== material.clippingPlanes ) {
  38110. overrideMaterial.clippingPlanes = material.clippingPlanes;
  38111. overrideMaterial.needsUpdate = true;
  38112. }
  38113. if ( overrideMaterial.clipIntersection !== material.clipIntersection ) {
  38114. overrideMaterial.clipIntersection = material.clipIntersection;
  38115. }
  38116. } else if ( Array.isArray( overrideMaterial.clippingPlanes ) ) {
  38117. overrideMaterial.clippingPlanes = null;
  38118. overrideMaterial.needsUpdate = true;
  38119. }
  38120. }
  38121. }
  38122. material = overrideMaterial;
  38123. }
  38124. //
  38125. if ( material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false ) {
  38126. material.side = BackSide;
  38127. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, 'backSide' ); // create backSide pass id
  38128. material.side = FrontSide;
  38129. this._handleObjectFunction( object, material, scene, camera, lightsNode, group ); // use default pass id
  38130. material.side = DoubleSide;
  38131. } else {
  38132. this._handleObjectFunction( object, material, scene, camera, lightsNode, group );
  38133. }
  38134. //
  38135. if ( overridePositionNode !== undefined ) {
  38136. scene.overrideMaterial.positionNode = overridePositionNode;
  38137. }
  38138. if ( overrideDepthNode !== undefined ) {
  38139. scene.overrideMaterial.depthNode = overrideDepthNode;
  38140. }
  38141. if ( overrideFragmentNode !== undefined ) {
  38142. scene.overrideMaterial.fragmentNode = overrideFragmentNode;
  38143. }
  38144. //
  38145. object.onAfterRender( this, scene, camera, geometry, material, group );
  38146. }
  38147. _renderObjectDirect( object, material, scene, camera, lightsNode, group, passId ) {
  38148. const renderObject = this._objects.get( object, material, scene, camera, lightsNode, this._currentRenderContext, passId );
  38149. renderObject.drawRange = object.geometry.drawRange;
  38150. renderObject.group = group;
  38151. //
  38152. const needsRefresh = this._nodes.needsRefresh( renderObject );
  38153. if ( needsRefresh ) {
  38154. this._nodes.updateBefore( renderObject );
  38155. this._geometries.updateForRender( renderObject );
  38156. this._nodes.updateForRender( renderObject );
  38157. this._bindings.updateForRender( renderObject );
  38158. }
  38159. this._pipelines.updateForRender( renderObject );
  38160. //
  38161. if ( this._currentRenderBundle !== null ) {
  38162. const renderBundleData = this.backend.get( this._currentRenderBundle );
  38163. renderBundleData.renderObjects.push( renderObject );
  38164. renderObject.bundle = this._currentRenderBundle.scene;
  38165. }
  38166. this.backend.draw( renderObject, this.info );
  38167. if ( needsRefresh ) this._nodes.updateAfter( renderObject );
  38168. }
  38169. _createObjectPipeline( object, material, scene, camera, lightsNode, passId ) {
  38170. const renderObject = this._objects.get( object, material, scene, camera, lightsNode, this._currentRenderContext, passId );
  38171. //
  38172. this._nodes.updateBefore( renderObject );
  38173. this._geometries.updateForRender( renderObject );
  38174. this._nodes.updateForRender( renderObject );
  38175. this._bindings.updateForRender( renderObject );
  38176. this._pipelines.getForRender( renderObject, this._compilationPromises );
  38177. this._nodes.updateAfter( renderObject );
  38178. }
  38179. get compile() {
  38180. return this.compileAsync;
  38181. }
  38182. }
  38183. class Binding {
  38184. constructor( name = '' ) {
  38185. this.name = name;
  38186. this.visibility = 0;
  38187. }
  38188. setVisibility( visibility ) {
  38189. this.visibility |= visibility;
  38190. }
  38191. clone() {
  38192. return Object.assign( new this.constructor(), this );
  38193. }
  38194. }
  38195. function getFloatLength( floatLength ) {
  38196. // ensure chunk size alignment (STD140 layout)
  38197. return floatLength + ( ( GPU_CHUNK_BYTES - ( floatLength % GPU_CHUNK_BYTES ) ) % GPU_CHUNK_BYTES );
  38198. }
  38199. class Buffer extends Binding {
  38200. constructor( name, buffer = null ) {
  38201. super( name );
  38202. this.isBuffer = true;
  38203. this.bytesPerElement = Float32Array.BYTES_PER_ELEMENT;
  38204. this._buffer = buffer;
  38205. }
  38206. get byteLength() {
  38207. return getFloatLength( this._buffer.byteLength );
  38208. }
  38209. get buffer() {
  38210. return this._buffer;
  38211. }
  38212. update() {
  38213. return true;
  38214. }
  38215. }
  38216. class UniformBuffer extends Buffer {
  38217. constructor( name, buffer = null ) {
  38218. super( name, buffer );
  38219. this.isUniformBuffer = true;
  38220. }
  38221. }
  38222. let _id$4 = 0;
  38223. class NodeUniformBuffer extends UniformBuffer {
  38224. constructor( nodeUniform, groupNode ) {
  38225. super( 'UniformBuffer_' + _id$4 ++, nodeUniform ? nodeUniform.value : null );
  38226. this.nodeUniform = nodeUniform;
  38227. this.groupNode = groupNode;
  38228. }
  38229. get buffer() {
  38230. return this.nodeUniform.value;
  38231. }
  38232. }
  38233. class UniformsGroup extends UniformBuffer {
  38234. constructor( name ) {
  38235. super( name );
  38236. this.isUniformsGroup = true;
  38237. this._values = null;
  38238. // the order of uniforms in this array must match the order of uniforms in the shader
  38239. this.uniforms = [];
  38240. }
  38241. addUniform( uniform ) {
  38242. this.uniforms.push( uniform );
  38243. return this;
  38244. }
  38245. removeUniform( uniform ) {
  38246. const index = this.uniforms.indexOf( uniform );
  38247. if ( index !== - 1 ) {
  38248. this.uniforms.splice( index, 1 );
  38249. }
  38250. return this;
  38251. }
  38252. get values() {
  38253. if ( this._values === null ) {
  38254. this._values = Array.from( this.buffer );
  38255. }
  38256. return this._values;
  38257. }
  38258. get buffer() {
  38259. let buffer = this._buffer;
  38260. if ( buffer === null ) {
  38261. const byteLength = this.byteLength;
  38262. buffer = new Float32Array( new ArrayBuffer( byteLength ) );
  38263. this._buffer = buffer;
  38264. }
  38265. return buffer;
  38266. }
  38267. get byteLength() {
  38268. let offset = 0; // global buffer offset in bytes
  38269. for ( let i = 0, l = this.uniforms.length; i < l; i ++ ) {
  38270. const uniform = this.uniforms[ i ];
  38271. const { boundary, itemSize } = uniform;
  38272. // offset within a single chunk in bytes
  38273. const chunkOffset = offset % GPU_CHUNK_BYTES;
  38274. const remainingSizeInChunk = GPU_CHUNK_BYTES - chunkOffset;
  38275. // conformance tests
  38276. if ( chunkOffset !== 0 && ( remainingSizeInChunk - boundary ) < 0 ) {
  38277. // check for chunk overflow
  38278. offset += ( GPU_CHUNK_BYTES - chunkOffset );
  38279. } else if ( chunkOffset % boundary !== 0 ) {
  38280. // check for correct alignment
  38281. offset += ( chunkOffset % boundary );
  38282. }
  38283. uniform.offset = ( offset / this.bytesPerElement );
  38284. offset += ( itemSize * this.bytesPerElement );
  38285. }
  38286. return Math.ceil( offset / GPU_CHUNK_BYTES ) * GPU_CHUNK_BYTES;
  38287. }
  38288. update() {
  38289. let updated = false;
  38290. for ( const uniform of this.uniforms ) {
  38291. if ( this.updateByType( uniform ) === true ) {
  38292. updated = true;
  38293. }
  38294. }
  38295. return updated;
  38296. }
  38297. updateByType( uniform ) {
  38298. if ( uniform.isNumberUniform ) return this.updateNumber( uniform );
  38299. if ( uniform.isVector2Uniform ) return this.updateVector2( uniform );
  38300. if ( uniform.isVector3Uniform ) return this.updateVector3( uniform );
  38301. if ( uniform.isVector4Uniform ) return this.updateVector4( uniform );
  38302. if ( uniform.isColorUniform ) return this.updateColor( uniform );
  38303. if ( uniform.isMatrix3Uniform ) return this.updateMatrix3( uniform );
  38304. if ( uniform.isMatrix4Uniform ) return this.updateMatrix4( uniform );
  38305. console.error( 'THREE.WebGPUUniformsGroup: Unsupported uniform type.', uniform );
  38306. }
  38307. updateNumber( uniform ) {
  38308. let updated = false;
  38309. const a = this.values;
  38310. const v = uniform.getValue();
  38311. const offset = uniform.offset;
  38312. if ( a[ offset ] !== v ) {
  38313. const b = this.buffer;
  38314. b[ offset ] = a[ offset ] = v;
  38315. updated = true;
  38316. }
  38317. return updated;
  38318. }
  38319. updateVector2( uniform ) {
  38320. let updated = false;
  38321. const a = this.values;
  38322. const v = uniform.getValue();
  38323. const offset = uniform.offset;
  38324. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y ) {
  38325. const b = this.buffer;
  38326. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  38327. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  38328. updated = true;
  38329. }
  38330. return updated;
  38331. }
  38332. updateVector3( uniform ) {
  38333. let updated = false;
  38334. const a = this.values;
  38335. const v = uniform.getValue();
  38336. const offset = uniform.offset;
  38337. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y || a[ offset + 2 ] !== v.z ) {
  38338. const b = this.buffer;
  38339. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  38340. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  38341. b[ offset + 2 ] = a[ offset + 2 ] = v.z;
  38342. updated = true;
  38343. }
  38344. return updated;
  38345. }
  38346. updateVector4( uniform ) {
  38347. let updated = false;
  38348. const a = this.values;
  38349. const v = uniform.getValue();
  38350. const offset = uniform.offset;
  38351. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y || a[ offset + 2 ] !== v.z || a[ offset + 4 ] !== v.w ) {
  38352. const b = this.buffer;
  38353. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  38354. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  38355. b[ offset + 2 ] = a[ offset + 2 ] = v.z;
  38356. b[ offset + 3 ] = a[ offset + 3 ] = v.w;
  38357. updated = true;
  38358. }
  38359. return updated;
  38360. }
  38361. updateColor( uniform ) {
  38362. let updated = false;
  38363. const a = this.values;
  38364. const c = uniform.getValue();
  38365. const offset = uniform.offset;
  38366. if ( a[ offset + 0 ] !== c.r || a[ offset + 1 ] !== c.g || a[ offset + 2 ] !== c.b ) {
  38367. const b = this.buffer;
  38368. b[ offset + 0 ] = a[ offset + 0 ] = c.r;
  38369. b[ offset + 1 ] = a[ offset + 1 ] = c.g;
  38370. b[ offset + 2 ] = a[ offset + 2 ] = c.b;
  38371. updated = true;
  38372. }
  38373. return updated;
  38374. }
  38375. updateMatrix3( uniform ) {
  38376. let updated = false;
  38377. const a = this.values;
  38378. const e = uniform.getValue().elements;
  38379. const offset = uniform.offset;
  38380. if ( a[ offset + 0 ] !== e[ 0 ] || a[ offset + 1 ] !== e[ 1 ] || a[ offset + 2 ] !== e[ 2 ] ||
  38381. a[ offset + 4 ] !== e[ 3 ] || a[ offset + 5 ] !== e[ 4 ] || a[ offset + 6 ] !== e[ 5 ] ||
  38382. a[ offset + 8 ] !== e[ 6 ] || a[ offset + 9 ] !== e[ 7 ] || a[ offset + 10 ] !== e[ 8 ] ) {
  38383. const b = this.buffer;
  38384. b[ offset + 0 ] = a[ offset + 0 ] = e[ 0 ];
  38385. b[ offset + 1 ] = a[ offset + 1 ] = e[ 1 ];
  38386. b[ offset + 2 ] = a[ offset + 2 ] = e[ 2 ];
  38387. b[ offset + 4 ] = a[ offset + 4 ] = e[ 3 ];
  38388. b[ offset + 5 ] = a[ offset + 5 ] = e[ 4 ];
  38389. b[ offset + 6 ] = a[ offset + 6 ] = e[ 5 ];
  38390. b[ offset + 8 ] = a[ offset + 8 ] = e[ 6 ];
  38391. b[ offset + 9 ] = a[ offset + 9 ] = e[ 7 ];
  38392. b[ offset + 10 ] = a[ offset + 10 ] = e[ 8 ];
  38393. updated = true;
  38394. }
  38395. return updated;
  38396. }
  38397. updateMatrix4( uniform ) {
  38398. let updated = false;
  38399. const a = this.values;
  38400. const e = uniform.getValue().elements;
  38401. const offset = uniform.offset;
  38402. if ( arraysEqual( a, e, offset ) === false ) {
  38403. const b = this.buffer;
  38404. b.set( e, offset );
  38405. setArray( a, e, offset );
  38406. updated = true;
  38407. }
  38408. return updated;
  38409. }
  38410. }
  38411. function setArray( a, b, offset ) {
  38412. for ( let i = 0, l = b.length; i < l; i ++ ) {
  38413. a[ offset + i ] = b[ i ];
  38414. }
  38415. }
  38416. function arraysEqual( a, b, offset ) {
  38417. for ( let i = 0, l = b.length; i < l; i ++ ) {
  38418. if ( a[ offset + i ] !== b[ i ] ) return false;
  38419. }
  38420. return true;
  38421. }
  38422. let _id$3 = 0;
  38423. class NodeUniformsGroup extends UniformsGroup {
  38424. constructor( name, groupNode ) {
  38425. super( name );
  38426. this.id = _id$3 ++;
  38427. this.groupNode = groupNode;
  38428. this.isNodeUniformsGroup = true;
  38429. }
  38430. getNodes() {
  38431. const nodes = [];
  38432. for ( const uniform of this.uniforms ) {
  38433. const node = uniform.nodeUniform.node;
  38434. if ( ! node ) throw new Error( 'NodeUniformsGroup: Uniform has no node.' );
  38435. nodes.push( node );
  38436. }
  38437. return nodes;
  38438. }
  38439. }
  38440. let _id$2 = 0;
  38441. class SampledTexture extends Binding {
  38442. constructor( name, texture ) {
  38443. super( name );
  38444. this.id = _id$2 ++;
  38445. this.texture = texture;
  38446. this.version = texture ? texture.version : 0;
  38447. this.store = false;
  38448. this.generation = null;
  38449. this.isSampledTexture = true;
  38450. }
  38451. needsBindingsUpdate( generation ) {
  38452. const { texture } = this;
  38453. if ( generation !== this.generation ) {
  38454. this.generation = generation;
  38455. return true;
  38456. }
  38457. return texture.isVideoTexture;
  38458. }
  38459. update() {
  38460. const { texture, version } = this;
  38461. if ( version !== texture.version ) {
  38462. this.version = texture.version;
  38463. return true;
  38464. }
  38465. return false;
  38466. }
  38467. }
  38468. class NodeSampledTexture extends SampledTexture {
  38469. constructor( name, textureNode, groupNode, access = null ) {
  38470. super( name, textureNode ? textureNode.value : null );
  38471. this.textureNode = textureNode;
  38472. this.groupNode = groupNode;
  38473. this.access = access;
  38474. }
  38475. needsBindingsUpdate( generation ) {
  38476. return this.textureNode.value !== this.texture || super.needsBindingsUpdate( generation );
  38477. }
  38478. update() {
  38479. const { textureNode } = this;
  38480. if ( this.texture !== textureNode.value ) {
  38481. this.texture = textureNode.value;
  38482. return true;
  38483. }
  38484. return super.update();
  38485. }
  38486. }
  38487. class NodeSampledCubeTexture extends NodeSampledTexture {
  38488. constructor( name, textureNode, groupNode, access ) {
  38489. super( name, textureNode, groupNode, access );
  38490. this.isSampledCubeTexture = true;
  38491. }
  38492. }
  38493. class NodeSampledTexture3D extends NodeSampledTexture {
  38494. constructor( name, textureNode, groupNode, access ) {
  38495. super( name, textureNode, groupNode, access );
  38496. this.isSampledTexture3D = true;
  38497. }
  38498. }
  38499. const glslMethods = {
  38500. atan2: 'atan',
  38501. textureDimensions: 'textureSize',
  38502. equals: 'equal'
  38503. };
  38504. const precisionLib = {
  38505. low: 'lowp',
  38506. medium: 'mediump',
  38507. high: 'highp'
  38508. };
  38509. const supports$1 = {
  38510. swizzleAssign: true,
  38511. storageBuffer: false
  38512. };
  38513. const defaultPrecisions = `
  38514. precision highp float;
  38515. precision highp int;
  38516. precision highp sampler2D;
  38517. precision highp sampler3D;
  38518. precision highp samplerCube;
  38519. precision highp sampler2DArray;
  38520. precision highp usampler2D;
  38521. precision highp usampler3D;
  38522. precision highp usamplerCube;
  38523. precision highp usampler2DArray;
  38524. precision highp isampler2D;
  38525. precision highp isampler3D;
  38526. precision highp isamplerCube;
  38527. precision highp isampler2DArray;
  38528. precision lowp sampler2DShadow;
  38529. `;
  38530. class GLSLNodeBuilder extends NodeBuilder {
  38531. constructor( object, renderer ) {
  38532. super( object, renderer, new GLSLNodeParser() );
  38533. this.uniformGroups = {};
  38534. this.transforms = [];
  38535. this.extensions = {};
  38536. this.useComparisonMethod = true;
  38537. }
  38538. needsColorSpaceToLinearSRGB( texture ) {
  38539. return texture.isVideoTexture === true && texture.colorSpace !== NoColorSpace;
  38540. }
  38541. getMethod( method ) {
  38542. return glslMethods[ method ] || method;
  38543. }
  38544. getOutputStructName() {
  38545. return '';
  38546. }
  38547. buildFunctionCode( shaderNode ) {
  38548. const layout = shaderNode.layout;
  38549. const flowData = this.flowShaderNode( shaderNode );
  38550. const parameters = [];
  38551. for ( const input of layout.inputs ) {
  38552. parameters.push( this.getType( input.type ) + ' ' + input.name );
  38553. }
  38554. //
  38555. const code = `${ this.getType( layout.type ) } ${ layout.name }( ${ parameters.join( ', ' ) } ) {
  38556. ${ flowData.vars }
  38557. ${ flowData.code }
  38558. return ${ flowData.result };
  38559. }`;
  38560. //
  38561. return code;
  38562. }
  38563. setupPBO( storageBufferNode ) {
  38564. const attribute = storageBufferNode.value;
  38565. if ( attribute.pbo === undefined ) {
  38566. const originalArray = attribute.array;
  38567. const numElements = attribute.count * attribute.itemSize;
  38568. const { itemSize } = attribute;
  38569. const isInteger = attribute.array.constructor.name.toLowerCase().includes( 'int' );
  38570. let format = isInteger ? RedIntegerFormat : RedFormat;
  38571. if ( itemSize === 2 ) {
  38572. format = isInteger ? RGIntegerFormat : RGFormat;
  38573. } else if ( itemSize === 3 ) {
  38574. format = isInteger ? RGBIntegerFormat : RGBFormat;
  38575. } else if ( itemSize === 4 ) {
  38576. format = isInteger ? RGBAIntegerFormat : RGBAFormat;
  38577. }
  38578. const typeMap = {
  38579. Float32Array: FloatType,
  38580. Uint8Array: UnsignedByteType,
  38581. Uint16Array: UnsignedShortType,
  38582. Uint32Array: UnsignedIntType,
  38583. Int8Array: ByteType,
  38584. Int16Array: ShortType,
  38585. Int32Array: IntType,
  38586. Uint8ClampedArray: UnsignedByteType,
  38587. };
  38588. const width = Math.pow( 2, Math.ceil( Math.log2( Math.sqrt( numElements / itemSize ) ) ) );
  38589. let height = Math.ceil( ( numElements / itemSize ) / width );
  38590. if ( width * height * itemSize < numElements ) height ++; // Ensure enough space
  38591. const newSize = width * height * itemSize;
  38592. const newArray = new originalArray.constructor( newSize );
  38593. newArray.set( originalArray, 0 );
  38594. attribute.array = newArray;
  38595. const pboTexture = new DataTexture( attribute.array, width, height, format, typeMap[ attribute.array.constructor.name ] || FloatType );
  38596. pboTexture.needsUpdate = true;
  38597. pboTexture.isPBOTexture = true;
  38598. const pbo = new TextureNode( pboTexture, null, null );
  38599. pbo.setPrecision( 'high' );
  38600. attribute.pboNode = pbo;
  38601. attribute.pbo = pbo.value;
  38602. this.getUniformFromNode( attribute.pboNode, 'texture', this.shaderStage, this.context.label );
  38603. }
  38604. }
  38605. getPropertyName( node, shaderStage = this.shaderStage ) {
  38606. if ( node.isNodeUniform && node.node.isTextureNode !== true && node.node.isBufferNode !== true ) {
  38607. return shaderStage.charAt( 0 ) + '_' + node.name;
  38608. }
  38609. return super.getPropertyName( node, shaderStage );
  38610. }
  38611. generatePBO( storageArrayElementNode ) {
  38612. const { node, indexNode } = storageArrayElementNode;
  38613. const attribute = node.value;
  38614. if ( this.renderer.backend.has( attribute ) ) {
  38615. const attributeData = this.renderer.backend.get( attribute );
  38616. attributeData.pbo = attribute.pbo;
  38617. }
  38618. const nodeUniform = this.getUniformFromNode( attribute.pboNode, 'texture', this.shaderStage, this.context.label );
  38619. const textureName = this.getPropertyName( nodeUniform );
  38620. this.increaseUsage( indexNode ); // force cache generate to be used as index in x,y
  38621. const indexSnippet = indexNode.build( this, 'uint' );
  38622. const elementNodeData = this.getDataFromNode( storageArrayElementNode );
  38623. let propertyName = elementNodeData.propertyName;
  38624. if ( propertyName === undefined ) {
  38625. // property element
  38626. const nodeVar = this.getVarFromNode( storageArrayElementNode );
  38627. propertyName = this.getPropertyName( nodeVar );
  38628. // property size
  38629. const bufferNodeData = this.getDataFromNode( node );
  38630. let propertySizeName = bufferNodeData.propertySizeName;
  38631. if ( propertySizeName === undefined ) {
  38632. propertySizeName = propertyName + 'Size';
  38633. this.getVarFromNode( node, propertySizeName, 'uint' );
  38634. this.addLineFlowCode( `${ propertySizeName } = uint( textureSize( ${ textureName }, 0 ).x )`, storageArrayElementNode );
  38635. bufferNodeData.propertySizeName = propertySizeName;
  38636. }
  38637. //
  38638. const { itemSize } = attribute;
  38639. const channel = '.' + vectorComponents.join( '' ).slice( 0, itemSize );
  38640. const uvSnippet = `ivec2(${indexSnippet} % ${ propertySizeName }, ${indexSnippet} / ${ propertySizeName })`;
  38641. const snippet = this.generateTextureLoad( null, textureName, uvSnippet, null, '0' );
  38642. //
  38643. let prefix = 'vec4';
  38644. if ( attribute.pbo.type === UnsignedIntType ) {
  38645. prefix = 'uvec4';
  38646. } else if ( attribute.pbo.type === IntType ) {
  38647. prefix = 'ivec4';
  38648. }
  38649. this.addLineFlowCode( `${ propertyName } = ${prefix}(${ snippet })${channel}`, storageArrayElementNode );
  38650. elementNodeData.propertyName = propertyName;
  38651. }
  38652. return propertyName;
  38653. }
  38654. generateTextureLoad( texture, textureProperty, uvIndexSnippet, depthSnippet, levelSnippet = '0' ) {
  38655. if ( depthSnippet ) {
  38656. return `texelFetch( ${ textureProperty }, ivec3( ${ uvIndexSnippet }, ${ depthSnippet } ), ${ levelSnippet } )`;
  38657. } else {
  38658. return `texelFetch( ${ textureProperty }, ${ uvIndexSnippet }, ${ levelSnippet } )`;
  38659. }
  38660. }
  38661. generateTexture( texture, textureProperty, uvSnippet, depthSnippet ) {
  38662. if ( texture.isDepthTexture ) {
  38663. return `texture( ${ textureProperty }, ${ uvSnippet } ).x`;
  38664. } else {
  38665. if ( depthSnippet ) uvSnippet = `vec3( ${ uvSnippet }, ${ depthSnippet } )`;
  38666. return `texture( ${ textureProperty }, ${ uvSnippet } )`;
  38667. }
  38668. }
  38669. generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet ) {
  38670. return `textureLod( ${ textureProperty }, ${ uvSnippet }, ${ levelSnippet } )`;
  38671. }
  38672. generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet ) {
  38673. return `texture( ${ textureProperty }, ${ uvSnippet }, ${ biasSnippet } )`;
  38674. }
  38675. generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet ) {
  38676. return `textureGrad( ${ textureProperty }, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] } )`;
  38677. }
  38678. generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  38679. if ( shaderStage === 'fragment' ) {
  38680. return `texture( ${ textureProperty }, vec3( ${ uvSnippet }, ${ compareSnippet } ) )`;
  38681. } else {
  38682. console.error( `WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${ shaderStage } shader.` );
  38683. }
  38684. }
  38685. getVars( shaderStage ) {
  38686. const snippets = [];
  38687. const vars = this.vars[ shaderStage ];
  38688. if ( vars !== undefined ) {
  38689. for ( const variable of vars ) {
  38690. snippets.push( `${ this.getVar( variable.type, variable.name ) };` );
  38691. }
  38692. }
  38693. return snippets.join( '\n\t' );
  38694. }
  38695. getUniforms( shaderStage ) {
  38696. const uniforms = this.uniforms[ shaderStage ];
  38697. const bindingSnippets = [];
  38698. const uniformGroups = {};
  38699. for ( const uniform of uniforms ) {
  38700. let snippet = null;
  38701. let group = false;
  38702. if ( uniform.type === 'texture' ) {
  38703. const texture = uniform.node.value;
  38704. let typePrefix = '';
  38705. if ( texture.isDataTexture === true ) {
  38706. if ( texture.type === UnsignedIntType ) {
  38707. typePrefix = 'u';
  38708. } else if ( texture.type === IntType ) {
  38709. typePrefix = 'i';
  38710. }
  38711. }
  38712. if ( texture.compareFunction ) {
  38713. snippet = `sampler2DShadow ${ uniform.name };`;
  38714. } else if ( texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  38715. snippet = `${typePrefix}sampler2DArray ${ uniform.name };`;
  38716. } else {
  38717. snippet = `${typePrefix}sampler2D ${ uniform.name };`;
  38718. }
  38719. } else if ( uniform.type === 'cubeTexture' ) {
  38720. snippet = `samplerCube ${ uniform.name };`;
  38721. } else if ( uniform.type === 'texture3D' ) {
  38722. snippet = `sampler3D ${ uniform.name };`;
  38723. } else if ( uniform.type === 'buffer' ) {
  38724. const bufferNode = uniform.node;
  38725. const bufferType = this.getType( bufferNode.bufferType );
  38726. const bufferCount = bufferNode.bufferCount;
  38727. const bufferCountSnippet = bufferCount > 0 ? bufferCount : '';
  38728. snippet = `${bufferNode.name} {\n\t${ bufferType } ${ uniform.name }[${ bufferCountSnippet }];\n};\n`;
  38729. } else {
  38730. const vectorType = this.getVectorType( uniform.type );
  38731. snippet = `${ vectorType } ${ this.getPropertyName( uniform, shaderStage ) };`;
  38732. group = true;
  38733. }
  38734. const precision = uniform.node.precision;
  38735. if ( precision !== null ) {
  38736. snippet = precisionLib[ precision ] + ' ' + snippet;
  38737. }
  38738. if ( group ) {
  38739. snippet = '\t' + snippet;
  38740. const groupName = uniform.groupNode.name;
  38741. const groupSnippets = uniformGroups[ groupName ] || ( uniformGroups[ groupName ] = [] );
  38742. groupSnippets.push( snippet );
  38743. } else {
  38744. snippet = 'uniform ' + snippet;
  38745. bindingSnippets.push( snippet );
  38746. }
  38747. }
  38748. let output = '';
  38749. for ( const name in uniformGroups ) {
  38750. const groupSnippets = uniformGroups[ name ];
  38751. output += this._getGLSLUniformStruct( shaderStage + '_' + name, groupSnippets.join( '\n' ) ) + '\n';
  38752. }
  38753. output += bindingSnippets.join( '\n' );
  38754. return output;
  38755. }
  38756. getTypeFromAttribute( attribute ) {
  38757. let nodeType = super.getTypeFromAttribute( attribute );
  38758. if ( /^[iu]/.test( nodeType ) && attribute.gpuType !== IntType ) {
  38759. let dataAttribute = attribute;
  38760. if ( attribute.isInterleavedBufferAttribute ) dataAttribute = attribute.data;
  38761. const array = dataAttribute.array;
  38762. if ( ( array instanceof Uint32Array || array instanceof Int32Array ) === false ) {
  38763. nodeType = nodeType.slice( 1 );
  38764. }
  38765. }
  38766. return nodeType;
  38767. }
  38768. getAttributes( shaderStage ) {
  38769. let snippet = '';
  38770. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  38771. const attributes = this.getAttributesArray();
  38772. let location = 0;
  38773. for ( const attribute of attributes ) {
  38774. snippet += `layout( location = ${ location ++ } ) in ${ attribute.type } ${ attribute.name };\n`;
  38775. }
  38776. }
  38777. return snippet;
  38778. }
  38779. getStructMembers( struct ) {
  38780. const snippets = [];
  38781. const members = struct.getMemberTypes();
  38782. for ( let i = 0; i < members.length; i ++ ) {
  38783. const member = members[ i ];
  38784. snippets.push( `layout( location = ${i} ) out ${ member} m${i};` );
  38785. }
  38786. return snippets.join( '\n' );
  38787. }
  38788. getStructs( shaderStage ) {
  38789. const snippets = [];
  38790. const structs = this.structs[ shaderStage ];
  38791. if ( structs.length === 0 ) {
  38792. return 'layout( location = 0 ) out vec4 fragColor;\n';
  38793. }
  38794. for ( let index = 0, length = structs.length; index < length; index ++ ) {
  38795. const struct = structs[ index ];
  38796. let snippet = '\n';
  38797. snippet += this.getStructMembers( struct );
  38798. snippet += '\n';
  38799. snippets.push( snippet );
  38800. }
  38801. return snippets.join( '\n\n' );
  38802. }
  38803. getVaryings( shaderStage ) {
  38804. let snippet = '';
  38805. const varyings = this.varyings;
  38806. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  38807. for ( const varying of varyings ) {
  38808. if ( shaderStage === 'compute' ) varying.needsInterpolation = true;
  38809. const type = varying.type;
  38810. const flat = type.includes( 'int' ) || type.includes( 'uv' ) || type.includes( 'iv' ) ? 'flat ' : '';
  38811. snippet += `${flat}${varying.needsInterpolation ? 'out' : '/*out*/'} ${type} ${varying.name};\n`;
  38812. }
  38813. } else if ( shaderStage === 'fragment' ) {
  38814. for ( const varying of varyings ) {
  38815. if ( varying.needsInterpolation ) {
  38816. const type = varying.type;
  38817. const flat = type.includes( 'int' ) || type.includes( 'uv' ) || type.includes( 'iv' ) ? 'flat ' : '';
  38818. snippet += `${flat}in ${type} ${varying.name};\n`;
  38819. }
  38820. }
  38821. }
  38822. return snippet;
  38823. }
  38824. getVertexIndex() {
  38825. return 'uint( gl_VertexID )';
  38826. }
  38827. getInstanceIndex() {
  38828. return 'uint( gl_InstanceID )';
  38829. }
  38830. getInvocationLocalIndex() {
  38831. const workgroupSize = this.object.workgroupSize;
  38832. const size = workgroupSize.reduce( ( acc, curr ) => acc * curr, 1 );
  38833. return `uint( gl_InstanceID ) % ${size}u`;
  38834. }
  38835. getDrawIndex() {
  38836. const extensions = this.renderer.backend.extensions;
  38837. if ( extensions.has( 'WEBGL_multi_draw' ) ) {
  38838. return 'uint( gl_DrawID )';
  38839. }
  38840. return null;
  38841. }
  38842. getFrontFacing() {
  38843. return 'gl_FrontFacing';
  38844. }
  38845. getFragCoord() {
  38846. return 'gl_FragCoord.xy';
  38847. }
  38848. getFragDepth() {
  38849. return 'gl_FragDepth';
  38850. }
  38851. enableExtension( name, behavior, shaderStage = this.shaderStage ) {
  38852. const map = this.extensions[ shaderStage ] || ( this.extensions[ shaderStage ] = new Map() );
  38853. if ( map.has( name ) === false ) {
  38854. map.set( name, {
  38855. name,
  38856. behavior
  38857. } );
  38858. }
  38859. }
  38860. getExtensions( shaderStage ) {
  38861. const snippets = [];
  38862. if ( shaderStage === 'vertex' ) {
  38863. const ext = this.renderer.backend.extensions;
  38864. const isBatchedMesh = this.object.isBatchedMesh;
  38865. if ( isBatchedMesh && ext.has( 'WEBGL_multi_draw' ) ) {
  38866. this.enableExtension( 'GL_ANGLE_multi_draw', 'require', shaderStage );
  38867. }
  38868. }
  38869. const extensions = this.extensions[ shaderStage ];
  38870. if ( extensions !== undefined ) {
  38871. for ( const { name, behavior } of extensions.values() ) {
  38872. snippets.push( `#extension ${name} : ${behavior}` );
  38873. }
  38874. }
  38875. return snippets.join( '\n' );
  38876. }
  38877. isAvailable( name ) {
  38878. let result = supports$1[ name ];
  38879. if ( result === undefined ) {
  38880. if ( name === 'float32Filterable' ) {
  38881. const extensions = this.renderer.backend.extensions;
  38882. if ( extensions.has( 'OES_texture_float_linear' ) ) {
  38883. extensions.get( 'OES_texture_float_linear' );
  38884. result = true;
  38885. } else {
  38886. result = false;
  38887. }
  38888. }
  38889. supports$1[ name ] = result;
  38890. }
  38891. return result;
  38892. }
  38893. isFlipY() {
  38894. return true;
  38895. }
  38896. registerTransform( varyingName, attributeNode ) {
  38897. this.transforms.push( { varyingName, attributeNode } );
  38898. }
  38899. getTransforms( /* shaderStage */ ) {
  38900. const transforms = this.transforms;
  38901. let snippet = '';
  38902. for ( let i = 0; i < transforms.length; i ++ ) {
  38903. const transform = transforms[ i ];
  38904. const attributeName = this.getPropertyName( transform.attributeNode );
  38905. snippet += `${ transform.varyingName } = ${ attributeName };\n\t`;
  38906. }
  38907. return snippet;
  38908. }
  38909. _getGLSLUniformStruct( name, vars ) {
  38910. return `
  38911. layout( std140 ) uniform ${name} {
  38912. ${vars}
  38913. };`;
  38914. }
  38915. _getGLSLVertexCode( shaderData ) {
  38916. return `#version 300 es
  38917. ${ this.getSignature() }
  38918. // extensions
  38919. ${shaderData.extensions}
  38920. // precision
  38921. ${ defaultPrecisions }
  38922. // uniforms
  38923. ${shaderData.uniforms}
  38924. // varyings
  38925. ${shaderData.varyings}
  38926. // attributes
  38927. ${shaderData.attributes}
  38928. // codes
  38929. ${shaderData.codes}
  38930. void main() {
  38931. // vars
  38932. ${shaderData.vars}
  38933. // transforms
  38934. ${shaderData.transforms}
  38935. // flow
  38936. ${shaderData.flow}
  38937. gl_PointSize = 1.0;
  38938. }
  38939. `;
  38940. }
  38941. _getGLSLFragmentCode( shaderData ) {
  38942. return `#version 300 es
  38943. ${ this.getSignature() }
  38944. // precision
  38945. ${ defaultPrecisions }
  38946. // uniforms
  38947. ${shaderData.uniforms}
  38948. // varyings
  38949. ${shaderData.varyings}
  38950. // codes
  38951. ${shaderData.codes}
  38952. ${shaderData.structs}
  38953. void main() {
  38954. // vars
  38955. ${shaderData.vars}
  38956. // flow
  38957. ${shaderData.flow}
  38958. }
  38959. `;
  38960. }
  38961. buildCode() {
  38962. const shadersData = this.material !== null ? { fragment: {}, vertex: {} } : { compute: {} };
  38963. this.sortBindingGroups();
  38964. for ( const shaderStage in shadersData ) {
  38965. let flow = '// code\n\n';
  38966. flow += this.flowCode[ shaderStage ];
  38967. const flowNodes = this.flowNodes[ shaderStage ];
  38968. const mainNode = flowNodes[ flowNodes.length - 1 ];
  38969. for ( const node of flowNodes ) {
  38970. const flowSlotData = this.getFlowData( node/*, shaderStage*/ );
  38971. const slotName = node.name;
  38972. if ( slotName ) {
  38973. if ( flow.length > 0 ) flow += '\n';
  38974. flow += `\t// flow -> ${ slotName }\n\t`;
  38975. }
  38976. flow += `${ flowSlotData.code }\n\t`;
  38977. if ( node === mainNode && shaderStage !== 'compute' ) {
  38978. flow += '// result\n\t';
  38979. if ( shaderStage === 'vertex' ) {
  38980. flow += 'gl_Position = ';
  38981. flow += `${ flowSlotData.result };`;
  38982. } else if ( shaderStage === 'fragment' ) {
  38983. if ( ! node.outputNode.isOutputStructNode ) {
  38984. flow += 'fragColor = ';
  38985. flow += `${ flowSlotData.result };`;
  38986. }
  38987. }
  38988. }
  38989. }
  38990. const stageData = shadersData[ shaderStage ];
  38991. stageData.extensions = this.getExtensions( shaderStage );
  38992. stageData.uniforms = this.getUniforms( shaderStage );
  38993. stageData.attributes = this.getAttributes( shaderStage );
  38994. stageData.varyings = this.getVaryings( shaderStage );
  38995. stageData.vars = this.getVars( shaderStage );
  38996. stageData.structs = this.getStructs( shaderStage );
  38997. stageData.codes = this.getCodes( shaderStage );
  38998. stageData.transforms = this.getTransforms( shaderStage );
  38999. stageData.flow = flow;
  39000. }
  39001. if ( this.material !== null ) {
  39002. this.vertexShader = this._getGLSLVertexCode( shadersData.vertex );
  39003. this.fragmentShader = this._getGLSLFragmentCode( shadersData.fragment );
  39004. } else {
  39005. this.computeShader = this._getGLSLVertexCode( shadersData.compute );
  39006. }
  39007. }
  39008. getUniformFromNode( node, type, shaderStage, name = null ) {
  39009. const uniformNode = super.getUniformFromNode( node, type, shaderStage, name );
  39010. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  39011. let uniformGPU = nodeData.uniformGPU;
  39012. if ( uniformGPU === undefined ) {
  39013. const group = node.groupNode;
  39014. const groupName = group.name;
  39015. const bindings = this.getBindGroupArray( groupName, shaderStage );
  39016. if ( type === 'texture' ) {
  39017. uniformGPU = new NodeSampledTexture( uniformNode.name, uniformNode.node, group );
  39018. bindings.push( uniformGPU );
  39019. } else if ( type === 'cubeTexture' ) {
  39020. uniformGPU = new NodeSampledCubeTexture( uniformNode.name, uniformNode.node, group );
  39021. bindings.push( uniformGPU );
  39022. } else if ( type === 'texture3D' ) {
  39023. uniformGPU = new NodeSampledTexture3D( uniformNode.name, uniformNode.node, group );
  39024. bindings.push( uniformGPU );
  39025. } else if ( type === 'buffer' ) {
  39026. node.name = `NodeBuffer_${ node.id }`;
  39027. uniformNode.name = `buffer${ node.id }`;
  39028. const buffer = new NodeUniformBuffer( node, group );
  39029. buffer.name = node.name;
  39030. bindings.push( buffer );
  39031. uniformGPU = buffer;
  39032. } else {
  39033. const uniformsStage = this.uniformGroups[ shaderStage ] || ( this.uniformGroups[ shaderStage ] = {} );
  39034. let uniformsGroup = uniformsStage[ groupName ];
  39035. if ( uniformsGroup === undefined ) {
  39036. uniformsGroup = new NodeUniformsGroup( shaderStage + '_' + groupName, group );
  39037. //uniformsGroup.setVisibility( gpuShaderStageLib[ shaderStage ] );
  39038. uniformsStage[ groupName ] = uniformsGroup;
  39039. bindings.push( uniformsGroup );
  39040. }
  39041. uniformGPU = this.getNodeUniform( uniformNode, type );
  39042. uniformsGroup.addUniform( uniformGPU );
  39043. }
  39044. nodeData.uniformGPU = uniformGPU;
  39045. }
  39046. return uniformNode;
  39047. }
  39048. }
  39049. let vector2 = null;
  39050. let vector4 = null;
  39051. let color4 = null;
  39052. class Backend {
  39053. constructor( parameters = {} ) {
  39054. this.parameters = Object.assign( {}, parameters );
  39055. this.data = new WeakMap();
  39056. this.renderer = null;
  39057. this.domElement = null;
  39058. }
  39059. async init( renderer ) {
  39060. this.renderer = renderer;
  39061. }
  39062. // render context
  39063. begin( /*renderContext*/ ) { }
  39064. finish( /*renderContext*/ ) { }
  39065. // render object
  39066. draw( /*renderObject, info*/ ) { }
  39067. // program
  39068. createProgram( /*program*/ ) { }
  39069. destroyProgram( /*program*/ ) { }
  39070. // bindings
  39071. createBindings( /*bingGroup, bindings*/ ) { }
  39072. updateBindings( /*bingGroup, bindings*/ ) { }
  39073. // pipeline
  39074. createRenderPipeline( /*renderObject*/ ) { }
  39075. createComputePipeline( /*computeNode, pipeline*/ ) { }
  39076. destroyPipeline( /*pipeline*/ ) { }
  39077. // cache key
  39078. needsRenderUpdate( /*renderObject*/ ) { } // return Boolean ( fast test )
  39079. getRenderCacheKey( /*renderObject*/ ) { } // return String
  39080. // node builder
  39081. createNodeBuilder( /*renderObject*/ ) { } // return NodeBuilder (ADD IT)
  39082. // textures
  39083. createSampler( /*texture*/ ) { }
  39084. createDefaultTexture( /*texture*/ ) { }
  39085. createTexture( /*texture*/ ) { }
  39086. copyTextureToBuffer( /*texture, x, y, width, height*/ ) {}
  39087. // attributes
  39088. createAttribute( /*attribute*/ ) { }
  39089. createIndexAttribute( /*attribute*/ ) { }
  39090. updateAttribute( /*attribute*/ ) { }
  39091. destroyAttribute( /*attribute*/ ) { }
  39092. // canvas
  39093. getContext() { }
  39094. updateSize() { }
  39095. // utils
  39096. resolveTimestampAsync( /*renderContext, type*/ ) { }
  39097. hasFeatureAsync( /*name*/ ) { } // return Boolean
  39098. hasFeature( /*name*/ ) { } // return Boolean
  39099. getInstanceCount( renderObject ) {
  39100. const { object, geometry } = renderObject;
  39101. return geometry.isInstancedBufferGeometry ? geometry.instanceCount : ( object.count > 1 ? object.count : 1 );
  39102. }
  39103. getDrawingBufferSize() {
  39104. vector2 = vector2 || new Vector2();
  39105. return this.renderer.getDrawingBufferSize( vector2 );
  39106. }
  39107. getScissor() {
  39108. vector4 = vector4 || new Vector4();
  39109. return this.renderer.getScissor( vector4 );
  39110. }
  39111. setScissorTest( /*boolean*/ ) { }
  39112. getClearColor() {
  39113. const renderer = this.renderer;
  39114. color4 = color4 || new Color4();
  39115. renderer.getClearColor( color4 );
  39116. color4.getRGB( color4, this.renderer.currentColorSpace );
  39117. return color4;
  39118. }
  39119. getDomElement() {
  39120. let domElement = this.domElement;
  39121. if ( domElement === null ) {
  39122. domElement = ( this.parameters.canvas !== undefined ) ? this.parameters.canvas : createCanvasElement();
  39123. // OffscreenCanvas does not have setAttribute, see #22811
  39124. if ( 'setAttribute' in domElement ) domElement.setAttribute( 'data-engine', `three.js r${REVISION} webgpu` );
  39125. this.domElement = domElement;
  39126. }
  39127. return domElement;
  39128. }
  39129. // resource properties
  39130. set( object, value ) {
  39131. this.data.set( object, value );
  39132. }
  39133. get( object ) {
  39134. let map = this.data.get( object );
  39135. if ( map === undefined ) {
  39136. map = {};
  39137. this.data.set( object, map );
  39138. }
  39139. return map;
  39140. }
  39141. has( object ) {
  39142. return this.data.has( object );
  39143. }
  39144. delete( object ) {
  39145. this.data.delete( object );
  39146. }
  39147. }
  39148. let _id$1 = 0;
  39149. class DualAttributeData {
  39150. constructor( attributeData, dualBuffer ) {
  39151. this.buffers = [ attributeData.bufferGPU, dualBuffer ];
  39152. this.type = attributeData.type;
  39153. this.bufferType = attributeData.bufferType;
  39154. this.pbo = attributeData.pbo;
  39155. this.byteLength = attributeData.byteLength;
  39156. this.bytesPerElement = attributeData.BYTES_PER_ELEMENT;
  39157. this.version = attributeData.version;
  39158. this.isInteger = attributeData.isInteger;
  39159. this.activeBufferIndex = 0;
  39160. this.baseId = attributeData.id;
  39161. }
  39162. get id() {
  39163. return `${ this.baseId }|${ this.activeBufferIndex }`;
  39164. }
  39165. get bufferGPU() {
  39166. return this.buffers[ this.activeBufferIndex ];
  39167. }
  39168. get transformBuffer() {
  39169. return this.buffers[ this.activeBufferIndex ^ 1 ];
  39170. }
  39171. switchBuffers() {
  39172. this.activeBufferIndex ^= 1;
  39173. }
  39174. }
  39175. class WebGLAttributeUtils {
  39176. constructor( backend ) {
  39177. this.backend = backend;
  39178. }
  39179. createAttribute( attribute, bufferType ) {
  39180. const backend = this.backend;
  39181. const { gl } = backend;
  39182. const array = attribute.array;
  39183. const usage = attribute.usage || gl.STATIC_DRAW;
  39184. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  39185. const bufferData = backend.get( bufferAttribute );
  39186. let bufferGPU = bufferData.bufferGPU;
  39187. if ( bufferGPU === undefined ) {
  39188. bufferGPU = this._createBuffer( gl, bufferType, array, usage );
  39189. bufferData.bufferGPU = bufferGPU;
  39190. bufferData.bufferType = bufferType;
  39191. bufferData.version = bufferAttribute.version;
  39192. }
  39193. //attribute.onUploadCallback();
  39194. let type;
  39195. if ( array instanceof Float32Array ) {
  39196. type = gl.FLOAT;
  39197. } else if ( array instanceof Uint16Array ) {
  39198. if ( attribute.isFloat16BufferAttribute ) {
  39199. type = gl.HALF_FLOAT;
  39200. } else {
  39201. type = gl.UNSIGNED_SHORT;
  39202. }
  39203. } else if ( array instanceof Int16Array ) {
  39204. type = gl.SHORT;
  39205. } else if ( array instanceof Uint32Array ) {
  39206. type = gl.UNSIGNED_INT;
  39207. } else if ( array instanceof Int32Array ) {
  39208. type = gl.INT;
  39209. } else if ( array instanceof Int8Array ) {
  39210. type = gl.BYTE;
  39211. } else if ( array instanceof Uint8Array ) {
  39212. type = gl.UNSIGNED_BYTE;
  39213. } else if ( array instanceof Uint8ClampedArray ) {
  39214. type = gl.UNSIGNED_BYTE;
  39215. } else {
  39216. throw new Error( 'THREE.WebGLBackend: Unsupported buffer data format: ' + array );
  39217. }
  39218. let attributeData = {
  39219. bufferGPU,
  39220. bufferType,
  39221. type,
  39222. byteLength: array.byteLength,
  39223. bytesPerElement: array.BYTES_PER_ELEMENT,
  39224. version: attribute.version,
  39225. pbo: attribute.pbo,
  39226. isInteger: type === gl.INT || type === gl.UNSIGNED_INT || attribute.gpuType === IntType,
  39227. id: _id$1 ++
  39228. };
  39229. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) {
  39230. // create buffer for tranform feedback use
  39231. const bufferGPUDual = this._createBuffer( gl, bufferType, array, usage );
  39232. attributeData = new DualAttributeData( attributeData, bufferGPUDual );
  39233. }
  39234. backend.set( attribute, attributeData );
  39235. }
  39236. updateAttribute( attribute ) {
  39237. const backend = this.backend;
  39238. const { gl } = backend;
  39239. const array = attribute.array;
  39240. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  39241. const bufferData = backend.get( bufferAttribute );
  39242. const bufferType = bufferData.bufferType;
  39243. const updateRanges = attribute.isInterleavedBufferAttribute ? attribute.data.updateRanges : attribute.updateRanges;
  39244. gl.bindBuffer( bufferType, bufferData.bufferGPU );
  39245. if ( updateRanges.length === 0 ) {
  39246. // Not using update ranges
  39247. gl.bufferSubData( bufferType, 0, array );
  39248. } else {
  39249. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  39250. const range = updateRanges[ i ];
  39251. gl.bufferSubData( bufferType, range.start * array.BYTES_PER_ELEMENT,
  39252. array, range.start, range.count );
  39253. }
  39254. bufferAttribute.clearUpdateRanges();
  39255. }
  39256. gl.bindBuffer( bufferType, null );
  39257. bufferData.version = bufferAttribute.version;
  39258. }
  39259. destroyAttribute( attribute ) {
  39260. const backend = this.backend;
  39261. const { gl } = backend;
  39262. if ( attribute.isInterleavedBufferAttribute ) {
  39263. backend.delete( attribute.data );
  39264. }
  39265. const attributeData = backend.get( attribute );
  39266. gl.deleteBuffer( attributeData.bufferGPU );
  39267. backend.delete( attribute );
  39268. }
  39269. async getArrayBufferAsync( attribute ) {
  39270. const backend = this.backend;
  39271. const { gl } = backend;
  39272. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  39273. const { bufferGPU } = backend.get( bufferAttribute );
  39274. const array = attribute.array;
  39275. const byteLength = array.byteLength;
  39276. gl.bindBuffer( gl.COPY_READ_BUFFER, bufferGPU );
  39277. const writeBuffer = gl.createBuffer();
  39278. gl.bindBuffer( gl.COPY_WRITE_BUFFER, writeBuffer );
  39279. gl.bufferData( gl.COPY_WRITE_BUFFER, byteLength, gl.STREAM_READ );
  39280. gl.copyBufferSubData( gl.COPY_READ_BUFFER, gl.COPY_WRITE_BUFFER, 0, 0, byteLength );
  39281. await backend.utils._clientWaitAsync();
  39282. const dstBuffer = new attribute.array.constructor( array.length );
  39283. // Ensure the buffer is bound before reading
  39284. gl.bindBuffer( gl.COPY_WRITE_BUFFER, writeBuffer );
  39285. gl.getBufferSubData( gl.COPY_WRITE_BUFFER, 0, dstBuffer );
  39286. gl.deleteBuffer( writeBuffer );
  39287. gl.bindBuffer( gl.COPY_READ_BUFFER, null );
  39288. gl.bindBuffer( gl.COPY_WRITE_BUFFER, null );
  39289. return dstBuffer.buffer;
  39290. }
  39291. _createBuffer( gl, bufferType, array, usage ) {
  39292. const bufferGPU = gl.createBuffer();
  39293. gl.bindBuffer( bufferType, bufferGPU );
  39294. gl.bufferData( bufferType, array, usage );
  39295. gl.bindBuffer( bufferType, null );
  39296. return bufferGPU;
  39297. }
  39298. }
  39299. let initialized$1 = false, equationToGL, factorToGL;
  39300. class WebGLState {
  39301. constructor( backend ) {
  39302. this.backend = backend;
  39303. this.gl = this.backend.gl;
  39304. this.enabled = {};
  39305. this.currentFlipSided = null;
  39306. this.currentCullFace = null;
  39307. this.currentProgram = null;
  39308. this.currentBlendingEnabled = false;
  39309. this.currentBlending = null;
  39310. this.currentBlendSrc = null;
  39311. this.currentBlendDst = null;
  39312. this.currentBlendSrcAlpha = null;
  39313. this.currentBlendDstAlpha = null;
  39314. this.currentPremultipledAlpha = null;
  39315. this.currentPolygonOffsetFactor = null;
  39316. this.currentPolygonOffsetUnits = null;
  39317. this.currentColorMask = null;
  39318. this.currentDepthFunc = null;
  39319. this.currentDepthMask = null;
  39320. this.currentStencilFunc = null;
  39321. this.currentStencilRef = null;
  39322. this.currentStencilFuncMask = null;
  39323. this.currentStencilFail = null;
  39324. this.currentStencilZFail = null;
  39325. this.currentStencilZPass = null;
  39326. this.currentStencilMask = null;
  39327. this.currentLineWidth = null;
  39328. this.currentBoundFramebuffers = {};
  39329. this.currentDrawbuffers = new WeakMap();
  39330. this.maxTextures = this.gl.getParameter( this.gl.MAX_TEXTURE_IMAGE_UNITS );
  39331. this.currentTextureSlot = null;
  39332. this.currentBoundTextures = {};
  39333. this.currentBoundBufferBases = {};
  39334. if ( initialized$1 === false ) {
  39335. this._init( this.gl );
  39336. initialized$1 = true;
  39337. }
  39338. }
  39339. _init( gl ) {
  39340. // Store only WebGL constants here.
  39341. equationToGL = {
  39342. [ AddEquation ]: gl.FUNC_ADD,
  39343. [ SubtractEquation ]: gl.FUNC_SUBTRACT,
  39344. [ ReverseSubtractEquation ]: gl.FUNC_REVERSE_SUBTRACT
  39345. };
  39346. factorToGL = {
  39347. [ ZeroFactor ]: gl.ZERO,
  39348. [ OneFactor ]: gl.ONE,
  39349. [ SrcColorFactor ]: gl.SRC_COLOR,
  39350. [ SrcAlphaFactor ]: gl.SRC_ALPHA,
  39351. [ SrcAlphaSaturateFactor ]: gl.SRC_ALPHA_SATURATE,
  39352. [ DstColorFactor ]: gl.DST_COLOR,
  39353. [ DstAlphaFactor ]: gl.DST_ALPHA,
  39354. [ OneMinusSrcColorFactor ]: gl.ONE_MINUS_SRC_COLOR,
  39355. [ OneMinusSrcAlphaFactor ]: gl.ONE_MINUS_SRC_ALPHA,
  39356. [ OneMinusDstColorFactor ]: gl.ONE_MINUS_DST_COLOR,
  39357. [ OneMinusDstAlphaFactor ]: gl.ONE_MINUS_DST_ALPHA
  39358. };
  39359. }
  39360. enable( id ) {
  39361. const { enabled } = this;
  39362. if ( enabled[ id ] !== true ) {
  39363. this.gl.enable( id );
  39364. enabled[ id ] = true;
  39365. }
  39366. }
  39367. disable( id ) {
  39368. const { enabled } = this;
  39369. if ( enabled[ id ] !== false ) {
  39370. this.gl.disable( id );
  39371. enabled[ id ] = false;
  39372. }
  39373. }
  39374. setFlipSided( flipSided ) {
  39375. if ( this.currentFlipSided !== flipSided ) {
  39376. const { gl } = this;
  39377. if ( flipSided ) {
  39378. gl.frontFace( gl.CW );
  39379. } else {
  39380. gl.frontFace( gl.CCW );
  39381. }
  39382. this.currentFlipSided = flipSided;
  39383. }
  39384. }
  39385. setCullFace( cullFace ) {
  39386. const { gl } = this;
  39387. if ( cullFace !== CullFaceNone ) {
  39388. this.enable( gl.CULL_FACE );
  39389. if ( cullFace !== this.currentCullFace ) {
  39390. if ( cullFace === CullFaceBack ) {
  39391. gl.cullFace( gl.BACK );
  39392. } else if ( cullFace === CullFaceFront ) {
  39393. gl.cullFace( gl.FRONT );
  39394. } else {
  39395. gl.cullFace( gl.FRONT_AND_BACK );
  39396. }
  39397. }
  39398. } else {
  39399. this.disable( gl.CULL_FACE );
  39400. }
  39401. this.currentCullFace = cullFace;
  39402. }
  39403. setLineWidth( width ) {
  39404. const { currentLineWidth, gl } = this;
  39405. if ( width !== currentLineWidth ) {
  39406. gl.lineWidth( width );
  39407. this.currentLineWidth = width;
  39408. }
  39409. }
  39410. setBlending( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha ) {
  39411. const { gl } = this;
  39412. if ( blending === NoBlending ) {
  39413. if ( this.currentBlendingEnabled === true ) {
  39414. this.disable( gl.BLEND );
  39415. this.currentBlendingEnabled = false;
  39416. }
  39417. return;
  39418. }
  39419. if ( this.currentBlendingEnabled === false ) {
  39420. this.enable( gl.BLEND );
  39421. this.currentBlendingEnabled = true;
  39422. }
  39423. if ( blending !== CustomBlending ) {
  39424. if ( blending !== this.currentBlending || premultipliedAlpha !== this.currentPremultipledAlpha ) {
  39425. if ( this.currentBlendEquation !== AddEquation || this.currentBlendEquationAlpha !== AddEquation ) {
  39426. gl.blendEquation( gl.FUNC_ADD );
  39427. this.currentBlendEquation = AddEquation;
  39428. this.currentBlendEquationAlpha = AddEquation;
  39429. }
  39430. if ( premultipliedAlpha ) {
  39431. switch ( blending ) {
  39432. case NormalBlending:
  39433. gl.blendFuncSeparate( gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  39434. break;
  39435. case AdditiveBlending:
  39436. gl.blendFunc( gl.ONE, gl.ONE );
  39437. break;
  39438. case SubtractiveBlending:
  39439. gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  39440. break;
  39441. case MultiplyBlending:
  39442. gl.blendFuncSeparate( gl.ZERO, gl.SRC_COLOR, gl.ZERO, gl.SRC_ALPHA );
  39443. break;
  39444. default:
  39445. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  39446. break;
  39447. }
  39448. } else {
  39449. switch ( blending ) {
  39450. case NormalBlending:
  39451. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  39452. break;
  39453. case AdditiveBlending:
  39454. gl.blendFunc( gl.SRC_ALPHA, gl.ONE );
  39455. break;
  39456. case SubtractiveBlending:
  39457. gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  39458. break;
  39459. case MultiplyBlending:
  39460. gl.blendFunc( gl.ZERO, gl.SRC_COLOR );
  39461. break;
  39462. default:
  39463. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  39464. break;
  39465. }
  39466. }
  39467. this.currentBlendSrc = null;
  39468. this.currentBlendDst = null;
  39469. this.currentBlendSrcAlpha = null;
  39470. this.currentBlendDstAlpha = null;
  39471. this.currentBlending = blending;
  39472. this.currentPremultipledAlpha = premultipliedAlpha;
  39473. }
  39474. return;
  39475. }
  39476. // custom blending
  39477. blendEquationAlpha = blendEquationAlpha || blendEquation;
  39478. blendSrcAlpha = blendSrcAlpha || blendSrc;
  39479. blendDstAlpha = blendDstAlpha || blendDst;
  39480. if ( blendEquation !== this.currentBlendEquation || blendEquationAlpha !== this.currentBlendEquationAlpha ) {
  39481. gl.blendEquationSeparate( equationToGL[ blendEquation ], equationToGL[ blendEquationAlpha ] );
  39482. this.currentBlendEquation = blendEquation;
  39483. this.currentBlendEquationAlpha = blendEquationAlpha;
  39484. }
  39485. if ( blendSrc !== this.currentBlendSrc || blendDst !== this.currentBlendDst || blendSrcAlpha !== this.currentBlendSrcAlpha || blendDstAlpha !== this.currentBlendDstAlpha ) {
  39486. gl.blendFuncSeparate( factorToGL[ blendSrc ], factorToGL[ blendDst ], factorToGL[ blendSrcAlpha ], factorToGL[ blendDstAlpha ] );
  39487. this.currentBlendSrc = blendSrc;
  39488. this.currentBlendDst = blendDst;
  39489. this.currentBlendSrcAlpha = blendSrcAlpha;
  39490. this.currentBlendDstAlpha = blendDstAlpha;
  39491. }
  39492. this.currentBlending = blending;
  39493. this.currentPremultipledAlpha = false;
  39494. }
  39495. setColorMask( colorMask ) {
  39496. if ( this.currentColorMask !== colorMask ) {
  39497. this.gl.colorMask( colorMask, colorMask, colorMask, colorMask );
  39498. this.currentColorMask = colorMask;
  39499. }
  39500. }
  39501. setDepthTest( depthTest ) {
  39502. const { gl } = this;
  39503. if ( depthTest ) {
  39504. this.enable( gl.DEPTH_TEST );
  39505. } else {
  39506. this.disable( gl.DEPTH_TEST );
  39507. }
  39508. }
  39509. setDepthMask( depthMask ) {
  39510. if ( this.currentDepthMask !== depthMask ) {
  39511. this.gl.depthMask( depthMask );
  39512. this.currentDepthMask = depthMask;
  39513. }
  39514. }
  39515. setDepthFunc( depthFunc ) {
  39516. if ( this.currentDepthFunc !== depthFunc ) {
  39517. const { gl } = this;
  39518. switch ( depthFunc ) {
  39519. case NeverDepth:
  39520. gl.depthFunc( gl.NEVER );
  39521. break;
  39522. case AlwaysDepth:
  39523. gl.depthFunc( gl.ALWAYS );
  39524. break;
  39525. case LessDepth:
  39526. gl.depthFunc( gl.LESS );
  39527. break;
  39528. case LessEqualDepth:
  39529. gl.depthFunc( gl.LEQUAL );
  39530. break;
  39531. case EqualDepth:
  39532. gl.depthFunc( gl.EQUAL );
  39533. break;
  39534. case GreaterEqualDepth:
  39535. gl.depthFunc( gl.GEQUAL );
  39536. break;
  39537. case GreaterDepth:
  39538. gl.depthFunc( gl.GREATER );
  39539. break;
  39540. case NotEqualDepth:
  39541. gl.depthFunc( gl.NOTEQUAL );
  39542. break;
  39543. default:
  39544. gl.depthFunc( gl.LEQUAL );
  39545. }
  39546. this.currentDepthFunc = depthFunc;
  39547. }
  39548. }
  39549. setStencilTest( stencilTest ) {
  39550. const { gl } = this;
  39551. if ( stencilTest ) {
  39552. this.enable( gl.STENCIL_TEST );
  39553. } else {
  39554. this.disable( gl.STENCIL_TEST );
  39555. }
  39556. }
  39557. setStencilMask( stencilMask ) {
  39558. if ( this.currentStencilMask !== stencilMask ) {
  39559. this.gl.stencilMask( stencilMask );
  39560. this.currentStencilMask = stencilMask;
  39561. }
  39562. }
  39563. setStencilFunc( stencilFunc, stencilRef, stencilMask ) {
  39564. if ( this.currentStencilFunc !== stencilFunc ||
  39565. this.currentStencilRef !== stencilRef ||
  39566. this.currentStencilFuncMask !== stencilMask ) {
  39567. this.gl.stencilFunc( stencilFunc, stencilRef, stencilMask );
  39568. this.currentStencilFunc = stencilFunc;
  39569. this.currentStencilRef = stencilRef;
  39570. this.currentStencilFuncMask = stencilMask;
  39571. }
  39572. }
  39573. setStencilOp( stencilFail, stencilZFail, stencilZPass ) {
  39574. if ( this.currentStencilFail !== stencilFail ||
  39575. this.currentStencilZFail !== stencilZFail ||
  39576. this.currentStencilZPass !== stencilZPass ) {
  39577. this.gl.stencilOp( stencilFail, stencilZFail, stencilZPass );
  39578. this.currentStencilFail = stencilFail;
  39579. this.currentStencilZFail = stencilZFail;
  39580. this.currentStencilZPass = stencilZPass;
  39581. }
  39582. }
  39583. setMaterial( material, frontFaceCW ) {
  39584. const { gl } = this;
  39585. material.side === DoubleSide
  39586. ? this.disable( gl.CULL_FACE )
  39587. : this.enable( gl.CULL_FACE );
  39588. let flipSided = ( material.side === BackSide );
  39589. if ( frontFaceCW ) flipSided = ! flipSided;
  39590. this.setFlipSided( flipSided );
  39591. ( material.blending === NormalBlending && material.transparent === false )
  39592. ? this.setBlending( NoBlending )
  39593. : this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha );
  39594. this.setDepthFunc( material.depthFunc );
  39595. this.setDepthTest( material.depthTest );
  39596. this.setDepthMask( material.depthWrite );
  39597. this.setColorMask( material.colorWrite );
  39598. const stencilWrite = material.stencilWrite;
  39599. this.setStencilTest( stencilWrite );
  39600. if ( stencilWrite ) {
  39601. this.setStencilMask( material.stencilWriteMask );
  39602. this.setStencilFunc( material.stencilFunc, material.stencilRef, material.stencilFuncMask );
  39603. this.setStencilOp( material.stencilFail, material.stencilZFail, material.stencilZPass );
  39604. }
  39605. this.setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  39606. material.alphaToCoverage === true && this.backend.renderer.samples > 1
  39607. ? this.enable( gl.SAMPLE_ALPHA_TO_COVERAGE )
  39608. : this.disable( gl.SAMPLE_ALPHA_TO_COVERAGE );
  39609. }
  39610. setPolygonOffset( polygonOffset, factor, units ) {
  39611. const { gl } = this;
  39612. if ( polygonOffset ) {
  39613. this.enable( gl.POLYGON_OFFSET_FILL );
  39614. if ( this.currentPolygonOffsetFactor !== factor || this.currentPolygonOffsetUnits !== units ) {
  39615. gl.polygonOffset( factor, units );
  39616. this.currentPolygonOffsetFactor = factor;
  39617. this.currentPolygonOffsetUnits = units;
  39618. }
  39619. } else {
  39620. this.disable( gl.POLYGON_OFFSET_FILL );
  39621. }
  39622. }
  39623. useProgram( program ) {
  39624. if ( this.currentProgram !== program ) {
  39625. this.gl.useProgram( program );
  39626. this.currentProgram = program;
  39627. return true;
  39628. }
  39629. return false;
  39630. }
  39631. // framebuffer
  39632. bindFramebuffer( target, framebuffer ) {
  39633. const { gl, currentBoundFramebuffers } = this;
  39634. if ( currentBoundFramebuffers[ target ] !== framebuffer ) {
  39635. gl.bindFramebuffer( target, framebuffer );
  39636. currentBoundFramebuffers[ target ] = framebuffer;
  39637. // gl.DRAW_FRAMEBUFFER is equivalent to gl.FRAMEBUFFER
  39638. if ( target === gl.DRAW_FRAMEBUFFER ) {
  39639. currentBoundFramebuffers[ gl.FRAMEBUFFER ] = framebuffer;
  39640. }
  39641. if ( target === gl.FRAMEBUFFER ) {
  39642. currentBoundFramebuffers[ gl.DRAW_FRAMEBUFFER ] = framebuffer;
  39643. }
  39644. return true;
  39645. }
  39646. return false;
  39647. }
  39648. drawBuffers( renderContext, framebuffer ) {
  39649. const { gl } = this;
  39650. let drawBuffers = [];
  39651. let needsUpdate = false;
  39652. if ( renderContext.textures !== null ) {
  39653. drawBuffers = this.currentDrawbuffers.get( framebuffer );
  39654. if ( drawBuffers === undefined ) {
  39655. drawBuffers = [];
  39656. this.currentDrawbuffers.set( framebuffer, drawBuffers );
  39657. }
  39658. const textures = renderContext.textures;
  39659. if ( drawBuffers.length !== textures.length || drawBuffers[ 0 ] !== gl.COLOR_ATTACHMENT0 ) {
  39660. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  39661. drawBuffers[ i ] = gl.COLOR_ATTACHMENT0 + i;
  39662. }
  39663. drawBuffers.length = textures.length;
  39664. needsUpdate = true;
  39665. }
  39666. } else {
  39667. if ( drawBuffers[ 0 ] !== gl.BACK ) {
  39668. drawBuffers[ 0 ] = gl.BACK;
  39669. needsUpdate = true;
  39670. }
  39671. }
  39672. if ( needsUpdate ) {
  39673. gl.drawBuffers( drawBuffers );
  39674. }
  39675. }
  39676. // texture
  39677. activeTexture( webglSlot ) {
  39678. const { gl, currentTextureSlot, maxTextures } = this;
  39679. if ( webglSlot === undefined ) webglSlot = gl.TEXTURE0 + maxTextures - 1;
  39680. if ( currentTextureSlot !== webglSlot ) {
  39681. gl.activeTexture( webglSlot );
  39682. this.currentTextureSlot = webglSlot;
  39683. }
  39684. }
  39685. bindTexture( webglType, webglTexture, webglSlot ) {
  39686. const { gl, currentTextureSlot, currentBoundTextures, maxTextures } = this;
  39687. if ( webglSlot === undefined ) {
  39688. if ( currentTextureSlot === null ) {
  39689. webglSlot = gl.TEXTURE0 + maxTextures - 1;
  39690. } else {
  39691. webglSlot = currentTextureSlot;
  39692. }
  39693. }
  39694. let boundTexture = currentBoundTextures[ webglSlot ];
  39695. if ( boundTexture === undefined ) {
  39696. boundTexture = { type: undefined, texture: undefined };
  39697. currentBoundTextures[ webglSlot ] = boundTexture;
  39698. }
  39699. if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) {
  39700. if ( currentTextureSlot !== webglSlot ) {
  39701. gl.activeTexture( webglSlot );
  39702. this.currentTextureSlot = webglSlot;
  39703. }
  39704. gl.bindTexture( webglType, webglTexture );
  39705. boundTexture.type = webglType;
  39706. boundTexture.texture = webglTexture;
  39707. }
  39708. }
  39709. bindBufferBase( target, index, buffer ) {
  39710. const { gl } = this;
  39711. const key = `${target}-${index}`;
  39712. if ( this.currentBoundBufferBases[ key ] !== buffer ) {
  39713. gl.bindBufferBase( target, index, buffer );
  39714. this.currentBoundBufferBases[ key ] = buffer;
  39715. return true;
  39716. }
  39717. return false;
  39718. }
  39719. unbindTexture() {
  39720. const { gl, currentTextureSlot, currentBoundTextures } = this;
  39721. const boundTexture = currentBoundTextures[ currentTextureSlot ];
  39722. if ( boundTexture !== undefined && boundTexture.type !== undefined ) {
  39723. gl.bindTexture( boundTexture.type, null );
  39724. boundTexture.type = undefined;
  39725. boundTexture.texture = undefined;
  39726. }
  39727. }
  39728. }
  39729. class WebGLUtils {
  39730. constructor( backend ) {
  39731. this.backend = backend;
  39732. this.gl = this.backend.gl;
  39733. this.extensions = backend.extensions;
  39734. }
  39735. convert( p, colorSpace = NoColorSpace ) {
  39736. const { gl, extensions } = this;
  39737. let extension;
  39738. if ( p === UnsignedByteType ) return gl.UNSIGNED_BYTE;
  39739. if ( p === UnsignedShort4444Type ) return gl.UNSIGNED_SHORT_4_4_4_4;
  39740. if ( p === UnsignedShort5551Type ) return gl.UNSIGNED_SHORT_5_5_5_1;
  39741. if ( p === UnsignedInt5999Type ) return gl.UNSIGNED_INT_5_9_9_9_REV;
  39742. if ( p === ByteType ) return gl.BYTE;
  39743. if ( p === ShortType ) return gl.SHORT;
  39744. if ( p === UnsignedShortType ) return gl.UNSIGNED_SHORT;
  39745. if ( p === IntType ) return gl.INT;
  39746. if ( p === UnsignedIntType ) return gl.UNSIGNED_INT;
  39747. if ( p === FloatType ) return gl.FLOAT;
  39748. if ( p === HalfFloatType ) {
  39749. return gl.HALF_FLOAT;
  39750. }
  39751. if ( p === AlphaFormat ) return gl.ALPHA;
  39752. if ( p === RGBFormat ) return gl.RGB;
  39753. if ( p === RGBAFormat ) return gl.RGBA;
  39754. if ( p === LuminanceFormat ) return gl.LUMINANCE;
  39755. if ( p === LuminanceAlphaFormat ) return gl.LUMINANCE_ALPHA;
  39756. if ( p === DepthFormat ) return gl.DEPTH_COMPONENT;
  39757. if ( p === DepthStencilFormat ) return gl.DEPTH_STENCIL;
  39758. // WebGL2 formats.
  39759. if ( p === RedFormat ) return gl.RED;
  39760. if ( p === RedIntegerFormat ) return gl.RED_INTEGER;
  39761. if ( p === RGFormat ) return gl.RG;
  39762. if ( p === RGIntegerFormat ) return gl.RG_INTEGER;
  39763. if ( p === RGBAIntegerFormat ) return gl.RGBA_INTEGER;
  39764. // S3TC
  39765. if ( p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format ) {
  39766. if ( colorSpace === SRGBColorSpace ) {
  39767. extension = extensions.get( 'WEBGL_compressed_texture_s3tc_srgb' );
  39768. if ( extension !== null ) {
  39769. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_S3TC_DXT1_EXT;
  39770. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;
  39771. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;
  39772. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT;
  39773. } else {
  39774. return null;
  39775. }
  39776. } else {
  39777. extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
  39778. if ( extension !== null ) {
  39779. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  39780. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  39781. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  39782. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  39783. } else {
  39784. return null;
  39785. }
  39786. }
  39787. }
  39788. // PVRTC
  39789. if ( p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format ) {
  39790. extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  39791. if ( extension !== null ) {
  39792. if ( p === RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  39793. if ( p === RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  39794. if ( p === RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  39795. if ( p === RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  39796. } else {
  39797. return null;
  39798. }
  39799. }
  39800. // ETC
  39801. if ( p === RGB_ETC1_Format || p === RGB_ETC2_Format || p === RGBA_ETC2_EAC_Format ) {
  39802. extension = extensions.get( 'WEBGL_compressed_texture_etc' );
  39803. if ( extension !== null ) {
  39804. if ( p === RGB_ETC1_Format || p === RGB_ETC2_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ETC2 : extension.COMPRESSED_RGB8_ETC2;
  39805. if ( p === RGBA_ETC2_EAC_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC : extension.COMPRESSED_RGBA8_ETC2_EAC;
  39806. } else {
  39807. return null;
  39808. }
  39809. }
  39810. // ASTC
  39811. if ( p === RGBA_ASTC_4x4_Format || p === RGBA_ASTC_5x4_Format || p === RGBA_ASTC_5x5_Format ||
  39812. p === RGBA_ASTC_6x5_Format || p === RGBA_ASTC_6x6_Format || p === RGBA_ASTC_8x5_Format ||
  39813. p === RGBA_ASTC_8x6_Format || p === RGBA_ASTC_8x8_Format || p === RGBA_ASTC_10x5_Format ||
  39814. p === RGBA_ASTC_10x6_Format || p === RGBA_ASTC_10x8_Format || p === RGBA_ASTC_10x10_Format ||
  39815. p === RGBA_ASTC_12x10_Format || p === RGBA_ASTC_12x12_Format ) {
  39816. extension = extensions.get( 'WEBGL_compressed_texture_astc' );
  39817. if ( extension !== null ) {
  39818. if ( p === RGBA_ASTC_4x4_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR : extension.COMPRESSED_RGBA_ASTC_4x4_KHR;
  39819. if ( p === RGBA_ASTC_5x4_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR : extension.COMPRESSED_RGBA_ASTC_5x4_KHR;
  39820. if ( p === RGBA_ASTC_5x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR : extension.COMPRESSED_RGBA_ASTC_5x5_KHR;
  39821. if ( p === RGBA_ASTC_6x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR : extension.COMPRESSED_RGBA_ASTC_6x5_KHR;
  39822. if ( p === RGBA_ASTC_6x6_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR : extension.COMPRESSED_RGBA_ASTC_6x6_KHR;
  39823. if ( p === RGBA_ASTC_8x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR : extension.COMPRESSED_RGBA_ASTC_8x5_KHR;
  39824. if ( p === RGBA_ASTC_8x6_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR : extension.COMPRESSED_RGBA_ASTC_8x6_KHR;
  39825. if ( p === RGBA_ASTC_8x8_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR : extension.COMPRESSED_RGBA_ASTC_8x8_KHR;
  39826. if ( p === RGBA_ASTC_10x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR : extension.COMPRESSED_RGBA_ASTC_10x5_KHR;
  39827. if ( p === RGBA_ASTC_10x6_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR : extension.COMPRESSED_RGBA_ASTC_10x6_KHR;
  39828. if ( p === RGBA_ASTC_10x8_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR : extension.COMPRESSED_RGBA_ASTC_10x8_KHR;
  39829. if ( p === RGBA_ASTC_10x10_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR : extension.COMPRESSED_RGBA_ASTC_10x10_KHR;
  39830. if ( p === RGBA_ASTC_12x10_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR : extension.COMPRESSED_RGBA_ASTC_12x10_KHR;
  39831. if ( p === RGBA_ASTC_12x12_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR : extension.COMPRESSED_RGBA_ASTC_12x12_KHR;
  39832. } else {
  39833. return null;
  39834. }
  39835. }
  39836. // BPTC
  39837. if ( p === RGBA_BPTC_Format ) {
  39838. extension = extensions.get( 'EXT_texture_compression_bptc' );
  39839. if ( extension !== null ) {
  39840. if ( p === RGBA_BPTC_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT : extension.COMPRESSED_RGBA_BPTC_UNORM_EXT;
  39841. } else {
  39842. return null;
  39843. }
  39844. }
  39845. // RGTC
  39846. if ( p === RED_RGTC1_Format || p === SIGNED_RED_RGTC1_Format || p === RED_GREEN_RGTC2_Format || p === SIGNED_RED_GREEN_RGTC2_Format ) {
  39847. extension = extensions.get( 'EXT_texture_compression_rgtc' );
  39848. if ( extension !== null ) {
  39849. if ( p === RGBA_BPTC_Format ) return extension.COMPRESSED_RED_RGTC1_EXT;
  39850. if ( p === SIGNED_RED_RGTC1_Format ) return extension.COMPRESSED_SIGNED_RED_RGTC1_EXT;
  39851. if ( p === RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_RED_GREEN_RGTC2_EXT;
  39852. if ( p === SIGNED_RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT;
  39853. } else {
  39854. return null;
  39855. }
  39856. }
  39857. //
  39858. if ( p === UnsignedInt248Type ) {
  39859. return gl.UNSIGNED_INT_24_8;
  39860. }
  39861. // if "p" can't be resolved, assume the user defines a WebGL constant as a string (fallback/workaround for packed RGB formats)
  39862. return ( gl[ p ] !== undefined ) ? gl[ p ] : null;
  39863. }
  39864. _clientWaitAsync() {
  39865. const { gl } = this;
  39866. const sync = gl.fenceSync( gl.SYNC_GPU_COMMANDS_COMPLETE, 0 );
  39867. gl.flush();
  39868. return new Promise( ( resolve, reject ) => {
  39869. function test() {
  39870. const res = gl.clientWaitSync( sync, gl.SYNC_FLUSH_COMMANDS_BIT, 0 );
  39871. if ( res === gl.WAIT_FAILED ) {
  39872. gl.deleteSync( sync );
  39873. reject();
  39874. return;
  39875. }
  39876. if ( res === gl.TIMEOUT_EXPIRED ) {
  39877. requestAnimationFrame( test );
  39878. return;
  39879. }
  39880. gl.deleteSync( sync );
  39881. resolve();
  39882. }
  39883. test();
  39884. } );
  39885. }
  39886. }
  39887. let initialized = false, wrappingToGL, filterToGL, compareToGL;
  39888. class WebGLTextureUtils {
  39889. constructor( backend ) {
  39890. this.backend = backend;
  39891. this.gl = backend.gl;
  39892. this.extensions = backend.extensions;
  39893. this.defaultTextures = {};
  39894. if ( initialized === false ) {
  39895. this._init( this.gl );
  39896. initialized = true;
  39897. }
  39898. }
  39899. _init( gl ) {
  39900. // Store only WebGL constants here.
  39901. wrappingToGL = {
  39902. [ RepeatWrapping ]: gl.REPEAT,
  39903. [ ClampToEdgeWrapping ]: gl.CLAMP_TO_EDGE,
  39904. [ MirroredRepeatWrapping ]: gl.MIRRORED_REPEAT
  39905. };
  39906. filterToGL = {
  39907. [ NearestFilter ]: gl.NEAREST,
  39908. [ NearestMipmapNearestFilter ]: gl.NEAREST_MIPMAP_NEAREST,
  39909. [ NearestMipmapLinearFilter ]: gl.NEAREST_MIPMAP_LINEAR,
  39910. [ LinearFilter ]: gl.LINEAR,
  39911. [ LinearMipmapNearestFilter ]: gl.LINEAR_MIPMAP_NEAREST,
  39912. [ LinearMipmapLinearFilter ]: gl.LINEAR_MIPMAP_LINEAR
  39913. };
  39914. compareToGL = {
  39915. [ NeverCompare ]: gl.NEVER,
  39916. [ AlwaysCompare ]: gl.ALWAYS,
  39917. [ LessCompare ]: gl.LESS,
  39918. [ LessEqualCompare ]: gl.LEQUAL,
  39919. [ EqualCompare ]: gl.EQUAL,
  39920. [ GreaterEqualCompare ]: gl.GEQUAL,
  39921. [ GreaterCompare ]: gl.GREATER,
  39922. [ NotEqualCompare ]: gl.NOTEQUAL
  39923. };
  39924. }
  39925. filterFallback( f ) {
  39926. const { gl } = this;
  39927. if ( f === NearestFilter || f === NearestMipmapNearestFilter || f === NearestMipmapLinearFilter ) {
  39928. return gl.NEAREST;
  39929. }
  39930. return gl.LINEAR;
  39931. }
  39932. getGLTextureType( texture ) {
  39933. const { gl } = this;
  39934. let glTextureType;
  39935. if ( texture.isCubeTexture === true ) {
  39936. glTextureType = gl.TEXTURE_CUBE_MAP;
  39937. } else if ( texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  39938. glTextureType = gl.TEXTURE_2D_ARRAY;
  39939. } else if ( texture.isData3DTexture === true ) { // TODO: isCompressed3DTexture, wait for #26642
  39940. glTextureType = gl.TEXTURE_3D;
  39941. } else {
  39942. glTextureType = gl.TEXTURE_2D;
  39943. }
  39944. return glTextureType;
  39945. }
  39946. getInternalFormat( internalFormatName, glFormat, glType, colorSpace, forceLinearTransfer = false ) {
  39947. const { gl, extensions } = this;
  39948. if ( internalFormatName !== null ) {
  39949. if ( gl[ internalFormatName ] !== undefined ) return gl[ internalFormatName ];
  39950. console.warn( 'THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\'' );
  39951. }
  39952. let internalFormat = glFormat;
  39953. if ( glFormat === gl.RED ) {
  39954. if ( glType === gl.FLOAT ) internalFormat = gl.R32F;
  39955. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.R16F;
  39956. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.R8;
  39957. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.R16;
  39958. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.R32UI;
  39959. if ( glType === gl.BYTE ) internalFormat = gl.R8I;
  39960. if ( glType === gl.SHORT ) internalFormat = gl.R16I;
  39961. if ( glType === gl.INT ) internalFormat = gl.R32I;
  39962. }
  39963. if ( glFormat === gl.RED_INTEGER ) {
  39964. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.R8UI;
  39965. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.R16UI;
  39966. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.R32UI;
  39967. if ( glType === gl.BYTE ) internalFormat = gl.R8I;
  39968. if ( glType === gl.SHORT ) internalFormat = gl.R16I;
  39969. if ( glType === gl.INT ) internalFormat = gl.R32I;
  39970. }
  39971. if ( glFormat === gl.RG ) {
  39972. if ( glType === gl.FLOAT ) internalFormat = gl.RG32F;
  39973. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RG16F;
  39974. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RG8;
  39975. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RG16;
  39976. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RG32UI;
  39977. if ( glType === gl.BYTE ) internalFormat = gl.RG8I;
  39978. if ( glType === gl.SHORT ) internalFormat = gl.RG16I;
  39979. if ( glType === gl.INT ) internalFormat = gl.RG32I;
  39980. }
  39981. if ( glFormat === gl.RG_INTEGER ) {
  39982. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RG8UI;
  39983. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RG16UI;
  39984. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RG32UI;
  39985. if ( glType === gl.BYTE ) internalFormat = gl.RG8I;
  39986. if ( glType === gl.SHORT ) internalFormat = gl.RG16I;
  39987. if ( glType === gl.INT ) internalFormat = gl.RG32I;
  39988. }
  39989. if ( glFormat === gl.RGB ) {
  39990. if ( glType === gl.FLOAT ) internalFormat = gl.RGB32F;
  39991. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RGB16F;
  39992. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGB8;
  39993. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGB16;
  39994. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGB32UI;
  39995. if ( glType === gl.BYTE ) internalFormat = gl.RGB8I;
  39996. if ( glType === gl.SHORT ) internalFormat = gl.RGB16I;
  39997. if ( glType === gl.INT ) internalFormat = gl.RGB32I;
  39998. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = ( colorSpace === SRGBColorSpace && forceLinearTransfer === false ) ? gl.SRGB8 : gl.RGB8;
  39999. if ( glType === gl.UNSIGNED_SHORT_5_6_5 ) internalFormat = gl.RGB565;
  40000. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = gl.RGB5_A1;
  40001. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = gl.RGB4;
  40002. if ( glType === gl.UNSIGNED_INT_5_9_9_9_REV ) internalFormat = gl.RGB9_E5;
  40003. }
  40004. if ( glFormat === gl.RGB_INTEGER ) {
  40005. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGB8UI;
  40006. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGB16UI;
  40007. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGB32UI;
  40008. if ( glType === gl.BYTE ) internalFormat = gl.RGB8I;
  40009. if ( glType === gl.SHORT ) internalFormat = gl.RGB16I;
  40010. if ( glType === gl.INT ) internalFormat = gl.RGB32I;
  40011. }
  40012. if ( glFormat === gl.RGBA ) {
  40013. if ( glType === gl.FLOAT ) internalFormat = gl.RGBA32F;
  40014. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RGBA16F;
  40015. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGBA8;
  40016. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGBA16;
  40017. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGBA32UI;
  40018. if ( glType === gl.BYTE ) internalFormat = gl.RGBA8I;
  40019. if ( glType === gl.SHORT ) internalFormat = gl.RGBA16I;
  40020. if ( glType === gl.INT ) internalFormat = gl.RGBA32I;
  40021. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = ( colorSpace === SRGBColorSpace && forceLinearTransfer === false ) ? gl.SRGB8_ALPHA8 : gl.RGBA8;
  40022. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = gl.RGBA4;
  40023. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = gl.RGB5_A1;
  40024. }
  40025. if ( glFormat === gl.RGBA_INTEGER ) {
  40026. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGBA8UI;
  40027. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGBA16UI;
  40028. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGBA32UI;
  40029. if ( glType === gl.BYTE ) internalFormat = gl.RGBA8I;
  40030. if ( glType === gl.SHORT ) internalFormat = gl.RGBA16I;
  40031. if ( glType === gl.INT ) internalFormat = gl.RGBA32I;
  40032. }
  40033. if ( glFormat === gl.DEPTH_COMPONENT ) {
  40034. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.DEPTH24_STENCIL8;
  40035. if ( glType === gl.FLOAT ) internalFormat = gl.DEPTH_COMPONENT32F;
  40036. }
  40037. if ( glFormat === gl.DEPTH_STENCIL ) {
  40038. if ( glType === gl.UNSIGNED_INT_24_8 ) internalFormat = gl.DEPTH24_STENCIL8;
  40039. }
  40040. if ( internalFormat === gl.R16F || internalFormat === gl.R32F ||
  40041. internalFormat === gl.RG16F || internalFormat === gl.RG32F ||
  40042. internalFormat === gl.RGBA16F || internalFormat === gl.RGBA32F ) {
  40043. extensions.get( 'EXT_color_buffer_float' );
  40044. }
  40045. return internalFormat;
  40046. }
  40047. setTextureParameters( textureType, texture ) {
  40048. const { gl, extensions, backend } = this;
  40049. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  40050. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  40051. gl.pixelStorei( gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  40052. gl.pixelStorei( gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, gl.NONE );
  40053. gl.texParameteri( textureType, gl.TEXTURE_WRAP_S, wrappingToGL[ texture.wrapS ] );
  40054. gl.texParameteri( textureType, gl.TEXTURE_WRAP_T, wrappingToGL[ texture.wrapT ] );
  40055. if ( textureType === gl.TEXTURE_3D || textureType === gl.TEXTURE_2D_ARRAY ) {
  40056. gl.texParameteri( textureType, gl.TEXTURE_WRAP_R, wrappingToGL[ texture.wrapR ] );
  40057. }
  40058. gl.texParameteri( textureType, gl.TEXTURE_MAG_FILTER, filterToGL[ texture.magFilter ] );
  40059. const hasMipmaps = texture.mipmaps !== undefined && texture.mipmaps.length > 0;
  40060. // follow WebGPU backend mapping for texture filtering
  40061. const minFilter = texture.minFilter === LinearFilter && hasMipmaps ? LinearMipmapLinearFilter : texture.minFilter;
  40062. gl.texParameteri( textureType, gl.TEXTURE_MIN_FILTER, filterToGL[ minFilter ] );
  40063. if ( texture.compareFunction ) {
  40064. gl.texParameteri( textureType, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE );
  40065. gl.texParameteri( textureType, gl.TEXTURE_COMPARE_FUNC, compareToGL[ texture.compareFunction ] );
  40066. }
  40067. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  40068. if ( texture.magFilter === NearestFilter ) return;
  40069. if ( texture.minFilter !== NearestMipmapLinearFilter && texture.minFilter !== LinearMipmapLinearFilter ) return;
  40070. if ( texture.type === FloatType && extensions.has( 'OES_texture_float_linear' ) === false ) return; // verify extension for WebGL 1 and WebGL 2
  40071. if ( texture.anisotropy > 1 ) {
  40072. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  40073. gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, backend.getMaxAnisotropy() ) );
  40074. }
  40075. }
  40076. }
  40077. createDefaultTexture( texture ) {
  40078. const { gl, backend, defaultTextures } = this;
  40079. const glTextureType = this.getGLTextureType( texture );
  40080. let textureGPU = defaultTextures[ glTextureType ];
  40081. if ( textureGPU === undefined ) {
  40082. textureGPU = gl.createTexture();
  40083. backend.state.bindTexture( glTextureType, textureGPU );
  40084. gl.texParameteri( glTextureType, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  40085. gl.texParameteri( glTextureType, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  40086. // gl.texImage2D( glTextureType, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data );
  40087. defaultTextures[ glTextureType ] = textureGPU;
  40088. }
  40089. backend.set( texture, {
  40090. textureGPU,
  40091. glTextureType,
  40092. isDefault: true
  40093. } );
  40094. }
  40095. createTexture( texture, options ) {
  40096. const { gl, backend } = this;
  40097. const { levels, width, height, depth } = options;
  40098. const glFormat = backend.utils.convert( texture.format, texture.colorSpace );
  40099. const glType = backend.utils.convert( texture.type );
  40100. const glInternalFormat = this.getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace, texture.isVideoTexture );
  40101. const textureGPU = gl.createTexture();
  40102. const glTextureType = this.getGLTextureType( texture );
  40103. backend.state.bindTexture( glTextureType, textureGPU );
  40104. this.setTextureParameters( glTextureType, texture );
  40105. if ( texture.isDataArrayTexture || texture.isCompressedArrayTexture ) {
  40106. gl.texStorage3D( gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, width, height, depth );
  40107. } else if ( texture.isData3DTexture ) {
  40108. gl.texStorage3D( gl.TEXTURE_3D, levels, glInternalFormat, width, height, depth );
  40109. } else if ( ! texture.isVideoTexture ) {
  40110. gl.texStorage2D( glTextureType, levels, glInternalFormat, width, height );
  40111. }
  40112. backend.set( texture, {
  40113. textureGPU,
  40114. glTextureType,
  40115. glFormat,
  40116. glType,
  40117. glInternalFormat
  40118. } );
  40119. }
  40120. copyBufferToTexture( buffer, texture ) {
  40121. const { gl, backend } = this;
  40122. const { textureGPU, glTextureType, glFormat, glType } = backend.get( texture );
  40123. const { width, height } = texture.source.data;
  40124. gl.bindBuffer( gl.PIXEL_UNPACK_BUFFER, buffer );
  40125. backend.state.bindTexture( glTextureType, textureGPU );
  40126. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, false );
  40127. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false );
  40128. gl.texSubImage2D( glTextureType, 0, 0, 0, width, height, glFormat, glType, 0 );
  40129. gl.bindBuffer( gl.PIXEL_UNPACK_BUFFER, null );
  40130. backend.state.unbindTexture();
  40131. // debug
  40132. // const framebuffer = gl.createFramebuffer();
  40133. // gl.bindFramebuffer( gl.FRAMEBUFFER, framebuffer );
  40134. // gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, glTextureType, textureGPU, 0 );
  40135. // const readout = new Float32Array( width * height * 4 );
  40136. // const altFormat = gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_FORMAT );
  40137. // const altType = gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_TYPE );
  40138. // gl.readPixels( 0, 0, width, height, altFormat, altType, readout );
  40139. // gl.bindFramebuffer( gl.FRAMEBUFFER, null );
  40140. // console.log( readout );
  40141. }
  40142. updateTexture( texture, options ) {
  40143. const { gl } = this;
  40144. const { width, height } = options;
  40145. const { textureGPU, glTextureType, glFormat, glType, glInternalFormat } = this.backend.get( texture );
  40146. if ( texture.isRenderTargetTexture || ( textureGPU === undefined /* unsupported texture format */ ) )
  40147. return;
  40148. const getImage = ( source ) => {
  40149. if ( source.isDataTexture ) {
  40150. return source.image.data;
  40151. } else if ( source instanceof ImageBitmap || source instanceof OffscreenCanvas || source instanceof HTMLImageElement || source instanceof HTMLCanvasElement ) {
  40152. return source;
  40153. }
  40154. return source.data;
  40155. };
  40156. this.backend.state.bindTexture( glTextureType, textureGPU );
  40157. this.setTextureParameters( glTextureType, texture );
  40158. if ( texture.isCompressedTexture ) {
  40159. const mipmaps = texture.mipmaps;
  40160. const image = options.image;
  40161. for ( let i = 0; i < mipmaps.length; i ++ ) {
  40162. const mipmap = mipmaps[ i ];
  40163. if ( texture.isCompressedArrayTexture ) {
  40164. if ( texture.format !== gl.RGBA ) {
  40165. if ( glFormat !== null ) {
  40166. gl.compressedTexSubImage3D( gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, mipmap.data );
  40167. } else {
  40168. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' );
  40169. }
  40170. } else {
  40171. gl.texSubImage3D( gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, glType, mipmap.data );
  40172. }
  40173. } else {
  40174. if ( glFormat !== null ) {
  40175. gl.compressedTexSubImage2D( gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data );
  40176. } else {
  40177. console.warn( 'Unsupported compressed texture format' );
  40178. }
  40179. }
  40180. }
  40181. } else if ( texture.isCubeTexture ) {
  40182. const images = options.images;
  40183. for ( let i = 0; i < 6; i ++ ) {
  40184. const image = getImage( images[ i ] );
  40185. gl.texSubImage2D( gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, width, height, glFormat, glType, image );
  40186. }
  40187. } else if ( texture.isDataArrayTexture ) {
  40188. const image = options.image;
  40189. gl.texSubImage3D( gl.TEXTURE_2D_ARRAY, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  40190. } else if ( texture.isData3DTexture ) {
  40191. const image = options.image;
  40192. gl.texSubImage3D( gl.TEXTURE_3D, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  40193. } else if ( texture.isVideoTexture ) {
  40194. texture.update();
  40195. gl.texImage2D( glTextureType, 0, glInternalFormat, glFormat, glType, options.image );
  40196. } else {
  40197. const image = getImage( options.image );
  40198. gl.texSubImage2D( glTextureType, 0, 0, 0, width, height, glFormat, glType, image );
  40199. }
  40200. }
  40201. generateMipmaps( texture ) {
  40202. const { gl, backend } = this;
  40203. const { textureGPU, glTextureType } = backend.get( texture );
  40204. backend.state.bindTexture( glTextureType, textureGPU );
  40205. gl.generateMipmap( glTextureType );
  40206. }
  40207. deallocateRenderBuffers( renderTarget ) {
  40208. const { gl, backend } = this;
  40209. // remove framebuffer reference
  40210. if ( renderTarget ) {
  40211. const renderContextData = backend.get( renderTarget );
  40212. renderContextData.renderBufferStorageSetup = undefined;
  40213. if ( renderContextData.framebuffers ) {
  40214. for ( const cacheKey in renderContextData.framebuffers ) {
  40215. gl.deleteFramebuffer( renderContextData.framebuffers[ cacheKey ] );
  40216. }
  40217. delete renderContextData.framebuffers;
  40218. }
  40219. if ( renderContextData.depthRenderbuffer ) {
  40220. gl.deleteRenderbuffer( renderContextData.depthRenderbuffer );
  40221. delete renderContextData.depthRenderbuffer;
  40222. }
  40223. if ( renderContextData.stencilRenderbuffer ) {
  40224. gl.deleteRenderbuffer( renderContextData.stencilRenderbuffer );
  40225. delete renderContextData.stencilRenderbuffer;
  40226. }
  40227. if ( renderContextData.msaaFrameBuffer ) {
  40228. gl.deleteFramebuffer( renderContextData.msaaFrameBuffer );
  40229. delete renderContextData.msaaFrameBuffer;
  40230. }
  40231. if ( renderContextData.msaaRenderbuffers ) {
  40232. for ( let i = 0; i < renderContextData.msaaRenderbuffers.length; i ++ ) {
  40233. gl.deleteRenderbuffer( renderContextData.msaaRenderbuffers[ i ] );
  40234. }
  40235. delete renderContextData.msaaRenderbuffers;
  40236. }
  40237. }
  40238. }
  40239. destroyTexture( texture ) {
  40240. const { gl, backend } = this;
  40241. const { textureGPU, renderTarget } = backend.get( texture );
  40242. this.deallocateRenderBuffers( renderTarget );
  40243. gl.deleteTexture( textureGPU );
  40244. backend.delete( texture );
  40245. }
  40246. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, level = 0 ) {
  40247. const { gl, backend } = this;
  40248. const { state } = this.backend;
  40249. const { textureGPU: dstTextureGPU, glTextureType, glType, glFormat } = backend.get( dstTexture );
  40250. let width, height, minX, minY;
  40251. let dstX, dstY;
  40252. if ( srcRegion !== null ) {
  40253. width = srcRegion.max.x - srcRegion.min.x;
  40254. height = srcRegion.max.y - srcRegion.min.y;
  40255. minX = srcRegion.min.x;
  40256. minY = srcRegion.min.y;
  40257. } else {
  40258. width = srcTexture.image.width;
  40259. height = srcTexture.image.height;
  40260. minX = 0;
  40261. minY = 0;
  40262. }
  40263. if ( dstPosition !== null ) {
  40264. dstX = dstPosition.x;
  40265. dstY = dstPosition.y;
  40266. } else {
  40267. dstX = 0;
  40268. dstY = 0;
  40269. }
  40270. state.bindTexture( glTextureType, dstTextureGPU );
  40271. // As another texture upload may have changed pixelStorei
  40272. // parameters, make sure they are correct for the dstTexture
  40273. gl.pixelStorei( gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment );
  40274. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY );
  40275. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha );
  40276. gl.pixelStorei( gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment );
  40277. const currentUnpackRowLen = gl.getParameter( gl.UNPACK_ROW_LENGTH );
  40278. const currentUnpackImageHeight = gl.getParameter( gl.UNPACK_IMAGE_HEIGHT );
  40279. const currentUnpackSkipPixels = gl.getParameter( gl.UNPACK_SKIP_PIXELS );
  40280. const currentUnpackSkipRows = gl.getParameter( gl.UNPACK_SKIP_ROWS );
  40281. const currentUnpackSkipImages = gl.getParameter( gl.UNPACK_SKIP_IMAGES );
  40282. const image = srcTexture.isCompressedTexture ? srcTexture.mipmaps[ level ] : srcTexture.image;
  40283. gl.pixelStorei( gl.UNPACK_ROW_LENGTH, image.width );
  40284. gl.pixelStorei( gl.UNPACK_IMAGE_HEIGHT, image.height );
  40285. gl.pixelStorei( gl.UNPACK_SKIP_PIXELS, minX );
  40286. gl.pixelStorei( gl.UNPACK_SKIP_ROWS, minY );
  40287. if ( srcTexture.isDataTexture ) {
  40288. gl.texSubImage2D( gl.TEXTURE_2D, level, dstX, dstY, width, height, glFormat, glType, image.data );
  40289. } else {
  40290. if ( srcTexture.isCompressedTexture ) {
  40291. gl.compressedTexSubImage2D( gl.TEXTURE_2D, level, dstX, dstY, image.width, image.height, glFormat, image.data );
  40292. } else {
  40293. gl.texSubImage2D( gl.TEXTURE_2D, level, dstX, dstY, width, height, glFormat, glType, image );
  40294. }
  40295. }
  40296. gl.pixelStorei( gl.UNPACK_ROW_LENGTH, currentUnpackRowLen );
  40297. gl.pixelStorei( gl.UNPACK_IMAGE_HEIGHT, currentUnpackImageHeight );
  40298. gl.pixelStorei( gl.UNPACK_SKIP_PIXELS, currentUnpackSkipPixels );
  40299. gl.pixelStorei( gl.UNPACK_SKIP_ROWS, currentUnpackSkipRows );
  40300. gl.pixelStorei( gl.UNPACK_SKIP_IMAGES, currentUnpackSkipImages );
  40301. // Generate mipmaps only when copying level 0
  40302. if ( level === 0 && dstTexture.generateMipmaps ) gl.generateMipmap( gl.TEXTURE_2D );
  40303. state.unbindTexture();
  40304. }
  40305. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  40306. const { gl } = this;
  40307. const { state } = this.backend;
  40308. const { textureGPU } = this.backend.get( texture );
  40309. const { x, y, z: width, w: height } = rectangle;
  40310. const requireDrawFrameBuffer = texture.isDepthTexture === true || ( renderContext.renderTarget && renderContext.renderTarget.samples > 0 );
  40311. const srcHeight = renderContext.renderTarget ? renderContext.renderTarget.height : this.backend.gerDrawingBufferSize().y;
  40312. if ( requireDrawFrameBuffer ) {
  40313. const partial = ( x !== 0 || y !== 0 );
  40314. let mask;
  40315. let attachment;
  40316. if ( texture.isDepthTexture === true ) {
  40317. mask = gl.DEPTH_BUFFER_BIT;
  40318. attachment = gl.DEPTH_ATTACHMENT;
  40319. if ( renderContext.stencil ) {
  40320. mask |= gl.STENCIL_BUFFER_BIT;
  40321. }
  40322. } else {
  40323. mask = gl.COLOR_BUFFER_BIT;
  40324. attachment = gl.COLOR_ATTACHMENT0;
  40325. }
  40326. if ( partial ) {
  40327. const renderTargetContextData = this.backend.get( renderContext.renderTarget );
  40328. const fb = renderTargetContextData.framebuffers[ renderContext.getCacheKey() ];
  40329. const msaaFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  40330. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  40331. state.bindFramebuffer( gl.READ_FRAMEBUFFER, msaaFrameBuffer );
  40332. const flippedY = srcHeight - y - height;
  40333. gl.blitFramebuffer( x, flippedY, x + width, flippedY + height, x, flippedY, x + width, flippedY + height, mask, gl.NEAREST );
  40334. state.bindFramebuffer( gl.READ_FRAMEBUFFER, fb );
  40335. state.bindTexture( gl.TEXTURE_2D, textureGPU );
  40336. gl.copyTexSubImage2D( gl.TEXTURE_2D, 0, 0, 0, x, flippedY, width, height );
  40337. state.unbindTexture();
  40338. } else {
  40339. const fb = gl.createFramebuffer();
  40340. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  40341. gl.framebufferTexture2D( gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureGPU, 0 );
  40342. gl.blitFramebuffer( 0, 0, width, height, 0, 0, width, height, mask, gl.NEAREST );
  40343. gl.deleteFramebuffer( fb );
  40344. }
  40345. } else {
  40346. state.bindTexture( gl.TEXTURE_2D, textureGPU );
  40347. gl.copyTexSubImage2D( gl.TEXTURE_2D, 0, 0, 0, x, srcHeight - height - y, width, height );
  40348. state.unbindTexture();
  40349. }
  40350. if ( texture.generateMipmaps ) this.generateMipmaps( texture );
  40351. this.backend._setFramebuffer( renderContext );
  40352. }
  40353. // Setup storage for internal depth/stencil buffers and bind to correct framebuffer
  40354. setupRenderBufferStorage( renderbuffer, renderContext ) {
  40355. const { gl } = this;
  40356. const renderTarget = renderContext.renderTarget;
  40357. const { samples, depthTexture, depthBuffer, stencilBuffer, width, height } = renderTarget;
  40358. gl.bindRenderbuffer( gl.RENDERBUFFER, renderbuffer );
  40359. if ( depthBuffer && ! stencilBuffer ) {
  40360. let glInternalFormat = gl.DEPTH_COMPONENT24;
  40361. if ( samples > 0 ) {
  40362. if ( depthTexture && depthTexture.isDepthTexture ) {
  40363. if ( depthTexture.type === gl.FLOAT ) {
  40364. glInternalFormat = gl.DEPTH_COMPONENT32F;
  40365. }
  40366. }
  40367. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, glInternalFormat, width, height );
  40368. } else {
  40369. gl.renderbufferStorage( gl.RENDERBUFFER, glInternalFormat, width, height );
  40370. }
  40371. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, renderbuffer );
  40372. } else if ( depthBuffer && stencilBuffer ) {
  40373. if ( samples > 0 ) {
  40374. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height );
  40375. } else {
  40376. gl.renderbufferStorage( gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height );
  40377. }
  40378. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, renderbuffer );
  40379. }
  40380. }
  40381. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  40382. const { backend, gl } = this;
  40383. const { textureGPU, glFormat, glType } = this.backend.get( texture );
  40384. const fb = gl.createFramebuffer();
  40385. gl.bindFramebuffer( gl.READ_FRAMEBUFFER, fb );
  40386. const target = texture.isCubeTexture ? gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex : gl.TEXTURE_2D;
  40387. gl.framebufferTexture2D( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, target, textureGPU, 0 );
  40388. const typedArrayType = this._getTypedArrayType( glType );
  40389. const bytesPerTexel = this._getBytesPerTexel( glType, glFormat );
  40390. const elementCount = width * height;
  40391. const byteLength = elementCount * bytesPerTexel;
  40392. const buffer = gl.createBuffer();
  40393. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, buffer );
  40394. gl.bufferData( gl.PIXEL_PACK_BUFFER, byteLength, gl.STREAM_READ );
  40395. gl.readPixels( x, y, width, height, glFormat, glType, 0 );
  40396. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, null );
  40397. await backend.utils._clientWaitAsync();
  40398. const dstBuffer = new typedArrayType( byteLength / typedArrayType.BYTES_PER_ELEMENT );
  40399. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, buffer );
  40400. gl.getBufferSubData( gl.PIXEL_PACK_BUFFER, 0, dstBuffer );
  40401. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, null );
  40402. gl.deleteFramebuffer( fb );
  40403. return dstBuffer;
  40404. }
  40405. _getTypedArrayType( glType ) {
  40406. const { gl } = this;
  40407. if ( glType === gl.UNSIGNED_BYTE ) return Uint8Array;
  40408. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) return Uint16Array;
  40409. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) return Uint16Array;
  40410. if ( glType === gl.UNSIGNED_SHORT_5_6_5 ) return Uint16Array;
  40411. if ( glType === gl.UNSIGNED_SHORT ) return Uint16Array;
  40412. if ( glType === gl.UNSIGNED_INT ) return Uint32Array;
  40413. if ( glType === gl.HALF_FLOAT ) return Uint16Array;
  40414. if ( glType === gl.FLOAT ) return Float32Array;
  40415. throw new Error( `Unsupported WebGL type: ${glType}` );
  40416. }
  40417. _getBytesPerTexel( glType, glFormat ) {
  40418. const { gl } = this;
  40419. let bytesPerComponent = 0;
  40420. if ( glType === gl.UNSIGNED_BYTE ) bytesPerComponent = 1;
  40421. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ||
  40422. glType === gl.UNSIGNED_SHORT_5_5_5_1 ||
  40423. glType === gl.UNSIGNED_SHORT_5_6_5 ||
  40424. glType === gl.UNSIGNED_SHORT ||
  40425. glType === gl.HALF_FLOAT ) bytesPerComponent = 2;
  40426. if ( glType === gl.UNSIGNED_INT ||
  40427. glType === gl.FLOAT ) bytesPerComponent = 4;
  40428. if ( glFormat === gl.RGBA ) return bytesPerComponent * 4;
  40429. if ( glFormat === gl.RGB ) return bytesPerComponent * 3;
  40430. if ( glFormat === gl.ALPHA ) return bytesPerComponent;
  40431. }
  40432. }
  40433. class WebGLExtensions {
  40434. constructor( backend ) {
  40435. this.backend = backend;
  40436. this.gl = this.backend.gl;
  40437. this.availableExtensions = this.gl.getSupportedExtensions();
  40438. this.extensions = {};
  40439. }
  40440. get( name ) {
  40441. let extension = this.extensions[ name ];
  40442. if ( extension === undefined ) {
  40443. extension = this.gl.getExtension( name );
  40444. this.extensions[ name ] = extension;
  40445. }
  40446. return extension;
  40447. }
  40448. has( name ) {
  40449. return this.availableExtensions.includes( name );
  40450. }
  40451. }
  40452. class WebGLCapabilities {
  40453. constructor( backend ) {
  40454. this.backend = backend;
  40455. this.maxAnisotropy = null;
  40456. }
  40457. getMaxAnisotropy() {
  40458. if ( this.maxAnisotropy !== null ) return this.maxAnisotropy;
  40459. const gl = this.backend.gl;
  40460. const extensions = this.backend.extensions;
  40461. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  40462. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  40463. this.maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT );
  40464. } else {
  40465. this.maxAnisotropy = 0;
  40466. }
  40467. return this.maxAnisotropy;
  40468. }
  40469. }
  40470. const GLFeatureName = {
  40471. 'WEBGL_multi_draw': 'WEBGL_multi_draw',
  40472. 'WEBGL_compressed_texture_astc': 'texture-compression-astc',
  40473. 'WEBGL_compressed_texture_etc': 'texture-compression-etc2',
  40474. 'WEBGL_compressed_texture_etc1': 'texture-compression-etc1',
  40475. 'WEBGL_compressed_texture_pvrtc': 'texture-compression-pvrtc',
  40476. 'WEBKIT_WEBGL_compressed_texture_pvrtc': 'texture-compression-pvrtc',
  40477. 'WEBGL_compressed_texture_s3tc': 'texture-compression-bc',
  40478. 'EXT_texture_compression_bptc': 'texture-compression-bptc',
  40479. 'EXT_disjoint_timer_query_webgl2': 'timestamp-query',
  40480. };
  40481. class WebGLBufferRenderer {
  40482. constructor( backend ) {
  40483. this.gl = backend.gl;
  40484. this.extensions = backend.extensions;
  40485. this.info = backend.renderer.info;
  40486. this.mode = null;
  40487. this.index = 0;
  40488. this.type = null;
  40489. this.object = null;
  40490. }
  40491. render( start, count ) {
  40492. const { gl, mode, object, type, info, index } = this;
  40493. if ( index !== 0 ) {
  40494. gl.drawElements( mode, count, type, start );
  40495. } else {
  40496. gl.drawArrays( mode, start, count );
  40497. }
  40498. info.update( object, count, mode, 1 );
  40499. }
  40500. renderInstances( start, count, primcount ) {
  40501. const { gl, mode, type, index, object, info } = this;
  40502. if ( primcount === 0 ) return;
  40503. if ( index !== 0 ) {
  40504. gl.drawElementsInstanced( mode, count, type, start, primcount );
  40505. } else {
  40506. gl.drawArraysInstanced( mode, start, count, primcount );
  40507. }
  40508. info.update( object, count, mode, primcount );
  40509. }
  40510. renderMultiDraw( starts, counts, drawCount ) {
  40511. const { extensions, mode, object, info } = this;
  40512. if ( drawCount === 0 ) return;
  40513. const extension = extensions.get( 'WEBGL_multi_draw' );
  40514. if ( extension === null ) {
  40515. for ( let i = 0; i < drawCount; i ++ ) {
  40516. this.render( starts[ i ], counts[ i ] );
  40517. }
  40518. } else {
  40519. if ( this.index !== 0 ) {
  40520. extension.multiDrawElementsWEBGL( mode, counts, 0, this.type, starts, 0, drawCount );
  40521. } else {
  40522. extension.multiDrawArraysWEBGL( mode, starts, 0, counts, 0, drawCount );
  40523. }
  40524. let elementCount = 0;
  40525. for ( let i = 0; i < drawCount; i ++ ) {
  40526. elementCount += counts[ i ];
  40527. }
  40528. info.update( object, elementCount, mode, 1 );
  40529. }
  40530. }
  40531. renderMultiDrawInstances( starts, counts, drawCount, primcount ) {
  40532. const { extensions, mode, object, info } = this;
  40533. if ( drawCount === 0 ) return;
  40534. const extension = extensions.get( 'WEBGL_multi_draw' );
  40535. if ( extension === null ) {
  40536. for ( let i = 0; i < drawCount; i ++ ) {
  40537. this.renderInstances( starts[ i ], counts[ i ], primcount[ i ] );
  40538. }
  40539. } else {
  40540. if ( this.index !== 0 ) {
  40541. extension.multiDrawElementsInstancedWEBGL( mode, counts, 0, this.type, starts, 0, primcount, 0, drawCount );
  40542. } else {
  40543. extension.multiDrawArraysInstancedWEBGL( mode, starts, 0, counts, 0, primcount, 0, drawCount );
  40544. }
  40545. let elementCount = 0;
  40546. for ( let i = 0; i < drawCount; i ++ ) {
  40547. elementCount += counts[ i ] * primcount[ i ];
  40548. }
  40549. info.update( object, elementCount, mode, 1 );
  40550. }
  40551. }
  40552. //
  40553. }
  40554. //
  40555. class WebGLBackend extends Backend {
  40556. constructor( parameters = {} ) {
  40557. super( parameters );
  40558. this.isWebGLBackend = true;
  40559. }
  40560. init( renderer ) {
  40561. super.init( renderer );
  40562. //
  40563. const parameters = this.parameters;
  40564. const glContext = ( parameters.context !== undefined ) ? parameters.context : renderer.domElement.getContext( 'webgl2' );
  40565. this.gl = glContext;
  40566. this.extensions = new WebGLExtensions( this );
  40567. this.capabilities = new WebGLCapabilities( this );
  40568. this.attributeUtils = new WebGLAttributeUtils( this );
  40569. this.textureUtils = new WebGLTextureUtils( this );
  40570. this.bufferRenderer = new WebGLBufferRenderer( this );
  40571. this.state = new WebGLState( this );
  40572. this.utils = new WebGLUtils( this );
  40573. this.vaoCache = {};
  40574. this.transformFeedbackCache = {};
  40575. this.discard = false;
  40576. this.trackTimestamp = ( parameters.trackTimestamp === true );
  40577. this.extensions.get( 'EXT_color_buffer_float' );
  40578. this.extensions.get( 'WEBGL_clip_cull_distance' );
  40579. this.extensions.get( 'OES_texture_float_linear' );
  40580. this.extensions.get( 'EXT_color_buffer_half_float' );
  40581. this.extensions.get( 'WEBGL_multisampled_render_to_texture' );
  40582. this.extensions.get( 'WEBGL_render_shared_exponent' );
  40583. this.extensions.get( 'WEBGL_multi_draw' );
  40584. this.disjoint = this.extensions.get( 'EXT_disjoint_timer_query_webgl2' );
  40585. this.parallel = this.extensions.get( 'KHR_parallel_shader_compile' );
  40586. this._currentContext = null;
  40587. }
  40588. get coordinateSystem() {
  40589. return WebGLCoordinateSystem;
  40590. }
  40591. async getArrayBufferAsync( attribute ) {
  40592. return await this.attributeUtils.getArrayBufferAsync( attribute );
  40593. }
  40594. initTimestampQuery( renderContext ) {
  40595. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  40596. const renderContextData = this.get( renderContext );
  40597. if ( this.queryRunning ) {
  40598. if ( ! renderContextData.queryQueue ) renderContextData.queryQueue = [];
  40599. renderContextData.queryQueue.push( renderContext );
  40600. return;
  40601. }
  40602. if ( renderContextData.activeQuery ) {
  40603. this.gl.endQuery( this.disjoint.TIME_ELAPSED_EXT );
  40604. renderContextData.activeQuery = null;
  40605. }
  40606. renderContextData.activeQuery = this.gl.createQuery();
  40607. if ( renderContextData.activeQuery !== null ) {
  40608. this.gl.beginQuery( this.disjoint.TIME_ELAPSED_EXT, renderContextData.activeQuery );
  40609. this.queryRunning = true;
  40610. }
  40611. }
  40612. // timestamp utils
  40613. prepareTimestampBuffer( renderContext ) {
  40614. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  40615. const renderContextData = this.get( renderContext );
  40616. if ( renderContextData.activeQuery ) {
  40617. this.gl.endQuery( this.disjoint.TIME_ELAPSED_EXT );
  40618. if ( ! renderContextData.gpuQueries ) renderContextData.gpuQueries = [];
  40619. renderContextData.gpuQueries.push( { query: renderContextData.activeQuery } );
  40620. renderContextData.activeQuery = null;
  40621. this.queryRunning = false;
  40622. if ( renderContextData.queryQueue && renderContextData.queryQueue.length > 0 ) {
  40623. const nextRenderContext = renderContextData.queryQueue.shift();
  40624. this.initTimestampQuery( nextRenderContext );
  40625. }
  40626. }
  40627. }
  40628. async resolveTimestampAsync( renderContext, type = 'render' ) {
  40629. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  40630. const renderContextData = this.get( renderContext );
  40631. if ( ! renderContextData.gpuQueries ) renderContextData.gpuQueries = [];
  40632. for ( let i = 0; i < renderContextData.gpuQueries.length; i ++ ) {
  40633. const queryInfo = renderContextData.gpuQueries[ i ];
  40634. const available = this.gl.getQueryParameter( queryInfo.query, this.gl.QUERY_RESULT_AVAILABLE );
  40635. const disjoint = this.gl.getParameter( this.disjoint.GPU_DISJOINT_EXT );
  40636. if ( available && ! disjoint ) {
  40637. const elapsed = this.gl.getQueryParameter( queryInfo.query, this.gl.QUERY_RESULT );
  40638. const duration = Number( elapsed ) / 1000000; // Convert nanoseconds to milliseconds
  40639. this.gl.deleteQuery( queryInfo.query );
  40640. renderContextData.gpuQueries.splice( i, 1 ); // Remove the processed query
  40641. i --;
  40642. this.renderer.info.updateTimestamp( type, duration );
  40643. }
  40644. }
  40645. }
  40646. getContext() {
  40647. return this.gl;
  40648. }
  40649. beginRender( renderContext ) {
  40650. const { gl } = this;
  40651. const renderContextData = this.get( renderContext );
  40652. //
  40653. //
  40654. this.initTimestampQuery( renderContext );
  40655. renderContextData.previousContext = this._currentContext;
  40656. this._currentContext = renderContext;
  40657. this._setFramebuffer( renderContext );
  40658. this.clear( renderContext.clearColor, renderContext.clearDepth, renderContext.clearStencil, renderContext, false );
  40659. //
  40660. if ( renderContext.viewport ) {
  40661. this.updateViewport( renderContext );
  40662. } else {
  40663. gl.viewport( 0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight );
  40664. }
  40665. if ( renderContext.scissor ) {
  40666. const { x, y, width, height } = renderContext.scissorValue;
  40667. gl.scissor( x, renderContext.height - height - y, width, height );
  40668. }
  40669. const occlusionQueryCount = renderContext.occlusionQueryCount;
  40670. if ( occlusionQueryCount > 0 ) {
  40671. // Get a reference to the array of objects with queries. The renderContextData property
  40672. // can be changed by another render pass before the async reading of all previous queries complete
  40673. renderContextData.currentOcclusionQueries = renderContextData.occlusionQueries;
  40674. renderContextData.currentOcclusionQueryObjects = renderContextData.occlusionQueryObjects;
  40675. renderContextData.lastOcclusionObject = null;
  40676. renderContextData.occlusionQueries = new Array( occlusionQueryCount );
  40677. renderContextData.occlusionQueryObjects = new Array( occlusionQueryCount );
  40678. renderContextData.occlusionQueryIndex = 0;
  40679. }
  40680. }
  40681. finishRender( renderContext ) {
  40682. const { gl, state } = this;
  40683. const renderContextData = this.get( renderContext );
  40684. const previousContext = renderContextData.previousContext;
  40685. const occlusionQueryCount = renderContext.occlusionQueryCount;
  40686. if ( occlusionQueryCount > 0 ) {
  40687. if ( occlusionQueryCount > renderContextData.occlusionQueryIndex ) {
  40688. gl.endQuery( gl.ANY_SAMPLES_PASSED );
  40689. }
  40690. this.resolveOccludedAsync( renderContext );
  40691. }
  40692. const textures = renderContext.textures;
  40693. if ( textures !== null ) {
  40694. for ( let i = 0; i < textures.length; i ++ ) {
  40695. const texture = textures[ i ];
  40696. if ( texture.generateMipmaps ) {
  40697. this.generateMipmaps( texture );
  40698. }
  40699. }
  40700. }
  40701. this._currentContext = previousContext;
  40702. if ( renderContext.textures !== null && renderContext.renderTarget ) {
  40703. const renderTargetContextData = this.get( renderContext.renderTarget );
  40704. const { samples } = renderContext.renderTarget;
  40705. if ( samples > 0 ) {
  40706. const fb = renderTargetContextData.framebuffers[ renderContext.getCacheKey() ];
  40707. const mask = gl.COLOR_BUFFER_BIT;
  40708. const msaaFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  40709. const textures = renderContext.textures;
  40710. state.bindFramebuffer( gl.READ_FRAMEBUFFER, msaaFrameBuffer );
  40711. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  40712. for ( let i = 0; i < textures.length; i ++ ) {
  40713. // TODO Add support for MRT
  40714. if ( renderContext.scissor ) {
  40715. const { x, y, width, height } = renderContext.scissorValue;
  40716. const viewY = renderContext.height - height - y;
  40717. gl.blitFramebuffer( x, viewY, x + width, viewY + height, x, viewY, x + width, viewY + height, mask, gl.NEAREST );
  40718. gl.invalidateSubFramebuffer( gl.READ_FRAMEBUFFER, renderTargetContextData.invalidationArray, x, viewY, width, height );
  40719. } else {
  40720. gl.blitFramebuffer( 0, 0, renderContext.width, renderContext.height, 0, 0, renderContext.width, renderContext.height, mask, gl.NEAREST );
  40721. gl.invalidateFramebuffer( gl.READ_FRAMEBUFFER, renderTargetContextData.invalidationArray );
  40722. }
  40723. }
  40724. }
  40725. }
  40726. if ( previousContext !== null ) {
  40727. this._setFramebuffer( previousContext );
  40728. if ( previousContext.viewport ) {
  40729. this.updateViewport( previousContext );
  40730. } else {
  40731. gl.viewport( 0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight );
  40732. }
  40733. }
  40734. this.prepareTimestampBuffer( renderContext );
  40735. }
  40736. resolveOccludedAsync( renderContext ) {
  40737. const renderContextData = this.get( renderContext );
  40738. // handle occlusion query results
  40739. const { currentOcclusionQueries, currentOcclusionQueryObjects } = renderContextData;
  40740. if ( currentOcclusionQueries && currentOcclusionQueryObjects ) {
  40741. const occluded = new WeakSet();
  40742. const { gl } = this;
  40743. renderContextData.currentOcclusionQueryObjects = null;
  40744. renderContextData.currentOcclusionQueries = null;
  40745. const check = () => {
  40746. let completed = 0;
  40747. // check all queries and requeue as appropriate
  40748. for ( let i = 0; i < currentOcclusionQueries.length; i ++ ) {
  40749. const query = currentOcclusionQueries[ i ];
  40750. if ( query === null ) continue;
  40751. if ( gl.getQueryParameter( query, gl.QUERY_RESULT_AVAILABLE ) ) {
  40752. if ( gl.getQueryParameter( query, gl.QUERY_RESULT ) > 0 ) occluded.add( currentOcclusionQueryObjects[ i ] );
  40753. currentOcclusionQueries[ i ] = null;
  40754. gl.deleteQuery( query );
  40755. completed ++;
  40756. }
  40757. }
  40758. if ( completed < currentOcclusionQueries.length ) {
  40759. requestAnimationFrame( check );
  40760. } else {
  40761. renderContextData.occluded = occluded;
  40762. }
  40763. };
  40764. check();
  40765. }
  40766. }
  40767. isOccluded( renderContext, object ) {
  40768. const renderContextData = this.get( renderContext );
  40769. return renderContextData.occluded && renderContextData.occluded.has( object );
  40770. }
  40771. updateViewport( renderContext ) {
  40772. const gl = this.gl;
  40773. const { x, y, width, height } = renderContext.viewportValue;
  40774. gl.viewport( x, renderContext.height - height - y, width, height );
  40775. }
  40776. setScissorTest( boolean ) {
  40777. const gl = this.gl;
  40778. if ( boolean ) {
  40779. gl.enable( gl.SCISSOR_TEST );
  40780. } else {
  40781. gl.disable( gl.SCISSOR_TEST );
  40782. }
  40783. }
  40784. clear( color, depth, stencil, descriptor = null, setFrameBuffer = true ) {
  40785. const { gl } = this;
  40786. if ( descriptor === null ) {
  40787. const clearColor = this.getClearColor();
  40788. // premultiply alpha
  40789. clearColor.r *= clearColor.a;
  40790. clearColor.g *= clearColor.a;
  40791. clearColor.b *= clearColor.a;
  40792. descriptor = {
  40793. textures: null,
  40794. clearColorValue: clearColor
  40795. };
  40796. }
  40797. //
  40798. let clear = 0;
  40799. if ( color ) clear |= gl.COLOR_BUFFER_BIT;
  40800. if ( depth ) clear |= gl.DEPTH_BUFFER_BIT;
  40801. if ( stencil ) clear |= gl.STENCIL_BUFFER_BIT;
  40802. if ( clear !== 0 ) {
  40803. let clearColor;
  40804. if ( descriptor.clearColorValue ) {
  40805. clearColor = descriptor.clearColorValue;
  40806. } else {
  40807. clearColor = this.getClearColor();
  40808. // premultiply alpha
  40809. clearColor.r *= clearColor.a;
  40810. clearColor.g *= clearColor.a;
  40811. clearColor.b *= clearColor.a;
  40812. }
  40813. if ( depth ) this.state.setDepthMask( true );
  40814. if ( descriptor.textures === null ) {
  40815. gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearColor.a );
  40816. gl.clear( clear );
  40817. } else {
  40818. if ( setFrameBuffer ) this._setFramebuffer( descriptor );
  40819. if ( color ) {
  40820. for ( let i = 0; i < descriptor.textures.length; i ++ ) {
  40821. gl.clearBufferfv( gl.COLOR, i, [ clearColor.r, clearColor.g, clearColor.b, clearColor.a ] );
  40822. }
  40823. }
  40824. if ( depth && stencil ) {
  40825. gl.clearBufferfi( gl.DEPTH_STENCIL, 0, 1, 0 );
  40826. } else if ( depth ) {
  40827. gl.clearBufferfv( gl.DEPTH, 0, [ 1.0 ] );
  40828. } else if ( stencil ) {
  40829. gl.clearBufferiv( gl.STENCIL, 0, [ 0 ] );
  40830. }
  40831. }
  40832. }
  40833. }
  40834. beginCompute( computeGroup ) {
  40835. const { state, gl } = this;
  40836. state.bindFramebuffer( gl.FRAMEBUFFER, null );
  40837. this.initTimestampQuery( computeGroup );
  40838. }
  40839. compute( computeGroup, computeNode, bindings, pipeline ) {
  40840. const { state, gl } = this;
  40841. if ( ! this.discard ) {
  40842. // required here to handle async behaviour of render.compute()
  40843. gl.enable( gl.RASTERIZER_DISCARD );
  40844. this.discard = true;
  40845. }
  40846. const { programGPU, transformBuffers, attributes } = this.get( pipeline );
  40847. const vaoKey = this._getVaoKey( null, attributes );
  40848. const vaoGPU = this.vaoCache[ vaoKey ];
  40849. if ( vaoGPU === undefined ) {
  40850. this._createVao( null, attributes );
  40851. } else {
  40852. gl.bindVertexArray( vaoGPU );
  40853. }
  40854. state.useProgram( programGPU );
  40855. this._bindUniforms( bindings );
  40856. const transformFeedbackGPU = this._getTransformFeedback( transformBuffers );
  40857. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, transformFeedbackGPU );
  40858. gl.beginTransformFeedback( gl.POINTS );
  40859. if ( attributes[ 0 ].isStorageInstancedBufferAttribute ) {
  40860. gl.drawArraysInstanced( gl.POINTS, 0, 1, computeNode.count );
  40861. } else {
  40862. gl.drawArrays( gl.POINTS, 0, computeNode.count );
  40863. }
  40864. gl.endTransformFeedback();
  40865. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, null );
  40866. // switch active buffers
  40867. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  40868. const dualAttributeData = transformBuffers[ i ];
  40869. if ( dualAttributeData.pbo ) {
  40870. this.textureUtils.copyBufferToTexture( dualAttributeData.transformBuffer, dualAttributeData.pbo );
  40871. }
  40872. dualAttributeData.switchBuffers();
  40873. }
  40874. }
  40875. finishCompute( computeGroup ) {
  40876. const gl = this.gl;
  40877. this.discard = false;
  40878. gl.disable( gl.RASTERIZER_DISCARD );
  40879. this.prepareTimestampBuffer( computeGroup );
  40880. if ( this._currentContext ) {
  40881. this._setFramebuffer( this._currentContext );
  40882. }
  40883. }
  40884. draw( renderObject/*, info*/ ) {
  40885. const { object, pipeline, material, context } = renderObject;
  40886. const { programGPU } = this.get( pipeline );
  40887. const { gl, state } = this;
  40888. const contextData = this.get( context );
  40889. const drawParams = renderObject.getDrawParameters();
  40890. if ( drawParams === null ) return;
  40891. //
  40892. this._bindUniforms( renderObject.getBindings() );
  40893. const frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 );
  40894. state.setMaterial( material, frontFaceCW );
  40895. state.useProgram( programGPU );
  40896. //
  40897. let vaoGPU = renderObject.staticVao;
  40898. if ( vaoGPU === undefined ) {
  40899. const vaoKey = this._getVaoKey( renderObject.getIndex(), renderObject.getAttributes() );
  40900. vaoGPU = this.vaoCache[ vaoKey ];
  40901. if ( vaoGPU === undefined ) {
  40902. let staticVao;
  40903. ( { vaoGPU, staticVao } = this._createVao( renderObject.getIndex(), renderObject.getAttributes() ) );
  40904. if ( staticVao ) renderObject.staticVao = vaoGPU;
  40905. }
  40906. }
  40907. gl.bindVertexArray( vaoGPU );
  40908. //
  40909. const index = renderObject.getIndex();
  40910. //
  40911. const lastObject = contextData.lastOcclusionObject;
  40912. if ( lastObject !== object && lastObject !== undefined ) {
  40913. if ( lastObject !== null && lastObject.occlusionTest === true ) {
  40914. gl.endQuery( gl.ANY_SAMPLES_PASSED );
  40915. contextData.occlusionQueryIndex ++;
  40916. }
  40917. if ( object.occlusionTest === true ) {
  40918. const query = gl.createQuery();
  40919. gl.beginQuery( gl.ANY_SAMPLES_PASSED, query );
  40920. contextData.occlusionQueries[ contextData.occlusionQueryIndex ] = query;
  40921. contextData.occlusionQueryObjects[ contextData.occlusionQueryIndex ] = object;
  40922. }
  40923. contextData.lastOcclusionObject = object;
  40924. }
  40925. //
  40926. const renderer = this.bufferRenderer;
  40927. if ( object.isPoints ) renderer.mode = gl.POINTS;
  40928. else if ( object.isLineSegments ) renderer.mode = gl.LINES;
  40929. else if ( object.isLine ) renderer.mode = gl.LINE_STRIP;
  40930. else if ( object.isLineLoop ) renderer.mode = gl.LINE_LOOP;
  40931. else {
  40932. if ( material.wireframe === true ) {
  40933. state.setLineWidth( material.wireframeLinewidth * this.renderer.getPixelRatio() );
  40934. renderer.mode = gl.LINES;
  40935. } else {
  40936. renderer.mode = gl.TRIANGLES;
  40937. }
  40938. }
  40939. //
  40940. const { vertexCount, instanceCount } = drawParams;
  40941. let { firstVertex } = drawParams;
  40942. renderer.object = object;
  40943. if ( index !== null ) {
  40944. firstVertex *= index.array.BYTES_PER_ELEMENT;
  40945. const indexData = this.get( index );
  40946. renderer.index = index.count;
  40947. renderer.type = indexData.type;
  40948. } else {
  40949. renderer.index = 0;
  40950. }
  40951. if ( object.isBatchedMesh ) {
  40952. if ( object._multiDrawInstances !== null ) {
  40953. renderer.renderMultiDrawInstances( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount, object._multiDrawInstances );
  40954. } else if ( ! this.hasFeature( 'WEBGL_multi_draw' ) ) {
  40955. warnOnce( 'THREE.WebGLRenderer: WEBGL_multi_draw not supported.' );
  40956. } else {
  40957. renderer.renderMultiDraw( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount );
  40958. }
  40959. } else if ( instanceCount > 1 ) {
  40960. renderer.renderInstances( firstVertex, vertexCount, instanceCount );
  40961. } else {
  40962. renderer.render( firstVertex, vertexCount );
  40963. }
  40964. //
  40965. gl.bindVertexArray( null );
  40966. }
  40967. needsRenderUpdate( /*renderObject*/ ) {
  40968. return false;
  40969. }
  40970. getRenderCacheKey( /*renderObject*/ ) {
  40971. return '';
  40972. }
  40973. // textures
  40974. createDefaultTexture( texture ) {
  40975. this.textureUtils.createDefaultTexture( texture );
  40976. }
  40977. createTexture( texture, options ) {
  40978. this.textureUtils.createTexture( texture, options );
  40979. }
  40980. updateTexture( texture, options ) {
  40981. this.textureUtils.updateTexture( texture, options );
  40982. }
  40983. generateMipmaps( texture ) {
  40984. this.textureUtils.generateMipmaps( texture );
  40985. }
  40986. destroyTexture( texture ) {
  40987. this.textureUtils.destroyTexture( texture );
  40988. }
  40989. copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  40990. return this.textureUtils.copyTextureToBuffer( texture, x, y, width, height, faceIndex );
  40991. }
  40992. createSampler( /*texture*/ ) {
  40993. //console.warn( 'Abstract class.' );
  40994. }
  40995. destroySampler() {}
  40996. // node builder
  40997. createNodeBuilder( object, renderer ) {
  40998. return new GLSLNodeBuilder( object, renderer );
  40999. }
  41000. // program
  41001. createProgram( program ) {
  41002. const gl = this.gl;
  41003. const { stage, code } = program;
  41004. const shader = stage === 'fragment' ? gl.createShader( gl.FRAGMENT_SHADER ) : gl.createShader( gl.VERTEX_SHADER );
  41005. gl.shaderSource( shader, code );
  41006. gl.compileShader( shader );
  41007. this.set( program, {
  41008. shaderGPU: shader
  41009. } );
  41010. }
  41011. destroyProgram( /*program*/ ) {
  41012. console.warn( 'Abstract class.' );
  41013. }
  41014. createRenderPipeline( renderObject, promises ) {
  41015. const gl = this.gl;
  41016. const pipeline = renderObject.pipeline;
  41017. // Program
  41018. const { fragmentProgram, vertexProgram } = pipeline;
  41019. const programGPU = gl.createProgram();
  41020. const fragmentShader = this.get( fragmentProgram ).shaderGPU;
  41021. const vertexShader = this.get( vertexProgram ).shaderGPU;
  41022. gl.attachShader( programGPU, fragmentShader );
  41023. gl.attachShader( programGPU, vertexShader );
  41024. gl.linkProgram( programGPU );
  41025. this.set( pipeline, {
  41026. programGPU,
  41027. fragmentShader,
  41028. vertexShader
  41029. } );
  41030. if ( promises !== null && this.parallel ) {
  41031. const p = new Promise( ( resolve /*, reject*/ ) => {
  41032. const parallel = this.parallel;
  41033. const checkStatus = () => {
  41034. if ( gl.getProgramParameter( programGPU, parallel.COMPLETION_STATUS_KHR ) ) {
  41035. this._completeCompile( renderObject, pipeline );
  41036. resolve();
  41037. } else {
  41038. requestAnimationFrame( checkStatus );
  41039. }
  41040. };
  41041. checkStatus();
  41042. } );
  41043. promises.push( p );
  41044. return;
  41045. }
  41046. this._completeCompile( renderObject, pipeline );
  41047. }
  41048. _handleSource( string, errorLine ) {
  41049. const lines = string.split( '\n' );
  41050. const lines2 = [];
  41051. const from = Math.max( errorLine - 6, 0 );
  41052. const to = Math.min( errorLine + 6, lines.length );
  41053. for ( let i = from; i < to; i ++ ) {
  41054. const line = i + 1;
  41055. lines2.push( `${line === errorLine ? '>' : ' '} ${line}: ${lines[ i ]}` );
  41056. }
  41057. return lines2.join( '\n' );
  41058. }
  41059. _getShaderErrors( gl, shader, type ) {
  41060. const status = gl.getShaderParameter( shader, gl.COMPILE_STATUS );
  41061. const errors = gl.getShaderInfoLog( shader ).trim();
  41062. if ( status && errors === '' ) return '';
  41063. const errorMatches = /ERROR: 0:(\d+)/.exec( errors );
  41064. if ( errorMatches ) {
  41065. const errorLine = parseInt( errorMatches[ 1 ] );
  41066. return type.toUpperCase() + '\n\n' + errors + '\n\n' + this._handleSource( gl.getShaderSource( shader ), errorLine );
  41067. } else {
  41068. return errors;
  41069. }
  41070. }
  41071. _logProgramError( programGPU, glFragmentShader, glVertexShader ) {
  41072. if ( this.renderer.debug.checkShaderErrors ) {
  41073. const gl = this.gl;
  41074. const programLog = gl.getProgramInfoLog( programGPU ).trim();
  41075. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  41076. if ( typeof this.renderer.debug.onShaderError === 'function' ) {
  41077. this.renderer.debug.onShaderError( gl, programGPU, glVertexShader, glFragmentShader );
  41078. } else {
  41079. // default error reporting
  41080. const vertexErrors = this._getShaderErrors( gl, glVertexShader, 'vertex' );
  41081. const fragmentErrors = this._getShaderErrors( gl, glFragmentShader, 'fragment' );
  41082. console.error(
  41083. 'THREE.WebGLProgram: Shader Error ' + gl.getError() + ' - ' +
  41084. 'VALIDATE_STATUS ' + gl.getProgramParameter( programGPU, gl.VALIDATE_STATUS ) + '\n\n' +
  41085. 'Program Info Log: ' + programLog + '\n' +
  41086. vertexErrors + '\n' +
  41087. fragmentErrors
  41088. );
  41089. }
  41090. } else if ( programLog !== '' ) {
  41091. console.warn( 'THREE.WebGLProgram: Program Info Log:', programLog );
  41092. }
  41093. }
  41094. }
  41095. _completeCompile( renderObject, pipeline ) {
  41096. const { state, gl } = this;
  41097. const pipelineData = this.get( pipeline );
  41098. const { programGPU, fragmentShader, vertexShader } = pipelineData;
  41099. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  41100. this._logProgramError( programGPU, fragmentShader, vertexShader );
  41101. }
  41102. state.useProgram( programGPU );
  41103. // Bindings
  41104. const bindings = renderObject.getBindings();
  41105. this._setupBindings( bindings, programGPU );
  41106. //
  41107. this.set( pipeline, {
  41108. programGPU
  41109. } );
  41110. }
  41111. createComputePipeline( computePipeline, bindings ) {
  41112. const { state, gl } = this;
  41113. // Program
  41114. const fragmentProgram = {
  41115. stage: 'fragment',
  41116. code: '#version 300 es\nprecision highp float;\nvoid main() {}'
  41117. };
  41118. this.createProgram( fragmentProgram );
  41119. const { computeProgram } = computePipeline;
  41120. const programGPU = gl.createProgram();
  41121. const fragmentShader = this.get( fragmentProgram ).shaderGPU;
  41122. const vertexShader = this.get( computeProgram ).shaderGPU;
  41123. const transforms = computeProgram.transforms;
  41124. const transformVaryingNames = [];
  41125. const transformAttributeNodes = [];
  41126. for ( let i = 0; i < transforms.length; i ++ ) {
  41127. const transform = transforms[ i ];
  41128. transformVaryingNames.push( transform.varyingName );
  41129. transformAttributeNodes.push( transform.attributeNode );
  41130. }
  41131. gl.attachShader( programGPU, fragmentShader );
  41132. gl.attachShader( programGPU, vertexShader );
  41133. gl.transformFeedbackVaryings(
  41134. programGPU,
  41135. transformVaryingNames,
  41136. gl.SEPARATE_ATTRIBS
  41137. );
  41138. gl.linkProgram( programGPU );
  41139. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  41140. this._logProgramError( programGPU, fragmentShader, vertexShader );
  41141. }
  41142. state.useProgram( programGPU );
  41143. // Bindings
  41144. this.createBindings( null, bindings );
  41145. this._setupBindings( bindings, programGPU );
  41146. const attributeNodes = computeProgram.attributes;
  41147. const attributes = [];
  41148. const transformBuffers = [];
  41149. for ( let i = 0; i < attributeNodes.length; i ++ ) {
  41150. const attribute = attributeNodes[ i ].node.attribute;
  41151. attributes.push( attribute );
  41152. if ( ! this.has( attribute ) ) this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  41153. }
  41154. for ( let i = 0; i < transformAttributeNodes.length; i ++ ) {
  41155. const attribute = transformAttributeNodes[ i ].attribute;
  41156. if ( ! this.has( attribute ) ) this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  41157. const attributeData = this.get( attribute );
  41158. transformBuffers.push( attributeData );
  41159. }
  41160. //
  41161. this.set( computePipeline, {
  41162. programGPU,
  41163. transformBuffers,
  41164. attributes
  41165. } );
  41166. }
  41167. createBindings( bindGroup, bindings ) {
  41168. this.updateBindings( bindGroup, bindings );
  41169. }
  41170. updateBindings( bindGroup, bindings ) {
  41171. if ( ! bindGroup ) return;
  41172. const { gl } = this;
  41173. const bindingsData = this.get( bindings );
  41174. const bindGroupData = this.get( bindGroup );
  41175. if ( bindingsData.textureIndex === undefined ) bindingsData.textureIndex = 0;
  41176. if ( bindGroupData.textureIndex === undefined ) {
  41177. bindGroupData.textureIndex = bindingsData.textureIndex;
  41178. } else {
  41179. // reset textureIndex to match previous mappimgs when rebuilt
  41180. bindingsData.textureIndex = bindGroupData.textureIndex;
  41181. }
  41182. let i = 0;
  41183. for ( const binding of bindGroup.bindings ) {
  41184. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  41185. const data = binding.buffer;
  41186. const bufferGPU = gl.createBuffer();
  41187. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  41188. gl.bufferData( gl.UNIFORM_BUFFER, data, gl.DYNAMIC_DRAW );
  41189. this.set( binding, {
  41190. index: bindGroup.index * 2 + i ++,
  41191. bufferGPU
  41192. } );
  41193. } else if ( binding.isSampledTexture ) {
  41194. const { textureGPU, glTextureType } = this.get( binding.texture );
  41195. this.set( binding, {
  41196. index: bindingsData.textureIndex ++,
  41197. textureGPU,
  41198. glTextureType
  41199. } );
  41200. }
  41201. }
  41202. }
  41203. updateBinding( binding ) {
  41204. const gl = this.gl;
  41205. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  41206. const bindingData = this.get( binding );
  41207. const bufferGPU = bindingData.bufferGPU;
  41208. const data = binding.buffer;
  41209. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  41210. gl.bufferData( gl.UNIFORM_BUFFER, data, gl.DYNAMIC_DRAW );
  41211. }
  41212. }
  41213. // attributes
  41214. createIndexAttribute( attribute ) {
  41215. const gl = this.gl;
  41216. this.attributeUtils.createAttribute( attribute, gl.ELEMENT_ARRAY_BUFFER );
  41217. }
  41218. createAttribute( attribute ) {
  41219. if ( this.has( attribute ) ) return;
  41220. const gl = this.gl;
  41221. this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  41222. }
  41223. createStorageAttribute( attribute ) {
  41224. if ( this.has( attribute ) ) return;
  41225. const gl = this.gl;
  41226. this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  41227. }
  41228. updateAttribute( attribute ) {
  41229. this.attributeUtils.updateAttribute( attribute );
  41230. }
  41231. destroyAttribute( attribute ) {
  41232. this.attributeUtils.destroyAttribute( attribute );
  41233. }
  41234. updateSize() {
  41235. //console.warn( 'Abstract class.' );
  41236. }
  41237. hasFeature( name ) {
  41238. const keysMatching = Object.keys( GLFeatureName ).filter( key => GLFeatureName[ key ] === name );
  41239. const extensions = this.extensions;
  41240. for ( let i = 0; i < keysMatching.length; i ++ ) {
  41241. if ( extensions.has( keysMatching[ i ] ) ) return true;
  41242. }
  41243. return false;
  41244. }
  41245. getMaxAnisotropy() {
  41246. return this.capabilities.getMaxAnisotropy();
  41247. }
  41248. copyTextureToTexture( position, srcTexture, dstTexture, level ) {
  41249. this.textureUtils.copyTextureToTexture( position, srcTexture, dstTexture, level );
  41250. }
  41251. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  41252. this.textureUtils.copyFramebufferToTexture( texture, renderContext, rectangle );
  41253. }
  41254. _setFramebuffer( descriptor ) {
  41255. const { gl, state } = this;
  41256. let currentFrameBuffer = null;
  41257. if ( descriptor.textures !== null ) {
  41258. const renderTarget = descriptor.renderTarget;
  41259. const renderTargetContextData = this.get( renderTarget );
  41260. const { samples, depthBuffer, stencilBuffer } = renderTarget;
  41261. const isCube = renderTarget.isWebGLCubeRenderTarget === true;
  41262. let msaaFb = renderTargetContextData.msaaFrameBuffer;
  41263. let depthRenderbuffer = renderTargetContextData.depthRenderbuffer;
  41264. const cacheKey = getCacheKey( descriptor );
  41265. let fb;
  41266. if ( isCube ) {
  41267. renderTargetContextData.cubeFramebuffers || ( renderTargetContextData.cubeFramebuffers = {} );
  41268. fb = renderTargetContextData.cubeFramebuffers[ cacheKey ];
  41269. } else {
  41270. renderTargetContextData.framebuffers || ( renderTargetContextData.framebuffers = {} );
  41271. fb = renderTargetContextData.framebuffers[ cacheKey ];
  41272. }
  41273. if ( fb === undefined ) {
  41274. fb = gl.createFramebuffer();
  41275. state.bindFramebuffer( gl.FRAMEBUFFER, fb );
  41276. const textures = descriptor.textures;
  41277. if ( isCube ) {
  41278. renderTargetContextData.cubeFramebuffers[ cacheKey ] = fb;
  41279. const { textureGPU } = this.get( textures[ 0 ] );
  41280. const cubeFace = this.renderer._activeCubeFace;
  41281. gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + cubeFace, textureGPU, 0 );
  41282. } else {
  41283. renderTargetContextData.framebuffers[ cacheKey ] = fb;
  41284. for ( let i = 0; i < textures.length; i ++ ) {
  41285. const texture = textures[ i ];
  41286. const textureData = this.get( texture );
  41287. textureData.renderTarget = descriptor.renderTarget;
  41288. const attachment = gl.COLOR_ATTACHMENT0 + i;
  41289. gl.framebufferTexture2D( gl.FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  41290. }
  41291. state.drawBuffers( descriptor, fb );
  41292. }
  41293. if ( descriptor.depthTexture !== null ) {
  41294. const textureData = this.get( descriptor.depthTexture );
  41295. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  41296. gl.framebufferTexture2D( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  41297. }
  41298. }
  41299. if ( samples > 0 ) {
  41300. if ( msaaFb === undefined ) {
  41301. const invalidationArray = [];
  41302. msaaFb = gl.createFramebuffer();
  41303. state.bindFramebuffer( gl.FRAMEBUFFER, msaaFb );
  41304. const msaaRenderbuffers = [];
  41305. const textures = descriptor.textures;
  41306. for ( let i = 0; i < textures.length; i ++ ) {
  41307. msaaRenderbuffers[ i ] = gl.createRenderbuffer();
  41308. gl.bindRenderbuffer( gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  41309. invalidationArray.push( gl.COLOR_ATTACHMENT0 + i );
  41310. if ( depthBuffer ) {
  41311. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  41312. invalidationArray.push( depthStyle );
  41313. }
  41314. const texture = descriptor.textures[ i ];
  41315. const textureData = this.get( texture );
  41316. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, textureData.glInternalFormat, descriptor.width, descriptor.height );
  41317. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  41318. }
  41319. renderTargetContextData.msaaFrameBuffer = msaaFb;
  41320. renderTargetContextData.msaaRenderbuffers = msaaRenderbuffers;
  41321. if ( depthRenderbuffer === undefined ) {
  41322. depthRenderbuffer = gl.createRenderbuffer();
  41323. this.textureUtils.setupRenderBufferStorage( depthRenderbuffer, descriptor );
  41324. renderTargetContextData.depthRenderbuffer = depthRenderbuffer;
  41325. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  41326. invalidationArray.push( depthStyle );
  41327. }
  41328. renderTargetContextData.invalidationArray = invalidationArray;
  41329. }
  41330. currentFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  41331. } else {
  41332. currentFrameBuffer = fb;
  41333. }
  41334. }
  41335. state.bindFramebuffer( gl.FRAMEBUFFER, currentFrameBuffer );
  41336. }
  41337. _getVaoKey( index, attributes ) {
  41338. let key = [];
  41339. if ( index !== null ) {
  41340. const indexData = this.get( index );
  41341. key += ':' + indexData.id;
  41342. }
  41343. for ( let i = 0; i < attributes.length; i ++ ) {
  41344. const attributeData = this.get( attributes[ i ] );
  41345. key += ':' + attributeData.id;
  41346. }
  41347. return key;
  41348. }
  41349. _createVao( index, attributes ) {
  41350. const { gl } = this;
  41351. const vaoGPU = gl.createVertexArray();
  41352. let key = '';
  41353. let staticVao = true;
  41354. gl.bindVertexArray( vaoGPU );
  41355. if ( index !== null ) {
  41356. const indexData = this.get( index );
  41357. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, indexData.bufferGPU );
  41358. key += ':' + indexData.id;
  41359. }
  41360. for ( let i = 0; i < attributes.length; i ++ ) {
  41361. const attribute = attributes[ i ];
  41362. const attributeData = this.get( attribute );
  41363. key += ':' + attributeData.id;
  41364. gl.bindBuffer( gl.ARRAY_BUFFER, attributeData.bufferGPU );
  41365. gl.enableVertexAttribArray( i );
  41366. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) staticVao = false;
  41367. let stride, offset;
  41368. if ( attribute.isInterleavedBufferAttribute === true ) {
  41369. stride = attribute.data.stride * attributeData.bytesPerElement;
  41370. offset = attribute.offset * attributeData.bytesPerElement;
  41371. } else {
  41372. stride = 0;
  41373. offset = 0;
  41374. }
  41375. if ( attributeData.isInteger ) {
  41376. gl.vertexAttribIPointer( i, attribute.itemSize, attributeData.type, stride, offset );
  41377. } else {
  41378. gl.vertexAttribPointer( i, attribute.itemSize, attributeData.type, attribute.normalized, stride, offset );
  41379. }
  41380. if ( attribute.isInstancedBufferAttribute && ! attribute.isInterleavedBufferAttribute ) {
  41381. gl.vertexAttribDivisor( i, attribute.meshPerAttribute );
  41382. } else if ( attribute.isInterleavedBufferAttribute && attribute.data.isInstancedInterleavedBuffer ) {
  41383. gl.vertexAttribDivisor( i, attribute.data.meshPerAttribute );
  41384. }
  41385. }
  41386. gl.bindBuffer( gl.ARRAY_BUFFER, null );
  41387. this.vaoCache[ key ] = vaoGPU;
  41388. return { vaoGPU, staticVao };
  41389. }
  41390. _getTransformFeedback( transformBuffers ) {
  41391. let key = '';
  41392. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  41393. key += ':' + transformBuffers[ i ].id;
  41394. }
  41395. let transformFeedbackGPU = this.transformFeedbackCache[ key ];
  41396. if ( transformFeedbackGPU !== undefined ) {
  41397. return transformFeedbackGPU;
  41398. }
  41399. const { gl } = this;
  41400. transformFeedbackGPU = gl.createTransformFeedback();
  41401. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, transformFeedbackGPU );
  41402. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  41403. const attributeData = transformBuffers[ i ];
  41404. gl.bindBufferBase( gl.TRANSFORM_FEEDBACK_BUFFER, i, attributeData.transformBuffer );
  41405. }
  41406. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, null );
  41407. this.transformFeedbackCache[ key ] = transformFeedbackGPU;
  41408. return transformFeedbackGPU;
  41409. }
  41410. _setupBindings( bindings, programGPU ) {
  41411. const gl = this.gl;
  41412. for ( const bindGroup of bindings ) {
  41413. for ( const binding of bindGroup.bindings ) {
  41414. const bindingData = this.get( binding );
  41415. const index = bindingData.index;
  41416. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  41417. const location = gl.getUniformBlockIndex( programGPU, binding.name );
  41418. gl.uniformBlockBinding( programGPU, location, index );
  41419. } else if ( binding.isSampledTexture ) {
  41420. const location = gl.getUniformLocation( programGPU, binding.name );
  41421. gl.uniform1i( location, index );
  41422. }
  41423. }
  41424. }
  41425. }
  41426. _bindUniforms( bindings ) {
  41427. const { gl, state } = this;
  41428. for ( const bindGroup of bindings ) {
  41429. for ( const binding of bindGroup.bindings ) {
  41430. const bindingData = this.get( binding );
  41431. const index = bindingData.index;
  41432. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  41433. // TODO USE bindBufferRange to group multiple uniform buffers
  41434. state.bindBufferBase( gl.UNIFORM_BUFFER, index, bindingData.bufferGPU );
  41435. } else if ( binding.isSampledTexture ) {
  41436. state.bindTexture( bindingData.glTextureType, bindingData.textureGPU, gl.TEXTURE0 + index );
  41437. }
  41438. }
  41439. }
  41440. }
  41441. }
  41442. class Sampler extends Binding {
  41443. constructor( name, texture ) {
  41444. super( name );
  41445. this.texture = texture;
  41446. this.version = texture ? texture.version : 0;
  41447. this.isSampler = true;
  41448. }
  41449. }
  41450. class NodeSampler extends Sampler {
  41451. constructor( name, textureNode, groupNode ) {
  41452. super( name, textureNode ? textureNode.value : null );
  41453. this.textureNode = textureNode;
  41454. this.groupNode = groupNode;
  41455. }
  41456. update() {
  41457. this.texture = this.textureNode.value;
  41458. }
  41459. }
  41460. class StorageBuffer extends Buffer {
  41461. constructor( name, attribute ) {
  41462. super( name, attribute ? attribute.array : null );
  41463. this.attribute = attribute;
  41464. this.isStorageBuffer = true;
  41465. }
  41466. }
  41467. let _id = 0;
  41468. class NodeStorageBuffer extends StorageBuffer {
  41469. constructor( nodeUniform, groupNode ) {
  41470. super( 'StorageBuffer_' + _id ++, nodeUniform ? nodeUniform.value : null );
  41471. this.nodeUniform = nodeUniform;
  41472. this.access = nodeUniform ? nodeUniform.access : GPUBufferBindingType.Storage;
  41473. this.groupNode = groupNode;
  41474. }
  41475. get buffer() {
  41476. return this.nodeUniform.value;
  41477. }
  41478. }
  41479. class WebGPUTexturePassUtils extends DataMap {
  41480. constructor( device ) {
  41481. super();
  41482. this.device = device;
  41483. const mipmapVertexSource = `
  41484. struct VarysStruct {
  41485. @builtin( position ) Position: vec4<f32>,
  41486. @location( 0 ) vTex : vec2<f32>
  41487. };
  41488. @vertex
  41489. fn main( @builtin( vertex_index ) vertexIndex : u32 ) -> VarysStruct {
  41490. var Varys : VarysStruct;
  41491. var pos = array< vec2<f32>, 4 >(
  41492. vec2<f32>( -1.0, 1.0 ),
  41493. vec2<f32>( 1.0, 1.0 ),
  41494. vec2<f32>( -1.0, -1.0 ),
  41495. vec2<f32>( 1.0, -1.0 )
  41496. );
  41497. var tex = array< vec2<f32>, 4 >(
  41498. vec2<f32>( 0.0, 0.0 ),
  41499. vec2<f32>( 1.0, 0.0 ),
  41500. vec2<f32>( 0.0, 1.0 ),
  41501. vec2<f32>( 1.0, 1.0 )
  41502. );
  41503. Varys.vTex = tex[ vertexIndex ];
  41504. Varys.Position = vec4<f32>( pos[ vertexIndex ], 0.0, 1.0 );
  41505. return Varys;
  41506. }
  41507. `;
  41508. const mipmapFragmentSource = `
  41509. @group( 0 ) @binding( 0 )
  41510. var imgSampler : sampler;
  41511. @group( 0 ) @binding( 1 )
  41512. var img : texture_2d<f32>;
  41513. @fragment
  41514. fn main( @location( 0 ) vTex : vec2<f32> ) -> @location( 0 ) vec4<f32> {
  41515. return textureSample( img, imgSampler, vTex );
  41516. }
  41517. `;
  41518. const flipYFragmentSource = `
  41519. @group( 0 ) @binding( 0 )
  41520. var imgSampler : sampler;
  41521. @group( 0 ) @binding( 1 )
  41522. var img : texture_2d<f32>;
  41523. @fragment
  41524. fn main( @location( 0 ) vTex : vec2<f32> ) -> @location( 0 ) vec4<f32> {
  41525. return textureSample( img, imgSampler, vec2( vTex.x, 1.0 - vTex.y ) );
  41526. }
  41527. `;
  41528. this.mipmapSampler = device.createSampler( { minFilter: GPUFilterMode.Linear } );
  41529. this.flipYSampler = device.createSampler( { minFilter: GPUFilterMode.Nearest } ); //@TODO?: Consider using textureLoad()
  41530. // We'll need a new pipeline for every texture format used.
  41531. this.transferPipelines = {};
  41532. this.flipYPipelines = {};
  41533. this.mipmapVertexShaderModule = device.createShaderModule( {
  41534. label: 'mipmapVertex',
  41535. code: mipmapVertexSource
  41536. } );
  41537. this.mipmapFragmentShaderModule = device.createShaderModule( {
  41538. label: 'mipmapFragment',
  41539. code: mipmapFragmentSource
  41540. } );
  41541. this.flipYFragmentShaderModule = device.createShaderModule( {
  41542. label: 'flipYFragment',
  41543. code: flipYFragmentSource
  41544. } );
  41545. }
  41546. getTransferPipeline( format ) {
  41547. let pipeline = this.transferPipelines[ format ];
  41548. if ( pipeline === undefined ) {
  41549. pipeline = this.device.createRenderPipeline( {
  41550. label: `mipmap-${ format }`,
  41551. vertex: {
  41552. module: this.mipmapVertexShaderModule,
  41553. entryPoint: 'main'
  41554. },
  41555. fragment: {
  41556. module: this.mipmapFragmentShaderModule,
  41557. entryPoint: 'main',
  41558. targets: [ { format } ]
  41559. },
  41560. primitive: {
  41561. topology: GPUPrimitiveTopology.TriangleStrip,
  41562. stripIndexFormat: GPUIndexFormat.Uint32
  41563. },
  41564. layout: 'auto'
  41565. } );
  41566. this.transferPipelines[ format ] = pipeline;
  41567. }
  41568. return pipeline;
  41569. }
  41570. getFlipYPipeline( format ) {
  41571. let pipeline = this.flipYPipelines[ format ];
  41572. if ( pipeline === undefined ) {
  41573. pipeline = this.device.createRenderPipeline( {
  41574. label: `flipY-${ format }`,
  41575. vertex: {
  41576. module: this.mipmapVertexShaderModule,
  41577. entryPoint: 'main'
  41578. },
  41579. fragment: {
  41580. module: this.flipYFragmentShaderModule,
  41581. entryPoint: 'main',
  41582. targets: [ { format } ]
  41583. },
  41584. primitive: {
  41585. topology: GPUPrimitiveTopology.TriangleStrip,
  41586. stripIndexFormat: GPUIndexFormat.Uint32
  41587. },
  41588. layout: 'auto'
  41589. } );
  41590. this.flipYPipelines[ format ] = pipeline;
  41591. }
  41592. return pipeline;
  41593. }
  41594. flipY( textureGPU, textureGPUDescriptor, baseArrayLayer = 0 ) {
  41595. const format = textureGPUDescriptor.format;
  41596. const { width, height } = textureGPUDescriptor.size;
  41597. const transferPipeline = this.getTransferPipeline( format );
  41598. const flipYPipeline = this.getFlipYPipeline( format );
  41599. const tempTexture = this.device.createTexture( {
  41600. size: { width, height, depthOrArrayLayers: 1 },
  41601. format,
  41602. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.TEXTURE_BINDING
  41603. } );
  41604. const srcView = textureGPU.createView( {
  41605. baseMipLevel: 0,
  41606. mipLevelCount: 1,
  41607. dimension: GPUTextureViewDimension.TwoD,
  41608. baseArrayLayer
  41609. } );
  41610. const dstView = tempTexture.createView( {
  41611. baseMipLevel: 0,
  41612. mipLevelCount: 1,
  41613. dimension: GPUTextureViewDimension.TwoD,
  41614. baseArrayLayer: 0
  41615. } );
  41616. const commandEncoder = this.device.createCommandEncoder( {} );
  41617. const pass = ( pipeline, sourceView, destinationView ) => {
  41618. const bindGroupLayout = pipeline.getBindGroupLayout( 0 ); // @TODO: Consider making this static.
  41619. const bindGroup = this.device.createBindGroup( {
  41620. layout: bindGroupLayout,
  41621. entries: [ {
  41622. binding: 0,
  41623. resource: this.flipYSampler
  41624. }, {
  41625. binding: 1,
  41626. resource: sourceView
  41627. } ]
  41628. } );
  41629. const passEncoder = commandEncoder.beginRenderPass( {
  41630. colorAttachments: [ {
  41631. view: destinationView,
  41632. loadOp: GPULoadOp.Clear,
  41633. storeOp: GPUStoreOp.Store,
  41634. clearValue: [ 0, 0, 0, 0 ]
  41635. } ]
  41636. } );
  41637. passEncoder.setPipeline( pipeline );
  41638. passEncoder.setBindGroup( 0, bindGroup );
  41639. passEncoder.draw( 4, 1, 0, 0 );
  41640. passEncoder.end();
  41641. };
  41642. pass( transferPipeline, srcView, dstView );
  41643. pass( flipYPipeline, dstView, srcView );
  41644. this.device.queue.submit( [ commandEncoder.finish() ] );
  41645. tempTexture.destroy();
  41646. }
  41647. generateMipmaps( textureGPU, textureGPUDescriptor, baseArrayLayer = 0 ) {
  41648. const textureData = this.get( textureGPU );
  41649. if ( textureData.useCount === undefined ) {
  41650. textureData.useCount = 0;
  41651. textureData.layers = [];
  41652. }
  41653. const passes = textureData.layers[ baseArrayLayer ] || this._mipmapCreateBundles( textureGPU, textureGPUDescriptor, baseArrayLayer );
  41654. const commandEncoder = this.device.createCommandEncoder( {} );
  41655. this._mipmapRunBundles( commandEncoder, passes );
  41656. this.device.queue.submit( [ commandEncoder.finish() ] );
  41657. if ( textureData.useCount !== 0 ) textureData.layers[ baseArrayLayer ] = passes;
  41658. textureData.useCount ++;
  41659. }
  41660. _mipmapCreateBundles( textureGPU, textureGPUDescriptor, baseArrayLayer ) {
  41661. const pipeline = this.getTransferPipeline( textureGPUDescriptor.format );
  41662. const bindGroupLayout = pipeline.getBindGroupLayout( 0 ); // @TODO: Consider making this static.
  41663. let srcView = textureGPU.createView( {
  41664. baseMipLevel: 0,
  41665. mipLevelCount: 1,
  41666. dimension: GPUTextureViewDimension.TwoD,
  41667. baseArrayLayer
  41668. } );
  41669. const passes = [];
  41670. for ( let i = 1; i < textureGPUDescriptor.mipLevelCount; i ++ ) {
  41671. const bindGroup = this.device.createBindGroup( {
  41672. layout: bindGroupLayout,
  41673. entries: [ {
  41674. binding: 0,
  41675. resource: this.mipmapSampler
  41676. }, {
  41677. binding: 1,
  41678. resource: srcView
  41679. } ]
  41680. } );
  41681. const dstView = textureGPU.createView( {
  41682. baseMipLevel: i,
  41683. mipLevelCount: 1,
  41684. dimension: GPUTextureViewDimension.TwoD,
  41685. baseArrayLayer
  41686. } );
  41687. const passDescriptor = {
  41688. colorAttachments: [ {
  41689. view: dstView,
  41690. loadOp: GPULoadOp.Clear,
  41691. storeOp: GPUStoreOp.Store,
  41692. clearValue: [ 0, 0, 0, 0 ]
  41693. } ]
  41694. };
  41695. const passEncoder = this.device.createRenderBundleEncoder( {
  41696. colorFormats: [ textureGPUDescriptor.format ]
  41697. } );
  41698. passEncoder.setPipeline( pipeline );
  41699. passEncoder.setBindGroup( 0, bindGroup );
  41700. passEncoder.draw( 4, 1, 0, 0 );
  41701. passes.push( {
  41702. renderBundles: [ passEncoder.finish() ],
  41703. passDescriptor
  41704. } );
  41705. srcView = dstView;
  41706. }
  41707. return passes;
  41708. }
  41709. _mipmapRunBundles( commandEncoder, passes ) {
  41710. const levels = passes.length;
  41711. for ( let i = 0; i < levels; i ++ ) {
  41712. const pass = passes[ i ];
  41713. const passEncoder = commandEncoder.beginRenderPass( pass.passDescriptor );
  41714. passEncoder.executeBundles( pass.renderBundles );
  41715. passEncoder.end();
  41716. }
  41717. }
  41718. }
  41719. const _compareToWebGPU = {
  41720. [ NeverCompare ]: 'never',
  41721. [ LessCompare ]: 'less',
  41722. [ EqualCompare ]: 'equal',
  41723. [ LessEqualCompare ]: 'less-equal',
  41724. [ GreaterCompare ]: 'greater',
  41725. [ GreaterEqualCompare ]: 'greater-equal',
  41726. [ AlwaysCompare ]: 'always',
  41727. [ NotEqualCompare ]: 'not-equal'
  41728. };
  41729. const _flipMap = [ 0, 1, 3, 2, 4, 5 ];
  41730. class WebGPUTextureUtils {
  41731. constructor( backend ) {
  41732. this.backend = backend;
  41733. this._passUtils = null;
  41734. this.defaultTexture = {};
  41735. this.defaultCubeTexture = {};
  41736. this.defaultVideoFrame = null;
  41737. this.colorBuffer = null;
  41738. this.depthTexture = new DepthTexture();
  41739. this.depthTexture.name = 'depthBuffer';
  41740. }
  41741. createSampler( texture ) {
  41742. const backend = this.backend;
  41743. const device = backend.device;
  41744. const textureGPU = backend.get( texture );
  41745. const samplerDescriptorGPU = {
  41746. addressModeU: this._convertAddressMode( texture.wrapS ),
  41747. addressModeV: this._convertAddressMode( texture.wrapT ),
  41748. addressModeW: this._convertAddressMode( texture.wrapR ),
  41749. magFilter: this._convertFilterMode( texture.magFilter ),
  41750. minFilter: this._convertFilterMode( texture.minFilter ),
  41751. mipmapFilter: this._convertFilterMode( texture.minFilter ),
  41752. maxAnisotropy: texture.anisotropy
  41753. };
  41754. if ( texture.isDepthTexture && texture.compareFunction !== null ) {
  41755. samplerDescriptorGPU.compare = _compareToWebGPU[ texture.compareFunction ];
  41756. }
  41757. textureGPU.sampler = device.createSampler( samplerDescriptorGPU );
  41758. }
  41759. createDefaultTexture( texture ) {
  41760. let textureGPU;
  41761. const format = getFormat( texture );
  41762. if ( texture.isCubeTexture ) {
  41763. textureGPU = this._getDefaultCubeTextureGPU( format );
  41764. } else if ( texture.isVideoTexture ) {
  41765. this.backend.get( texture ).externalTexture = this._getDefaultVideoFrame();
  41766. } else {
  41767. textureGPU = this._getDefaultTextureGPU( format );
  41768. }
  41769. this.backend.get( texture ).texture = textureGPU;
  41770. }
  41771. createTexture( texture, options = {} ) {
  41772. const backend = this.backend;
  41773. const textureData = backend.get( texture );
  41774. if ( textureData.initialized ) {
  41775. throw new Error( 'WebGPUTextureUtils: Texture already initialized.' );
  41776. }
  41777. if ( options.needsMipmaps === undefined ) options.needsMipmaps = false;
  41778. if ( options.levels === undefined ) options.levels = 1;
  41779. if ( options.depth === undefined ) options.depth = 1;
  41780. const { width, height, depth, levels } = options;
  41781. const dimension = this._getDimension( texture );
  41782. const format = texture.internalFormat || options.format || getFormat( texture, backend.device );
  41783. textureData.format = format;
  41784. let sampleCount = options.sampleCount !== undefined ? options.sampleCount : 1;
  41785. sampleCount = backend.utils.getSampleCount( sampleCount );
  41786. const primarySampleCount = texture.isRenderTargetTexture && ! texture.isMultisampleRenderTargetTexture ? 1 : sampleCount;
  41787. let usage = GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST | GPUTextureUsage.COPY_SRC;
  41788. if ( texture.isStorageTexture === true ) {
  41789. usage |= GPUTextureUsage.STORAGE_BINDING;
  41790. }
  41791. if ( texture.isCompressedTexture !== true && texture.isCompressedArrayTexture !== true ) {
  41792. usage |= GPUTextureUsage.RENDER_ATTACHMENT;
  41793. }
  41794. const textureDescriptorGPU = {
  41795. label: texture.name,
  41796. size: {
  41797. width: width,
  41798. height: height,
  41799. depthOrArrayLayers: depth,
  41800. },
  41801. mipLevelCount: levels,
  41802. sampleCount: primarySampleCount,
  41803. dimension: dimension,
  41804. format: format,
  41805. usage: usage
  41806. };
  41807. // texture creation
  41808. if ( texture.isVideoTexture ) {
  41809. const video = texture.source.data;
  41810. const videoFrame = new VideoFrame( video );
  41811. textureDescriptorGPU.size.width = videoFrame.displayWidth;
  41812. textureDescriptorGPU.size.height = videoFrame.displayHeight;
  41813. videoFrame.close();
  41814. textureData.externalTexture = video;
  41815. } else {
  41816. if ( format === undefined ) {
  41817. console.warn( 'WebGPURenderer: Texture format not supported.' );
  41818. return this.createDefaultTexture( texture );
  41819. }
  41820. textureData.texture = backend.device.createTexture( textureDescriptorGPU );
  41821. }
  41822. if ( texture.isRenderTargetTexture && sampleCount > 1 && ! texture.isMultisampleRenderTargetTexture ) {
  41823. const msaaTextureDescriptorGPU = Object.assign( {}, textureDescriptorGPU );
  41824. msaaTextureDescriptorGPU.label = msaaTextureDescriptorGPU.label + '-msaa';
  41825. msaaTextureDescriptorGPU.sampleCount = sampleCount;
  41826. textureData.msaaTexture = backend.device.createTexture( msaaTextureDescriptorGPU );
  41827. }
  41828. textureData.initialized = true;
  41829. textureData.textureDescriptorGPU = textureDescriptorGPU;
  41830. }
  41831. destroyTexture( texture ) {
  41832. const backend = this.backend;
  41833. const textureData = backend.get( texture );
  41834. textureData.texture.destroy();
  41835. if ( textureData.msaaTexture !== undefined ) textureData.msaaTexture.destroy();
  41836. backend.delete( texture );
  41837. }
  41838. destroySampler( texture ) {
  41839. const backend = this.backend;
  41840. const textureData = backend.get( texture );
  41841. delete textureData.sampler;
  41842. }
  41843. generateMipmaps( texture ) {
  41844. const textureData = this.backend.get( texture );
  41845. if ( texture.isCubeTexture ) {
  41846. for ( let i = 0; i < 6; i ++ ) {
  41847. this._generateMipmaps( textureData.texture, textureData.textureDescriptorGPU, i );
  41848. }
  41849. } else {
  41850. const depth = texture.image.depth || 1;
  41851. for ( let i = 0; i < depth; i ++ ) {
  41852. this._generateMipmaps( textureData.texture, textureData.textureDescriptorGPU, i );
  41853. }
  41854. }
  41855. }
  41856. getColorBuffer() {
  41857. if ( this.colorBuffer ) this.colorBuffer.destroy();
  41858. const backend = this.backend;
  41859. const { width, height } = backend.getDrawingBufferSize();
  41860. this.colorBuffer = backend.device.createTexture( {
  41861. label: 'colorBuffer',
  41862. size: {
  41863. width: width,
  41864. height: height,
  41865. depthOrArrayLayers: 1
  41866. },
  41867. sampleCount: backend.utils.getSampleCount( backend.renderer.samples ),
  41868. format: backend.utils.getPreferredCanvasFormat(),
  41869. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC
  41870. } );
  41871. return this.colorBuffer;
  41872. }
  41873. getDepthBuffer( depth = true, stencil = false ) {
  41874. const backend = this.backend;
  41875. const { width, height } = backend.getDrawingBufferSize();
  41876. const depthTexture = this.depthTexture;
  41877. const depthTextureGPU = backend.get( depthTexture ).texture;
  41878. let format, type;
  41879. if ( stencil ) {
  41880. format = DepthStencilFormat;
  41881. type = UnsignedInt248Type;
  41882. } else if ( depth ) {
  41883. format = DepthFormat;
  41884. type = UnsignedIntType;
  41885. }
  41886. if ( depthTextureGPU !== undefined ) {
  41887. if ( depthTexture.image.width === width && depthTexture.image.height === height && depthTexture.format === format && depthTexture.type === type ) {
  41888. return depthTextureGPU;
  41889. }
  41890. this.destroyTexture( depthTexture );
  41891. }
  41892. depthTexture.name = 'depthBuffer';
  41893. depthTexture.format = format;
  41894. depthTexture.type = type;
  41895. depthTexture.image.width = width;
  41896. depthTexture.image.height = height;
  41897. this.createTexture( depthTexture, { sampleCount: backend.utils.getSampleCount( backend.renderer.samples ), width, height } );
  41898. return backend.get( depthTexture ).texture;
  41899. }
  41900. updateTexture( texture, options ) {
  41901. const textureData = this.backend.get( texture );
  41902. const { textureDescriptorGPU } = textureData;
  41903. if ( texture.isRenderTargetTexture || ( textureDescriptorGPU === undefined /* unsupported texture format */ ) )
  41904. return;
  41905. // transfer texture data
  41906. if ( texture.isDataTexture ) {
  41907. this._copyBufferToTexture( options.image, textureData.texture, textureDescriptorGPU, 0, texture.flipY );
  41908. } else if ( texture.isDataArrayTexture || texture.isData3DTexture ) {
  41909. for ( let i = 0; i < options.image.depth; i ++ ) {
  41910. this._copyBufferToTexture( options.image, textureData.texture, textureDescriptorGPU, i, texture.flipY, i );
  41911. }
  41912. } else if ( texture.isCompressedTexture || texture.isCompressedArrayTexture ) {
  41913. this._copyCompressedBufferToTexture( texture.mipmaps, textureData.texture, textureDescriptorGPU );
  41914. } else if ( texture.isCubeTexture ) {
  41915. this._copyCubeMapToTexture( options.images, textureData.texture, textureDescriptorGPU, texture.flipY );
  41916. } else if ( texture.isVideoTexture ) {
  41917. const video = texture.source.data;
  41918. textureData.externalTexture = video;
  41919. } else {
  41920. this._copyImageToTexture( options.image, textureData.texture, textureDescriptorGPU, 0, texture.flipY );
  41921. }
  41922. //
  41923. textureData.version = texture.version;
  41924. if ( texture.onUpdate ) texture.onUpdate( texture );
  41925. }
  41926. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  41927. const device = this.backend.device;
  41928. const textureData = this.backend.get( texture );
  41929. const textureGPU = textureData.texture;
  41930. const format = textureData.textureDescriptorGPU.format;
  41931. const bytesPerTexel = this._getBytesPerTexel( format );
  41932. let bytesPerRow = width * bytesPerTexel;
  41933. bytesPerRow = Math.ceil( bytesPerRow / 256 ) * 256; // Align to 256 bytes
  41934. const readBuffer = device.createBuffer(
  41935. {
  41936. size: width * height * bytesPerTexel,
  41937. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  41938. }
  41939. );
  41940. const encoder = device.createCommandEncoder();
  41941. encoder.copyTextureToBuffer(
  41942. {
  41943. texture: textureGPU,
  41944. origin: { x, y, z: faceIndex },
  41945. },
  41946. {
  41947. buffer: readBuffer,
  41948. bytesPerRow: bytesPerRow
  41949. },
  41950. {
  41951. width: width,
  41952. height: height
  41953. }
  41954. );
  41955. const typedArrayType = this._getTypedArrayType( format );
  41956. device.queue.submit( [ encoder.finish() ] );
  41957. await readBuffer.mapAsync( GPUMapMode.READ );
  41958. const buffer = readBuffer.getMappedRange();
  41959. return new typedArrayType( buffer );
  41960. }
  41961. _isEnvironmentTexture( texture ) {
  41962. const mapping = texture.mapping;
  41963. return ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) || ( mapping === CubeReflectionMapping || mapping === CubeRefractionMapping );
  41964. }
  41965. _getDefaultTextureGPU( format ) {
  41966. let defaultTexture = this.defaultTexture[ format ];
  41967. if ( defaultTexture === undefined ) {
  41968. const texture = new Texture();
  41969. texture.minFilter = NearestFilter;
  41970. texture.magFilter = NearestFilter;
  41971. this.createTexture( texture, { width: 1, height: 1, format } );
  41972. this.defaultTexture[ format ] = defaultTexture = texture;
  41973. }
  41974. return this.backend.get( defaultTexture ).texture;
  41975. }
  41976. _getDefaultCubeTextureGPU( format ) {
  41977. let defaultCubeTexture = this.defaultTexture[ format ];
  41978. if ( defaultCubeTexture === undefined ) {
  41979. const texture = new CubeTexture();
  41980. texture.minFilter = NearestFilter;
  41981. texture.magFilter = NearestFilter;
  41982. this.createTexture( texture, { width: 1, height: 1, depth: 6 } );
  41983. this.defaultCubeTexture[ format ] = defaultCubeTexture = texture;
  41984. }
  41985. return this.backend.get( defaultCubeTexture ).texture;
  41986. }
  41987. _getDefaultVideoFrame() {
  41988. let defaultVideoFrame = this.defaultVideoFrame;
  41989. if ( defaultVideoFrame === null ) {
  41990. const init = {
  41991. timestamp: 0,
  41992. codedWidth: 1,
  41993. codedHeight: 1,
  41994. format: 'RGBA',
  41995. };
  41996. this.defaultVideoFrame = defaultVideoFrame = new VideoFrame( new Uint8Array( [ 0, 0, 0, 0xff ] ), init );
  41997. }
  41998. return defaultVideoFrame;
  41999. }
  42000. _copyCubeMapToTexture( images, textureGPU, textureDescriptorGPU, flipY ) {
  42001. for ( let i = 0; i < 6; i ++ ) {
  42002. const image = images[ i ];
  42003. const flipIndex = flipY === true ? _flipMap[ i ] : i;
  42004. if ( image.isDataTexture ) {
  42005. this._copyBufferToTexture( image.image, textureGPU, textureDescriptorGPU, flipIndex, flipY );
  42006. } else {
  42007. this._copyImageToTexture( image, textureGPU, textureDescriptorGPU, flipIndex, flipY );
  42008. }
  42009. }
  42010. }
  42011. _copyImageToTexture( image, textureGPU, textureDescriptorGPU, originDepth, flipY ) {
  42012. const device = this.backend.device;
  42013. device.queue.copyExternalImageToTexture(
  42014. {
  42015. source: image
  42016. }, {
  42017. texture: textureGPU,
  42018. mipLevel: 0,
  42019. origin: { x: 0, y: 0, z: originDepth }
  42020. }, {
  42021. width: image.width,
  42022. height: image.height,
  42023. depthOrArrayLayers: 1
  42024. }
  42025. );
  42026. if ( flipY === true ) {
  42027. this._flipY( textureGPU, textureDescriptorGPU, originDepth );
  42028. }
  42029. }
  42030. _getPassUtils() {
  42031. let passUtils = this._passUtils;
  42032. if ( passUtils === null ) {
  42033. this._passUtils = passUtils = new WebGPUTexturePassUtils( this.backend.device );
  42034. }
  42035. return passUtils;
  42036. }
  42037. _generateMipmaps( textureGPU, textureDescriptorGPU, baseArrayLayer = 0 ) {
  42038. this._getPassUtils().generateMipmaps( textureGPU, textureDescriptorGPU, baseArrayLayer );
  42039. }
  42040. _flipY( textureGPU, textureDescriptorGPU, originDepth = 0 ) {
  42041. this._getPassUtils().flipY( textureGPU, textureDescriptorGPU, originDepth );
  42042. }
  42043. _copyBufferToTexture( image, textureGPU, textureDescriptorGPU, originDepth, flipY, depth = 0 ) {
  42044. // @TODO: Consider to use GPUCommandEncoder.copyBufferToTexture()
  42045. // @TODO: Consider to support valid buffer layouts with other formats like RGB
  42046. const device = this.backend.device;
  42047. const data = image.data;
  42048. const bytesPerTexel = this._getBytesPerTexel( textureDescriptorGPU.format );
  42049. const bytesPerRow = image.width * bytesPerTexel;
  42050. device.queue.writeTexture(
  42051. {
  42052. texture: textureGPU,
  42053. mipLevel: 0,
  42054. origin: { x: 0, y: 0, z: originDepth }
  42055. },
  42056. data,
  42057. {
  42058. offset: image.width * image.height * bytesPerTexel * depth,
  42059. bytesPerRow
  42060. },
  42061. {
  42062. width: image.width,
  42063. height: image.height,
  42064. depthOrArrayLayers: 1
  42065. } );
  42066. if ( flipY === true ) {
  42067. this._flipY( textureGPU, textureDescriptorGPU, originDepth );
  42068. }
  42069. }
  42070. _copyCompressedBufferToTexture( mipmaps, textureGPU, textureDescriptorGPU ) {
  42071. // @TODO: Consider to use GPUCommandEncoder.copyBufferToTexture()
  42072. const device = this.backend.device;
  42073. const blockData = this._getBlockData( textureDescriptorGPU.format );
  42074. const isTextureArray = textureDescriptorGPU.size.depthOrArrayLayers > 1;
  42075. for ( let i = 0; i < mipmaps.length; i ++ ) {
  42076. const mipmap = mipmaps[ i ];
  42077. const width = mipmap.width;
  42078. const height = mipmap.height;
  42079. const depth = isTextureArray ? textureDescriptorGPU.size.depthOrArrayLayers : 1;
  42080. const bytesPerRow = Math.ceil( width / blockData.width ) * blockData.byteLength;
  42081. const bytesPerImage = bytesPerRow * Math.ceil( height / blockData.height );
  42082. for ( let j = 0; j < depth; j ++ ) {
  42083. device.queue.writeTexture(
  42084. {
  42085. texture: textureGPU,
  42086. mipLevel: i,
  42087. origin: { x: 0, y: 0, z: j }
  42088. },
  42089. mipmap.data,
  42090. {
  42091. offset: j * bytesPerImage,
  42092. bytesPerRow,
  42093. rowsPerImage: Math.ceil( height / blockData.height )
  42094. },
  42095. {
  42096. width: Math.ceil( width / blockData.width ) * blockData.width,
  42097. height: Math.ceil( height / blockData.height ) * blockData.height,
  42098. depthOrArrayLayers: 1
  42099. }
  42100. );
  42101. }
  42102. }
  42103. }
  42104. _getBlockData( format ) {
  42105. // this method is only relevant for compressed texture formats
  42106. if ( format === GPUTextureFormat.BC1RGBAUnorm || format === GPUTextureFormat.BC1RGBAUnormSRGB ) return { byteLength: 8, width: 4, height: 4 }; // DXT1
  42107. if ( format === GPUTextureFormat.BC2RGBAUnorm || format === GPUTextureFormat.BC2RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // DXT3
  42108. if ( format === GPUTextureFormat.BC3RGBAUnorm || format === GPUTextureFormat.BC3RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // DXT5
  42109. if ( format === GPUTextureFormat.BC4RUnorm || format === GPUTextureFormat.BC4RSNorm ) return { byteLength: 8, width: 4, height: 4 }; // RGTC1
  42110. if ( format === GPUTextureFormat.BC5RGUnorm || format === GPUTextureFormat.BC5RGSnorm ) return { byteLength: 16, width: 4, height: 4 }; // RGTC2
  42111. if ( format === GPUTextureFormat.BC6HRGBUFloat || format === GPUTextureFormat.BC6HRGBFloat ) return { byteLength: 16, width: 4, height: 4 }; // BPTC (float)
  42112. if ( format === GPUTextureFormat.BC7RGBAUnorm || format === GPUTextureFormat.BC7RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // BPTC (unorm)
  42113. if ( format === GPUTextureFormat.ETC2RGB8Unorm || format === GPUTextureFormat.ETC2RGB8UnormSRGB ) return { byteLength: 8, width: 4, height: 4 };
  42114. if ( format === GPUTextureFormat.ETC2RGB8A1Unorm || format === GPUTextureFormat.ETC2RGB8A1UnormSRGB ) return { byteLength: 8, width: 4, height: 4 };
  42115. if ( format === GPUTextureFormat.ETC2RGBA8Unorm || format === GPUTextureFormat.ETC2RGBA8UnormSRGB ) return { byteLength: 16, width: 4, height: 4 };
  42116. if ( format === GPUTextureFormat.EACR11Unorm ) return { byteLength: 8, width: 4, height: 4 };
  42117. if ( format === GPUTextureFormat.EACR11Snorm ) return { byteLength: 8, width: 4, height: 4 };
  42118. if ( format === GPUTextureFormat.EACRG11Unorm ) return { byteLength: 16, width: 4, height: 4 };
  42119. if ( format === GPUTextureFormat.EACRG11Snorm ) return { byteLength: 16, width: 4, height: 4 };
  42120. if ( format === GPUTextureFormat.ASTC4x4Unorm || format === GPUTextureFormat.ASTC4x4UnormSRGB ) return { byteLength: 16, width: 4, height: 4 };
  42121. if ( format === GPUTextureFormat.ASTC5x4Unorm || format === GPUTextureFormat.ASTC5x4UnormSRGB ) return { byteLength: 16, width: 5, height: 4 };
  42122. if ( format === GPUTextureFormat.ASTC5x5Unorm || format === GPUTextureFormat.ASTC5x5UnormSRGB ) return { byteLength: 16, width: 5, height: 5 };
  42123. if ( format === GPUTextureFormat.ASTC6x5Unorm || format === GPUTextureFormat.ASTC6x5UnormSRGB ) return { byteLength: 16, width: 6, height: 5 };
  42124. if ( format === GPUTextureFormat.ASTC6x6Unorm || format === GPUTextureFormat.ASTC6x6UnormSRGB ) return { byteLength: 16, width: 6, height: 6 };
  42125. if ( format === GPUTextureFormat.ASTC8x5Unorm || format === GPUTextureFormat.ASTC8x5UnormSRGB ) return { byteLength: 16, width: 8, height: 5 };
  42126. if ( format === GPUTextureFormat.ASTC8x6Unorm || format === GPUTextureFormat.ASTC8x6UnormSRGB ) return { byteLength: 16, width: 8, height: 6 };
  42127. if ( format === GPUTextureFormat.ASTC8x8Unorm || format === GPUTextureFormat.ASTC8x8UnormSRGB ) return { byteLength: 16, width: 8, height: 8 };
  42128. if ( format === GPUTextureFormat.ASTC10x5Unorm || format === GPUTextureFormat.ASTC10x5UnormSRGB ) return { byteLength: 16, width: 10, height: 5 };
  42129. if ( format === GPUTextureFormat.ASTC10x6Unorm || format === GPUTextureFormat.ASTC10x6UnormSRGB ) return { byteLength: 16, width: 10, height: 6 };
  42130. if ( format === GPUTextureFormat.ASTC10x8Unorm || format === GPUTextureFormat.ASTC10x8UnormSRGB ) return { byteLength: 16, width: 10, height: 8 };
  42131. if ( format === GPUTextureFormat.ASTC10x10Unorm || format === GPUTextureFormat.ASTC10x10UnormSRGB ) return { byteLength: 16, width: 10, height: 10 };
  42132. if ( format === GPUTextureFormat.ASTC12x10Unorm || format === GPUTextureFormat.ASTC12x10UnormSRGB ) return { byteLength: 16, width: 12, height: 10 };
  42133. if ( format === GPUTextureFormat.ASTC12x12Unorm || format === GPUTextureFormat.ASTC12x12UnormSRGB ) return { byteLength: 16, width: 12, height: 12 };
  42134. }
  42135. _convertAddressMode( value ) {
  42136. let addressMode = GPUAddressMode.ClampToEdge;
  42137. if ( value === RepeatWrapping ) {
  42138. addressMode = GPUAddressMode.Repeat;
  42139. } else if ( value === MirroredRepeatWrapping ) {
  42140. addressMode = GPUAddressMode.MirrorRepeat;
  42141. }
  42142. return addressMode;
  42143. }
  42144. _convertFilterMode( value ) {
  42145. let filterMode = GPUFilterMode.Linear;
  42146. if ( value === NearestFilter || value === NearestMipmapNearestFilter || value === NearestMipmapLinearFilter ) {
  42147. filterMode = GPUFilterMode.Nearest;
  42148. }
  42149. return filterMode;
  42150. }
  42151. _getBytesPerTexel( format ) {
  42152. // 8-bit formats
  42153. if ( format === GPUTextureFormat.R8Unorm ||
  42154. format === GPUTextureFormat.R8Snorm ||
  42155. format === GPUTextureFormat.R8Uint ||
  42156. format === GPUTextureFormat.R8Sint ) return 1;
  42157. // 16-bit formats
  42158. if ( format === GPUTextureFormat.R16Uint ||
  42159. format === GPUTextureFormat.R16Sint ||
  42160. format === GPUTextureFormat.R16Float ||
  42161. format === GPUTextureFormat.RG8Unorm ||
  42162. format === GPUTextureFormat.RG8Snorm ||
  42163. format === GPUTextureFormat.RG8Uint ||
  42164. format === GPUTextureFormat.RG8Sint ) return 2;
  42165. // 32-bit formats
  42166. if ( format === GPUTextureFormat.R32Uint ||
  42167. format === GPUTextureFormat.R32Sint ||
  42168. format === GPUTextureFormat.R32Float ||
  42169. format === GPUTextureFormat.RG16Uint ||
  42170. format === GPUTextureFormat.RG16Sint ||
  42171. format === GPUTextureFormat.RG16Float ||
  42172. format === GPUTextureFormat.RGBA8Unorm ||
  42173. format === GPUTextureFormat.RGBA8UnormSRGB ||
  42174. format === GPUTextureFormat.RGBA8Snorm ||
  42175. format === GPUTextureFormat.RGBA8Uint ||
  42176. format === GPUTextureFormat.RGBA8Sint ||
  42177. format === GPUTextureFormat.BGRA8Unorm ||
  42178. format === GPUTextureFormat.BGRA8UnormSRGB ||
  42179. // Packed 32-bit formats
  42180. format === GPUTextureFormat.RGB9E5UFloat ||
  42181. format === GPUTextureFormat.RGB10A2Unorm ||
  42182. format === GPUTextureFormat.RG11B10UFloat ||
  42183. format === GPUTextureFormat.Depth32Float ||
  42184. format === GPUTextureFormat.Depth24Plus ||
  42185. format === GPUTextureFormat.Depth24PlusStencil8 ||
  42186. format === GPUTextureFormat.Depth32FloatStencil8 ) return 4;
  42187. // 64-bit formats
  42188. if ( format === GPUTextureFormat.RG32Uint ||
  42189. format === GPUTextureFormat.RG32Sint ||
  42190. format === GPUTextureFormat.RG32Float ||
  42191. format === GPUTextureFormat.RGBA16Uint ||
  42192. format === GPUTextureFormat.RGBA16Sint ||
  42193. format === GPUTextureFormat.RGBA16Float ) return 8;
  42194. // 128-bit formats
  42195. if ( format === GPUTextureFormat.RGBA32Uint ||
  42196. format === GPUTextureFormat.RGBA32Sint ||
  42197. format === GPUTextureFormat.RGBA32Float ) return 16;
  42198. }
  42199. _getTypedArrayType( format ) {
  42200. if ( format === GPUTextureFormat.R8Uint ) return Uint8Array;
  42201. if ( format === GPUTextureFormat.R8Sint ) return Int8Array;
  42202. if ( format === GPUTextureFormat.R8Unorm ) return Uint8Array;
  42203. if ( format === GPUTextureFormat.R8Snorm ) return Int8Array;
  42204. if ( format === GPUTextureFormat.RG8Uint ) return Uint8Array;
  42205. if ( format === GPUTextureFormat.RG8Sint ) return Int8Array;
  42206. if ( format === GPUTextureFormat.RG8Unorm ) return Uint8Array;
  42207. if ( format === GPUTextureFormat.RG8Snorm ) return Int8Array;
  42208. if ( format === GPUTextureFormat.RGBA8Uint ) return Uint8Array;
  42209. if ( format === GPUTextureFormat.RGBA8Sint ) return Int8Array;
  42210. if ( format === GPUTextureFormat.RGBA8Unorm ) return Uint8Array;
  42211. if ( format === GPUTextureFormat.RGBA8Snorm ) return Int8Array;
  42212. if ( format === GPUTextureFormat.R16Uint ) return Uint16Array;
  42213. if ( format === GPUTextureFormat.R16Sint ) return Int16Array;
  42214. if ( format === GPUTextureFormat.RG16Uint ) return Uint16Array;
  42215. if ( format === GPUTextureFormat.RG16Sint ) return Int16Array;
  42216. if ( format === GPUTextureFormat.RGBA16Uint ) return Uint16Array;
  42217. if ( format === GPUTextureFormat.RGBA16Sint ) return Int16Array;
  42218. if ( format === GPUTextureFormat.R16Float ) return Uint16Array;
  42219. if ( format === GPUTextureFormat.RG16Float ) return Uint16Array;
  42220. if ( format === GPUTextureFormat.RGBA16Float ) return Uint16Array;
  42221. if ( format === GPUTextureFormat.R32Uint ) return Uint32Array;
  42222. if ( format === GPUTextureFormat.R32Sint ) return Int32Array;
  42223. if ( format === GPUTextureFormat.R32Float ) return Float32Array;
  42224. if ( format === GPUTextureFormat.RG32Uint ) return Uint32Array;
  42225. if ( format === GPUTextureFormat.RG32Sint ) return Int32Array;
  42226. if ( format === GPUTextureFormat.RG32Float ) return Float32Array;
  42227. if ( format === GPUTextureFormat.RGBA32Uint ) return Uint32Array;
  42228. if ( format === GPUTextureFormat.RGBA32Sint ) return Int32Array;
  42229. if ( format === GPUTextureFormat.RGBA32Float ) return Float32Array;
  42230. if ( format === GPUTextureFormat.BGRA8Unorm ) return Uint8Array;
  42231. if ( format === GPUTextureFormat.BGRA8UnormSRGB ) return Uint8Array;
  42232. if ( format === GPUTextureFormat.RGB10A2Unorm ) return Uint32Array;
  42233. if ( format === GPUTextureFormat.RGB9E5UFloat ) return Uint32Array;
  42234. if ( format === GPUTextureFormat.RG11B10UFloat ) return Uint32Array;
  42235. if ( format === GPUTextureFormat.Depth32Float ) return Float32Array;
  42236. if ( format === GPUTextureFormat.Depth24Plus ) return Uint32Array;
  42237. if ( format === GPUTextureFormat.Depth24PlusStencil8 ) return Uint32Array;
  42238. if ( format === GPUTextureFormat.Depth32FloatStencil8 ) return Float32Array;
  42239. }
  42240. _getDimension( texture ) {
  42241. let dimension;
  42242. if ( texture.isData3DTexture ) {
  42243. dimension = GPUTextureDimension.ThreeD;
  42244. } else {
  42245. dimension = GPUTextureDimension.TwoD;
  42246. }
  42247. return dimension;
  42248. }
  42249. }
  42250. function getFormat( texture, device = null ) {
  42251. const format = texture.format;
  42252. const type = texture.type;
  42253. const colorSpace = texture.colorSpace;
  42254. let formatGPU;
  42255. if ( texture.isFramebufferTexture === true && texture.type === UnsignedByteType ) {
  42256. formatGPU = GPUTextureFormat.BGRA8Unorm;
  42257. } else if ( texture.isCompressedTexture === true || texture.isCompressedArrayTexture === true ) {
  42258. switch ( format ) {
  42259. case RGBA_S3TC_DXT1_Format:
  42260. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.BC1RGBAUnormSRGB : GPUTextureFormat.BC1RGBAUnorm;
  42261. break;
  42262. case RGBA_S3TC_DXT3_Format:
  42263. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.BC2RGBAUnormSRGB : GPUTextureFormat.BC2RGBAUnorm;
  42264. break;
  42265. case RGBA_S3TC_DXT5_Format:
  42266. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.BC3RGBAUnormSRGB : GPUTextureFormat.BC3RGBAUnorm;
  42267. break;
  42268. case RGB_ETC2_Format:
  42269. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ETC2RGB8UnormSRGB : GPUTextureFormat.ETC2RGB8Unorm;
  42270. break;
  42271. case RGBA_ETC2_EAC_Format:
  42272. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ETC2RGBA8UnormSRGB : GPUTextureFormat.ETC2RGBA8Unorm;
  42273. break;
  42274. case RGBA_ASTC_4x4_Format:
  42275. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC4x4UnormSRGB : GPUTextureFormat.ASTC4x4Unorm;
  42276. break;
  42277. case RGBA_ASTC_5x4_Format:
  42278. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC5x4UnormSRGB : GPUTextureFormat.ASTC5x4Unorm;
  42279. break;
  42280. case RGBA_ASTC_5x5_Format:
  42281. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC5x5UnormSRGB : GPUTextureFormat.ASTC5x5Unorm;
  42282. break;
  42283. case RGBA_ASTC_6x5_Format:
  42284. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC6x5UnormSRGB : GPUTextureFormat.ASTC6x5Unorm;
  42285. break;
  42286. case RGBA_ASTC_6x6_Format:
  42287. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC6x6UnormSRGB : GPUTextureFormat.ASTC6x6Unorm;
  42288. break;
  42289. case RGBA_ASTC_8x5_Format:
  42290. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC8x5UnormSRGB : GPUTextureFormat.ASTC8x5Unorm;
  42291. break;
  42292. case RGBA_ASTC_8x6_Format:
  42293. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC8x6UnormSRGB : GPUTextureFormat.ASTC8x6Unorm;
  42294. break;
  42295. case RGBA_ASTC_8x8_Format:
  42296. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC8x8UnormSRGB : GPUTextureFormat.ASTC8x8Unorm;
  42297. break;
  42298. case RGBA_ASTC_10x5_Format:
  42299. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC10x5UnormSRGB : GPUTextureFormat.ASTC10x5Unorm;
  42300. break;
  42301. case RGBA_ASTC_10x6_Format:
  42302. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC10x6UnormSRGB : GPUTextureFormat.ASTC10x6Unorm;
  42303. break;
  42304. case RGBA_ASTC_10x8_Format:
  42305. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC10x8UnormSRGB : GPUTextureFormat.ASTC10x8Unorm;
  42306. break;
  42307. case RGBA_ASTC_10x10_Format:
  42308. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC10x10UnormSRGB : GPUTextureFormat.ASTC10x10Unorm;
  42309. break;
  42310. case RGBA_ASTC_12x10_Format:
  42311. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC12x10UnormSRGB : GPUTextureFormat.ASTC12x10Unorm;
  42312. break;
  42313. case RGBA_ASTC_12x12_Format:
  42314. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC12x12UnormSRGB : GPUTextureFormat.ASTC12x12Unorm;
  42315. break;
  42316. default:
  42317. console.error( 'WebGPURenderer: Unsupported texture format.', format );
  42318. }
  42319. } else {
  42320. switch ( format ) {
  42321. case RGBAFormat:
  42322. switch ( type ) {
  42323. case ByteType:
  42324. formatGPU = GPUTextureFormat.RGBA8Snorm;
  42325. break;
  42326. case ShortType:
  42327. formatGPU = GPUTextureFormat.RGBA16Sint;
  42328. break;
  42329. case UnsignedShortType:
  42330. formatGPU = GPUTextureFormat.RGBA16Uint;
  42331. break;
  42332. case UnsignedIntType:
  42333. formatGPU = GPUTextureFormat.RGBA32Uint;
  42334. break;
  42335. case IntType:
  42336. formatGPU = GPUTextureFormat.RGBA32Sint;
  42337. break;
  42338. case UnsignedByteType:
  42339. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.RGBA8UnormSRGB : GPUTextureFormat.RGBA8Unorm;
  42340. break;
  42341. case HalfFloatType:
  42342. formatGPU = GPUTextureFormat.RGBA16Float;
  42343. break;
  42344. case FloatType:
  42345. formatGPU = GPUTextureFormat.RGBA32Float;
  42346. break;
  42347. default:
  42348. console.error( 'WebGPURenderer: Unsupported texture type with RGBAFormat.', type );
  42349. }
  42350. break;
  42351. case RGBFormat:
  42352. switch ( type ) {
  42353. case UnsignedInt5999Type:
  42354. formatGPU = GPUTextureFormat.RGB9E5UFloat;
  42355. break;
  42356. default:
  42357. console.error( 'WebGPURenderer: Unsupported texture type with RGBFormat.', type );
  42358. }
  42359. break;
  42360. case RedFormat:
  42361. switch ( type ) {
  42362. case ByteType:
  42363. formatGPU = GPUTextureFormat.R8Snorm;
  42364. break;
  42365. case ShortType:
  42366. formatGPU = GPUTextureFormat.R16Sint;
  42367. break;
  42368. case UnsignedShortType:
  42369. formatGPU = GPUTextureFormat.R16Uint;
  42370. break;
  42371. case UnsignedIntType:
  42372. formatGPU = GPUTextureFormat.R32Uint;
  42373. break;
  42374. case IntType:
  42375. formatGPU = GPUTextureFormat.R32Sint;
  42376. break;
  42377. case UnsignedByteType:
  42378. formatGPU = GPUTextureFormat.R8Unorm;
  42379. break;
  42380. case HalfFloatType:
  42381. formatGPU = GPUTextureFormat.R16Float;
  42382. break;
  42383. case FloatType:
  42384. formatGPU = GPUTextureFormat.R32Float;
  42385. break;
  42386. default:
  42387. console.error( 'WebGPURenderer: Unsupported texture type with RedFormat.', type );
  42388. }
  42389. break;
  42390. case RGFormat:
  42391. switch ( type ) {
  42392. case ByteType:
  42393. formatGPU = GPUTextureFormat.RG8Snorm;
  42394. break;
  42395. case ShortType:
  42396. formatGPU = GPUTextureFormat.RG16Sint;
  42397. break;
  42398. case UnsignedShortType:
  42399. formatGPU = GPUTextureFormat.RG16Uint;
  42400. break;
  42401. case UnsignedIntType:
  42402. formatGPU = GPUTextureFormat.RG32Uint;
  42403. break;
  42404. case IntType:
  42405. formatGPU = GPUTextureFormat.RG32Sint;
  42406. break;
  42407. case UnsignedByteType:
  42408. formatGPU = GPUTextureFormat.RG8Unorm;
  42409. break;
  42410. case HalfFloatType:
  42411. formatGPU = GPUTextureFormat.RG16Float;
  42412. break;
  42413. case FloatType:
  42414. formatGPU = GPUTextureFormat.RG32Float;
  42415. break;
  42416. default:
  42417. console.error( 'WebGPURenderer: Unsupported texture type with RGFormat.', type );
  42418. }
  42419. break;
  42420. case DepthFormat:
  42421. switch ( type ) {
  42422. case UnsignedShortType:
  42423. formatGPU = GPUTextureFormat.Depth16Unorm;
  42424. break;
  42425. case UnsignedIntType:
  42426. formatGPU = GPUTextureFormat.Depth24Plus;
  42427. break;
  42428. case FloatType:
  42429. formatGPU = GPUTextureFormat.Depth32Float;
  42430. break;
  42431. default:
  42432. console.error( 'WebGPURenderer: Unsupported texture type with DepthFormat.', type );
  42433. }
  42434. break;
  42435. case DepthStencilFormat:
  42436. switch ( type ) {
  42437. case UnsignedInt248Type:
  42438. formatGPU = GPUTextureFormat.Depth24PlusStencil8;
  42439. break;
  42440. case FloatType:
  42441. if ( device && device.features.has( GPUFeatureName.Depth32FloatStencil8 ) === false ) {
  42442. console.error( 'WebGPURenderer: Depth textures with DepthStencilFormat + FloatType can only be used with the "depth32float-stencil8" GPU feature.' );
  42443. }
  42444. formatGPU = GPUTextureFormat.Depth32FloatStencil8;
  42445. break;
  42446. default:
  42447. console.error( 'WebGPURenderer: Unsupported texture type with DepthStencilFormat.', type );
  42448. }
  42449. break;
  42450. case RedIntegerFormat:
  42451. switch ( type ) {
  42452. case IntType:
  42453. formatGPU = GPUTextureFormat.R32Sint;
  42454. break;
  42455. case UnsignedIntType:
  42456. formatGPU = GPUTextureFormat.R32Uint;
  42457. break;
  42458. default:
  42459. console.error( 'WebGPURenderer: Unsupported texture type with RedIntegerFormat.', type );
  42460. }
  42461. break;
  42462. case RGIntegerFormat:
  42463. switch ( type ) {
  42464. case IntType:
  42465. formatGPU = GPUTextureFormat.RG32Sint;
  42466. break;
  42467. case UnsignedIntType:
  42468. formatGPU = GPUTextureFormat.RG32Uint;
  42469. break;
  42470. default:
  42471. console.error( 'WebGPURenderer: Unsupported texture type with RGIntegerFormat.', type );
  42472. }
  42473. break;
  42474. case RGBAIntegerFormat:
  42475. switch ( type ) {
  42476. case IntType:
  42477. formatGPU = GPUTextureFormat.RGBA32Sint;
  42478. break;
  42479. case UnsignedIntType:
  42480. formatGPU = GPUTextureFormat.RGBA32Uint;
  42481. break;
  42482. default:
  42483. console.error( 'WebGPURenderer: Unsupported texture type with RGBAIntegerFormat.', type );
  42484. }
  42485. break;
  42486. default:
  42487. console.error( 'WebGPURenderer: Unsupported texture format.', format );
  42488. }
  42489. }
  42490. return formatGPU;
  42491. }
  42492. const declarationRegexp = /^[fn]*\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)\s*[\-\>]*\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/i;
  42493. const propertiesRegexp = /([a-z_0-9]+)\s*:\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/ig;
  42494. const wgslTypeLib$1 = {
  42495. 'f32': 'float',
  42496. 'i32': 'int',
  42497. 'u32': 'uint',
  42498. 'bool': 'bool',
  42499. 'vec2<f32>': 'vec2',
  42500. 'vec2<i32>': 'ivec2',
  42501. 'vec2<u32>': 'uvec2',
  42502. 'vec2<bool>': 'bvec2',
  42503. 'vec2f': 'vec2',
  42504. 'vec2i': 'ivec2',
  42505. 'vec2u': 'uvec2',
  42506. 'vec2b': 'bvec2',
  42507. 'vec3<f32>': 'vec3',
  42508. 'vec3<i32>': 'ivec3',
  42509. 'vec3<u32>': 'uvec3',
  42510. 'vec3<bool>': 'bvec3',
  42511. 'vec3f': 'vec3',
  42512. 'vec3i': 'ivec3',
  42513. 'vec3u': 'uvec3',
  42514. 'vec3b': 'bvec3',
  42515. 'vec4<f32>': 'vec4',
  42516. 'vec4<i32>': 'ivec4',
  42517. 'vec4<u32>': 'uvec4',
  42518. 'vec4<bool>': 'bvec4',
  42519. 'vec4f': 'vec4',
  42520. 'vec4i': 'ivec4',
  42521. 'vec4u': 'uvec4',
  42522. 'vec4b': 'bvec4',
  42523. 'mat2x2<f32>': 'mat2',
  42524. 'mat2x2f': 'mat2',
  42525. 'mat3x3<f32>': 'mat3',
  42526. 'mat3x3f': 'mat3',
  42527. 'mat4x4<f32>': 'mat4',
  42528. 'mat4x4f': 'mat4',
  42529. 'sampler': 'sampler',
  42530. 'texture_1d': 'texture',
  42531. 'texture_2d': 'texture',
  42532. 'texture_2d_array': 'texture',
  42533. 'texture_multisampled_2d': 'cubeTexture',
  42534. 'texture_depth_2d': 'depthTexture',
  42535. 'texture_3d': 'texture3D',
  42536. 'texture_cube': 'cubeTexture',
  42537. 'texture_cube_array': 'cubeTexture',
  42538. 'texture_storage_1d': 'storageTexture',
  42539. 'texture_storage_2d': 'storageTexture',
  42540. 'texture_storage_2d_array': 'storageTexture',
  42541. 'texture_storage_3d': 'storageTexture'
  42542. };
  42543. const parse = ( source ) => {
  42544. source = source.trim();
  42545. const declaration = source.match( declarationRegexp );
  42546. if ( declaration !== null && declaration.length === 4 ) {
  42547. const inputsCode = declaration[ 2 ];
  42548. const propsMatches = [];
  42549. let match = null;
  42550. while ( ( match = propertiesRegexp.exec( inputsCode ) ) !== null ) {
  42551. propsMatches.push( { name: match[ 1 ], type: match[ 2 ] } );
  42552. }
  42553. // Process matches to correctly pair names and types
  42554. const inputs = [];
  42555. for ( let i = 0; i < propsMatches.length; i ++ ) {
  42556. const { name, type } = propsMatches[ i ];
  42557. let resolvedType = type;
  42558. if ( resolvedType.startsWith( 'texture' ) ) {
  42559. resolvedType = type.split( '<' )[ 0 ];
  42560. } else if ( resolvedType.startsWith( 'ptr' ) ) {
  42561. resolvedType = 'pointer';
  42562. }
  42563. resolvedType = wgslTypeLib$1[ resolvedType ] || resolvedType;
  42564. inputs.push( new NodeFunctionInput( resolvedType, name ) );
  42565. }
  42566. const blockCode = source.substring( declaration[ 0 ].length );
  42567. const outputType = declaration[ 3 ] || 'void';
  42568. const name = declaration[ 1 ] !== undefined ? declaration[ 1 ] : '';
  42569. const type = wgslTypeLib$1[ outputType ] || outputType;
  42570. return {
  42571. type,
  42572. inputs,
  42573. name,
  42574. inputsCode,
  42575. blockCode,
  42576. outputType
  42577. };
  42578. } else {
  42579. throw new Error( 'FunctionNode: Function is not a WGSL code.' );
  42580. }
  42581. };
  42582. class WGSLNodeFunction extends NodeFunction {
  42583. constructor( source ) {
  42584. const { type, inputs, name, inputsCode, blockCode, outputType } = parse( source );
  42585. super( type, inputs, name );
  42586. this.inputsCode = inputsCode;
  42587. this.blockCode = blockCode;
  42588. this.outputType = outputType;
  42589. }
  42590. getCode( name = this.name ) {
  42591. const outputType = this.outputType !== 'void' ? '-> ' + this.outputType : '';
  42592. return `fn ${ name } ( ${ this.inputsCode.trim() } ) ${ outputType }` + this.blockCode;
  42593. }
  42594. }
  42595. class WGSLNodeParser extends NodeParser {
  42596. parseFunction( source ) {
  42597. return new WGSLNodeFunction( source );
  42598. }
  42599. }
  42600. // GPUShaderStage is not defined in browsers not supporting WebGPU
  42601. const GPUShaderStage = self.GPUShaderStage;
  42602. const gpuShaderStageLib = {
  42603. 'vertex': GPUShaderStage ? GPUShaderStage.VERTEX : 1,
  42604. 'fragment': GPUShaderStage ? GPUShaderStage.FRAGMENT : 2,
  42605. 'compute': GPUShaderStage ? GPUShaderStage.COMPUTE : 4
  42606. };
  42607. const supports = {
  42608. instance: true,
  42609. swizzleAssign: false,
  42610. storageBuffer: true
  42611. };
  42612. const wgslFnOpLib = {
  42613. '^^': 'tsl_xor'
  42614. };
  42615. const wgslTypeLib = {
  42616. float: 'f32',
  42617. int: 'i32',
  42618. uint: 'u32',
  42619. bool: 'bool',
  42620. color: 'vec3<f32>',
  42621. vec2: 'vec2<f32>',
  42622. ivec2: 'vec2<i32>',
  42623. uvec2: 'vec2<u32>',
  42624. bvec2: 'vec2<bool>',
  42625. vec3: 'vec3<f32>',
  42626. ivec3: 'vec3<i32>',
  42627. uvec3: 'vec3<u32>',
  42628. bvec3: 'vec3<bool>',
  42629. vec4: 'vec4<f32>',
  42630. ivec4: 'vec4<i32>',
  42631. uvec4: 'vec4<u32>',
  42632. bvec4: 'vec4<bool>',
  42633. mat2: 'mat2x2<f32>',
  42634. imat2: 'mat2x2<i32>',
  42635. umat2: 'mat2x2<u32>',
  42636. bmat2: 'mat2x2<bool>',
  42637. mat3: 'mat3x3<f32>',
  42638. imat3: 'mat3x3<i32>',
  42639. umat3: 'mat3x3<u32>',
  42640. bmat3: 'mat3x3<bool>',
  42641. mat4: 'mat4x4<f32>',
  42642. imat4: 'mat4x4<i32>',
  42643. umat4: 'mat4x4<u32>',
  42644. bmat4: 'mat4x4<bool>'
  42645. };
  42646. const wgslPolyfill = {
  42647. tsl_xor: new CodeNode( 'fn tsl_xor( a : bool, b : bool ) -> bool { return ( a || b ) && !( a && b ); }' ),
  42648. mod_float: new CodeNode( 'fn tsl_mod_float( x : f32, y : f32 ) -> f32 { return x - y * floor( x / y ); }' ),
  42649. mod_vec2: new CodeNode( 'fn tsl_mod_vec2( x : vec2f, y : vec2f ) -> vec2f { return x - y * floor( x / y ); }' ),
  42650. mod_vec3: new CodeNode( 'fn tsl_mod_vec3( x : vec3f, y : vec3f ) -> vec3f { return x - y * floor( x / y ); }' ),
  42651. mod_vec4: new CodeNode( 'fn tsl_mod_vec4( x : vec4f, y : vec4f ) -> vec4f { return x - y * floor( x / y ); }' ),
  42652. equals_bool: new CodeNode( 'fn tsl_equals_bool( a : bool, b : bool ) -> bool { return a == b; }' ),
  42653. equals_bvec2: new CodeNode( 'fn tsl_equals_bvec2( a : vec2f, b : vec2f ) -> vec2<bool> { return vec2<bool>( a.x == b.x, a.y == b.y ); }' ),
  42654. equals_bvec3: new CodeNode( 'fn tsl_equals_bvec3( a : vec3f, b : vec3f ) -> vec3<bool> { return vec3<bool>( a.x == b.x, a.y == b.y, a.z == b.z ); }' ),
  42655. equals_bvec4: new CodeNode( 'fn tsl_equals_bvec4( a : vec4f, b : vec4f ) -> vec4<bool> { return vec4<bool>( a.x == b.x, a.y == b.y, a.z == b.z, a.w == b.w ); }' ),
  42656. repeatWrapping: new CodeNode( `
  42657. fn tsl_repeatWrapping( uv : vec2<f32>, dimension : vec2<u32> ) -> vec2<u32> {
  42658. let uvScaled = vec2<u32>( uv * vec2<f32>( dimension ) );
  42659. return ( ( uvScaled % dimension ) + dimension ) % dimension;
  42660. }
  42661. ` ),
  42662. biquadraticTexture: new CodeNode( `
  42663. fn tsl_biquadraticTexture( map : texture_2d<f32>, coord : vec2f, level : i32 ) -> vec4f {
  42664. let iRes = vec2i( textureDimensions( map, level ) );
  42665. let res = vec2f( iRes );
  42666. let uvScaled = coord * res;
  42667. let uvWrapping = ( ( uvScaled % res ) + res ) % res;
  42668. // https://www.shadertoy.com/view/WtyXRy
  42669. let uv = uvWrapping - 0.5;
  42670. let iuv = floor( uv );
  42671. let f = fract( uv );
  42672. let rg1 = textureLoad( map, vec2i( iuv + vec2( 0.5, 0.5 ) ) % iRes, level );
  42673. let rg2 = textureLoad( map, vec2i( iuv + vec2( 1.5, 0.5 ) ) % iRes, level );
  42674. let rg3 = textureLoad( map, vec2i( iuv + vec2( 0.5, 1.5 ) ) % iRes, level );
  42675. let rg4 = textureLoad( map, vec2i( iuv + vec2( 1.5, 1.5 ) ) % iRes, level );
  42676. return mix( mix( rg1, rg2, f.x ), mix( rg3, rg4, f.x ), f.y );
  42677. }
  42678. ` )
  42679. };
  42680. const wgslMethods = {
  42681. dFdx: 'dpdx',
  42682. dFdy: '- dpdy',
  42683. mod_float: 'tsl_mod_float',
  42684. mod_vec2: 'tsl_mod_vec2',
  42685. mod_vec3: 'tsl_mod_vec3',
  42686. mod_vec4: 'tsl_mod_vec4',
  42687. equals_bool: 'tsl_equals_bool',
  42688. equals_bvec2: 'tsl_equals_bvec2',
  42689. equals_bvec3: 'tsl_equals_bvec3',
  42690. equals_bvec4: 'tsl_equals_bvec4',
  42691. inversesqrt: 'inverseSqrt',
  42692. bitcast: 'bitcast<f32>'
  42693. };
  42694. // WebGPU issue: does not support pow() with negative base on Windows
  42695. if ( /Windows/g.test( navigator.userAgent ) ) {
  42696. wgslPolyfill.pow_float = new CodeNode( 'fn tsl_pow_float( a : f32, b : f32 ) -> f32 { return select( -pow( -a, b ), pow( a, b ), a > 0.0 ); }' );
  42697. wgslPolyfill.pow_vec2 = new CodeNode( 'fn tsl_pow_vec2( a : vec2f, b : vec2f ) -> vec2f { return vec2f( tsl_pow_float( a.x, b.x ), tsl_pow_float( a.y, b.y ) ); }', [ wgslPolyfill.pow_float ] );
  42698. wgslPolyfill.pow_vec3 = new CodeNode( 'fn tsl_pow_vec3( a : vec3f, b : vec3f ) -> vec3f { return vec3f( tsl_pow_float( a.x, b.x ), tsl_pow_float( a.y, b.y ), tsl_pow_float( a.z, b.z ) ); }', [ wgslPolyfill.pow_float ] );
  42699. wgslPolyfill.pow_vec4 = new CodeNode( 'fn tsl_pow_vec4( a : vec4f, b : vec4f ) -> vec4f { return vec4f( tsl_pow_float( a.x, b.x ), tsl_pow_float( a.y, b.y ), tsl_pow_float( a.z, b.z ), tsl_pow_float( a.w, b.w ) ); }', [ wgslPolyfill.pow_float ] );
  42700. wgslMethods.pow_float = 'tsl_pow_float';
  42701. wgslMethods.pow_vec2 = 'tsl_pow_vec2';
  42702. wgslMethods.pow_vec3 = 'tsl_pow_vec3';
  42703. wgslMethods.pow_vec4 = 'tsl_pow_vec4';
  42704. }
  42705. //
  42706. let diagnostics = '';
  42707. if ( /Firefox|Deno/g.test( navigator.userAgent ) !== true ) {
  42708. diagnostics += 'diagnostic( off, derivative_uniformity );\n';
  42709. }
  42710. //
  42711. class WGSLNodeBuilder extends NodeBuilder {
  42712. constructor( object, renderer ) {
  42713. super( object, renderer, new WGSLNodeParser() );
  42714. this.uniformGroups = {};
  42715. this.builtins = {};
  42716. this.directives = {};
  42717. this.scopedArrays = new Map();
  42718. }
  42719. needsToWorkingColorSpace( texture ) {
  42720. return texture.isVideoTexture === true && texture.colorSpace !== NoColorSpace;
  42721. }
  42722. _generateTextureSample( texture, textureProperty, uvSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  42723. if ( shaderStage === 'fragment' ) {
  42724. if ( depthSnippet ) {
  42725. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet } )`;
  42726. } else {
  42727. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet } )`;
  42728. }
  42729. } else if ( this.isFilteredTexture( texture ) ) {
  42730. return this.generateFilteredTexture( texture, textureProperty, uvSnippet );
  42731. } else {
  42732. return this.generateTextureLod( texture, textureProperty, uvSnippet, '0' );
  42733. }
  42734. }
  42735. _generateVideoSample( textureProperty, uvSnippet, shaderStage = this.shaderStage ) {
  42736. if ( shaderStage === 'fragment' ) {
  42737. return `textureSampleBaseClampToEdge( ${ textureProperty }, ${ textureProperty }_sampler, vec2<f32>( ${ uvSnippet }.x, 1.0 - ${ uvSnippet }.y ) )`;
  42738. } else {
  42739. console.error( `WebGPURenderer: THREE.VideoTexture does not support ${ shaderStage } shader.` );
  42740. }
  42741. }
  42742. _generateTextureSampleLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  42743. if ( shaderStage === 'fragment' && this.isUnfilterable( texture ) === false ) {
  42744. return `textureSampleLevel( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ levelSnippet } )`;
  42745. } else if ( this.isFilteredTexture( texture ) ) {
  42746. return this.generateFilteredTexture( texture, textureProperty, uvSnippet, levelSnippet );
  42747. } else {
  42748. return this.generateTextureLod( texture, textureProperty, uvSnippet, levelSnippet );
  42749. }
  42750. }
  42751. generateFilteredTexture( texture, textureProperty, uvSnippet, levelSnippet = '0' ) {
  42752. this._include( 'biquadraticTexture' );
  42753. return `tsl_biquadraticTexture( ${ textureProperty }, ${ uvSnippet }, i32( ${ levelSnippet } ) )`;
  42754. }
  42755. generateTextureLod( texture, textureProperty, uvSnippet, levelSnippet = '0' ) {
  42756. this._include( 'repeatWrapping' );
  42757. const dimension = texture.isMultisampleRenderTargetTexture === true ? `textureDimensions( ${ textureProperty } )` : `textureDimensions( ${ textureProperty }, 0 )`;
  42758. return `textureLoad( ${ textureProperty }, tsl_repeatWrapping( ${ uvSnippet }, ${ dimension } ), i32( ${ levelSnippet } ) )`;
  42759. }
  42760. generateTextureLoad( texture, textureProperty, uvIndexSnippet, depthSnippet, levelSnippet = '0u' ) {
  42761. if ( depthSnippet ) {
  42762. return `textureLoad( ${ textureProperty }, ${ uvIndexSnippet }, ${ depthSnippet }, ${ levelSnippet } )`;
  42763. } else {
  42764. return `textureLoad( ${ textureProperty }, ${ uvIndexSnippet }, ${ levelSnippet } )`;
  42765. }
  42766. }
  42767. generateTextureStore( texture, textureProperty, uvIndexSnippet, valueSnippet ) {
  42768. return `textureStore( ${ textureProperty }, ${ uvIndexSnippet }, ${ valueSnippet } )`;
  42769. }
  42770. isUnfilterable( texture ) {
  42771. return this.getComponentTypeFromTexture( texture ) !== 'float' || ( ! this.isAvailable( 'float32Filterable' ) && texture.isDataTexture === true && texture.type === FloatType ) || texture.isMultisampleRenderTargetTexture === true;
  42772. }
  42773. generateTexture( texture, textureProperty, uvSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  42774. let snippet = null;
  42775. if ( texture.isVideoTexture === true ) {
  42776. snippet = this._generateVideoSample( textureProperty, uvSnippet, shaderStage );
  42777. } else if ( this.isUnfilterable( texture ) ) {
  42778. snippet = this.generateTextureLod( texture, textureProperty, uvSnippet, '0', depthSnippet, shaderStage );
  42779. } else {
  42780. snippet = this._generateTextureSample( texture, textureProperty, uvSnippet, depthSnippet, shaderStage );
  42781. }
  42782. return snippet;
  42783. }
  42784. generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  42785. if ( shaderStage === 'fragment' ) {
  42786. // TODO handle i32 or u32 --> uvSnippet, array_index: A, ddx, ddy
  42787. return `textureSampleGrad( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] } )`;
  42788. } else {
  42789. console.error( `WebGPURenderer: THREE.TextureNode.gradient() does not support ${ shaderStage } shader.` );
  42790. }
  42791. }
  42792. generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  42793. if ( shaderStage === 'fragment' ) {
  42794. return `textureSampleCompare( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ compareSnippet } )`;
  42795. } else {
  42796. console.error( `WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${ shaderStage } shader.` );
  42797. }
  42798. }
  42799. generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  42800. let snippet = null;
  42801. if ( texture.isVideoTexture === true ) {
  42802. snippet = this._generateVideoSample( textureProperty, uvSnippet, shaderStage );
  42803. } else {
  42804. snippet = this._generateTextureSampleLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, shaderStage );
  42805. }
  42806. return snippet;
  42807. }
  42808. generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  42809. if ( shaderStage === 'fragment' ) {
  42810. return `textureSampleBias( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ biasSnippet } )`;
  42811. } else {
  42812. console.error( `WebGPURenderer: THREE.TextureNode.biasNode does not support ${ shaderStage } shader.` );
  42813. }
  42814. }
  42815. getPropertyName( node, shaderStage = this.shaderStage ) {
  42816. if ( node.isNodeVarying === true && node.needsInterpolation === true ) {
  42817. if ( shaderStage === 'vertex' ) {
  42818. return `varyings.${ node.name }`;
  42819. }
  42820. } else if ( node.isNodeUniform === true ) {
  42821. const name = node.name;
  42822. const type = node.type;
  42823. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) {
  42824. return name;
  42825. } else if ( type === 'buffer' || type === 'storageBuffer' || type === 'indirectStorageBuffer' ) {
  42826. return `NodeBuffer_${ node.id }.${name}`;
  42827. } else {
  42828. return node.groupNode.name + '.' + name;
  42829. }
  42830. }
  42831. return super.getPropertyName( node );
  42832. }
  42833. getOutputStructName() {
  42834. return 'output';
  42835. }
  42836. _getUniformGroupCount( shaderStage ) {
  42837. return Object.keys( this.uniforms[ shaderStage ] ).length;
  42838. }
  42839. getFunctionOperator( op ) {
  42840. const fnOp = wgslFnOpLib[ op ];
  42841. if ( fnOp !== undefined ) {
  42842. this._include( fnOp );
  42843. return fnOp;
  42844. }
  42845. return null;
  42846. }
  42847. getStorageAccess( node ) {
  42848. if ( node.isStorageTextureNode ) {
  42849. switch ( node.access ) {
  42850. case GPUStorageTextureAccess.ReadOnly:
  42851. return 'read';
  42852. case GPUStorageTextureAccess.WriteOnly:
  42853. return 'write';
  42854. default:
  42855. return 'read_write';
  42856. }
  42857. } else {
  42858. switch ( node.access ) {
  42859. case GPUBufferBindingType.Storage:
  42860. return 'read_write';
  42861. case GPUBufferBindingType.ReadOnlyStorage:
  42862. return 'read';
  42863. default:
  42864. return 'write';
  42865. }
  42866. }
  42867. }
  42868. getUniformFromNode( node, type, shaderStage, name = null ) {
  42869. const uniformNode = super.getUniformFromNode( node, type, shaderStage, name );
  42870. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  42871. if ( nodeData.uniformGPU === undefined ) {
  42872. let uniformGPU;
  42873. const group = node.groupNode;
  42874. const groupName = group.name;
  42875. const bindings = this.getBindGroupArray( groupName, shaderStage );
  42876. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) {
  42877. let texture = null;
  42878. if ( type === 'texture' || type === 'storageTexture' ) {
  42879. texture = new NodeSampledTexture( uniformNode.name, uniformNode.node, group, node.access ? node.access : null );
  42880. } else if ( type === 'cubeTexture' ) {
  42881. texture = new NodeSampledCubeTexture( uniformNode.name, uniformNode.node, group, node.access ? node.access : null );
  42882. } else if ( type === 'texture3D' ) {
  42883. texture = new NodeSampledTexture3D( uniformNode.name, uniformNode.node, group, node.access ? node.access : null );
  42884. }
  42885. texture.store = node.isStorageTextureNode === true;
  42886. texture.setVisibility( gpuShaderStageLib[ shaderStage ] );
  42887. if ( shaderStage === 'fragment' && this.isUnfilterable( node.value ) === false && texture.store === false ) {
  42888. const sampler = new NodeSampler( `${uniformNode.name}_sampler`, uniformNode.node, group );
  42889. sampler.setVisibility( gpuShaderStageLib[ shaderStage ] );
  42890. bindings.push( sampler, texture );
  42891. uniformGPU = [ sampler, texture ];
  42892. } else {
  42893. bindings.push( texture );
  42894. uniformGPU = [ texture ];
  42895. }
  42896. } else if ( type === 'buffer' || type === 'storageBuffer' || type === 'indirectStorageBuffer' ) {
  42897. const bufferClass = type === 'buffer' ? NodeUniformBuffer : NodeStorageBuffer;
  42898. const buffer = new bufferClass( node, group );
  42899. buffer.setVisibility( gpuShaderStageLib[ shaderStage ] );
  42900. bindings.push( buffer );
  42901. uniformGPU = buffer;
  42902. } else {
  42903. const uniformsStage = this.uniformGroups[ shaderStage ] || ( this.uniformGroups[ shaderStage ] = {} );
  42904. let uniformsGroup = uniformsStage[ groupName ];
  42905. if ( uniformsGroup === undefined ) {
  42906. uniformsGroup = new NodeUniformsGroup( groupName, group );
  42907. uniformsGroup.setVisibility( gpuShaderStageLib[ shaderStage ] );
  42908. uniformsStage[ groupName ] = uniformsGroup;
  42909. bindings.push( uniformsGroup );
  42910. }
  42911. uniformGPU = this.getNodeUniform( uniformNode, type );
  42912. uniformsGroup.addUniform( uniformGPU );
  42913. }
  42914. nodeData.uniformGPU = uniformGPU;
  42915. }
  42916. return uniformNode;
  42917. }
  42918. getBuiltin( name, property, type, shaderStage = this.shaderStage ) {
  42919. const map = this.builtins[ shaderStage ] || ( this.builtins[ shaderStage ] = new Map() );
  42920. if ( map.has( name ) === false ) {
  42921. map.set( name, {
  42922. name,
  42923. property,
  42924. type
  42925. } );
  42926. }
  42927. return property;
  42928. }
  42929. hasBuiltin( name, shaderStage = this.shaderStage ) {
  42930. return ( this.builtins[ shaderStage ] !== undefined && this.builtins[ shaderStage ].has( name ) );
  42931. }
  42932. getVertexIndex() {
  42933. if ( this.shaderStage === 'vertex' ) {
  42934. return this.getBuiltin( 'vertex_index', 'vertexIndex', 'u32', 'attribute' );
  42935. }
  42936. return 'vertexIndex';
  42937. }
  42938. buildFunctionCode( shaderNode ) {
  42939. const layout = shaderNode.layout;
  42940. const flowData = this.flowShaderNode( shaderNode );
  42941. const parameters = [];
  42942. for ( const input of layout.inputs ) {
  42943. parameters.push( input.name + ' : ' + this.getType( input.type ) );
  42944. }
  42945. //
  42946. let code = `fn ${ layout.name }( ${ parameters.join( ', ' ) } ) -> ${ this.getType( layout.type ) } {
  42947. ${ flowData.vars }
  42948. ${ flowData.code }
  42949. `;
  42950. if ( flowData.result ) {
  42951. code += `\treturn ${ flowData.result };\n`;
  42952. }
  42953. code += '\n}\n';
  42954. //
  42955. return code;
  42956. }
  42957. getInstanceIndex() {
  42958. if ( this.shaderStage === 'vertex' ) {
  42959. return this.getBuiltin( 'instance_index', 'instanceIndex', 'u32', 'attribute' );
  42960. }
  42961. return 'instanceIndex';
  42962. }
  42963. getInvocationLocalIndex() {
  42964. return this.getBuiltin( 'local_invocation_index', 'invocationLocalIndex', 'u32', 'attribute' );
  42965. }
  42966. getSubgroupSize() {
  42967. this.enableSubGroups();
  42968. return this.getBuiltin( 'subgroup_size', 'subgroupSize', 'u32', 'attribute' );
  42969. }
  42970. getInvocationSubgroupIndex() {
  42971. this.enableSubGroups();
  42972. return this.getBuiltin( 'subgroup_invocation_id', 'invocationSubgroupIndex', 'u32', 'attribute' );
  42973. }
  42974. getSubgroupIndex() {
  42975. this.enableSubGroups();
  42976. return this.getBuiltin( 'subgroup_id', 'subgroupIndex', 'u32', 'attribute' );
  42977. }
  42978. getDrawIndex() {
  42979. return null;
  42980. }
  42981. getFrontFacing() {
  42982. return this.getBuiltin( 'front_facing', 'isFront', 'bool' );
  42983. }
  42984. getFragCoord() {
  42985. return this.getBuiltin( 'position', 'fragCoord', 'vec4<f32>' ) + '.xy';
  42986. }
  42987. getFragDepth() {
  42988. return 'output.' + this.getBuiltin( 'frag_depth', 'depth', 'f32', 'output' );
  42989. }
  42990. isFlipY() {
  42991. return false;
  42992. }
  42993. enableDirective( name, shaderStage = this.shaderStage ) {
  42994. const stage = this.directives[ shaderStage ] || ( this.directives[ shaderStage ] = new Set() );
  42995. stage.add( name );
  42996. }
  42997. getDirectives( shaderStage ) {
  42998. const snippets = [];
  42999. const directives = this.directives[ shaderStage ];
  43000. if ( directives !== undefined ) {
  43001. for ( const directive of directives ) {
  43002. snippets.push( `enable ${directive};` );
  43003. }
  43004. }
  43005. return snippets.join( '\n' );
  43006. }
  43007. enableSubGroups() {
  43008. this.enableDirective( 'subgroups' );
  43009. }
  43010. enableSubgroupsF16() {
  43011. this.enableDirective( 'subgroups-f16' );
  43012. }
  43013. enableClipDistances() {
  43014. this.enableDirective( 'clip_distances' );
  43015. }
  43016. enableShaderF16() {
  43017. this.enableDirective( 'f16' );
  43018. }
  43019. enableDualSourceBlending() {
  43020. this.enableDirective( 'dual_source_blending' );
  43021. }
  43022. getBuiltins( shaderStage ) {
  43023. const snippets = [];
  43024. const builtins = this.builtins[ shaderStage ];
  43025. if ( builtins !== undefined ) {
  43026. for ( const { name, property, type } of builtins.values() ) {
  43027. snippets.push( `@builtin( ${name} ) ${property} : ${type}` );
  43028. }
  43029. }
  43030. return snippets.join( ',\n\t' );
  43031. }
  43032. getScopedArray( name, scope, bufferType, bufferCount ) {
  43033. if ( this.scopedArrays.has( name ) === false ) {
  43034. this.scopedArrays.set( name, {
  43035. name,
  43036. scope,
  43037. bufferType,
  43038. bufferCount
  43039. } );
  43040. }
  43041. return name;
  43042. }
  43043. getScopedArrays( shaderStage ) {
  43044. if ( shaderStage !== 'compute' ) {
  43045. return;
  43046. }
  43047. const snippets = [];
  43048. for ( const { name, scope, bufferType, bufferCount } of this.scopedArrays.values() ) {
  43049. const type = this.getType( bufferType );
  43050. snippets.push( `var<${scope}> ${name}: array< ${type}, ${bufferCount} >;` );
  43051. }
  43052. return snippets.join( '\n' );
  43053. }
  43054. getAttributes( shaderStage ) {
  43055. const snippets = [];
  43056. if ( shaderStage === 'compute' ) {
  43057. this.getBuiltin( 'global_invocation_id', 'id', 'vec3<u32>', 'attribute' );
  43058. this.getBuiltin( 'workgroup_id', 'workgroupId', 'vec3<u32>', 'attribute' );
  43059. this.getBuiltin( 'local_invocation_id', 'localId', 'vec3<u32>', 'attribute' );
  43060. this.getBuiltin( 'num_workgroups', 'numWorkgroups', 'vec3<u32>', 'attribute' );
  43061. if ( this.renderer.hasFeature( 'subgroups' ) ) {
  43062. this.enableDirective( 'subgroups', shaderStage );
  43063. this.getBuiltin( 'subgroup_size', 'subgroupSize', 'u32', 'attribute' );
  43064. }
  43065. }
  43066. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  43067. const builtins = this.getBuiltins( 'attribute' );
  43068. if ( builtins ) snippets.push( builtins );
  43069. const attributes = this.getAttributesArray();
  43070. for ( let index = 0, length = attributes.length; index < length; index ++ ) {
  43071. const attribute = attributes[ index ];
  43072. const name = attribute.name;
  43073. const type = this.getType( attribute.type );
  43074. snippets.push( `@location( ${index} ) ${ name } : ${ type }` );
  43075. }
  43076. }
  43077. return snippets.join( ',\n\t' );
  43078. }
  43079. getStructMembers( struct ) {
  43080. const snippets = [];
  43081. const members = struct.getMemberTypes();
  43082. for ( let i = 0; i < members.length; i ++ ) {
  43083. const member = members[ i ];
  43084. snippets.push( `\t@location( ${i} ) m${i} : ${ member }<f32>` );
  43085. }
  43086. const builtins = this.getBuiltins( 'output' );
  43087. if ( builtins ) snippets.push( '\t' + builtins );
  43088. return snippets.join( ',\n' );
  43089. }
  43090. getStructs( shaderStage ) {
  43091. const snippets = [];
  43092. const structs = this.structs[ shaderStage ];
  43093. for ( let index = 0, length = structs.length; index < length; index ++ ) {
  43094. const struct = structs[ index ];
  43095. const name = struct.name;
  43096. let snippet = `\struct ${ name } {\n`;
  43097. snippet += this.getStructMembers( struct );
  43098. snippet += '\n}';
  43099. snippets.push( snippet );
  43100. snippets.push( `\nvar<private> output : ${ name };\n\n` );
  43101. }
  43102. return snippets.join( '\n\n' );
  43103. }
  43104. getVar( type, name ) {
  43105. return `var ${ name } : ${ this.getType( type ) }`;
  43106. }
  43107. getVars( shaderStage ) {
  43108. const snippets = [];
  43109. const vars = this.vars[ shaderStage ];
  43110. if ( vars !== undefined ) {
  43111. for ( const variable of vars ) {
  43112. snippets.push( `\t${ this.getVar( variable.type, variable.name ) };` );
  43113. }
  43114. }
  43115. return `\n${ snippets.join( '\n' ) }\n`;
  43116. }
  43117. getVaryings( shaderStage ) {
  43118. const snippets = [];
  43119. if ( shaderStage === 'vertex' ) {
  43120. this.getBuiltin( 'position', 'Vertex', 'vec4<f32>', 'vertex' );
  43121. }
  43122. if ( shaderStage === 'vertex' || shaderStage === 'fragment' ) {
  43123. const varyings = this.varyings;
  43124. const vars = this.vars[ shaderStage ];
  43125. for ( let index = 0; index < varyings.length; index ++ ) {
  43126. const varying = varyings[ index ];
  43127. if ( varying.needsInterpolation ) {
  43128. let attributesSnippet = `@location( ${index} )`;
  43129. if ( /^(int|uint|ivec|uvec)/.test( varying.type ) ) {
  43130. attributesSnippet += ' @interpolate( flat )';
  43131. }
  43132. snippets.push( `${ attributesSnippet } ${ varying.name } : ${ this.getType( varying.type ) }` );
  43133. } else if ( shaderStage === 'vertex' && vars.includes( varying ) === false ) {
  43134. vars.push( varying );
  43135. }
  43136. }
  43137. }
  43138. const builtins = this.getBuiltins( shaderStage );
  43139. if ( builtins ) snippets.push( builtins );
  43140. const code = snippets.join( ',\n\t' );
  43141. return shaderStage === 'vertex' ? this._getWGSLStruct( 'VaryingsStruct', '\t' + code ) : code;
  43142. }
  43143. getUniforms( shaderStage ) {
  43144. const uniforms = this.uniforms[ shaderStage ];
  43145. const bindingSnippets = [];
  43146. const bufferSnippets = [];
  43147. const structSnippets = [];
  43148. const uniformGroups = {};
  43149. for ( const uniform of uniforms ) {
  43150. const groupName = uniform.groupNode.name;
  43151. const uniformIndexes = this.bindingsIndexes[ groupName ];
  43152. if ( uniform.type === 'texture' || uniform.type === 'cubeTexture' || uniform.type === 'storageTexture' || uniform.type === 'texture3D' ) {
  43153. const texture = uniform.node.value;
  43154. if ( shaderStage === 'fragment' && this.isUnfilterable( texture ) === false && uniform.node.isStorageTextureNode !== true ) {
  43155. if ( texture.isDepthTexture === true && texture.compareFunction !== null ) {
  43156. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name }_sampler : sampler_comparison;` );
  43157. } else {
  43158. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name }_sampler : sampler;` );
  43159. }
  43160. }
  43161. let textureType;
  43162. let multisampled = '';
  43163. if ( texture.isMultisampleRenderTargetTexture === true ) {
  43164. multisampled = '_multisampled';
  43165. }
  43166. if ( texture.isCubeTexture === true ) {
  43167. textureType = 'texture_cube<f32>';
  43168. } else if ( texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  43169. textureType = 'texture_2d_array<f32>';
  43170. } else if ( texture.isDepthTexture === true ) {
  43171. textureType = `texture_depth${multisampled}_2d`;
  43172. } else if ( texture.isVideoTexture === true ) {
  43173. textureType = 'texture_external';
  43174. } else if ( texture.isData3DTexture === true ) {
  43175. textureType = 'texture_3d<f32>';
  43176. } else if ( uniform.node.isStorageTextureNode === true ) {
  43177. const format = getFormat( texture );
  43178. const access = this.getStorageAccess( uniform.node );
  43179. textureType = `texture_storage_2d<${ format }, ${ access }>`;
  43180. } else {
  43181. const componentPrefix = this.getComponentTypeFromTexture( texture ).charAt( 0 );
  43182. textureType = `texture${multisampled}_2d<${ componentPrefix }32>`;
  43183. }
  43184. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name } : ${ textureType };` );
  43185. } else if ( uniform.type === 'buffer' || uniform.type === 'storageBuffer' || uniform.type === 'indirectStorageBuffer' ) {
  43186. const bufferNode = uniform.node;
  43187. const bufferType = this.getType( bufferNode.bufferType );
  43188. const bufferCount = bufferNode.bufferCount;
  43189. const bufferCountSnippet = bufferCount > 0 && uniform.type === 'buffer' ? ', ' + bufferCount : '';
  43190. const bufferTypeSnippet = bufferNode.isAtomic ? `atomic<${bufferType}>` : `${bufferType}`;
  43191. const bufferSnippet = `\t${ uniform.name } : array< ${ bufferTypeSnippet }${ bufferCountSnippet } >\n`;
  43192. const bufferAccessMode = bufferNode.isStorageBufferNode ? `storage, ${ this.getStorageAccess( bufferNode ) }` : 'uniform';
  43193. bufferSnippets.push( this._getWGSLStructBinding( 'NodeBuffer_' + bufferNode.id, bufferSnippet, bufferAccessMode, uniformIndexes.binding ++, uniformIndexes.group ) );
  43194. } else {
  43195. const vectorType = this.getType( this.getVectorType( uniform.type ) );
  43196. const groupName = uniform.groupNode.name;
  43197. const group = uniformGroups[ groupName ] || ( uniformGroups[ groupName ] = {
  43198. index: uniformIndexes.binding ++,
  43199. id: uniformIndexes.group,
  43200. snippets: []
  43201. } );
  43202. group.snippets.push( `\t${ uniform.name } : ${ vectorType }` );
  43203. }
  43204. }
  43205. for ( const name in uniformGroups ) {
  43206. const group = uniformGroups[ name ];
  43207. structSnippets.push( this._getWGSLStructBinding( name, group.snippets.join( ',\n' ), 'uniform', group.index, group.id ) );
  43208. }
  43209. let code = bindingSnippets.join( '\n' );
  43210. code += bufferSnippets.join( '\n' );
  43211. code += structSnippets.join( '\n' );
  43212. return code;
  43213. }
  43214. buildCode() {
  43215. const shadersData = this.material !== null ? { fragment: {}, vertex: {} } : { compute: {} };
  43216. this.sortBindingGroups();
  43217. for ( const shaderStage in shadersData ) {
  43218. const stageData = shadersData[ shaderStage ];
  43219. stageData.uniforms = this.getUniforms( shaderStage );
  43220. stageData.attributes = this.getAttributes( shaderStage );
  43221. stageData.varyings = this.getVaryings( shaderStage );
  43222. stageData.structs = this.getStructs( shaderStage );
  43223. stageData.vars = this.getVars( shaderStage );
  43224. stageData.codes = this.getCodes( shaderStage );
  43225. stageData.directives = this.getDirectives( shaderStage );
  43226. stageData.scopedArrays = this.getScopedArrays( shaderStage );
  43227. //
  43228. let flow = '// code\n\n';
  43229. flow += this.flowCode[ shaderStage ];
  43230. const flowNodes = this.flowNodes[ shaderStage ];
  43231. const mainNode = flowNodes[ flowNodes.length - 1 ];
  43232. const outputNode = mainNode.outputNode;
  43233. const isOutputStruct = ( outputNode !== undefined && outputNode.isOutputStructNode === true );
  43234. for ( const node of flowNodes ) {
  43235. const flowSlotData = this.getFlowData( node/*, shaderStage*/ );
  43236. const slotName = node.name;
  43237. if ( slotName ) {
  43238. if ( flow.length > 0 ) flow += '\n';
  43239. flow += `\t// flow -> ${ slotName }\n\t`;
  43240. }
  43241. flow += `${ flowSlotData.code }\n\t`;
  43242. if ( node === mainNode && shaderStage !== 'compute' ) {
  43243. flow += '// result\n\n\t';
  43244. if ( shaderStage === 'vertex' ) {
  43245. flow += `varyings.Vertex = ${ flowSlotData.result };`;
  43246. } else if ( shaderStage === 'fragment' ) {
  43247. if ( isOutputStruct ) {
  43248. stageData.returnType = outputNode.nodeType;
  43249. flow += `return ${ flowSlotData.result };`;
  43250. } else {
  43251. let structSnippet = '\t@location(0) color: vec4<f32>';
  43252. const builtins = this.getBuiltins( 'output' );
  43253. if ( builtins ) structSnippet += ',\n\t' + builtins;
  43254. stageData.returnType = 'OutputStruct';
  43255. stageData.structs += this._getWGSLStruct( 'OutputStruct', structSnippet );
  43256. stageData.structs += '\nvar<private> output : OutputStruct;\n\n';
  43257. flow += `output.color = ${ flowSlotData.result };\n\n\treturn output;`;
  43258. }
  43259. }
  43260. }
  43261. }
  43262. stageData.flow = flow;
  43263. }
  43264. if ( this.material !== null ) {
  43265. this.vertexShader = this._getWGSLVertexCode( shadersData.vertex );
  43266. this.fragmentShader = this._getWGSLFragmentCode( shadersData.fragment );
  43267. } else {
  43268. this.computeShader = this._getWGSLComputeCode( shadersData.compute, ( this.object.workgroupSize || [ 64 ] ).join( ', ' ) );
  43269. }
  43270. }
  43271. getMethod( method, output = null ) {
  43272. let wgslMethod;
  43273. if ( output !== null ) {
  43274. wgslMethod = this._getWGSLMethod( method + '_' + output );
  43275. }
  43276. if ( wgslMethod === undefined ) {
  43277. wgslMethod = this._getWGSLMethod( method );
  43278. }
  43279. return wgslMethod || method;
  43280. }
  43281. getType( type ) {
  43282. return wgslTypeLib[ type ] || type;
  43283. }
  43284. isAvailable( name ) {
  43285. let result = supports[ name ];
  43286. if ( result === undefined ) {
  43287. if ( name === 'float32Filterable' ) {
  43288. result = this.renderer.hasFeature( 'float32-filterable' );
  43289. }
  43290. supports[ name ] = result;
  43291. }
  43292. return result;
  43293. }
  43294. _getWGSLMethod( method ) {
  43295. if ( wgslPolyfill[ method ] !== undefined ) {
  43296. this._include( method );
  43297. }
  43298. return wgslMethods[ method ];
  43299. }
  43300. _include( name ) {
  43301. const codeNode = wgslPolyfill[ name ];
  43302. codeNode.build( this );
  43303. if ( this.currentFunctionNode !== null ) {
  43304. this.currentFunctionNode.includes.push( codeNode );
  43305. }
  43306. return codeNode;
  43307. }
  43308. _getWGSLVertexCode( shaderData ) {
  43309. return `${ this.getSignature() }
  43310. // directives
  43311. ${shaderData.directives}
  43312. // uniforms
  43313. ${shaderData.uniforms}
  43314. // varyings
  43315. ${shaderData.varyings}
  43316. var<private> varyings : VaryingsStruct;
  43317. // codes
  43318. ${shaderData.codes}
  43319. @vertex
  43320. fn main( ${shaderData.attributes} ) -> VaryingsStruct {
  43321. // vars
  43322. ${shaderData.vars}
  43323. // flow
  43324. ${shaderData.flow}
  43325. return varyings;
  43326. }
  43327. `;
  43328. }
  43329. _getWGSLFragmentCode( shaderData ) {
  43330. return `${ this.getSignature() }
  43331. // global
  43332. ${ diagnostics }
  43333. // uniforms
  43334. ${shaderData.uniforms}
  43335. // structs
  43336. ${shaderData.structs}
  43337. // codes
  43338. ${shaderData.codes}
  43339. @fragment
  43340. fn main( ${shaderData.varyings} ) -> ${shaderData.returnType} {
  43341. // vars
  43342. ${shaderData.vars}
  43343. // flow
  43344. ${shaderData.flow}
  43345. }
  43346. `;
  43347. }
  43348. _getWGSLComputeCode( shaderData, workgroupSize ) {
  43349. return `${ this.getSignature() }
  43350. // directives
  43351. ${shaderData.directives}
  43352. // system
  43353. var<private> instanceIndex : u32;
  43354. // locals
  43355. ${shaderData.scopedArrays}
  43356. // uniforms
  43357. ${shaderData.uniforms}
  43358. // codes
  43359. ${shaderData.codes}
  43360. @compute @workgroup_size( ${workgroupSize} )
  43361. fn main( ${shaderData.attributes} ) {
  43362. // system
  43363. instanceIndex = id.x + id.y * numWorkgroups.x * u32(${workgroupSize}) + id.z * numWorkgroups.x * numWorkgroups.y * u32(${workgroupSize});
  43364. // vars
  43365. ${shaderData.vars}
  43366. // flow
  43367. ${shaderData.flow}
  43368. }
  43369. `;
  43370. }
  43371. _getWGSLStruct( name, vars ) {
  43372. return `
  43373. struct ${name} {
  43374. ${vars}
  43375. };`;
  43376. }
  43377. _getWGSLStructBinding( name, vars, access, binding = 0, group = 0 ) {
  43378. const structName = name + 'Struct';
  43379. const structSnippet = this._getWGSLStruct( structName, vars );
  43380. return `${structSnippet}
  43381. @binding( ${binding} ) @group( ${group} )
  43382. var<${access}> ${name} : ${structName};`;
  43383. }
  43384. }
  43385. class WebGPUUtils {
  43386. constructor( backend ) {
  43387. this.backend = backend;
  43388. }
  43389. getCurrentDepthStencilFormat( renderContext ) {
  43390. let format;
  43391. if ( renderContext.depthTexture !== null ) {
  43392. format = this.getTextureFormatGPU( renderContext.depthTexture );
  43393. } else if ( renderContext.depth && renderContext.stencil ) {
  43394. format = GPUTextureFormat.Depth24PlusStencil8;
  43395. } else if ( renderContext.depth ) {
  43396. format = GPUTextureFormat.Depth24Plus;
  43397. }
  43398. return format;
  43399. }
  43400. getTextureFormatGPU( texture ) {
  43401. return this.backend.get( texture ).format;
  43402. }
  43403. getCurrentColorFormat( renderContext ) {
  43404. let format;
  43405. if ( renderContext.textures !== null ) {
  43406. format = this.getTextureFormatGPU( renderContext.textures[ 0 ] );
  43407. } else {
  43408. format = this.getPreferredCanvasFormat(); // default context format
  43409. }
  43410. return format;
  43411. }
  43412. getCurrentColorSpace( renderContext ) {
  43413. if ( renderContext.textures !== null ) {
  43414. return renderContext.textures[ 0 ].colorSpace;
  43415. }
  43416. return this.backend.renderer.outputColorSpace;
  43417. }
  43418. getPrimitiveTopology( object, material ) {
  43419. if ( object.isPoints ) return GPUPrimitiveTopology.PointList;
  43420. else if ( object.isLineSegments || ( object.isMesh && material.wireframe === true ) ) return GPUPrimitiveTopology.LineList;
  43421. else if ( object.isLine ) return GPUPrimitiveTopology.LineStrip;
  43422. else if ( object.isMesh ) return GPUPrimitiveTopology.TriangleList;
  43423. }
  43424. getSampleCount( sampleCount ) {
  43425. let count = 1;
  43426. if ( sampleCount > 1 ) {
  43427. // WebGPU only supports power-of-two sample counts and 2 is not a valid value
  43428. count = Math.pow( 2, Math.floor( Math.log2( sampleCount ) ) );
  43429. if ( count === 2 ) {
  43430. count = 4;
  43431. }
  43432. }
  43433. return count;
  43434. }
  43435. getSampleCountRenderContext( renderContext ) {
  43436. if ( renderContext.textures !== null ) {
  43437. return this.getSampleCount( renderContext.sampleCount );
  43438. }
  43439. return this.getSampleCount( this.backend.renderer.samples );
  43440. }
  43441. getPreferredCanvasFormat() {
  43442. // TODO: Remove this check when Quest 34.5 is out
  43443. // https://github.com/mrdoob/three.js/pull/29221/files#r1731833949
  43444. if ( navigator.userAgent.includes( 'Quest' ) ) {
  43445. return GPUTextureFormat.BGRA8Unorm;
  43446. } else {
  43447. return navigator.gpu.getPreferredCanvasFormat();
  43448. }
  43449. }
  43450. }
  43451. const typedArraysToVertexFormatPrefix = new Map( [
  43452. [ Int8Array, [ 'sint8', 'snorm8' ]],
  43453. [ Uint8Array, [ 'uint8', 'unorm8' ]],
  43454. [ Int16Array, [ 'sint16', 'snorm16' ]],
  43455. [ Uint16Array, [ 'uint16', 'unorm16' ]],
  43456. [ Int32Array, [ 'sint32', 'snorm32' ]],
  43457. [ Uint32Array, [ 'uint32', 'unorm32' ]],
  43458. [ Float32Array, [ 'float32', ]],
  43459. ] );
  43460. const typedAttributeToVertexFormatPrefix = new Map( [
  43461. [ Float16BufferAttribute, [ 'float16', ]],
  43462. ] );
  43463. const typeArraysToVertexFormatPrefixForItemSize1 = new Map( [
  43464. [ Int32Array, 'sint32' ],
  43465. [ Int16Array, 'sint32' ], // patch for INT16
  43466. [ Uint32Array, 'uint32' ],
  43467. [ Uint16Array, 'uint32' ], // patch for UINT16
  43468. [ Float32Array, 'float32' ]
  43469. ] );
  43470. class WebGPUAttributeUtils {
  43471. constructor( backend ) {
  43472. this.backend = backend;
  43473. }
  43474. createAttribute( attribute, usage ) {
  43475. const bufferAttribute = this._getBufferAttribute( attribute );
  43476. const backend = this.backend;
  43477. const bufferData = backend.get( bufferAttribute );
  43478. let buffer = bufferData.buffer;
  43479. if ( buffer === undefined ) {
  43480. const device = backend.device;
  43481. let array = bufferAttribute.array;
  43482. // patch for INT16 and UINT16
  43483. if ( attribute.normalized === false && ( array.constructor === Int16Array || array.constructor === Uint16Array ) ) {
  43484. const tempArray = new Uint32Array( array.length );
  43485. for ( let i = 0; i < array.length; i ++ ) {
  43486. tempArray[ i ] = array[ i ];
  43487. }
  43488. array = tempArray;
  43489. }
  43490. bufferAttribute.array = array;
  43491. if ( ( bufferAttribute.isStorageBufferAttribute || bufferAttribute.isStorageInstancedBufferAttribute ) && bufferAttribute.itemSize === 3 ) {
  43492. array = new array.constructor( bufferAttribute.count * 4 );
  43493. for ( let i = 0; i < bufferAttribute.count; i ++ ) {
  43494. array.set( bufferAttribute.array.subarray( i * 3, i * 3 + 3 ), i * 4 );
  43495. }
  43496. // Update BufferAttribute
  43497. bufferAttribute.itemSize = 4;
  43498. bufferAttribute.array = array;
  43499. }
  43500. const size = array.byteLength + ( ( 4 - ( array.byteLength % 4 ) ) % 4 ); // ensure 4 byte alignment, see #20441
  43501. buffer = device.createBuffer( {
  43502. label: bufferAttribute.name,
  43503. size: size,
  43504. usage: usage,
  43505. mappedAtCreation: true
  43506. } );
  43507. new array.constructor( buffer.getMappedRange() ).set( array );
  43508. buffer.unmap();
  43509. bufferData.buffer = buffer;
  43510. }
  43511. }
  43512. updateAttribute( attribute ) {
  43513. const bufferAttribute = this._getBufferAttribute( attribute );
  43514. const backend = this.backend;
  43515. const device = backend.device;
  43516. const buffer = backend.get( bufferAttribute ).buffer;
  43517. const array = bufferAttribute.array;
  43518. const updateRanges = bufferAttribute.updateRanges;
  43519. if ( updateRanges.length === 0 ) {
  43520. // Not using update ranges
  43521. device.queue.writeBuffer(
  43522. buffer,
  43523. 0,
  43524. array,
  43525. 0
  43526. );
  43527. } else {
  43528. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  43529. const range = updateRanges[ i ];
  43530. device.queue.writeBuffer(
  43531. buffer,
  43532. 0,
  43533. array,
  43534. range.start * array.BYTES_PER_ELEMENT,
  43535. range.count * array.BYTES_PER_ELEMENT
  43536. );
  43537. }
  43538. bufferAttribute.clearUpdateRanges();
  43539. }
  43540. }
  43541. createShaderVertexBuffers( renderObject ) {
  43542. const attributes = renderObject.getAttributes();
  43543. const vertexBuffers = new Map();
  43544. for ( let slot = 0; slot < attributes.length; slot ++ ) {
  43545. const geometryAttribute = attributes[ slot ];
  43546. const bytesPerElement = geometryAttribute.array.BYTES_PER_ELEMENT;
  43547. const bufferAttribute = this._getBufferAttribute( geometryAttribute );
  43548. let vertexBufferLayout = vertexBuffers.get( bufferAttribute );
  43549. if ( vertexBufferLayout === undefined ) {
  43550. let arrayStride, stepMode;
  43551. if ( geometryAttribute.isInterleavedBufferAttribute === true ) {
  43552. arrayStride = geometryAttribute.data.stride * bytesPerElement;
  43553. stepMode = geometryAttribute.data.isInstancedInterleavedBuffer ? GPUInputStepMode.Instance : GPUInputStepMode.Vertex;
  43554. } else {
  43555. arrayStride = geometryAttribute.itemSize * bytesPerElement;
  43556. stepMode = geometryAttribute.isInstancedBufferAttribute ? GPUInputStepMode.Instance : GPUInputStepMode.Vertex;
  43557. }
  43558. // patch for INT16 and UINT16
  43559. if ( geometryAttribute.normalized === false && ( geometryAttribute.array.constructor === Int16Array || geometryAttribute.array.constructor === Uint16Array ) ) {
  43560. arrayStride = 4;
  43561. }
  43562. vertexBufferLayout = {
  43563. arrayStride,
  43564. attributes: [],
  43565. stepMode
  43566. };
  43567. vertexBuffers.set( bufferAttribute, vertexBufferLayout );
  43568. }
  43569. const format = this._getVertexFormat( geometryAttribute );
  43570. const offset = ( geometryAttribute.isInterleavedBufferAttribute === true ) ? geometryAttribute.offset * bytesPerElement : 0;
  43571. vertexBufferLayout.attributes.push( {
  43572. shaderLocation: slot,
  43573. offset,
  43574. format
  43575. } );
  43576. }
  43577. return Array.from( vertexBuffers.values() );
  43578. }
  43579. destroyAttribute( attribute ) {
  43580. const backend = this.backend;
  43581. const data = backend.get( this._getBufferAttribute( attribute ) );
  43582. data.buffer.destroy();
  43583. backend.delete( attribute );
  43584. }
  43585. async getArrayBufferAsync( attribute ) {
  43586. const backend = this.backend;
  43587. const device = backend.device;
  43588. const data = backend.get( this._getBufferAttribute( attribute ) );
  43589. const bufferGPU = data.buffer;
  43590. const size = bufferGPU.size;
  43591. const readBufferGPU = device.createBuffer( {
  43592. label: attribute.name,
  43593. size,
  43594. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  43595. } );
  43596. const cmdEncoder = device.createCommandEncoder( {} );
  43597. cmdEncoder.copyBufferToBuffer(
  43598. bufferGPU,
  43599. 0,
  43600. readBufferGPU,
  43601. 0,
  43602. size
  43603. );
  43604. readBufferGPU.unmap();
  43605. const gpuCommands = cmdEncoder.finish();
  43606. device.queue.submit( [ gpuCommands ] );
  43607. await readBufferGPU.mapAsync( GPUMapMode.READ );
  43608. const arrayBuffer = readBufferGPU.getMappedRange();
  43609. return arrayBuffer;
  43610. }
  43611. _getVertexFormat( geometryAttribute ) {
  43612. const { itemSize, normalized } = geometryAttribute;
  43613. const ArrayType = geometryAttribute.array.constructor;
  43614. const AttributeType = geometryAttribute.constructor;
  43615. let format;
  43616. if ( itemSize == 1 ) {
  43617. format = typeArraysToVertexFormatPrefixForItemSize1.get( ArrayType );
  43618. } else {
  43619. const prefixOptions = typedAttributeToVertexFormatPrefix.get( AttributeType ) || typedArraysToVertexFormatPrefix.get( ArrayType );
  43620. const prefix = prefixOptions[ normalized ? 1 : 0 ];
  43621. if ( prefix ) {
  43622. const bytesPerUnit = ArrayType.BYTES_PER_ELEMENT * itemSize;
  43623. const paddedBytesPerUnit = Math.floor( ( bytesPerUnit + 3 ) / 4 ) * 4;
  43624. const paddedItemSize = paddedBytesPerUnit / ArrayType.BYTES_PER_ELEMENT;
  43625. if ( paddedItemSize % 1 ) {
  43626. throw new Error( 'THREE.WebGPUAttributeUtils: Bad vertex format item size.' );
  43627. }
  43628. format = `${prefix}x${paddedItemSize}`;
  43629. }
  43630. }
  43631. if ( ! format ) {
  43632. console.error( 'THREE.WebGPUAttributeUtils: Vertex format not supported yet.' );
  43633. }
  43634. return format;
  43635. }
  43636. _getBufferAttribute( attribute ) {
  43637. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  43638. return attribute;
  43639. }
  43640. }
  43641. class WebGPUBindingUtils {
  43642. constructor( backend ) {
  43643. this.backend = backend;
  43644. this.bindGroupLayoutCache = new WeakMap();
  43645. }
  43646. createBindingsLayout( bindGroup ) {
  43647. const backend = this.backend;
  43648. const device = backend.device;
  43649. const entries = [];
  43650. let index = 0;
  43651. for ( const binding of bindGroup.bindings ) {
  43652. const bindingGPU = {
  43653. binding: index ++,
  43654. visibility: binding.visibility
  43655. };
  43656. if ( binding.isUniformBuffer || binding.isStorageBuffer ) {
  43657. const buffer = {}; // GPUBufferBindingLayout
  43658. if ( binding.isStorageBuffer ) {
  43659. buffer.type = binding.access;
  43660. }
  43661. bindingGPU.buffer = buffer;
  43662. } else if ( binding.isSampler ) {
  43663. const sampler = {}; // GPUSamplerBindingLayout
  43664. if ( binding.texture.isDepthTexture ) {
  43665. if ( binding.texture.compareFunction !== null ) {
  43666. sampler.type = 'comparison';
  43667. }
  43668. }
  43669. bindingGPU.sampler = sampler;
  43670. } else if ( binding.isSampledTexture && binding.texture.isVideoTexture ) {
  43671. bindingGPU.externalTexture = {}; // GPUExternalTextureBindingLayout
  43672. } else if ( binding.isSampledTexture && binding.store ) {
  43673. const format = this.backend.get( binding.texture ).texture.format;
  43674. const access = binding.access;
  43675. bindingGPU.storageTexture = { format, access }; // GPUStorageTextureBindingLayout
  43676. } else if ( binding.isSampledTexture ) {
  43677. const texture = {}; // GPUTextureBindingLayout
  43678. if ( binding.texture.isMultisampleRenderTargetTexture === true ) {
  43679. texture.multisampled = true;
  43680. }
  43681. if ( binding.texture.isDepthTexture ) {
  43682. texture.sampleType = GPUTextureSampleType.Depth;
  43683. } else if ( binding.texture.isDataTexture || binding.texture.isDataArrayTexture || binding.texture.isData3DTexture ) {
  43684. const type = binding.texture.type;
  43685. if ( type === IntType ) {
  43686. texture.sampleType = GPUTextureSampleType.SInt;
  43687. } else if ( type === UnsignedIntType ) {
  43688. texture.sampleType = GPUTextureSampleType.UInt;
  43689. } else if ( type === FloatType ) {
  43690. if ( this.backend.hasFeature( 'float32-filterable' ) ) {
  43691. texture.sampleType = GPUTextureSampleType.Float;
  43692. } else {
  43693. texture.sampleType = GPUTextureSampleType.UnfilterableFloat;
  43694. }
  43695. }
  43696. }
  43697. if ( binding.isSampledCubeTexture ) {
  43698. texture.viewDimension = GPUTextureViewDimension.Cube;
  43699. } else if ( binding.texture.isDataArrayTexture || binding.texture.isCompressedArrayTexture ) {
  43700. texture.viewDimension = GPUTextureViewDimension.TwoDArray;
  43701. } else if ( binding.isSampledTexture3D ) {
  43702. texture.viewDimension = GPUTextureViewDimension.ThreeD;
  43703. }
  43704. bindingGPU.texture = texture;
  43705. } else {
  43706. console.error( `WebGPUBindingUtils: Unsupported binding "${ binding }".` );
  43707. }
  43708. entries.push( bindingGPU );
  43709. }
  43710. return device.createBindGroupLayout( { entries } );
  43711. }
  43712. createBindings( bindGroup ) {
  43713. const { backend, bindGroupLayoutCache } = this;
  43714. const bindingsData = backend.get( bindGroup );
  43715. // setup (static) binding layout and (dynamic) binding group
  43716. let bindLayoutGPU = bindGroupLayoutCache.get( bindGroup.bindingsReference );
  43717. if ( bindLayoutGPU === undefined ) {
  43718. bindLayoutGPU = this.createBindingsLayout( bindGroup );
  43719. bindGroupLayoutCache.set( bindGroup.bindingsReference, bindLayoutGPU );
  43720. }
  43721. const bindGroupGPU = this.createBindGroup( bindGroup, bindLayoutGPU );
  43722. bindingsData.layout = bindLayoutGPU;
  43723. bindingsData.group = bindGroupGPU;
  43724. }
  43725. updateBinding( binding ) {
  43726. const backend = this.backend;
  43727. const device = backend.device;
  43728. const buffer = binding.buffer;
  43729. const bufferGPU = backend.get( binding ).buffer;
  43730. device.queue.writeBuffer( bufferGPU, 0, buffer, 0 );
  43731. }
  43732. createBindGroup( bindGroup, layoutGPU ) {
  43733. const backend = this.backend;
  43734. const device = backend.device;
  43735. let bindingPoint = 0;
  43736. const entriesGPU = [];
  43737. for ( const binding of bindGroup.bindings ) {
  43738. if ( binding.isUniformBuffer ) {
  43739. const bindingData = backend.get( binding );
  43740. if ( bindingData.buffer === undefined ) {
  43741. const byteLength = binding.byteLength;
  43742. const usage = GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST;
  43743. const bufferGPU = device.createBuffer( {
  43744. label: 'bindingBuffer_' + binding.name,
  43745. size: byteLength,
  43746. usage: usage
  43747. } );
  43748. bindingData.buffer = bufferGPU;
  43749. }
  43750. entriesGPU.push( { binding: bindingPoint, resource: { buffer: bindingData.buffer } } );
  43751. } else if ( binding.isStorageBuffer ) {
  43752. const bindingData = backend.get( binding );
  43753. if ( bindingData.buffer === undefined ) {
  43754. const attribute = binding.attribute;
  43755. //const usage = GPUBufferUsage.STORAGE | GPUBufferUsage.VERTEX | /*GPUBufferUsage.COPY_SRC |*/ GPUBufferUsage.COPY_DST;
  43756. //backend.attributeUtils.createAttribute( attribute, usage ); // @TODO: Move it to universal renderer
  43757. bindingData.buffer = backend.get( attribute ).buffer;
  43758. }
  43759. entriesGPU.push( { binding: bindingPoint, resource: { buffer: bindingData.buffer } } );
  43760. } else if ( binding.isSampler ) {
  43761. const textureGPU = backend.get( binding.texture );
  43762. entriesGPU.push( { binding: bindingPoint, resource: textureGPU.sampler } );
  43763. } else if ( binding.isSampledTexture ) {
  43764. const textureData = backend.get( binding.texture );
  43765. let resourceGPU;
  43766. if ( textureData.externalTexture !== undefined ) {
  43767. resourceGPU = device.importExternalTexture( { source: textureData.externalTexture } );
  43768. } else {
  43769. const mipLevelCount = binding.store ? 1 : textureData.texture.mipLevelCount;
  43770. const propertyName = `view-${ textureData.texture.width }-${ textureData.texture.height }-${ mipLevelCount }`;
  43771. resourceGPU = textureData[ propertyName ];
  43772. if ( resourceGPU === undefined ) {
  43773. const aspectGPU = GPUTextureAspect.All;
  43774. let dimensionViewGPU;
  43775. if ( binding.isSampledCubeTexture ) {
  43776. dimensionViewGPU = GPUTextureViewDimension.Cube;
  43777. } else if ( binding.isSampledTexture3D ) {
  43778. dimensionViewGPU = GPUTextureViewDimension.ThreeD;
  43779. } else if ( binding.texture.isDataArrayTexture || binding.texture.isCompressedArrayTexture ) {
  43780. dimensionViewGPU = GPUTextureViewDimension.TwoDArray;
  43781. } else {
  43782. dimensionViewGPU = GPUTextureViewDimension.TwoD;
  43783. }
  43784. resourceGPU = textureData[ propertyName ] = textureData.texture.createView( { aspect: aspectGPU, dimension: dimensionViewGPU, mipLevelCount } );
  43785. }
  43786. }
  43787. entriesGPU.push( { binding: bindingPoint, resource: resourceGPU } );
  43788. }
  43789. bindingPoint ++;
  43790. }
  43791. return device.createBindGroup( {
  43792. label: 'bindGroup_' + bindGroup.name,
  43793. layout: layoutGPU,
  43794. entries: entriesGPU
  43795. } );
  43796. }
  43797. }
  43798. class WebGPUPipelineUtils {
  43799. constructor( backend ) {
  43800. this.backend = backend;
  43801. }
  43802. _getSampleCount( renderObjectContext ) {
  43803. return this.backend.utils.getSampleCountRenderContext( renderObjectContext );
  43804. }
  43805. createRenderPipeline( renderObject, promises ) {
  43806. const { object, material, geometry, pipeline } = renderObject;
  43807. const { vertexProgram, fragmentProgram } = pipeline;
  43808. const backend = this.backend;
  43809. const device = backend.device;
  43810. const utils = backend.utils;
  43811. const pipelineData = backend.get( pipeline );
  43812. // bind group layouts
  43813. const bindGroupLayouts = [];
  43814. for ( const bindGroup of renderObject.getBindings() ) {
  43815. const bindingsData = backend.get( bindGroup );
  43816. bindGroupLayouts.push( bindingsData.layout );
  43817. }
  43818. // vertex buffers
  43819. const vertexBuffers = backend.attributeUtils.createShaderVertexBuffers( renderObject );
  43820. // blending
  43821. let blending;
  43822. if ( material.transparent === true && material.blending !== NoBlending ) {
  43823. blending = this._getBlending( material );
  43824. }
  43825. // stencil
  43826. let stencilFront = {};
  43827. if ( material.stencilWrite === true ) {
  43828. stencilFront = {
  43829. compare: this._getStencilCompare( material ),
  43830. failOp: this._getStencilOperation( material.stencilFail ),
  43831. depthFailOp: this._getStencilOperation( material.stencilZFail ),
  43832. passOp: this._getStencilOperation( material.stencilZPass )
  43833. };
  43834. }
  43835. const colorWriteMask = this._getColorWriteMask( material );
  43836. const targets = [];
  43837. if ( renderObject.context.textures !== null ) {
  43838. const textures = renderObject.context.textures;
  43839. for ( let i = 0; i < textures.length; i ++ ) {
  43840. const colorFormat = utils.getTextureFormatGPU( textures[ i ] );
  43841. targets.push( {
  43842. format: colorFormat,
  43843. blend: blending,
  43844. writeMask: colorWriteMask
  43845. } );
  43846. }
  43847. } else {
  43848. const colorFormat = utils.getCurrentColorFormat( renderObject.context );
  43849. targets.push( {
  43850. format: colorFormat,
  43851. blend: blending,
  43852. writeMask: colorWriteMask
  43853. } );
  43854. }
  43855. const vertexModule = backend.get( vertexProgram ).module;
  43856. const fragmentModule = backend.get( fragmentProgram ).module;
  43857. const primitiveState = this._getPrimitiveState( object, geometry, material );
  43858. const depthCompare = this._getDepthCompare( material );
  43859. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderObject.context );
  43860. const sampleCount = this._getSampleCount( renderObject.context );
  43861. const pipelineDescriptor = {
  43862. label: `renderPipeline_${ material.name || material.type }_${ material.id }`,
  43863. vertex: Object.assign( {}, vertexModule, { buffers: vertexBuffers } ),
  43864. fragment: Object.assign( {}, fragmentModule, { targets } ),
  43865. primitive: primitiveState,
  43866. multisample: {
  43867. count: sampleCount,
  43868. alphaToCoverageEnabled: material.alphaToCoverage && sampleCount > 1
  43869. },
  43870. layout: device.createPipelineLayout( {
  43871. bindGroupLayouts
  43872. } )
  43873. };
  43874. const depthStencil = {};
  43875. const renderDepth = renderObject.context.depth;
  43876. const renderStencil = renderObject.context.stencil;
  43877. if ( renderDepth === true || renderStencil === true ) {
  43878. if ( renderDepth === true ) {
  43879. depthStencil.format = depthStencilFormat;
  43880. depthStencil.depthWriteEnabled = material.depthWrite;
  43881. depthStencil.depthCompare = depthCompare;
  43882. }
  43883. if ( renderStencil === true ) {
  43884. depthStencil.stencilFront = stencilFront;
  43885. depthStencil.stencilBack = {}; // three.js does not provide an API to configure the back function (gl.stencilFuncSeparate() was never used)
  43886. depthStencil.stencilReadMask = material.stencilFuncMask;
  43887. depthStencil.stencilWriteMask = material.stencilWriteMask;
  43888. }
  43889. pipelineDescriptor.depthStencil = depthStencil;
  43890. }
  43891. if ( promises === null ) {
  43892. pipelineData.pipeline = device.createRenderPipeline( pipelineDescriptor );
  43893. } else {
  43894. const p = new Promise( ( resolve /*, reject*/ ) => {
  43895. device.createRenderPipelineAsync( pipelineDescriptor ).then( pipeline => {
  43896. pipelineData.pipeline = pipeline;
  43897. resolve();
  43898. } );
  43899. } );
  43900. promises.push( p );
  43901. }
  43902. }
  43903. createBundleEncoder( renderContext ) {
  43904. const backend = this.backend;
  43905. const { utils, device } = backend;
  43906. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderContext );
  43907. const colorFormat = utils.getCurrentColorFormat( renderContext );
  43908. const sampleCount = this._getSampleCount( renderContext );
  43909. const descriptor = {
  43910. label: 'renderBundleEncoder',
  43911. colorFormats: [ colorFormat ],
  43912. depthStencilFormat,
  43913. sampleCount
  43914. };
  43915. return device.createRenderBundleEncoder( descriptor );
  43916. }
  43917. createComputePipeline( pipeline, bindings ) {
  43918. const backend = this.backend;
  43919. const device = backend.device;
  43920. const computeProgram = backend.get( pipeline.computeProgram ).module;
  43921. const pipelineGPU = backend.get( pipeline );
  43922. // bind group layouts
  43923. const bindGroupLayouts = [];
  43924. for ( const bindingsGroup of bindings ) {
  43925. const bindingsData = backend.get( bindingsGroup );
  43926. bindGroupLayouts.push( bindingsData.layout );
  43927. }
  43928. pipelineGPU.pipeline = device.createComputePipeline( {
  43929. compute: computeProgram,
  43930. layout: device.createPipelineLayout( {
  43931. bindGroupLayouts
  43932. } )
  43933. } );
  43934. }
  43935. _getBlending( material ) {
  43936. let color, alpha;
  43937. const blending = material.blending;
  43938. const blendSrc = material.blendSrc;
  43939. const blendDst = material.blendDst;
  43940. const blendEquation = material.blendEquation;
  43941. if ( blending === CustomBlending ) {
  43942. const blendSrcAlpha = material.blendSrcAlpha !== null ? material.blendSrcAlpha : blendSrc;
  43943. const blendDstAlpha = material.blendDstAlpha !== null ? material.blendDstAlpha : blendDst;
  43944. const blendEquationAlpha = material.blendEquationAlpha !== null ? material.blendEquationAlpha : blendEquation;
  43945. color = {
  43946. srcFactor: this._getBlendFactor( blendSrc ),
  43947. dstFactor: this._getBlendFactor( blendDst ),
  43948. operation: this._getBlendOperation( blendEquation )
  43949. };
  43950. alpha = {
  43951. srcFactor: this._getBlendFactor( blendSrcAlpha ),
  43952. dstFactor: this._getBlendFactor( blendDstAlpha ),
  43953. operation: this._getBlendOperation( blendEquationAlpha )
  43954. };
  43955. } else {
  43956. const premultipliedAlpha = material.premultipliedAlpha;
  43957. const setBlend = ( srcRGB, dstRGB, srcAlpha, dstAlpha ) => {
  43958. color = {
  43959. srcFactor: srcRGB,
  43960. dstFactor: dstRGB,
  43961. operation: GPUBlendOperation.Add
  43962. };
  43963. alpha = {
  43964. srcFactor: srcAlpha,
  43965. dstFactor: dstAlpha,
  43966. operation: GPUBlendOperation.Add
  43967. };
  43968. };
  43969. if ( premultipliedAlpha ) {
  43970. switch ( blending ) {
  43971. case NormalBlending:
  43972. setBlend( GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha, GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha );
  43973. break;
  43974. case AdditiveBlending:
  43975. setBlend( GPUBlendFactor.One, GPUBlendFactor.One, GPUBlendFactor.One, GPUBlendFactor.One );
  43976. break;
  43977. case SubtractiveBlending:
  43978. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.OneMinusSrc, GPUBlendFactor.Zero, GPUBlendFactor.One );
  43979. break;
  43980. case MultiplyBlending:
  43981. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.Src, GPUBlendFactor.Zero, GPUBlendFactor.SrcAlpha );
  43982. break;
  43983. }
  43984. } else {
  43985. switch ( blending ) {
  43986. case NormalBlending:
  43987. setBlend( GPUBlendFactor.SrcAlpha, GPUBlendFactor.OneMinusSrcAlpha, GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha );
  43988. break;
  43989. case AdditiveBlending:
  43990. setBlend( GPUBlendFactor.SrcAlpha, GPUBlendFactor.One, GPUBlendFactor.SrcAlpha, GPUBlendFactor.One );
  43991. break;
  43992. case SubtractiveBlending:
  43993. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.OneMinusSrc, GPUBlendFactor.Zero, GPUBlendFactor.One );
  43994. break;
  43995. case MultiplyBlending:
  43996. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.Src, GPUBlendFactor.Zero, GPUBlendFactor.Src );
  43997. break;
  43998. }
  43999. }
  44000. }
  44001. if ( color !== undefined && alpha !== undefined ) {
  44002. return { color, alpha };
  44003. } else {
  44004. console.error( 'THREE.WebGPURenderer: Invalid blending: ', blending );
  44005. }
  44006. }
  44007. _getBlendFactor( blend ) {
  44008. let blendFactor;
  44009. switch ( blend ) {
  44010. case ZeroFactor:
  44011. blendFactor = GPUBlendFactor.Zero;
  44012. break;
  44013. case OneFactor:
  44014. blendFactor = GPUBlendFactor.One;
  44015. break;
  44016. case SrcColorFactor:
  44017. blendFactor = GPUBlendFactor.Src;
  44018. break;
  44019. case OneMinusSrcColorFactor:
  44020. blendFactor = GPUBlendFactor.OneMinusSrc;
  44021. break;
  44022. case SrcAlphaFactor:
  44023. blendFactor = GPUBlendFactor.SrcAlpha;
  44024. break;
  44025. case OneMinusSrcAlphaFactor:
  44026. blendFactor = GPUBlendFactor.OneMinusSrcAlpha;
  44027. break;
  44028. case DstColorFactor:
  44029. blendFactor = GPUBlendFactor.Dst;
  44030. break;
  44031. case OneMinusDstColorFactor:
  44032. blendFactor = GPUBlendFactor.OneMinusDstColor;
  44033. break;
  44034. case DstAlphaFactor:
  44035. blendFactor = GPUBlendFactor.DstAlpha;
  44036. break;
  44037. case OneMinusDstAlphaFactor:
  44038. blendFactor = GPUBlendFactor.OneMinusDstAlpha;
  44039. break;
  44040. case SrcAlphaSaturateFactor:
  44041. blendFactor = GPUBlendFactor.SrcAlphaSaturated;
  44042. break;
  44043. case BlendColorFactor:
  44044. blendFactor = GPUBlendFactor.Constant;
  44045. break;
  44046. case OneMinusBlendColorFactor:
  44047. blendFactor = GPUBlendFactor.OneMinusConstant;
  44048. break;
  44049. default:
  44050. console.error( 'THREE.WebGPURenderer: Blend factor not supported.', blend );
  44051. }
  44052. return blendFactor;
  44053. }
  44054. _getStencilCompare( material ) {
  44055. let stencilCompare;
  44056. const stencilFunc = material.stencilFunc;
  44057. switch ( stencilFunc ) {
  44058. case NeverStencilFunc:
  44059. stencilCompare = GPUCompareFunction.Never;
  44060. break;
  44061. case AlwaysStencilFunc:
  44062. stencilCompare = GPUCompareFunction.Always;
  44063. break;
  44064. case LessStencilFunc:
  44065. stencilCompare = GPUCompareFunction.Less;
  44066. break;
  44067. case LessEqualStencilFunc:
  44068. stencilCompare = GPUCompareFunction.LessEqual;
  44069. break;
  44070. case EqualStencilFunc:
  44071. stencilCompare = GPUCompareFunction.Equal;
  44072. break;
  44073. case GreaterEqualStencilFunc:
  44074. stencilCompare = GPUCompareFunction.GreaterEqual;
  44075. break;
  44076. case GreaterStencilFunc:
  44077. stencilCompare = GPUCompareFunction.Greater;
  44078. break;
  44079. case NotEqualStencilFunc:
  44080. stencilCompare = GPUCompareFunction.NotEqual;
  44081. break;
  44082. default:
  44083. console.error( 'THREE.WebGPURenderer: Invalid stencil function.', stencilFunc );
  44084. }
  44085. return stencilCompare;
  44086. }
  44087. _getStencilOperation( op ) {
  44088. let stencilOperation;
  44089. switch ( op ) {
  44090. case KeepStencilOp:
  44091. stencilOperation = GPUStencilOperation.Keep;
  44092. break;
  44093. case ZeroStencilOp:
  44094. stencilOperation = GPUStencilOperation.Zero;
  44095. break;
  44096. case ReplaceStencilOp:
  44097. stencilOperation = GPUStencilOperation.Replace;
  44098. break;
  44099. case InvertStencilOp:
  44100. stencilOperation = GPUStencilOperation.Invert;
  44101. break;
  44102. case IncrementStencilOp:
  44103. stencilOperation = GPUStencilOperation.IncrementClamp;
  44104. break;
  44105. case DecrementStencilOp:
  44106. stencilOperation = GPUStencilOperation.DecrementClamp;
  44107. break;
  44108. case IncrementWrapStencilOp:
  44109. stencilOperation = GPUStencilOperation.IncrementWrap;
  44110. break;
  44111. case DecrementWrapStencilOp:
  44112. stencilOperation = GPUStencilOperation.DecrementWrap;
  44113. break;
  44114. default:
  44115. console.error( 'THREE.WebGPURenderer: Invalid stencil operation.', stencilOperation );
  44116. }
  44117. return stencilOperation;
  44118. }
  44119. _getBlendOperation( blendEquation ) {
  44120. let blendOperation;
  44121. switch ( blendEquation ) {
  44122. case AddEquation:
  44123. blendOperation = GPUBlendOperation.Add;
  44124. break;
  44125. case SubtractEquation:
  44126. blendOperation = GPUBlendOperation.Subtract;
  44127. break;
  44128. case ReverseSubtractEquation:
  44129. blendOperation = GPUBlendOperation.ReverseSubtract;
  44130. break;
  44131. case MinEquation:
  44132. blendOperation = GPUBlendOperation.Min;
  44133. break;
  44134. case MaxEquation:
  44135. blendOperation = GPUBlendOperation.Max;
  44136. break;
  44137. default:
  44138. console.error( 'THREE.WebGPUPipelineUtils: Blend equation not supported.', blendEquation );
  44139. }
  44140. return blendOperation;
  44141. }
  44142. _getPrimitiveState( object, geometry, material ) {
  44143. const descriptor = {};
  44144. const utils = this.backend.utils;
  44145. descriptor.topology = utils.getPrimitiveTopology( object, material );
  44146. if ( geometry.index !== null && object.isLine === true && object.isLineSegments !== true ) {
  44147. descriptor.stripIndexFormat = ( geometry.index.array instanceof Uint16Array ) ? GPUIndexFormat.Uint16 : GPUIndexFormat.Uint32;
  44148. }
  44149. switch ( material.side ) {
  44150. case FrontSide:
  44151. descriptor.frontFace = GPUFrontFace.CCW;
  44152. descriptor.cullMode = GPUCullMode.Back;
  44153. break;
  44154. case BackSide:
  44155. descriptor.frontFace = GPUFrontFace.CCW;
  44156. descriptor.cullMode = GPUCullMode.Front;
  44157. break;
  44158. case DoubleSide:
  44159. descriptor.frontFace = GPUFrontFace.CCW;
  44160. descriptor.cullMode = GPUCullMode.None;
  44161. break;
  44162. default:
  44163. console.error( 'THREE.WebGPUPipelineUtils: Unknown material.side value.', material.side );
  44164. break;
  44165. }
  44166. return descriptor;
  44167. }
  44168. _getColorWriteMask( material ) {
  44169. return ( material.colorWrite === true ) ? GPUColorWriteFlags.All : GPUColorWriteFlags.None;
  44170. }
  44171. _getDepthCompare( material ) {
  44172. let depthCompare;
  44173. if ( material.depthTest === false ) {
  44174. depthCompare = GPUCompareFunction.Always;
  44175. } else {
  44176. const depthFunc = material.depthFunc;
  44177. switch ( depthFunc ) {
  44178. case NeverDepth:
  44179. depthCompare = GPUCompareFunction.Never;
  44180. break;
  44181. case AlwaysDepth:
  44182. depthCompare = GPUCompareFunction.Always;
  44183. break;
  44184. case LessDepth:
  44185. depthCompare = GPUCompareFunction.Less;
  44186. break;
  44187. case LessEqualDepth:
  44188. depthCompare = GPUCompareFunction.LessEqual;
  44189. break;
  44190. case EqualDepth:
  44191. depthCompare = GPUCompareFunction.Equal;
  44192. break;
  44193. case GreaterEqualDepth:
  44194. depthCompare = GPUCompareFunction.GreaterEqual;
  44195. break;
  44196. case GreaterDepth:
  44197. depthCompare = GPUCompareFunction.Greater;
  44198. break;
  44199. case NotEqualDepth:
  44200. depthCompare = GPUCompareFunction.NotEqual;
  44201. break;
  44202. default:
  44203. console.error( 'THREE.WebGPUPipelineUtils: Invalid depth function.', depthFunc );
  44204. }
  44205. }
  44206. return depthCompare;
  44207. }
  44208. }
  44209. /*// debugger tools
  44210. import 'https://greggman.github.io/webgpu-avoid-redundant-state-setting/webgpu-check-redundant-state-setting.js';
  44211. //*/
  44212. //
  44213. class WebGPUBackend extends Backend {
  44214. constructor( parameters = {} ) {
  44215. super( parameters );
  44216. this.isWebGPUBackend = true;
  44217. // some parameters require default values other than "undefined"
  44218. this.parameters.alpha = ( parameters.alpha === undefined ) ? true : parameters.alpha;
  44219. this.parameters.requiredLimits = ( parameters.requiredLimits === undefined ) ? {} : parameters.requiredLimits;
  44220. this.trackTimestamp = ( parameters.trackTimestamp === true );
  44221. this.device = null;
  44222. this.context = null;
  44223. this.colorBuffer = null;
  44224. this.defaultRenderPassdescriptor = null;
  44225. this.utils = new WebGPUUtils( this );
  44226. this.attributeUtils = new WebGPUAttributeUtils( this );
  44227. this.bindingUtils = new WebGPUBindingUtils( this );
  44228. this.pipelineUtils = new WebGPUPipelineUtils( this );
  44229. this.textureUtils = new WebGPUTextureUtils( this );
  44230. this.occludedResolveCache = new Map();
  44231. }
  44232. async init( renderer ) {
  44233. await super.init( renderer );
  44234. //
  44235. const parameters = this.parameters;
  44236. // create the device if it is not passed with parameters
  44237. let device;
  44238. if ( parameters.device === undefined ) {
  44239. const adapterOptions = {
  44240. powerPreference: parameters.powerPreference
  44241. };
  44242. const adapter = await navigator.gpu.requestAdapter( adapterOptions );
  44243. if ( adapter === null ) {
  44244. throw new Error( 'WebGPUBackend: Unable to create WebGPU adapter.' );
  44245. }
  44246. // feature support
  44247. const features = Object.values( GPUFeatureName );
  44248. const supportedFeatures = [];
  44249. for ( const name of features ) {
  44250. if ( adapter.features.has( name ) ) {
  44251. supportedFeatures.push( name );
  44252. }
  44253. }
  44254. const deviceDescriptor = {
  44255. requiredFeatures: supportedFeatures,
  44256. requiredLimits: parameters.requiredLimits
  44257. };
  44258. device = await adapter.requestDevice( deviceDescriptor );
  44259. } else {
  44260. device = parameters.device;
  44261. }
  44262. const context = ( parameters.context !== undefined ) ? parameters.context : renderer.domElement.getContext( 'webgpu' );
  44263. this.device = device;
  44264. this.context = context;
  44265. const alphaMode = parameters.alpha ? 'premultiplied' : 'opaque';
  44266. this.trackTimestamp = this.trackTimestamp && this.hasFeature( GPUFeatureName.TimestampQuery );
  44267. this.context.configure( {
  44268. device: this.device,
  44269. format: this.utils.getPreferredCanvasFormat(),
  44270. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC,
  44271. alphaMode: alphaMode
  44272. } );
  44273. this.updateSize();
  44274. }
  44275. get coordinateSystem() {
  44276. return WebGPUCoordinateSystem;
  44277. }
  44278. async getArrayBufferAsync( attribute ) {
  44279. return await this.attributeUtils.getArrayBufferAsync( attribute );
  44280. }
  44281. getContext() {
  44282. return this.context;
  44283. }
  44284. _getDefaultRenderPassDescriptor() {
  44285. let descriptor = this.defaultRenderPassdescriptor;
  44286. if ( descriptor === null ) {
  44287. const renderer = this.renderer;
  44288. descriptor = {
  44289. colorAttachments: [ {
  44290. view: null
  44291. } ],
  44292. };
  44293. if ( this.renderer.depth === true || this.renderer.stencil === true ) {
  44294. descriptor.depthStencilAttachment = {
  44295. view: this.textureUtils.getDepthBuffer( renderer.depth, renderer.stencil ).createView()
  44296. };
  44297. }
  44298. const colorAttachment = descriptor.colorAttachments[ 0 ];
  44299. if ( this.renderer.samples > 0 ) {
  44300. colorAttachment.view = this.colorBuffer.createView();
  44301. } else {
  44302. colorAttachment.resolveTarget = undefined;
  44303. }
  44304. this.defaultRenderPassdescriptor = descriptor;
  44305. }
  44306. const colorAttachment = descriptor.colorAttachments[ 0 ];
  44307. if ( this.renderer.samples > 0 ) {
  44308. colorAttachment.resolveTarget = this.context.getCurrentTexture().createView();
  44309. } else {
  44310. colorAttachment.view = this.context.getCurrentTexture().createView();
  44311. }
  44312. return descriptor;
  44313. }
  44314. _getRenderPassDescriptor( renderContext ) {
  44315. const renderTarget = renderContext.renderTarget;
  44316. const renderTargetData = this.get( renderTarget );
  44317. let descriptors = renderTargetData.descriptors;
  44318. if ( descriptors === undefined ||
  44319. renderTargetData.width !== renderTarget.width ||
  44320. renderTargetData.height !== renderTarget.height ||
  44321. renderTargetData.activeMipmapLevel !== renderTarget.activeMipmapLevel ||
  44322. renderTargetData.samples !== renderTarget.samples
  44323. ) {
  44324. descriptors = {};
  44325. renderTargetData.descriptors = descriptors;
  44326. // dispose
  44327. const onDispose = () => {
  44328. renderTarget.removeEventListener( 'dispose', onDispose );
  44329. this.delete( renderTarget );
  44330. };
  44331. renderTarget.addEventListener( 'dispose', onDispose );
  44332. }
  44333. const cacheKey = renderContext.getCacheKey();
  44334. let descriptor = descriptors[ cacheKey ];
  44335. if ( descriptor === undefined ) {
  44336. const textures = renderContext.textures;
  44337. const colorAttachments = [];
  44338. for ( let i = 0; i < textures.length; i ++ ) {
  44339. const textureData = this.get( textures[ i ] );
  44340. const textureView = textureData.texture.createView( {
  44341. baseMipLevel: renderContext.activeMipmapLevel,
  44342. mipLevelCount: 1,
  44343. baseArrayLayer: renderContext.activeCubeFace,
  44344. dimension: GPUTextureViewDimension.TwoD
  44345. } );
  44346. let view, resolveTarget;
  44347. if ( textureData.msaaTexture !== undefined ) {
  44348. view = textureData.msaaTexture.createView();
  44349. resolveTarget = textureView;
  44350. } else {
  44351. view = textureView;
  44352. resolveTarget = undefined;
  44353. }
  44354. colorAttachments.push( {
  44355. view,
  44356. resolveTarget,
  44357. loadOp: GPULoadOp.Load,
  44358. storeOp: GPUStoreOp.Store
  44359. } );
  44360. }
  44361. descriptor = {
  44362. colorAttachments,
  44363. };
  44364. if ( renderContext.depth ) {
  44365. const depthTextureData = this.get( renderContext.depthTexture );
  44366. const depthStencilAttachment = {
  44367. view: depthTextureData.texture.createView()
  44368. };
  44369. descriptor.depthStencilAttachment = depthStencilAttachment;
  44370. }
  44371. descriptors[ cacheKey ] = descriptor;
  44372. renderTargetData.width = renderTarget.width;
  44373. renderTargetData.height = renderTarget.height;
  44374. renderTargetData.samples = renderTarget.samples;
  44375. renderTargetData.activeMipmapLevel = renderTarget.activeMipmapLevel;
  44376. }
  44377. return descriptor;
  44378. }
  44379. beginRender( renderContext ) {
  44380. const renderContextData = this.get( renderContext );
  44381. const device = this.device;
  44382. const occlusionQueryCount = renderContext.occlusionQueryCount;
  44383. let occlusionQuerySet;
  44384. if ( occlusionQueryCount > 0 ) {
  44385. if ( renderContextData.currentOcclusionQuerySet ) renderContextData.currentOcclusionQuerySet.destroy();
  44386. if ( renderContextData.currentOcclusionQueryBuffer ) renderContextData.currentOcclusionQueryBuffer.destroy();
  44387. // Get a reference to the array of objects with queries. The renderContextData property
  44388. // can be changed by another render pass before the buffer.mapAsyc() completes.
  44389. renderContextData.currentOcclusionQuerySet = renderContextData.occlusionQuerySet;
  44390. renderContextData.currentOcclusionQueryBuffer = renderContextData.occlusionQueryBuffer;
  44391. renderContextData.currentOcclusionQueryObjects = renderContextData.occlusionQueryObjects;
  44392. //
  44393. occlusionQuerySet = device.createQuerySet( { type: 'occlusion', count: occlusionQueryCount } );
  44394. renderContextData.occlusionQuerySet = occlusionQuerySet;
  44395. renderContextData.occlusionQueryIndex = 0;
  44396. renderContextData.occlusionQueryObjects = new Array( occlusionQueryCount );
  44397. renderContextData.lastOcclusionObject = null;
  44398. }
  44399. let descriptor;
  44400. if ( renderContext.textures === null ) {
  44401. descriptor = this._getDefaultRenderPassDescriptor();
  44402. } else {
  44403. descriptor = this._getRenderPassDescriptor( renderContext );
  44404. }
  44405. this.initTimestampQuery( renderContext, descriptor );
  44406. descriptor.occlusionQuerySet = occlusionQuerySet;
  44407. const depthStencilAttachment = descriptor.depthStencilAttachment;
  44408. if ( renderContext.textures !== null ) {
  44409. const colorAttachments = descriptor.colorAttachments;
  44410. for ( let i = 0; i < colorAttachments.length; i ++ ) {
  44411. const colorAttachment = colorAttachments[ i ];
  44412. if ( renderContext.clearColor ) {
  44413. colorAttachment.clearValue = i === 0 ? renderContext.clearColorValue : { r: 0, g: 0, b: 0, a: 1 };
  44414. colorAttachment.loadOp = GPULoadOp.Clear;
  44415. colorAttachment.storeOp = GPUStoreOp.Store;
  44416. } else {
  44417. colorAttachment.loadOp = GPULoadOp.Load;
  44418. colorAttachment.storeOp = GPUStoreOp.Store;
  44419. }
  44420. }
  44421. } else {
  44422. const colorAttachment = descriptor.colorAttachments[ 0 ];
  44423. if ( renderContext.clearColor ) {
  44424. colorAttachment.clearValue = renderContext.clearColorValue;
  44425. colorAttachment.loadOp = GPULoadOp.Clear;
  44426. colorAttachment.storeOp = GPUStoreOp.Store;
  44427. } else {
  44428. colorAttachment.loadOp = GPULoadOp.Load;
  44429. colorAttachment.storeOp = GPUStoreOp.Store;
  44430. }
  44431. }
  44432. //
  44433. if ( renderContext.depth ) {
  44434. if ( renderContext.clearDepth ) {
  44435. depthStencilAttachment.depthClearValue = renderContext.clearDepthValue;
  44436. depthStencilAttachment.depthLoadOp = GPULoadOp.Clear;
  44437. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  44438. } else {
  44439. depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  44440. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  44441. }
  44442. }
  44443. if ( renderContext.stencil ) {
  44444. if ( renderContext.clearStencil ) {
  44445. depthStencilAttachment.stencilClearValue = renderContext.clearStencilValue;
  44446. depthStencilAttachment.stencilLoadOp = GPULoadOp.Clear;
  44447. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  44448. } else {
  44449. depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  44450. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  44451. }
  44452. }
  44453. //
  44454. const encoder = device.createCommandEncoder( { label: 'renderContext_' + renderContext.id } );
  44455. const currentPass = encoder.beginRenderPass( descriptor );
  44456. //
  44457. renderContextData.descriptor = descriptor;
  44458. renderContextData.encoder = encoder;
  44459. renderContextData.currentPass = currentPass;
  44460. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  44461. renderContextData.renderBundles = [];
  44462. //
  44463. if ( renderContext.viewport ) {
  44464. this.updateViewport( renderContext );
  44465. }
  44466. if ( renderContext.scissor ) {
  44467. const { x, y, width, height } = renderContext.scissorValue;
  44468. currentPass.setScissorRect( x, y, width, height );
  44469. }
  44470. }
  44471. finishRender( renderContext ) {
  44472. const renderContextData = this.get( renderContext );
  44473. const occlusionQueryCount = renderContext.occlusionQueryCount;
  44474. if ( renderContextData.renderBundles.length > 0 ) {
  44475. renderContextData.currentPass.executeBundles( renderContextData.renderBundles );
  44476. }
  44477. if ( occlusionQueryCount > renderContextData.occlusionQueryIndex ) {
  44478. renderContextData.currentPass.endOcclusionQuery();
  44479. }
  44480. renderContextData.currentPass.end();
  44481. if ( occlusionQueryCount > 0 ) {
  44482. const bufferSize = occlusionQueryCount * 8; // 8 byte entries for query results
  44483. //
  44484. let queryResolveBuffer = this.occludedResolveCache.get( bufferSize );
  44485. if ( queryResolveBuffer === undefined ) {
  44486. queryResolveBuffer = this.device.createBuffer(
  44487. {
  44488. size: bufferSize,
  44489. usage: GPUBufferUsage.QUERY_RESOLVE | GPUBufferUsage.COPY_SRC
  44490. }
  44491. );
  44492. this.occludedResolveCache.set( bufferSize, queryResolveBuffer );
  44493. }
  44494. //
  44495. const readBuffer = this.device.createBuffer(
  44496. {
  44497. size: bufferSize,
  44498. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  44499. }
  44500. );
  44501. // two buffers required here - WebGPU doesn't allow usage of QUERY_RESOLVE & MAP_READ to be combined
  44502. renderContextData.encoder.resolveQuerySet( renderContextData.occlusionQuerySet, 0, occlusionQueryCount, queryResolveBuffer, 0 );
  44503. renderContextData.encoder.copyBufferToBuffer( queryResolveBuffer, 0, readBuffer, 0, bufferSize );
  44504. renderContextData.occlusionQueryBuffer = readBuffer;
  44505. //
  44506. this.resolveOccludedAsync( renderContext );
  44507. }
  44508. this.prepareTimestampBuffer( renderContext, renderContextData.encoder );
  44509. this.device.queue.submit( [ renderContextData.encoder.finish() ] );
  44510. //
  44511. if ( renderContext.textures !== null ) {
  44512. const textures = renderContext.textures;
  44513. for ( let i = 0; i < textures.length; i ++ ) {
  44514. const texture = textures[ i ];
  44515. if ( texture.generateMipmaps === true ) {
  44516. this.textureUtils.generateMipmaps( texture );
  44517. }
  44518. }
  44519. }
  44520. }
  44521. isOccluded( renderContext, object ) {
  44522. const renderContextData = this.get( renderContext );
  44523. return renderContextData.occluded && renderContextData.occluded.has( object );
  44524. }
  44525. async resolveOccludedAsync( renderContext ) {
  44526. const renderContextData = this.get( renderContext );
  44527. // handle occlusion query results
  44528. const { currentOcclusionQueryBuffer, currentOcclusionQueryObjects } = renderContextData;
  44529. if ( currentOcclusionQueryBuffer && currentOcclusionQueryObjects ) {
  44530. const occluded = new WeakSet();
  44531. renderContextData.currentOcclusionQueryObjects = null;
  44532. renderContextData.currentOcclusionQueryBuffer = null;
  44533. await currentOcclusionQueryBuffer.mapAsync( GPUMapMode.READ );
  44534. const buffer = currentOcclusionQueryBuffer.getMappedRange();
  44535. const results = new BigUint64Array( buffer );
  44536. for ( let i = 0; i < currentOcclusionQueryObjects.length; i ++ ) {
  44537. if ( results[ i ] !== BigInt( 0 ) ) {
  44538. occluded.add( currentOcclusionQueryObjects[ i ] );
  44539. }
  44540. }
  44541. currentOcclusionQueryBuffer.destroy();
  44542. renderContextData.occluded = occluded;
  44543. }
  44544. }
  44545. updateViewport( renderContext ) {
  44546. const { currentPass } = this.get( renderContext );
  44547. const { x, y, width, height, minDepth, maxDepth } = renderContext.viewportValue;
  44548. currentPass.setViewport( x, y, width, height, minDepth, maxDepth );
  44549. }
  44550. clear( color, depth, stencil, renderTargetData = null ) {
  44551. const device = this.device;
  44552. const renderer = this.renderer;
  44553. let colorAttachments = [];
  44554. let depthStencilAttachment;
  44555. let clearValue;
  44556. let supportsDepth;
  44557. let supportsStencil;
  44558. if ( color ) {
  44559. const clearColor = this.getClearColor();
  44560. if ( this.renderer.alpha === true ) {
  44561. // premultiply alpha
  44562. const a = clearColor.a;
  44563. clearValue = { r: clearColor.r * a, g: clearColor.g * a, b: clearColor.b * a, a: a };
  44564. } else {
  44565. clearValue = { r: clearColor.r, g: clearColor.g, b: clearColor.b, a: clearColor.a };
  44566. }
  44567. }
  44568. if ( renderTargetData === null ) {
  44569. supportsDepth = renderer.depth;
  44570. supportsStencil = renderer.stencil;
  44571. const descriptor = this._getDefaultRenderPassDescriptor();
  44572. if ( color ) {
  44573. colorAttachments = descriptor.colorAttachments;
  44574. const colorAttachment = colorAttachments[ 0 ];
  44575. colorAttachment.clearValue = clearValue;
  44576. colorAttachment.loadOp = GPULoadOp.Clear;
  44577. colorAttachment.storeOp = GPUStoreOp.Store;
  44578. }
  44579. if ( supportsDepth || supportsStencil ) {
  44580. depthStencilAttachment = descriptor.depthStencilAttachment;
  44581. }
  44582. } else {
  44583. supportsDepth = renderTargetData.depth;
  44584. supportsStencil = renderTargetData.stencil;
  44585. if ( color ) {
  44586. for ( const texture of renderTargetData.textures ) {
  44587. const textureData = this.get( texture );
  44588. const textureView = textureData.texture.createView();
  44589. let view, resolveTarget;
  44590. if ( textureData.msaaTexture !== undefined ) {
  44591. view = textureData.msaaTexture.createView();
  44592. resolveTarget = textureView;
  44593. } else {
  44594. view = textureView;
  44595. resolveTarget = undefined;
  44596. }
  44597. colorAttachments.push( {
  44598. view,
  44599. resolveTarget,
  44600. clearValue,
  44601. loadOp: GPULoadOp.Clear,
  44602. storeOp: GPUStoreOp.Store
  44603. } );
  44604. }
  44605. }
  44606. if ( supportsDepth || supportsStencil ) {
  44607. const depthTextureData = this.get( renderTargetData.depthTexture );
  44608. depthStencilAttachment = {
  44609. view: depthTextureData.texture.createView()
  44610. };
  44611. }
  44612. }
  44613. //
  44614. if ( supportsDepth ) {
  44615. if ( depth ) {
  44616. depthStencilAttachment.depthLoadOp = GPULoadOp.Clear;
  44617. depthStencilAttachment.depthClearValue = renderer.getClearDepth();
  44618. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  44619. } else {
  44620. depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  44621. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  44622. }
  44623. }
  44624. //
  44625. if ( supportsStencil ) {
  44626. if ( stencil ) {
  44627. depthStencilAttachment.stencilLoadOp = GPULoadOp.Clear;
  44628. depthStencilAttachment.stencilClearValue = renderer.getClearStencil();
  44629. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  44630. } else {
  44631. depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  44632. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  44633. }
  44634. }
  44635. //
  44636. const encoder = device.createCommandEncoder( {} );
  44637. const currentPass = encoder.beginRenderPass( {
  44638. colorAttachments,
  44639. depthStencilAttachment
  44640. } );
  44641. currentPass.end();
  44642. device.queue.submit( [ encoder.finish() ] );
  44643. }
  44644. // compute
  44645. beginCompute( computeGroup ) {
  44646. const groupGPU = this.get( computeGroup );
  44647. const descriptor = {};
  44648. this.initTimestampQuery( computeGroup, descriptor );
  44649. groupGPU.cmdEncoderGPU = this.device.createCommandEncoder();
  44650. groupGPU.passEncoderGPU = groupGPU.cmdEncoderGPU.beginComputePass( descriptor );
  44651. }
  44652. compute( computeGroup, computeNode, bindings, pipeline ) {
  44653. const { passEncoderGPU } = this.get( computeGroup );
  44654. // pipeline
  44655. const pipelineGPU = this.get( pipeline ).pipeline;
  44656. passEncoderGPU.setPipeline( pipelineGPU );
  44657. // bind groups
  44658. for ( let i = 0, l = bindings.length; i < l; i ++ ) {
  44659. const bindGroup = bindings[ i ];
  44660. const bindingsData = this.get( bindGroup );
  44661. passEncoderGPU.setBindGroup( i, bindingsData.group );
  44662. }
  44663. const maxComputeWorkgroupsPerDimension = this.device.limits.maxComputeWorkgroupsPerDimension;
  44664. const computeNodeData = this.get( computeNode );
  44665. if ( computeNodeData.dispatchSize === undefined ) computeNodeData.dispatchSize = { x: 0, y: 1, z: 1 };
  44666. const { dispatchSize } = computeNodeData;
  44667. if ( computeNode.dispatchCount > maxComputeWorkgroupsPerDimension ) {
  44668. dispatchSize.x = Math.min( computeNode.dispatchCount, maxComputeWorkgroupsPerDimension );
  44669. dispatchSize.y = Math.ceil( computeNode.dispatchCount / maxComputeWorkgroupsPerDimension );
  44670. } else {
  44671. dispatchSize.x = computeNode.dispatchCount;
  44672. }
  44673. passEncoderGPU.dispatchWorkgroups(
  44674. dispatchSize.x,
  44675. dispatchSize.y,
  44676. dispatchSize.z
  44677. );
  44678. }
  44679. finishCompute( computeGroup ) {
  44680. const groupData = this.get( computeGroup );
  44681. groupData.passEncoderGPU.end();
  44682. this.prepareTimestampBuffer( computeGroup, groupData.cmdEncoderGPU );
  44683. this.device.queue.submit( [ groupData.cmdEncoderGPU.finish() ] );
  44684. }
  44685. // render object
  44686. draw( renderObject, info ) {
  44687. const { object, context, pipeline } = renderObject;
  44688. const bindings = renderObject.getBindings();
  44689. const renderContextData = this.get( context );
  44690. const pipelineGPU = this.get( pipeline ).pipeline;
  44691. const currentSets = renderContextData.currentSets;
  44692. const passEncoderGPU = renderContextData.currentPass;
  44693. const drawParams = renderObject.getDrawParameters();
  44694. if ( drawParams === null ) return;
  44695. // pipeline
  44696. if ( currentSets.pipeline !== pipelineGPU ) {
  44697. passEncoderGPU.setPipeline( pipelineGPU );
  44698. currentSets.pipeline = pipelineGPU;
  44699. }
  44700. // bind groups
  44701. const currentBindingGroups = currentSets.bindingGroups;
  44702. for ( let i = 0, l = bindings.length; i < l; i ++ ) {
  44703. const bindGroup = bindings[ i ];
  44704. const bindingsData = this.get( bindGroup );
  44705. if ( currentBindingGroups[ bindGroup.index ] !== bindGroup.id ) {
  44706. passEncoderGPU.setBindGroup( bindGroup.index, bindingsData.group );
  44707. currentBindingGroups[ bindGroup.index ] = bindGroup.id;
  44708. }
  44709. }
  44710. // attributes
  44711. const index = renderObject.getIndex();
  44712. const hasIndex = ( index !== null );
  44713. // index
  44714. if ( hasIndex === true ) {
  44715. if ( currentSets.index !== index ) {
  44716. const buffer = this.get( index ).buffer;
  44717. const indexFormat = ( index.array instanceof Uint16Array ) ? GPUIndexFormat.Uint16 : GPUIndexFormat.Uint32;
  44718. passEncoderGPU.setIndexBuffer( buffer, indexFormat );
  44719. currentSets.index = index;
  44720. }
  44721. }
  44722. // vertex buffers
  44723. const vertexBuffers = renderObject.getVertexBuffers();
  44724. for ( let i = 0, l = vertexBuffers.length; i < l; i ++ ) {
  44725. const vertexBuffer = vertexBuffers[ i ];
  44726. if ( currentSets.attributes[ i ] !== vertexBuffer ) {
  44727. const buffer = this.get( vertexBuffer ).buffer;
  44728. passEncoderGPU.setVertexBuffer( i, buffer );
  44729. currentSets.attributes[ i ] = vertexBuffer;
  44730. }
  44731. }
  44732. // occlusion queries - handle multiple consecutive draw calls for an object
  44733. if ( renderContextData.occlusionQuerySet !== undefined ) {
  44734. const lastObject = renderContextData.lastOcclusionObject;
  44735. if ( lastObject !== object ) {
  44736. if ( lastObject !== null && lastObject.occlusionTest === true ) {
  44737. passEncoderGPU.endOcclusionQuery();
  44738. renderContextData.occlusionQueryIndex ++;
  44739. }
  44740. if ( object.occlusionTest === true ) {
  44741. passEncoderGPU.beginOcclusionQuery( renderContextData.occlusionQueryIndex );
  44742. renderContextData.occlusionQueryObjects[ renderContextData.occlusionQueryIndex ] = object;
  44743. }
  44744. renderContextData.lastOcclusionObject = object;
  44745. }
  44746. }
  44747. // draw
  44748. if ( object.isBatchedMesh === true ) {
  44749. const starts = object._multiDrawStarts;
  44750. const counts = object._multiDrawCounts;
  44751. const drawCount = object._multiDrawCount;
  44752. const drawInstances = object._multiDrawInstances;
  44753. const bytesPerElement = hasIndex ? index.array.BYTES_PER_ELEMENT : 1;
  44754. for ( let i = 0; i < drawCount; i ++ ) {
  44755. const count = drawInstances ? drawInstances[ i ] : 1;
  44756. const firstInstance = count > 1 ? 0 : i;
  44757. passEncoderGPU.drawIndexed( counts[ i ], count, starts[ i ] / bytesPerElement, 0, firstInstance );
  44758. }
  44759. } else if ( hasIndex === true ) {
  44760. const { vertexCount: indexCount, instanceCount, firstVertex: firstIndex } = drawParams;
  44761. const indirect = renderObject.getIndirect();
  44762. if ( indirect !== null ) {
  44763. const buffer = this.get( indirect ).buffer;
  44764. passEncoderGPU.drawIndexedIndirect( buffer, 0 );
  44765. } else {
  44766. passEncoderGPU.drawIndexed( indexCount, instanceCount, firstIndex, 0, 0 );
  44767. }
  44768. info.update( object, indexCount, instanceCount );
  44769. } else {
  44770. const { vertexCount, instanceCount, firstVertex } = drawParams;
  44771. const indirect = renderObject.getIndirect();
  44772. if ( indirect !== null ) {
  44773. const buffer = this.get( indirect ).buffer;
  44774. passEncoderGPU.drawIndirect( buffer, 0 );
  44775. } else {
  44776. passEncoderGPU.draw( vertexCount, instanceCount, firstVertex, 0 );
  44777. }
  44778. info.update( object, vertexCount, instanceCount );
  44779. }
  44780. }
  44781. // cache key
  44782. needsRenderUpdate( renderObject ) {
  44783. const data = this.get( renderObject );
  44784. const { object, material } = renderObject;
  44785. const utils = this.utils;
  44786. const sampleCount = utils.getSampleCountRenderContext( renderObject.context );
  44787. const colorSpace = utils.getCurrentColorSpace( renderObject.context );
  44788. const colorFormat = utils.getCurrentColorFormat( renderObject.context );
  44789. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderObject.context );
  44790. const primitiveTopology = utils.getPrimitiveTopology( object, material );
  44791. let needsUpdate = false;
  44792. if ( data.material !== material || data.materialVersion !== material.version ||
  44793. data.transparent !== material.transparent || data.blending !== material.blending || data.premultipliedAlpha !== material.premultipliedAlpha ||
  44794. data.blendSrc !== material.blendSrc || data.blendDst !== material.blendDst || data.blendEquation !== material.blendEquation ||
  44795. data.blendSrcAlpha !== material.blendSrcAlpha || data.blendDstAlpha !== material.blendDstAlpha || data.blendEquationAlpha !== material.blendEquationAlpha ||
  44796. data.colorWrite !== material.colorWrite || data.depthWrite !== material.depthWrite || data.depthTest !== material.depthTest || data.depthFunc !== material.depthFunc ||
  44797. data.stencilWrite !== material.stencilWrite || data.stencilFunc !== material.stencilFunc ||
  44798. data.stencilFail !== material.stencilFail || data.stencilZFail !== material.stencilZFail || data.stencilZPass !== material.stencilZPass ||
  44799. data.stencilFuncMask !== material.stencilFuncMask || data.stencilWriteMask !== material.stencilWriteMask ||
  44800. data.side !== material.side || data.alphaToCoverage !== material.alphaToCoverage ||
  44801. data.sampleCount !== sampleCount || data.colorSpace !== colorSpace ||
  44802. data.colorFormat !== colorFormat || data.depthStencilFormat !== depthStencilFormat ||
  44803. data.primitiveTopology !== primitiveTopology ||
  44804. data.clippingContextCacheKey !== renderObject.clippingContext.cacheKey
  44805. ) {
  44806. data.material = material; data.materialVersion = material.version;
  44807. data.transparent = material.transparent; data.blending = material.blending; data.premultipliedAlpha = material.premultipliedAlpha;
  44808. data.blendSrc = material.blendSrc; data.blendDst = material.blendDst; data.blendEquation = material.blendEquation;
  44809. data.blendSrcAlpha = material.blendSrcAlpha; data.blendDstAlpha = material.blendDstAlpha; data.blendEquationAlpha = material.blendEquationAlpha;
  44810. data.colorWrite = material.colorWrite;
  44811. data.depthWrite = material.depthWrite; data.depthTest = material.depthTest; data.depthFunc = material.depthFunc;
  44812. data.stencilWrite = material.stencilWrite; data.stencilFunc = material.stencilFunc;
  44813. data.stencilFail = material.stencilFail; data.stencilZFail = material.stencilZFail; data.stencilZPass = material.stencilZPass;
  44814. data.stencilFuncMask = material.stencilFuncMask; data.stencilWriteMask = material.stencilWriteMask;
  44815. data.side = material.side; data.alphaToCoverage = material.alphaToCoverage;
  44816. data.sampleCount = sampleCount;
  44817. data.colorSpace = colorSpace;
  44818. data.colorFormat = colorFormat;
  44819. data.depthStencilFormat = depthStencilFormat;
  44820. data.primitiveTopology = primitiveTopology;
  44821. data.clippingContextCacheKey = renderObject.clippingContext.cacheKey;
  44822. needsUpdate = true;
  44823. }
  44824. return needsUpdate;
  44825. }
  44826. getRenderCacheKey( renderObject ) {
  44827. const { object, material } = renderObject;
  44828. const utils = this.utils;
  44829. const renderContext = renderObject.context;
  44830. return [
  44831. material.transparent, material.blending, material.premultipliedAlpha,
  44832. material.blendSrc, material.blendDst, material.blendEquation,
  44833. material.blendSrcAlpha, material.blendDstAlpha, material.blendEquationAlpha,
  44834. material.colorWrite,
  44835. material.depthWrite, material.depthTest, material.depthFunc,
  44836. material.stencilWrite, material.stencilFunc,
  44837. material.stencilFail, material.stencilZFail, material.stencilZPass,
  44838. material.stencilFuncMask, material.stencilWriteMask,
  44839. material.side,
  44840. utils.getSampleCountRenderContext( renderContext ),
  44841. utils.getCurrentColorSpace( renderContext ), utils.getCurrentColorFormat( renderContext ), utils.getCurrentDepthStencilFormat( renderContext ),
  44842. utils.getPrimitiveTopology( object, material ),
  44843. renderObject.clippingContext.cacheKey
  44844. ].join();
  44845. }
  44846. // textures
  44847. createSampler( texture ) {
  44848. this.textureUtils.createSampler( texture );
  44849. }
  44850. destroySampler( texture ) {
  44851. this.textureUtils.destroySampler( texture );
  44852. }
  44853. createDefaultTexture( texture ) {
  44854. this.textureUtils.createDefaultTexture( texture );
  44855. }
  44856. createTexture( texture, options ) {
  44857. this.textureUtils.createTexture( texture, options );
  44858. }
  44859. updateTexture( texture, options ) {
  44860. this.textureUtils.updateTexture( texture, options );
  44861. }
  44862. generateMipmaps( texture ) {
  44863. this.textureUtils.generateMipmaps( texture );
  44864. }
  44865. destroyTexture( texture ) {
  44866. this.textureUtils.destroyTexture( texture );
  44867. }
  44868. copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  44869. return this.textureUtils.copyTextureToBuffer( texture, x, y, width, height, faceIndex );
  44870. }
  44871. initTimestampQuery( renderContext, descriptor ) {
  44872. if ( ! this.trackTimestamp ) return;
  44873. const renderContextData = this.get( renderContext );
  44874. if ( ! renderContextData.timeStampQuerySet ) {
  44875. // Create a GPUQuerySet which holds 2 timestamp query results: one for the
  44876. // beginning and one for the end of compute pass execution.
  44877. const timeStampQuerySet = this.device.createQuerySet( { type: 'timestamp', count: 2 } );
  44878. const timestampWrites = {
  44879. querySet: timeStampQuerySet,
  44880. beginningOfPassWriteIndex: 0, // Write timestamp in index 0 when pass begins.
  44881. endOfPassWriteIndex: 1, // Write timestamp in index 1 when pass ends.
  44882. };
  44883. Object.assign( descriptor, {
  44884. timestampWrites,
  44885. } );
  44886. renderContextData.timeStampQuerySet = timeStampQuerySet;
  44887. }
  44888. }
  44889. // timestamp utils
  44890. prepareTimestampBuffer( renderContext, encoder ) {
  44891. if ( ! this.trackTimestamp ) return;
  44892. const renderContextData = this.get( renderContext );
  44893. const size = 2 * BigInt64Array.BYTES_PER_ELEMENT;
  44894. if ( renderContextData.currentTimestampQueryBuffers === undefined ) {
  44895. renderContextData.currentTimestampQueryBuffers = {
  44896. resolveBuffer: this.device.createBuffer( {
  44897. label: 'timestamp resolve buffer',
  44898. size: size,
  44899. usage: GPUBufferUsage.QUERY_RESOLVE | GPUBufferUsage.COPY_SRC,
  44900. } ),
  44901. resultBuffer: this.device.createBuffer( {
  44902. label: 'timestamp result buffer',
  44903. size: size,
  44904. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ,
  44905. } ),
  44906. isMappingPending: false,
  44907. };
  44908. }
  44909. const { resolveBuffer, resultBuffer, isMappingPending } = renderContextData.currentTimestampQueryBuffers;
  44910. if ( isMappingPending === true ) return;
  44911. encoder.resolveQuerySet( renderContextData.timeStampQuerySet, 0, 2, resolveBuffer, 0 );
  44912. encoder.copyBufferToBuffer( resolveBuffer, 0, resultBuffer, 0, size );
  44913. }
  44914. async resolveTimestampAsync( renderContext, type = 'render' ) {
  44915. if ( ! this.trackTimestamp ) return;
  44916. const renderContextData = this.get( renderContext );
  44917. if ( renderContextData.currentTimestampQueryBuffers === undefined ) return;
  44918. const { resultBuffer, isMappingPending } = renderContextData.currentTimestampQueryBuffers;
  44919. if ( isMappingPending === true ) return;
  44920. renderContextData.currentTimestampQueryBuffers.isMappingPending = true;
  44921. resultBuffer.mapAsync( GPUMapMode.READ ).then( () => {
  44922. const times = new BigUint64Array( resultBuffer.getMappedRange() );
  44923. const duration = Number( times[ 1 ] - times[ 0 ] ) / 1000000;
  44924. this.renderer.info.updateTimestamp( type, duration );
  44925. resultBuffer.unmap();
  44926. renderContextData.currentTimestampQueryBuffers.isMappingPending = false;
  44927. } );
  44928. }
  44929. // node builder
  44930. createNodeBuilder( object, renderer ) {
  44931. return new WGSLNodeBuilder( object, renderer );
  44932. }
  44933. // program
  44934. createProgram( program ) {
  44935. const programGPU = this.get( program );
  44936. programGPU.module = {
  44937. module: this.device.createShaderModule( { code: program.code, label: program.stage } ),
  44938. entryPoint: 'main'
  44939. };
  44940. }
  44941. destroyProgram( program ) {
  44942. this.delete( program );
  44943. }
  44944. // pipelines
  44945. createRenderPipeline( renderObject, promises ) {
  44946. this.pipelineUtils.createRenderPipeline( renderObject, promises );
  44947. }
  44948. createComputePipeline( computePipeline, bindings ) {
  44949. this.pipelineUtils.createComputePipeline( computePipeline, bindings );
  44950. }
  44951. beginBundle( renderContext ) {
  44952. const renderContextData = this.get( renderContext );
  44953. renderContextData._currentPass = renderContextData.currentPass;
  44954. renderContextData._currentSets = renderContextData.currentSets;
  44955. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  44956. renderContextData.currentPass = this.pipelineUtils.createBundleEncoder( renderContext );
  44957. }
  44958. finishBundle( renderContext, bundle ) {
  44959. const renderContextData = this.get( renderContext );
  44960. const bundleEncoder = renderContextData.currentPass;
  44961. const bundleGPU = bundleEncoder.finish();
  44962. this.get( bundle ).bundleGPU = bundleGPU;
  44963. // restore render pass state
  44964. renderContextData.currentSets = renderContextData._currentSets;
  44965. renderContextData.currentPass = renderContextData._currentPass;
  44966. }
  44967. addBundle( renderContext, bundle ) {
  44968. const renderContextData = this.get( renderContext );
  44969. renderContextData.renderBundles.push( this.get( bundle ).bundleGPU );
  44970. }
  44971. // bindings
  44972. createBindings( bindGroup ) {
  44973. this.bindingUtils.createBindings( bindGroup );
  44974. }
  44975. updateBindings( bindGroup ) {
  44976. this.bindingUtils.createBindings( bindGroup );
  44977. }
  44978. updateBinding( binding ) {
  44979. this.bindingUtils.updateBinding( binding );
  44980. }
  44981. // attributes
  44982. createIndexAttribute( attribute ) {
  44983. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.INDEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  44984. }
  44985. createAttribute( attribute ) {
  44986. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  44987. }
  44988. createStorageAttribute( attribute ) {
  44989. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.STORAGE | GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  44990. }
  44991. createIndirectStorageAttribute( attribute ) {
  44992. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.STORAGE | GPUBufferUsage.INDIRECT | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  44993. }
  44994. updateAttribute( attribute ) {
  44995. this.attributeUtils.updateAttribute( attribute );
  44996. }
  44997. destroyAttribute( attribute ) {
  44998. this.attributeUtils.destroyAttribute( attribute );
  44999. }
  45000. // canvas
  45001. updateSize() {
  45002. this.colorBuffer = this.textureUtils.getColorBuffer();
  45003. this.defaultRenderPassdescriptor = null;
  45004. }
  45005. // utils public
  45006. getMaxAnisotropy() {
  45007. return 16;
  45008. }
  45009. hasFeature( name ) {
  45010. return this.device.features.has( name );
  45011. }
  45012. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, level = 0 ) {
  45013. let dstX = 0;
  45014. let dstY = 0;
  45015. let dstLayer = 0;
  45016. let srcX = 0;
  45017. let srcY = 0;
  45018. let srcLayer = 0;
  45019. let srcWidth = srcTexture.image.width;
  45020. let srcHeight = srcTexture.image.height;
  45021. if ( srcRegion !== null ) {
  45022. srcX = srcRegion.x;
  45023. srcY = srcRegion.y;
  45024. srcLayer = srcRegion.z || 0;
  45025. srcWidth = srcRegion.width;
  45026. srcHeight = srcRegion.height;
  45027. }
  45028. if ( dstPosition !== null ) {
  45029. dstX = dstPosition.x;
  45030. dstY = dstPosition.y;
  45031. dstLayer = dstPosition.z || 0;
  45032. }
  45033. const encoder = this.device.createCommandEncoder( { label: 'copyTextureToTexture_' + srcTexture.id + '_' + dstTexture.id } );
  45034. const sourceGPU = this.get( srcTexture ).texture;
  45035. const destinationGPU = this.get( dstTexture ).texture;
  45036. encoder.copyTextureToTexture(
  45037. {
  45038. texture: sourceGPU,
  45039. mipLevel: level,
  45040. origin: { x: srcX, y: srcY, z: srcLayer }
  45041. },
  45042. {
  45043. texture: destinationGPU,
  45044. mipLevel: level,
  45045. origin: { x: dstX, y: dstY, z: dstLayer }
  45046. },
  45047. [
  45048. srcWidth,
  45049. srcHeight,
  45050. 1
  45051. ]
  45052. );
  45053. this.device.queue.submit( [ encoder.finish() ] );
  45054. }
  45055. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  45056. const renderContextData = this.get( renderContext );
  45057. const { encoder, descriptor } = renderContextData;
  45058. let sourceGPU = null;
  45059. if ( renderContext.renderTarget ) {
  45060. if ( texture.isDepthTexture ) {
  45061. sourceGPU = this.get( renderContext.depthTexture ).texture;
  45062. } else {
  45063. sourceGPU = this.get( renderContext.textures[ 0 ] ).texture;
  45064. }
  45065. } else {
  45066. if ( texture.isDepthTexture ) {
  45067. sourceGPU = this.textureUtils.getDepthBuffer( renderContext.depth, renderContext.stencil );
  45068. } else {
  45069. sourceGPU = this.context.getCurrentTexture();
  45070. }
  45071. }
  45072. const destinationGPU = this.get( texture ).texture;
  45073. if ( sourceGPU.format !== destinationGPU.format ) {
  45074. console.error( 'WebGPUBackend: copyFramebufferToTexture: Source and destination formats do not match.', sourceGPU.format, destinationGPU.format );
  45075. return;
  45076. }
  45077. renderContextData.currentPass.end();
  45078. encoder.copyTextureToTexture(
  45079. {
  45080. texture: sourceGPU,
  45081. origin: { x: rectangle.x, y: rectangle.y, z: 0 }
  45082. },
  45083. {
  45084. texture: destinationGPU
  45085. },
  45086. [
  45087. rectangle.z,
  45088. rectangle.w
  45089. ]
  45090. );
  45091. if ( texture.generateMipmaps ) this.textureUtils.generateMipmaps( texture );
  45092. for ( let i = 0; i < descriptor.colorAttachments.length; i ++ ) {
  45093. descriptor.colorAttachments[ i ].loadOp = GPULoadOp.Load;
  45094. }
  45095. if ( renderContext.depth ) descriptor.depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  45096. if ( renderContext.stencil ) descriptor.depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  45097. renderContextData.currentPass = encoder.beginRenderPass( descriptor );
  45098. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  45099. }
  45100. }
  45101. class IESSpotLight extends SpotLight {
  45102. constructor( color, intensity, distance, angle, penumbra, decay ) {
  45103. super( color, intensity, distance, angle, penumbra, decay );
  45104. this.iesMap = null;
  45105. }
  45106. copy( source, recursive ) {
  45107. super.copy( source, recursive );
  45108. this.iesMap = source.iesMap;
  45109. return this;
  45110. }
  45111. }
  45112. class StandardNodeLibrary extends NodeLibrary {
  45113. constructor() {
  45114. super();
  45115. this.addMaterial( MeshPhongNodeMaterial, MeshPhongMaterial );
  45116. this.addMaterial( MeshStandardNodeMaterial, MeshStandardMaterial );
  45117. this.addMaterial( MeshPhysicalNodeMaterial, MeshPhysicalMaterial );
  45118. this.addMaterial( MeshToonNodeMaterial, MeshToonMaterial );
  45119. this.addMaterial( MeshBasicNodeMaterial, MeshBasicMaterial );
  45120. this.addMaterial( MeshLambertNodeMaterial, MeshLambertMaterial );
  45121. this.addMaterial( MeshNormalNodeMaterial, MeshNormalMaterial );
  45122. this.addMaterial( MeshMatcapNodeMaterial, MeshMatcapMaterial );
  45123. this.addMaterial( LineBasicNodeMaterial, LineBasicMaterial );
  45124. this.addMaterial( LineDashedNodeMaterial, LineDashedMaterial );
  45125. this.addMaterial( PointsNodeMaterial, PointsMaterial );
  45126. this.addMaterial( SpriteNodeMaterial, SpriteMaterial );
  45127. this.addMaterial( ShadowNodeMaterial, ShadowMaterial );
  45128. this.addLight( PointLightNode, PointLight );
  45129. this.addLight( DirectionalLightNode, DirectionalLight );
  45130. this.addLight( RectAreaLightNode, RectAreaLight );
  45131. this.addLight( SpotLightNode, SpotLight );
  45132. this.addLight( AmbientLightNode, AmbientLight );
  45133. this.addLight( HemisphereLightNode, HemisphereLight );
  45134. this.addLight( LightProbeNode, LightProbe );
  45135. this.addLight( IESSpotLightNode, IESSpotLight );
  45136. this.addToneMapping( linearToneMapping, LinearToneMapping );
  45137. this.addToneMapping( reinhardToneMapping, ReinhardToneMapping );
  45138. this.addToneMapping( cineonToneMapping, CineonToneMapping );
  45139. this.addToneMapping( acesFilmicToneMapping, ACESFilmicToneMapping );
  45140. this.addToneMapping( agxToneMapping, AgXToneMapping );
  45141. this.addToneMapping( neutralToneMapping, NeutralToneMapping );
  45142. this.addColorSpace( linearSRGBTosRGB, getColorSpaceMethod( LinearSRGBColorSpace, SRGBColorSpace ) );
  45143. this.addColorSpace( sRGBToLinearSRGB, getColorSpaceMethod( SRGBColorSpace, LinearSRGBColorSpace ) );
  45144. }
  45145. }
  45146. /*
  45147. const debugHandler = {
  45148. get: function ( target, name ) {
  45149. // Add |update
  45150. if ( /^(create|destroy)/.test( name ) ) console.log( 'WebGPUBackend.' + name );
  45151. return target[ name ];
  45152. }
  45153. };
  45154. */
  45155. class WebGPURenderer extends Renderer {
  45156. constructor( parameters = {} ) {
  45157. let BackendClass;
  45158. if ( parameters.forceWebGL ) {
  45159. BackendClass = WebGLBackend;
  45160. } else {
  45161. BackendClass = WebGPUBackend;
  45162. parameters.getFallback = () => {
  45163. console.warn( 'THREE.WebGPURenderer: WebGPU is not available, running under WebGL2 backend.' );
  45164. return new WebGLBackend( parameters );
  45165. };
  45166. }
  45167. const backend = new BackendClass( parameters );
  45168. //super( new Proxy( backend, debugHandler ) );
  45169. super( backend, parameters );
  45170. this.nodes.library = new StandardNodeLibrary();
  45171. this.isWebGPURenderer = true;
  45172. }
  45173. }
  45174. class BundleGroup extends Group {
  45175. constructor() {
  45176. super();
  45177. this.isBundleGroup = true;
  45178. this.type = 'BundleGroup';
  45179. this.static = true;
  45180. this.version = 0;
  45181. }
  45182. set needsUpdate( value ) {
  45183. if ( value === true ) this.version ++;
  45184. }
  45185. }
  45186. const _material = /*@__PURE__*/ new NodeMaterial();
  45187. const _quadMesh = /*@__PURE__*/ new QuadMesh( _material );
  45188. class PostProcessing {
  45189. constructor( renderer, outputNode = vec4( 0, 0, 1, 1 ) ) {
  45190. this.renderer = renderer;
  45191. this.outputNode = outputNode;
  45192. this.outputColorTransform = true;
  45193. this.needsUpdate = true;
  45194. _material.name = 'PostProcessing';
  45195. }
  45196. render() {
  45197. this.update();
  45198. const renderer = this.renderer;
  45199. const toneMapping = renderer.toneMapping;
  45200. const outputColorSpace = renderer.outputColorSpace;
  45201. renderer.toneMapping = NoToneMapping;
  45202. renderer.outputColorSpace = LinearSRGBColorSpace;
  45203. //
  45204. _quadMesh.render( renderer );
  45205. //
  45206. renderer.toneMapping = toneMapping;
  45207. renderer.outputColorSpace = outputColorSpace;
  45208. }
  45209. update() {
  45210. if ( this.needsUpdate === true ) {
  45211. const renderer = this.renderer;
  45212. const toneMapping = renderer.toneMapping;
  45213. const outputColorSpace = renderer.outputColorSpace;
  45214. _quadMesh.material.fragmentNode = this.outputColorTransform === true ? renderOutput( this.outputNode, toneMapping, outputColorSpace ) : this.outputNode.context( { toneMapping, outputColorSpace } );
  45215. _quadMesh.material.needsUpdate = true;
  45216. this.needsUpdate = false;
  45217. }
  45218. }
  45219. async renderAsync() {
  45220. this.update();
  45221. const renderer = this.renderer;
  45222. const toneMapping = renderer.toneMapping;
  45223. const outputColorSpace = renderer.outputColorSpace;
  45224. renderer.toneMapping = NoToneMapping;
  45225. renderer.outputColorSpace = LinearSRGBColorSpace;
  45226. //
  45227. await _quadMesh.renderAsync( renderer );
  45228. //
  45229. renderer.toneMapping = toneMapping;
  45230. renderer.outputColorSpace = outputColorSpace;
  45231. }
  45232. }
  45233. // renderer state
  45234. function saveRendererState( renderer, state = {} ) {
  45235. state.toneMapping = renderer.toneMapping;
  45236. state.toneMappingExposure = renderer.toneMappingExposure;
  45237. state.outputColorSpace = renderer.outputColorSpace;
  45238. state.renderTarget = renderer.getRenderTarget();
  45239. state.activeCubeFace = renderer.getActiveCubeFace();
  45240. state.activeMipmapLevel = renderer.getActiveMipmapLevel();
  45241. state.renderObjectFunction = renderer.getRenderObjectFunction();
  45242. state.pixelRatio = renderer.getPixelRatio();
  45243. state.mrt = renderer.getMRT();
  45244. state.clearColor = renderer.getClearColor( state.clearColor || new Color() );
  45245. state.clearAlpha = renderer.getClearAlpha();
  45246. state.autoClear = renderer.autoClear;
  45247. state.scissorTest = renderer.getScissorTest();
  45248. return state;
  45249. }
  45250. function resetRendererState( renderer, state ) {
  45251. state = saveRendererState( renderer, state );
  45252. renderer.setMRT( null );
  45253. renderer.setRenderObjectFunction( null );
  45254. renderer.setClearColor( 0x000000, 1 );
  45255. renderer.autoClear = true;
  45256. return state;
  45257. }
  45258. function restoreRendererState( renderer, state ) {
  45259. renderer.toneMapping = state.toneMapping;
  45260. renderer.toneMappingExposure = state.toneMappingExposure;
  45261. renderer.outputColorSpace = state.outputColorSpace;
  45262. renderer.setRenderTarget( state.renderTarget, state.activeCubeFace, state.activeMipmapLevel );
  45263. renderer.setRenderObjectFunction( state.renderObjectFunction );
  45264. renderer.setPixelRatio( state.pixelRatio );
  45265. renderer.setMRT( state.mrt );
  45266. renderer.setClearColor( state.clearColor, state.clearAlpha );
  45267. renderer.autoClear = state.autoClear;
  45268. renderer.setScissorTest( state.scissorTest );
  45269. }
  45270. // renderer and scene state
  45271. function saveRendererAndSceneState( renderer, scene, state = {} ) {
  45272. state = saveRendererState( renderer, state );
  45273. state.background = scene.background;
  45274. state.backgroundNode = scene.backgroundNode;
  45275. state.overrideMaterial = scene.overrideMaterial;
  45276. return state;
  45277. }
  45278. function resetRendererAndSceneState( renderer, scene, state ) {
  45279. state = saveRendererAndSceneState( renderer, scene, state );
  45280. scene.background = null;
  45281. scene.backgroundNode = null;
  45282. scene.overrideMaterial = null;
  45283. return state;
  45284. }
  45285. function restoreRendererAndSceneState( renderer, scene, state ) {
  45286. restoreRendererState( renderer, state );
  45287. scene.background = state.background;
  45288. scene.backgroundNode = state.backgroundNode;
  45289. scene.overrideMaterial = state.overrideMaterial;
  45290. }
  45291. var PostProcessingUtils = /*#__PURE__*/Object.freeze({
  45292. __proto__: null,
  45293. resetRendererAndSceneState: resetRendererAndSceneState,
  45294. resetRendererState: resetRendererState,
  45295. restoreRendererAndSceneState: restoreRendererAndSceneState,
  45296. restoreRendererState: restoreRendererState,
  45297. saveRendererAndSceneState: saveRendererAndSceneState,
  45298. saveRendererState: saveRendererState
  45299. });
  45300. class StorageTexture extends Texture {
  45301. constructor( width = 1, height = 1 ) {
  45302. super();
  45303. this.image = { width, height };
  45304. this.magFilter = LinearFilter;
  45305. this.minFilter = LinearFilter;
  45306. this.isStorageTexture = true;
  45307. }
  45308. }
  45309. class StorageBufferAttribute extends BufferAttribute {
  45310. constructor( array, itemSize, typeClass = Float32Array ) {
  45311. if ( ArrayBuffer.isView( array ) === false ) array = new typeClass( array * itemSize );
  45312. super( array, itemSize );
  45313. this.isStorageBufferAttribute = true;
  45314. }
  45315. }
  45316. class StorageInstancedBufferAttribute extends InstancedBufferAttribute {
  45317. constructor( array, itemSize, typeClass = Float32Array ) {
  45318. if ( ArrayBuffer.isView( array ) === false ) array = new typeClass( array * itemSize );
  45319. super( array, itemSize );
  45320. this.isStorageInstancedBufferAttribute = true;
  45321. }
  45322. }
  45323. class IndirectStorageBufferAttribute extends StorageBufferAttribute {
  45324. constructor( array, itemSize ) {
  45325. super( array, itemSize, Uint32Array );
  45326. this.isIndirectStorageBufferAttribute = true;
  45327. }
  45328. }
  45329. class NodeLoader extends Loader {
  45330. constructor( manager ) {
  45331. super( manager );
  45332. this.textures = {};
  45333. this.nodes = {};
  45334. }
  45335. load( url, onLoad, onProgress, onError ) {
  45336. const loader = new FileLoader( this.manager );
  45337. loader.setPath( this.path );
  45338. loader.setRequestHeader( this.requestHeader );
  45339. loader.setWithCredentials( this.withCredentials );
  45340. loader.load( url, ( text ) => {
  45341. try {
  45342. onLoad( this.parse( JSON.parse( text ) ) );
  45343. } catch ( e ) {
  45344. if ( onError ) {
  45345. onError( e );
  45346. } else {
  45347. console.error( e );
  45348. }
  45349. this.manager.itemError( url );
  45350. }
  45351. }, onProgress, onError );
  45352. }
  45353. parseNodes( json ) {
  45354. const nodes = {};
  45355. if ( json !== undefined ) {
  45356. for ( const nodeJSON of json ) {
  45357. const { uuid, type } = nodeJSON;
  45358. nodes[ uuid ] = this.createNodeFromType( type );
  45359. nodes[ uuid ].uuid = uuid;
  45360. }
  45361. const meta = { nodes, textures: this.textures };
  45362. for ( const nodeJSON of json ) {
  45363. nodeJSON.meta = meta;
  45364. const node = nodes[ nodeJSON.uuid ];
  45365. node.deserialize( nodeJSON );
  45366. delete nodeJSON.meta;
  45367. }
  45368. }
  45369. return nodes;
  45370. }
  45371. parse( json ) {
  45372. const node = this.createNodeFromType( json.type );
  45373. node.uuid = json.uuid;
  45374. const nodes = this.parseNodes( json.nodes );
  45375. const meta = { nodes, textures: this.textures };
  45376. json.meta = meta;
  45377. node.deserialize( json );
  45378. delete json.meta;
  45379. return node;
  45380. }
  45381. setTextures( value ) {
  45382. this.textures = value;
  45383. return this;
  45384. }
  45385. setNodes( value ) {
  45386. this.nodes = value;
  45387. return this;
  45388. }
  45389. createNodeFromType( type ) {
  45390. if ( this.nodes[ type ] === undefined ) {
  45391. console.error( 'THREE.NodeLoader: Node type not found:', type );
  45392. return float();
  45393. }
  45394. return nodeObject( new this.nodes[ type ]() );
  45395. }
  45396. }
  45397. class NodeMaterialLoader extends MaterialLoader {
  45398. constructor( manager ) {
  45399. super( manager );
  45400. this.nodes = {};
  45401. this.nodeMaterials = {};
  45402. }
  45403. parse( json ) {
  45404. const material = super.parse( json );
  45405. const nodes = this.nodes;
  45406. const inputNodes = json.inputNodes;
  45407. for ( const property in inputNodes ) {
  45408. const uuid = inputNodes[ property ];
  45409. material[ property ] = nodes[ uuid ];
  45410. }
  45411. return material;
  45412. }
  45413. setNodes( value ) {
  45414. this.nodes = value;
  45415. return this;
  45416. }
  45417. setNodeMaterials( value ) {
  45418. this.nodeMaterials = value;
  45419. return this;
  45420. }
  45421. createMaterialFromType( type ) {
  45422. const materialClass = this.nodeMaterials[ type ];
  45423. if ( materialClass !== undefined ) {
  45424. return new materialClass();
  45425. }
  45426. return super.createMaterialFromType( type );
  45427. }
  45428. }
  45429. class NodeObjectLoader extends ObjectLoader {
  45430. constructor( manager ) {
  45431. super( manager );
  45432. this.nodes = {};
  45433. this.nodeMaterials = {};
  45434. this._nodesJSON = null;
  45435. }
  45436. setNodes( value ) {
  45437. this.nodes = value;
  45438. return this;
  45439. }
  45440. setNodeMaterials( value ) {
  45441. this.nodeMaterials = value;
  45442. return this;
  45443. }
  45444. parse( json, onLoad ) {
  45445. this._nodesJSON = json.nodes;
  45446. const data = super.parse( json, onLoad );
  45447. this._nodesJSON = null; // dispose
  45448. return data;
  45449. }
  45450. parseNodes( json, textures ) {
  45451. if ( json !== undefined ) {
  45452. const loader = new NodeLoader();
  45453. loader.setNodes( this.nodes );
  45454. loader.setTextures( textures );
  45455. return loader.parseNodes( json );
  45456. }
  45457. return {};
  45458. }
  45459. parseMaterials( json, textures ) {
  45460. const materials = {};
  45461. if ( json !== undefined ) {
  45462. const nodes = this.parseNodes( this._nodesJSON, textures );
  45463. const loader = new NodeMaterialLoader();
  45464. loader.setTextures( textures );
  45465. loader.setNodes( nodes );
  45466. loader.setNodeMaterials( this.nodeMaterials );
  45467. for ( let i = 0, l = json.length; i < l; i ++ ) {
  45468. const data = json[ i ];
  45469. materials[ data.uuid ] = loader.parse( data );
  45470. }
  45471. }
  45472. return materials;
  45473. }
  45474. }
  45475. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  45476. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'register', { detail: {
  45477. revision: REVISION,
  45478. } } ) );
  45479. }
  45480. if ( typeof window !== 'undefined' ) {
  45481. if ( window.__THREE__ ) {
  45482. console.warn( 'WARNING: Multiple instances of Three.js being imported.' );
  45483. } else {
  45484. window.__THREE__ = REVISION;
  45485. }
  45486. }
  45487. export { ACESFilmicToneMapping, AONode, AddEquation, AddOperation, AdditiveAnimationBlendMode, AdditiveBlending, AgXToneMapping, AlphaFormat, AlwaysCompare, AlwaysDepth, AlwaysStencilFunc, AmbientLight, AmbientLightNode, AnalyticLightNode, AnimationAction, AnimationClip, AnimationLoader, AnimationMixer, AnimationObjectGroup, AnimationUtils, ArcCurve, ArrayCamera, ArrayElementNode, ArrowHelper, AssignNode, AttachedBindMode, AttributeNode, Audio, AudioAnalyser, AudioContext, AudioListener, AudioLoader, AxesHelper, BRDF_GGX, BRDF_Lambert, BackSide, BasicDepthPacking, BasicEnvironmentNode, BasicShadowMap$1 as BasicShadowMap, BatchNode, BatchedMesh, Bone, BooleanKeyframeTrack, Box2, Box3, Box3Helper, BoxGeometry, BoxHelper, Break, BufferAttribute, BufferAttributeNode, BufferGeometry, BufferGeometryLoader, BufferNode, BumpMapNode, BundleGroup, BypassNode, ByteType, Cache, CacheNode, Camera, CameraHelper, CanvasTexture, CapsuleGeometry, CatmullRomCurve3, CineonToneMapping, CircleGeometry, ClampToEdgeWrapping, Clock, CodeNode, Color, ColorKeyframeTrack, ColorManagement, ColorSpaceNode, CompressedArrayTexture, CompressedCubeTexture, CompressedTexture, CompressedTextureLoader, ComputeNode, ConeGeometry, ConstNode, ConstantAlphaFactor, ConstantColorFactor, ContextNode, Continue, Controls, ConvertNode, CubeCamera, CubeReflectionMapping, CubeRefractionMapping, CubeTexture, CubeTextureLoader, CubeTextureNode, CubeUVReflectionMapping, CubicBezierCurve, CubicBezierCurve3, CubicInterpolant, CullFaceBack, CullFaceFront, CullFaceFrontBack, CullFaceNone, Curve, CurvePath, CustomBlending, CustomToneMapping, CylinderGeometry, Cylindrical, DFGApprox, D_GGX, Data3DTexture, DataArrayTexture, DataTexture, DataTextureLoader, DataUtils, DecrementStencilOp, DecrementWrapStencilOp, DefaultLoadingManager, DepthFormat, DepthStencilFormat, DepthTexture, DetachedBindMode, DirectionalLight, DirectionalLightHelper, DirectionalLightNode, Discard, DiscreteInterpolant, DodecahedronGeometry, DoubleSide, DstAlphaFactor, DstColorFactor, DynamicCopyUsage, DynamicDrawUsage, DynamicReadUsage, EPSILON, EdgesGeometry, EllipseCurve, EnvironmentNode, EqualCompare, EqualDepth, EqualStencilFunc, EquirectUVNode, EquirectangularReflectionMapping, EquirectangularRefractionMapping, Euler, EventDispatcher, ExpressionNode, ExtrudeGeometry, F_Schlick, FileLoader, Float16BufferAttribute, Float32BufferAttribute, FloatType, Fn, Fog, FogExp2, FogExp2Node, FogNode, FogRangeNode, FramebufferTexture, FrontFacingNode, FrontSide, Frustum, FunctionCallNode, FunctionNode, FunctionOverloadingNode, GLBufferAttribute, GLSL1, GLSL3, GLSLNodeParser, GreaterCompare, GreaterDepth, GreaterEqualCompare, GreaterEqualDepth, GreaterEqualStencilFunc, GreaterStencilFunc, GridHelper, Group, HalfFloatType, HemisphereLight, HemisphereLightHelper, HemisphereLightNode, IESSpotLight, IESSpotLightNode, INFINITY, IcosahedronGeometry, If, ImageBitmapLoader, ImageLoader, ImageUtils, IncrementStencilOp, IncrementWrapStencilOp, IndexNode, IndirectStorageBufferAttribute, InstanceNode, InstancedBufferAttribute, InstancedBufferGeometry, InstancedInterleavedBuffer, InstancedMesh, InstancedPointsNodeMaterial, Int16BufferAttribute, Int32BufferAttribute, Int8BufferAttribute, IntType, InterleavedBuffer, InterleavedBufferAttribute, Interpolant, InterpolateDiscrete, InterpolateLinear, InterpolateSmooth, InvertStencilOp, IrradianceNode, JoinNode, KeepStencilOp, KeyframeTrack, LOD, LatheGeometry, Layers, LessCompare, LessDepth, LessEqualCompare, LessEqualDepth, LessEqualStencilFunc, LessStencilFunc, Light, LightProbe, LightProbeNode, LightingContextNode, LightingModel, LightingNode, LightsNode, Line, Line2NodeMaterial, Line3, LineBasicMaterial, LineBasicNodeMaterial, LineCurve, LineCurve3, LineDashedMaterial, LineDashedNodeMaterial, LineLoop, LineSegments, LinearFilter, LinearInterpolant, LinearMipMapLinearFilter, LinearMipMapNearestFilter, LinearMipmapLinearFilter, LinearMipmapNearestFilter, LinearSRGBColorSpace, LinearToneMapping, LinearTransfer, Loader, LoaderUtils, LoadingManager, Loop, LoopNode, LoopOnce, LoopPingPong, LoopRepeat, LuminanceAlphaFormat, LuminanceFormat, MOUSE, MRTNode, MatcapUVNode, Material, MaterialLoader, MaterialNode, MaterialReferenceNode, MathUtils, Matrix2, Matrix3, Matrix4, MaxEquation, MaxMipLevelNode, Mesh, MeshBasicMaterial, MeshBasicNodeMaterial, MeshDepthMaterial, MeshDistanceMaterial, MeshLambertMaterial, MeshLambertNodeMaterial, MeshMatcapMaterial, MeshMatcapNodeMaterial, MeshNormalMaterial, MeshNormalNodeMaterial, MeshPhongMaterial, MeshPhongNodeMaterial, MeshPhysicalMaterial, MeshPhysicalNodeMaterial, MeshSSSNodeMaterial, MeshStandardMaterial, MeshStandardNodeMaterial, MeshToonMaterial, MeshToonNodeMaterial, MinEquation, MirroredRepeatWrapping, MixOperation, ModelNode, ModelViewProjectionNode, MorphNode, MultiplyBlending, MultiplyOperation, NearestFilter, NearestMipMapLinearFilter, NearestMipMapNearestFilter, NearestMipmapLinearFilter, NearestMipmapNearestFilter, NeutralToneMapping, NeverCompare, NeverDepth, NeverStencilFunc, NoBlending, NoColorSpace, NoToneMapping, Node, NodeAttribute, NodeBuilder, NodeCache, NodeCode, NodeFrame, NodeFunctionInput, NodeLoader, NodeMaterial, NodeMaterialLoader, NodeMaterialObserver, NodeObjectLoader, NodeShaderStage, NodeType, NodeUniform, NodeUpdateType, NodeUtils, NodeVar, NodeVarying, NormalAnimationBlendMode, NormalBlending, NormalMapNode, NotEqualCompare, NotEqualDepth, NotEqualStencilFunc, NumberKeyframeTrack, Object3D, Object3DNode, ObjectLoader, ObjectSpaceNormalMap, OctahedronGeometry, OneFactor, OneMinusConstantAlphaFactor, OneMinusConstantColorFactor, OneMinusDstAlphaFactor, OneMinusDstColorFactor, OneMinusSrcAlphaFactor, OneMinusSrcColorFactor, OrthographicCamera, OutputStructNode, PCFShadowMap$1 as PCFShadowMap, PCFSoftShadowMap$1 as PCFSoftShadowMap, PI, PI2, PMREMGenerator, PMREMNode, ParameterNode, PassNode, Path, PerspectiveCamera, PhongLightingModel, PhysicalLightingModel, Plane, PlaneGeometry, PlaneHelper, PointLight, PointLightHelper, PointLightNode, PointUVNode, Points, PointsMaterial, PointsNodeMaterial, PolarGridHelper, PolyhedronGeometry, PositionalAudio, PostProcessing, PostProcessingUtils, PosterizeNode, PropertyBinding, PropertyMixer, PropertyNode, QuadMesh, QuadraticBezierCurve, QuadraticBezierCurve3, Quaternion, QuaternionKeyframeTrack, QuaternionLinearInterpolant, RED_GREEN_RGTC2_Format, RED_RGTC1_Format, REVISION, RGBADepthPacking, RGBAFormat, RGBAIntegerFormat, RGBA_ASTC_10x10_Format, RGBA_ASTC_10x5_Format, RGBA_ASTC_10x6_Format, RGBA_ASTC_10x8_Format, RGBA_ASTC_12x10_Format, RGBA_ASTC_12x12_Format, RGBA_ASTC_4x4_Format, RGBA_ASTC_5x4_Format, RGBA_ASTC_5x5_Format, RGBA_ASTC_6x5_Format, RGBA_ASTC_6x6_Format, RGBA_ASTC_8x5_Format, RGBA_ASTC_8x6_Format, RGBA_ASTC_8x8_Format, RGBA_BPTC_Format, RGBA_ETC2_EAC_Format, RGBA_PVRTC_2BPPV1_Format, RGBA_PVRTC_4BPPV1_Format, RGBA_S3TC_DXT1_Format, RGBA_S3TC_DXT3_Format, RGBA_S3TC_DXT5_Format, RGBDepthPacking, RGBFormat, RGBIntegerFormat, RGB_BPTC_SIGNED_Format, RGB_BPTC_UNSIGNED_Format, RGB_ETC1_Format, RGB_ETC2_Format, RGB_PVRTC_2BPPV1_Format, RGB_PVRTC_4BPPV1_Format, RGB_S3TC_DXT1_Format, RGDepthPacking, RGFormat, RGIntegerFormat, RTTNode, RangeNode, RawShaderMaterial, Ray, Raycaster, RectAreaLight, RectAreaLightNode, RedFormat, RedIntegerFormat, ReferenceNode, ReflectorNode, ReinhardToneMapping, RemapNode, RenderOutputNode, RenderTarget, RendererReferenceNode, RepeatWrapping, ReplaceStencilOp, Return, ReverseSubtractEquation, RingGeometry, RotateNode, SIGNED_RED_GREEN_RGTC2_Format, SIGNED_RED_RGTC1_Format, SRGBColorSpace, SRGBTransfer, Scene, SceneNode, Schlick_to_F0, ScreenNode, ScriptableNode, ScriptableValueNode, SetNode, ShaderMaterial, ShaderNode, ShadowMaterial, ShadowNode, ShadowNodeMaterial, Shape, ShapeGeometry, ShapePath, ShapeUtils, ShortType, Skeleton, SkeletonHelper, SkinnedMesh, SkinningNode, Source, Sphere, SphereGeometry, Spherical, SphericalHarmonics3, SplineCurve, SplitNode, SpotLight, SpotLightHelper, SpotLightNode, Sprite, SpriteMaterial, SpriteNodeMaterial, SpriteSheetUVNode, SrcAlphaFactor, SrcAlphaSaturateFactor, SrcColorFactor, StackNode, StaticCopyUsage, StaticDrawUsage, StaticReadUsage, StereoCamera, StorageArrayElementNode, StorageBufferAttribute, StorageBufferNode, StorageInstancedBufferAttribute, StorageTexture, StorageTextureNode, StreamCopyUsage, StreamDrawUsage, StreamReadUsage, StringKeyframeTrack, SubtractEquation, SubtractiveBlending, TBNViewMatrix, TOUCH, TangentSpaceNormalMap, TempNode, TetrahedronGeometry, Texture, Texture3DNode, TextureLoader, TextureNode, TextureSizeNode, ToneMappingNode, ToonOutlinePassNode, TorusGeometry, TorusKnotGeometry, Triangle, TriangleFanDrawMode, TriangleStripDrawMode, TrianglesDrawMode, TriplanarTexturesNode, TubeGeometry, UVMapping, Uint16BufferAttribute, Uint32BufferAttribute, Uint8BufferAttribute, Uint8ClampedBufferAttribute, Uniform$1 as Uniform, UniformArrayNode, UniformGroupNode, UniformNode, UniformsGroup$1 as UniformsGroup, UnsignedByteType, UnsignedInt248Type, UnsignedInt5999Type, UnsignedIntType, UnsignedShort4444Type, UnsignedShort5551Type, UnsignedShortType, UserDataNode, VSMShadowMap, V_GGX_SmithCorrelated, VarNode, VaryingNode, Vector2, Vector3, Vector4, VectorKeyframeTrack, VertexColorNode, VideoTexture, ViewportDepthNode, ViewportDepthTextureNode, ViewportSharedTextureNode, ViewportTextureNode, VolumeNodeMaterial, WebGL3DRenderTarget, WebGLArrayRenderTarget, WebGLCoordinateSystem, WebGLCubeRenderTarget, WebGLMultipleRenderTargets, WebGLRenderTarget, WebGPUCoordinateSystem, WebGPURenderer, WireframeGeometry, WrapAroundEnding, ZeroCurvatureEnding, ZeroFactor, ZeroSlopeEnding, ZeroStencilOp, abs, acesFilmicToneMapping, acos, add, addMethodChaining, addNodeElement, agxToneMapping, all, alphaT, and, anisotropy, anisotropyB, anisotropyT, any, append, arrayBuffer, asin, assign, atan, atan2, atomicAdd, atomicAnd, atomicFunc, atomicMax, atomicMin, atomicOr, atomicStore, atomicSub, atomicXor, attenuationColor, attenuationDistance, attribute, backgroundBlurriness, backgroundIntensity, batch, billboarding, bitAnd, bitNot, bitOr, bitXor, bitangentGeometry, bitangentLocal, bitangentView, bitangentWorld, bitcast, blur, bool, buffer, bufferAttribute, bumpMap, burn, bvec2, bvec3, bvec4, bypass, cache, call, cameraFar, cameraNear, cameraNormalMatrix, cameraPosition, cameraProjectionMatrix, cameraProjectionMatrixInverse, cameraViewMatrix, cameraWorldMatrix, cbrt, cdl, ceil, checker, cineonToneMapping, clamp, clearcoat, clearcoatRoughness, code, color, colorSpaceToWorking, colorToDirection, compute, cond, context, convert, convertToTexture, cos, createCanvasElement, cross, cubeTexture, dFdx, dFdy, dashSize, defaultBuildStages, defaultShaderStages, defined, degrees, deltaTime, densityFog, depth, depthPass, difference, diffuseColor, directionToColor, dispersion, distance, div, dodge, dot, drawIndex, dynamicBufferAttribute, element, emissive, equal, equals, equirectUV, exp, exp2, expression, faceDirection, faceForward, float, floor, fog, fract, frameGroup, frameId, frontFacing, fwidth, gain, gapSize, getColorSpaceMethod, getConstNodeType, getCurrentStack, getDirection, getDistanceAttenuation, getGeometryRoughness, getRoughness, getScreenPosition, getShIrradianceAt, getTextureIndex, getViewPosition, global, glsl, glslFn, grayscale, greaterThan, greaterThanEqual, hash, highPrecisionModelNormalViewMatrix, highPrecisionModelViewMatrix, hue, instance, instanceIndex, instancedBufferAttribute, instancedDynamicBufferAttribute, int, inverseSqrt, invocationLocalIndex, invocationSubgroupIndex, ior, iridescence, iridescenceIOR, iridescenceThickness, ivec2, ivec3, ivec4, js, label, length, lengthSq, lessThan, lessThanEqual, lightPosition, lightTargetDirection, lightTargetPosition, lightViewPosition, lightingContext, lights, linearDepth, linearSRGBTosRGB, linearToneMapping, localId, log, log2, loop, luminance, mat2, mat3, mat4, matcapUV, materialAOMap, materialAlphaTest, materialAnisotropy, materialAnisotropyVector, materialAttenuationColor, materialAttenuationDistance, materialClearcoat, materialClearcoatNormal, materialClearcoatRoughness, materialColor, materialDispersion, materialEmissive, materialIOR, materialIridescence, materialIridescenceIOR, materialIridescenceThickness, materialLightMap, materialLineDashOffset, materialLineDashSize, materialLineGapSize, materialLineScale, materialLineWidth, materialMetalness, materialNormal, materialOpacity, materialPointWidth, materialReference, materialReflectivity, materialRefractionRatio, materialRotation, materialRoughness, materialSheen, materialSheenRoughness, materialShininess, materialSpecular, materialSpecularColor, materialSpecularIntensity, materialSpecularStrength, materialThickness, materialTransmission, max$1 as max, maxMipLevel, metalness, min$1 as min, mix, mixElement, mod, modInt, modelDirection, modelNormalMatrix, modelPosition, modelScale, modelViewMatrix, modelViewPosition, modelViewProjection, modelWorldMatrix, modelWorldMatrixInverse, morphReference, mrt, mul, mx_aastep, mx_cell_noise_float, mx_contrast, mx_fractal_noise_float, mx_fractal_noise_vec2, mx_fractal_noise_vec3, mx_fractal_noise_vec4, mx_hsvtorgb, mx_noise_float, mx_noise_vec3, mx_noise_vec4, mx_ramplr, mx_ramptb, mx_rgbtohsv, mx_safepower, mx_splitlr, mx_splittb, mx_srgb_texture_to_lin_rec709, mx_transform_uv, mx_worley_noise_float, mx_worley_noise_vec2, mx_worley_noise_vec3, negate, neutralToneMapping, nodeArray, nodeImmutable, nodeObject, nodeObjects, nodeProxy, normalFlat, normalGeometry, normalLocal, normalMap, normalView, normalWorld, normalize, not, notEqual, numWorkgroups, objectDirection, objectGroup, objectPosition, objectScale, objectViewPosition, objectWorldMatrix, oneMinus, or, orthographicDepthToViewZ, oscSawtooth, oscSine, oscSquare, oscTriangle, output, outputStruct, overlay, overloadingFn, parabola, parallaxDirection, parallaxUV, parameter, pass, passTexture, pcurve, perspectiveDepthToLogarithmicDepth, perspectiveDepthToViewZ, pmremTexture, pointUV, pointWidth, positionGeometry, positionLocal, positionPrevious, positionView, positionViewDirection, positionWorld, positionWorldDirection, posterize, pow, pow2, pow3, pow4, property, radians, rand, range, rangeFog, reciprocal, reference, referenceBuffer, reflect, reflectVector, reflectView, reflector, refract, refractVector, refractView, reinhardToneMapping, remainder, remap, remapClamp, renderGroup, renderOutput, rendererReference, rotate, rotateUV, roughness, round, rtt, sRGBToLinearSRGB, sampler, saturate, saturation, screen, screenCoordinate, screenSize, screenUV, scriptable, scriptableValue, select, setCurrentStack, shaderStages, shadow, sharedUniformGroup, sheen, sheenRoughness, shiftLeft, shiftRight, shininess, sign, sin, sinc, skinning, skinningReference, smoothstep, smoothstepElement, specularColor, specularF90, spherizeUV, split, spritesheetUV, sqrt, stack, step, storage, storageBarrier, storageObject, storageTexture, string, sub, subgroupIndex, subgroupSize, tan, tangentGeometry, tangentLocal, tangentView, tangentWorld, temp, texture, texture3D, textureBarrier, textureBicubic, textureCubeUV, textureLoad, textureSize, textureStore, thickness, threshold, time, timerDelta, timerGlobal, timerLocal, toOutputColorSpace, toWorkingColorSpace, toneMapping, toneMappingExposure, toonOutlinePass, transformDirection, transformNormal, transformNormalToView, transformedBentNormalView, transformedBitangentView, transformedBitangentWorld, transformedClearcoatNormalView, transformedNormalView, transformedNormalWorld, transformedTangentView, transformedTangentWorld, transmission, transpose, tri, tri3, triNoise3D, triplanarTexture, triplanarTextures, trunc, tslFn, uint, uniform, uniformArray, uniformGroup, uniforms, userData, uv, uvec2, uvec3, uvec4, varying, varyingProperty, vec2, vec3, vec4, vectorComponents, velocity, vertexColor, vertexIndex, vibrance, viewZToOrthographicDepth, viewZToPerspectiveDepth, viewport, viewportBottomLeft, viewportCoordinate, viewportDepthTexture, viewportLinearDepth, viewportMipTexture, viewportResolution, viewportSafeUV, viewportSharedTexture, viewportSize, viewportTexture, viewportTopLeft, viewportUV, wgsl, wgslFn, workgroupArray, workgroupBarrier, workgroupId, workingToColorSpace, xor };
粤ICP备19079148号